refactor: 整体迁移控制面至MySQL + 替换UI框架为Element Plus
1. 移除naive-ui依赖,迁移前端至Element Plus 2. 重构后端数据库层,切换为MySQL替代SQLite 3. 调整项目部署架构,停止exe打包改为源码部署 4. 新增设备上报接口与相关数据库模型 5. 优化配置路径与SQL语法,替换为MySQL占位符格式 6. 调整站点名称与文案,统一为「37du 插件管理平台」 7. 新增SQLite到MySQL迁移脚本
This commit is contained in:
+5
-2
@@ -18,11 +18,14 @@ desktop/*/frontend/node_modules
|
||||
desktop/*/frontend/dist/
|
||||
|
||||
# 桌面版打包产物(PyInstaller 中间/输出、安装包、插件构建包,不入库)
|
||||
desktop/**/build-exe/
|
||||
desktop/**/dist-exe/
|
||||
# 仅执行机(壳子)仍走 PyInstaller 打包;中心机已改源码部署,不再产出 exe
|
||||
desktop/webhost/**/build-exe/
|
||||
desktop/webhost/**/dist-exe/
|
||||
desktop/releases/
|
||||
desktop/build/
|
||||
dist-plugin/
|
||||
desktop/**/setup-*.exe
|
||||
desktop/**/installer/
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ controlplane/frontend/
|
||||
```javascript
|
||||
import { reactive } from 'vue'
|
||||
export const store = reactive({
|
||||
appName: '37du 内网插件控制面',
|
||||
appName: '37du 插件管理平台',
|
||||
isAdmin: false,
|
||||
current: (() => {
|
||||
try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' }
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
# 执行机 Chrome 检测/下载 + 中心机配置入口 + 全项目 MySQL 迁移 方案
|
||||
|
||||
> 状态:方案评审稿(未编码)
|
||||
> 面向对象:37du 自动化平台(desktop/controlplane 中心机 + desktop/webhost 执行机)
|
||||
|
||||
---
|
||||
|
||||
## 一、现状盘点(已核实代码)
|
||||
|
||||
### 1.1 执行机(webhost)现状
|
||||
- 已有能力:统一账户登录、插件按权限自下载(`plugin_sync.py`)、进程级隔离执行(`runner.py` + Windows Job Object)、壳子自动更新(`shell_updater.py`:检查 `/api/shell/version` → 下载 `/api/shell/pkg` → 前端提示 → 静默升级重启)、离线授权票据、平台登录态、WebSocket 日志流、Vue 前端。
|
||||
- **浏览器依赖**:插件走浏览器自动化(依赖 `DrissionPage`,见根 [requirements.txt](file:///d:/work/code/37duAutomation/requirements.txt#L28-L29)),浏览器(Chrome)是几乎所有插件的硬依赖。
|
||||
- **缺口确认**:全库检索 `chrome|browser|chromium`,**没有任何 Chrome 安装检测逻辑**,仅有 UA 字符串和 pywebview 的 `edgechromium` 渲染参数。**没有 Chrome 安装包下载能力**(壳子只能自更新,不能装 Chrome)。
|
||||
|
||||
### 1.2 中心机(controlplane)现状
|
||||
- FastAPI + Vue(naive-ui),菜单:概览 / 数据看板 / 插件管理 / 账号管理 / 权限授权 / 审计报表。
|
||||
- **存储 = SQLite**(`controlplane/core/db.py`,`controlplane.db`),表:
|
||||
- `accounts` / `plugins` / `plugin_versions` / `account_plugins` / `plugin_grants` / `account_platforms` / `audit_logs` / `runtime_reports`
|
||||
- 壳子更新源已做成「中心机 shell/ 目录 + version.json + `/api/admin/shell-release` 上传接口」,执行机拉取更新——**Chrome 下载可完全复用这套模式**,只是安装包不落中心机(外链 URL)。
|
||||
- SQLite 专属语法分布很集中:`db.py`(连接/迁移)+ `apis/admin.py` 5 处(`INSERT OR IGNORE`/`ON CONFLICT`/`substr`/`date('now')`)+ `auth.py`(仅用 `_db()`)。迁移成本可控。
|
||||
|
||||
### 1.3 执行机是否也要 MySQL?
|
||||
**不需要。** webhost 无数据库:登录会话存内存 + 本地文件,授权/管控用 `%LOCALAPPDATA%\37duAutomation\` 下 JSON 缓存(离线可用的核心设计)。「全项目切 MySQL」实际只落在**中心机控制面**,执行机保持无库、离线可用,不改。
|
||||
|
||||
---
|
||||
|
||||
## 二、方案 A:执行机 Chrome 自动检测 + 下载安装(壳子提供)
|
||||
|
||||
### A1. 检测模块(webhost 新增 `backend/core/chrome_check.py`)
|
||||
目标:判断本机是否安装 Chrome、路径、主版本号。检测优先级:
|
||||
|
||||
1. **标准安装路径探测**(最可靠、无需权限):
|
||||
- `%ProgramFiles%\Google\Chrome\Application\chrome.exe`
|
||||
- `%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`
|
||||
- `%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe`
|
||||
2. **注册表兜底**(路径被改到非常规位置时):
|
||||
- `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe`
|
||||
- `HKLM\SOFTWARE\WOW6432Node\...\App Paths\chrome.exe`
|
||||
- `HKCU\SOFTWARE\Google\Chrome\BLBeacon`(version)
|
||||
3. **版本号读取**:
|
||||
- 优先读 `chrome.exe` 文件版本(`win32api.GetFileVersionInfo`,pywin32 已在依赖内);
|
||||
- 兜底读 `...\Chrome\Application\<版本号目录>\` 目录名;
|
||||
- 再兜底 `subprocess chrome.exe --version`。
|
||||
4. 可选深度探测:`DrissionPage.ChromiumPage` 试启(慢,默认不做,仅“诊断模式”)。
|
||||
|
||||
返回结构:`{ installed: bool, path, version, major, dirty: bool }`(dirty=主版本非 64 位或异常,供提示)。
|
||||
|
||||
### A2. 后端 API(webhost)
|
||||
| 方法/路径 | 说明 |
|
||||
|---|---|
|
||||
| `GET /api/chrome/status` | 实时检测(登录态)返回 A1 结果 |
|
||||
| `POST /api/chrome/download` | 从中心机拉取 Chrome 配置 → 下载安装包到本地缓存 `%LOCALAPPDATA%\37duAutomation\chrome\`,返回下载进度句柄 |
|
||||
| `GET /api/chrome/download-status` | 轮询下载进度(percent / speed / done / err) |
|
||||
| `POST /api/chrome/install` | 运行已下载的安装包静默安装 |
|
||||
| `POST /api/chrome/recheck` | 安装完成后复检(等价 status) |
|
||||
|
||||
下载用 `requests` 流式写盘(分块 + 进度累计),与壳子更新同款 sha256 校验(中心机下发时携带)。
|
||||
|
||||
### A3. 前端 UI(执行机壳子)
|
||||
- **顶栏**:新增「环境」状态条(仅展示)——Chrome 图标 + `已安装 vxxx`(绿)/ `未检测到 Chrome`(红)+「检测」刷新按钮。
|
||||
- **个人中心(ProfilePanel)**:新增「运行环境」区块:
|
||||
- 当前状态、版本、安装路径;
|
||||
- 未安装 → 显示「下载并安装 Chrome」按钮(点击走 A2 下载→进度条→完成后自动静默安装→复检);
|
||||
- 已安装但非最新/损坏 → 提示「重新安装」。
|
||||
- 下载大包(约 100MB+)期间不阻塞主界面:下载/安装放后台线程,前端进度条。
|
||||
|
||||
### A4. 下载源:中心机托管「外链 URL 配置」,不落包
|
||||
- 中心机只存 Chrome 安装包**下载地址(外链 URL)+ sha256 + 版本 + 说明**(见方案 B 表 `chrome_releases`)。
|
||||
- 执行机 `POST /api/chrome/download` → 向中心机 `GET /api/chrome/config`(X-API-Token)拿 URL → 下载到本地缓存 → sha256 校验。
|
||||
- 好处:安装包 100MB+,中心机/控制面不承担存储与上传带宽;URL 由管理员在中心机随时改(换新版本),执行机每次点下载读最新。
|
||||
- **你后续提供链接后,只需在中心机「系统设置」页填入即可内置。**
|
||||
|
||||
### A5. 静默安装策略(已确认:自动静默安装)
|
||||
- 下载完成后执行 `ChromeStandaloneSetup64.exe /silent /install`(Chrome 官方安装器支持静默;逐用户安装通常无需管理员)。
|
||||
- 进程托管进 Job Object(复用 `winjob.py`),超时兜底;安装完成后自动复检(轮询 `status` 直到 `installed` 或超时给出失败提示,失败时引导用户手动双击安装包)。
|
||||
|
||||
### A6. 前端位置(已确认:顶栏状态条 + 个人中心)
|
||||
- **顶栏**:常驻「环境」状态条,Chrome 图标 + 已安装(绿,含版本)/ 未检测到(红)+ 检测刷新按钮。
|
||||
- **个人中心**:操作入口(下载/安装/复检、安装路径展示、进度条)。
|
||||
|
||||
---
|
||||
|
||||
## 三、方案 B:中心机新增 Chrome 配置编辑位置
|
||||
|
||||
### B1. 数据表(随 MySQL 迁移一并建)
|
||||
```sql
|
||||
CREATE TABLE chrome_releases (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
version VARCHAR(32) NOT NULL DEFAULT '', -- 版本号,用于展示/比对
|
||||
url TEXT NOT NULL, -- 安装包外链下载地址
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '', -- 落盘文件名(可选)
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '', -- 校验值(可选,有则校验)
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '', -- 说明
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1, -- 启用/停用该下载源
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
(单行生效配置,管理员改一条即可,保留多条历史可选。)
|
||||
|
||||
### B2. 管理 API(`apis/admin.py`,需管理员票据)
|
||||
- `GET /api/admin/chrome-config` → 当前配置
|
||||
- `POST /api/admin/chrome-config` → 更新 url/sha256/version/notes/enabled
|
||||
|
||||
### B3. 客户端拉取 API(`apis/plugins.py`,X-API-Token)
|
||||
- `GET /api/chrome/config` → 下发 `{ url, sha256, version, notes, enabled }`(执行机 A2 用)
|
||||
|
||||
### B4. 中心机前端:新增「系统设置」页
|
||||
- `frontend/views/SettingsView.vue` + `App.vue` 菜单新增 `系统设置`(`#/settings`)。
|
||||
- 页面区块「Chrome 安装包」:URL 输入框 + sha256/version/notes + 启用开关 + 保存 + 「测试链接」(HEAD 请求看可访问性与大小)。
|
||||
- 后续其它全局配置(如新环境依赖)也沉淀到该页。
|
||||
|
||||
---
|
||||
|
||||
## 四、方案 C:全项目切换 MySQL + 表结构重新设计
|
||||
|
||||
### C1. 驱动与配置
|
||||
- 驱动:**PyMySQL**(纯 Python,PyInstaller 打包零坑;`mysql-connector-python` 作备选)。
|
||||
- 依赖:根 [requirements.txt](file:///d:/work/code/37duAutomation/requirements.txt) 增加 `PyMySQL`;中心机 PyInstaller `37du-center.spec` 确认带上。
|
||||
- 配置(`desktop/controlplane/.env` 新增,按 AGENTS.md 模块隔离):
|
||||
```
|
||||
MYSQL_HOST=127.0.0.1
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=37du
|
||||
MYSQL_PASSWORD=***
|
||||
MYSQL_DB=37du_center
|
||||
```
|
||||
|
||||
### C2. `db.py` 兼容层改造(改动收敛在数据层)
|
||||
保留 `_db()` 上下文管理器语义(自动 commit/close),内部改为:
|
||||
- `pymysql.connect(..., cursorclass=pymysql.cursors.DictCursor)`(等效 `sqlite3.Row`);
|
||||
- 启动时自动建库 `CREATE DATABASE IF NOT EXISTS ... utf8mb4`;
|
||||
- 参数占位符 `?` → `%s`(注意 `dict cursor` 下 `%` 需注意);
|
||||
- 迁移机制重构:建表用「完整 DDL + 幂等」替代旧的 `_ensure_col` 渐进补列(MySQL `ADD COLUMN IF NOT EXISTS` 需 MySQL 8.0+,直接以 DDL 建齐最稳),引入 `schema_migrations` 表记录已执行版本。
|
||||
|
||||
### C3. SQL 兼容改写清单(全库仅这几处)
|
||||
| 现状(SQLite) | 改写(MySQL) | 位置 |
|
||||
|---|---|---|
|
||||
| `INSERT OR IGNORE` | `INSERT IGNORE` | db.py / admin.py×4 |
|
||||
| `INSERT ... ON CONFLICT(...) DO UPDATE SET` | `INSERT ... ON DUPLICATE KEY UPDATE` | admin.py 227/304/316 |
|
||||
| `substr(at,1,10)` | `LEFT(at,10)` 或 `DATE(at)` | admin.py 478 |
|
||||
| `date('now','-13 days')` | `CURDATE() - INTERVAL 13 DAY` | admin.py 482 |
|
||||
| `PRAGMA table_info` 动态补列 | 全量 DDL + 迁移版本表 | db.py(重写) |
|
||||
|
||||
### C4. 重新设计的 MySQL 表结构(InnoDB / utf8mb4,**目标 MySQL 5.7**)
|
||||
核心约定:主键用自增 `INT/BIGINT UNSIGNED`;业务唯一键用 `UNIQUE KEY`;布尔用 `TINYINT(1)`;时间用 `DATETIME`;关键查询列加索引;关联表加外键(`ON DELETE CASCADE`)。完整 DDL 见附录「七」。
|
||||
|
||||
MySQL 5.7 适配要点:
|
||||
- **`manifest` 用 `TEXT` 存 JSON 串**,不用 `JSON` 类型——PyMySQL 会对 MySQL JSON 列自动 `json.loads` 成对象,与既有 `_load_manifest(json.loads(...))` 冲突;TEXT 保持零改动、迁移零风险;
|
||||
- **`force_deadline` 保持 `VARCHAR(32)`**——既有 `_deadline_passed` 用 `fromisoformat` 解析,需兼容带时区 ISO 串;TEXT 列在 5.7 不支持 DEFAULT,应用层始终传入值;
|
||||
- 时间列(`at/created_at/uploaded_at/...`)用 `DATETIME`:PyMySQL 读回 `datetime` 对象,FastAPI 序列化为 ISO 串(`T` 分隔),前端纯文本展示兼容;趋势分组改 `DATE_FORMAT(at,'%Y-%m-%d')`;
|
||||
- 避开 MySQL 8.0 专属语法(如 `ADD COLUMN IF NOT EXISTS`、窗口函数),DDL 一律全量建齐、幂等;
|
||||
- `utf8mb4` 下索引列总长注意(5.7 默认 DYNAMIC 行格式 + innodb_large_prefix,3072 字节上限足够;设计已控制单列 ≤ 255、复合索引 ≤ 3 列)。
|
||||
|
||||
表清单(完整 DDL 以 `desktop/controlplane/tools/schema_mysql.sql` 为准,本文档不再内嵌 DDL 以免双份维护):
|
||||
1. `accounts`(账号)— 自增 id 主键 + `account` 唯一键、`updated_at`、`dept` 索引;
|
||||
2. `plugins`(插件元数据)— `manifest TEXT NULL`(JSON 串,可空;兼容种子 INSERT)、`force_deadline VARCHAR(32)`、`status VARCHAR(16)`(白名单由代码层校验,不用 ENUM);
|
||||
3. `plugin_versions`(版本)— 补 `size_bytes`、`UNIQUE(plugin_id,version)`、外键级联;
|
||||
4. `account_plugins`(账号-插件授权)— **合并原 `plugin_grants`**:`can_download/can_run` 权限位并入本表,加 `idx_plugin` 反向索引;
|
||||
5. `account_platforms`(账号-平台白名单);
|
||||
6. `audit_logs`(审计)— `BIGINT` 主键 + `action/at/account` 索引;
|
||||
7. `runtime_reports`(运行上报)— 常用查询索引(`at` 单列 + `account+at`、`plugin_id+at`、`status+at`);
|
||||
8. **新增 `devices`(执行机设备)**— 环境/心跳上报(`device_id` 主键、`chrome_installed/chrome_version/chrome_ok/last_seen`),配合执行机 Chrome 检测看每台执行机环境;`account` 仅归属标识、不建外键(避免误删设备记录);
|
||||
9. **新增 `chrome_releases`**(见方案 B);
|
||||
10. **新增 `system_settings`**(通用键值配置,`key` 唯一,`value` TEXT 存 JSON 文本)——留作后续全局配置沉淀;
|
||||
11. **新增 `schema_migrations`**(迁移版本记录)。
|
||||
|
||||
### C5. 数据迁移
|
||||
- 提供一次性脚本 `desktop/controlplane/tools/migrate_sqlite_to_mysql.py`:
|
||||
- 读旧 `controlplane.db` → 按新表结构批量 `INSERT IGNORE` 灌入 MySQL;
|
||||
- 覆盖:accounts(含密码哈希/salt,原样搬迁)、plugins、plugin_versions、account_plugins(**原 plugin_grants 的 can_download/can_run 并入**)、account_platforms、audit_logs、runtime_reports;
|
||||
- 迁移前自动备份 SQLite 文件;迁移后中心机 `.env` 切 `MYSQL_*` 即启用 MySQL。
|
||||
- 迁移执行顺序建议在 MySQL 表建好、接口回归通过后进行。
|
||||
|
||||
### C6. 部署注意
|
||||
- 需一台 MySQL 服务(现有/新装均可):`CREATE DATABASE 37du_center utf8mb4; CREATE USER '37du'@'%' IDENTIFIED BY '...'; GRANT ALL ON 37du_center.* TO '37du'@'%';`
|
||||
- 中心机 PyInstaller 打包重新出 `37du-center.exe`(带 PyMySQL 与连接参数 .env)。
|
||||
- 字符集统一 `utf8mb4`、排序 `utf8mb4_unicode_ci`;连接参数加 `charset='utf8mb4'`。
|
||||
- 执行机(webhost)无库,**不受迁移影响**,无需改动。
|
||||
|
||||
---
|
||||
|
||||
## 五、实施步骤(建议顺序)
|
||||
|
||||
1. **P0 执行机 Chrome 检测**:`chrome_check.py` + `GET /api/chrome/status` + 顶栏状态条 + 个人中心「运行环境」展示。
|
||||
2. **P1 中心机 Chrome 配置**:表 `chrome_releases`(先落 SQLite,MySQL 迁移时同步建 MySQL 版)、管理 API、`/api/chrome/config`、前端「系统设置」页。
|
||||
3. **P2 执行机下载+静默安装**:`/api/chrome/download` + 进度轮询 + `/api/chrome/install` + 复检闭环。
|
||||
4. **P3 MySQL 迁移**:驱动/配置 → `db.py` 兼容层 → DDL(附录)→ SQL 改写 → 迁移脚本 → 回归(登录/插件/授权/看板/审计/运行上报/壳子更新)→ 打包。
|
||||
5. **P4 收尾**:URL 内置(你提供链接后填入中心机)、文档更新。
|
||||
|
||||
> 依赖关系:P0 独立可先行;P1/P2 是 Chrome 功能闭环;P3 与 P1/P2 的数据表并存(先 SQLite 后 MySQL),互不阻塞。
|
||||
|
||||
---
|
||||
|
||||
## 六、决策点(评审确认记录)
|
||||
|
||||
| # | 决策点 | 结论 |
|
||||
|---|---|---|
|
||||
| 1 | MySQL 实例 | **已有 MySQL 5.7**(表结构按 5.7 适配,JSON 类型可用) |
|
||||
| 2 | 驱动 | **PyMySQL** |
|
||||
| 3 | Chrome 静默安装 | **自动静默安装**(`/silent /install` + Job Object 托管 + 自动复检) |
|
||||
| 4 | 执行机 UI 位置 | **顶栏状态条 + 个人中心区块** |
|
||||
| 5 | 旧库去留 | **待定**(MySQL 稳定后保留 SQLite 只读备份,建议不删,可随时回滚) |
|
||||
|
||||
剩余待办:待你提供 Chrome 安装包链接(用于中心机「系统设置」页内置);确认 MySQL 连接账号/密码后填入 `controlplane/.env`。
|
||||
|
||||
---
|
||||
|
||||
## 七、附录:数据库脚本
|
||||
|
||||
完整 DDL(含字段注释)以 `desktop/controlplane/tools/schema_mysql.sql` 为准,本文档不内嵌 DDL 以免双份维护。
|
||||
|
||||
执行方式:
|
||||
|
||||
```bash
|
||||
mysql -h<host> -u<user> -p < desktop/controlplane/tools/schema_mysql.sql
|
||||
```
|
||||
|
||||
> 说明:脚本幂等(`CREATE DATABASE IF NOT EXISTS` + `CREATE TABLE IF NOT EXISTS`),可重复执行;也可由 `db.py` 启动时幂等建表并登记 `schema_migrations`。
|
||||
> 共 11 张表:schema_migrations / accounts / plugins / plugin_versions / account_plugins(含权限位)/ account_platforms / audit_logs / runtime_reports / devices(新增)/ chrome_releases(新增)/ system_settings(新增)。
|
||||
@@ -0,0 +1,147 @@
|
||||
# 37du 中心机控制面 · 前后端部署 SOP
|
||||
|
||||
> 对象:控制面(controlplane)前端 + 后端部署到宝塔面板服务器(117.72.191.188)。
|
||||
> 用途:下次改完代码后按此文档快速部署,无需重新勘察。
|
||||
> 本文档由 2026-09-16 实际部署过程沉淀,路径/端口/命令均为已验证事实。
|
||||
|
||||
---
|
||||
|
||||
## 一、架构现状(已落地)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 前端 | 独立静态站(html 项目),与后端解耦 |
|
||||
| 前端站点名 | `117.72.191.188`(面板 html 项目,id=2) |
|
||||
| 前端访问地址 | `http://117.72.191.188:8090` |
|
||||
| 前端根目录 | `/www/wwwroot/controlplane-web` |
|
||||
| 前端 nginx 配置 | `/www/server/panel/vhost/nginx/html_117.72.191.188.conf` |
|
||||
| 前端伪静态 | `/www/server/panel/vhost/rewrite/html_117.72.191.188.conf`(SPA try_files + /api 反代) |
|
||||
| 后端 | Python 项目 `controlplane`,gunicorn + FastAPI,端口 8800 |
|
||||
| 后端源码目录 | `/www/wwwroot/controlplane/controlplane/`(rfile: `app.py`,call_app: `app`) |
|
||||
| 后端日志 | `/www/wwwlogs/python/controlplane` |
|
||||
| 服务器外网 IP | `117.72.191.188`,宝塔 MCP 入口 `8765` |
|
||||
|
||||
**关键架构决策**:前端已从「后端 FastAPI 挂载 dist」改为独立静态站。
|
||||
`app.py` 中**已删除** `app.mount("/", StaticFiles(...))`,后端不再提供页面,只出 `/api/*`。
|
||||
`core/config.py` 中的 `DIST` 常量已删除;中心机**不再 exe 打包**(`37du-center.spec`、`register_autostart.bat`、`stop_center.bat` 已移除,统一源码部署)。
|
||||
|
||||
---
|
||||
|
||||
## 二、前端部署流程(改完 frontend/ 后)
|
||||
|
||||
### 1. 本地构建
|
||||
```powershell
|
||||
cd d:\work\code\37duAutomation\desktop\controlplane\frontend
|
||||
npm install # 首次/依赖变更后
|
||||
npm run build # 产物在 dist/(index.html + assets/index-*.js/css)
|
||||
```
|
||||
|
||||
### 2. 打包
|
||||
```powershell
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "controlplane-web-dist.zip" -Force
|
||||
```
|
||||
|
||||
### 3. 上传(宝塔 MCP)
|
||||
1. MCP 工具 `Upload`,`file_name: "controlplane-web-dist.zip"`(可带 size)
|
||||
2. 返回 `next_action.windows` 后,在本机 PowerShell 执行该 curl(替换 `<LOCAL_FILE>` 为本地绝对路径)
|
||||
3. 上传成功返回服务器路径:`/www/server/panel/data/agent/mcp_uploads/files/key_8b967e9fd815/<file_id>/controlplane-web-dist.zip`
|
||||
|
||||
### 4. 服务器部署(MCP Bash)
|
||||
```bash
|
||||
cd /www/wwwroot/controlplane-web
|
||||
mkdir -p /www/backup/cp-web-old
|
||||
mv -f index.html /www/backup/cp-web-old/ 2>/dev/null
|
||||
mv -f assets /www/backup/cp-web-old/assets-$(date +%H%M%S) 2>/dev/null # 清旧产物,避免哈希文件堆积
|
||||
unzip -o /www/server/panel/data/agent/mcp_uploads/files/key_8b967e9fd815/<file_id>/controlplane-web-dist.zip
|
||||
chown -R www:www /www/wwwroot/controlplane-web/index.html /www/wwwroot/controlplane-web/assets
|
||||
```
|
||||
> 注意:**不要用 `rm -rf`** 清理站点目录——宝塔 MCP 会按"递归强删关键路径"拦截命令,必须改用 `mv` 移到备份目录再解压。
|
||||
> 也不要对整个站点目录 `chown -R`,`/www/wwwroot/controlplane-web/.user.ini` 是锁定文件会报 `Operation not permitted` 并中断。
|
||||
|
||||
### 5. 验证
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8090/ | head -c 300 # 首页 200,含新 index-*.js 引用
|
||||
curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8090/assets/index-*.js
|
||||
curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8090/api/admin/overview # 401 = 反代到后端鉴权正常
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、后端部署流程(改完 controlplane 后端代码后)
|
||||
|
||||
### 1. 语法校验(本地)
|
||||
```powershell
|
||||
& "d:\work\code\37duAutomation\.venv\Scripts\python.exe" -c "import ast; ast.parse(open(r'd:\work\code\37duAutomation\desktop\controlplane\app.py', encoding='utf-8').read()); print('OK')"
|
||||
```
|
||||
|
||||
### 2. 逐个上传改动文件(MCP `Upload` + 本机 curl,同前端步骤 3)
|
||||
常用文件:`app.py`、`core/config.py`、`core/db.py` 等
|
||||
|
||||
### 3. 覆盖到服务器(MCP Bash,先备份)
|
||||
```bash
|
||||
cd /www/wwwroot/controlplane/controlplane
|
||||
cp app.py app.py.bak-$(date +%Y%m%d)
|
||||
cp /www/server/panel/data/agent/mcp_uploads/files/key_8b967e9fd815/<file_id>/app.py app.py
|
||||
chown root:root app.py
|
||||
```
|
||||
|
||||
### 4. 重启项目
|
||||
MCP `PythonProjectControl` → `project_name: "controlplane"`, `action: "restart"`
|
||||
然后 MCP `PythonProjectInfo` 确认 `status=1`、`run=true`、`listen:[8800]`。
|
||||
|
||||
### 5. 验证
|
||||
```bash
|
||||
curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8800/ # 404 = 无静态挂载(正常)
|
||||
curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8800/api/admin/overview # 401 = API 正常
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、nginx 伪静态配置(已写好,勿丢)
|
||||
|
||||
`/www/server/panel/vhost/rewrite/html_117.72.191.188.conf` 内容:
|
||||
|
||||
```nginx
|
||||
# 控制面前端静态站(37du 中心机)
|
||||
# /api 反代到后端 FastAPI 8800
|
||||
location /api {
|
||||
proxy_pass http://127.0.0.1:8800;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_read_timeout 120s;
|
||||
}
|
||||
|
||||
# SPA 单页应用:子路由刷新回退 index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
```
|
||||
|
||||
改完 `nginx -t && nginx -s reload`。
|
||||
|
||||
---
|
||||
|
||||
## 五、踩坑记录
|
||||
|
||||
1. **8080 端口创建站点失败**:宝塔报「端口范围不合法」,8090 可用。非 80 端口建站时若报错直接换端口。
|
||||
2. **`.user.ini` 锁定**:chown 站点根目录会失败,只对部署的文件 chown。
|
||||
3. **`rm -rf` 被 MCP 拦截**:清理站点旧产物用 `mv` 到 `/www/backup/cp-web-old/`,不要用 rm -rf。
|
||||
4. **zip 反斜杠警告**:Windows `Compress-Archive` 解压有 warning,`unzip` 仍能正常解出文件(exit 1,不影响)。
|
||||
5. **WebFetch 无法验证 http 站点**:工具会自动升级 https,纯 http 站点用服务器 `curl 127.0.0.1` 验证。
|
||||
6. **`DINGTALK_CALLBACK`** 在 `controlplane/.env`,回调域名是 `http://172.30.28.131:8800`,改前端/后端地址时需同步。
|
||||
7. **前端 hash 路由**(`#/xxx`),静态站刷新天然安全,无需后端 history 回退。
|
||||
8. **上传文件默认 `root:root/0600`**,nginx 读不到需 `chown www:www`(或至少 0644)。
|
||||
|
||||
---
|
||||
|
||||
## 六、本地前端开发
|
||||
|
||||
```powershell
|
||||
cd d:\work\code\37duAutomation\desktop\controlplane\frontend
|
||||
npm run dev # 5173,vite 代理 /api → http://127.0.0.1:8800
|
||||
```
|
||||
UI 组件库:Element Plus(已移除 naive-ui);图标:`@element-plus/icons-vue`(全局注册)。
|
||||
主题:浅色「纸张+墨色」编辑部风格,设计令牌集中在 `src/style.css` 的 `:root`(`--cp-*` 与 `--el-*`)。
|
||||
@@ -0,0 +1,122 @@
|
||||
---
|
||||
name: BT-Go-Project-Deploy
|
||||
description: >
|
||||
在宝塔面板上部署 Go 项目(编译好的二进制,含 Go SDK 版本安装、项目注册、进程启停、域名/外网映射),
|
||||
并在项目启动失败时排错。当用户要求把本机编译好的 Go 二进制部署成面板可管理的项目(含 Go SDK 安装、
|
||||
端口/运行用户配置、域名绑定),或 Go 项目启动失败/访问异常需要排查根因时使用。
|
||||
触发关键词:部署 Go、Go 项目、go build 产物部署、Go 二进制、Gin/Beego/Echo 服务、Go SDK 安装、
|
||||
go1.xx、GOPROXY、Go 项目启动失败、error while loading shared libraries、Address already in use。
|
||||
日常的启停/状态/日志/改配置/删项目等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||
---
|
||||
|
||||
# Go 项目部署与启动排错 SOP
|
||||
|
||||
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||
> 本 SOP 只覆盖两个主场景:**① 部署 Go 项目(含 Go SDK 安装);② 项目启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、删除)不做 SOP,直接使用工具。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先只读侦察,再执行变更** —— 部署前先 `GoProjectInfo` 查是否已存在同名项目、`GoVersion(action=list)` 看 SDK;排错先读日志,不盲目重启。
|
||||
2. **Go 是编译产物,无源码分析** —— `GoProjectCreate` 不需要分析步骤:给二进制绝对路径 + 端口 + 启动命令(缺省=二进制)直接注册。**不提供 analyze_only。**
|
||||
3. **Go SDK 安装走 Bash 后台** —— btpygvm 装的是完整预编译包(快),但网络慢仍可能超时:`GoVersion(action=install, version=...)` 返回 `install_command` 后,必须用 `Bash(command=install_command, run_in_background=true)` 后台执行 + `BashStatus(task_id, wait=true)` 轮询;**一次只装一个版本**。
|
||||
4. **创建即同步启动** —— `GoProjectCreate` 注册后面板同步启动(nohup 脚本 + pid,**无守护、崩了不自愈**);创建成功 ≠ 进程一定活着,必须 `GoProjectInfo` 核验 `run=true` + 端口在 `listen`。
|
||||
5. **Go 项目是编译二进制** —— 缺动态库/权限/端口占用是启动失败主因,排错按日志对号入座(场景二)。
|
||||
6. **改配置即重启** —— `GoProjectModify(action='config')` 面板改完自动 stop+start;改端口后若绑了域名,nginx 反代按新端口重写。
|
||||
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||
8. **禁止操作**:删除项目目录/二进制源码、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||
|
||||
---
|
||||
|
||||
# 场景一:部署 Go 项目
|
||||
|
||||
## Step 0 —— 预检
|
||||
1. 确认任务确为"部署 Go 项目"(非排错/运维)。
|
||||
2. 确认有编译好的**可执行二进制**(`go build` 产物,Linux 目标平台),拿到绝对路径。
|
||||
3. 确认**端口**(应用监听,10-65535)与**运行用户**(默认 www)。
|
||||
4. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||
|
||||
## Step 1 —— Go SDK 确认 / 安装
|
||||
1. `GoVersion(action='list')`:看 `data.installed` 是否已有可用 Go、`data.used` 当前版本。
|
||||
2. 没有可用版本 → `GoVersion(action='list')` 的 `data.available` 挑一个稳定版(每项含 `install_command`),再调 `GoVersion(action='install', version=<go1.xx>)` 拿该版本的 install_command。
|
||||
3. **用 Bash 后台执行**:`Bash(command=<install_command>, run_in_background=true)` → 得到 task_id → `BashStatus(task_id, wait=true)` 轮询到完成(预编译包下载+解压,通常几十秒到几分钟)。
|
||||
4. 完成后 `GoVersion(action='list')` 确认该版本在 `installed`;需要时 `GoVersion(action='use', version=...)` 切换当前版本;拉依赖慢可 `GoVersion(action='goproxy', goproxy=<源>)` 设置 GOPROXY。
|
||||
|
||||
## Step 2 —— 创建项目(注册 + 启动)
|
||||
调用 `GoProjectCreate(project_name=..., project_exe=<二进制绝对路径>, port=<端口>, ...)`:
|
||||
- **必填**:`project_name`(字母/数字/下划线)、`project_exe`、`port`。
|
||||
- **可选**:`project_cmd`(缺省=二进制本身)、`run_user`(默认 www)、`domains`(给则自动开启外网映射,'域名' 或 '域名:端口')、`env_list`(`[{"k","v"}]`,如 `[{"k":"PORT","v":"9000"}]`,**字符串 "K=V" 会被 schema 拒**)、`env_file`、`is_power_on`(默认 true)、`ps`、`release_firewall`(需外网访问时 true)。
|
||||
|
||||
> 返回"创建成功"= 已注册并尝试启动;`data.project` 含 run/listen 运行态。
|
||||
|
||||
## Step 3 —— 启动验证(强制)
|
||||
1. `GoProjectInfo(project_name=...)`:`run=true`、端口在 `listen`。
|
||||
2. 用返回的 `log_files` 里应用日志路径(`/www/wwwlogs/go/<name>.log`)调 filesystem `Read` 看尾部无致命异常(`error while loading shared libraries`/`Address already in use`/`bind: address already in use`)。
|
||||
3. 有域名映射的项目核验外网映射(`bind_extranet`)与反代(nginx `go_<name>.conf` 的 `proxy_pass 127.0.0.1:{port}`)。
|
||||
|
||||
- 全通过 → 按"完成汇报"收尾。
|
||||
- 任一失败 → **转场景二排错**。
|
||||
|
||||
---
|
||||
|
||||
# 场景二:启动排错
|
||||
|
||||
> 适用:创建后 run=false、或用户报"Go 项目启动失败/访问异常"。
|
||||
|
||||
## Step 0 —— 快速定位现状(只读)
|
||||
并行收集,不跳过:
|
||||
1. `GoProjectInfo(project_name=...)`:`run`、`listen`、`project_config`(exe/命令/端口/用户/环境变量)。
|
||||
2. 读应用日志尾部(`log_files` 里"应用日志")找根因。
|
||||
3. 已知配置:二进制路径、启动命令、端口、运行用户、是否绑域名。
|
||||
|
||||
收集后按症状进分支。
|
||||
|
||||
## 分支 A —— 启动失败(进程起不来 / run=false)
|
||||
按日志根因对号入座:
|
||||
| 日志特征 | 根因 | 处置 |
|
||||
|---|---|---|
|
||||
| `error while loading shared libraries: libxxx.so` | 缺动态库 | 汇报需装系统库(如 glibc/其他 .so),装后 `GoProjectControl(action='start')` |
|
||||
| `bind: address already in use` / `EADDRINUSE` | 端口被占 | `GoProjectModify(action='config', port=新端口)`(自动重启) |
|
||||
| `permission denied` / 无法写入日志 | 运行用户无权限 | `GoProjectModify(action='config', run_user=<有权限用户>)` |
|
||||
| 启动即退出 / pid 无 | 启动命令错 / 环境变量缺 | 核对 `project_cmd` 与 `env_list`;`GoProjectControl(action='start')` 重试 |
|
||||
| 二进制非当前平台编译 | 目标平台不符 | 重新 `go build` 目标平台二进制 |
|
||||
|
||||
- 修正后回场景一 Step 3 重新验证。**Go 进程无守护,崩了不会自动拉起**——排错后必须手动 start。
|
||||
|
||||
## 分支 B —— 访问异常(502/无法访问,但进程活着)
|
||||
1. `GoProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 A。
|
||||
2. **端口/反代核对**:`listen`(实际监听)vs `project_config.port`(反代目标)是否一致;grep `proxy_pass` `nginx/go_<name>.conf` 确认指向 `127.0.0.1:{实际端口}`。
|
||||
- 端口改了没同步 → `GoProjectModify(action='config', port=实际端口)`。
|
||||
- 反代指向错误端口 → 同上。
|
||||
3. 域名绑定:`bind_extranet` 是否开、域名是否在 nginx `server_name`(未绑 → `GoProjectModify(action='add_domain', domains=[...])` + `bind_extranet`)。
|
||||
4. 读 nginx error log(`log_files` 里 `/www/wwwlogs/<name>.error.log`)进一步定位。
|
||||
5. 修正后验证。
|
||||
|
||||
## 分支 C —— 进程在但无响应 / 卡死
|
||||
1. 应用日志尾部看异常/死锁(filesystem `Read`)。
|
||||
2. `SystemInfo()` 看系统资源(CPU/内存/负载)。
|
||||
3. 汇报,建议用户确认后 `GoProjectControl(action='restart')` 重启。
|
||||
|
||||
---
|
||||
|
||||
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||
|
||||
| 需求 | 工具 |
|
||||
|---|---|
|
||||
| 查看项目列表/状态 | `GoProjectInfo()`(project_name 留空) |
|
||||
| 查看单项目详情(run/listen/log_files/配置) | `GoProjectInfo(project_name=...)` |
|
||||
| 启动 / 停止 / 重启 | `GoProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||
| 看应用日志 / nginx 日志 | `GoProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||
| 改二进制/命令/端口/用户/开机自启/环境变量/备注(自动重启) | `GoProjectModify(action='config', ...)` |
|
||||
| 加域名 / 删域名(至少留一个) / 开 / 关外网映射 | `GoProjectModify(action='add_domain'/'remove_domain'/'bind_extranet'/'unbind_extranet', domains=[...])` |
|
||||
| Go SDK 列表 / 安装(Bash 后台) / 切换 / 卸载 / 设 GOPROXY | `GoVersion(action='list'/'install'/'use'/'uninstall'/'goproxy', ...)` |
|
||||
| **安装 Go SDK(下载+解压,后台)** | `GoVersion` install 取 `install_command` → `Bash(run_in_background=true)` + `BashStatus` 轮询 |
|
||||
| 删除项目(**高风险,先确认**;保留二进制与目录) | `GoProjectDelete(project_name=...)` |
|
||||
|
||||
---
|
||||
|
||||
# 完成汇报模板(部署成功)
|
||||
|
||||
返回:项目名 / 二进制路径(project_exe)/ 端口 / 运行用户 / Go SDK 版本;若绑域名:访问地址 + nginx 配置路径;启动验证结果(进程/端口/日志);遗留隐患提示(GOPROXY 未设、防火墙未放行、依赖库缺失、绑外网未开等)。
|
||||
@@ -0,0 +1,182 @@
|
||||
---
|
||||
name: BT-Html-Project-Deploy
|
||||
description: >
|
||||
在宝塔面板上管理 Html(静态)项目:创建静态站点(域名 + 网站根目录)、把前端构建产物部署到站点目录、
|
||||
编辑伪静态 rewrite 配置(SPA try_files / 自定义 location / 缓存)、改域名/网站根目录/运行目录/启停,
|
||||
并在静态站点访问异常(404 / SPA 刷新 404 / 伪静态不生效 / 目录权限)时排错。
|
||||
当用户要求把前端静态页面(HTML/SPA/单页应用)挂到域名上,或静态站点访问异常需要排查时使用。
|
||||
触发关键词:静态网站、HTML项目、部署前端、SPA、单页应用、伪静态、rewrite、运行目录、静态站 404、
|
||||
SPA 404、BT-Html-Project-Deploy。
|
||||
日常的查看/启停/改备注等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||
---
|
||||
|
||||
# Html(静态)项目运维 SOP
|
||||
|
||||
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||
> 本 SOP 覆盖三个主场景:**① 创建静态项目;② 配置编辑(伪静态 rewrite / 主 conf);③ 静态站点访问异常排错**。其他简单操作(状态查看、启停、改备注、绑删域名、改目录、运行目录、删除)不做 SOP,直接使用工具。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先只读侦察,再执行变更** —— 操作前先 `HtmlProjectInfo`(site_name 留空)列项目找到站点名(可能带 `_<端口>` 后缀),再 `HtmlProjectInfo(site_name=...)` 看当前域名/路径/运行目录/SSL;排错先读日志,不盲目重写配置。
|
||||
2. **静态站点本质 = 网站根目录 + nginx/apache conf + rewrite 文件** —— nginx 主 conf 在 `/www/server/panel/vhost/nginx/html_<name>.conf`(模板渲染产物),**伪静态 rewrite 文件在 `/www/server/panel/vhost/rewrite/html_<name>.conf`(面板官方自定义配置入口,被主 conf include)**。
|
||||
3. **改配置优先写 rewrite 文件** —— SPA `try_files`、自定义 `location`、静态资源缓存等写 rewrite 文件(面板创建的注释即引导"请将伪静态规则或自定义NGINX配置填写到此处");**只有确实要改 listen/root/自定义 server 段才动主 conf,且改前必须 filesystem `Read` 留基线**(面板 SSL/域名/改目录操作会重写覆盖主 conf)。
|
||||
4. **域名/路径/启停/运行目录走 `HtmlProjectModify`** —— 面板方法同步 domain 表与 nginx/apache server_name;**不要用 filesystem 直接改主 conf 来加域名**,会与面板不同步。
|
||||
5. **创建即生效** —— `HtmlProjectCreate` 成功即写 nginx/apache 配置 + 建目录(目录不存在自动创建)+ 非 80 端口放行防火墙 + 重载服务;返回的 `site_name_hint` 仅供参考,**实际站点名以 `HtmlProjectInfo` 列表返回的 name 为准**(主域名重名会带 `_<端口>`)。
|
||||
6. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||
7. **禁止操作**:`rm -rf` 站点根目录外的路径、修改宝塔/插件自身文件、读取插件 `data/` 凭据、直接写 nginx 主 conf 来改域名(走 Modify)。
|
||||
|
||||
---
|
||||
|
||||
# 场景一:创建静态项目
|
||||
|
||||
## Step 0 —— 预检
|
||||
1. 确认任务确为"创建 Html(静态)项目"。
|
||||
2. 拿到**要对外暴露的域名**(可带 `:端口`,非 80 端口会成为监听端口)与**网站根目录**(绝对路径,目录不存在会自动创建;也可指向已有前端目录)。
|
||||
3. 确认 Nginx/Apache 已安装(静态站依赖 web 服务)。
|
||||
|
||||
## Step 1 —— 调用创建
|
||||
`HtmlProjectCreate(domains=[...], path=...)`:
|
||||
- **必填**:`domains`(list,首项为主域名,如 `'example.com'` 或 `'example.com:8080'`)、`path`(网站根目录绝对路径,如 `/www/wwwroot/demo.example.com`)。
|
||||
- **可选**:`ps`(备注)、`type_id`(项目分类,默认 0)。
|
||||
|
||||
> 返回"创建成功"= 已写 nginx/apache 配置 + 建目录 + 放行端口 + 重载。`site_name_hint` 仅供参考。
|
||||
|
||||
## Step 2 —— 部署静态文件
|
||||
1. 把前端构建产物(如 `dist/` 下文件)上传到站点根目录 `path`:
|
||||
- 文件已在本机:用文件上传(PrepareUpload 分块上传)到站点目录,或用 filesystem 移动。
|
||||
- 远端构建:先下载到本机再上传,或直接把站点 `path` 指到已有构建目录。
|
||||
2. 确认 `index.html` 已在根目录(或运行目录,见场景二 set_run_path)。
|
||||
|
||||
## Step 3 —— 验证(强制)
|
||||
1. `HtmlProjectInfo`(site_name 留空)确认站点出现,记下真实 `name`。
|
||||
2. `HtmlProjectInfo(site_name=...)` 看域名/路径/SSL。
|
||||
3. 访问域名验证首页正常返回。
|
||||
|
||||
- 全通过 → 按"完成汇报"收尾。
|
||||
- 访问异常 → 转场景三排错。
|
||||
|
||||
---
|
||||
|
||||
# 场景二:配置编辑(伪静态 rewrite / 主 conf)
|
||||
|
||||
## Step 0 —— 拿基线与现状
|
||||
1. `HtmlProjectInfo(site_name=...)`:拿到 `rewrite_file`(伪静态/自定义入口)、`config_file`(nginx 主 conf)、`apache_config_file` 路径,以及当前域名/路径/运行目录。
|
||||
2. filesystem `Read` `rewrite_file` 与 `config_file` 看当前配置。
|
||||
|
||||
## Step 1 —— 改配置(优先 rewrite 文件)
|
||||
按「常用静态站点 nginx 配置速查」(见文末)在 **rewrite 文件**里加/改规则。常见操作:
|
||||
- **SPA 路由重写**(刷新子路由 404):`location / { try_files $uri $uri/ /index.html; }`。
|
||||
- **自定义 location**:如 `location /api { proxy_pass http://127.0.0.1:9000; ... }`(把某路径转发到后端)。
|
||||
- **静态资源缓存**:`location ~* \.(js|css|png|jpg|svg|woff2)$ { expires 30d; add_header Cache-Control "public, max-age=2592000"; }`。
|
||||
- **开启 gzip**:`gzip on; gzip_types text/css application/javascript image/svg+xml;`。
|
||||
|
||||
> 只有确实要改 `listen` / `root` / `server_name` 之外的 server 层配置才动**主 conf**:filesystem `Read` `config_file` 留基线 → 改 → filesystem `Write` 回写。**改主 conf 前必须 Read**,写坏可恢复。
|
||||
|
||||
## Step 2 —— 回传并验证
|
||||
1. filesystem `Write` 回写修改后的文件(rewrite 或主 conf)。
|
||||
2. `Bash` 执行 `nginx -t` 确认配置语法通过;失败按报错行修文件重写。
|
||||
3. `Bash` `nginx -s reload`(如有需要)让新配置生效。
|
||||
4. 访问验证(如有域名):确认新规则生效、旧规则仍在。
|
||||
|
||||
- 配置写坏导致站点异常 → 用 Read 留的基线恢复重写;主 conf 被面板覆盖 → 用 `HtmlProjectModify(action='change_path'/'set_run_path')` 走面板。
|
||||
|
||||
## Step 3 —— 面板操作走 Modify(域名/路径/启停/运行目录)
|
||||
| 需求 | 调用 |
|
||||
|---|---|
|
||||
| 加域名 | `HtmlProjectModify(site_name, action='add_domain', domains=['www.example.com'])` |
|
||||
| 删域名 | `HtmlProjectModify(site_name, action='remove_domain', domain='www.example.com')` |
|
||||
| 启/停/重启 | `HtmlProjectModify(site_name, action='start'/'stop'/'restart')` |
|
||||
| 改网站根目录 | `HtmlProjectModify(site_name, action='change_path', path='/www/wwwroot/new')`(**目标目录必须已存在**) |
|
||||
| 设运行目录(子目录) | `HtmlProjectModify(site_name, action='set_run_path', run_path='/dist')` |
|
||||
|
||||
---
|
||||
|
||||
# 场景三:静态站点访问异常排错
|
||||
|
||||
## Step 0 —— 只读侦察(不盲改)
|
||||
1. `HtmlProjectInfo` 确认项目存在、域名/路径/运行目录现状。
|
||||
2. `Bash` 读 nginx 错误日志 `/www/wwwlogs/<name>.error.log` 与访问日志 `/www/wwwlogs/<name>.log` 尾部。
|
||||
|
||||
## Step 1 —— 按症状对号入座
|
||||
|
||||
| 症状 | 常见根因 | 处置 |
|
||||
|---|---|---|
|
||||
| **首页 404 / 空白** | 前端文件没传到根目录、`index.html` 缺失、运行目录不对 | 确认文件在站点根目录(或运行目录);`HtmlProjectModify(action='set_run_path', run_path=...)` 指到实际构建目录 |
|
||||
| **子路由刷新 404(SPA)** | 没配 `try_files` 回退 index.html | 场景二在 rewrite 文件加 `location / { try_files $uri $uri/ /index.html; }` |
|
||||
| **伪静态不生效** | rewrite 文件没写对/没 include、nginx 没重载 | `nginx -t` + `nginx -s reload`;确认 rewrite 文件语法 |
|
||||
| **静态资源 404 / 403** | 目录权限不对、资源在子目录但 root 指错 | `Bash` `ls -la` 站点目录、`chown -R www:www` 站点目录 |
|
||||
| **只对本机/内网生效** | 域名未绑定、非 80 端口防火墙未放行 | `HtmlProjectModify(action='add_domain')` 补域名;`Bash` 查防火墙端口放行状态 |
|
||||
| **HTTPS 不生效** | 证书未部署(MCP 不封装 SSL) | 证书部署走面板,MCP 只读 ssl 状态 |
|
||||
|
||||
## Step 2 —— 修复与验证
|
||||
1. 按上表定位根因,**改配置文件必须 filesystem Read 基线 → 改 → Write → `nginx -t`**,改域名/路径走 `HtmlProjectModify`。
|
||||
2. 修复后重访验证;仍异常则回到 Step 0 换角度(读实时日志尾部 `tail -f`)。
|
||||
|
||||
---
|
||||
|
||||
# 运维速查
|
||||
|
||||
| 需求 | 调用 |
|
||||
|---|---|
|
||||
| 列表/找站点名 | `HtmlProjectInfo(search=..., page=...)`(site_name 留空) |
|
||||
| 查看详情/域名/路径/conf 路径 | `HtmlProjectInfo(site_name=...)` |
|
||||
| 创建静态项目 | `HtmlProjectCreate(domains=[...], path=...)` |
|
||||
| 读/改伪静态(优先) | filesystem `Read`/`Write` `rewrite_file`(`/www/server/panel/vhost/rewrite/html_<name>.conf`) |
|
||||
| 读/改 nginx 主 conf | filesystem `Read` 留基线 → 改 → `Write` `config_file`(`/www/server/panel/vhost/nginx/html_<name>.conf`) |
|
||||
| 验证语法 | `Bash` `nginx -t` |
|
||||
| 加删域名 / 启停 / 改目录 / 运行目录 | `HtmlProjectModify(site_name=..., action=..., ...)` |
|
||||
| 删除项目 | `HtmlProjectDelete(site_name=...)`(高风险,确认后;不删站点目录,需删目录用文件系统工具) |
|
||||
|
||||
---
|
||||
|
||||
# 常用静态站点 nginx 配置格式与位置速查
|
||||
|
||||
**位置**:
|
||||
- **rewrite 文件**(`/www/server/panel/vhost/rewrite/html_<name>.conf`):被 nginx 主 conf include 在 server 块内,**伪静态/自定义 location/缓存优先写这里**。
|
||||
- **nginx 主 conf**(`/www/server/panel/vhost/nginx/html_<name>.conf`):完整 server 块(listen/server_name/root/ssl/日志/include),模板渲染产物。
|
||||
|
||||
**典型片段**(写进 rewrite 文件即可):
|
||||
|
||||
```nginx
|
||||
# SPA 单页应用:子路由刷新回退到 index.html(最常用)
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# 静态资源缓存
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2|ico)$ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, max-age=2592000";
|
||||
}
|
||||
|
||||
# 自定义 location:把某路径转发到后端
|
||||
location /api {
|
||||
proxy_pass http://127.0.0.1:9000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
|
||||
# 开启 gzip 压缩(server 层,放 rewrite 文件顶部即可)
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- `location / { try_files $uri $uri/ /index.html; }` 是 SPA(Vue/React 等 history 路由)部署后**必配**的伪静态规则,否则刷新子路由 404。
|
||||
- 伪静态/缓存/自定义 location 一律写 rewrite 文件,**不改主 conf**;只有要动 listen/root/自定义 server 段才碰主 conf,且先 `Read` 留基线。
|
||||
- 改完**必须** `nginx -t` 验证,再确认访问生效。
|
||||
- 涉及域名/路径/运行目录的变更走 `HtmlProjectModify`,不要手改主 conf。
|
||||
|
||||
---
|
||||
|
||||
# 完成汇报模板
|
||||
|
||||
汇报固定四段(每段 1-3 行,用一次工具查证一个结论,不堆 log):
|
||||
|
||||
- **现状**:静态项目 `<name>`,域名 `<域名:端口>`,网站根目录 `<path>`,状态(运行中/已停止)。
|
||||
- **变更**:`<创建了静态项目 / 部署了前端文件到 <path> / 添加了 SPA try_files 伪静态 / 修改了网站根目录 / 启停了项目 / 绑定了域名>`。
|
||||
- **验证**:`nginx -t` 通过 / `HtmlProjectInfo` 复查域名与路径 / 访问 `<域名>` 返回预期。
|
||||
- **遗留**:`<若有:SSL 证书未部署需面板处理 / 后端服务未监听需确认>;否则无`。
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
name: BT-Java-Project-Deploy
|
||||
description: >
|
||||
在宝塔面板上部署 Java jar 项目(Spring Boot),并在项目启动失败时排错。
|
||||
当用户要求把本机已有的 jar 包部署成面板可管理的 Java 项目(含 JDK、Nginx 代理/域名),
|
||||
或 Java 项目启动失败/访问异常需要排查根因时使用。
|
||||
触发关键词:部署 Java、jar 包部署、Spring Boot 部署、Java 项目创建、
|
||||
Java 项目启动失败、jar 起不来、jar 启动报错、502、访问异常、JDK 版本不匹配。
|
||||
日常的启停/状态/日志/改配置等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||
---
|
||||
|
||||
# Java 项目部署与启动排错 SOP
|
||||
|
||||
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||
> 本 SOP 只覆盖两个主场景:**① 部署 Java 项目;② 项目启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、删除)不做 SOP,直接使用工具。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先只读侦察,再执行变更** —— 部署前必须完成 jar 分析;排错先读日志,不盲目重启。
|
||||
2. **创建后必须验证启动** —— "创建成功"不算完,必须确认进程存活 + 监听端口 + 日志无致命错误;验证失败即转入场景二。
|
||||
3. **删除项目属高风险**,必须先获得用户明确确认;启停/重启/改配置属中风险,操作前说明影响。
|
||||
4. **JDK 匹配** —— Spring Boot 3.x 需 JDK 17+,Boot 2.x 需 JDK 8/11;安装或切换前先检测本机 JDK。
|
||||
5. **端口唯一性** —— 创建/改端口前检查占用。
|
||||
6. **域名可访问 = 三件事** —— ① `add_domain` 写入 `server_name`;② `bind_extranet` 开启外网框架(生成 conf 骨架,**不含反代**);③ `add_proxy(proxy_port=应用端口)` 真正注入 `proxy_pass http://127.0.0.1:port`。**漏掉 ③ 会访问 403**。创建时带 `domains` 会完成 ①② 并尝试自动建 ③,但**必须验证**(`proxy_list` 或 grep `proxy_pass`),缺失即补 `add_proxy`。
|
||||
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||
8. **禁止操作**:删除 jar 源文件、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||
|
||||
---
|
||||
|
||||
# 场景一:部署 Java 项目
|
||||
|
||||
## Step 0 —— 预检
|
||||
1. 确认任务确为"部署新 Java 项目"(非排错/运维)。
|
||||
2. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||
3. (可用 todo 工具时)建任务列表:定位 jar → 分析 → JDK → 创建 → 验证。
|
||||
|
||||
## Step 1 —— 定位 jar 包
|
||||
- 用户直接给出 jar 绝对路径,或:
|
||||
- 用文件工具 `Glob(pattern='**/*.jar')` / `LS(path=...)` 在服务器上定位 jar(排除运行目录与 `lib/` 依赖库)。
|
||||
- **校验**:路径存在、是普通文件、非敏感目录(`/etc`、`/boot`、插件 `data/` 等)。
|
||||
- 记录 jar 绝对路径与所在目录(jar_path)。
|
||||
|
||||
## Step 2 —— 分析 jar(部署前必须)
|
||||
调用 `JavaProjectCreate(jar_path=..., analyze_only=true)`(只读,不创建)。返回:
|
||||
1. 是否 Spring Boot 可执行 jar(jar_info)。
|
||||
2. **应用端口**(`application.yml/properties` 的 `server.port`,或命令行/环境变量覆盖)。
|
||||
3. 实际生效的配置文件路径与优先级(config_files)。
|
||||
4. **启动前隐患清单**(tips:数据库/中间件连通性、账号密码疑似错误、profile 缺失等)。
|
||||
|
||||
**决策**:
|
||||
- 解析不出端口 → 询问用户指定,并在创建时显式传 `port`。
|
||||
- 隐患清单含阻断级(error)→ 向用户说明,确认是否继续。
|
||||
|
||||
## Step 3 —— JDK 确认 / 安装
|
||||
1. `JavaJdk(action='list')` 检测本机 JDK(name/path/operation:0 未装 1 已装 2 系统 3 安装中)。
|
||||
2. 按 Spring Boot 版本定所需 JDK(Boot3→17+,Boot2→8/11)。
|
||||
3. 已有 → 记录 path;无 → 询问用户后 `JavaJdk(action='install', version=...)`(异步,用 list 轮询 operation=3→1)。
|
||||
|
||||
## Step 4 —— 创建项目(注册)
|
||||
调用 `JavaProjectCreate(project_name=..., jar_path=..., port=..., [domains=...])`。
|
||||
创建前确认参数:`project_name`(1-20 字符、不重复)、jar 路径、JDK 路径(缺省自动选已装)、`run_user`(默认 www)、端口(**检查未被占用**)、启动命令(缺省自动拼 `{jdk}/bin/java -jar ... --server.port=<port>`)。
|
||||
**外网映射决策**:
|
||||
- 要域名访问 → `domains=['域名']`(或 `['域名:端口']`),创建时绑定域名并开启外网框架(`server_name`)。创建工具会**尝试**自动建反代(`proxy_path` 默认 `'/'` 全站,可改如 `'/api'`;`proxy_path=''` 关闭)。
|
||||
**创建后必须验证反代已注入**:`JavaProjectModify(action='proxy_list')` 应有 `proxy_port`,或 grep `proxy_pass` `java_<name>.conf`。缺失 → `JavaProjectModify(action='add_proxy', proxy_port=应用端口, proxy_dir='/')` 补齐,否则访问 403。
|
||||
- 仅本机 → 不传 domains(`bind_extranet=0`)。
|
||||
|
||||
## Step 5 —— 启动验证(强制)
|
||||
创建后调用 `JavaProjectInfo(project_name=...)` 依次确认:
|
||||
1. 进程存活(有 pid)。
|
||||
2. 应用端口在 `listen` 列表。
|
||||
3. 用返回的 `log_files` 里的应用日志路径,调 filesystem `Read` 看尾部无致命异常(`Exception`/`Caused by`)。
|
||||
- 全通过 → 按"完成汇报"收尾。
|
||||
- 任一失败 → **转场景二排错**。
|
||||
|
||||
---
|
||||
|
||||
# 场景二:项目启动排错
|
||||
|
||||
> 适用:部署后验证失败、或用户报"Java 项目启动失败/访问异常"。
|
||||
|
||||
## Step 0 —— 快速定位现状(只读)
|
||||
并行收集 3 项,不跳过:
|
||||
1. `JavaProjectInfo(project_name=...)`:pid 是否生成、`listen` 端口、运行态(区分"进程没起来"与"进程起来了但访问不了")。
|
||||
2. 读应用日志尾部:用返回的 `log_files` 应用日志路径调 filesystem `Read`,找异常堆栈根因。
|
||||
3. 已知配置:jar 路径、JDK、端口、启动命令。
|
||||
|
||||
收集后按症状进分支。
|
||||
|
||||
## 分支 A —— 启动失败(进程起不来 / pid 无 / 端口未监听)
|
||||
按日志根因对号入座:
|
||||
| 日志特征 | 根因 | 处置 |
|
||||
|---|---|---|
|
||||
| `Address already in use` / 端口占用 | 端口被占 | 换端口:`JavaProjectModify(action='config', project_cmd=改 --server.port=)` 或重建 |
|
||||
| `UnsupportedClassVersionError` | JDK 版本过低/过高 | `JavaProjectModify(action='config', project_jdk=匹配JDK)` 或 `JavaJdk(action='install', version=...)` |
|
||||
| `ClassNotFoundException` / 缺依赖 | 依赖库缺失 | 检查启动命令 `-Dloader.path` 与 lib 目录,改 `project_cmd` |
|
||||
| 数据库/中间件连接失败 | 服务未起或账号密码错 | 结合 Step 2 的 tips,确认中间件与账号 |
|
||||
| 配置缺失 / 环境变量 | 缺配置 | 改 `project_cmd`/`env_file` 补配置后重启 |
|
||||
|
||||
- 无明确报错 → 查 `JavaProjectInfo`:pid 是否生成、端口是否监听、启动命令是否完整。
|
||||
- 修复后回到场景一 Step 5 重新验证。
|
||||
|
||||
## 分支 B —— 访问异常(502 / 无法访问,但进程活着)
|
||||
1. `JavaProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 A。
|
||||
2. **nginx 反代目标匹配**:用 `log_files` 或 `JavaProjectInfo` 定位 `java_<name>.conf`,调 filesystem `Read` 看 `proxy_pass` 是否指向 `127.0.0.1:实际端口`。
|
||||
- 配置里**没有** `proxy_pass` location(`project_config.proxy_info` 为空)→ 反代缺失,用 `JavaProjectModify(action='add_proxy', proxy_port=实际端口, proxy_dir='/')` 补齐,`action='proxy_list'` 核对。
|
||||
- 端口改了但反代没同步 → `JavaProjectModify(action='add_proxy', proxy_port=新端口)` 或改配置重建。
|
||||
3. **反代是否真注入**:`JavaProjectModify(action='proxy_list')` 看有无 `proxy_port`;`grep proxy_pass /www/server/panel/vhost/nginx/java_<name>.conf`。`bind_extranet` 为开但 `proxy_pass` 为空 → 漏了 `add_proxy`,用 `action='add_proxy', proxy_port=实际端口` 补。
|
||||
4. **外网绑定状态**:`bind_extranet` 是否为开;域名是否在 nginx `server_name`(未开 → `JavaProjectModify(action='bind_extranet')`)。
|
||||
5. 读 nginx error log(`log_files` 里的路径)进一步定位。
|
||||
6. 修正后验证。
|
||||
|
||||
## 分支 C —— 进程在但无响应 / 卡死
|
||||
1. 应用日志尾部看异常/死锁(filesystem `Read`)。
|
||||
2. `SystemInfo()` 看系统资源(CPU/内存/负载)是否异常。
|
||||
3. 汇报,建议用户确认后 `JavaProjectControl(action='restart')` 重启。
|
||||
|
||||
---
|
||||
|
||||
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||
|
||||
| 需求 | 工具 |
|
||||
|---|---|
|
||||
| 查看项目列表/状态 | `JavaProjectInfo()`(project_name 留空) |
|
||||
| 查看单项目详情(含日志路径) | `JavaProjectInfo(project_name=...)` |
|
||||
| 启动 / 停止 / 重启 | `JavaProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||
| 看应用日志 / nginx 日志 | `JavaProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||
| 加域名 / 删域名(至少留一个) | `JavaProjectModify(action='add_domain'/'remove_domain', domains=[...])` |
|
||||
| 开/关外网框架(只生成 server_name 骨架,**不注入反代**) | `JavaProjectModify(action='bind_extranet'/'unbind_extranet')` |
|
||||
| 增反代(真正注入 proxy_pass) | `JavaProjectModify(action='add_proxy', proxy_port=应用端口, proxy_dir='/')` |
|
||||
| 删反代 | `JavaProjectModify(action='remove_proxy', proxy_id=...)`(id 用 proxy_list 取) |
|
||||
| 查反代 | `JavaProjectModify(action='proxy_list')` |
|
||||
| 改 jar / JDK / 启动命令 / 运行用户 / 守护 | `JavaProjectModify(action='config', ...)`(重启生效) |
|
||||
| 删除项目(**高风险,先确认**) | `JavaProjectDelete(project_name=...)`(保留 jar) |
|
||||
|
||||
---
|
||||
|
||||
# 完成汇报模板(部署成功)
|
||||
|
||||
返回:项目名 / jar 路径 / 运行用户 / JDK 路径 / 监听端口;若绑域名:访问地址 + nginx 配置路径;应用日志路径;启动验证结果(进程/端口/日志);遗留隐患提示(若有)。
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
name: BT-Node-Project-Deploy
|
||||
description: >
|
||||
在宝塔面板上部署 Node.js 项目(nodejs/general/pm2 三种类型,含 Nginx 域名/反代),
|
||||
并在项目启动失败或访问异常时排错。
|
||||
当用户要求把本机已有的 Node 项目目录部署成面板可管理的项目(含 node 版本、依赖安装、
|
||||
Nginx 代理/域名、pm2 守护),或 Node 项目启动失败/访问异常需要排查根因时使用。
|
||||
触发关键词:部署 Node、Node 项目部署、nodejs 部署、npm 项目部署、PM2 部署、
|
||||
Node 项目启动失败、npm 起不来、Node 报错、502、访问异常、pm2 errored、Cannot find module。
|
||||
日常的启停/状态/日志/改配置等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||
---
|
||||
|
||||
# Node.js 项目部署与启动排错 SOP
|
||||
|
||||
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||
> 本 SOP 只覆盖两个主场景:**① 部署 Node 项目;② 启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、删除)不做 SOP,直接使用工具。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先只读侦察,再执行变更** —— 部署前必须完成项目分析;排错先读日志,不盲目重启。
|
||||
2. **创建后必须验证启动** —— "创建成功"不算完,必须确认进程存活 + 监听端口 + 日志无致命错误;验证失败即转入场景二。
|
||||
3. **删除项目属高风险**,必须先获得用户明确确认;启停/重启/改配置属中风险,操作前说明影响。
|
||||
4. **Node 版本匹配** —— 创建前用 `NodeVersion(action='list')` 检测已装版本;`package.json` 的 `engines.node` 不符时优先换已装版本或安装。
|
||||
5. **端口唯一性** —— 创建/改端口前检查占用;**绑外网必须有端口**(`bind_extranet` 依赖 `port`)。
|
||||
6. **绑域名 = 自动反代** —— Node 的反代由 nginx 模板按 `project_config.port` 自动生成(`proxy_pass http://127.0.0.1:{port}`),**无独立反代步骤**。访问异常时核对:`NodeProjectInfo` 的 `listen`(实际监听端口)vs 配置端口(反代目标)是否一致,不一致 = 502。
|
||||
7. **依赖先行** —— nodejs 类型缺 `node_modules` 启动必失败。创建时 `install_deps=true` 或创建后装依赖再启动。
|
||||
8. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||
9. **禁止操作**:删除项目目录/源码、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||
|
||||
---
|
||||
|
||||
# 场景一:部署 Node 项目
|
||||
|
||||
## Step 0 —— 预检
|
||||
1. 确认任务确为"部署新 Node 项目"(非排错/运维)。
|
||||
2. 确定**项目类型**:`nodejs`(package.json scripts)/ `general`(直接指定启动文件)/ `pm2`(守护+cluster+自愈)。
|
||||
3. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||
|
||||
## Step 1 —— 定位项目目录
|
||||
- 用户给出 `project_cwd`(项目根,含 package.json),或:
|
||||
- 用文件工具 `Glob(pattern='**/package.json')` / `LS(path=...)` 定位(排除 `node_modules`、`dist`、`build` 等构建目录)。
|
||||
- **校验**:目录存在、含 `package.json`(nodejs/pm2 必需;general 可没有)、非敏感目录(`/etc`、`/boot`、插件 `data/` 等)。
|
||||
|
||||
## Step 2 —— 分析项目(部署前必须)
|
||||
调用 `NodeProjectCreate(project_cwd=..., analyze_only=true)`(只读,不创建)。返回:
|
||||
1. `package.json` 的 `name/version`、`engines.node`、`dependencies` 数量。
|
||||
2. `scripts` 启动项列表(nodejs 类型的 `project_script` 从这里选)。
|
||||
3. `node_modules` 是否存在(缺 → 需先装依赖)。
|
||||
4. `port`/`port_hints`:从入口文件启发式探测的端口(仅供参考)。
|
||||
|
||||
**决策**:
|
||||
- nodejs 类型:确认启动脚本名(`start`/`dev`/自定义),即 `project_script`。
|
||||
- pm2 类型:确认入口文件(js 或 ecosystem 配置)与 `cluster` 实例数。
|
||||
- 无端口或启发式不准 → 询问用户,创建时显式传 `port`(绑外网必需)。
|
||||
|
||||
## Step 3 —— Node 版本确认 / 安装
|
||||
1. `NodeVersion(action='list')` 检测已装版本与可用包管理器(npm/yarn/pnpm)。
|
||||
2. 若返回 `plugin_installed=false`:nodejs 版本管理器插件未装,**先调 `SoftwareInstall(name='nodejs')` 安装插件**(可再用 `SoftwareList(name='nodejs')` 查进度),装完继续。
|
||||
3. 需要新装版本时,用 `NodeVersion(action='online', lts_only=true, page=...)` 浏览可安装版本(按版本从新到旧排序、本地分页,`lts_only=false` 看全部;每项 `installed` 标记是否已装),从中挑选稳定版。
|
||||
4. 对照 `engines.node`(无则默认 LTS)。
|
||||
5. 已装 → 记录版本号(如 `v20.15.0`);无 → 询问用户后 `NodeVersion(action='install', version=..., install_pm2=<pm2 类型时 true>)`(插件安装,较慢,装完用 list 确认)。
|
||||
|
||||
## Step 4 —— 创建项目(注册)
|
||||
调用 `NodeProjectCreate(project_type=..., project_name=..., project_cwd=..., nodejs_version=..., ...)`。
|
||||
按类型传参:
|
||||
- **nodejs**:`project_script`(scripts key,如 `'start'`)、`pkg_manager`(npm/yarn/pnpm)。
|
||||
- **general**:`project_file`(启动文件绝对路径)、`project_args`(可选)。**同时必须传 `nodejs_version`**(三类型均必填、须已安装——general 漏传会直接报错,不是可选项)。
|
||||
- **pm2**:`project_file`(js 入口或 ecosystem 配置,内容检测自动路由)、`cluster`、`watch`、`max_memory_limit`。**pm2 类型项目启动依赖该 node 版本已全局安装 pm2**——创建工具会自动检测,该版本缺 pm2 时自动调插件安装(结果 `data.pm2_auto_installed` 标记);也可手动 `NodeVersion(action='module', version=<nodejs_version>, modules=['pm2'])`。
|
||||
- **通用**:`port`(绑外网必需)、`run_user`(默认 www)、`env`(**注意:面板对 nodejs 类型的 env 注入有缺陷——存了但不写进启动脚本,需要环境变量的项目建议用 general 类型**)、`install_deps`(package.json 有依赖且未装 node_modules 时给 true)、`release_firewall`(需放行端口时)、`domains=['域名']`(绑域名+自动反代)。
|
||||
|
||||
**外网映射**:要域名访问 → 传 `domains`(自动写 `server_name` + `proxy_pass 127.0.0.1:{port}`,**无需额外反代步骤**)。`install_deps=true` 较慢(npm install),可接受等待。
|
||||
|
||||
## Step 5 —— 启动验证(强制)
|
||||
创建后调用 `NodeProjectInfo(project_name=...)` 依次确认:
|
||||
1. 进程存活(`run=true`)。
|
||||
2. 应用端口在 `listen` 列表(`listen_ok=true`)。
|
||||
3. 用返回的 `log_files` 里应用日志路径,调 filesystem `Read` 看尾部无致命异常(`Cannot find module`/`EADDRINUSE`/`throw er`)。
|
||||
|
||||
⚠️ **pm2 类型不要信创建返回的「已自动启动」**:daemon 可能未持久化(`run:false`、`listen` 空但 `listen_ok=true`)。创建后必须:
|
||||
① 立即 `NodeProjectInfo` 核验 `run=true`;
|
||||
② 间隔几秒**再次** `NodeProjectInfo` 复检持久化(本地等待即可,不调长工具);
|
||||
③ 不持久 → `NodeProjectControl(action='start')` 重拉再复检。
|
||||
|
||||
- 全通过 → 按"完成汇报"收尾。
|
||||
- 任一失败 → **转场景二排错**。
|
||||
|
||||
---
|
||||
|
||||
# 场景二:启动排错
|
||||
|
||||
> 适用:部署后验证失败、或用户报"Node 项目启动失败/访问异常"。
|
||||
|
||||
## Step 0 —— 快速定位现状(只读)
|
||||
并行收集,不跳过:
|
||||
1. `NodeProjectInfo(project_name=...)`:`run`、`listen`、`listen_ok`(区分"进程没起来"与"起来了但访问不了");pm2 项目看状态。
|
||||
2. 读应用日志尾部:用返回的 `log_files` 应用日志路径调 filesystem `Read`,找异常堆栈根因。
|
||||
3. 已知配置:项目类型、入口/脚本、node 版本、端口、是否已装依赖。
|
||||
|
||||
收集后按症状进分支。
|
||||
|
||||
## 分支 A —— 启动失败(进程起不来 / run=false)
|
||||
按日志根因对号入座:
|
||||
| 日志特征 | 根因 | 处置 |
|
||||
|---|---|---|
|
||||
| `Error: Cannot find module 'x'` | 依赖未安装 | `NodeProjectCreate(project_cwd=<项目目录>, nodejs_version=..., project_script=..., install_deps=true)` 或装依赖后重启 |
|
||||
| `EADDRINUSE` / `Port 3000 is already in use` | 端口被占 | `NodeProjectModify(action='config', port=新端口)` 后 `NodeProjectControl(action='restart')` |
|
||||
| `npm ERR! Missing script: "start"` | scripts key 名错 | `NodeProjectModify(action='config', project_script=正确key)` |
|
||||
| `throw er; Unhandled 'error' event` | 启动即崩(端口/环境) | 看堆栈中具体原因;换端口或补 env |
|
||||
| `ERR_REQUIRE_ESM` / 语法错误 | 模块系统/代码问题 | 检查入口与 `package.json` 的 `type` 字段 |
|
||||
| node 版本引擎不符 | `engines.node` 不匹配 | `NodeProjectModify(action='config', nodejs_version=匹配版本)` 或 `NodeVersion(action='install')` |
|
||||
| 进程起来但 pid 无/端口没监听 | 启动后立即退出 | 读日志尾找 `exit`/`Error` 根因 |
|
||||
|
||||
- 无明确报错 → 查 `NodeProjectInfo`:run、listen、启动命令是否完整;`log_files` 有无 pm2 err.log。
|
||||
- 修复后回到场景一 Step 5 重新验证。
|
||||
|
||||
## 分支 B —— 访问异常(502/无法访问,但进程活着)
|
||||
1. `NodeProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 A。
|
||||
2. **反代端口匹配**:看 `listen`(实际监听)vs `project_config.port`(反代目标)是否一致;grep `proxy_pass` `node_<name>.conf`(`/www/server/panel/vhost/nginx/node_<name>.conf`)确认反代指向 `127.0.0.1:{实际端口}`。
|
||||
- 端口改了没同步 → `NodeProjectModify(action='config', port=实际端口)`(有 domains 时自动重写反代)。
|
||||
- 反代指向错误端口 → 同上。
|
||||
3. **域名绑定**:`bind_extranet` 是否开、域名是否在 nginx `server_name`(未绑 → `NodeProjectModify(action='add_domain', domains=[...])`)。
|
||||
4. 读 nginx error log(`log_files` 里 `/www/wwwlogs/<name>.error.log`)进一步定位。
|
||||
5. 修正后验证。
|
||||
|
||||
## 分支 C —— PM2 项目异常
|
||||
1. `NodeProjectInfo` 看 pm2 状态(online/stopped/errored)。
|
||||
2. `errored`(崩溃超限)→ 读 `log_files` 里 pm2 `err.log` 找根因;修复后用 `NodeProjectControl(action='restart')` 重启。
|
||||
3. 读 `/www/wwwlogs/pm2/<name>/out.log|err.log`。
|
||||
4. 依赖问题 → 同分支 A。
|
||||
|
||||
## 分支 D —— 进程在但无响应 / 卡死
|
||||
1. 应用日志尾部看异常/死锁(filesystem `Read`)。
|
||||
2. `SystemInfo()` 看系统资源(CPU/内存/负载)。
|
||||
3. 汇报,建议用户确认后 `NodeProjectControl(action='restart')` 重启。
|
||||
|
||||
---
|
||||
|
||||
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||
|
||||
| 需求 | 工具 |
|
||||
|---|---|
|
||||
| 查看项目列表/状态 | `NodeProjectInfo()`(project_name 留空) |
|
||||
| 查看单项目详情(含日志路径) | `NodeProjectInfo(project_name=...)` |
|
||||
| 启动 / 停止 / 重启 | `NodeProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||
| 看应用日志 / pm2 / nginx 日志 | `NodeProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||
| 改脚本/参数/node 版本/端口/用户/环境/内存 | `NodeProjectModify(action='config', ...)`(重启生效) |
|
||||
| 加域名 / 删域名(至少留一个) | `NodeProjectModify(action='add_domain'/'remove_domain', domains=[...])` |
|
||||
| node 版本检测 / 在线浏览 / 安装 | `NodeVersion(action='list'/'online'/'install', ...)` |
|
||||
| 给 node 版本装全局模块(pm2/pnpm/yarn 等) | `NodeVersion(action='module', version=<nodejs_version>, modules=['pm2'])` |
|
||||
| 删除项目(**高风险,先确认**) | `NodeProjectDelete(project_name=...)`(保留目录源码) |
|
||||
|
||||
---
|
||||
|
||||
# 完成汇报模板(部署成功)
|
||||
|
||||
返回:项目名 / 项目类型 / 目录 / node 版本 / 运行用户 / 监听端口;若绑域名:访问地址 + nginx 配置路径;应用日志路径;启动验证结果(进程/端口/日志);遗留隐患提示(依赖未装、env 未注入等)。
|
||||
@@ -0,0 +1,174 @@
|
||||
---
|
||||
name: BT-Python-Project-Deploy
|
||||
description: >
|
||||
在宝塔面板上部署 Python 项目(uwsgi/gunicorn/command 三种运行方式,含虚拟环境配置、
|
||||
Python 版本安装、requirements 依赖、Nginx 域名/反代),并在环境准备或启动失败时排错。
|
||||
当用户要求把本机已有的 Python 项目目录部署成面板可管理的项目(含 Python 版本安装、
|
||||
虚拟环境创建、pip 依赖、uwsgi/gunicorn 托管或自定义命令启动),或 Python 项目
|
||||
启动失败/访问异常/环境准备失败需要排查根因时使用。
|
||||
触发关键词:部署 Python、Python 项目部署、django/flask/fastapi/sanic 部署、
|
||||
uvicorn/gunicorn/uwsgi、虚拟环境 venv、pip install、Python 项目启动失败、
|
||||
ImportError、ModuleNotFoundError、502、访问异常、celery、关联进程、requirements。
|
||||
日常的启停/状态/日志/改配置/装包等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||
---
|
||||
|
||||
# Python 项目部署与启动排错 SOP
|
||||
|
||||
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||
> 本 SOP 只覆盖两个主场景:**① 部署 Python 项目;② 环境准备/启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、装包、删除)不做 SOP,直接使用工具。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先只读侦察,再执行变更** —— 部署前必须完成项目分析;排错先读日志,不盲目重启。
|
||||
2. **创建成功 ≠ 启动成功** —— Python 创建项目后环境准备(装依赖+生成启动脚本+尝试启动)是**后台异步**的。必须用 `PythonProjectInfo` 轮询 `prep_status` 到 `complete`,再核验进程存活 + 监听端口 + 日志无致命错误;`prep_status=failure` 立即转场景二。**这是本场景最容易栽的坑。**
|
||||
3. **建项目前必须有虚拟环境** —— 面板要求 `python_bin` 是已托管的 venv/conda(`can_use_directly`)。部署顺序:版本 → 环境 → 项目。
|
||||
4. **Python 版本安装走 Bash 后台** —— 源码编译极慢(10-30 分钟),不得用同步工具卡住;必须 `Bash(run_in_background=true)` + `BashStatus` 轮询。
|
||||
5. **删除项目保留虚拟环境** —— venv 与项目非强绑定(可复用/共享),删除不删 venv(面板语义);如需移除单独用 `PythonEnv(action='remove')`。删除本身仍高风险(停进程/清配置/删记录),先确认。
|
||||
6. **绑域名 = 外网映射 + 反代** —— `add_domain` 只写域名,需 `bind_extranet` 生成 nginx 配置(proxy 到 127.0.0.1:port);path→port 反代(`add_proxy`)**必须先开启外网映射**。
|
||||
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||
8. **禁止操作**:删除项目目录/源码、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||
|
||||
---
|
||||
|
||||
# 场景一:部署 Python 项目
|
||||
|
||||
## Step 0 —— 预检
|
||||
1. 确认任务确为"部署新 Python 项目"(非排错/运维)。
|
||||
2. 确定**运行方式 `stype`**:`uwsgi` / `gunicorn` / `command`(直跑,python 文件方式已并入 command)。
|
||||
3. 确认**协议**:`wsgi`(Flask/Django 传统)/ `asgi`(FastAPI/Sanic/uvicorn)。
|
||||
4. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||
|
||||
## Step 1 —— 定位项目目录
|
||||
- 用户给出 `project_path`(项目根,含 `*.py`),或:
|
||||
- 用文件工具 `Glob(pattern='**/*.py')` / `LS(path=...)` 定位(排除 `node_modules`、`dist`、`.venv`、`venv` 等)。
|
||||
- **校验**:目录存在、含入口 `*.py`(或 `requirements.txt`)、非敏感目录(`/etc`、`/boot`、插件 `data/` 等)。
|
||||
|
||||
## Step 2 —— 分析项目(部署前必须)
|
||||
调用 `PythonProjectCreate(project_path=..., analyze_only=true)`(只读,不创建)。返回:
|
||||
1. `framework`:django/flask/sanic/fastapi 等(按 requirement/入口代码识别)。
|
||||
2. `runfile`:入口文件、`xsgi`(wsgi/asgi)、`call_app`(可调用对象名)。
|
||||
3. `requirement_path`:requirements 文件(缺 → 需先补)。
|
||||
4. `has_venv` / `port` / `port_hints`:目录是否自带 venv、启发式端口(仅供参考)。
|
||||
|
||||
**决策**:
|
||||
- 选 `stype`:Django/Flask 传统 → `gunicorn`(或 `uwsgi`);FastAPI/Sanic → `gunicorn` + `xsgi='asgi'`;无框架/自写 socket → `command`(`project_cmd='{python_bin} -u {runfile} {parm}'`)。
|
||||
- 确认 `rfile`(启动文件绝对路径)与 `call_app`(app/application,或自动探测)。
|
||||
- 无端口或启发式不准 → 询问用户,创建时显式传 `port`(uwsgi/gunicorn 必填;command 可空)。
|
||||
|
||||
## Step 3 —— Python 版本确认 / 虚拟环境准备
|
||||
1. `PythonVersion(action='list')` 查看已装 Python 版本与当前默认;返回含 `install_hint`。
|
||||
2. 需要新版本时 `PythonVersion(action='online', ...)` 浏览可安装版本(每项含 `install_command`),**用 Bash 后台安装**:
|
||||
- `Bash(command=<install_command>, run_in_background=true)` → 得到 `task_id`;
|
||||
- `BashStatus(task_id, wait=true)` 轮询到完成(后台最长 30 分钟,超时强杀;若超时汇报并让用户决定重跑/换源)。
|
||||
3. `PythonEnv(action='list')` 查看虚拟环境:找 `can_use_directly=true` 的 venv;若需新建,看每项 `source` 与顶层 `source_priority` 判断源优先级。
|
||||
4. 没有可用 venv → `PythonEnv(action='create', venv_name=<项目名或自定义>, python_bin=<源环境bin>, ps=<备注>)` 创建,得到 `python_bin`(venv_path + python_bin)。创建较慢(venv + ensurepip),**创建成功返回后必须再跑一次 `PythonEnv(action='list')` 确认该 venv 出现在列表里且目录真实存在**——工具已规避面板 `create_venv_sync` 的"只写记录不建目录"假成功缺陷并做磁盘校验,但仍建议复核。
|
||||
**源 python_bin 选择优先级(重要)**:① 面板安装的 Python 版本(`source=panel_installed`,如 `/www/server/pyporject_evn/versions/<ver>/bin/python`,**推荐**)→ ② 系统 Python(`source=system`,如 `/usr/bin/python3`,需有 venv/pip,缺则自动安装可能失败)→ ③ 面板自带 pyenv(`source=panel_pyenv`,`/www/server/panel/pyenv`——打包时移除过大量非必要文件,**不适合普通用户**,工具会直接拒绝)。优先用 `PythonVersion` 装好版本再作源。
|
||||
|
||||
## Step 4 —— 创建项目(注册)
|
||||
调用 `PythonProjectCreate(project_name=..., project_path=..., python_bin=<第3步的venv>, stype=..., ...)`。
|
||||
按类型传参:
|
||||
- **uwsgi**:`rfile` + `call_app` + `port`(+ `processes`/`threads`)。
|
||||
- **gunicorn**:`rfile` + `call_app` + `port`;FastAPI/Sanic 加 `xsgi='asgi'`。
|
||||
- **command**:`project_cmd`(如 `'{python_bin} -u {runfile}'`,**占位符由工具替换为实际路径**),`port` 可留 0。
|
||||
- **通用**:`user`(默认 root)、`env_list=[{"k","v"}]`(**必须 dict 格式**,如 `[{"k":"PORT","v":"9000"}]`,字符串 "K=V" 会被 schema 拒绝)、`env_file`、`requirement_path`(有则自动装依赖)、`auto_run`、`release_firewall`(需外网访问时 true)、`initialize`(可选初始化命令)。
|
||||
创建返回 `prep_status=running`(或 complete/failure)+ `prep_log` 路径。
|
||||
|
||||
## Step 5 —— 环境准备等待 + 启动验证(强制)
|
||||
1. `PythonProjectInfo(project_name=...)` 轮询 `prep_status`:**`running` → 等待后重查**(本地 sleep 即可,不调长工具);到 `complete` 继续,到 `failure` **立即转场景二分支 A**。
|
||||
2. 核验启动:`run=true`、应用端口在 `listen` 列表。
|
||||
3. 用返回的 `log_files` 里应用日志路径,调 filesystem `Read` 看尾部无致命异常(`ImportError`/`ModuleNotFoundError`/`Address already in use`/`Error: [Errno 98]`)。
|
||||
4. 有域名映射的项目核验 `services`(关联进程)与反代。
|
||||
|
||||
- 全通过 → 按"完成汇报"收尾。
|
||||
- 任一失败 → **转场景二排错**。
|
||||
|
||||
---
|
||||
|
||||
# 场景二:环境准备 / 启动排错
|
||||
|
||||
> 适用:部署后验证失败(prep_status=failure / run=false)、或用户报"Python 项目启动失败/访问异常"。
|
||||
|
||||
## Step 0 —— 快速定位现状(只读)
|
||||
并行收集,不跳过:
|
||||
1. `PythonProjectInfo(project_name=...)`:`prep_status`、`run`、`listen`、`log_files`(区分"环境没准备好 / 进程没起来 / 起来了但访问不了")。
|
||||
2. 按症状读日志:`prep_status=failure` 读**环境准备日志**(`log_files` 里 "环境准备日志");`run=false` 读**应用日志**(`log_files` 里 stype 对应项:error.log / uwsgi.log / gunicorn_error.log)。
|
||||
3. 已知配置:stype、入口文件、虚拟环境、端口、是否已装依赖。
|
||||
|
||||
收集后按症状进分支。
|
||||
|
||||
## 分支 A —— 环境准备失败(prep_status=failure)
|
||||
- 读 `log_files` 里的"环境准备日志"(`/www/server/python_project/vhost/logs/<name>.log`)找根因:
|
||||
| 日志特征 | 根因 | 处置 |
|
||||
|---|---|---|
|
||||
| `pip ... Could not find a version that satisfies` | 依赖源/包名错 | 换 pip 源或 `PythonEnv` 手动装对应包;`PythonProjectControl(action='restart')` 重拉 |
|
||||
| `ImportError` / `ModuleNotFoundError: No module named 'x'` | 缺依赖 | `PythonEnv(action='package', python_bin=<env>, package_action='install', package_name='x')` 后重启 |
|
||||
| `configure: error` / `make: *** Error`(装托管依赖失败) | 编译缺系统库 | 汇报,需安装系统依赖库后再 `re_prep_env` 或重建 |
|
||||
| `uwsgi/gunicorn` 命令 not found | 托管依赖没装上 | 同上 |
|
||||
- 修复后 `PythonProjectControl(action='restart')`(或 `action='start'`)重新拉取,回场景一 Step 5 复检。
|
||||
|
||||
## 分支 B —— 启动失败(进程起不来 / run=false,但 prep_status=complete)
|
||||
按应用日志根因对号入座:
|
||||
| 日志特征 | 根因 | 处置 |
|
||||
|---|---|---|
|
||||
| `ModuleNotFoundError` / `ImportError: No module named 'x'` | 依赖未装 | `PythonEnv(action='package', python_bin=..., package_action='install', package_name='x')` 后重启 |
|
||||
| `Error: [Errno 98] Address already in use` | 端口被占 | `PythonProjectModify(action='config', port=新端口)` 后 `PythonProjectControl(action='restart')` |
|
||||
| `[Errno 13] Permission denied` | 目录/日志权限 | `PythonProjectModify(action='config', user=<有权限用户>)` 或修目录属主 |
|
||||
| `No module named 'app'` / `gunicorn.errors.HaltServer` | rfile/call_app 错 | `PythonProjectModify(action='config', rfile=/call_app=正确值)` |
|
||||
| `Command '('...')' returned non-zero exit status` | command 命令本身失败 | 检查 `project_cmd` 与环境变量 |
|
||||
| `django.core.exceptions.ImproperlyConfigured` | Django settings 问题 | 检查 env_list 里的 DJANGO_SETTINGS_MODULE 等 |
|
||||
| 进程起来但 pid 无/端口没监听 | 启动后立即退出 | 读日志尾找 `Traceback` 根因 |
|
||||
|
||||
- 无明确报错 → 查 `PythonProjectInfo`:run、listen、启动脚本(`project_config`)是否完整。
|
||||
- 修复后回场景一 Step 5 重新验证。
|
||||
|
||||
## 分支 C —— 访问异常(502/无法访问,但进程活着)
|
||||
1. `PythonProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 B。
|
||||
2. **映射/反代核对**:
|
||||
- 域名是否绑定、`bind_extranet` 是否开启(未开启 → `PythonProjectModify(action='add_domain', domains=[...])` + `action='bind_extranet'`)。
|
||||
- `listen`(实际监听端口)vs `project_config.port`(反代目标)是否一致;grep `proxy_pass` `python_<name>.conf`(`/www/server/panel/vhost/nginx/python_<name>.conf`)确认反代指向 `127.0.0.1:{实际端口}`。
|
||||
- path→port 反代缺失/指错 → `PythonProjectModify(action='add_proxy', proxy_path='/', proxy_port=实际端口)`(**需已开启外网映射**)。
|
||||
3. 读 nginx error log(`/www/wwwlogs/<name>.error.log`)进一步定位。
|
||||
4. 修正后验证。
|
||||
|
||||
## 分支 D —— 关联进程异常(celery worker 等)
|
||||
1. `PythonProjectService(project_name=..., action='list')` 看各服务 pid/ports(主服务 sid='main' 之外为关联进程)。
|
||||
2. 某服务异常 → `action='log'`(`sid=...`)读服务日志;`action='start'/'stop'/'restart'`(`sid=...`)重拉。
|
||||
3. 缺 celery → `PythonEnv(action='package', python_bin=..., package_action='install', package_name='celery')`。
|
||||
4. 修正后 `action='list'` 复检 pid 存在。
|
||||
|
||||
## 分支 E —— 依赖问题(环境内包管理)
|
||||
- `PythonEnv(action='package', python_bin=<虚拟环境>, package_action='list')` 看已装包。
|
||||
- `package_action='install'`(`package_name` + 可选 `package_version` + 可选 `pip_source`)/ `package_action='uninstall'`(`package_name`)。安装慢,返回 `log_tail`。
|
||||
- 修完回场景一 Step 5 验证。
|
||||
|
||||
---
|
||||
|
||||
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||
|
||||
| 需求 | 工具 |
|
||||
|---|---|
|
||||
| 查看项目列表/状态 | `PythonProjectInfo()`(project_name 留空) |
|
||||
| 查看单项目详情(prep_status/run/listen/日志路径/服务) | `PythonProjectInfo(project_name=...)` |
|
||||
| 启动 / 停止 / 重启(含关联进程) | `PythonProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||
| 只启动 / 只停止主服务 | `PythonProjectControl(project_name, action='start_main'/'stop_main')` |
|
||||
| 看应用 / 环境准备 / 服务日志 | `PythonProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||
| 改端口/启动方式/入口/用户/环境变量/日志路径 | `PythonProjectModify(action='config', ...)`(重启生效) |
|
||||
| 加 / 删域名、开 / 关外网映射、path→port 反代 | `PythonProjectModify(action='add_domain'/'remove_domain'/'bind_extranet'/'unbind_extranet'/'add_proxy', ...)` |
|
||||
| Python 版本检测 / 在线浏览 / 移除 | `PythonVersion(action='list'/'online'/'remove', ...)` |
|
||||
| **安装 Python 版本(编译慢,后台)** | `PythonVersion` online 取 `install_command` → `Bash(run_in_background=true)` + `BashStatus` 轮询 |
|
||||
| 虚拟环境列表 / 创建 / 移除 / 设默认 | `PythonEnv(action='list'/'create'/'remove'/'set_default', ...)` |
|
||||
| 环境内 pip 装 / 卸 / 列表 | `PythonEnv(action='package', python_bin=<env>, package_action='install'/'uninstall'/'list', ...)` |
|
||||
| 关联进程列表 / 启停 / 日志 / **删除(先停再删)** | `PythonProjectService(project_name, action='list'/'start'/'stop'/'restart'/'log'/'remove', sid=...)` |
|
||||
| 删除项目(**高风险,先确认**;保留虚拟环境,需删除用 `PythonEnv(action='remove')`) | `PythonProjectDelete(project_name=...)`(保留目录源码) |
|
||||
|
||||
> ⚠️ **remove_domain 注意**:面板移除域名会连带停止项目服务(主服务+协同服务,与是否剩最后一个域名无关,已实证、根因待定位)。工具**不自动恢复**(避免掩盖根因):移除后必须用 `PythonProjectInfo` 复核运行态,被停则手动 `PythonProjectControl(action='start')` 拉起。
|
||||
> **add_domain 注意**:对已存在的域名面板返回"已存在"=实际已绑定/可访问,工具按逐域结果如实上报(非失败);只有格式错误等才报错。
|
||||
|
||||
---
|
||||
|
||||
# 完成汇报模板(部署成功)
|
||||
|
||||
返回:项目名 / 运行方式(stype)/ 目录 / 虚拟环境 python_bin / 运行用户 / 监听端口;若绑域名:访问地址 + nginx 配置路径;环境准备状态(prep_status=complete)与启动验证结果(进程/端口/日志);关联进程清单;遗留隐患提示(依赖未装、requirements 缺失、env 未注入、端口启发不准等)。
|
||||
@@ -0,0 +1,176 @@
|
||||
---
|
||||
name: BT-Reverse-Proxy
|
||||
description: >
|
||||
在宝塔面板上管理反向代理项目:创建反代站点(域名 + 目标上游)、查看/增删改 URL 级转发规则、
|
||||
自由编辑 nginx 反代配置、改备注/启停/绑删域名/强制 HTTPS,并在反代访问异常(502/404/转发不生效)时排错。
|
||||
当用户要求把某个域名/路径转发到后端服务(HTTP/HTTPS 或 unix socket),或反代站点访问异常需要排查时使用。
|
||||
触发关键词:反向代理、反代、代理转发、proxy_pass、location 转发、域名转发到端口、nginx 反代配置、
|
||||
反代 502、反代 404、转发不生效、BT-Reverse-Proxy。
|
||||
日常的查看/启停/改备注等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||
---
|
||||
|
||||
# 反向代理项目运维 SOP
|
||||
|
||||
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||
> 本 SOP 覆盖三个主场景:**① 创建反代项目;② 编辑/增删 URL 转发规则(自由配置);③ 反代访问异常排错**。其他简单操作(状态查看、启停、改备注、绑删域名、强制 HTTPS、删除)不做 SOP,直接使用工具。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先只读侦察,再执行变更** —— 操作前先 `ProxyProjectInfo`(site_name 留空)列项目找到站点名(可能带 `_<端口>` 后缀),再 `ProxyProjectInfo(site_name=...)` 看当前规则/域名/端口/SSL;排错先读日志,不盲目重写配置。
|
||||
2. **反代项目 = sites 行 + 反代 JSON** —— 真正的配置在 `/www/server/proxy_project/sites/<name>/<name>.json`(`proxy_info[]` 多条 URL 规则);nginx conf 由它渲染。**改配置必须走 MCP 工具**(ProxyWriteConfig),保持 JSON 与 nginx 同步。
|
||||
3. **URL 规则增删改走自由配置** —— 不要期待 add/set/del_url_proxy 之类的工具(未提供)。改规则 = 读 conf → 改 location 块 → `ProxyWriteConfig` 回传完整 conf → `Bash` `nginx -t` 验证。**面板保存后会自动把 proxy_info/域名/端口同步回反代 JSON。**
|
||||
4. **改配置三步走**:`ProxyProjectInfo` 拿 `config_file` 路径 → filesystem `Read` 读当前 conf 作基线 → 修改后 `ProxyWriteConfig(conf_data=<完整 conf>)` → `Bash` 执行 `nginx -t` 验证。**改前必须 Read 留基线**,写坏可恢复。
|
||||
5. **域名增删走 `ProxyProjectModify`** —— 用 comMod 的方法(会同步反代 JSON);**不要用通用网站域名工具**(不更新反代 JSON,面板会不同步)。至少保留一个域名。
|
||||
6. **创建即生效** —— `ProxyProjectCreate` 成功即写 nginx + 放行防火墙 + 重载服务;返回的 `site_name_hint` 是主域名小写形式,**实际站点名以 `ProxyProjectInfo` 列表返回的 name 为准**(非 80 端口会带 `_<端口>`)。
|
||||
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||
8. **禁止操作**:`rm -rf` 反代站点根目录外的路径、修改宝塔/插件自身文件、读取插件 `data/` 凭据、直接用 filesystem Write 覆盖反代 nginx conf(必须走 ProxyWriteConfig 保持 JSON 同步)。
|
||||
9. **反代目标勿指向 bt_agent_mcp 自身端口**(`127.0.0.1:<MCP端口>`,默认 8765)——会把 MCP 服务暴露给该反代域名,且反代 conf 未设 `X-Real-IP` 时来源 IP 白名单会被绕过(仅剩 API Key 鉴权兜底)。**若工具返回 `data.warning` 说明代理目标指向 MCP 自身,须与用户确认意图**;确需经反代暴露 MCP,则在该 location 补 `proxy_set_header X-Real-IP $remote_addr;` 并把真实客户端 IP 加入白名单(`security.ip_allowlist`)。
|
||||
|
||||
---
|
||||
|
||||
# 场景一:创建反代项目
|
||||
|
||||
## Step 0 —— 预检
|
||||
1. 确认任务确为"创建反向代理项目"。
|
||||
2. 拿到**要对外暴露的域名**(可带 `:端口`,非 80 端口会成为监听端口)与**目标上游**(http/https URL 或 unix socket 路径)。
|
||||
3. 确认 Nginx 已安装(反代只支持 nginx)。
|
||||
|
||||
## Step 1 —— 调用创建
|
||||
`ProxyProjectCreate(domains=[...], proxy_pass=...)`:
|
||||
- **必填**:`domains`(list,`'example.com'` 或 `'example.com:8080'`)、`proxy_pass`(`http://127.0.0.1:8080`、`https://api.example.com`,或 unix 时 `/tmp/app.sock`)。
|
||||
- **可选**:`proxy_path`(默认 `/`,前缀)、`proxy_host`(默认 `$http_host`,转发 Host)、`proxy_type`(http/unix,默认 http)、`remark`。
|
||||
|
||||
> 返回"添加成功"= 已写 nginx conf + 放行端口 + 重载。`site_name_hint` 仅供参考。
|
||||
|
||||
## Step 2 —— 验证(强制)
|
||||
1. `ProxyProjectInfo`(site_name 留空)确认站点出现,记下真实 `name`。
|
||||
2. `ProxyProjectInfo(site_name=...)` 看 `config`(域名/端口/首条 proxy_info 的 proxy_pass 是否对上)。
|
||||
3. 需要的话 filesystem `Read` conf 确认 `location { proxy_pass ... }` 已渲染。
|
||||
|
||||
- 全通过 → 按"完成汇报"收尾。
|
||||
- 配置与预期不符 → 转场景二修正配置,或转场景三排错。
|
||||
|
||||
---
|
||||
|
||||
# 场景二:编辑 / 增删 URL 转发规则(自由配置)
|
||||
|
||||
## Step 0 —— 拿基线与现状
|
||||
1. `ProxyProjectInfo(site_name=...)`:拿到 `config_file` 路径(`/www/server/panel/vhost/nginx/<name>.conf`)、当前 `proxy_info`(每条 proxy_path/proxy_pass/proxy_host/websocket/超时)、域名与端口。
|
||||
2. filesystem `Read` `config_file` 读当前完整 conf。
|
||||
|
||||
## Step 1 —— 修改 conf
|
||||
按「常用 nginx 反代配置速查」(见文末)在 conf 里**增/删/改 location 块**(或 server/http 层配置)。常见操作:
|
||||
- **加一条转发规则**:新增 `location /api { proxy_pass http://127.0.0.1:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }`。
|
||||
- **改目标**:改对应 `location` 里的 `proxy_pass`(换后端端口/地址)。
|
||||
- **删规则**:删掉对应 `location` 块。
|
||||
- **改超时**:在 location 内加 `proxy_connect_timeout 60s; proxy_read_timeout 600s; proxy_send_timeout 600s;`。
|
||||
- **开 WebSocket**:加 `proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";`(反代 JSON 的 websocket 默认支持)。
|
||||
- **强制 HTTPS**:优先用 `ProxyProjectModify(action='force_https', force_https=true)`,不要手改 ssl 块。
|
||||
|
||||
> 注意:**location 的 proxy_pass 末尾不带 `;` 前不可跟变量**(`proxy_pass http://127.0.0.1:9000;` 可直接跟 URI 或不带 URI;用变量时必须 `resolver`)。简单场景直接写死目标即可。
|
||||
|
||||
## Step 2 —— 回传并验证
|
||||
1. `ProxyWriteConfig(site_name=..., conf_data=<修改后的完整 conf>)` → 面板写 conf 并自动同步反代 JSON。
|
||||
2. `Bash` 执行 `nginx -t` 确认配置语法通过;失败按报错行修 conf 重存。
|
||||
3. `ProxyProjectInfo` 复查 `proxy_info` 已同步新规则。
|
||||
4. 访问验证(如有域名):确认新规则生效、旧规则仍在。
|
||||
|
||||
- 配置写坏导致站点异常 → 用 Read 留的基线恢复后 `ProxyWriteConfig` 重存,或面板历史版本回滚。
|
||||
|
||||
---
|
||||
|
||||
# 场景三:反代访问异常排错
|
||||
|
||||
## Step 0 —— 只读侦察(不盲改)
|
||||
1. `ProxyProjectInfo` 确认项目存在、域名/端口/规则现状。
|
||||
2. filesystem `Read` nginx 错误日志 `/www/wwwlogs/<name>.error.log` 与访问日志 `/www/wwwlogs/<name>.log`;必要时 `ProxyWriteConfig` 不变,仅 Read conf 检查 proxy_pass/upstream。
|
||||
|
||||
## Step 1 —— 按症状对号入座
|
||||
|
||||
| 症状 | 常见根因 | 处置 |
|
||||
|---|---|---|
|
||||
| **502 Bad Gateway** | 后端未启动/端口错、proxy_pass 写错、unix socket 不存在、超时太短 | 确认后端进程在监听(`Bash` `ss -tlnp \| grep <port>`);核对 `ProxyProjectInfo` 的 proxy_pass 与真实后端;unix 路径检查文件存在;长请求调大 `proxy_read_timeout` |
|
||||
| **404** | proxy_path 前缀与后端路由不匹配、location 前缀未命中、误写 `try_files` | 核对 location 的 `proxy_pass` 是否带 URI 前缀;检查 conf 是否有多余 location 拦截 |
|
||||
| **转发不生效 / 仍是静态页** | conf 没保存成功、location 与现有规则冲突、缓存 | `nginx -t` + `ProxyProjectInfo` 看 JSON 是否同步;必要时 `Bash` `nginx -s reload` 后重试;缓存类规则先关 `proxy_cache` |
|
||||
| **只对本机/内网生效** | 域名未绑定外网、防火墙未放行端口 | `ProxyProjectModify(action='add_domain')` 补域名;`Bash` 查防火墙端口放行状态 |
|
||||
| **HTTPS 不强制 / 证书异常** | SSL 未部署、force_https 未开 | `ProxyProjectModify(action='force_https', force_https=true)`;证书部署走面板 |
|
||||
|
||||
## Step 2 —— 修复与验证
|
||||
1. 按上表定位根因,**改 conf 必须走 ProxyWriteConfig + `nginx -t`**,改域名走 `ProxyProjectModify`。
|
||||
2. 修复后重访验证;仍异常则回到 Step 0 换角度(读实时日志尾部 `tail`)。
|
||||
|
||||
---
|
||||
|
||||
# 运维速查
|
||||
|
||||
| 需求 | 调用 |
|
||||
|---|---|
|
||||
| 列表/找站点名 | `ProxyProjectInfo(search=..., page=...)`(site_name 留空) |
|
||||
| 查看详情/规则/conf 路径 | `ProxyProjectInfo(site_name=...)` |
|
||||
| 创建反代 | `ProxyProjectCreate(domains=[...], proxy_pass=...)` |
|
||||
| 读/改 nginx conf | filesystem `Read` + `ProxyWriteConfig(site_name=..., conf_data=...)` |
|
||||
| 验证语法 | `Bash` `nginx -t` |
|
||||
| 改备注 / 启停 / 绑删域名 / 强制 HTTPS | `ProxyProjectModify(site_name=..., action=..., ...)` |
|
||||
| 删除项目 | `ProxyProjectDelete(site_name=..., remove_path=false)`(高风险,确认后) |
|
||||
|
||||
---
|
||||
|
||||
# 常用 nginx 反代配置格式与位置速查
|
||||
|
||||
**位置**:反代项目的 nginx conf(`/www/server/panel/vhost/nginx/<name>.conf`)是完整 server 块。三块区域:
|
||||
- **http 层**(`server {` 之前):upstream 定义、`proxy_cache_path`。
|
||||
- **server 层**(`server { ... }` 内、location 外):`listen`、`server_name`、ssl 证书、`proxy_set_header`、`client_max_body_size`。
|
||||
- **location 层**:每一条 `location <path> { ... }` 是一条 URL 转发规则,对应反代 JSON 的 `proxy_info[]`。
|
||||
|
||||
**典型片段**:
|
||||
|
||||
```nginx
|
||||
# location 转发(最常用):/ 全站转发
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
# 按路径前缀转发:/api 到另一后端
|
||||
location /api {
|
||||
proxy_pass http://127.0.0.1:9000;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# 带自定义超时 + WebSocket
|
||||
location /ws {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
}
|
||||
|
||||
# server 层常用:限制上传大小、传递真实协议
|
||||
client_max_body_size 50m;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- `proxy_pass` 后**直接写死目标**(`http://IP:端口` 或 `https://域名`)最简单;若需在 URL 中带变量,必须配 `resolver`(一般不需要)。
|
||||
- **勿把 `proxy_pass` 指向本机 bt_agent_mcp 自身端口**(默认 8765);若工具返回 `data.warning` 提示目标指向 MCP 自身,先与用户确认,确需暴露则在 location 补 `proxy_set_header X-Real-IP $remote_addr;` 并把真实客户端 IP 加入白名单。
|
||||
- 改完**必须** `nginx -t` 验证,再确认访问生效。
|
||||
- 涉及 SSL/强制 HTTPS 用 `ProxyProjectModify(action='force_https')`,别手改 ssl 块。
|
||||
|
||||
---
|
||||
|
||||
# 完成汇报模板
|
||||
|
||||
汇报固定四段(每段 1-3 行,用一次工具查证一个结论,不堆 log):
|
||||
|
||||
- **现状**:反代项目 `<name>`,域名 `<域名:端口>`,转发目标 `<proxy_pass>`,状态(运行中/已停止)。
|
||||
- **变更**:`<创建了反代项目 / 新增了 /api 转发规则 / 修改了 proxy_pass / 启停了项目 / 设置了强制 HTTPS>`。
|
||||
- **验证**:`nginx -t` 通过 / `ProxyProjectInfo` 复查 proxy_info 已同步 / 访问 `<域名>` 返回预期。
|
||||
- **遗留**:`<若有:SSL 证书未部署需面板处理 / 后端服务未监听需确认>;否则无`。
|
||||
@@ -0,0 +1,257 @@
|
||||
---
|
||||
name: BT-Website-Troubleshoot
|
||||
description: >
|
||||
诊断并修复 bt panel 网站访问异常和服务启动失败问题。
|
||||
当用户报告以下问题时使用此技能:网站无法打开、403/404/500/502/503 错误、
|
||||
空白页/白屏、数据库连接错误、nginx 或 php-fpm 启动失败、
|
||||
服务启动失败但没有明确原因,或任何网站宕机/访问被拒绝问题。
|
||||
触发关键词:网站宕机、网站打不开、网站无法访问、502、
|
||||
500、403、404、空白页、白屏、nginx 错误、php-fpm 错误、启动失败、
|
||||
数据库连接失败、连接被拒绝、连接数过多、访问被拒绝、
|
||||
网站不可达、服务不可用、错误网关、网站异常。
|
||||
---
|
||||
|
||||
# bt panel 网站故障排查
|
||||
|
||||
> **停止。在执行任何操作前,必须完整阅读本文档。**
|
||||
> **第一个动作:若当前环境有 todo 工具(`TodoWrite`),先用它创建诊断任务列表**;没有则直接进入诊断。
|
||||
> 不要跳过任何章节。按顺序执行决策树。
|
||||
> 永远不要向用户展示原始命令、btpython 路径或代码块 —— 仅使用自然语言报告。
|
||||
|
||||
---
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **始终先执行预检查** —— 永远不要跳过 `curl --resolve` 本地回环验证。
|
||||
2. **修复前先读取** —— 在执行任何修复操作前,先诊断根因。
|
||||
3. **每个任务最多调用 15 次工具** —— 超出后,汇总当前发现并停止。
|
||||
4. **绝不让用户手动输入命令** —— 始终通过 `RunCommand/Bash` 执行。
|
||||
5. **修复过程中发生错误时** —— 向用户报告,不要自动重试。
|
||||
6. **服务报告“启动失败”时,始终检查原始服务日志** —— 面板提示通常过于模糊,无法直接采取行动。
|
||||
7. **禁止操作**:删除网站、删除数据库、删除文件、`rm -rf`、`DROP TABLE/DATABASE`。
|
||||
8. **任务跟踪(可选)** —— 若当前环境提供 todo 工具(`TodoWrite`/`TodoRead`),用它跟踪诊断:开始 Step 0 前建任务列表,保持单任务 `in_progress`,完成后标 `completed`,被中断用 `TodoRead` 恢复。没有 todo 工具则跳过,直接按决策树推进。
|
||||
9. **工具名双写(两个部署环境)** —— 同一个能力在内置宝塔 AI 端和插件对外接口里名字不同:执行命令是 `RunCommand` / `Bash`,精确编辑是 `SearchReplace` / `Edit`。本文档统一写成 `RunCommand/Bash`、`SearchReplace/Edit`,你按当前手头可用的那个调用即可。
|
||||
|
||||
---
|
||||
|
||||
## Step 0 —— 预检查(强制)
|
||||
|
||||
在任何诊断前,确认网站确实属于当前服务器,并且请求能够到达该服务器。
|
||||
|
||||
1. **创建任务列表(若可用)**:若当前有 `TodoWrite` 工具,先列出本次案例的步骤(预检查 → 探测 → 状态码分支 → 修复);没有则跳过本步,直接进入第 2 步。
|
||||
2. **执行**:`RunCommand/Bash: curl --resolve <domain>:80:127.0.0.1 -sS -o /dev/null -w '%{http_code}\\n' http://<domain>/`
|
||||
- 返回实际到达面板 nginx 的 HTTP 状态码。
|
||||
3. **列出网站**:`SiteList()` → 找到匹配的 `name`(域名,作为 `site_name` 传给 `SiteGetConfig`)、`path`、`project_type`。
|
||||
4. **如果网站不在当前面板上**(`curl` 返回连接错误或返回了其他网站):告知用户该域名可能并未托管在此处,不要继续。
|
||||
|
||||
> 仅当用户明确确认网站位于当前服务器,或直接提供了 `site_name`(域名)时,才可跳过预检查。
|
||||
|
||||
---
|
||||
|
||||
## Step 1 —— 双探针
|
||||
|
||||
这些探针是只读验证,不产生持久副作用。创建、测试,并在完成后**删除**。
|
||||
|
||||
### 探针 A —— 静态文件(验证域名绑定 + nginx + 根目录)
|
||||
|
||||
1. `RunCommand/Bash: echo 'bt Panel probe $(date)' > <site_path>/.probe_static.html`
|
||||
2. `RunCommand/Bash: chown www:www <site_path>/.probe_static.html && chmod 644 <site_path>/.probe_static.html`
|
||||
3. `RunCommand/Bash: curl --resolve <domain>:80:127.0.0.1 -sS http://<domain>/.probe_static.html`
|
||||
4. **预期结果**:返回探针文本,HTTP 状态码为 200。
|
||||
5. 清理:`RunCommand/Bash: rm -f <site_path>/.probe_static.html`
|
||||
|
||||
### 探针 B —— PHP 文件(验证 PHP 运行时 + php-fpm socket)
|
||||
|
||||
1. `RunCommand/Bash: echo '<?php echo "bt Panel PHP probe ".PHP_VERSION; ?>' > <site_path>/.probe_php.php`
|
||||
2. `RunCommand/Bash: chown www:www <site_path>/.probe_php.php && chmod 644 <site_path>/.probe_php.php`
|
||||
3. `RunCommand/Bash: curl --resolve <domain>:80:127.0.0.1 -sS http://<domain>/.probe_php.php`
|
||||
4. **预期结果**:返回包含 PHP 版本字符串的探针文本。
|
||||
5. 清理:`RunCommand/Bash: rm -f <site_path>/.probe_php.php`
|
||||
|
||||
> 从 `SiteList` 返回的匹配项 `path` 字段获取 `site_path`。`SiteGetConfig(site_name)` 返回的是**原始虚拟主机配置文本**(不是结构化字段)—— 阅读文本中的 `root`、`access_log` 和 `include enable-php-<ver>.conf;` 指令,以验证根目录。
|
||||
|
||||
---
|
||||
|
||||
## Step 2 —— 状态码决策树
|
||||
|
||||
### 403 Forbidden —— 权限 / 所有权
|
||||
|
||||
**目标**:确认 `www` 拥有网站目录树,目录权限为 755、文件权限为 644,并且父目录可读。
|
||||
|
||||
1. `SiteGetConfig(site_name)` → 获取 `root` 目录。
|
||||
2. `RunCommand/Bash: ls -la <root>/` 和 `RunCommand/Bash: ls -la <parent_of_root>/`(父目录同样重要)。
|
||||
3. 检查:
|
||||
- root 及所有父目录的所有者/用户组 = `www:www`
|
||||
- 目录权限 = `755`
|
||||
- 文件权限 = `644`
|
||||
4. 如果任一项不正确(自动修复,低风险):
|
||||
- `RunCommand/Bash: chown -R www:www <root>`
|
||||
- `RunCommand/Bash: find <root> -type d -exec chmod 755 {} \;`
|
||||
- `RunCommand/Bash: find <root> -type f -exec chmod 644 {} \;`
|
||||
5. 使用预检查 curl 重新测试。如果仍然返回 403,检查 nginx 错误日志:
|
||||
- `Read: /www/wwwlogs/<domain>.error.log`(最后 50 行,查找 `directory index of "..." is forbidden` 或 `access denied`)。
|
||||
|
||||
### 404 Not Found —— 路径 / Rewrite
|
||||
|
||||
**先分类**:缺失的 URL 应该由动态路由(PHP 路由/框架路由)提供,还是由静态文件提供?
|
||||
|
||||
- **静态 404**(例如 `/favicon.ico`、`/uploads/foo.jpg`):
|
||||
1. `SiteGetConfig(site_name)` → 检查 `root` 和 `access_log` 的位置。
|
||||
2. `RunCommand/Bash: ls -la <root>/<expected_path>` → 文件是否缺失?root 是否错误?
|
||||
3. 确认虚拟主机配置中的 `root` 指令与 `SiteList` 返回的实际 `site_path` 一致。
|
||||
|
||||
- **动态 404**(例如 `/category/news/`、`/article/123`、`/admin/login`):
|
||||
1. `SiteGetConfig(site_name)` → 查找 `include .../rewrite/<domain>.conf;` 行。
|
||||
2. `Read: /www/server/panel/vhost/rewrite/<domain>.conf`(如果存在)。
|
||||
3. **常见原因**:框架(WordPress / ThinkPHP / Laravel / Typecho 等)的 rewrite 规则缺失或错误。
|
||||
4. 修复(高风险 —— 需要面板确认):根据框架标准规则使用 `SearchReplace/Edit` 编辑 rewrite 文件,然后执行 `RunCommand/Bash: nginx -t && nginx -s reload`。
|
||||
|
||||
### 500 Internal Server Error —— 三个分支
|
||||
|
||||
运行预检查 curl,确认返回 500。然后依次检查各分支:
|
||||
|
||||
#### 分支 A —— 数据库
|
||||
|
||||
1. 读取 `SiteGetConfig` 找到项目根目录,然后查找框架数据库配置:
|
||||
- WordPress:`Read: <root>/wp-config.php` → 提取 `DB_NAME`、`DB_USER`、`DB_PASSWORD`、`DB_HOST`。
|
||||
- 其他框架:查找 `.env`、`config/database.php`、`application/database.php` 等。
|
||||
2. `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> <DB_NAME> -e "SELECT VERSION()"` → 连接成功时返回 MySQL 版本号(即连接测试通过);失败则按下一步读错误码。
|
||||
3. 如果连接失败,从 `mysql` 客户端的原始错误输出(形如 `ERROR 1045 (28000): ...`)中读取错误码,按下表判断:
|
||||
- `2002` / `2003` → MySQL 未运行。进入**服务启动失败 → MySQL**。
|
||||
- `1045` → 密码错误。比较配置中的 `DB_PASSWORD` 与 `databases` 表;如果不一致,向用户报告(不要自动重置数据库密码)。
|
||||
- `1146` → 数据表缺失。用 `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> <DB_NAME> -e "SHOW TABLES"` / `DESC <表名>` 确认(凭据取自上一步 wp-config;RunCommand/Bash 为 high,会触发确认),然后报告。
|
||||
- `1040` → 连接数过多。执行 `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> -e "SHOW GLOBAL STATUS LIKE 'Threads_connected'; SHOW FULL PROCESSLIST"`,查看连接数与连接来源;建议提高 `max_connections`(高风险)。
|
||||
|
||||
#### 分支 B —— 代码(未捕获异常)
|
||||
|
||||
1. 启用 PHP 错误显示(高风险 —— 需要确认,且仅适用于非生产环境):
|
||||
- `Read: /www/server/php/<ver>/etc/php.ini` → 检查 `display_errors` 和 `error_reporting`。
|
||||
2. `Read: /www/wwwlogs/<domain>.error.log`(最后 100 行)→ 查找 PHP `Fatal error` / `Parse error` / `Uncaught`。
|
||||
3. 向用户报告文件、行号和错误信息。不要自动修改网站代码。
|
||||
|
||||
#### 分支 C —— 配置(HTTP 200 但页面空白)
|
||||
|
||||
1. 这是典型的 **fastcgi.conf 损坏**模式:状态码为 200、响应体为空,并且网站此前正常。
|
||||
2. `Read: /www/server/nginx/conf/fastcgi.conf` → 检查文件是否被清空或被过度注释。
|
||||
3. 如果异常,向用户报告。修复需要恢复面板默认的 `fastcgi.conf`(高风险 —— 需要确认,并需要原始文件)。
|
||||
|
||||
### 502 / 503 Bad Gateway / Service Unavailable —— PHP-FPM 环境
|
||||
|
||||
1. `RunCommand/Bash: ps -ef \| grep php-fpm \| grep -v grep` → php-fpm 是否正在运行?
|
||||
2. `ServiceStatus("php-fpm-<ver>")` → 确认安装和运行状态。从 `SiteGetConfig` 中的 `include enable-php-<ver>.conf;` 行确定版本。
|
||||
3. `SiteGetConfig(site_name)` → 检查虚拟主机实际包含的 `enable-php-<ver>.conf` 是否与运行中的版本**一致**。
|
||||
4. `RunCommand/Bash: curl -sS http://127.0.0.1/phpfpm_<ver>_status` → 检查 active processes、listen queue、max children。
|
||||
- 如果 `listen queue` 非零 → 进程池已耗尽。参见**服务启动失败 → php-fpm**中的 OOM。
|
||||
5. `RunCommand/Bash: free -m` → 查看可用内存;如果少于 200MB,OOM killer 可能已终止 php-fpm。
|
||||
6. 对于**反向代理 502**:从面板主机执行 `RunCommand/Bash: curl -v <upstream_host>` → 检查上游是否可达(防火墙 / DNS / 上游宕机)。
|
||||
|
||||
---
|
||||
|
||||
## Step 3 —— 服务启动失败
|
||||
|
||||
> **核心原则**:当面板显示“启动失败”但没有有效细节时,**始终先读取原始服务日志**。面板提示通常过于模糊,无法直接采取行动。
|
||||
|
||||
### 3.1 nginx
|
||||
|
||||
```bash
|
||||
# 1. 语法检查 —— 可给出任何错误的准确文件和行号
|
||||
/www/server/nginx/sbin/nginx -t
|
||||
```
|
||||
|
||||
三种常见失败模式:
|
||||
|
||||
| 现象 | 原因 | 修复 |
|
||||
|---|---|---|
|
||||
| `unknown directive "xxx" in /www/server/panel/vhost/nginx/<site>.conf:N` | 网站虚拟主机配置中存在拼写错误或不受支持的指令 | 使用 `Read` 读取对应行,使用 `SearchReplace/Edit` 修复(高风险),然后重新执行 `nginx -t` |
|
||||
| `bind() to 0.0.0.0:80 failed` / `bind() to [::]:443 failed` | 端口被占用 | `RunCommand/Bash: netstat -tlnp \| grep -E ':80\|:443'` → 找出冲突进程,并向用户报告 |
|
||||
| `host not found in upstream "<name>"` | 启动时无法解析上游 DNS | 使用 `RunCommand/Bash: dig +short <name>` 验证;如果无法解析,向用户报告。修复:在虚拟主机中添加 `resolver` 指令,或替换为 IP(高风险) |
|
||||
|
||||
修复后,**始终**再次执行 `nginx -t`,然后执行 `RunCommand/Bash: /etc/init.d/nginx restart`(或 `ServiceRestart("nginx")`,高风险 —— 需要确认)。
|
||||
|
||||
### 3.2 php-fpm
|
||||
|
||||
从故障网站引用的 `enable-php-<ver>.conf` 中获取版本,然后执行:
|
||||
|
||||
```bash
|
||||
# 1. 查看原始 php-fpm 错误日志末尾 —— 信息最完整
|
||||
tail -n 50 /www/server/php/<ver>/var/log/php-fpm.log
|
||||
```
|
||||
|
||||
| 现象 | 原因 | 修复 |
|
||||
|---|---|---|
|
||||
| `Unable to load dynamic library '<ext>.so'` / `segfault (core dumped)` | 新安装的 PHP 扩展损坏 | 二分排查:在面板中进入应用商店 → PHP → 设置 → 扩展,逐个卸载最近新增的扩展,每次卸载后重启(`RunCommand/Bash: /etc/init.d/php-fpm-<ver> restart`) |
|
||||
| 启动后立即显示 `active (exited)` | 被 OOM killer 终止 | `RunCommand/Bash: dmesg \| grep -E "php\|oom" \| tail -20` + `RunCommand/Bash: free -m` → 降低 `/www/server/php/<ver>/etc/php-fpm.conf` 中的 `pm.max_children`(高风险) |
|
||||
| `bind() to /tmp/php-cgi-<ver>.sock failed: Address already in use` | 旧 php-fpm 进程仍在运行 | `RunCommand/Bash: pkill php-fpm && sleep 2 && /etc/init.d/php-fpm-<ver> start`(高风险) |
|
||||
| `ERROR: [/www/server/php/<ver>/etc/php-fpm.conf:N] unknown parameter` | 手动编辑导致指令损坏 | 使用 `Read` 读取对应行,修复或通过面板应用商店 → PHP → 设置 → 配置 → 重置(高风险) |
|
||||
| `Unable to access php-fpm.sock: Permission denied` | Socket 文件所有者错误 | `RunCommand/Bash: ls -la /tmp/php-cgi-<ver>.sock` → 如果不是 `www:www`,执行 `RunCommand/Bash: chown www:www /tmp/php-cgi-<ver>.sock && chown -R www:www /www/server/php/<ver>/var/log/`(低风险) |
|
||||
|
||||
---
|
||||
|
||||
## Step 4 —— 工具风险等级
|
||||
|
||||
工具由其注册的 `risk_level` 控制,而不是由命令本身的行为控制。
|
||||
|
||||
| risk_level | 工具 | 典型用途 | 处理方式 |
|
||||
|---|---|---|---|
|
||||
| **low** | `Read`、`SiteGetConfig`、`SiteLogs`、`ServiceStatus`、`TodoRead`、`TodoWrite` | 读取配置/日志、检查服务状态、跟踪任务 | 直接执行 |
|
||||
| **high** | `RunCommand/Bash`、`ServiceRestart`、`SearchReplace/Edit`、`Write` | 任何 shell 命令(包括只读的 `curl`/`ls`/`netstat`/`ps`/`mysql -e`,以及 `chown`/`chmod`)、重启服务、编辑 nginx/php 配置、写入文件、执行 SQL(读/写) | 每次调用都必须经过面板确认门禁 |
|
||||
| **forbidden** | — | 删除网站、删除数据库、删除文件、`rm -rf`、`DROP TABLE/DATABASE` | 永不执行 |
|
||||
|
||||
- `RunCommand/Bash` 作为工具的 `risk_level="high"`,因此即使是**只读探测**(`curl`、`ls`、`netstat`)也会触发确认门禁。应优先使用低风险读取工具(使用 `Read` 读取日志/配置,使用 `ServiceStatus` 检查状态),在无需确认的情况下收集事实。
|
||||
- 任何配置编辑(`SearchReplace/Edit`/`Write`)完成后,**必须**执行 `nginx -t` 验证,再进行 reload。
|
||||
|
||||
---
|
||||
|
||||
## Step 5 —— 输出格式
|
||||
|
||||
向用户报告发现时,始终使用以下形式的**自然语言**:
|
||||
|
||||
```
|
||||
根因:<用一句话说明根因>
|
||||
|
||||
已执行步骤:
|
||||
- <步骤 1>
|
||||
- <步骤 2>
|
||||
...
|
||||
|
||||
建议:
|
||||
- <预防措施或后续操作>
|
||||
```
|
||||
|
||||
规则:
|
||||
|
||||
- **绝不**在面向用户的消息中粘贴原始 shell 命令、btpython 路径或配置差异。
|
||||
- **绝不**要求用户手动输入命令 —— 如果需要修复,描述修复内容并等待用户确认。
|
||||
- 如果诊断尚不完整(例如无法复现、日志不明确),必须明确说明。不要编造根因。
|
||||
|
||||
---
|
||||
|
||||
## 快速参考 —— 常见错误码
|
||||
|
||||
这些错误由 `mysql_engine.MYSQL_ERROR_MAP` 自动映射;此处映射仅供 Agent 自身推理使用,**不要向用户原样输出错误码**。
|
||||
|
||||
| SQLSTATE / 错误码 | 友好含义 | 下一步 |
|
||||
|---|---|---|
|
||||
| `2002` / `2003` | 无法连接 MySQL socket / 端口 | 检查 `ServiceStatus("mysql")` |
|
||||
| `1045` | 数据库用户密码错误 | 比较 `wp-config.php` 与面板 `databases` 表 |
|
||||
| `1146` | 数据表不存在 | `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> <DB_NAME> -e "SHOW TABLES"` / `DESC` 确认 |
|
||||
| `1040` | 连接数过多 | `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> -e "SHOW GLOBAL STATUS LIKE 'Threads_connected'; SHOW FULL PROCESSLIST"` |
|
||||
| `1452` | 外键约束失败 | 检查被引用的数据行,并向用户报告 |
|
||||
|
||||
---
|
||||
|
||||
## 快速参考 —— 文件 / 日志路径
|
||||
|
||||
| 内容 | 路径 |
|
||||
|---|---|
|
||||
| Nginx 虚拟主机配置 | `/www/server/panel/vhost/nginx/<domain>.conf` |
|
||||
| Apache 虚拟主机配置 | `/www/server/panel/vhost/apache/<domain>.conf` |
|
||||
| Rewrite 规则 | `/www/server/panel/vhost/rewrite/<domain>.conf` |
|
||||
| Nginx 主配置 | `/www/server/nginx/conf/nginx.conf` |
|
||||
| Nginx fastcgi 配置(空白页常见原因) | `/www/server/nginx/conf/fastcgi.conf` |
|
||||
| 网站访问日志 | `/www/wwwlogs/<domain>.log` |
|
||||
| 网站错误日志 | `/www/wwwlogs/<domain>.error.log` |
|
||||
| PHP-FPM 错误日志 | `/www/server/php/<ver>/var/log/php-fpm.log` |
|
||||
| PHP-FPM socket | `/tmp/php-cgi-<ver>.sock` |
|
||||
| PHP-FPM 进程池配置 | `/www/server/php/<ver>/etc/php-fpm.conf` |
|
||||
| WordPress 数据库配置 | `<site_root>/wp-config.php` |
|
||||
@@ -40,5 +40,5 @@ AI 智能体开发约束 & 项目执行规范
|
||||
- 发版统一走 agent CLI(在 desktop/ 目录下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli,中心机本机 + 管理密钥,即控制面 /api/admin/pkg 与 shell 源):
|
||||
- 壳子发版:改 desktop/webhost/tools/shell.version 与 install.iss 的 MyAppVersion → desktop/webhost/frontend 执行 npm run build → PyInstaller 依次打 desktop/webhost/tools/37du-host.spec、37du-host-runner.spec、37du-host-console.spec → ISCC.exe desktop/webhost/tools/install.iss 出安装包;然后 agent_cli shell-release <安装包> --version <新版本> [--notes "说明"]。
|
||||
- 插件发版:根级 plugins/<id>/ 目录打成 zip(根目录含 plugin.json)后 agent_cli publish <插件.zip> --id <id> --version <v>;权限用 agent_cli grant / revoke 管理。
|
||||
- 中心机发版:改过 controlplane 后端后 PyInstaller desktop/controlplane/tools/37du-center.spec --distpath desktop/controlplane/dist-exe --workpath desktop/controlplane/build-exe --noconfirm。
|
||||
- 中心机发版:控制面为源码部署(宝塔 gunicorn 8800,不打包 exe)。改后端代码后按 .trae/documents/控制面前后端部署SOP.md「后端部署流程」上传文件 + 重启项目;改前端后按同一文档「前端部署流程」构建并发布到静态站 8090。
|
||||
- 发布后:执行机下次启动自动检测下载、前端提示后点击升级;插件登录后按权限自动下载更新。
|
||||
@@ -21,7 +21,7 @@ Process-Automation/
|
||||
│ │ ├── app.py # FastAPI 服务入口(在 desktop/ 下 python -m controlplane.app)
|
||||
│ │ ├── core/ # 配置、存储、鉴权
|
||||
│ │ ├── apis/ # REST 接口
|
||||
│ │ ├── tools/ # agent_cli 发布 CLI、PyInstaller spec、前端
|
||||
│ │ ├── tools/ # agent_cli 发布 CLI、运维脚本
|
||||
│ │ └── frontend/ # 中心机管理前端
|
||||
│ └── webhost/ # 执行机:本地服务 + 前端工作台 + 插件运行底座
|
||||
│ ├── launch.py # 启动器(uvicorn + PyWebView 窗口)
|
||||
|
||||
@@ -38,12 +38,12 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
"FROM accounts ORDER BY id")]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
a["grants"] = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
|
||||
"SELECT plugin_id, can_download, can_run FROM account_plugins WHERE account = %s",
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@@ -57,13 +57,13 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if exists:
|
||||
raise HTTPException(400, f"账号 {account} 已存在")
|
||||
_hex, _salt = _hash_password(a.password)
|
||||
with _db() as conn:
|
||||
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||
"created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
"created_at) VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||||
(a.nickname or "").strip(), _now()))
|
||||
conn.commit()
|
||||
@@ -81,26 +81,26 @@ def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
if a.dept is not None:
|
||||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET dept = %s WHERE account = %s",
|
||||
((a.dept or "").strip(), account))
|
||||
if a.nickname is not None:
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||||
((a.nickname or "").strip(), account))
|
||||
if a.is_admin is not None:
|
||||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||||
if a.is_admin:
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = %s", (account,))
|
||||
else:
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = %s AND account <> %s",
|
||||
(account, login))
|
||||
if a.status is not None:
|
||||
# 禁止停用自己,避免把自己锁在门外
|
||||
if not a.status and account == login:
|
||||
raise HTTPException(400, "不能停用当前登录的账号")
|
||||
conn.execute("UPDATE accounts SET status = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
|
||||
(int(bool(a.status)), account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
@@ -116,10 +116,10 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
_hex, _salt = _hash_password(r.new_password)
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
@@ -137,10 +137,10 @@ def admin_account_delete(d: schemas.AccountDelIn,
|
||||
if account == login:
|
||||
raise HTTPException(400, "不能删除当前登录的账号")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||||
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||||
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
@@ -172,9 +172,9 @@ def admin_avatar_upload(file: UploadFile = File(...),
|
||||
if not content or len(content) > 2 * 1024 * 1024:
|
||||
raise HTTPException(400, "头像文件为空或超过 2MB")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
old = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
old = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
old_name = (old["avatar"] if old else "") or ""
|
||||
config.AVATAR_DIR.mkdir(parents=True, exist_ok=True)
|
||||
fname = f"{account}{ext}"
|
||||
@@ -185,7 +185,7 @@ def admin_avatar_upload(file: UploadFile = File(...),
|
||||
except OSError:
|
||||
pass
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET avatar = ? WHERE account = ?", (fname, account))
|
||||
conn.execute("UPDATE accounts SET avatar = %s WHERE account = %s", (fname, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "avatar": fname}
|
||||
|
||||
@@ -194,7 +194,7 @@ def admin_avatar_upload(file: UploadFile = File(...),
|
||||
def admin_avatar_get(account: str) -> FileResponse:
|
||||
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
|
||||
with _db() as conn:
|
||||
row = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
row = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if not row or not row["avatar"]:
|
||||
raise HTTPException(404, "未设置头像")
|
||||
path = config.AVATAR_DIR / row["avatar"]
|
||||
@@ -208,7 +208,11 @@ def admin_avatar_get(account: str) -> FileResponse:
|
||||
def admin_grant(g: schemas.GrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤;同时维护插件级授权表。"""
|
||||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤。
|
||||
|
||||
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||||
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
@@ -216,21 +220,18 @@ def admin_grant(g: schemas.GrantIn,
|
||||
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在,请先上传发布")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
(account, plugin_id))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
|
||||
"can_download = excluded.can_download, can_run = excluded.can_run",
|
||||
"INSERT INTO account_plugins(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (%s, %s, %s, %s) "
|
||||
"ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), "
|
||||
"can_run = VALUES(can_run)",
|
||||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
@@ -250,13 +251,13 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||||
"INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (%s, %s)",
|
||||
(account, platform_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
@@ -301,11 +302,11 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
|
||||
"name = excluded.name, manifest = excluded.manifest"
|
||||
+ (", description = excluded.description" if manifest else "")
|
||||
+ (", category = excluded.category" if manifest else "")
|
||||
+ (", icon = excluded.icon" if manifest else ""),
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
|
||||
"name = VALUES(name), manifest = VALUES(manifest)"
|
||||
+ (", description = VALUES(description)" if manifest else "")
|
||||
+ (", category = VALUES(category)" if manifest else "")
|
||||
+ (", icon = VALUES(icon)" if manifest else ""),
|
||||
(plugin_id, name, version,
|
||||
(manifest or {}).get("description", ""),
|
||||
(manifest or {}).get("category", ""),
|
||||
@@ -313,12 +314,12 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
manifest_json))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
|
||||
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
|
||||
"VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
|
||||
"filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)",
|
||||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = %s", (plugin_id,))
|
||||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||||
conn.execute("UPDATE plugins SET latest_version = %s WHERE id = %s", (version, plugin_id))
|
||||
stale_files = _prune_versions(conn, plugin_id)
|
||||
conn.commit()
|
||||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||||
@@ -339,13 +340,14 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||||
files = [dict(r)["filename"] for r in conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))]
|
||||
# 外键 CASCADE 会连带清理 plugin_versions / account_plugins,显式删除仅作兜底保序
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = %s", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = %s", (plugin_id,))
|
||||
conn.commit()
|
||||
for fn in files:
|
||||
try:
|
||||
@@ -373,19 +375,19 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
fields = []
|
||||
vals = []
|
||||
if d.name is not None and d.name.strip():
|
||||
fields.append("name = ?"); vals.append(d.name.strip())
|
||||
fields.append("name = %s"); vals.append(d.name.strip())
|
||||
if d.description:
|
||||
fields.append("description = ?"); vals.append(d.description.strip())
|
||||
fields.append("description = %s"); vals.append(d.description.strip())
|
||||
if d.category:
|
||||
fields.append("category = ?"); vals.append(d.category.strip())
|
||||
fields.append("category = %s"); vals.append(d.category.strip())
|
||||
if d.icon:
|
||||
fields.append("icon = ?"); vals.append(d.icon.strip())
|
||||
fields.append("icon = %s"); vals.append(d.icon.strip())
|
||||
if d.status in ("published", "disabled", "revoked"):
|
||||
fields.append("status = ?"); vals.append(d.status)
|
||||
fields.append("status = %s"); vals.append(d.status)
|
||||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||||
if d.force_min_version and d.force_deadline:
|
||||
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
|
||||
fields.append("force_min_version = %s"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = %s"); vals.append(d.force_deadline.strip())
|
||||
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
|
||||
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
|
||||
elif d.clear_force:
|
||||
@@ -395,9 +397,9 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
return {"ok": True} # 无更新项
|
||||
vals.append(pid)
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (pid,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (pid,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = %s", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
@@ -424,27 +426,27 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
p["field_count"] = len(props)
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = ? ORDER BY version", (p["id"],))]
|
||||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = %s", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM plugin_grants "
|
||||
"WHERE plugin_id = ?", (p["id"],))}
|
||||
"SELECT account, can_download, can_run FROM account_plugins "
|
||||
"WHERE plugin_id = %s", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, is_admin, dept, nickname, avatar, status, created_at "
|
||||
"FROM accounts ORDER BY id")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants "
|
||||
"WHERE account = ?", (a["account"],))}
|
||||
"SELECT plugin_id, can_download, can_run FROM account_plugins "
|
||||
"WHERE account = %s", (a["account"],))}
|
||||
admins = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||||
@@ -475,11 +477,11 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
|
||||
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||||
trend_rows = conn.execute(
|
||||
"SELECT substr(at,1,10) AS day, "
|
||||
"SELECT LEFT(at,10) AS day, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||||
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
|
||||
"FROM runtime_reports WHERE at >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day"
|
||||
).fetchall()
|
||||
trend_map = {r["day"]: r for r in trend_rows}
|
||||
trend = []
|
||||
@@ -553,7 +555,7 @@ def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||||
"ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
"ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
@@ -570,12 +572,26 @@ def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
|
||||
|
||||
@router.get("/api/admin/devices")
|
||||
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""执行机设备列表(按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
|
||||
" chrome_ok, last_seen, status, created_at, updated_at "
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s", (limit,))]
|
||||
return {"devices": rows}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
async def admin_shell_release(upload: UploadFile = File(...),
|
||||
version: str = Query(...),
|
||||
|
||||
@@ -42,7 +42,7 @@ def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = ?",
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
|
||||
if not row or not row["status"]:
|
||||
@@ -74,7 +74,7 @@ def admin_auth(a: schemas.AuthIn,
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, is_admin, dept, nickname, must_change_pwd, status, avatar "
|
||||
"FROM accounts WHERE account = ?",
|
||||
"FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||
_auth_fail(account)
|
||||
@@ -105,7 +105,7 @@ def admin_password(p: schemas.PwdIn,
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = ?",
|
||||
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = %s",
|
||||
(login,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "账号不存在")
|
||||
@@ -115,8 +115,8 @@ def admin_password(p: schemas.PwdIn,
|
||||
raise HTTPException(401, "原密码错误")
|
||||
_hex, _salt = _hash_password(p.new_password)
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 "
|
||||
"WHERE account = ?", (_hex, _salt, login))
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s, must_change_pwd = 0 "
|
||||
"WHERE account = %s", (_hex, _salt, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": login}
|
||||
|
||||
|
||||
@@ -38,14 +38,14 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
ding_uid = (d.dingtalk_uid or "").strip()
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = ?",
|
||||
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
if nickname and nickname != (row["nickname"] or ""):
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account,
|
||||
@@ -60,7 +60,7 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
_hex, _salt = _hash_password(pwd)
|
||||
conn.execute(
|
||||
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||
"dingtalk_uid, must_change_pwd) VALUES (?, ?, ?, 0, '', ?, ?, 1)",
|
||||
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||
(account, _hex, _salt, nickname, ding_uid))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "nickname": nickname,
|
||||
|
||||
@@ -11,4 +11,4 @@ router = APIRouter()
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": config.DB_PATH.name}
|
||||
return {"ok": True, "db": "mysql", "host": config.MYSQL_HOST, "database": config.MYSQL_DB}
|
||||
@@ -22,7 +22,7 @@ router = APIRouter()
|
||||
def _account_disabled(acct: str) -> bool:
|
||||
"""账号是否已停用(停用后机器侧一律不给插件/授权)。"""
|
||||
with _db() as conn:
|
||||
row = conn.execute("SELECT status FROM accounts WHERE account = ?", (acct,)).fetchone()
|
||||
row = conn.execute("SELECT status FROM accounts WHERE account = %s", (acct,)).fetchone()
|
||||
return bool(row) and not bool(row["status"])
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ def plugins(account: str = Query(default="", description="账号(旧底座按此
|
||||
SELECT p.id, p.name, p.latest_version AS version
|
||||
FROM plugins p
|
||||
JOIN account_plugins ap ON ap.plugin_id = p.id
|
||||
WHERE ap.account = ?
|
||||
WHERE ap.account = %s
|
||||
ORDER BY p.id
|
||||
""",
|
||||
(acct,),
|
||||
@@ -72,7 +72,7 @@ def platforms_allowed(account: str = Query(default="", description="账号(旧
|
||||
return {"account": acct, "allowed": []}
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s ORDER BY platform_id",
|
||||
(acct,),
|
||||
).fetchall()
|
||||
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
|
||||
@@ -112,7 +112,7 @@ def pkg(plugin_id: str, version: str,
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, version),
|
||||
).fetchone()
|
||||
if not row:
|
||||
@@ -147,9 +147,9 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT g.plugin_id, g.can_download, g.can_run, p.name, p.status, p.latest_version
|
||||
FROM plugin_grants g
|
||||
FROM account_plugins g
|
||||
JOIN plugins p ON p.id = g.plugin_id
|
||||
WHERE g.account = ?
|
||||
WHERE g.account = %s
|
||||
""",
|
||||
(account.strip(),),
|
||||
).fetchall()
|
||||
@@ -199,10 +199,10 @@ def download_ticket(plugin_id: str, version: str,
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT can_download FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
"SELECT can_download FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||||
(account.strip(), plugin_id)).fetchone()
|
||||
ver = conn.execute(
|
||||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, version)).fetchone()
|
||||
if not ver:
|
||||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||
@@ -243,12 +243,42 @@ def runtime_report(b: schemas.RuntimeReportIn,
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO runtime_reports(account, device_id, plugin_id, version, status, msg, duration_sec, at) "
|
||||
"VALUES (?,?,?,?,?,?,?,?)",
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/device/report")
|
||||
def device_report(b: schemas.DeviceReportIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""执行机心跳/环境上报(含 Chrome 检测结果):按 device_id 幂等 upsert 设备记录。
|
||||
|
||||
供壳(执行机底座)启动/定时上报本机环境;last_seen 与 status 由中心机统一维护
|
||||
在线态(status 由调用方按心跳状态传,离线清理逻辑在管理端查询侧)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
device_id = (b.device_id or "").strip()
|
||||
if not device_id:
|
||||
raise HTTPException(400, "device_id 不能为空")
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO devices(device_id, account, hostname, os, ip, "
|
||||
"chrome_installed, chrome_version, chrome_ok, last_seen, status) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
|
||||
"ON DUPLICATE KEY UPDATE "
|
||||
"account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), "
|
||||
"ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), "
|
||||
"chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), "
|
||||
"last_seen = VALUES(last_seen), status = VALUES(status)",
|
||||
(device_id, (b.account or "").strip(), (b.hostname or "").strip(),
|
||||
(b.os or "").strip(), (b.ip or "").strip(),
|
||||
int(bool(b.chrome_installed)), (b.chrome_version or "").strip(),
|
||||
int(bool(b.chrome_ok)), _now(), int(bool(b.status))))
|
||||
conn.commit()
|
||||
return {"ok": True, "device_id": device_id}
|
||||
|
||||
|
||||
# ==================== 壳子(执行机主程序)自动更新 ====================
|
||||
# shell/version.json 约定:{"version": "1.0.0", "filename": "setup-37du-host-1.0.0.exe",
|
||||
# "sha256": "<可选,安装包校验值>", "notes": "<可选,更新说明>"}
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
- dingtalk.py 钉钉官方接口 - pkgutil.py 插件包校验/解析/版本
|
||||
- schemas.py 请求体模型 - apis/ 路由子包(meta/plugins/auth/dingtalk/admin)
|
||||
|
||||
DB:controlplane.db(同目录)。包文件:packages/。可选:CONTROLPLANE_TOKEN 非空时客户端须带
|
||||
DB:MySQL(连接参数在 controlplane/.env 的 MYSQL_*,库 37du_center;首次启动自动建库建表+种子)。
|
||||
包文件:packages/。可选:CONTROLPLANE_TOKEN 非空时客户端须带
|
||||
X-API-Token 请求头。
|
||||
|
||||
运行(本地 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
@@ -23,7 +24,6 @@ from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from controlplane import config
|
||||
from controlplane.core.db import _init_db, _seed
|
||||
@@ -41,7 +41,7 @@ async def lifespan(app: FastAPI):
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du 内网插件控制面", lifespan=lifespan)
|
||||
app = FastAPI(title="37du 插件管理平台", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
@@ -52,12 +52,6 @@ app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_admin.router)
|
||||
|
||||
|
||||
# ==================== 挂载控制面前端产物 ====================
|
||||
# 源码模式 => config.DIST(controlplane/frontend/dist);exe 模式 => _MEIPASS/frontend/dist(打进 exe)
|
||||
if config.DIST.is_dir():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
@@ -86,6 +80,6 @@ if __name__ == "__main__":
|
||||
if sys.stderr is None:
|
||||
sys.stderr = open(os.devnull, "w")
|
||||
|
||||
print(f"[controlplane] http://0.0.0.0:{config.CONTROLPLANE_PORT} sqlite={config.DB_PATH.name}")
|
||||
print(f"[controlplane] http://0.0.0.0:{config.CONTROLPLANE_PORT} mysql={config.MYSQL_DB}@{config.MYSQL_HOST}")
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.CONTROLPLANE_PORT,
|
||||
log_config=LOG_CONFIG, log_level="info")
|
||||
|
Before Width: | Height: | Size: 70 B After Width: | Height: | Size: 70 B |
@@ -68,7 +68,7 @@ def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
raise HTTPException(401, "缺少有效登录态")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM accounts WHERE account = ? AND is_admin = 1", (account,)).fetchone()
|
||||
"SELECT 1 FROM accounts WHERE account = %s AND is_admin = 1", (account,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||
return account
|
||||
@@ -131,7 +131,7 @@ def _auth_account_lookup(account: str) -> dict:
|
||||
return {"exists": False, "nickname": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT nickname FROM accounts WHERE account = ?", (account.strip(),)).fetchone()
|
||||
"SELECT nickname FROM accounts WHERE account = %s", (account.strip(),)).fetchone()
|
||||
return {"exists": bool(row), "nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
|
||||
@@ -18,11 +18,12 @@ from pathlib import Path
|
||||
def _app_base() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent
|
||||
# 源码模式:core/config.py → controlplane/(.env、packages、keys、.admin_secret、shell 均位于包根)
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_base()
|
||||
DB_PATH = APP_DIR / "controlplane.db"
|
||||
DB_PATH = APP_DIR / "controlplane.db" # 历史 SQLite 路径,仅作迁移数据源/备份,不再读写
|
||||
PKG_DIR = APP_DIR / "packages"
|
||||
AVATAR_DIR = APP_DIR / "avatars"
|
||||
# 壳子(执行机主程序)更新源:version.json + setup 安装包,供执行端自动下载升级
|
||||
@@ -52,6 +53,12 @@ _load_dotenv()
|
||||
# 内部凭证(底座→统一后端的调用凭证)。为空则不强制(内网可信场景)。
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
CONTROLPLANE_PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||
# MySQL 数据层(控制面唯一存储,无 SQLite 回退)。连接参数在 controlplane/.env 配置。
|
||||
MYSQL_HOST = os.getenv("MYSQL_HOST", "")
|
||||
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
|
||||
MYSQL_USER = os.getenv("MYSQL_USER", "root")
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "")
|
||||
MYSQL_DB = os.getenv("MYSQL_DB") or os.getenv("MYSQL_DATABASE") or "37du_center"
|
||||
# 钉钉扫码自动建号的初始密码;新号无插件权限、仅空壳,首次登录须改密。
|
||||
DINGTALK_DEFAULT_PASSWORD = os.getenv("DINGTALK_DEFAULT_PASSWORD", "123456")
|
||||
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||
@@ -85,5 +92,3 @@ def _admin_secret() -> str:
|
||||
return _ADMIN_SECRET_FALLBACK
|
||||
|
||||
|
||||
# 前端产物目录:源码 controlplane/frontend/dist;打包 _MEIPASS/frontend/dist(打进 exe)
|
||||
DIST = Path(getattr(sys, "_MEIPASS", APP_DIR)) / "frontend" / "dist"
|
||||
+240
-146
@@ -1,29 +1,235 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机数据层:SQLite 访问 + 建表 + 种子 + 审计 + 常用时间戳。
|
||||
"""中心机数据层:MySQL 访问 + 幂等建表(DDL 内嵌) + 迁移版本 + 种子 + 审计 + 常用时间戳。
|
||||
|
||||
数据访问统一收敛到 `_db()` 连接(commit+close 收口),路由只在本层之上组合读写。
|
||||
- 数据访问统一收敛到 `_db()`(PyMySQL DictCursor,commit+close 收口),路由只在本层之上组合读写。
|
||||
- 建表 DDL 与 `desktop/controlplane/tools/schema_mysql.sql` 保持同步(该文件为人工建库权威源,
|
||||
本文件为运行时幂等副本;新增表/字段需两处同步维护)。
|
||||
- 数据库连接由 `controlplane/.env` 的 MYSQL_* 决定;控制面不再提供 SQLite 回退。
|
||||
- 参数占位符统一 `%s`(PyMySQL),禁止 `?`(SQLite 语法)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
from pymysql.cursors import DictCursor
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260916_001"
|
||||
|
||||
# 全量 DDL(11 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' 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)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
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='系统级键值配置'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def _connect(server: bool = False) -> pymysql.connections.Connection:
|
||||
"""建立 PyMySQL 连接;server=True 时不指定 database(用于建库)。"""
|
||||
return pymysql.connect(
|
||||
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
|
||||
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
|
||||
database=None if server else config.MYSQL_DB,
|
||||
charset="utf8mb4", cursorclass=DictCursor, autocommit=False)
|
||||
|
||||
|
||||
class _DbConn:
|
||||
"""薄适配层:让路由层沿用旧 sqlite3 风格 `conn.execute(...)` 调用 PyMySQL。
|
||||
|
||||
PyMySQL 1.x 的 Connection 没有 execute() 快捷方法,故在此代理到 cursor,
|
||||
并透传 commit/rollback/close。execute() 每次新建游标(DictCursor 默认缓冲读取,
|
||||
返回后仍可 fetchone/fetchall/迭代),随连接关闭一并回收。
|
||||
"""
|
||||
|
||||
def __init__(self, conn: pymysql.connections.Connection) -> None:
|
||||
self._conn = conn
|
||||
|
||||
def execute(self, sql: str, args=None):
|
||||
# PyMySQL 的 Cursor.execute() 返回 rowcount(int),需返回游标以支持 .fetchone()/.fetchall()/迭代
|
||||
cur = self._conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
return cur
|
||||
|
||||
def commit(self) -> None:
|
||||
self._conn.commit()
|
||||
|
||||
def rollback(self) -> None:
|
||||
self._conn.rollback()
|
||||
|
||||
def close(self) -> None:
|
||||
self._conn.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(统一收口,避免长运行服务累积连接)。
|
||||
|
||||
sqlite3 原生 with 语义只 commit 不 close,这里补 close;异常时不 commit 等价于回滚。
|
||||
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚。
|
||||
"""
|
||||
conn = sqlite3.connect(config.DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
if not config.MYSQL_HOST:
|
||||
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||
conn = _connect()
|
||||
try:
|
||||
yield conn
|
||||
yield _DbConn(conn)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -33,142 +239,30 @@ def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _ensure_col(conn: sqlite3.Connection, table: str, col: str, ddl: str) -> None:
|
||||
"""幂等给表补列:列已存在则忽略(sqlite 无 ADD COLUMN IF NOT EXISTS)。"""
|
||||
cols = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
if col not in cols:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
|
||||
|
||||
|
||||
def _migrate_accounts(conn: sqlite3.Connection) -> None:
|
||||
"""老库 accounts 迁移:account 主键 → 自增 id 主键(account 改唯一键),并补新列。
|
||||
|
||||
仅当表缺 id 列时执行;新库/已迁移库直接跳过。old 表在此前已 _ensure_col 补齐
|
||||
must_change_pwd,故 SELECT 可直接引用。
|
||||
"""
|
||||
cols = {r["name"] for r in conn.execute("PRAGMA table_info(accounts)").fetchall()}
|
||||
if "id" in cols:
|
||||
return
|
||||
conn.executescript("""
|
||||
CREATE TABLE accounts_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
dept TEXT DEFAULT '',
|
||||
nickname TEXT DEFAULT '',
|
||||
dingtalk_uid TEXT DEFAULT '',
|
||||
must_change_pwd INTEGER DEFAULT 0,
|
||||
avatar TEXT DEFAULT '',
|
||||
status INTEGER DEFAULT 1,
|
||||
created_at TEXT DEFAULT ''
|
||||
);
|
||||
INSERT INTO accounts_new(account, password_hash, salt, is_admin, dept,
|
||||
nickname, dingtalk_uid, must_change_pwd)
|
||||
SELECT account, password_hash, salt, is_admin, dept,
|
||||
nickname, dingtalk_uid, COALESCE(must_change_pwd, 0)
|
||||
FROM accounts;
|
||||
DROP TABLE accounts;
|
||||
ALTER TABLE accounts_new RENAME TO accounts;
|
||||
""")
|
||||
def _ensure_database() -> None:
|
||||
"""幂等建库(utf8mb4)。"""
|
||||
conn = _connect(server=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 "
|
||||
"COLLATE utf8mb4_unicode_ci" % config.MYSQL_DB)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _init_db() -> None:
|
||||
"""建表(幂等)。基础表 + 产品化扩展表(插件授权/审计/运行上报),并兼容旧库补列。"""
|
||||
"""建表(幂等 DDL)+ 登记迁移版本,替代旧的 _ensure_col 渐进补列。"""
|
||||
if not config.MYSQL_HOST:
|
||||
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||
_ensure_database()
|
||||
with _db() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
latest_version TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
plugin_id TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
uploaded_at TEXT NOT NULL,
|
||||
PRIMARY KEY (plugin_id, version)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, platform_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
dept TEXT DEFAULT '',
|
||||
nickname TEXT DEFAULT '',
|
||||
dingtalk_uid TEXT DEFAULT '',
|
||||
must_change_pwd INTEGER DEFAULT 0,
|
||||
avatar TEXT DEFAULT '',
|
||||
status INTEGER DEFAULT 1,
|
||||
created_at TEXT DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_grants (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
can_download INTEGER DEFAULT 1,
|
||||
can_run INTEGER DEFAULT 1,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
target TEXT DEFAULT '',
|
||||
detail TEXT DEFAULT '',
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
device_id TEXT DEFAULT '',
|
||||
plugin_id TEXT DEFAULT '',
|
||||
version TEXT DEFAULT '',
|
||||
status TEXT DEFAULT '',
|
||||
msg TEXT DEFAULT '',
|
||||
duration_sec INTEGER DEFAULT 0,
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
# 幂等补齐旧表可能缺失的可选列(sqlite ALTER 不支持 ADD COLUMN IF NOT EXISTS)
|
||||
_ensure_col(conn, "plugins", "description", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "category", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "icon", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "status", "TEXT DEFAULT 'published'")
|
||||
_ensure_col(conn, "plugins", "force_min_version", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "force_deadline", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "manifest", "TEXT DEFAULT '{}'")
|
||||
_ensure_col(conn, "plugin_versions", "sha256", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "runtime_reports", "duration_sec", "INTEGER DEFAULT 0")
|
||||
_ensure_col(conn, "accounts", "nickname", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "dingtalk_uid", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "must_change_pwd", "INTEGER DEFAULT 0")
|
||||
# 老库迁移:account 主键 → 自增 id 主键 + 补 avatar/status/created_at(幂等)
|
||||
_migrate_accounts(conn)
|
||||
_ensure_col(conn, "accounts", "avatar", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "status", "INTEGER DEFAULT 1")
|
||||
_ensure_col(conn, "accounts", "created_at", "TEXT DEFAULT ''")
|
||||
# 回填:老库 account_plugins 已有授权但 plugin_grants 为空,则按"全权限"补录,
|
||||
# 保证离线票据 license 不会漏掉存量授权(can_download=1, can_run=1)。
|
||||
for ddl in _DDL_TABLES:
|
||||
conn.execute(ddl)
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"SELECT ap.account, ap.plugin_id, 1, 1 FROM account_plugins ap "
|
||||
"LEFT JOIN plugin_grants g ON g.account = ap.account AND g.plugin_id = ap.plugin_id "
|
||||
"WHERE g.account IS NULL"
|
||||
)
|
||||
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||
(_SCHEMA_VERSION,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
@@ -180,20 +274,20 @@ def _seed() -> None:
|
||||
config.PKG_DIR.mkdir(exist_ok=True)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugins(id, name, latest_version) VALUES (?, ?, ?)",
|
||||
"INSERT IGNORE INTO plugins(id, name, latest_version) VALUES (%s, %s, %s)",
|
||||
("seal_check", "考勤月报封存检查", "1.0.0"),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
"INSERT IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (%s, %s, %s, %s)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||||
for _acc, _dept in (("puddy", "IT"),):
|
||||
_hex, _salt = _hash_password("123456")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (?, ?, ?, ?, ?)", (_acc, _hex, _salt, 1, _dept))
|
||||
"INSERT IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (%s, %s, %s, %s, %s)", (_acc, _hex, _salt, 1, _dept))
|
||||
conn.commit()
|
||||
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
@@ -205,8 +299,8 @@ def _audit(account: str, action: str, target: str = "", detail: str = "") -> Non
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO audit_logs(account, action, target, detail, at) VALUES (?,?,?,?,?)",
|
||||
"INSERT INTO audit_logs(account, action, target, detail, at) VALUES (%s,%s,%s,%s,%s)",
|
||||
(account or "", action, target or "", detail or "", _now()))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
pass
|
||||
|
||||
@@ -75,10 +75,10 @@ def _extract_manifest(content: bytes) -> dict | None:
|
||||
def _prune_versions(conn, plugin_id: str) -> list:
|
||||
"""仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。"""
|
||||
rows = conn.execute(
|
||||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,)).fetchall()
|
||||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = %s", (plugin_id,)).fetchall()
|
||||
stale = sorted(rows, key=lambda r: _version_key(r["version"]), reverse=True)[_KEEP_VERSIONS:]
|
||||
for r in stale:
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, r["version"]))
|
||||
return [r["filename"] for r in stale]
|
||||
|
||||
|
||||
@@ -21,6 +21,19 @@ class RuntimeReportIn(BaseModel):
|
||||
duration_sec: int = 0
|
||||
|
||||
|
||||
class DeviceReportIn(BaseModel):
|
||||
"""执行机心跳/环境上报(含 Chrome 检测结果),与 devices 表一一对应。"""
|
||||
device_id: str
|
||||
account: str = ""
|
||||
hostname: str = ""
|
||||
os: str = ""
|
||||
ip: str = ""
|
||||
chrome_installed: int = 0 # 是否已安装 Chrome:1=是 0=否
|
||||
chrome_version: str = "" # Chrome 版本号(检测到才填)
|
||||
chrome_ok: int = 0 # Chrome 是否就绪:1=是 0=否
|
||||
status: int = 1 # 设备状态:1=在线 0=离线
|
||||
|
||||
|
||||
class AuthIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 内网插件控制面</title>
|
||||
<title>37du 插件管理平台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
-167
@@ -10,7 +10,6 @@
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"naive-ui": "^2.45.3",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -64,24 +63,6 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@css-render/plugin-bem": {
|
||||
"version": "0.15.14",
|
||||
"resolved": "https://registry.npmjs.org/@css-render/plugin-bem/-/plugin-bem-0.15.14.tgz",
|
||||
"integrity": "sha512-QK513CJ7yEQxm/P3EwsI+d+ha8kSOcjGvD6SevM41neEMxdULE+18iuQK6tEChAWMOQNQPLG/Rw3Khb69r5neg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"css-render": "~0.15.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@css-render/vue3-ssr": {
|
||||
"version": "0.15.14",
|
||||
"resolved": "https://registry.npmjs.org/@css-render/vue3-ssr/-/vue3-ssr-0.15.14.tgz",
|
||||
"integrity": "sha512-//8027GSbxE9n3QlD73xFY6z4ZbHbvrOVB7AO6hsmrEzGbg+h2A09HboUyDgu+xsmj7JnvJD39Irt+2D0+iV8g==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
},
|
||||
"node_modules/@ctrl/tinycolor": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.1.tgz",
|
||||
@@ -100,12 +81,6 @@
|
||||
"vue": "^3.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emotion/hash": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz",
|
||||
"integrity": "sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
@@ -579,12 +554,6 @@
|
||||
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@juggle/resize-observer": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@juggle/resize-observer/-/resize-observer-3.4.0.tgz",
|
||||
"integrity": "sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@napi-rs/lzma-linux-x64-gnu": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
|
||||
@@ -1189,47 +1158,12 @@
|
||||
"integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/css-render": {
|
||||
"version": "0.15.14",
|
||||
"resolved": "https://registry.npmjs.org/css-render/-/css-render-0.15.14.tgz",
|
||||
"integrity": "sha512-9nF4PdUle+5ta4W5SyZdLCCmFd37uVimSjg1evcTqKJCyvCEEj12WKzOSBNak6r4im4J4iYXKH1OWpUV5LBYFg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@emotion/hash": "~0.8.0",
|
||||
"csstype": "~3.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/css-render/node_modules/csstype": {
|
||||
"version": "3.0.11",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.11.tgz",
|
||||
"integrity": "sha512-sa6P2wJ+CAbgyy4KFssIb/JNMLxFvKF1pCYCSXS8ZMuqZnMsrxqI2E5sPyoTpxoPU/gVZMzr2zjOfg8GIZOMsw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/date-fns": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
|
||||
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/kossnocorp"
|
||||
}
|
||||
},
|
||||
"node_modules/date-fns-tz": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-3.2.0.tgz",
|
||||
"integrity": "sha512-sg8HqoTEulcbbbVXeg84u5UnlsQa8GS5QXMqjjYIhS4abEVVKIUwe0/l/UhrZdKaL/W5eWZNlbTeEIiOXTcsBQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"date-fns": "^3.0.0 || ^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dayjs": {
|
||||
"version": "1.11.23",
|
||||
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
|
||||
@@ -1322,12 +1256,6 @@
|
||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/evtd": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "https://registry.npmjs.org/evtd/-/evtd-0.2.4.tgz",
|
||||
"integrity": "sha512-qaeGN5bx63s/AXgQo8gj6fBkxge+OoLddLniox5qtLAEY5HSnuSlISXVPxnSae1dWblvTh4/HoMIB+mbMsvZzw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
@@ -1361,15 +1289,6 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/highlight.js": {
|
||||
"version": "11.12.0",
|
||||
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz",
|
||||
"integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.18.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||
@@ -1408,38 +1327,6 @@
|
||||
"integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/naive-ui": {
|
||||
"version": "2.45.3",
|
||||
"resolved": "https://registry.npmjs.org/naive-ui/-/naive-ui-2.45.3.tgz",
|
||||
"integrity": "sha512-D83gJ+6zUdkQ5DuUbmlfyaM1t8pV5WMPa6KmL9mByqQuiL12qBdA0n/iEIth4dQw1x/duNGpOS2anpt5FKO1kw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@css-render/plugin-bem": "^0.15.14",
|
||||
"@css-render/vue3-ssr": "^0.15.14",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"async-validator": "^4.2.5",
|
||||
"css-render": "^0.15.14",
|
||||
"csstype": "^3.1.3",
|
||||
"date-fns": "^4.1.0",
|
||||
"date-fns-tz": "^3.2.0",
|
||||
"evtd": "^0.2.4",
|
||||
"highlight.js": "^11.8.0",
|
||||
"lodash": "^4.17.21",
|
||||
"lodash-es": "^4.17.21",
|
||||
"seemly": "^0.3.10",
|
||||
"treemate": "^0.3.11",
|
||||
"vdirs": "^0.1.8",
|
||||
"vooks": "^0.2.12",
|
||||
"vueuc": "^0.4.66"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
@@ -1557,12 +1444,6 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/seemly": {
|
||||
"version": "0.3.10",
|
||||
"resolved": "https://registry.npmjs.org/seemly/-/seemly-0.3.10.tgz",
|
||||
"integrity": "sha512-2+SMxtG1PcsL0uyhkumlOU6Qo9TAQ/WyH7tthnPIOQB05/12jz9naq6GZ6iZ6ApVsO3rr2gsnTf3++OV63kE1Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -1589,24 +1470,6 @@
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/treemate": {
|
||||
"version": "0.3.11",
|
||||
"resolved": "https://registry.npmjs.org/treemate/-/treemate-0.3.11.tgz",
|
||||
"integrity": "sha512-M8RGFoKtZ8dF+iwJfAJTOH/SM4KluKOKRJpjCMhI8bG3qB74zrFoArKZ62ll0Fr3mqkMJiQOmWYkdYgDeITYQg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vdirs": {
|
||||
"version": "0.1.8",
|
||||
"resolved": "https://registry.npmjs.org/vdirs/-/vdirs-0.1.8.tgz",
|
||||
"integrity": "sha512-H9V1zGRLQZg9b+GdMk8MXDN2Lva0zx72MPahDKc30v+DtwKjfyOSXWRIX4t2mhDubM1H09gPhWeth/BJWPHGUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"evtd": "^0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
@@ -1682,18 +1545,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vooks": {
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/vooks/-/vooks-0.2.12.tgz",
|
||||
"integrity": "sha512-iox0I3RZzxtKlcgYaStQYKEzWWGAduMmq+jS7OrNdQo1FgGfPMubGL3uGHOU9n97NIvfFDBGnpSvkWyb/NSn/Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"evtd": "^0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue": {
|
||||
"version": "3.5.42",
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.42.tgz",
|
||||
@@ -1720,24 +1571,6 @@
|
||||
"resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz",
|
||||
"integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vueuc": {
|
||||
"version": "0.4.66",
|
||||
"resolved": "https://registry.npmjs.org/vueuc/-/vueuc-0.4.66.tgz",
|
||||
"integrity": "sha512-hHrZl+0AsrUvqYPBXSXQ2QaSrO3razjeUseLAhJWlOS/Hdfw/Y2MU05fOTP1qn1A3121gMxsHLaEz2V6CkWdTg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@css-render/vue3-ssr": "^0.15.10",
|
||||
"@juggle/resize-observer": "^3.3.1",
|
||||
"css-render": "^0.15.10",
|
||||
"evtd": "^0.2.4",
|
||||
"seemly": "^0.3.6",
|
||||
"vdirs": "^0.1.4",
|
||||
"vooks": "^0.2.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"naive-ui": "^2.45.3",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,49 +1,56 @@
|
||||
<template>
|
||||
<n-config-provider :theme-overrides="themeOverrides" :locale="zhCN" :date-locale="dateZhCN">
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="console" v-else>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>中心机 · 控制面</span>
|
||||
</div>
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="console" v-else>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>中心机 · 控制面</span>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<n-dropdown trigger="click" :options="acctOptions" @select="onCommand">
|
||||
<div class="acct">
|
||||
<span class="avatar">{{ initial }}</span>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<n-tag v-if="store.isAdmin" size="small" round :bordered="false" type="primary" class="admin-tag">管理员</n-tag>
|
||||
<n-icon class="caret" :size="13"><ArrowDown /></n-icon>
|
||||
</div>
|
||||
</n-dropdown>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<aside class="aside">
|
||||
<div class="aside-inner">
|
||||
<n-menu class="menu" :value="activeKey" :options="menuOptions" :root-indent="0" @update:value="onMenu" />
|
||||
</div>
|
||||
<div class="aside-foot">
|
||||
<span>37du 自动化</span>
|
||||
<span class="ver">v0.1.0</span>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="main">
|
||||
<component :is="viewComp" :key="route" />
|
||||
</main>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<el-dropdown trigger="click" @command="onCommand">
|
||||
<div class="acct">
|
||||
<span class="avatar">{{ initial }}</span>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<el-tag v-if="store.isAdmin" size="small" type="primary" round effect="light" class="admin-tag">管理员</el-tag>
|
||||
<el-icon class="caret"><ArrowDown /></el-icon>
|
||||
</div>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="pwd"><el-icon><Lock /></el-icon>修改密码</el-dropdown-item>
|
||||
<el-dropdown-item divided command="logout"><el-icon><SwitchButton /></el-icon>退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<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-icon><component :is="m.icon" /></el-icon>
|
||||
<span>{{ m.label }}</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="main">
|
||||
<transition name="view-fade" mode="out-in">
|
||||
<component :is="viewComp" :key="route" />
|
||||
</transition>
|
||||
</main>
|
||||
</div>
|
||||
<PasswordDialog v-model="pwdOpen" />
|
||||
</n-config-provider>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ArrowDown } from '@element-plus/icons-vue'
|
||||
import { themeOverrides, zhCN, dateZhCN, message } from './naive'
|
||||
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import PasswordDialog from './components/PasswordDialog.vue'
|
||||
import OverviewView from './views/OverviewView.vue'
|
||||
@@ -56,20 +63,15 @@ import { store, clearSession } from './store'
|
||||
import { adminMe } from './api'
|
||||
|
||||
const menuOptions = [
|
||||
{ label: '概览', key: 'overview' },
|
||||
{ label: '数据看板', key: 'stats' },
|
||||
{ label: '插件管理', key: 'plugins' },
|
||||
{ label: '账号管理', key: 'accounts' },
|
||||
{ label: '权限授权', key: 'grants' },
|
||||
{ label: '审计报表', key: 'audit' },
|
||||
]
|
||||
const acctOptions = [
|
||||
{ label: '修改密码', key: 'pwd' },
|
||||
{ type: 'divider', key: 'd1' },
|
||||
{ label: '退出登录', key: 'logout' },
|
||||
{ label: '概览', key: 'overview', icon: Odometer },
|
||||
{ label: '数据看板', key: 'stats', icon: TrendCharts },
|
||||
{ label: '插件管理', key: 'plugins', icon: Box },
|
||||
{ label: '账号管理', key: 'accounts', icon: User },
|
||||
{ label: '权限授权', key: 'grants', icon: Key },
|
||||
{ label: '审计报表', key: 'audit', icon: Document },
|
||||
]
|
||||
|
||||
// 轻量 hash 路由:StaticFiles(html=True) 下刷新安全,零后端改动
|
||||
// 轻量 hash 路由:静态站刷新安全,零后端改动
|
||||
const KEY = {
|
||||
'#/overview': 'overview',
|
||||
'#/stats': 'stats',
|
||||
@@ -129,71 +131,67 @@ onMounted(async () => {
|
||||
<style scoped>
|
||||
.console { height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* ---------- 顶栏:磨砂玻璃 ---------- */
|
||||
/* ---------- 顶栏:纸白面板 ---------- */
|
||||
.topbar {
|
||||
height: 64px; flex-shrink: 0;
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 0 24px;
|
||||
background: rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border-bottom: 1px solid var(--cp-border);
|
||||
padding: 0 26px;
|
||||
background: rgba(255, 253, 248, .86);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
border-bottom: 1px solid var(--cp-line);
|
||||
box-shadow: 0 6px 20px -18px rgba(35, 42, 58, .3);
|
||||
position: relative; z-index: 20;
|
||||
}
|
||||
.topbar::after {
|
||||
content: ''; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px;
|
||||
background: linear-gradient(90deg, transparent, rgba(59, 108, 255, .35), rgba(34, 199, 232, .35), transparent);
|
||||
background: linear-gradient(90deg, transparent, rgba(47, 92, 240, .4), rgba(15, 159, 155, .4), transparent);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 12px; }
|
||||
.logo {
|
||||
width: 38px; height: 38px; border-radius: 12px;
|
||||
display: grid; place-items: center; position: relative;
|
||||
background: linear-gradient(135deg, #3b6cff 0%, #22c7e8 130%);
|
||||
background: linear-gradient(135deg, var(--cp-blue) 0%, var(--cp-teal) 140%);
|
||||
color: #fff; font-size: 14px; font-weight: 800; letter-spacing: .5px;
|
||||
box-shadow: 0 6px 16px -6px rgba(59, 108, 255, .6);
|
||||
box-shadow: 0 8px 18px -8px rgba(47, 92, 240, .55);
|
||||
}
|
||||
.logo::after { content: ''; position: absolute; inset: 2px; border-radius: 10px; border: 1px solid rgba(255, 255, 255, .28); }
|
||||
.logo::after { content: ''; position: absolute; inset: 2px; border-radius: 10px; border: 1px solid rgba(255, 255, 255, .3); }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 15px; color: var(--cp-ink); letter-spacing: .2px; }
|
||||
.brand-meta strong { font-size: 15px; color: var(--cp-ink-1); letter-spacing: .2px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.spacer { flex: 1; }
|
||||
|
||||
.acct {
|
||||
display: flex; align-items: center; gap: 9px; cursor: pointer;
|
||||
padding: 6px 10px; border-radius: 12px; transition: background .18s;
|
||||
padding: 6px 12px; border-radius: 12px; border: 1px solid transparent;
|
||||
transition: background .18s, border-color .18s;
|
||||
}
|
||||
.acct:hover { background: rgba(59, 108, 255, .07); }
|
||||
.acct:hover { background: rgba(47, 92, 240, .06); border-color: rgba(47, 92, 240, .16); }
|
||||
.avatar {
|
||||
width: 30px; height: 30px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff, #22c7e8);
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff; font-size: 13px; font-weight: 700;
|
||||
}
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--cp-ink); }
|
||||
.acct-name { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.admin-tag { margin-left: 2px; }
|
||||
.caret { color: var(--cp-ink-3); }
|
||||
|
||||
/* ---------- 主体:悬浮侧栏 + 内容区 ---------- */
|
||||
.body { flex: 1; display: flex; gap: 18px; padding: 18px 24px 24px; min-height: 0; }
|
||||
/* ---------- 主体:侧栏 + 内容区(紧凑间距,避免挤压表格) ---------- */
|
||||
.body { flex: 1; display: flex; gap: 12px; padding: 14px 18px 22px; min-height: 0; }
|
||||
.aside {
|
||||
width: 208px; flex-shrink: 0;
|
||||
width: 192px; flex-shrink: 0;
|
||||
display: flex; flex-direction: column;
|
||||
background: rgba(255, 255, 255, .78);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
padding: 14px 10px;
|
||||
background: rgba(255, 253, 248, .8);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--cp-shadow);
|
||||
padding: 12px 8px;
|
||||
}
|
||||
.aside-inner { flex: 1; }
|
||||
.aside-foot {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 12px 12px 4px; margin-top: 8px;
|
||||
border-top: 1px dashed var(--cp-border);
|
||||
font-size: 11px; color: var(--cp-ink-3);
|
||||
}
|
||||
.main { flex: 1; min-width: 0; overflow: auto; padding: 4px 4px 8px; }
|
||||
.main { flex: 1; min-width: 0; overflow: auto; padding: 0 2px 8px; }
|
||||
|
||||
/* 页面切换过渡:轻微上浮淡入 */
|
||||
.view-fade-enter-active { transition: opacity .22s ease, transform .22s ease; }
|
||||
@@ -201,15 +199,18 @@ onMounted(async () => {
|
||||
.view-fade-enter-from { opacity: 0; transform: translateY(8px); }
|
||||
.view-fade-leave-to { opacity: 0; }
|
||||
|
||||
/* ---------- 侧栏菜单:干净的标准导航,配色由 naive 主题统一控制 ---------- */
|
||||
.menu { padding: 2px; }
|
||||
.menu :deep(.n-menu-item) { margin-bottom: 4px; }
|
||||
.menu :deep(.n-menu-item-content) {
|
||||
/* 无图标时 naive 给 `padding-left:0` 的内联样式,需 !important 压过,
|
||||
否则文字贴左边界、跑出圆角底色区域 */
|
||||
padding-left: 16px !important;
|
||||
padding-right: 16px !important;
|
||||
border-radius: 10px;
|
||||
box-sizing: border-box;
|
||||
/* ---------- 侧栏菜单:纸面导航 ---------- */
|
||||
.aside :deep(.el-menu-item) {
|
||||
height: 44px; margin-bottom: 4px;
|
||||
border-radius: 11px;
|
||||
font-weight: 600; color: var(--cp-ink-2);
|
||||
}
|
||||
.aside :deep(.el-menu-item:hover) { background: rgba(47, 92, 240, .06); color: var(--cp-blue); }
|
||||
.aside :deep(.el-menu-item.is-active) {
|
||||
background: linear-gradient(90deg, rgba(47, 92, 240, .12), rgba(47, 92, 240, .04));
|
||||
color: var(--cp-blue);
|
||||
font-weight: 700;
|
||||
box-shadow: inset 3px 0 0 var(--cp-blue);
|
||||
}
|
||||
.aside :deep(.el-menu-item .el-icon) { font-size: 17px; }
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<div class="card">
|
||||
<div class="card cp-rise">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
@@ -9,35 +9,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-form class="form" label-placement="top" @keydown.enter.prevent="doLogin">
|
||||
<n-form-item label="账号">
|
||||
<n-input
|
||||
v-model:value="account"
|
||||
placeholder="请输入账号"
|
||||
autocomplete="username"
|
||||
size="large"
|
||||
@keyup.enter="doLogin"
|
||||
>
|
||||
<template #prefix><n-icon><User /></n-icon></template>
|
||||
</n-input>
|
||||
</n-form-item>
|
||||
<n-form-item label="密码">
|
||||
<n-input
|
||||
v-model:value="password"
|
||||
type="password"
|
||||
placeholder="请输入密码"
|
||||
autocomplete="current-password"
|
||||
size="large"
|
||||
show-password-on="click"
|
||||
@keyup.enter="doLogin"
|
||||
>
|
||||
<template #prefix><n-icon><Lock /></n-icon></template>
|
||||
</n-input>
|
||||
</n-form-item>
|
||||
<n-button type="primary" size="large" block class="primary" :loading="busy" @click="doLogin">
|
||||
<el-form class="form" label-position="top" @keyup.enter="doLogin">
|
||||
<el-form-item label="账号">
|
||||
<el-input v-model="account" placeholder="请输入账号" autocomplete="username" size="large"
|
||||
:prefix-icon="User" @keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码">
|
||||
<el-input v-model="password" type="password" placeholder="请输入密码" autocomplete="current-password"
|
||||
size="large" :prefix-icon="Lock" show-password @keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" size="large" class="primary" :loading="busy" @click="doLogin">
|
||||
{{ busy ? '登录中…' : '登 录' }}
|
||||
</n-button>
|
||||
</n-form>
|
||||
</el-button>
|
||||
</el-form>
|
||||
|
||||
<div class="foot">内网管理面 · 请使用管理员账号登录</div>
|
||||
</div>
|
||||
@@ -47,9 +31,9 @@
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { User, Lock } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminLogin } from '../api'
|
||||
import { store } from '../store.js'
|
||||
import { message } from '../naive'
|
||||
|
||||
const props = defineProps({ appName: { type: String, default: '37du 自动化工作台' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
@@ -71,7 +55,7 @@ async function doLogin() {
|
||||
store.token = r.token || ''
|
||||
store.isAdmin = true
|
||||
store.nickname = r.nickname || ''
|
||||
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) {}
|
||||
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) { }
|
||||
message.success(`欢迎,${store.nickname || acct}`)
|
||||
emit('ok', r)
|
||||
} catch (e) {
|
||||
@@ -90,37 +74,111 @@ async function doLogin() {
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
background: linear-gradient(180deg, #f7f8fa 0%, #eef0f4 100%);
|
||||
font-family: var(--font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif);
|
||||
}
|
||||
|
||||
.card {
|
||||
width: 380px;
|
||||
width: 404px;
|
||||
box-sizing: border-box;
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--cp-border, #e5e7ec);
|
||||
border-radius: 16px;
|
||||
padding: 34px 32px 28px;
|
||||
box-shadow: 0 16px 40px -24px rgba(30, 42, 76, .25);
|
||||
position: relative;
|
||||
background: var(--cp-panel);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 22px;
|
||||
padding: 40px 36px 28px;
|
||||
box-shadow: 0 26px 64px -30px rgba(35, 42, 58, .45);
|
||||
}
|
||||
|
||||
/* 顶部渐变描边 */
|
||||
.card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 30px;
|
||||
right: 30px;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, var(--cp-blue), var(--cp-teal), transparent);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* 纸面噪点质感 */
|
||||
.card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 22px;
|
||||
pointer-events: none;
|
||||
opacity: .5;
|
||||
background-image: radial-gradient(rgba(35, 42, 58, .08) 0.5px, transparent 0.5px);
|
||||
background-size: 5px 5px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-bottom: 30px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.brand { display: flex; align-items: center; gap: 14px; margin-bottom: 28px; }
|
||||
.logo {
|
||||
width: 42px; height: 42px; border-radius: 12px; flex: none;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff 0%, #22c7e8 130%);
|
||||
color: #fff; font-size: 15px; font-weight: 800; letter-spacing: .4px;
|
||||
box-shadow: 0 8px 18px -8px rgba(59, 108, 255, .55);
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
border-radius: 14px;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
position: relative;
|
||||
background: linear-gradient(135deg, var(--cp-blue) 0%, var(--cp-teal) 140%);
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .4px;
|
||||
box-shadow: 0 10px 22px -10px rgba(47, 92, 240, .6);
|
||||
}
|
||||
.brand-meta h1 { margin: 0; font-size: 17px; font-weight: 700; color: var(--cp-ink, #1c2433); letter-spacing: .2px; }
|
||||
.brand-meta p { margin: 3px 0 0; font-size: 12px; color: var(--cp-ink-3, #8a93a6); }
|
||||
|
||||
.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; }
|
||||
.logo::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 2px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, .3);
|
||||
}
|
||||
|
||||
.primary.n-button--primary-type { height: 44px; border-radius: 8px; font-size: 14px; letter-spacing: .1em; }
|
||||
.brand-meta h1 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
color: var(--cp-ink-1);
|
||||
letter-spacing: .2px;
|
||||
}
|
||||
|
||||
.foot { margin-top: 20px; text-align: center; font-size: 11.5px; color: var(--cp-ink-3, #8a93a6); }
|
||||
</style>
|
||||
.brand-meta p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--cp-ink-3);
|
||||
letter-spacing: .4px;
|
||||
}
|
||||
|
||||
.form { position: relative; }
|
||||
.form .el-form-item { margin-bottom: 20px; }
|
||||
.form .el-form-item__label { font-size: 12.5px; font-weight: 700; padding-bottom: 6px; }
|
||||
.form .el-input__wrapper { border-radius: 10px; }
|
||||
|
||||
.primary {
|
||||
width: 100%;
|
||||
height: 46px;
|
||||
border-radius: 12px;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .12em;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.foot {
|
||||
margin-top: 24px;
|
||||
text-align: center;
|
||||
font-size: 11.5px;
|
||||
color: var(--cp-ink-3);
|
||||
letter-spacing: .4px;
|
||||
position: relative;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
<template>
|
||||
<n-modal v-model:show="visible" preset="card" title="修改密码" :style="{ width: '420px' }" :bordered="false" @after-leave="reset">
|
||||
<n-alert v-if="store.current" type="info" :bordered="false" class="acct-tip">当前账号:{{ store.current }}</n-alert>
|
||||
<n-form ref="formRef" :model="form" :rules="rules" label-placement="top">
|
||||
<n-form-item label="原密码" path="oldPwd">
|
||||
<n-input v-model:value="form.oldPwd" type="password" show-password-on="click" placeholder="请输入原密码" />
|
||||
</n-form-item>
|
||||
<n-form-item label="新密码" path="newPwd">
|
||||
<n-input v-model:value="form.newPwd" type="password" show-password-on="click" placeholder="至少 6 位,不与原密码相同" />
|
||||
</n-form-item>
|
||||
<n-form-item label="确认新密码" path="newPwd2">
|
||||
<n-input v-model:value="form.newPwd2" type="password" show-password-on="click" placeholder="再次输入新密码" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close @closed="reset">
|
||||
<el-alert v-if="store.current" type="info" :closable="false" class="acct-tip" show-icon>
|
||||
当前账号:<b class="mono">{{ store.current }}</b>
|
||||
</el-alert>
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top">
|
||||
<el-form-item label="原密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" placeholder="请输入原密码" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" placeholder="至少 6 位,不与原密码相同" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" placeholder="再次输入新密码" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="visible = false">取消</n-button>
|
||||
<n-button type="primary" :loading="busy" @click="submit">保存</n-button>
|
||||
</n-space>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="submit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { reactive, ref } from 'vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const visible = defineModel({ type: Boolean, default: false })
|
||||
const formRef = ref()
|
||||
@@ -37,17 +39,17 @@ const rules = {
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码' },
|
||||
{ min: 6, message: '新密码至少 6 位' },
|
||||
{ validator: (_r, v) => (v && v === form.oldPwd ? new Error('新密码不能与原密码相同') : true), message: '新密码不能与原密码相同' },
|
||||
{ validator: (_r, v, cb) => (v && v === form.oldPwd ? cb(new Error('新密码不能与原密码相同')) : cb()), message: '新密码不能与原密码相同' },
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码' },
|
||||
{ validator: (_r, v) => (v !== form.newPwd ? new Error('两次输入的密码不一致') : true), message: '两次输入的密码不一致' },
|
||||
{ validator: (_r, v, cb) => (v !== form.newPwd ? cb(new Error('两次输入的密码不一致')) : cb()), message: '两次输入的密码不一致' },
|
||||
],
|
||||
}
|
||||
|
||||
function reset() {
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
formRef.value?.restoreValidation()
|
||||
formRef.value?.resetFields()
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
@@ -66,5 +68,6 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.acct-tip { margin-bottom: 14px; }
|
||||
.acct-tip { margin-bottom: 16px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// 时间展示格式化:统一去掉 ISO 的 T,隐藏秒,避免出现 "2026-09-16T12:34:40" 这类原始格式
|
||||
export function fmtTime(iso) {
|
||||
if (!iso) return '—'
|
||||
if (!iso.includes('T')) return iso // 后端已是空格分隔格式,原样返回
|
||||
return iso.replace('T', ' ').slice(0, 16) // ISO → YYYY-MM-DD HH:mm
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import naive from 'naive-ui'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件,与 UI 框架解耦)
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件)
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
@@ -10,4 +11,4 @@ const app = createApp(App)
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(naive).mount('#app')
|
||||
app.use(ElementPlus).mount('#app')
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
// Naive UI 主题与离散式反馈(message/dialog 无需 Provider 包裹即可调用)
|
||||
import { createDiscreteApi, zhCN, dateZhCN } from 'naive-ui'
|
||||
|
||||
export const themeOverrides = {
|
||||
common: {
|
||||
primaryColor: '#3b6cff',
|
||||
primaryColorHover: '#5e84ff',
|
||||
primaryColorPressed: '#2f56d6',
|
||||
primaryColorSuppl: '#4c79ff',
|
||||
infoColor: '#3b6cff',
|
||||
successColor: '#22b07a',
|
||||
warningColor: '#eab308',
|
||||
errorColor: '#e5484d',
|
||||
borderRadius: '10px',
|
||||
borderRadiusSmall: '8px',
|
||||
fontFamily:
|
||||
'"HarmonyOS Sans SC","Microsoft YaHei UI","PingFang SC",-apple-system,"Segoe UI",sans-serif',
|
||||
},
|
||||
Card: {
|
||||
borderRadius: '16px',
|
||||
},
|
||||
Button: {
|
||||
borderRadiusMedium: '10px',
|
||||
borderRadiusLarge: '12px',
|
||||
},
|
||||
Menu: {
|
||||
itemHeight: '46px',
|
||||
itemBorderRadius: '10px',
|
||||
itemTextColor: '#3a4660',
|
||||
itemTextColorHover: '#3b6cff',
|
||||
itemTextColorActive: '#3b6cff',
|
||||
itemTextColorActiveHover: '#2f56d6',
|
||||
itemColorHover: 'rgba(31, 45, 80, .05)',
|
||||
itemColorActive: 'rgba(59, 108, 255, .10)',
|
||||
itemColorActiveHover: 'rgba(59, 108, 255, .15)',
|
||||
iconColor: '#7b8aa8',
|
||||
iconColorHover: '#3b6cff',
|
||||
iconColorActive: '#3b6cff',
|
||||
iconColorActiveHover: '#2f56d6',
|
||||
},
|
||||
DataTable: {
|
||||
thColor: '#f5f8fe',
|
||||
thTextColor: '#5b6b8c',
|
||||
thFontWeight: '600',
|
||||
tdColor: 'transparent',
|
||||
tdColorHover: 'rgba(59,108,255,.06)',
|
||||
borderColor: 'rgba(88,113,183,.10)',
|
||||
borderRadius: '12px',
|
||||
},
|
||||
Dialog: {
|
||||
borderRadius: '16px',
|
||||
},
|
||||
}
|
||||
|
||||
export const { message, dialog, notification } = createDiscreteApi(
|
||||
['message', 'dialog', 'notification'],
|
||||
{
|
||||
configProviderProps: { themeOverrides, locale: zhCN, dateLocale: dateZhCN },
|
||||
}
|
||||
)
|
||||
|
||||
export { zhCN, dateZhCN }
|
||||
@@ -2,7 +2,7 @@ import { reactive, ref } from 'vue'
|
||||
import { adminOverview } from './api'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '37du 内网插件控制面',
|
||||
appName: '37du 插件管理平台',
|
||||
isAdmin: false,
|
||||
current: _get('cp_account'),
|
||||
token: _get('cp_token'),
|
||||
|
||||
@@ -1,16 +1,65 @@
|
||||
/* ============ 37du 内网插件控制面 全局基础样式(组件由 Naive UI 提供) ============ */
|
||||
/* ============================================================
|
||||
37du 插件管理平台 · 全局样式(Element Plus)
|
||||
设计语言:纸张 + 墨色 · 编辑部数据台
|
||||
- 暖白纸感画布 + 细网格底纹
|
||||
- 深墨色文字 + 钴蓝/琥珀强调色
|
||||
- 数字/ID/时间用等宽字体,营造精密仪表感
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* 设计令牌:文字 / 边框 / 表面 / 品牌色 / 投影 */
|
||||
--cp-ink: #141c33;
|
||||
--cp-ink-2: #5b6b8c;
|
||||
--cp-ink-3: #94a3c4;
|
||||
--cp-border: rgba(88, 113, 183, .14);
|
||||
--cp-surface: rgba(255, 255, 255, .82);
|
||||
--cp-blue: #3b6cff;
|
||||
--cp-cyan: #22c7e8;
|
||||
--cp-violet: #8b5cf6;
|
||||
--cp-card-shadow: 0 10px 30px -14px rgba(43, 64, 132, .20);
|
||||
--cp-card-shadow-hover: 0 18px 44px -18px rgba(59, 108, 255, .30);
|
||||
/* ---------- Element Plus 主题变量 ---------- */
|
||||
--el-color-primary: #2f5cf0;
|
||||
--el-color-primary-light-3: #7a96f5;
|
||||
--el-color-primary-light-5: #a5b9f9;
|
||||
--el-color-primary-light-7: #cfdbfc;
|
||||
--el-color-primary-light-8: #e3eafd;
|
||||
--el-color-primary-light-9: #f1f5fe;
|
||||
--el-color-primary-dark-2: #2246c0;
|
||||
--el-color-success: #1d9d5c;
|
||||
--el-color-warning: #d97706;
|
||||
--el-color-danger: #d6453d;
|
||||
--el-color-error: #d6453d;
|
||||
--el-color-info: #7a8398;
|
||||
--el-bg-color: #fffdf8;
|
||||
--el-bg-color-overlay: #fffdf8;
|
||||
--el-bg-color-page: #f3f0e8;
|
||||
--el-fill-color-blank: #fffdf8;
|
||||
--el-fill-color: rgba(35, 42, 58, .08);
|
||||
--el-fill-color-light: rgba(35, 42, 58, .06);
|
||||
--el-fill-color-lighter: rgba(35, 42, 58, .04);
|
||||
--el-fill-color-extra-light: rgba(35, 42, 58, .03);
|
||||
--el-text-color-primary: #232a3a;
|
||||
--el-text-color-regular: #3b4358;
|
||||
--el-text-color-secondary: #6b7488;
|
||||
--el-text-color-placeholder: #9aa2b4;
|
||||
--el-text-color-disabled: #b9bfcc;
|
||||
--el-border-color: rgba(35, 42, 58, .16);
|
||||
--el-border-color-light: rgba(35, 42, 58, .12);
|
||||
--el-border-color-lighter: rgba(35, 42, 58, .10);
|
||||
--el-border-color-extra-light: rgba(35, 42, 58, .07);
|
||||
--el-border-radius-base: 10px;
|
||||
--el-border-radius-small: 8px;
|
||||
--el-box-shadow-light: 0 14px 34px -20px rgba(35, 42, 58, .28);
|
||||
--el-mask-color: rgba(20, 26, 40, .45);
|
||||
|
||||
/* ---------- 设计令牌 ---------- */
|
||||
--cp-bg: #f3f0e8; /* 纸感画布 */
|
||||
--cp-ink-1: #232a3a; /* 主墨色(标题) */
|
||||
--cp-ink: #3b4358; /* 正文 */
|
||||
--cp-ink-2: #6b7488; /* 次要文字 */
|
||||
--cp-ink-3: #9aa2b4; /* 弱化文字 */
|
||||
--cp-line: rgba(35, 42, 58, .12);
|
||||
--cp-line-strong: rgba(35, 42, 58, .22);
|
||||
--cp-panel: #fffdf8; /* 纸白面板 */
|
||||
--cp-panel-2: #faf7ee; /* 次级面板(轨道/底色) */
|
||||
--cp-blue: #2f5cf0;
|
||||
--cp-teal: #0f9f9b;
|
||||
--cp-amber: #d97706;
|
||||
--cp-success: #1d9d5c;
|
||||
--cp-danger: #d6453d;
|
||||
--cp-mono: ui-monospace, "Cascadia Code", "JetBrains Mono", Consolas, "Courier New", monospace;
|
||||
--cp-shadow: 0 14px 34px -22px rgba(35, 42, 58, .28);
|
||||
--cp-shadow-hover: 0 20px 44px -22px rgba(47, 92, 240, .30);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -21,57 +70,219 @@ body {
|
||||
font-size: 13px;
|
||||
color: var(--cp-ink);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
background-color: #eaf0fb;
|
||||
/* 浅色极光画布:三层低透明光晕 + 渐变底 */
|
||||
background-color: var(--cp-bg);
|
||||
/* 纸感画布:暖白底 + 低透明细网格 + 两侧轻微墨晕 */
|
||||
background-image:
|
||||
radial-gradient(1100px 520px at 88% -10%, rgba(59, 108, 255, .14), transparent 60%),
|
||||
radial-gradient(900px 480px at -8% 108%, rgba(34, 199, 232, .12), transparent 55%),
|
||||
radial-gradient(760px 420px at 55% 118%, rgba(139, 92, 246, .10), transparent 60%),
|
||||
linear-gradient(180deg, #f4f7fd 0%, #e9eefb 100%);
|
||||
radial-gradient(900px 420px at 90% -8%, rgba(47, 92, 240, .07), transparent 62%),
|
||||
radial-gradient(760px 400px at -6% 104%, rgba(15, 159, 155, .06), transparent 58%),
|
||||
linear-gradient(rgba(35, 42, 58, .035) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(35, 42, 58, .035) 1px, transparent 1px);
|
||||
background-size: auto, auto, 44px 44px, 44px 44px;
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
::selection { background: rgba(59, 108, 255, .18); }
|
||||
::selection { background: rgba(47, 92, 240, .16); }
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #c8d2e8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #b3c0de; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-thumb { background: rgba(35, 42, 58, .22); border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: rgba(35, 42, 58, .34); background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* ---------- Naive 组件统一质感 ---------- */
|
||||
.n-card {
|
||||
--n-border-color: var(--cp-border);
|
||||
--n-color: rgba(255, 255, 255, .82);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
/* ============================================================
|
||||
Element Plus 组件质感覆盖
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 按钮 ---------- */
|
||||
.el-button {
|
||||
--el-button-bg-color: #fffdf8;
|
||||
--el-button-border-color: rgba(35, 42, 58, .20);
|
||||
--el-button-text-color: var(--cp-ink);
|
||||
--el-button-hover-bg-color: #fff;
|
||||
--el-button-hover-border-color: var(--cp-blue);
|
||||
--el-button-hover-text-color: var(--cp-blue);
|
||||
--el-button-active-bg-color: #eef2fe;
|
||||
--el-button-active-border-color: var(--cp-blue);
|
||||
--el-button-active-text-color: var(--cp-blue);
|
||||
font-weight: 600;
|
||||
}
|
||||
.n-data-table {
|
||||
--n-border-color: rgba(88, 113, 183, .10);
|
||||
.el-button--primary {
|
||||
--el-button-bg-color: var(--cp-blue);
|
||||
--el-button-border-color: var(--cp-blue);
|
||||
--el-button-text-color: #fff;
|
||||
--el-button-hover-bg-color: #5579f3;
|
||||
--el-button-hover-border-color: #5579f3;
|
||||
--el-button-hover-text-color: #fff;
|
||||
--el-button-active-bg-color: #2246c0;
|
||||
--el-button-active-border-color: #2246c0;
|
||||
--el-button-active-text-color: #fff;
|
||||
box-shadow: 0 8px 18px -10px rgba(47, 92, 240, .55);
|
||||
}
|
||||
.el-button--danger {
|
||||
--el-button-bg-color: var(--cp-danger);
|
||||
--el-button-border-color: var(--cp-danger);
|
||||
--el-button-text-color: #fff;
|
||||
--el-button-hover-bg-color: #e26860;
|
||||
--el-button-hover-border-color: #e26860;
|
||||
--el-button-hover-text-color: #fff;
|
||||
--el-button-active-bg-color: #b33831;
|
||||
--el-button-active-border-color: #b33831;
|
||||
--el-button-active-text-color: #fff;
|
||||
}
|
||||
|
||||
/* ---------- 共享页面工具类 ---------- */
|
||||
.page { max-width: 1280px; margin: 0 auto; }
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 18px; }
|
||||
.page-head h3 { margin: 0 0 6px; font-size: 20px; font-weight: 700; letter-spacing: .2px; color: var(--cp-ink); display: flex; align-items: center; gap: 10px; }
|
||||
/* ---------- 输入类 ---------- */
|
||||
.el-input__wrapper,
|
||||
.el-select__wrapper {
|
||||
--el-input-border-color: rgba(35, 42, 58, .20);
|
||||
--el-input-hover-border-color: var(--cp-blue);
|
||||
--el-input-focus-border-color: var(--cp-blue);
|
||||
box-shadow: 0 0 0 1px rgba(35, 42, 58, .18) inset;
|
||||
background: #fffdf8;
|
||||
}
|
||||
.el-input__wrapper.is-focus,
|
||||
.el-select__wrapper.is-focused { box-shadow: 0 0 0 1px var(--cp-blue) inset, 0 0 0 3px rgba(47, 92, 240, .12); }
|
||||
.el-textarea__inner { background: #fffdf8; box-shadow: 0 0 0 1px rgba(35, 42, 58, .18) inset; }
|
||||
.el-textarea__inner:focus { box-shadow: 0 0 0 1px var(--cp-blue) inset, 0 0 0 3px rgba(47, 92, 240, .12); }
|
||||
|
||||
/* ---------- 卡片 ---------- */
|
||||
.el-card {
|
||||
--el-card-bg-color: var(--cp-panel);
|
||||
--el-card-border-color: var(--cp-line);
|
||||
--el-card-border-radius: 16px;
|
||||
border: 1px solid var(--cp-line);
|
||||
box-shadow: var(--cp-shadow);
|
||||
transition: box-shadow .22s ease, transform .22s ease;
|
||||
}
|
||||
.el-card:hover { box-shadow: var(--cp-shadow-hover); }
|
||||
|
||||
/* ---------- 表格 ---------- */
|
||||
.el-table {
|
||||
--el-table-border-color: rgba(35, 42, 58, .08);
|
||||
--el-table-header-bg-color: #f6f2e7;
|
||||
--el-table-header-text-color: var(--cp-ink-2);
|
||||
--el-table-row-hover-bg-color: rgba(47, 92, 240, .05);
|
||||
--el-table-bg-color: transparent;
|
||||
--el-table-tr-bg-color: transparent;
|
||||
--el-table-expanded-cell-bg-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
.el-table th.el-table__cell {
|
||||
font-weight: 700;
|
||||
font-size: 12px;
|
||||
letter-spacing: .4px;
|
||||
}
|
||||
.el-table .el-table__cell { padding: 9px 0; }
|
||||
.el-table__inner-wrapper::before { display: none; }
|
||||
.el-table--border .el-table__inner-wrapper::after { display: none; }
|
||||
|
||||
/* ---------- 标签 ---------- */
|
||||
.el-tag { font-weight: 600; }
|
||||
.el-tag--primary { --el-tag-bg-color: rgba(47,92,240,.10); --el-tag-border-color: rgba(47,92,240,.22); --el-tag-text-color: var(--cp-blue); }
|
||||
.el-tag--success { --el-tag-bg-color: rgba(29,157,92,.10); --el-tag-border-color: rgba(29,157,92,.24); --el-tag-text-color: #15803d; }
|
||||
.el-tag--warning { --el-tag-bg-color: rgba(217,119,6,.10); --el-tag-border-color: rgba(217,119,6,.24); --el-tag-text-color: var(--cp-amber); }
|
||||
.el-tag--danger { --el-tag-bg-color: rgba(214,69,61,.10); --el-tag-border-color: rgba(214,69,61,.24); --el-tag-text-color: var(--cp-danger); }
|
||||
.el-tag--info { --el-tag-bg-color: rgba(35,42,58,.06); --el-tag-border-color: rgba(35,42,58,.14); --el-tag-text-color: var(--cp-ink-2); }
|
||||
|
||||
/* ---------- 弹窗 / 浮层 ---------- */
|
||||
.el-dialog {
|
||||
--el-dialog-bg-color: var(--cp-panel);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 24px 60px -24px rgba(35, 42, 58, .4);
|
||||
}
|
||||
.el-dialog__header { padding-bottom: 14px; border-bottom: 1px solid var(--cp-line); }
|
||||
.el-dialog__title { font-weight: 800; color: var(--cp-ink-1); }
|
||||
.el-popper.is-light { background: var(--cp-panel); border-color: var(--cp-line); }
|
||||
.el-select-dropdown, .el-dropdown__popper { background: var(--cp-panel); }
|
||||
.el-select-dropdown__item.is-hovering { background: rgba(47, 92, 240, .08); }
|
||||
.el-select-dropdown__item.is-selected { color: var(--cp-blue); font-weight: 700; }
|
||||
|
||||
/* ---------- 开关 / 复选 / 单选 ---------- */
|
||||
.el-switch { --el-switch-on-color: var(--cp-blue); }
|
||||
.el-checkbox { --el-checkbox-checked-bg-color: var(--cp-blue); --el-checkbox-checked-input-border-color: var(--cp-blue); --el-checkbox-input-border-color: rgba(35,42,58,.3); --el-checkbox-text-color: var(--cp-ink); }
|
||||
.el-checkbox__label { font-weight: 500; }
|
||||
|
||||
/* ---------- 表单 ---------- */
|
||||
.el-form-item__label { font-weight: 600; color: var(--cp-ink-2); }
|
||||
|
||||
/* ---------- 标签页 ---------- */
|
||||
.el-tabs__item { font-weight: 600; color: var(--cp-ink-2); }
|
||||
.el-tabs__item.is-active { color: var(--cp-blue); }
|
||||
.el-tabs__active-bar { background-color: var(--cp-blue); height: 3px; border-radius: 2px; }
|
||||
|
||||
/* ---------- 消息 / 提示 ---------- */
|
||||
.el-message { background: var(--cp-panel); border-color: var(--cp-line); box-shadow: var(--cp-shadow); }
|
||||
.el-message-box { background: var(--cp-panel); border: 1px solid var(--cp-line); border-radius: 16px; }
|
||||
|
||||
/* ---------- 空态 / 骨架 ---------- */
|
||||
.el-empty__description p { color: var(--cp-ink-3); }
|
||||
.el-skeleton { --el-skeleton-color: rgba(35,42,58,.06); --el-skeleton-to-color: rgba(35,42,58,.10); }
|
||||
|
||||
/* ---------- 菜单 ---------- */
|
||||
.el-menu { border-right: none !important; background: transparent; }
|
||||
|
||||
/* ============================================================
|
||||
共享页面工具类
|
||||
============================================================ */
|
||||
.page { max-width: 1400px; margin: 0 auto; }
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 20px; }
|
||||
.page-head h3 {
|
||||
margin: 0 0 6px; font-size: 22px; font-weight: 800; letter-spacing: .3px;
|
||||
color: var(--cp-ink-1); display: flex; align-items: center; gap: 12px;
|
||||
}
|
||||
.page-head h3 .badge {
|
||||
font-size: 11px; font-weight: 600; color: var(--cp-blue); letter-spacing: .6px;
|
||||
background: rgba(59, 108, 255, .10); border: 1px solid rgba(59, 108, 255, .18);
|
||||
padding: 2px 9px; border-radius: 20px;
|
||||
font-size: 10.5px; font-weight: 700; color: var(--cp-blue); letter-spacing: 1px;
|
||||
font-family: var(--cp-mono); text-transform: uppercase;
|
||||
background: rgba(47, 92, 240, .08); border: 1px solid rgba(47, 92, 240, .2);
|
||||
padding: 3px 10px; border-radius: 20px;
|
||||
}
|
||||
.page-head p { margin: 0; font-size: 12.5px; color: var(--cp-ink-3); }
|
||||
.block { margin-bottom: 16px; }
|
||||
.page-head p { margin: 0; font-size: 12.5px; color: var(--cp-ink-3); letter-spacing: .2px; }
|
||||
.block { margin-bottom: 18px; }
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.who { color: var(--cp-blue); font-weight: 600; }
|
||||
.who { color: var(--cp-blue); font-weight: 700; }
|
||||
|
||||
/* 卡片标题前的小渐变竖条 */
|
||||
.card-title { font-size: 15px; font-weight: 700; color: var(--cp-ink); display: flex; align-items: center; gap: 8px; }
|
||||
.card-title::before { content: ''; width: 4px; height: 14px; border-radius: 3px; background: linear-gradient(180deg, #3b6cff, #22c7e8); }
|
||||
/* 面板卡片 */
|
||||
.cp-card {
|
||||
position: relative;
|
||||
background: var(--cp-panel);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--cp-shadow);
|
||||
transition: box-shadow .22s ease, transform .22s ease;
|
||||
}
|
||||
.cp-card:hover { box-shadow: var(--cp-shadow-hover); }
|
||||
/* 卡片顶部渐变发丝线 */
|
||||
.cp-card::before {
|
||||
content: ''; position: absolute; top: 0; left: 22px; right: 22px; height: 1px;
|
||||
background: linear-gradient(90deg, transparent, rgba(47, 92, 240, .45), rgba(15, 159, 155, .45), transparent);
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
/* 表格单元格通用 */
|
||||
.cell-strong { font-weight: 700; color: var(--cp-ink); }
|
||||
/* 小标题(带竖线标记) */
|
||||
.card-title {
|
||||
font-size: 14px; font-weight: 800; color: var(--cp-ink-1);
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
}
|
||||
.card-title::before {
|
||||
content: ''; width: 4px; height: 14px; border-radius: 2px;
|
||||
background: linear-gradient(180deg, var(--cp-blue), var(--cp-teal));
|
||||
}
|
||||
|
||||
/* 等宽数字(ID / 时间 / 统计值) */
|
||||
.mono { font-family: var(--cp-mono); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* 表格列通用 */
|
||||
.cell-strong { font-weight: 700; color: var(--cp-ink-1); }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
|
||||
/* 表格列内 render 的动态节点(不继承 scoped,全局生效) */
|
||||
.acct { line-height: 1.3; }
|
||||
.acct .ann { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); }
|
||||
.acct .anick { font-size: 11px; color: var(--cp-ink-3); }
|
||||
|
||||
/* 状态圆点 */
|
||||
.status-dot { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.status-dot i { width: 7px; height: 7px; border-radius: 50%; display: inline-block; }
|
||||
|
||||
/* ---------- 动效 ---------- */
|
||||
@keyframes cp-rise { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
|
||||
.cp-rise { animation: cp-rise .5s cubic-bezier(.22, .61, .36, 1) both; }
|
||||
|
||||
@@ -5,123 +5,149 @@
|
||||
<h3>账号管理 <span class="badge">Accounts</span></h3>
|
||||
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||
</div>
|
||||
<n-space :size="10">
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<n-button type="primary" @click="openCreate">
|
||||
<template #icon><n-icon><Plus /></n-icon></template>新建账号
|
||||
</n-button>
|
||||
</n-space>
|
||||
<div class="head-acts">
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建账号</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-card class="cp-rise" :bordered="false">
|
||||
<n-data-table
|
||||
:columns="columns"
|
||||
:data="accounts"
|
||||
:loading="overviewBusy"
|
||||
:row-key="r => r.account"
|
||||
:single-line="false"
|
||||
/>
|
||||
</n-card>
|
||||
<!-- 账号卡片 -->
|
||||
<div class="acct-grid" v-if="accounts.length">
|
||||
<div class="acct-card cp-card cp-rise" v-for="(a, i) in accounts" :key="a.account" :style="{ animationDelay: i * 40 + 'ms' }">
|
||||
<div class="acct-top">
|
||||
<div class="avatar-wrap">
|
||||
<img v-if="a.avatar" :src="`/api/avatar/${a.account}?v=${encodeURIComponent(a.avatar)}`" class="avatar"
|
||||
@error="e => e.target.style.display = 'none'" />
|
||||
<span v-else class="avatar avatar-fallback">{{ (a.nickname || a.account || '?')[0].toUpperCase() }}</span>
|
||||
<el-tooltip content="上传头像" placement="top">
|
||||
<span class="avatar-edit" @click="pickAvatar(a)"><el-icon><Camera /></el-icon></span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
<div class="acct-id">
|
||||
<div class="id-row">
|
||||
<span class="acct-account mono">{{ a.account }}</span>
|
||||
<el-tag v-if="a.is_admin" size="small" type="primary" round effect="light">管理员</el-tag>
|
||||
</div>
|
||||
<div class="acct-nick">{{ a.nickname || '未设置昵称' }}</div>
|
||||
</div>
|
||||
<div class="acct-actions">
|
||||
<el-tooltip content="重置密码"><el-button link type="primary" :icon="EditPen" @click="resetPwd(a)" /></el-tooltip>
|
||||
<el-tooltip content="编辑资料"><el-button link type="info" :icon="Edit" @click="openEdit(a)" /></el-tooltip>
|
||||
<el-tooltip content="删除账号"><el-button link type="danger" :icon="Delete" :disabled="a.account === current" @click="delAccount(a)" /></el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="acct-tags">
|
||||
<span class="tag-label">状态</span>
|
||||
<el-switch size="small" :model-value="!!a.status" :disabled="a.account === current"
|
||||
:loading="busySwitch === a.account" @change="v => toggleStatus(a, v)" />
|
||||
<el-tag v-if="a.dept" size="small" type="info" effect="plain" round>{{ a.dept }}</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="acct-tags" v-if="a.plugins?.length">
|
||||
<span class="tag-label">插件</span>
|
||||
<el-tag v-for="p in a.plugins.slice(0, 3)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||
<span v-if="a.plugins.length > 3" class="more mono">+{{ a.plugins.length - 3 }}</span>
|
||||
</div>
|
||||
<div class="acct-tags" v-else>
|
||||
<span class="tag-label">插件</span>
|
||||
<span class="dim">未授权</span>
|
||||
</div>
|
||||
|
||||
<div class="acct-tags" v-if="a.platforms?.length">
|
||||
<span class="tag-label">平台</span>
|
||||
<el-tag v-for="pf in a.platforms" :key="pf" size="small" type="success" effect="light" round>{{ pf }}</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="acct-foot">
|
||||
<span class="mono created dim-sm">创建于 {{ fmtTime(a.created_at) }}</span>
|
||||
<span class="mono uid dim-sm">ID {{ a.id ?? '—' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else-if="!overviewBusy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||
|
||||
<!-- 新建账号 -->
|
||||
<n-modal v-model:show="createOpen" preset="card" title="新建账号" :style="{ width: '420px' }" :bordered="false" @after-leave="resetCreate">
|
||||
<n-form ref="formRef" :model="form" :rules="rules" label-placement="top">
|
||||
<n-form-item label="账号" path="account">
|
||||
<n-input v-model:value="form.account" placeholder="登录账号" />
|
||||
</n-form-item>
|
||||
<n-form-item label="昵称">
|
||||
<n-input v-model:value="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</n-form-item>
|
||||
<n-form-item label="初始密码" path="password">
|
||||
<n-input v-model:value="form.password" type="password" show-password-on="click" placeholder="至少 6 位" />
|
||||
</n-form-item>
|
||||
<n-form-item label="部门">
|
||||
<n-input v-model:value="form.dept" placeholder="如 财务部 / IT" />
|
||||
</n-form-item>
|
||||
<n-form-item label="管理员">
|
||||
<n-switch v-model:value="form.is_admin" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<el-dialog v-model="createOpen" title="新建账号" width="440px" align-center destroy-on-close @closed="resetCreate">
|
||||
<el-form ref="createFormRef" :model="form" :rules="rules" label-position="top">
|
||||
<el-form-item label="账号" prop="account">
|
||||
<el-input v-model="form.account" placeholder="登录账号" />
|
||||
</el-form-item>
|
||||
<el-form-item label="昵称">
|
||||
<el-input v-model="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="初始密码" prop="password">
|
||||
<el-input v-model="form.password" type="password" placeholder="至少 6 位" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-input v-model="form.dept" placeholder="如 财务部 / IT" />
|
||||
</el-form-item>
|
||||
<el-form-item label="管理员">
|
||||
<el-switch v-model="form.is_admin" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="createOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="creating" @click="createAccount">建号</n-button>
|
||||
</n-space>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="createOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="creating" @click="createAccount">建号</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 编辑资料 -->
|
||||
<el-dialog v-model="editOpen" title="编辑账号资料" width="420px" align-center destroy-on-close>
|
||||
<el-form :model="editForm" label-position="top">
|
||||
<el-form-item label="账号">
|
||||
<el-input :model-value="editTarget" disabled class="mono" />
|
||||
</el-form-item>
|
||||
<el-form-item label="昵称">
|
||||
<el-input v-model="editForm.nickname" placeholder="真实姓名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-input v-model="editForm.dept" placeholder="如 财务部 / IT" />
|
||||
</el-form-item>
|
||||
<el-form-item label="管理员">
|
||||
<el-switch v-model="editForm.is_admin" :disabled="editTarget === current" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="editOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="savingEdit" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 重置密码 -->
|
||||
<n-modal v-model:show="resetOpen" preset="card" title="重置密码" :style="{ width: '400px' }" :bordered="false">
|
||||
<n-alert v-if="resetTarget" type="info" :bordered="false" style="margin-bottom: 14px">
|
||||
为账号 <b>{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
</n-alert>
|
||||
<n-input v-model:value="resetPwdVal" type="password" show-password-on="click" placeholder="新密码(至少 6 位)" @keydown.enter="confirmReset" />
|
||||
<el-dialog v-model="resetOpen" title="重置密码" width="420px" align-center destroy-on-close>
|
||||
<el-alert type="info" :closable="false" class="reset-tip" show-icon>
|
||||
为账号 <b class="mono">{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
</el-alert>
|
||||
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 6 位)" show-password @keyup.enter="confirmReset" />
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="resetOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="resetting" @click="confirmReset">确认重置</n-button>
|
||||
</n-space>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="resetOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="resetting" @click="confirmReset">确认重置</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { NButton, NInput, NSwitch, NTag } from 'naive-ui'
|
||||
import { Refresh, Plus } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, Plus, Camera, EditPen, Edit, Delete } from '@element-plus/icons-vue'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||
import { message, dialog } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
const busySwitch = ref('')
|
||||
|
||||
// ---------- 部门 / 昵称 行内编辑 ----------
|
||||
const editing = ref('') // 正在编辑的账号
|
||||
const editField = ref('') // 'dept' | 'nickname'
|
||||
const editDraft = ref('')
|
||||
function startEdit(row, field) {
|
||||
if (row.account === current.value) return
|
||||
editing.value = row.account
|
||||
editField.value = field
|
||||
editDraft.value = row[field] || ''
|
||||
}
|
||||
async function saveEdit(row) {
|
||||
if (editing.value !== row.account) return
|
||||
const field = editField.value
|
||||
editing.value = ''
|
||||
const val = (editDraft.value || '').trim()
|
||||
if (val === (row[field] || '')) return
|
||||
try {
|
||||
await adminAccountUpdate({ account: row.account, [field]: val })
|
||||
message.success(`已更新 ${row.account} 的${field === 'nickname' ? '昵称' : '部门'}`)
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
function inlineInput(row, field) {
|
||||
if (row.account === editing.value && editField.value === field) {
|
||||
return h(NInput, {
|
||||
value: editDraft.value,
|
||||
size: 'small',
|
||||
style: 'width: 140px',
|
||||
onUpdateValue: v => (editDraft.value = v),
|
||||
onKeyup: (e) => { if (e.key === 'Enter') saveEdit(row) },
|
||||
onBlur: () => saveEdit(row),
|
||||
})
|
||||
}
|
||||
return h('span', { class: 'dept', onClick: () => startEdit(row, field) },
|
||||
row[field] || '—')
|
||||
}
|
||||
async function toggleAdmin(row) {
|
||||
try { await adminAccountUpdate({ account: row.account, is_admin: !row.is_admin }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
async function toggleStatus(row, v) {
|
||||
if (row.account === current.value && !v) { message.warning('不能停用当前登录的账号'); return }
|
||||
try { await adminAccountUpdate({ account: row.account, status: v }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
// ---------- 头像(显示 + 上传) ----------
|
||||
@@ -131,83 +157,32 @@ const _fileInput = (() => {
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar(row) {
|
||||
function pickAvatar(a) {
|
||||
_fileInput.onchange = async () => {
|
||||
const f = _fileInput.files && _fileInput.files[0]
|
||||
_fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
await adminAvatarUpload(row.account, f)
|
||||
message.success(`已更新 ${row.account} 的头像`)
|
||||
await adminAvatarUpload(a.account, f)
|
||||
message.success(`已更新 ${a.account} 的头像`)
|
||||
await refresh()
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
_fileInput.click()
|
||||
}
|
||||
function avatarCell(row) {
|
||||
const img = row.avatar
|
||||
? h('img', {
|
||||
src: `/api/avatar/${row.account}?v=${encodeURIComponent(row.avatar)}`,
|
||||
class: 'cell-avatar',
|
||||
onError: (e) => { e.target.style.display = 'none' },
|
||||
})
|
||||
: h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'cell-avatar-wrap' }, [
|
||||
img,
|
||||
h(NButton, { text: true, size: 'tiny', type: 'primary', onClick: () => pickAvatar(row) }, { default: () => '上传' }),
|
||||
])
|
||||
}
|
||||
|
||||
function renderTags(list, kind) {
|
||||
if (!list || !list.length) return h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'tags' }, list.map(t => h(NTag, {
|
||||
size: 'small', round: true, bordered: false,
|
||||
type: kind === 'platform' ? 'success' : 'primary',
|
||||
}, { default: () => t })))
|
||||
async function toggleStatus(a, v) {
|
||||
if (a.account === current.value && !v) { message.warning('不能停用当前登录的账号'); return }
|
||||
busySwitch.value = a.account
|
||||
try { await adminAccountUpdate({ account: a.account, status: v }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
finally { busySwitch.value = '' }
|
||||
}
|
||||
|
||||
const columns = computed(() => [
|
||||
{ title: 'ID', key: 'id', width: 64, render: r => h('span', { class: 'dim' }, r.id ?? '—') },
|
||||
{ title: '用户名(工号)', key: 'account', width: 130, render: r => h('b', { class: 'cell-strong' }, r.account) },
|
||||
{ title: '昵称(姓名)', key: 'nickname', width: 130, render: r => inlineInput(r, 'nickname') },
|
||||
{ title: '部门', key: 'dept', width: 130, render: (row) => inlineInput(row, 'dept') },
|
||||
{ title: '头像', key: 'avatar', width: 120, render: r => avatarCell(r) },
|
||||
{
|
||||
title: '状态', key: 'status', width: 90,
|
||||
render: (row) => h(NSwitch, {
|
||||
value: !!row.status,
|
||||
disabled: row.account === current.value,
|
||||
onUpdateValue: (v) => toggleStatus(row, v),
|
||||
}),
|
||||
},
|
||||
{ title: '创建时间', key: 'created_at', width: 150, render: r => h('span', { class: 'dim' }, r.created_at || '—') },
|
||||
{
|
||||
title: '管理员', key: 'is_admin', width: 90,
|
||||
render: (row) => h(NSwitch, {
|
||||
value: !!row.is_admin,
|
||||
disabled: row.account === current.value,
|
||||
onUpdateValue: () => toggleAdmin(row),
|
||||
}),
|
||||
},
|
||||
{ title: '已授权插件', key: 'plugins', minWidth: 160, render: r => renderTags(r.plugins, 'plugin') },
|
||||
{ title: '已授权平台', key: 'platforms', minWidth: 130, render: r => renderTags(r.platforms, 'platform') },
|
||||
{
|
||||
title: '操作', key: 'actions', width: 170,
|
||||
render: (row) => h('div', { class: 'ops' }, [
|
||||
h(NButton, { text: true, type: 'primary', onClick: () => resetPwd(row) }, { default: () => '重置密码' }),
|
||||
h(NButton, {
|
||||
text: true, type: 'error',
|
||||
disabled: row.account === current.value,
|
||||
onClick: () => delAccount(row),
|
||||
}, { default: () => '删除' }),
|
||||
]),
|
||||
},
|
||||
])
|
||||
|
||||
// ---------- 新建账号 ----------
|
||||
const createOpen = ref(false)
|
||||
const creating = ref(false)
|
||||
const formRef = ref()
|
||||
const createFormRef = ref()
|
||||
const form = reactive({ account: '', password: '', dept: '', nickname: '', is_admin: false })
|
||||
const rules = {
|
||||
account: { required: true, message: '请输入账号' },
|
||||
@@ -220,10 +195,10 @@ function openCreate() { createOpen.value = true }
|
||||
function resetCreate() {
|
||||
form.account = form.password = form.dept = form.nickname = ''
|
||||
form.is_admin = false
|
||||
formRef.value?.restoreValidation()
|
||||
createFormRef.value?.resetFields()
|
||||
}
|
||||
async function createAccount() {
|
||||
try { await formRef.value.validate() } catch (_) { return }
|
||||
try { await createFormRef.value.validate() } catch (_) { return }
|
||||
creating.value = true
|
||||
try {
|
||||
await adminAccountCreate({ ...form, account: form.account.trim() })
|
||||
@@ -234,13 +209,36 @@ async function createAccount() {
|
||||
finally { creating.value = false }
|
||||
}
|
||||
|
||||
// ---------- 编辑资料 ----------
|
||||
const editOpen = ref(false)
|
||||
const savingEdit = ref(false)
|
||||
const editTarget = ref('')
|
||||
const editForm = reactive({ nickname: '', dept: '', is_admin: false })
|
||||
function openEdit(a) {
|
||||
editTarget.value = a.account
|
||||
editForm.nickname = a.nickname || ''
|
||||
editForm.dept = a.dept || ''
|
||||
editForm.is_admin = !!a.is_admin
|
||||
editOpen.value = true
|
||||
}
|
||||
async function saveEdit() {
|
||||
savingEdit.value = true
|
||||
try {
|
||||
await adminAccountUpdate({ account: editTarget.value, nickname: editForm.nickname, dept: editForm.dept, is_admin: editForm.is_admin })
|
||||
message.success(`已更新 ${editTarget.value}`)
|
||||
editOpen.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
finally { savingEdit.value = false }
|
||||
}
|
||||
|
||||
// ---------- 重置密码 ----------
|
||||
const resetOpen = ref(false)
|
||||
const resetTarget = ref('')
|
||||
const resetPwdVal = ref('')
|
||||
const resetting = ref(false)
|
||||
function resetPwd(row) {
|
||||
resetTarget.value = row.account
|
||||
function resetPwd(a) {
|
||||
resetTarget.value = a.account
|
||||
resetPwdVal.value = ''
|
||||
resetOpen.value = true
|
||||
}
|
||||
@@ -256,34 +254,75 @@ async function confirmReset() {
|
||||
finally { resetting.value = false }
|
||||
}
|
||||
|
||||
function delAccount(row) {
|
||||
dialog.warning({
|
||||
title: '删除账号',
|
||||
content: `确认删除账号 ${row.account}?其插件授权将一并清除`,
|
||||
positiveText: '删除',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
try { await adminAccountDelete({ account: row.account }); message.success(`已删除 ${row.account}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
},
|
||||
})
|
||||
function delAccount(a) {
|
||||
dialog.confirm(`确认删除账号 ${a.account}?其插件授权将一并清除`, '删除账号', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
}).then(async () => {
|
||||
try { await adminAccountDelete({ account: a.account }); message.success(`已删除 ${a.account}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dept { cursor: pointer; border-bottom: 1px dashed transparent; transition: border-color .15s; }
|
||||
.dept:hover { color: var(--cp-blue); border-bottom-color: rgba(59, 108, 255, .4); }
|
||||
</style>
|
||||
.head-acts { display: flex; gap: 10px; }
|
||||
|
||||
<!-- 列 render 中由 naive-ui 动态渲染的节点不继承 scoped scopeId,须用全局样式 -->
|
||||
<style>
|
||||
.ops { display: flex; align-items: center; gap: 16px; }
|
||||
.ops .n-button { padding: 0 4px; }
|
||||
.cell-avatar-wrap { display: flex; align-items: center; gap: 8px; }
|
||||
.cell-avatar { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; background: #f2f3f7; flex: none; }
|
||||
.acct-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.acct-card {
|
||||
padding: 20px;
|
||||
display: flex; flex-direction: column; gap: 12px;
|
||||
}
|
||||
.acct-top { display: flex; align-items: center; gap: 14px; }
|
||||
|
||||
.avatar-wrap { position: relative; flex-shrink: 0; }
|
||||
.avatar {
|
||||
width: 52px; height: 52px; border-radius: 16px; object-fit: cover;
|
||||
display: block; box-shadow: 0 6px 14px -8px rgba(35, 42, 58, .4);
|
||||
}
|
||||
.avatar-fallback {
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff; font-size: 20px; font-weight: 800;
|
||||
}
|
||||
.avatar-edit {
|
||||
position: absolute; right: -6px; bottom: -6px;
|
||||
width: 22px; height: 22px; border-radius: 8px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--cp-panel); border: 1px solid var(--cp-line-strong);
|
||||
color: var(--cp-ink-2); cursor: pointer;
|
||||
transition: all .18s;
|
||||
}
|
||||
.avatar-edit:hover { color: var(--cp-blue); border-color: var(--cp-blue); background: rgba(47, 92, 240, .06); }
|
||||
|
||||
.acct-id { flex: 1; min-width: 0; }
|
||||
.id-row { display: flex; align-items: center; gap: 8px; }
|
||||
.acct-account { font-size: 16px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.acct-nick { font-size: 12.5px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
.acct-actions { display: flex; align-items: center; gap: 2px; flex-shrink: 0; }
|
||||
.acct-actions .el-button { font-size: 16px; }
|
||||
|
||||
.acct-tags { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; }
|
||||
.tag-label {
|
||||
font-size: 11px; font-weight: 700; color: var(--cp-ink-3);
|
||||
letter-spacing: .5px; margin-right: 2px; flex-shrink: 0;
|
||||
}
|
||||
.more { font-size: 12px; color: var(--cp-ink-3); font-weight: 700; }
|
||||
|
||||
.acct-foot {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
margin-top: auto; padding-top: 12px;
|
||||
border-top: 1px dashed var(--cp-line-strong);
|
||||
}
|
||||
.dim-sm { color: var(--cp-ink-3); font-size: 11px; }
|
||||
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
.reset-tip { margin-bottom: 16px; }
|
||||
</style>
|
||||
|
||||
@@ -5,34 +5,115 @@
|
||||
<h3>审计与运行报表 <span class="badge">Audit</span></h3>
|
||||
<p>操作审计 · 部署端运行上报记录(最新在前)</p>
|
||||
</div>
|
||||
<n-button :loading="busy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<n-tabs type="line" class="block cp-rise" :value="tab" @update:value="v => tab = v" justify-content="space-evenly">
|
||||
<n-tab-pane name="audit" tab="操作审计">
|
||||
<n-data-table :columns="auditCols" :data="audits" size="small" :loading="busy" :row-key="r => r.id" :single-line="false" />
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="report" tab="运行上报">
|
||||
<n-data-table :columns="reportCols" :data="reports" size="small" :loading="busy" :row-key="r => r.id" :single-line="false" />
|
||||
</n-tab-pane>
|
||||
</n-tabs>
|
||||
<!-- 顶部摘要 -->
|
||||
<div class="kpis cp-rise" v-if="loaded">
|
||||
<div class="kpi cp-card" v-for="(k, i) in kpis" :key="k.label" :style="{ animationDelay: i * 50 + 'ms' }">
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }"><el-icon :size="17"><component :is="k.icon" /></el-icon></div>
|
||||
<div class="kpi-meta">
|
||||
<div class="kpi-num mono" :style="{ color: k.color }">{{ k.value }}</div>
|
||||
<div class="kpi-lab">{{ k.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-tabs v-model="tab">
|
||||
<el-tab-pane label="操作审计" name="audit">
|
||||
<div class="toolbar">
|
||||
<el-select v-model="actionFilter" clearable placeholder="操作类型" style="width: 150px">
|
||||
<el-option v-for="(lb, key) in DETAIL_LABEL" :key="key" :label="lb" :value="key" />
|
||||
</el-select>
|
||||
<el-input v-model="search" placeholder="搜索账号 / 对象 / 详情" clearable :prefix-icon="Search" style="width: 240px" />
|
||||
</div>
|
||||
<el-table :data="filteredAudits" size="small" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" round effect="light" :type="actType(row.action)">{{ DETAIL_LABEL[row.action] || row.action }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann mono">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else class="mono">{{ row.account || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="对象" width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.target || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="详情" min-width="220" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.detail }">{{ row.detail || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane label="运行上报" name="report">
|
||||
<el-table :data="reports" size="small" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="110">
|
||||
<template #default="{ row }">
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ row.status || '—' }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann mono">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else class="mono">{{ row.account || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="设备" width="130" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ row.device_id || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="150" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.plugin_id || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="版本" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时长" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ typeof row.duration_sec === 'number' ? fmtDur(row.duration_sec) : '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="消息" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { h } from 'vue'
|
||||
import { NTag } from 'naive-ui'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, Search, Document, DataLine, CircleCloseFilled, WarningFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminAudit, adminReports } from '../api'
|
||||
import { message } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const tab = ref('audit')
|
||||
const busy = ref(false)
|
||||
const loaded = ref(false)
|
||||
const audits = ref([])
|
||||
const reports = ref([])
|
||||
const actionFilter = ref('')
|
||||
const search = ref('')
|
||||
|
||||
const DETAIL_LABEL = {
|
||||
grant: '授权', 'revoke-grant': '撤销授权', 'plugin-patch': '更新插件',
|
||||
@@ -40,44 +121,13 @@ const DETAIL_LABEL = {
|
||||
'account-update': '改号', 'account-reset': '重置密码', 'account-delete': '删除',
|
||||
'platform-grant': '平台授权', login: '登录',
|
||||
}
|
||||
function actTag(a) {
|
||||
const map = { grant: 'info', 'revoke-grant': 'error', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'info', }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[a] || 'default', round: true },
|
||||
{ default: () => DETAIL_LABEL[a] || a })
|
||||
function actType(a) {
|
||||
return { grant: 'primary', 'revoke-grant': 'danger', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary' }[a] || 'info'
|
||||
}
|
||||
function acctCell(r) {
|
||||
const nn = r.nickname
|
||||
if (!r.account && !nn) return h('span', { class: 'dim' }, '—')
|
||||
if (!nn) return h('span', null, r.account || '—')
|
||||
return h('div', { class: 'acct' }, [
|
||||
h('div', { class: 'ann' }, r.account || '—'),
|
||||
h('div', { class: 'anick' }, nn || ''),
|
||||
])
|
||||
function statusColor(s) {
|
||||
return { start: '#2f5cf0', running: '#2f5cf0', done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d' }[s] || '#9aa2b4'
|
||||
}
|
||||
function statusTag(s) {
|
||||
const map = { start: 'info', running: 'info', done: 'success', error: 'error' }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[s] || 'default', round: true },
|
||||
{ default: () => s || '—' })
|
||||
}
|
||||
|
||||
const auditCols = [
|
||||
{ title: '时间', key: 'at', width: 170 },
|
||||
{ title: '操作', key: 'action', width: 130, render: r => actTag(r.action) },
|
||||
{ title: '账号', key: 'account', width: 130, render: r => acctCell(r) },
|
||||
{ title: '对象', key: 'target', width: 140, ellipsis: { tooltip: true } },
|
||||
{ title: '详情', key: 'detail', minWidth: 220, ellipsis: { tooltip: true } },
|
||||
]
|
||||
const reportCols = [
|
||||
{ title: '时间', key: 'at', width: 170 },
|
||||
{ title: '状态', key: 'status', width: 100, render: r => statusTag(r.status) },
|
||||
{ title: '账号', key: 'account', width: 130, render: r => acctCell(r) },
|
||||
{ title: '设备', key: 'device_id', width: 110, render: r => r.device_id || h('span', { class: 'dim' }, '—') },
|
||||
{ title: '插件', key: 'plugin_id', width: 140, ellipsis: { tooltip: true } },
|
||||
{ title: '版本', key: 'version', width: 90 },
|
||||
{ title: '时长', key: 'duration_sec', width: 90, render: r => typeof r.duration_sec === 'number' ? fmtDur(r.duration_sec) : '—' },
|
||||
{ title: '消息', key: 'msg', minWidth: 200, ellipsis: { tooltip: true } },
|
||||
]
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
if (sec < 60) return sec + 's'
|
||||
@@ -86,12 +136,35 @@ function fmtDur(sec) {
|
||||
return `${Math.floor(m / 60)}h${m % 60}m`
|
||||
}
|
||||
|
||||
const kpis = computed(() => {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const tActs = audits.value.filter(a => (a.at || '').slice(0, 10) === today).length
|
||||
const tReports = reports.value.filter(r => (r.at || '').slice(0, 10) === today).length
|
||||
const fails = reports.value.filter(r => r.status === 'error' || r.status === 'failed').length
|
||||
return [
|
||||
{ label: '审计记录', value: audits.value.length, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '今日操作', value: tActs, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '运行上报', value: reports.value.length, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '今日上报', value: tReports, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
{ label: '上报失败', value: fails, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
]
|
||||
})
|
||||
|
||||
const filteredAudits = computed(() => {
|
||||
let list = audits.value
|
||||
if (actionFilter.value) list = list.filter(a => a.action === actionFilter.value)
|
||||
const kw = search.value.trim().toLowerCase()
|
||||
if (kw) list = list.filter(a => [a.account, a.nickname, a.target, a.detail].join(' ').toLowerCase().includes(kw))
|
||||
return list
|
||||
})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const [a, r] = await Promise.all([adminAudit(), adminReports()])
|
||||
audits.value = a.auditlogs || []
|
||||
reports.value = r.reports || []
|
||||
loaded.value = true
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
@@ -99,10 +172,15 @@ onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.kpis { display: grid; grid-template-columns: repeat(5, 1fr); gap: 16px; margin-bottom: 18px; }
|
||||
@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(3, 1fr); } }
|
||||
.kpi { display: flex; align-items: center; gap: 13px; padding: 16px; }
|
||||
.kpi-ic { width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0; display: grid; place-items: center; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7); }
|
||||
.kpi-meta { min-width: 0; }
|
||||
.kpi-num { font-size: 22px; font-weight: 800; line-height: 1.1; }
|
||||
.kpi-lab { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
|
||||
.panel { padding: 8px 18px 18px; }
|
||||
.toolbar { display: flex; gap: 10px; margin: 4px 0 14px; }
|
||||
.dim-sm { color: var(--cp-ink-2); }
|
||||
</style>
|
||||
<style>
|
||||
.acct { line-height: 1.25; }
|
||||
.acct .ann { font-size: 13px; color: var(--cp-ink-1); }
|
||||
.acct .anick { font-size: 11px; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
@@ -5,88 +5,87 @@
|
||||
<h3>权限授权 <span class="badge">Grants</span></h3>
|
||||
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<n-form inline>
|
||||
<n-form-item label="选择账号">
|
||||
<n-select
|
||||
v-model:value="account"
|
||||
:options="accountOptions"
|
||||
placeholder="选择账号…"
|
||||
style="width: 240px"
|
||||
filterable
|
||||
clearable
|
||||
/>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="account">
|
||||
<span class="sel-hint">{{ account }} · 已授权 {{ grantedIds.length }} 个插件 / {{ platChecked.length }} 个平台</span>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</n-card>
|
||||
<div class="cp-card panel cp-rise">
|
||||
<!-- 账号选择 -->
|
||||
<div class="pick-row">
|
||||
<div class="pick-label">选择账号</div>
|
||||
<el-select v-model="account" filterable clearable placeholder="选择账号…" style="width: 260px" :prefix-icon="User">
|
||||
<el-option v-for="a in accountOptions" :key="a.value" :label="a.label" :value="a.value" />
|
||||
</el-select>
|
||||
<div class="pick-hint" v-if="account">
|
||||
已授权 <b class="mono">{{ grantedIds.length }}</b> 个插件 / <b class="mono">{{ platChecked.length }}</b> 个平台
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="account">
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<b>插件授权</b>
|
||||
<n-button type="primary" size="small" :loading="saving" @click="saveGrant">保存插件授权</n-button>
|
||||
<template v-if="account">
|
||||
<!-- 插件授权 -->
|
||||
<div class="section">
|
||||
<div class="section-head">
|
||||
<div class="card-title">插件授权</div>
|
||||
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||
</div>
|
||||
</template>
|
||||
<n-checkbox-group v-model:value="grantedIds" v-if="plugins.length">
|
||||
<div class="ck-grid">
|
||||
<n-checkbox v-for="p in plugins" :key="p.id" :value="p.id" class="ck">
|
||||
<span class="ck-main">
|
||||
<span>{{ p.id }}<span class="dim">({{ p.name }})</span></span>
|
||||
<span class="ck-sub" v-if="grantState[p.id]?.granted">
|
||||
<n-switch size="small" :value="grantState[p.id].canRun"
|
||||
@update:value="v => setGrant(p.id, { canRun: v })">
|
||||
<template #checked>可运行</template>
|
||||
<template #unchecked>禁运行</template>
|
||||
</n-switch>
|
||||
<n-switch size="small" :value="grantState[p.id].canDownload"
|
||||
@update:value="v => setGrant(p.id, { canDownload: v })">
|
||||
<template #checked>可下载</template>
|
||||
<template #unchecked>禁下载</template>
|
||||
</n-switch>
|
||||
</span>
|
||||
</span>
|
||||
</n-checkbox>
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
<n-empty v-else description="暂无插件,请先在「插件管理」上传" size="small" />
|
||||
</n-card>
|
||||
<el-checkbox-group v-model="grantedIds" class="plist">
|
||||
<div class="prow" v-for="p in plugins" :key="p.id" :class="{ on: grantedIds.includes(p.id) }">
|
||||
<el-checkbox :value="p.id" class="pck">
|
||||
<span class="pname mono">{{ p.id }}</span>
|
||||
<span class="psub dim">{{ p.name }}</span>
|
||||
</el-checkbox>
|
||||
<div class="pswitches">
|
||||
<div class="psw">
|
||||
<span class="psw-label" :class="{ on: canRun(p.id) }">可运行</span>
|
||||
<el-switch size="small" :model-value="canRun(p.id)" :disabled="!grantedIds.includes(p.id)" @change="v => setGrant(p.id, { canRun: v })" />
|
||||
</div>
|
||||
<div class="psw">
|
||||
<span class="psw-label" :class="{ on: canDownload(p.id) }">可下载</span>
|
||||
<el-switch size="small" :model-value="canDownload(p.id)" :disabled="!grantedIds.includes(p.id)" @change="v => setGrant(p.id, { canDownload: v })" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-checkbox-group>
|
||||
<el-empty v-if="!plugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<b>平台授权</b>
|
||||
<n-button type="primary" size="small" :loading="savingPlat" @click="savePlat">保存平台授权</n-button>
|
||||
<!-- 平台授权 -->
|
||||
<div class="section">
|
||||
<div class="section-head">
|
||||
<div class="card-title">平台授权</div>
|
||||
</div>
|
||||
</template>
|
||||
<n-checkbox-group v-model:value="platChecked">
|
||||
<div class="ck-grid">
|
||||
<n-checkbox v-for="pf in PLATFORM_OPTS" :key="pf.id" :value="pf.id" class="ck">
|
||||
{{ pf.label }}<span class="dim">({{ pf.id }})</span>
|
||||
</n-checkbox>
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
</n-card>
|
||||
</template>
|
||||
<el-checkbox-group v-model="platChecked" class="pf-list">
|
||||
<el-checkbox v-for="pf in PLATFORM_OPTS" :key="pf.id" :value="pf.id" class="pf-chip">
|
||||
<span>{{ pf.label }}</span>
|
||||
<span class="dim mono">({{ pf.id }})</span>
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<n-empty v-else description="先在上方选择一个账号" class="no-acc cp-rise" />
|
||||
<el-empty v-else description="先在上方选择一个账号" :image-size="80" class="no-acc" />
|
||||
</div>
|
||||
|
||||
<!-- 底部保存栏 -->
|
||||
<transition name="savebar">
|
||||
<div class="savebar cp-card cp-rise" v-if="account">
|
||||
<div class="save-hint">
|
||||
<span class="dot" :class="{ dirty: dirtyCount > 0 }"></span>
|
||||
{{ dirtyCount > 0 ? `有 ${dirtyCount} 项授权变更待保存` : '授权已是最新' }}
|
||||
</div>
|
||||
<el-button type="primary" :loading="saving" :disabled="dirtyCount === 0" :icon="Check" @click="saveAll">
|
||||
保存授权
|
||||
</el-button>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { Refresh, User, Check } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const PLATFORM_OPTS = ref([])
|
||||
|
||||
@@ -102,7 +101,6 @@ const grantedIds = ref([])
|
||||
const grantState = ref({}) // plugin_id -> { granted, canRun, canDownload }
|
||||
const platChecked = ref([])
|
||||
const saving = ref(false)
|
||||
const savingPlat = ref(false)
|
||||
let heldGrantState = {} // 已保存快照,用于差异比对
|
||||
let heldPlatforms = new Set()
|
||||
|
||||
@@ -110,6 +108,15 @@ function setGrant(pid, patch) {
|
||||
grantState.value[pid] = { ...grantState.value[pid], ...patch }
|
||||
grantState.value = { ...grantState.value }
|
||||
}
|
||||
function canRun(pid) { return grantState.value[pid]?.canRun !== false }
|
||||
function canDownload(pid) { return grantState.value[pid]?.canDownload !== false }
|
||||
|
||||
// 全选 / 半选
|
||||
const allChecked = computed(() => plugins.value.length > 0 && grantedIds.value.length === plugins.value.length)
|
||||
const someChecked = computed(() => grantedIds.value.length > 0 && !allChecked.value)
|
||||
function toggleAll(v) {
|
||||
grantedIds.value = v ? plugins.value.map(p => p.id) : []
|
||||
}
|
||||
|
||||
// 选中账号即自动载入其现有授权
|
||||
watch(account, (acc) => {
|
||||
@@ -139,10 +146,27 @@ watch(grantedIds, (ids) => {
|
||||
grantState.value = state
|
||||
})
|
||||
|
||||
// 差异计算
|
||||
const pluginDirty = computed(() => {
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => { if (s.granted) want[pid] = s })
|
||||
const allPids = [...new Set([...Object.keys(want), ...Object.keys(heldGrantState)])]
|
||||
return allPids.filter(pid => {
|
||||
const w = want[pid]; const h = heldGrantState[pid]
|
||||
if (!!w !== !!h) return true
|
||||
if (w && h) return w.canRun !== h.canRun || w.canDownload !== h.canDownload
|
||||
return false
|
||||
})
|
||||
})
|
||||
const platDirty = computed(() => {
|
||||
const want = new Set(platChecked.value)
|
||||
return [...new Set([...want, ...heldPlatforms])].filter(pf => want.has(pf) !== heldPlatforms.has(pf))
|
||||
})
|
||||
const dirtyCount = computed(() => pluginDirty.value.length + platDirty.value.length)
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
// 拉取可授权平台列表(后端只读接口,替代写死 hr/oa)
|
||||
async function loadPlatforms() {
|
||||
try {
|
||||
const r = await adminPlatforms()
|
||||
@@ -150,78 +174,121 @@ async function loadPlatforms() {
|
||||
} catch (e) { message.error('平台列表读取失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
async function saveGrant() {
|
||||
async function savePluginDiff() {
|
||||
const acc = account.value
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => { if (s.granted) want[pid] = s })
|
||||
const diff = pluginDirty.value
|
||||
const results = await Promise.allSettled(diff.map(pid => adminGrant({
|
||||
account: acc, plugin_id: pid, granted: !!want[pid],
|
||||
can_run: want[pid]?.canRun !== false, can_download: want[pid]?.canDownload !== false,
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`插件授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return 0 }
|
||||
heldGrantState = JSON.parse(JSON.stringify(grantState.value))
|
||||
return diff.length
|
||||
}
|
||||
async function savePlatDiff() {
|
||||
const acc = account.value
|
||||
const want = new Set(platChecked.value)
|
||||
const diff = platDirty.value
|
||||
const results = await Promise.allSettled(diff.map(pf => adminPlatformGrant({
|
||||
account: acc, platform_id: pf, granted: want.has(pf),
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`平台授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return 0 }
|
||||
heldPlatforms = new Set(platChecked.value)
|
||||
return diff.length
|
||||
}
|
||||
|
||||
async function saveAll() {
|
||||
const acc = account.value; if (!acc) return
|
||||
saving.value = true
|
||||
try {
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => {
|
||||
if (s.granted) want[pid] = s
|
||||
})
|
||||
const allPids = [...new Set([...Object.keys(want), ...Object.keys(heldGrantState)])]
|
||||
const diff = allPids.filter(pid => {
|
||||
const w = want[pid]; const h = heldGrantState[pid]
|
||||
if (!!w !== !!h) return true
|
||||
if (w && h) return w.canRun !== h.canRun || w.canDownload !== h.canDownload
|
||||
return false
|
||||
})
|
||||
if (!diff.length) { message.info('插件授权无需变更'); return }
|
||||
const results = await Promise.allSettled(diff.map(pid => adminGrant({
|
||||
account: acc, plugin_id: pid, granted: !!want[pid],
|
||||
can_run: want[pid]?.canRun !== false, can_download: want[pid]?.canDownload !== false,
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`插件授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return }
|
||||
message.success(`已更新 ${diff.length} 项插件授权`)
|
||||
heldGrantState = JSON.parse(JSON.stringify(grantState.value))
|
||||
let okP = 0, okPl = 0
|
||||
if (pluginDirty.value.length) okP = await savePluginDiff()
|
||||
if (platDirty.value.length) okPl = await savePlatDiff()
|
||||
if (!pluginDirty.value.length && !platDirty.value.length) { message.info('授权无需变更'); return }
|
||||
message.success(`已保存:插件 ${okP} 项,平台 ${okPl} 项`)
|
||||
await refresh()
|
||||
} finally { saving.value = false }
|
||||
}
|
||||
async function savePlat() {
|
||||
const acc = account.value; if (!acc) return
|
||||
savingPlat.value = true
|
||||
try {
|
||||
const want = new Set(platChecked.value)
|
||||
const diff = [...new Set([...want, ...heldPlatforms])].filter(pf => want.has(pf) !== heldPlatforms.has(pf))
|
||||
if (!diff.length) { message.info('平台授权无需变更'); return }
|
||||
const results = await Promise.allSettled(diff.map(pf => adminPlatformGrant({
|
||||
account: acc, platform_id: pf, granted: want.has(pf),
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`平台授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return }
|
||||
message.success(`已更新 ${diff.length} 项平台授权`)
|
||||
heldPlatforms = new Set(platChecked.value)
|
||||
await refresh()
|
||||
} finally { savingPlat.value = false }
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
onMounted(() => { refresh(); loadPlatforms() })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.sel-hint { font-size: 12px; color: var(--cp-ink-2); }
|
||||
.no-acc { margin-top: 60px; }
|
||||
.panel { padding: 22px 24px 26px; }
|
||||
|
||||
/* 授权项:卡片式勾选 */
|
||||
.ck-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 10px; }
|
||||
.ck-main { display: flex; flex-direction: column; gap: 8px; min-width: 0; line-height: 1.2; }
|
||||
.ck-sub { display: flex; align-items: center; gap: 10px; }
|
||||
:deep(.n-checkbox) {
|
||||
display: flex; align-items: center; margin: 0;
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--cp-border);
|
||||
.pick-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding-bottom: 20px; border-bottom: 1px dashed var(--cp-line-strong); }
|
||||
.pick-label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.pick-hint { font-size: 12.5px; color: var(--cp-ink-3); }
|
||||
.pick-hint b { color: var(--cp-blue); font-size: 13px; }
|
||||
|
||||
.section { margin-top: 24px; }
|
||||
.section-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||
.section-head .card-title { margin-bottom: 0; }
|
||||
|
||||
/* 插件授权行 */
|
||||
.plist { display: flex; flex-direction: column; gap: 8px; }
|
||||
.prow {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, .65);
|
||||
background: var(--cp-panel);
|
||||
transition: border-color .18s, background .18s, box-shadow .18s;
|
||||
}
|
||||
:deep(.n-checkbox:hover) { border-color: rgba(59, 108, 255, .4); }
|
||||
:deep(.n-checkbox.n-checkbox--checked) {
|
||||
border-color: rgba(59, 108, 255, .45);
|
||||
background: linear-gradient(135deg, rgba(59, 108, 255, .08), rgba(34, 199, 232, .06));
|
||||
box-shadow: 0 8px 18px -10px rgba(59, 108, 255, .35);
|
||||
.prow:hover { border-color: rgba(47, 92, 240, .35); }
|
||||
.prow.on {
|
||||
border-color: rgba(47, 92, 240, .4);
|
||||
background: linear-gradient(90deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .03));
|
||||
box-shadow: 0 8px 18px -12px rgba(47, 92, 240, .4);
|
||||
}
|
||||
:deep(.n-checkbox .n-checkbox__label) { padding-left: 4px; flex: 1; min-width: 0; }
|
||||
.prow .pck { flex: 1; min-width: 0; }
|
||||
.pname { font-weight: 700; color: var(--cp-ink-1); font-size: 13px; }
|
||||
.psub { font-size: 12px; margin-left: 8px; }
|
||||
|
||||
.pswitches { display: flex; gap: 22px; flex-shrink: 0; }
|
||||
.psw { display: flex; align-items: center; gap: 8px; }
|
||||
.psw-label { font-size: 12px; color: var(--cp-ink-3); transition: color .18s; }
|
||||
.psw-label.on { color: var(--cp-blue); font-weight: 600; }
|
||||
|
||||
/* 平台授权 chips */
|
||||
.pf-list { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.pf-chip { margin: 0 !important; }
|
||||
.pf-chip :deep(.el-checkbox__input) { display: none; }
|
||||
.pf-chip :deep(.el-checkbox__label) {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 12px;
|
||||
background: var(--cp-panel);
|
||||
font-weight: 600;
|
||||
transition: border-color .18s, background .18s, box-shadow .18s, color .18s;
|
||||
}
|
||||
.pf-chip:hover :deep(.el-checkbox__label) { border-color: rgba(47, 92, 240, .4); }
|
||||
.pf-chip.is-checked :deep(.el-checkbox__label) {
|
||||
border-color: rgba(47, 92, 240, .55);
|
||||
background: linear-gradient(135deg, rgba(47, 92, 240, .10), rgba(15, 159, 155, .06));
|
||||
color: var(--cp-blue);
|
||||
box-shadow: 0 6px 14px -10px rgba(47, 92, 240, .5);
|
||||
}
|
||||
.no-acc { padding: 30px 0; }
|
||||
|
||||
/* 底部保存栏 */
|
||||
.savebar {
|
||||
position: sticky; bottom: 18px; z-index: 10;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
margin-top: 20px; padding: 14px 20px;
|
||||
background: rgba(255, 253, 248, .92);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
.save-hint { display: flex; align-items: center; gap: 9px; font-size: 13px; color: var(--cp-ink-2); font-weight: 600; }
|
||||
.save-hint .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--cp-success); }
|
||||
.save-hint .dot.dirty { background: var(--cp-amber); box-shadow: 0 0 0 4px rgba(217, 119, 6, .18); }
|
||||
.savebar-enter-active, .savebar-leave-active { transition: opacity .25s ease, transform .25s ease; }
|
||||
.savebar-enter-from, .savebar-leave-to { opacity: 0; transform: translateY(10px); }
|
||||
</style>
|
||||
|
||||
@@ -5,27 +5,25 @@
|
||||
<h3>概览 <span class="badge">Dashboard</span></h3>
|
||||
<p>中心机 · 插件分发与账号权限 · 当前账号 <b class="who">{{ store.nickname || store.current }}</b></p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="stat-grid" v-if="ov">
|
||||
<div class="stat-card" v-for="(s, i) in stats" :key="s.label" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :class="{ wide: s.wide }" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<n-icon :size="20"><component :is="s.icon" /></n-icon>
|
||||
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-num mono" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
</div>
|
||||
<n-skeleton v-else-if="overviewBusy" text :repeat="3" style="margin-top: 20px" />
|
||||
<el-skeleton v-else-if="overviewBusy" animated :rows="3" style="margin-top: 20px" />
|
||||
|
||||
<div class="tip-card cp-rise">
|
||||
<div class="tip-ic"><n-icon :size="18"><InfoFilled /></n-icon></div>
|
||||
<div class="tip-card cp-card cp-rise">
|
||||
<div class="tip-ic"><el-icon :size="18"><InfoFilled /></el-icon></div>
|
||||
<div class="tip-body">
|
||||
<b>使用说明</b>
|
||||
<p>「插件管理」上传与发布插件包(每插件保留最近 3 个版本);「账号管理」建号与账号维护;「权限授权」按账号勾选可用的插件与平台。部署机(webhost)仅在启动与手动刷新时拉取插件,授权变更后需在部署机刷新生效。</p>
|
||||
@@ -36,26 +34,26 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Refresh, InfoFilled } from '@element-plus/icons-vue'
|
||||
import { Refresh, InfoFilled, Box, Collection, User, UserFilled, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { message } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const ov = computed(() => overview.value)
|
||||
const stats = computed(() => {
|
||||
const plugins = ov.value?.plugins || []
|
||||
return [
|
||||
{ label: '插件', value: plugins.length, icon: 'Box', color: '#3b6cff', bg: 'linear-gradient(135deg,#eef2ff,#dbe6ff)' },
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: 'Collection', color: '#7c5cff', bg: 'linear-gradient(135deg,#f2edff,#e6dcff)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: 'User', color: '#12a4d8', bg: 'linear-gradient(135deg,#e7f6fb,#d3effa)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: 'UserFilled', color: '#22b07a', bg: 'linear-gradient(135deg,#e6f7f0,#d2f1e4)' },
|
||||
{ label: '最近上传', value: latest(), icon: 'UploadFilled', color: '#d99a1b', bg: 'linear-gradient(135deg,#fbf3e2,#f6e8c8)', small: true },
|
||||
{ label: '插件', value: plugins.length, icon: Box, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: Collection, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: User, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: UserFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '最近上传', value: latest(), icon: UploadFilled, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)', small: true, wide: true },
|
||||
]
|
||||
})
|
||||
function latest() {
|
||||
const all = (ov.value?.plugins || []).flatMap(p => p.versions || []).map(v => v.uploaded_at).filter(Boolean)
|
||||
if (!all.length) return '—'
|
||||
// ISO 时间转友好格式:2026-09-10T12:51:33 → 2026-09-10 12:51
|
||||
return all.sort().at(-1).replace('T', ' ').slice(0, 16)
|
||||
return fmtTime(all.sort().at(-1))
|
||||
}
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
@@ -66,47 +64,39 @@ onMounted(refresh)
|
||||
<style scoped>
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fill, minmax(236px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.stat-card {
|
||||
position: relative; overflow: hidden;
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
background: var(--cp-surface);
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 18px;
|
||||
padding: 18px;
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
transition: transform .22s ease, box-shadow .22s ease;
|
||||
animation: cp-rise .5s cubic-bezier(.22, .61, .36, 1) both;
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stat-card:hover { transform: translateY(-4px); box-shadow: var(--cp-card-shadow-hover); }
|
||||
.stat-card.wide { grid-column: span 2; }
|
||||
.stat-ic {
|
||||
width: 46px; height: 46px; border-radius: 14px; flex-shrink: 0;
|
||||
width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .6);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.stat-meta { min-width: 0; }
|
||||
.stat-num { font-size: 26px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink); font-variant-numeric: tabular-nums; }
|
||||
.stat-num.sm { font-size: 13px; font-weight: 600; word-break: break-all; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 3px; }
|
||||
.stat-num { font-size: 27px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink-1); }
|
||||
.stat-num.sm { font-size: 18px; font-weight: 700; white-space: nowrap; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
.stat-glow { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; border-radius: 0 6px 6px 0; opacity: .9; }
|
||||
|
||||
.tip-card {
|
||||
margin-top: 18px;
|
||||
margin-top: 20px;
|
||||
display: flex; gap: 14px;
|
||||
background: linear-gradient(135deg, rgba(59, 108, 255, .06), rgba(34, 199, 232, .05)), rgba(255, 255, 255, .7);
|
||||
border: 1px solid rgba(59, 108, 255, .16);
|
||||
border-radius: 16px;
|
||||
padding: 18px 20px;
|
||||
padding: 20px 22px;
|
||||
background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel);
|
||||
}
|
||||
.tip-ic {
|
||||
width: 38px; height: 38px; border-radius: 12px; flex-shrink: 0;
|
||||
width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff, #22c7e8);
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff;
|
||||
box-shadow: 0 6px 14px -6px rgba(59, 108, 255, .55);
|
||||
box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6);
|
||||
}
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink); margin-bottom: 4px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.7; color: var(--cp-ink-2); }
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink-1); margin-bottom: 5px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.8; color: var(--cp-ink-2); }
|
||||
</style>
|
||||
|
||||
@@ -5,125 +5,199 @@
|
||||
<h3>插件管理 <span class="badge">Plugins</span></h3>
|
||||
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header><span class="card-title">上传插件包</span></template>
|
||||
<n-form inline>
|
||||
<n-form-item label="插件 ID">
|
||||
<n-input v-model:value="pid" placeholder="如 seal_check" style="width: 150px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="名称">
|
||||
<n-input v-model:value="pname" placeholder="插件显示名" style="width: 150px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="版本">
|
||||
<n-input v-model:value="pver" placeholder="如 1.1.0" style="width: 110px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="包文件">
|
||||
<n-space align="center" :size="8">
|
||||
<n-upload :default-upload="false" :show-file-list="false" accept=".zip" @change="onFileChange">
|
||||
<n-button :type="pfile ? 'info' : 'default'">
|
||||
<template #icon><n-icon><UploadFilled /></n-icon></template>
|
||||
<div class="cp-card block cp-rise up-card">
|
||||
<div class="card-title">上传插件包</div>
|
||||
<el-form inline class="up-form" @submit.prevent>
|
||||
<el-form-item label="插件 ID">
|
||||
<el-input v-model="pid" placeholder="如 seal_check" style="width: 160px" class="mono" />
|
||||
</el-form-item>
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="pname" placeholder="插件显示名" style="width: 160px" />
|
||||
</el-form-item>
|
||||
<el-form-item label="版本">
|
||||
<el-input v-model="pver" placeholder="如 1.1.0" style="width: 120px" class="mono" />
|
||||
</el-form-item>
|
||||
<el-form-item label="包文件">
|
||||
<div class="file-row">
|
||||
<el-upload :auto-upload="false" :show-file-list="false" accept=".zip" :on-change="onFileChange" ref="upRef">
|
||||
<el-button :type="pfile ? 'primary' : 'default'" plain :icon="FolderOpened">
|
||||
{{ pfile ? '重新选择' : '选择 ZIP 包' }}
|
||||
</n-button>
|
||||
</n-upload>
|
||||
<n-tag v-if="pfile" size="small" round type="info" :bordered="false">{{ pfile.name }}</n-tag>
|
||||
</n-space>
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
<n-button type="primary" :loading="uploading" @click="upload">
|
||||
<template #icon v-if="!uploading"><n-icon><UploadFilled /></n-icon></template>上传发布
|
||||
</n-button>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</el-button>
|
||||
</el-upload>
|
||||
<el-tag v-if="pfile" size="small" round effect="plain" type="primary" class="mono">{{ pfile.name }}</el-tag>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="uploading" :icon="UploadFilled" @click="upload">上传发布</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="hint">包根目录需含 plugin.json / main.py / requirements.txt,ZIP 完整性校验通过才会发布。</div>
|
||||
</n-card>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header><span class="card-title">插件列表</span></template>
|
||||
<n-data-table
|
||||
:columns="columns"
|
||||
:data="plugins"
|
||||
:loading="overviewBusy"
|
||||
:row-key="r => r.id"
|
||||
:single-line="false"
|
||||
:row-props="rowProps"
|
||||
/>
|
||||
</n-card>
|
||||
<div class="cp-card block cp-rise list-card">
|
||||
<div class="card-title">插件列表</div>
|
||||
<el-table :data="plugins" size="small" :loading="overviewBusy" :row-key="r => r.id">
|
||||
<el-table-column label="插件 ID" min-width="160">
|
||||
<template #default="{ row }"><b class="cell-strong mono">{{ row.id }}</b></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="名称" min-width="180" show-overflow-tooltip prop="name" />
|
||||
<el-table-column label="分类" min-width="110">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="row.category" size="small" effect="plain" type="info" round>{{ row.category }}</el-tag>
|
||||
<span v-else class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[row.status]?.type || 'info'">
|
||||
{{ statusMeta[row.status]?.label || row.status || '—' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最新版" min-width="110">
|
||||
<template #default="{ row }"><span class="mono">{{ row.latest_version || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="210" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-ops">
|
||||
<el-button link type="info" :icon="View" @click="openDetail(row)">详情</el-button>
|
||||
<el-button link type="primary" :icon="Edit" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" :icon="Delete" @click="delPlugin(row)">删除</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<n-modal v-model:show="editShow" preset="card" :bordered="false" style="width: 560px" :title="`编辑插件 · ${edit.pid}`">
|
||||
<n-form label-placement="top">
|
||||
<n-form-item label="名称">
|
||||
<n-input v-model:value="edit.name" placeholder="插件显示名" />
|
||||
</n-form-item>
|
||||
<n-form-item label="分类">
|
||||
<n-input v-model:value="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</n-form-item>
|
||||
<n-form-item label="描述">
|
||||
<n-input v-model:value="edit.description" type="textarea" :rows="2" placeholder="插件用途说明" />
|
||||
</n-form-item>
|
||||
<n-form-item label="状态">
|
||||
<n-radio-group v-model:value="edit.status">
|
||||
<n-radio-button value="published">正常发布</n-radio-button>
|
||||
<n-radio-button value="disabled">禁用(停止分发)</n-radio-button>
|
||||
<n-radio-button value="revoked">下架(禁止运行)</n-radio-button>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
<n-form-item label="强制更新(留空表示不强制)" :show-feedback="false">
|
||||
<!-- 编辑插件 -->
|
||||
<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">
|
||||
<n-input v-model:value="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 180px" />
|
||||
<n-input v-model:value="edit.force_dl" type="datetime-local" placeholder="截止时间" style="width: 200px" />
|
||||
<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>
|
||||
</div>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<n-button @click="editShow = false">取消</n-button>
|
||||
<n-button type="primary" :loading="saving" @click="saveEdit">保存</n-button>
|
||||
<el-button @click="editShow = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 插件详情 -->
|
||||
<el-dialog v-model="detailShow" :title="`插件详情 · ${detail?.id || ''}`" width="640px" align-center destroy-on-close>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<div class="d-sec"><label>描述</label><p class="d-desc">{{ detail.description || '—' }}</p></div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>能力</label>
|
||||
<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>
|
||||
</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>
|
||||
</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>
|
||||
<span v-else class="dim">未授权</span>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="detailShow = false">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { NButton, NTag } from 'naive-ui'
|
||||
import { Refresh, UploadFilled } from '@element-plus/icons-vue'
|
||||
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 { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { message, dialog } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
const uploading = ref(false)
|
||||
const upRef = ref()
|
||||
|
||||
// 状态徽标文案与配色
|
||||
const STATUS_META = {
|
||||
const statusMeta = {
|
||||
published: { label: '正常', type: 'success' },
|
||||
disabled: { label: '禁用', type: 'warning' },
|
||||
revoked: { label: '已下架', type: 'error' },
|
||||
}
|
||||
function renderStatus(row) {
|
||||
const s = STATUS_META[row.status] || { label: row.status || '—', type: 'default' }
|
||||
return h(NTag, { size: 'small', round: true, bordered: false, type: s.type }, { default: () => s.label })
|
||||
revoked: { label: '已下架', type: 'danger' },
|
||||
}
|
||||
|
||||
function onFileChange(e) {
|
||||
pfile.value = e?.file?.file || null
|
||||
function onFileChange(uploadFile) {
|
||||
pfile.value = uploadFile.raw || null
|
||||
}
|
||||
|
||||
function renderVersions(row) {
|
||||
const list = row.versions || []
|
||||
if (!list.length) return h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'tags' }, list.map(v => h(NTag, {
|
||||
size: 'small', round: true, bordered: false,
|
||||
type: v.version === row.latest_version ? 'primary' : 'default',
|
||||
}, { default: () => v.version })))
|
||||
// —— 详情弹窗 ——
|
||||
const detailShow = ref(false)
|
||||
const detail = ref(null)
|
||||
function openDetail(row) {
|
||||
detail.value = row
|
||||
detailShow.value = true
|
||||
}
|
||||
function forceText(p) {
|
||||
if (p.force_min_version && p.force_deadline) return `${p.force_min_version} 起 · 截止 ${fmtTime(p.force_deadline)}`
|
||||
return '无'
|
||||
}
|
||||
|
||||
// —— 编辑弹窗状态 ——
|
||||
@@ -163,37 +237,6 @@ async function saveEdit() {
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
const columns = computed(() => [
|
||||
{ title: '插件 ID', key: 'id', width: 150, render: r => h('b', { class: 'cell-strong' }, r.id) },
|
||||
{ title: '名称', key: 'name', width: 130, ellipsis: { tooltip: true } },
|
||||
{ title: '分类', key: 'category', width: 90, render: r => r.category ? h(NTag, { size: 'small', bordered: false, type: 'info' }, { default: () => r.category }) : h('span', { class: 'dim' }, '—') },
|
||||
{
|
||||
title: '能力 / 表单', key: 'caps', minWidth: 130,
|
||||
render: r => h('div', { class: 'tags' }, [
|
||||
...(r.capabilities?.length ? r.capabilities.map(c => h(NTag, { size: 'small', bordered: false, type: 'default' }, { default: () => c })) : [h('span', { class: 'dim' }, '—')]),
|
||||
h(NTag, { size: 'small', bordered: false, type: 'info', style: 'margin-left:2px' }, { default: () => `${r.field_count || 0} 字段` }),
|
||||
]),
|
||||
},
|
||||
{ title: '状态', key: 'status', width: 80, render: renderStatus },
|
||||
{ title: '最新版', key: 'latest_version', width: 90 },
|
||||
{ title: '版本历史', key: 'versions', minWidth: 200, render: renderVersions },
|
||||
{
|
||||
title: '授权账号', key: 'accounts', minWidth: 130,
|
||||
render: r => (r.accounts?.length ? r.accounts.join('、') : h('span', { class: 'dim' }, '—')),
|
||||
ellipsis: { tooltip: true },
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'actions', width: 120,
|
||||
render: r => h('div', { class: 'row-acts' }, [
|
||||
h(NButton, { size: 'small', text: true, type: 'primary', onClick: () => openEdit(r) }, { default: () => '编辑' }),
|
||||
h(NButton, { size: 'small', text: true, type: 'error', onClick: () => delPlugin(r) }, { default: () => '删除' }),
|
||||
]),
|
||||
},
|
||||
])
|
||||
function rowProps() {
|
||||
return { style: 'cursor:default' }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
@@ -204,38 +247,51 @@ async function upload() {
|
||||
await adminUpload(pid.value, pname.value || pid.value, pver.value, pfile.value)
|
||||
message.success(`已发布 ${pid.value}@${pver.value}`)
|
||||
pid.value = ''; pname.value = ''; pver.value = ''; pfile.value = null
|
||||
upRef.value?.clearFiles()
|
||||
await refresh()
|
||||
} catch (e) { message.error('上传失败:' + (e.message || e)) }
|
||||
finally { uploading.value = false }
|
||||
}
|
||||
function delPlugin(p) {
|
||||
dialog.warning({
|
||||
title: '删除插件',
|
||||
content: `确认删除插件 ${p.id}?其全部版本与授权将一并清除`,
|
||||
positiveText: '删除',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
try { await adminPluginDelete({ plugin_id: p.id }); message.success(`已删除插件 ${p.id}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
},
|
||||
})
|
||||
dialog.confirm(`确认删除插件 ${p.id}?其全部版本与授权将一并清除`, '删除插件', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
}).then(async () => {
|
||||
try { await adminPluginDelete({ plugin_id: p.id }); message.success(`已删除插件 ${p.id}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}).catch(() => {})
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
.up-card, .list-card { padding: 20px 22px; }
|
||||
.up-card .card-title { margin-bottom: 16px; }
|
||||
.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; }
|
||||
</style>
|
||||
.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; }
|
||||
|
||||
<!-- 以下类用于 n-data-table 列 render 中由 naive-ui 作用域动态渲染的节点,
|
||||
它们不继承本组件 scoped scopeId,必须用全局(非 scoped)样式才生效。 -->
|
||||
<style>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.cell-strong { font-weight: 600; color: var(--cp-ink-1); }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.row-acts { display: flex; align-items: center; gap: 14px; white-space: nowrap; }
|
||||
.row-acts .n-button { --n-padding: 0; }
|
||||
.row-acts .n-button + .n-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; }
|
||||
.dim-sm { color: var(--cp-ink-3); }
|
||||
</style>
|
||||
|
||||
@@ -5,25 +5,26 @@
|
||||
<h3>运行统计 <span class="badge">Stats</span></h3>
|
||||
<p>账号 · 插件规模 · 执行次数/时长/成败 · 近 14 天趋势</p>
|
||||
</div>
|
||||
<n-button :loading="busy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<template v-if="st">
|
||||
<!-- 指标卡 -->
|
||||
<div class="kpis cp-rise">
|
||||
<div class="kpi"><span class="num" style="color:var(--cp-blue)">{{ st.users.total }}</span><span class="lab">用户总数</span></div>
|
||||
<div class="kpi"><span class="num">{{ st.plugins.total }}</span><span class="lab">插件总数</span></div>
|
||||
<div class="kpi"><span class="num">{{ st.runs.total }}</span><span class="lab">累计执行</span></div>
|
||||
<div class="kpi"><span class="num" style="color:#34a853">{{ st.runs.success }}</span><span class="lab">成功</span></div>
|
||||
<div class="kpi"><span class="num" style="color:#e5484d">{{ st.runs.failed }}</span><span class="lab">失败</span></div>
|
||||
<div class="kpi"><span class="num">{{ fmtDur(st.runs.durationSec) }}</span><span class="lab">总运行时长</span></div>
|
||||
<div class="kpi cp-card" v-for="(k, i) in kpis" :key="k.label" :style="{ animationDelay: i * 50 + 'ms' }">
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }">
|
||||
<el-icon :size="18"><component :is="k.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="kpi-meta">
|
||||
<div class="kpi-num mono" :style="{ color: k.color }">{{ k.value }}</div>
|
||||
<div class="kpi-lab">{{ k.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cp-rise">
|
||||
<div class="grid">
|
||||
<!-- 近 14 天趋势 -->
|
||||
<div class="card">
|
||||
<div class="cp-card trend-card cp-rise">
|
||||
<div class="card-title">近 14 天运行趋势</div>
|
||||
<div class="trend">
|
||||
<div class="tcol" v-for="d in st.trend" :key="d.day" :title="`${d.day} · ${d.runs} 次(成功 ${d.success} / 失败 ${d.failed})`">
|
||||
@@ -31,33 +32,44 @@
|
||||
<div class="tbar failed" :style="{ height: pct(d.failed, maxRuns) + '%' }"></div>
|
||||
<div class="tbar success" :style="{ height: pct(d.success, maxRuns) + '%' }"></div>
|
||||
</div>
|
||||
<span class="tday">{{ d.day }}</span>
|
||||
<span class="tday mono">{{ d.day }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="trend-legend">
|
||||
<span><i class="dot ok"></i>成功</span>
|
||||
<span><i class="dot fail"></i>失败</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 插件 / 用户排行 -->
|
||||
<div class="rank-wrap">
|
||||
<div class="card">
|
||||
<div class="card-title">插件排行(按运行次数)</div>
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">插件排行 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk">{{ i + 1 }}</span>
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead"><span class="rname">{{ p.name || p.pluginId }}</span><em>{{ p.runs }} 次</em></div>
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ p.name || p.pluginId }}</span>
|
||||
<em class="mono">{{ p.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(p.runs, rankMax(st.topPlugins)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topPlugins.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-title">活跃用户</div>
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">活跃用户 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk">{{ i + 1 }}</span>
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead"><span class="rname">{{ u.account }}</span><em>{{ u.runs }} 次</em></div>
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ u.account }}</span>
|
||||
<em class="mono">{{ u.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(u.runs, rankMax(st.topUsers)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topUsers.length" class="empty">暂无运行记录</li>
|
||||
@@ -70,39 +82,76 @@
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近运行</h4></div>
|
||||
</div>
|
||||
<n-card class="cp-rise" :bordered="false" size="small">
|
||||
<n-data-table :columns="recentCols" :data="st.recent" size="small" :row-key="r => r.at + r.pluginId" :single-line="false" />
|
||||
</n-card>
|
||||
<div class="cp-card cp-rise recent-card">
|
||||
<el-table :data="st.recent" size="small" :row-key="r => r.at + r.pluginId">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="110">
|
||||
<template #default="{ row }">
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ statusLabel(row.status) }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else>{{ row.account || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.pluginId }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="版本" width="100">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时长" width="100">
|
||||
<template #default="{ row }"><span class="mono">{{ fmtDur(row.durationSec) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="信息" min-width="220" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<n-skeleton v-else-if="busy" text :repeat="4" style="margin-top: 20px" />
|
||||
<div v-else class="empty-tip cp-rise">加载失败或暂无数据</div>
|
||||
<el-skeleton v-else-if="busy" animated :rows="5" style="margin-top: 20px" />
|
||||
<div v-else class="empty-tip cp-card cp-rise">加载失败或暂无数据</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { h } from 'vue'
|
||||
import { NTag } from 'naive-ui'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, User, Box, VideoPlay, CircleCheckFilled, CircleCloseFilled, Timer } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminStats } from '../api'
|
||||
import { message } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const busy = ref(false)
|
||||
const st = ref(null)
|
||||
|
||||
function statusTag(s) {
|
||||
const map = { done: 'success', success: 'success', error: 'error', failed: 'error', running: 'info', start: 'info' }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[s] || 'default', round: true },
|
||||
{ default: () => (s === 'done' || s === 'success' ? '成功' : s === 'error' || s === 'failed' ? '失败' : s) })
|
||||
const kpis = computed(() => {
|
||||
if (!st.value) return []
|
||||
const r = st.value
|
||||
return [
|
||||
{ label: '用户总数', value: r.users.total, icon: User, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '插件总数', value: r.plugins.total, icon: Box, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '累计执行', value: r.runs.total, icon: VideoPlay, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '成功', value: r.runs.success, icon: CircleCheckFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '失败', value: r.runs.failed, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
{ label: '总运行时长', value: fmtDur(r.runs.durationSec), icon: Timer, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
]
|
||||
})
|
||||
|
||||
function statusColor(s) {
|
||||
return { done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d', running: '#2f5cf0', start: '#2f5cf0' }[s] || '#9aa2b4'
|
||||
}
|
||||
function acctCell(r) {
|
||||
const nn = r.nickname
|
||||
if (!nn) return h('span', null, r.account || '—')
|
||||
return h('div', { class: 'acct' }, [
|
||||
h('div', { class: 'ann' }, r.account || '—'),
|
||||
h('div', { class: 'anick' }, nn || ''),
|
||||
])
|
||||
function statusLabel(s) {
|
||||
return (s === 'done' || s === 'success') ? '成功' : (s === 'error' || s === 'failed') ? '失败' : s
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
@@ -112,17 +161,8 @@ function fmtDur(sec) {
|
||||
const hh = Math.floor(m / 60)
|
||||
return `${hh}h${m % 60}m`
|
||||
}
|
||||
const recentCols = [
|
||||
{ title: '时间', key: 'at', width: 165 },
|
||||
{ title: '状态', key: 'status', width: 90, render: r => statusTag(r.status) },
|
||||
{ title: '账号', key: 'account', width: 110, render: r => acctCell(r) },
|
||||
{ title: '插件', key: 'pluginId', width: 150, ellipsis: { tooltip: true } },
|
||||
{ title: '版本', key: 'version', width: 90 },
|
||||
{ title: '时长', key: 'durationSec', width: 90, render: r => fmtDur(r.durationSec) },
|
||||
{ title: '信息', key: 'msg', minWidth: 220, ellipsis: { tooltip: true }, render: r => r.msg || h('span', { class: 'dim' }, '—') },
|
||||
]
|
||||
const maxRuns = () => Math.max(1, ...(st.value?.trend || []).map(t => t.runs || 0))
|
||||
const pct = (n, max) => Math.max(1, Math.round((n || 0) / (max || 1) * 100))
|
||||
const pct = (n, max) => Math.max(2, Math.round((n || 0) / (max || 1) * 100))
|
||||
const rankMax = list => Math.max(1, ...(list || []).map(x => x.runs || 1))
|
||||
|
||||
async function refresh() {
|
||||
@@ -141,36 +181,59 @@ onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 14px; margin-bottom: 16px; }
|
||||
.kpi { padding: 16px 18px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.kpi .num { font-size: 26px; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; }
|
||||
.kpi .lab { font-size: 12px; color: var(--cp-ink-3); }
|
||||
.grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 16px; margin-bottom: 16px; }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 16px; }
|
||||
.card { padding: 18px 20px; }
|
||||
.card-title { font-size: 14px; font-weight: 600; color: var(--cp-ink-1); margin-bottom: 14px; }
|
||||
.trend { display: flex; gap: 4px; height: 160px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 4px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 1px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 1px 1px 0 0; }
|
||||
.tbar.success { background: #34a853; }
|
||||
.tbar.failed { background: #e5484d; }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 10px; padding: 7px 0; }
|
||||
.rank .rk { width: 20px; height: 20px; flex: none; border-radius: 6px; background: var(--cp-bg-2); color: var(--cp-ink-3); font-size: 12px; display: flex; align-items: center; justify-content: center; }
|
||||
.rank li:nth-child(1) .rk { background: rgba(59,108,255,.12); color: var(--cp-blue); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; }
|
||||
.rname { font-size: 13px; color: var(--cp-ink-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rhead em { font-style: normal; font-size: 12px; color: var(--cp-ink-3); }
|
||||
.rbar { height: 5px; border-radius: 3px; background: var(--cp-bg-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: var(--cp-blue); border-radius: 3px; }
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 16px 0 !important; }
|
||||
.empty-tip { padding: 30px; text-align: center; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 18px; }
|
||||
@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(3, 1fr); } }
|
||||
.kpi {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 18px;
|
||||
}
|
||||
.kpi-ic {
|
||||
width: 42px; height: 42px; border-radius: 13px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.kpi-meta { min-width: 0; }
|
||||
.kpi-num { font-size: 24px; font-weight: 800; line-height: 1.1; }
|
||||
.kpi-lab { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
|
||||
<style>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
</style>
|
||||
.grid { display: grid; grid-template-columns: 1.45fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||
@media (max-width: 1100px) { .grid { grid-template-columns: 1fr; } }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 18px; }
|
||||
.trend-card, .rank-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 16px; }
|
||||
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||
|
||||
.trend { display: flex; gap: 5px; height: 176px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 6px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 2px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 3px 3px 0 0; transition: filter .18s, transform .18s; }
|
||||
.tbar.success { background: linear-gradient(180deg, #34b877, #1d9d5c); }
|
||||
.tbar.failed { background: linear-gradient(180deg, #f07a72, #d6453d); }
|
||||
.tcol:hover .tbar { filter: brightness(1.05); }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.trend-legend { display: flex; gap: 18px; margin-top: 14px; font-size: 12px; color: var(--cp-ink-2); }
|
||||
.trend-legend .dot { width: 9px; height: 9px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||
.trend-legend .ok { background: #1d9d5c; }
|
||||
.trend-legend .fail { background: #d6453d; }
|
||||
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 11px; padding: 8px 0; }
|
||||
.rank .rk {
|
||||
width: 24px; height: 24px; flex: none; border-radius: 8px;
|
||||
background: var(--cp-panel-2); color: var(--cp-ink-3);
|
||||
font-size: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.rank .rk.top { background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 4px 10px -4px rgba(47, 92, 240, .5); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; gap: 10px; }
|
||||
.rname { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rhead em { font-style: normal; font-size: 11.5px; color: var(--cp-ink-3); flex: none; }
|
||||
.rbar { height: 6px; border-radius: 4px; background: var(--cp-panel-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--cp-blue), var(--cp-teal)); border-radius: 4px; transition: width .6s cubic-bezier(.22, .61, .36, 1); }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 18px 0 !important; }
|
||||
.empty-tip { padding: 40px; text-align: center; color: var(--cp-ink-3); }
|
||||
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.recent-card { padding: 12px 16px; }
|
||||
.dim-sm { color: var(--cp-ink-2); }
|
||||
</style>
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 运维/构建工具集(CLI、PyInstaller spec、Windows 运维脚本)。"""
|
||||
"""controlplane 运维/构建工具集(CLI、数据库迁移、Windows 防火墙脚本)。"""
|
||||
@@ -0,0 +1,166 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SQLite → MySQL 一次性迁移脚本(37du 控制面)。
|
||||
|
||||
将历史 controlplane.db(SQLite)中的业务数据迁入 MySQL(MYSQL_DB 库)。
|
||||
- 幂等:有唯一键的表用 ON DUPLICATE KEY UPDATE,可重复执行;
|
||||
audit_logs / runtime_reports 无唯一键(纯追加日志),请勿重复执行,否则会追加副本。
|
||||
- plugin_grants 已并入 account_plugins(MySQL 版无独立 plugin_grants 表),
|
||||
迁移时以 plugin_grants 的 can_download/can_run 覆盖同名 account_plugins 行。
|
||||
|
||||
用法(在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.migrate_sqlite_to_mysql
|
||||
|
||||
前提:
|
||||
- controlplane/.env 已配置 MYSQL_*(迁移目标);
|
||||
- 脚本会自动建库建表(幂等 DDL),无需手工先建。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 兼容两种执行方式:python -m controlplane.tools.xxx(desktop/ 为搜索根)或直接跑脚本
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
import pymysql # noqa: E402
|
||||
from pymysql.cursors import DictCursor # noqa: E402
|
||||
|
||||
from controlplane.core import config # noqa: E402
|
||||
from controlplane.core.db import _ensure_database, _init_db # noqa: E402
|
||||
|
||||
|
||||
def _mysql() -> pymysql.connections.Connection:
|
||||
return pymysql.connect(
|
||||
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
|
||||
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
|
||||
database=config.MYSQL_DB, charset="utf8mb4",
|
||||
cursorclass=DictCursor, autocommit=False)
|
||||
|
||||
|
||||
def _sqlite_cols(conn: sqlite3.Connection, table: str) -> set:
|
||||
try:
|
||||
return {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
except sqlite3.OperationalError:
|
||||
return set()
|
||||
|
||||
|
||||
def _common_cols(conn: sqlite3.Connection, table: str, wanted: list) -> list:
|
||||
have = _sqlite_cols(conn, table)
|
||||
return [c for c in wanted if c in have]
|
||||
|
||||
|
||||
def _upsert(mysql, table: str, columns: list, rows: list) -> int:
|
||||
"""按唯一键幂等写入;columns 含目标列名(与 SQLite 同名)。"""
|
||||
if not columns or not rows:
|
||||
return 0
|
||||
ph = ", ".join(["%s"] * len(columns))
|
||||
sets = ", ".join(f"{c} = VALUES({c})" for c in columns)
|
||||
sql = (f"INSERT INTO {table}({', '.join(columns)}) VALUES ({ph}) "
|
||||
f"ON DUPLICATE KEY UPDATE {sets}")
|
||||
with mysql.cursor() as cur:
|
||||
for r in rows:
|
||||
cur.execute(sql, tuple(r))
|
||||
mysql.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _insert_append(mysql, table: str, columns: list, rows: list) -> int:
|
||||
"""日志类纯追加写入(无唯一键,重复执行会追加副本)。"""
|
||||
if not columns or not rows:
|
||||
return 0
|
||||
ph = ", ".join(["%s"] * len(columns))
|
||||
sql = f"INSERT INTO {table}({', '.join(columns)}) VALUES ({ph})"
|
||||
with mysql.cursor() as cur:
|
||||
for r in rows:
|
||||
cur.execute(sql, tuple(r))
|
||||
mysql.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _main() -> int:
|
||||
if not config.MYSQL_HOST:
|
||||
print("[migrate] 未配置 MySQL(MYSQL_HOST),请先配置 controlplane/.env")
|
||||
return 1
|
||||
src = config.DB_PATH
|
||||
if not src.is_file():
|
||||
print(f"[migrate] 未找到 SQLite 源库:{src},无需迁移")
|
||||
return 0
|
||||
|
||||
print(f"[migrate] 源库(SQLite):{src}")
|
||||
print(f"[migrate] 目标(MySQL):{config.MYSQL_DB}@{config.MYSQL_HOST}:{config.MYSQL_PORT}")
|
||||
|
||||
_ensure_database()
|
||||
_init_db() # 幂等建表 + 登记迁移版本,保证目标结构就绪
|
||||
mysql = _mysql()
|
||||
try:
|
||||
with sqlite3.connect(str(src)) as sconn:
|
||||
sconn.row_factory = sqlite3.Row
|
||||
|
||||
# ---- 1) accounts(id 自增不迁移,账号唯一键幂等) ----
|
||||
cols = _common_cols(sconn, "accounts", [
|
||||
"account", "password_hash", "salt", "is_admin", "dept", "nickname",
|
||||
"dingtalk_uid", "must_change_pwd", "avatar", "status", "created_at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM accounts")] if cols else []
|
||||
print(f"[migrate] accounts: {_upsert(mysql, 'accounts', cols, rows)}")
|
||||
|
||||
# ---- 2) plugins ----
|
||||
cols = _common_cols(sconn, "plugins", [
|
||||
"id", "name", "latest_version", "description", "category", "icon",
|
||||
"status", "force_min_version", "force_deadline", "manifest", "created_at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM plugins")] if cols else []
|
||||
print(f"[migrate] plugins: {_upsert(mysql, 'plugins', cols, rows)}")
|
||||
|
||||
# ---- 3) plugin_versions(id 不迁移) ----
|
||||
cols = _common_cols(sconn, "plugin_versions", [
|
||||
"plugin_id", "version", "filename", "uploaded_at", "sha256", "size_bytes"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM plugin_versions")] if cols else []
|
||||
print(f"[migrate] plugin_versions: {_upsert(mysql, 'plugin_versions', cols, rows)}")
|
||||
|
||||
# ---- 4) account_plugins + plugin_grants 合并(后者权限位覆盖前者) ----
|
||||
a_cols = _common_cols(sconn, "account_plugins", ["account", "plugin_id"])
|
||||
a_rows = [tuple(r[c] for c in a_cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(a_cols)} FROM account_plugins")] if a_cols else []
|
||||
g_cols = _common_cols(sconn, "plugin_grants",
|
||||
["account", "plugin_id", "can_download", "can_run"])
|
||||
g_rows = [tuple(r[c] for c in g_cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(g_cols)} FROM plugin_grants")] if g_cols else []
|
||||
acc_rows = []
|
||||
for _a, _p in a_rows:
|
||||
acc_rows.append((_a, _p, 1, 1))
|
||||
for _a, _p, _d, _rn in g_rows:
|
||||
acc_rows.append((_a, _p, int(_d), int(_rn)))
|
||||
print(f"[migrate] account_plugins(合并 plugin_grants): "
|
||||
f"{_upsert(mysql, 'account_plugins', ['account', 'plugin_id', 'can_download', 'can_run'], acc_rows)}")
|
||||
|
||||
# ---- 5) account_platforms ----
|
||||
cols = _common_cols(sconn, "account_platforms", ["account", "platform_id"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM account_platforms")] if cols else []
|
||||
print(f"[migrate] account_platforms: {_upsert(mysql, 'account_platforms', cols, rows)}")
|
||||
|
||||
# ---- 6) audit_logs / 7) runtime_reports(纯追加,id 不迁移) ----
|
||||
cols = _common_cols(sconn, "audit_logs", ["account", "action", "target", "detail", "at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM audit_logs")] if cols else []
|
||||
print(f"[migrate] audit_logs(追加): {_insert_append(mysql, 'audit_logs', cols, rows)}")
|
||||
|
||||
cols = _common_cols(sconn, "runtime_reports", [
|
||||
"account", "device_id", "plugin_id", "version", "status", "msg",
|
||||
"duration_sec", "at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM runtime_reports")] if cols else []
|
||||
print(f"[migrate] runtime_reports(追加): {_insert_append(mysql, 'runtime_reports', cols, rows)}")
|
||||
|
||||
finally:
|
||||
mysql.close()
|
||||
|
||||
print("[migrate] 完成:devices/chrome_releases/system_settings 为 MySQL 新增表,无历史数据,跳过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(_main())
|
||||
@@ -1,39 +0,0 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane deployment script
|
||||
rem 1) copy 37du-center.exe to D:\code\controlplane
|
||||
rem 2) register auto-start (Startup folder vbs)
|
||||
rem 3) launch 37du-center.exe
|
||||
rem Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
set "TARGET=D:\code\controlplane"
|
||||
|
||||
rem locate exe: parent folder (controlplane/), or its dist-exe\ subfolder
|
||||
if exist "%~dp0..\37du-center.exe" (
|
||||
set "SRC=%~dp0..\37du-center.exe"
|
||||
) else if exist "%~dp0..\dist-exe\37du-center.exe" (
|
||||
set "SRC=%~dp0..\dist-exe\37du-center.exe"
|
||||
) else (
|
||||
set "SRC=%~dp0..\dist\37du-center.exe"
|
||||
)
|
||||
if not exist "%SRC%" (echo [ERROR] Not found: 37du-center.exe & pause & exit /b 1)
|
||||
|
||||
rem 1) copy to deployment folder
|
||||
if not exist "%TARGET%" mkdir "%TARGET%"
|
||||
copy /y "%SRC%" "%TARGET%\37du-center.exe" >nul
|
||||
echo [OK] Copied to %TARGET%
|
||||
|
||||
rem 2) register auto-start
|
||||
set "STARTUP=%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup"
|
||||
set "VBS=%STARTUP%\37du-center.vbs"
|
||||
echo Set WshShell = CreateObject("WScript.Shell") > "%VBS%"
|
||||
echo WshShell.Run """%TARGET%\37du-center.exe""", 0, False >> "%VBS%"
|
||||
echo [OK] Auto-start registered.
|
||||
|
||||
rem 3) launch service
|
||||
taskkill /f /im 37du-center.exe >nul 2>&1
|
||||
start "" "%TARGET%\37du-center.exe"
|
||||
echo [OK] 37du-center started. Visit http://this-host-ip:8800
|
||||
pause
|
||||
@@ -0,0 +1,189 @@
|
||||
-- ============================================================
|
||||
-- 37du 自动化平台 · 中心机控制面 表结构(MySQL 5.7+)
|
||||
-- 引擎:InnoDB / 字符集:utf8mb4 / 排序:utf8mb4_unicode_ci
|
||||
-- 执行:mysql -h<host> -u<user> -p < schema_mysql.sql
|
||||
-- 幂等:全部 CREATE TABLE IF NOT EXISTS,可重复执行
|
||||
-- ============================================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS 37du_center
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE 37du_center;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 迁移版本记录:db.py 启动幂等建表时登记,替代旧 _ensure_col 渐进补列
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 统一账号
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件元数据
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件版本:每插件仅保留最近 N 版,旧版由应用层裁剪
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-插件授权:含下载/运行权限位(合并原 plugin_grants)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-平台白名单:账号可登录的平台
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 审计日志:下载/授权/管控/发布等关键操作留痕
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 运行上报:执行机运行记录(启动/完成/失败/离线补报)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机设备:环境/心跳上报(配合执行机 Chrome 检测)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Chrome 安装包下载源配置:外链 URL,中心机不存包
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' 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)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 系统级键值配置:全局配置沉淀(如环境依赖项)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
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='系统级键值配置';
|
||||
@@ -1,16 +0,0 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane stop script
|
||||
rem stops 37du-center.exe (auto-start registration is kept)
|
||||
rem MUST run as Administrator because the service was started
|
||||
rem from an elevated register_autostart.bat.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
taskkill /f /im 37du-center.exe >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [OK] 37du-center.exe is not running.
|
||||
) else (
|
||||
echo [OK] 37du-center.exe stopped.
|
||||
)
|
||||
pause
|
||||
@@ -9,7 +9,7 @@ from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, _cloud_plugin_manifest
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
@@ -53,6 +53,11 @@ def plugins_sync(request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
# 以「登录账号的授权插件集」作为加载白名单(替代启动时 CONTROLPLANE_ACCOUNT 的固定白名单),
|
||||
# 保证给员工账号授权插件后登录即可见/可运行;控制面不可达(manifest=None)时保持原白名单。
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
|
||||
@@ -12,14 +12,14 @@ from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/config.py,parents[1]=webhost)
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/core/config.py,parents[2]=webhost)
|
||||
# 打包运行(frozen)时:底座根 = exe 所在目录(.env、plugins/ 与 exe 同级部署);
|
||||
# 前端静态资源打包进 exe 内部,运行时从解压目录(_MEIPASS)读取
|
||||
if getattr(sys, "frozen", False):
|
||||
_HOST_ROOT = Path(sys.executable).resolve().parent
|
||||
DIST = Path(getattr(sys, "_MEIPASS", _HOST_ROOT)) / "frontend" / "dist"
|
||||
else:
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[1]
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[2]
|
||||
DIST = _HOST_ROOT / "frontend" / "dist"
|
||||
|
||||
PORT = 8799
|
||||
|
||||
@@ -104,7 +104,7 @@
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员在控制面授权</span></div>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员进行授权</span></div>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
</aside>
|
||||
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
# 重构方案:中心机(云端/后台)与部署壳(员工客户端)拆分 v3
|
||||
|
||||
> 目标:把「服务器管理所有」和「壳只在设备上干活」分开;**中心机离线不影响日常执行,只影响插件更新**。
|
||||
>
|
||||
> v2:钉钉身份换取必须在持有 AppSecret 的云端完成(钉钉仅支持 Authorization Code,无 PKCE/无 secret 模式),登录链路定为"云端换取 + 一次性 code + 壳建本机会话",并补齐机器凭证双因子、插件签名、权限缓存 TTL/吊销。
|
||||
>
|
||||
> v3:细化为**最简可实施方案**——两层架构(云端控制面 + 本地壳执行面),插件保留现有形态不动,执行链路复用现状 `plugin_runner`+`RunContext`+`scheduler`+`winjob`+`hub`。新增内容:登录实现细节(壳本机浏览器直连接 code / state 防 CSRF / userid→工号映射 / `/auth/exchange` 鉴权 / 登出 / 续期)与阶段二触发条件。
|
||||
|
||||
***
|
||||
|
||||
## 0. 前置验证项(先于一切动工,未过则后续设计需重排)
|
||||
|
||||
### 0.0 登录不再依赖云端公网可达(关键前提,已核实)
|
||||
|
||||
**钉钉扫码登录是浏览器跳转,不是服务器回调。** 跳转由**用户本机浏览器**完成,浏览器访问 `http://localhost:8799` 毫无障碍。因此"服务器能出不能进/云端无公网域名"**对登录链路不构成任何障碍**——钉钉根本不访问云端,只把浏览器重定向到本机 localhost 壳。
|
||||
|
||||
- 钉钉官方开放平台文档**明示可用 `http://localhost` 作为 OAuth 回调域名**(示例 `http://localhost:5173`),即 `localhost` 回调平台原生支持,无需公网域名。
|
||||
- 故 §0.0(原"云端必须对钉钉回调可达")**删除**:不再需要公网域名、内网穿透、反代。
|
||||
- AppSecret 仍只在云端:换取动作由壳 POST 云端 `/auth/exchange{code}` 在服务端完成,**不涉及任何公网回调**。
|
||||
|
||||
### 0.0b 钉钉开放平台事实(2026-09 查证)
|
||||
|
||||
1. 登录采用 Authorization Code Grant:`authCode` → `POST /v1.0/oauth2/userAccessToken` 换 access\_token,**必填 clientSecret**;`response_type` 固定 `code`,只此一种响应模式。
|
||||
2. 无公共客户端 / 无 secret / 原生 PKCE 授权模式——**不支持**(网上"钉钉+PKCE"方案是在自有网关段引入 PKCE,不解除 secret 依赖)。
|
||||
3. `redirect_uri` 需在开发者后台**提前登记且与调用一致**(协议/域名/端口/路径字面量一致、大小写及尾斜杠敏感),**`localhost` 可登记**(官方支持);两处须 URL 编码。
|
||||
|
||||
结论:**AppSecret 只能放云端;换 token 由壳 POST 云端完成。** redirect\_uri 登记为**壳本机 `http://localhost:8799`(协议/端口固定)**,多壳共用同一应用、同一回调地址(各壳本机均为 localhost:8799),无需逐壳登记、无需公网域名。
|
||||
|
||||
前置验证清单(全部通过才动工):
|
||||
|
||||
- 钉钉开发者后台「钉钉登录与分享」登记回调域名 `http://localhost:8799`,并验证与授权 URL 的 `redirect_uri` **字面量一致**。
|
||||
- 用户扫码后**浏览器能跳回 `http://localhost:8799`** 且带 `code` + `state` 两参数。
|
||||
- 壳 POST 云端 `/auth/exchange{code}` 后,`code`+`AppSecret` 能换取到 `jobNumber`(现状 `_dingtalk_userinfo` 已验,确认该应用已开取工号权限)。
|
||||
|
||||
***
|
||||
|
||||
## 1. 目标架构
|
||||
|
||||
```
|
||||
云端 = 中心机 (controlplane/,一台服务器,唯一"管理员入口")
|
||||
├─ 账号与授权 哪个员工能用哪些插件 ✅ 现有 /api/plugins?account / admin 后台
|
||||
├─ 插件仓库 zip + plugin.json(版本/manifest) ✅ 现有 packages/ + /api/manifest + /api/pkg
|
||||
├─ 审计/运行记录 ✅ 现有 admin/audit、admin/reports
|
||||
├─ 钉钉身份换取 唯一持有 DINGTALK_APP_KEY/SECRET ✅ /auth/exchange(壳浏览器直连接 code,云端仅换身份)
|
||||
└─ 不做 使用界面 / 跨机调度 / 参数透传 / 长期持员工会话 ← 移除
|
||||
|
||||
本地壳 = 执行端 (webhost/,每台机器一个,唯一"员工入口")
|
||||
├─ 登录 壳会话=员工身份;身份由云端一次性 code 换取建立 ← 链路改造
|
||||
├─ 查 持身份 → 云端换「权限 + 插件目录/schema」
|
||||
├─ 更新 版本比对 → 下载 zip → 验签 → 解压 exe 到本机
|
||||
├─ 运行 本机选插件 → 本机填参 → 起 exe(JSON 进/出) → 本机看日志
|
||||
└─ 上报 结果上报云端审计;离线先本地缓存、联网补报
|
||||
```
|
||||
|
||||
身份边界精确表述:
|
||||
|
||||
- **会话/令牌不出本机**(成立):壳本机会话 cookie 只在壳内有效。
|
||||
- **工号必然到云端**(成立):权限本体的键是工号,壳持工号才能向云端查权限。
|
||||
|
||||
***
|
||||
|
||||
## 2. 关键链路设计
|
||||
|
||||
### 2.1 钉钉登录:壳本机直接接 code(浏览器跳转,非云端中转)
|
||||
|
||||
**机制本质**:钉钉扫码是**浏览器跳转**,不是服务器回调。`redirect_uri` 设为壳本机 `http://localhost:8799`,用户本机浏览器就地把 code 交给壳——**云端不参与中转,无 poll、无 nonce、无回调白名单**。AppSecret 仍在云端,由壳 POST 云端换 token 完成。
|
||||
|
||||
```
|
||||
1. LoginPage 点"钉钉登录"
|
||||
2. 壳后端生成 state(随机,防CSRF),落盘存本地
|
||||
3. 壳打开钉钉授权 URL:
|
||||
https://login.dingtalk.com/oauth2/challenge.htm?redirect_uri=http://localhost:8799/auth/done&...&state=<state>
|
||||
4. 用户扫码确认
|
||||
5. 钉钉让【用户本机浏览器】跳转 → http://localhost:8799/auth/done?code=xxx&state=xxx
|
||||
6. 壳后端接住 code + state,校验 state 与发起时一致(防 CSRF,不一致→拒绝)
|
||||
7. 壳后端 POST 云端 /auth/exchange {code}
|
||||
8. 云端用 code + AppSecret 换 access_token → 拉 job_number/工号/姓名(复用 _dingtalk_userinfo) → 只验证不建号(_auth_account_lookup)
|
||||
9. 云端返回 工号 + 云端会话 token
|
||||
10. 壳建本机会话(壳 SESSION_COOKIE) + 存云端 token → 前端进入插件清单(2.2)
|
||||
```
|
||||
|
||||
- **code 经本机浏览器地址栏落到 localhost 壳**:code 为一次性、60s、单次消费、且落在用户自己的机器,等效标准 OAuth loopback 模式,可接受。
|
||||
- **云端只有一个接口 `/auth/exchange`**:AppSecret 不出云端;那里是本链路唯一"见过 code+工号"的瞬间。
|
||||
- 无需 `client_nonce`(不再有取码方与发起方分离的问题)、无需 `poll`(壳直接拿到 code)、无需回调白名单(回跳地址由钉钉按登记的 localhost 固定,不接受任意参数)。
|
||||
- code 与工号一对一绑定、单次消费、秒级过期,防重放/冒充。
|
||||
|
||||
#### 2.1.1 redirect_uri:一层,固定壳本机 localhost
|
||||
|
||||
- **仅一层**:钉钉 → 壳本机 `http://localhost:8799/auth/done`。无"云端→壳"第二层。
|
||||
- 登记:钉钉开发者后台「钉钉登录与分享」登记回调域名 `http://localhost:8799`(协议/端口固定)。**多壳共用同一应用、同一回调**(各壳本机都是 localhost:8799),无需逐壳登记、无需公网域名。
|
||||
- 校验:`redirect_uri` 与登记处**字面量一致**(协议/域名/端口/路径一致、大小写及尾斜杠敏感),且 URL 编码。
|
||||
- **open-redirect 问题不存在**:回跳地址由钉钉按登记固定为 localhost,不接受任何可注入的"回跳去哪"参数,故无需回调白名单。
|
||||
|
||||
#### 2.1.2 state(防 CSRF,唯一回跳校验)
|
||||
|
||||
- `state`:**壳后端本地生成**(一次性随机串,落盘存本地),发起登录时随授权 URL 传给钉钉;钉钉回调 `code+state` 原样带回,壳校验 `state` 与发起时一致才处理 code;**不一致/缺失/已消费 → 拒绝**,防止攻击者伪造回调把自己的 code 塞进壳会话。
|
||||
- state 只在壳本地生成与校验,云端不持有、不校验(云端只有 `/auth/exchange`)。
|
||||
- **落盘**:壳在发起与接收之间若重启,本地 state 丢失即视为登录失败重新扫码即可;设**登录超时清理**(如 5 分钟未收到回调即丢弃本地 state)。
|
||||
|
||||
#### 2.1.3 userid → 员工工号映射(现状已具备,写清绑定规则)
|
||||
|
||||
- 现状 `_dingtalk_userinfo` 已返回 `account`(优先 `jobNumber`,回退 `userId`/`unionid`),见 [app.py](file:///d:/work/code/Process-Automation/controlplane/app.py#L937-L978) [`_dingtalk_userinfo`](file:///d:/work/code/Process-Automation/controlplane/app.py#L937-L978)。
|
||||
- 账号绑定规则:**账号主键 = 工号**,由管理员入口 `/api/admin/dingtalk/auth`(`find-or-create`)建立。
|
||||
- 换钉钉账号:建议 accounts 表加一列 `dingtalk_uid`(unionid)。扫码时若该 unionid 已绑定某工号则沿用;否则按 `jobNumber` 匹配。避免同/异工号造成散号;散号由管理员后台合并,账号以工号为唯一键。
|
||||
- 若 `jobNumber` 拿不到(权限/配置缺失):回退 `userId`,并要求管理员在后台补绑工号后该账号才可见插件。
|
||||
|
||||
#### 2.1.3b 登录接口不建号(权限边界,重要)
|
||||
|
||||
- **员工登录链路(`/auth/exchange`)只验证、不建号**:壳 POST `/auth/exchange{code}` 云端换取时**不 create 账号**,只在账号已存在时返回工号 + 云端 token。
|
||||
- **建号只发生在管理员入口** `/api/admin/dingtalk/auth`(后台为员工开通,或管理员主动建号)。
|
||||
- 员工首次扫码若工号在 accounts 不存在:登录链路返回"账号未开通,请联系管理员",壳端提示人工开通,**绝不自动建号**。避免"壳能建云端账号"这一隐含越权。
|
||||
- 登录接口因此天然避免"任何扫到钉钉身份的人自建账号"的权限提升面。
|
||||
|
||||
#### 2.1.4 `/auth/exchange` 鉴权
|
||||
|
||||
- 输入:壳 POST `{code}`(钉钉授权码,已由浏览器带到 localhost 壳)。输出:工号 + 云端会话 token。
|
||||
- 一次性 code 短时效(60s) + 单次消费;即使泄漏攻击窗口极小。
|
||||
- 云端用 code + AppSecret 换 access\_token → 拉工号(`_dingtalk_userinfo`)→ **只验证不建号**;工号存在则签发云端会话 token,壳据此建本机会话 + 存云端 token。
|
||||
- 该接口**不建号**:工号不存在时返回 `exists=False`,壳端提示"账号未开通,请联系管理员",不建立会话。
|
||||
|
||||
#### 2.1.4b TTL
|
||||
|
||||
- **code 60 秒**(云端 `/auth/exchange` 消费时限,单次消费)。
|
||||
- **state 5 分钟**(壳本地:发起登录到收到回调的最大间隔,超时丢弃本地 state,重新扫码)。
|
||||
|
||||
#### 2.1.4c 登录页交互路径与 `/auth/done` 路由(新增)
|
||||
|
||||
- **当前窗口跳转,不用新窗口**。`LoginPage.vue` 点"钉钉登录"→ 壳后端生成 state 落盘 → 当前标签页跳转钉钉授权 URL(`redirect_uri=http://localhost:8799/auth/done`)。
|
||||
- **壳新增 `/auth/done` 路由**:钉钉把浏览器跳回 `http://localhost:8799/auth/done?code=xxx&state=xxx`。壳后端:
|
||||
1. 校验 `state` 与本地已发起的一致(不一致→拒绝);
|
||||
2. POST 云端 `/auth/exchange{code}` → 得工号 + 云端 token;
|
||||
3. 建本机会话(`SESSION_COOKIE`)+ 存云端 token → 前端 `window.location` 进插件清单(§2.2)。
|
||||
- `/auth/done` 是本链路唯一浏览器落点,不做其它中转。
|
||||
|
||||
#### 2.1.4d 启动流程与会话检查(默认真实变化:能进插件页就不显示登录页)
|
||||
|
||||
**打开壳的默认落点是插件页,不是登录页。** 只有两种情况会看到登录页:**首次安装(从没登录过)**① 或 **会话过期(超过 7 天没打开,滑动 TTL 超了)**。天天用的人永不重扫。
|
||||
|
||||
```
|
||||
双击壳
|
||||
→ 壳后端启动(FastAPI/8799)
|
||||
→ 前端加载(本地 Vue)
|
||||
→ 前端调壳后端 /auth/status 检查本机会话
|
||||
├─ 会话有效 → 直接进插件页
|
||||
└─ 会话无效/过期 → 进登录页,展示二维码(§2.1 直连接 code)
|
||||
```
|
||||
|
||||
- **`/auth/status`(壳后端新增)**:读本地会话,返回 `{logged_in: true}` 或 `{logged_in: false}`;前端据此定向。
|
||||
- **能否保活与云端在线无关**:会话存壳本地 cookie;云端只在登录时参与一次换 token,换完即忘;云端宕机不影响 7 天内会话有效性。
|
||||
- **联网依赖**:首次登录必须联网(调云端 `/auth/exchange` 换 token);日常使用不查云端、本地直接放行;会话过期后需联网重扫。
|
||||
|
||||
① 注:统一账户早期形态可先"账号+密码"登录,扫码为后续升级;但会话保持/`/auth/status` 逻辑与登录方式无关,先行落地。
|
||||
|
||||
#### 2.1.5 登出
|
||||
|
||||
- 壳:清本地 `SESSION_COOKIE` / session.json 即登出。
|
||||
- 云端:本就不持有员工会话,**无需清**;一次性 code 已消费。钉钉 access\_token 属短期,不强调登出接口,可选在登出时弹钉钉退出授权(可后置)。
|
||||
|
||||
#### 2.1.6 续期
|
||||
|
||||
- 本机会话沿用现有 `SESSION_COOKIE` + **滑动续期**机制(每次有效请求刷新 TTL,如 7 天)。
|
||||
- 续期在壳本地完成,不依赖云端在线;超期未访问需重新扫码。
|
||||
- 无需 refresh\_token/云端续期(会话本来只在壳,不涉及云端会话生命周期)。
|
||||
|
||||
**会话续期 ≠ 权限续期(两个维度,不要混)**:
|
||||
|
||||
```text
|
||||
会话续期:本地滑动 TTL,不查云端(体验优先,见 §2.1.6)
|
||||
权限判定:每次登录/执行时调云端实时判(安全优先,见 §2.2)
|
||||
权限缓存:TTL 7 天,超期降级拒绝敏感插件(离线妥协,见 §2.5)
|
||||
```
|
||||
|
||||
- 会话可以在壳本地无限续期;**但权限是否有效必须由云端判定**。壳离线太久或权限被吊销,会话仍在、权限应失效。
|
||||
- 一句话:**会话可以本地续,权限必须云端判。**
|
||||
|
||||
### 2.2 壳持身份 → 云端查权限与插件目录(两层会话,各司其职)
|
||||
|
||||
**先分清两个不同层级的会话,不要混用一个 cookie**:
|
||||
|
||||
| 会话 | 归属 | 谁签发 / 客户端 | 存了什么 | 谁解 / 校验 | 用途 |
|
||||
|------|------|----------------|---------|------------|------|
|
||||
| 壳本机 `SESSION_COOKIE` | 壳 ↔ 壳前端 | 壳后端 | 壳前端会话 | 壳后端 | 壳内页面鉴权,**不拿去调云端** |
|
||||
| 云端会话 token | 壳后端 ↔ 云端 | 云端(`/auth/exchange` 签发) | 工号 + device | 云端 | 壳调 `/api/plugins`、审计上报 |
|
||||
|
||||
**`/auth/exchange` 除了返回工号,还要签发一个云端会话 token**(不能复用壳本机 SESSION_COOKIE——那是给壳前端用的一层会话)。
|
||||
|
||||
```
|
||||
壳调云端 /api/plugins 带「云端会话 token」(由 /auth/exchange 签发)
|
||||
→ 云端从 token 解出工号 → 按工号白名单返回插件清单(含 fields schema)
|
||||
→ 壳前端通用表单渲染器(现有 PluginPage) 按 fields 渲染本机参数录入
|
||||
```
|
||||
|
||||
- **鉴权机制定为方案 A:云端会话 token**(非明文传 `X-Employee-Id`)。云端从 token 解出工号判权限,工号不可伪造,天然防越权。token 由 `/auth/exchange` 签发并绑定工号与发放给该壳,杜绝"拿 token 跨机冒充"。
|
||||
- 云端会话 token 由 `/auth/exchange` 签发、壳后端持久化;效期与现有会话习惯对齐,超期需重新扫码(不推翻既有会话体系)。
|
||||
- 参数只在壳本机录入、不上云端(除非随结果上报)。
|
||||
|
||||
### 2.3 版本下载 → 验签 → 解压落盘(新增)
|
||||
|
||||
```
|
||||
壳 → GET 云端 /api/manifest → 比对本地已解压版本(本地版本标记)
|
||||
→ 有更新 → GET 云端 /api/pkg/{id}/{version} 下载 zip
|
||||
→ 用内置公开钥校验 顺序签名(Ed25519) → 通过才解压
|
||||
→ 解压到 %LOCALAPPDATA%\37duAutomation\plugins → 写本地版本标记
|
||||
```
|
||||
|
||||
- **签名而非仅 hash**:防云端被入或中间人替换后执行恶意插件。云端用私钥签包,壳内置公钥验签。控件 `controlplane` 现有 `cryptography` Ed25519 依赖(app.py 已引入 Ed25519)。
|
||||
|
||||
### 2.4 执行(沿用、几乎零改动)
|
||||
|
||||
- 复用 `plugin_runner.py`(JSON 参数 stdin 进 / 日志结果 stdout 出)、`scheduler.py`(设备单活)、`winjob.py`(Job 整树托管)、`hub.py`(WS 广播)。
|
||||
- 结果:本机展示 + 上报云端审计。
|
||||
- **审计上报带本机 cookie**(同 `/api/plugins`):云端从 cookie 取工号写审计记录,与权限鉴权同一身份源,防伪造。
|
||||
|
||||
### 2.5 离线与补报(复用现有 + 加 TTL/吊销)
|
||||
|
||||
- 在线:执行前拉权限/目录/版本;命中更新即下载验签解压。
|
||||
- 离线:直接用本机已落盘插件照跑;权限用**缓存清单**兜底。
|
||||
- **权限缓存加 TTL(如 7 天)**:超期未联网则拒绝执行敏感插件;敏感插件可强制在线校验。防止"员工离职、云端已回收权限,但壳离线继续用缓存插件"。
|
||||
- **"敏感插件"定义(写入** **`manifest.json`,新增字段)**:插件作者在 `plugin.json`/`manifest.json` 里显式声明 `"sensitive": true`。敏感插件=涉及文件读写、网络访问、系统命令等副作用/越权面的插件;非敏感=纯计算/纯查询。敏感插件在权限缓存超 TTL 时**拒绝离线执行**;非敏感插件可放行。
|
||||
- 结果/审计离线本地缓存,联网后 `flush_offline_reports` 补报(复用 `licensing.py` 机制)。
|
||||
|
||||
***
|
||||
|
||||
## 3. 复用清单(几乎不动)
|
||||
|
||||
| 资产 | 路径 | 说明 |
|
||||
| :------------------ | :-------------------------------------------------------------------- | :---------------------- |
|
||||
| 云端后台/授权/仓库/审计/OAuth | `controlplane/` | 账号、上传、白名单、audit、钉钉回调全保留 |
|
||||
| 壳前端页面 | `webhost/frontend/src/components/{LoginPage,PluginPage,LogPanel}.vue` | 登录、通用表单、日志界面直接用 |
|
||||
| 壳执行基建 | `plugin_runner.py / scheduler.py / winjob.py / hub.py` | 子进程协议、单活、Job 托管、WS 广播 |
|
||||
| 离线能力 | `licensing.py` | 离线票据缓存 + 延迟补报 |
|
||||
| 权限隔离 + 签名库 | `/api/plugins?account=` + cryptography Ed25519 | 现成 |
|
||||
|
||||
Vue 部署位置(明确):**页面前端跟随壳(本地),云端不放使用界面。** UI 迭代需更新壳(收影响小、通常插件才迭代)。评估点已对齐。
|
||||
|
||||
***
|
||||
|
||||
## 4. 新增 / 改造清单
|
||||
|
||||
| # | 项 | 归属 | 说明 |
|
||||
| :- | :------------------------------------------------------ | :- | :----------------------------------------------------------------- |
|
||||
| A | 云端 `/auth/exchange {code}`(唯一登录接口) | 云端 | 壳 POST code → code+AppSecret 换身份 → 只验证不建号 → 返回工号+云端会话 token(§2.1.4/§2.2) |
|
||||
| B | 壳登录页改打开钉钉授权 + `/auth/done` 直接接 code | 壳 | 改 `LoginPage.vue` + 新增 `/auth/done` 路由 + `main.py`:生成/校验 state、POST `/auth/exchange{code}`、建本机会话 + 存云端 token |
|
||||
| C | 壳下载解压插件落盘 | 壳 | 新增,复用 `licensing.py` 目录约定 |
|
||||
| D | 云端 `/api/plugins` 返回 fields | 云端 | 确保 schema 完整 |
|
||||
| E | 壳离线队列补报 | 壳 | 复用 `licensing.py` |
|
||||
| F | `fields` 支持 file 类型 | 壳 | `PluginPage.vue` 加控件(阶段一可后置) |
|
||||
| G | accounts 表加 `dingtalk_uid` | 云端 | unionid 绑定,避免散号;账号仍以工号为唯一键
|
||||
|
||||
***
|
||||
|
||||
## 5. 迁移步骤(每步可独立验证)
|
||||
|
||||
1. **前置验证**:钉钉后台登记回调域名 `http://localhost:8799` 并验证扫码后浏览器能带 code+state 跳回本机;`/auth/exchange{code}` 能换到工号。
|
||||
2. **登录链路改壳本机直接接 code**(`/auth/done` 收 code + state 校验 + POST `/auth/exchange`,不建号):壳建本机会话、存云端 token。验证:壳上扫码→建会话;AppSecret 只出现在云端;未开通工号提示联系管理员。
|
||||
3. **壳→云端双因子查权限/目录**,前端渲染本地表单。验证:员工只见授权内插件;越权工号被拒。
|
||||
4. **版本下载→验签→解压落盘**。验证:篡改包被拒,新版本运行的是验签通过的包。
|
||||
5. **离线与补报 + 权限缓存 TTL/吊销**。验证:断网跑存量、结果不丢;超 TTL 敏感插件被拒。
|
||||
6. **插件 exe 化(可选阶段二)**,按需打包 exe 由云端分发。
|
||||
|
||||
***
|
||||
|
||||
## 6. 插件形态(阶段化)
|
||||
|
||||
- **壳 venv 形态(已定:预装,方案 A)**:壳安装包**预装真实 venv**(DrissionPage/pyautogui/pywin32/FastAPI 全套打进安装包),**不选 PyInstaller 冻结**。
|
||||
- 理由:最大化**复用现有** **`webhost`** **的 venv 形态**与「插件在壳内 load 源码、动态 import 复用壳依赖」的现状;冻结 exe 下动态 import 受限、插件热更不便。
|
||||
- 代价(写清):安装包较大(几百 MB);**壳升级 = 下载新 venv/新壳版本**,升级带宽成本高于冻结方案。此为可接受取舍——阶段一频繁发壳低、插件频率高,预装最省事。
|
||||
- 兜底:若后续对升级带宽敏感,可在壳升级时做"版本间 venv diff 增量",不推翻预装形态。
|
||||
- **阶段一(本次核心)**:插件维持源码模块在壳内 load,依赖**复用壳 venv**(DrissionPage/pyautogui/pywin32 等已预装),云端只下发 `main.py + manifest.json`;不动骨架。
|
||||
- **阶段一的实质约束(写清,避免插件开发者预期落差)**:壳的 venv **随壳安装包/壳版本分发、版本锁定**。因此插件能用的依赖 = 该版本壳 venv 里已装的库;**插件开发者不能自主加依赖**,加新依赖必须等壳发新版。
|
||||
- 约定:插件 `requirements.txt` 只声明壳 venv 已包含的库;出现新依赖即触发阶段二(见下),而不是让壳临时 pip install。
|
||||
- **阶段二触发条件(何时必须升级,写清)**:**当"插件新增了壳 venv 中没有的依赖"时**,无法本地 pip install(本地不装),壳 venv 又要发新版才能补依赖——此时必须进阶段二:云端 vendor 打包(`pip install --target vendor`)+ 独立/嵌入 Python 运行时 + 插件自包含分发。
|
||||
- 若插件依赖长期固定且都在壳 venv:阶段一可一直用,不必进二。
|
||||
- 若某插件依赖开始演进:进阶段二,按需打包 exe 由云端分发。
|
||||
- **阶段二(exe/自包含)**:build 成 exe 或 vendor 包由云端分发,壳以子进程拉起;schema 仍放 plugin.json(云端 manifest 提供)。exe 化是打包问题,不改变架构判断。
|
||||
|
||||
***
|
||||
|
||||
## 7. 风险分级(按威胁模型分三档)
|
||||
|
||||
按"使用者不懂这些,别过度设防"的取向,风险按三档收敛:**只做防意外的必做项;防主动攻击的降级为可后置(阶段一先简);超出威胁模型的不做。**
|
||||
|
||||
### 7.1 必须做(防意外——低成本、防误操作/误配导致的破坏)
|
||||
|
||||
- **AppSecret 只在云端**:绝不下发到壳/客户端(安全红线),见 §8。
|
||||
- **登录不建号**:员工登录链路 `/auth/exchange` 只验证不建号,建号只在管理员入口,防"随意扫码自建账号"的越权面,见 §2.1.3b。
|
||||
- **state 防 CSRF(唯一回跳校验)**:壳本地校验 DingTalk 带回的 `state` 与发起时一致,不一致/缺失/已消费 → 拒绝,防"攻击者伪造回调把自己的 code 塞进壳会话"。见 §2.1.2。(原"回调白名单"概念随 localhost 固定回跳消失,等价防护由 state 承担。)
|
||||
- **权限缓存 TTL**:离线权限缓存设 TTL,超期拒绝敏感插件,防"员工离职/回收权限后仍离线可跑",见 §2.5。
|
||||
|
||||
> 备注:**钉钉回调登记(§0)**与 **userid→工号映射(§2.1.3)** 是"先于动工的前置约束 + 数据完整性约定",不是风险分级项,单独见 §0 与 §2.1.3。
|
||||
|
||||
### 7.2 可以后置(防主动攻击——阶段一先简,有需要再上)
|
||||
|
||||
- **插件签名**:最终为 Ed25519 签名(防云端被入/中间人替换),壳内置公钥验签。**阶段一可先 hash 即可**;注意 hash 防不了中间人(改包同时改 hash),端到端安全以签名为准,签名阶段二落地。
|
||||
- **防重放签名**:请求加时间戳+签名的重放防护,阶段一可不做(一次性 code + 短时效已覆盖登录主链路)。
|
||||
- **OS 级凭据存储**:云端会话 token 的落盘加密走 OS 凭据库(Trusted Platform / DPAPI),阶段一可先存明文配置文件。
|
||||
|
||||
> 已无 device_token:新链路云端只有 `/auth/exchange`(无 `start`/回调入口可被随机脚本打),故不再需要设备在册校验。
|
||||
|
||||
### 7.3 不做(威胁模型外)
|
||||
|
||||
- **社会工程攻击防护**(诱导扫码、钓鱼授权页等)。
|
||||
- **多因子认证**(钉钉自己就是身份源,MFA 在钉钉侧)。
|
||||
- **设备指纹绑定 / 硬件绑定唯一性**(装过壳的机器即视为可信)。
|
||||
|
||||
### 7.4 其它约束 / 兼容
|
||||
|
||||
- **userid→工号映射**:账号以工号为唯一键,accounts 加 `dingtalk_uid(unionid)` 防散号;登录链路不建号;拿不到工号时回退 userId 并要求后台补绑。见 §2.1.3。
|
||||
- **旧接口兼容**:`/api/admin/dingtalk/*` 改动不影响管理员后台(云端直连)。
|
||||
|
||||
***
|
||||
|
||||
## 8. 明确不做(防范围蔓延)
|
||||
|
||||
- ❌ 不把 AppSecret 下发到任何壳/客户端(安全红线)
|
||||
- ❌ 不做跨机调度 / 任务派发中心
|
||||
- ❌ 不做参数透传(参数只在壳本机,不上云端)
|
||||
- ❌ 不做云端持员工会话 / 把员工钉钉 token 长期驻留云端
|
||||
- ❌ 不做第二套"使用界面"(日常只访问壳,管理员只访问云端后台)
|
||||
|
||||
@@ -85,8 +85,10 @@ CONTRACT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
# 监听其响应以区分提交成功/失败:state="1" 成功,state="0" 失败(失败时页面不关闭)
|
||||
SEND_WE_TASK_URL = f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc"
|
||||
SEND_WE_TASK_MARK = "WeTask.mc?method=sendWeTask"
|
||||
# 流程节点列表查询接口:按 processId 查流程全部节点(activityName/createTime/endTime 等)
|
||||
WE_PROCESS_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc"
|
||||
# 流程节点列表查询接口:按 processId 查流程全部节点任务(activityName/createTime/endTime/currentState 等)。
|
||||
# 原 WeProcess.mc?method=getActivityList 返回不含「完善信息(操作人)」节点,
|
||||
# 已换为 WeTask.mc?method=query(按任务/人返回,同一节点可能有多条记录,取 endTime 时优先 COMPLETED 那条)
|
||||
WE_TASK_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc"
|
||||
# 超期检查:「完善信息(操作人)」节点 endTime 非空且距今超过 3 天 -> 超期提醒
|
||||
OVERDUE_ACTIVITY_NAME = "完善信息(操作人)"
|
||||
OVERDUE_DAYS = 3
|
||||
@@ -98,7 +100,7 @@ DEFAULT_PAGE_SIZE = 100
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = False
|
||||
APPROVE_ENABLED = True
|
||||
# 审批按钮:仅自动提交"同意"(校验通过);未完成一律不自动提交("不管"),保留待后续流转
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
@@ -297,7 +299,6 @@ def get_wf_activity_by_task_id(session, task_id):
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
@@ -349,32 +350,36 @@ def get_business_data(session, business_key, form_id):
|
||||
|
||||
|
||||
def get_activity_list(session, process_id):
|
||||
"""调用 WeProcess.mc?method=getActivityList 按 processId 查询流程全部节点。
|
||||
"""调用 WeTask.mc?method=query 按 processId 查询流程全部节点任务。
|
||||
|
||||
返回 jsonList(每项含 activityName/createTime/endTime/currentState 等)。
|
||||
注意:按任务/人返回,同一节点会有多条记录(多候选人各一条,
|
||||
currentState 可能为 COMPLETED/OVERDUE/WAITING/ACCEPTED)。
|
||||
"""
|
||||
url = f"{WE_PROCESS_URL}?method=getActivityList&processId={process_id}"
|
||||
url = (
|
||||
f"{WE_TASK_QUERY_URL}?method=query"
|
||||
f"&sortName=create_time&sortType=asc&process_id={process_id}"
|
||||
)
|
||||
logger.info("查询流程节点列表: processId=%s", process_id)
|
||||
|
||||
session.post(url)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("WeProcess 请求失败,未获取到响应")
|
||||
raise RuntimeError("WeTask 请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"WeProcess 接口状态码异常: {resp.status_code}")
|
||||
raise RuntimeError(f"WeTask 接口状态码异常: {resp.status_code}")
|
||||
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"WeProcess 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
raise RuntimeError(f"WeTask 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
if json_data.get("state") != "1":
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: {json_data.get('meg')}")
|
||||
raise RuntimeError(f"WeTask 接口返回失败: {json_data.get('meg')}")
|
||||
|
||||
json_list = json_data.get("jsonList") or []
|
||||
logger.info("WeProcess 返回成功,共 %d 个节点", len(json_list))
|
||||
logger.debug("WeProcess 返回: %s", json_data)
|
||||
logger.info("WeTask 返回成功,共 %d 条节点任务", len(json_list))
|
||||
return json_list
|
||||
|
||||
|
||||
@@ -382,13 +387,18 @@ def check_process_overdue(session, process_id, now=None):
|
||||
"""超期检查:取「完善信息(操作人)」节点 endTime 判断是否超期。
|
||||
|
||||
规则:endTime 为 null(节点未完成)-> 不算超期,返回 None;
|
||||
endTime 非空且距今超过 OVERDUE_DAYS 天 -> 返回 {"endTime", "days"}。
|
||||
endTime 非空且距今超过 OVERDUE_DAYS 天 -> 返回 {"endTime", "days", "operator"},
|
||||
operator 为该节点实际办理人姓名(取自命中记录的 participantName)。
|
||||
"""
|
||||
activities = get_activity_list(session, process_id)
|
||||
target = next(
|
||||
(a for a in activities if a.get("activityName") == OVERDUE_ACTIVITY_NAME),
|
||||
None,
|
||||
)
|
||||
# 同一节点会有多条记录(多候选人各一条),优先取有审批意见(remark 非空)的那条,
|
||||
# 其次取 COMPLETED,最后取第一条有 endTime 的;实际审批人的 endTime 才是节点真实完成时间
|
||||
matched = [a for a in activities if a.get("activityName") == OVERDUE_ACTIVITY_NAME]
|
||||
target = next((a for a in matched if a.get("remark") and a.get("endTime")), None)
|
||||
if target is None:
|
||||
target = next((a for a in matched if a.get("currentState") == "COMPLETED" and a.get("endTime")), None)
|
||||
if target is None:
|
||||
target = next((a for a in matched if a.get("endTime")), None)
|
||||
if target is None:
|
||||
logger.warning("流程 %s 未找到「%s」节点,跳过超期检查", process_id, OVERDUE_ACTIVITY_NAME)
|
||||
return None
|
||||
@@ -404,7 +414,13 @@ def check_process_overdue(session, process_id, now=None):
|
||||
days = (now - end_dt).total_seconds() / 86400
|
||||
if days > OVERDUE_DAYS:
|
||||
logger.info("流程 %s 已超期:endTime=%s(%.1f 天)", process_id, end_time, days)
|
||||
return {"endTime": str(end_time), "days": int(days)}
|
||||
# 实际办理人:取命中记录的 participantName(优先 remark 非空/COMPLETED 那条);
|
||||
# 注意未办理记录的 operator 字段是上一节点触发人(申请人),不能当办理人用
|
||||
return {
|
||||
"endTime": str(end_time),
|
||||
"days": int(days),
|
||||
"operator": target.get("participantName") or "",
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
@@ -694,7 +710,7 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
# 重定向 URL 同时携带流程实例 processId(WeProcess.getActivityList 超期检查用);
|
||||
# 重定向 URL 同时携带流程实例 processId(WeTask.query 超期检查用);
|
||||
# WfActivity 接口返回不含 processId,processId 只能从这里拿,缺失不阻断主流程
|
||||
process_id = params.get("processId", [None])[0] or ""
|
||||
|
||||
@@ -1155,7 +1171,10 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
if overdue_list:
|
||||
overdue_blocks = []
|
||||
for r in overdue_list:
|
||||
lines = [f"**🔹 {r['staff_name'] or r['title']}**({r['creator']})"]
|
||||
# 括号内显示实际办理人(完善信息节点实际办理人),缺失时回退到发起人,避免空白
|
||||
operator = r.get("operator") or ""
|
||||
who = f"办理人:{operator}" if operator else f"发起人:{r.get('creator') or ''}"
|
||||
lines = [f"**🔹 {r['staff_name'] or r['title']}**({who})"]
|
||||
if r.get("brand"):
|
||||
lines.append(f"> 原归属品牌:{r['brand']}")
|
||||
if r.get("leaveoffice_time"):
|
||||
|
||||
Reference in New Issue
Block a user