Compare commits
108
Commits
main
...
eeb951f9f6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eeb951f9f6 | ||
|
|
68f29d0a14 | ||
|
|
6525275a54 | ||
|
|
8c61a05d8a | ||
|
|
57028b8626 | ||
|
|
5abdd91f35 | ||
|
|
008f6f5998 | ||
|
|
41bcb44e34 | ||
|
|
26d4125798 | ||
|
|
08d26a416e | ||
|
|
ffeebf80e6 | ||
|
|
e115bb7113 | ||
|
|
2a08338ed1 | ||
|
|
ee46776648 | ||
|
|
f8f108af5d | ||
|
|
87f995ca47 | ||
|
|
3214305dea | ||
|
|
7e0838de64 | ||
|
|
be1a2899ba | ||
|
|
dd546fc07b | ||
|
|
a4c172bc98 | ||
|
|
c7add9574e | ||
|
|
b034b51685 | ||
|
|
600379933d | ||
|
|
530cfe38dc | ||
|
|
11fc3cee6a | ||
|
|
78aa8c361c | ||
|
|
f30ab9cc29 | ||
|
|
6d2dd93628 | ||
|
|
813bee743b | ||
|
|
0ab43d0ed8 | ||
|
|
a1a06504a5 | ||
|
|
b86bc1bf97 | ||
|
|
67bb73fa30 | ||
|
|
6f248b0741 | ||
|
|
9f6deaae76 | ||
|
|
d605a7f9cc | ||
|
|
42c7cf24f2 | ||
|
|
c00c4423f0 | ||
|
|
3f901d3882 | ||
|
|
65540fb121 | ||
|
|
9d067c0646 | ||
|
|
be07de0e92 | ||
|
|
0354a1ca58 | ||
|
|
1a16b1b5b7 | ||
|
|
f8889cdf51 | ||
|
|
8593f0fec4 | ||
|
|
e5884bd943 | ||
|
|
657f444041 | ||
|
|
16d59e4e69 | ||
|
|
ea92c62bb9 | ||
|
|
121df38da1 | ||
|
|
75d0903c0a | ||
|
|
8375df692a | ||
|
|
3b5ce2d219 | ||
|
|
9cfa096ec8 | ||
|
|
30218cc339 | ||
|
|
1178ea37b3 | ||
|
|
5c90747d0f | ||
|
|
be6817bafd | ||
|
|
7af2132b99 | ||
|
|
acca8c5e8a | ||
|
|
aee37b200f | ||
|
|
05842f36d5 | ||
|
|
76d7459515 | ||
|
|
fc2cf49c35 | ||
|
|
93795ffec0 | ||
|
|
4b168c3982 | ||
|
|
e3dc6369ee | ||
|
|
bdcc0326bf | ||
|
|
20d93187f9 | ||
|
|
b2db418d39 | ||
|
|
d19b783302 | ||
|
|
13eb46f4e1 | ||
|
|
7a4f3590ef | ||
|
|
9e61206be2 | ||
|
|
e5c598e67a | ||
|
|
39bf3e14a0 | ||
|
|
ce0422979a | ||
|
|
bfef048695 | ||
|
|
2f67a15083 | ||
|
|
d773f783eb | ||
|
|
dc8d038e34 | ||
|
|
195edb8b32 | ||
|
|
59b2ee9acb | ||
|
|
d7f3cbfcfd | ||
|
|
d2b24051af | ||
|
|
0973533bab | ||
|
|
61e9e123c4 | ||
|
|
60a177605a | ||
|
|
60112ad367 | ||
|
|
c95720514b | ||
|
|
2fafd9af18 | ||
|
|
4d9928abf3 | ||
|
|
28b74fce4e | ||
|
|
d468d15032 | ||
|
|
c1c54e61fc | ||
|
|
966d529551 | ||
|
|
186636a8e4 | ||
|
|
c749d951a0 | ||
|
|
9a14f5aca6 | ||
|
|
9927066abb | ||
|
|
7e46b5cc06 | ||
|
|
eef5df9ce2 | ||
|
|
83d8204847 | ||
|
|
0489fbe62c | ||
|
|
5d339b3d0e | ||
|
|
724a4f7b77 |
+44
-2
@@ -13,6 +13,27 @@ sdist/
|
|||||||
wheels/
|
wheels/
|
||||||
*.manifest
|
*.manifest
|
||||||
*.spec
|
*.spec
|
||||||
|
# 前端依赖与构建产物(desktop 桌面端)
|
||||||
|
desktop/*/frontend/node_modules
|
||||||
|
plugins/**/ui-src/node_modules
|
||||||
|
desktop/*/frontend/dist/
|
||||||
|
desktop/**/frontend/*.zip # controlplane-web-dist.zip 等部署用压缩包
|
||||||
|
# Node 依赖全局兜底(含 electron-shell 根目录)
|
||||||
|
node_modules/
|
||||||
|
# Electron 壳子运行环境 / 打包产物(可再生,不入库;详细规则见 desktop/electron-shell/.gitignore)
|
||||||
|
dist-app/
|
||||||
|
dist-env/
|
||||||
|
python-env/
|
||||||
|
|
||||||
|
# 桌面版打包产物(PyInstaller 中间/输出、安装包、插件构建包,不入库)
|
||||||
|
# 仅执行机(壳子)/文件服务器仍走 PyInstaller 打包;中心机已改源码部署,不再产出 exe
|
||||||
|
desktop/*/build-exe/
|
||||||
|
desktop/*/dist-exe/
|
||||||
|
desktop/releases/
|
||||||
|
desktop/build/
|
||||||
|
dist-plugin/
|
||||||
|
desktop/**/setup-*.exe
|
||||||
|
desktop/**/installer/
|
||||||
pip-log.txt
|
pip-log.txt
|
||||||
pip-delete-this-directory.txt
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
@@ -26,14 +47,26 @@ ENV/
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
# 各平台会话 cookies 持久化目录(OA / 其他平台共用,按平台名分文件)
|
# 控制面签名密钥 / 运行期产物(禁止入库)
|
||||||
app/service/.sessions/
|
.admin_secret
|
||||||
|
.webhost.pid
|
||||||
|
*.pid
|
||||||
|
desktop/**/keys/
|
||||||
|
desktop/**/packages/
|
||||||
|
desktop/**/controlplane.db
|
||||||
|
desktop/**/_cp_sessions.json
|
||||||
|
# 各平台会话 cookies / 缓存目录(统一移入 %LOCALAPPDATA%\37duAutomation,禁止入库)
|
||||||
|
**/.sessions/
|
||||||
|
|
||||||
# ---------- IDE ----------
|
# ---------- IDE ----------
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
|
# Trae IDE 本地配置/技能(不入库)
|
||||||
|
.trae/
|
||||||
|
# 工具 ACL 恢复备份产物
|
||||||
|
.dsh-acl-recovery/
|
||||||
|
|
||||||
# ---------- 操作系统 ----------
|
# ---------- 操作系统 ----------
|
||||||
.DS_Store
|
.DS_Store
|
||||||
@@ -49,3 +82,12 @@ logs/
|
|||||||
.coverage
|
.coverage
|
||||||
htmlcov/
|
htmlcov/
|
||||||
.tox/
|
.tox/
|
||||||
|
aa.md
|
||||||
|
|
||||||
|
# vc运行库
|
||||||
|
vc_redist/
|
||||||
|
vc_redist_x64/
|
||||||
|
vc_redist_x86/
|
||||||
|
|
||||||
|
静态资源/
|
||||||
|
.assets/
|
||||||
@@ -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` |
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
AI 智能体开发约束 & 项目执行规范
|
||||||
|
本文件为项目根目录全局 Agent 行为规则,AI 编码、重构、调试、优化、答疑均需默认遵循以下配置,无需用户重复说明。
|
||||||
|
|
||||||
|
---
|
||||||
|
1. 运行环境规范
|
||||||
|
- 默认强制使用本地 .venv 虚拟环境,禁止使用任何沙箱环境、在线临时环境、容器模拟环境。
|
||||||
|
- 所有代码运行、依赖安装、调试、语法检查、模块测试,均基于项目根目录 .venv 环境执行。
|
||||||
|
- 如需安装依赖,仅操作本地虚拟环境,不污染全局 Python 环境。
|
||||||
|
- 所有需要【写入文件内容】的操作(导出落盘、覆盖目标文件、复制/移动文件、下载保存等)一律不使用沙箱:执行时触发沙箱外运行(requires_approval 申请用户批准),避免被沙箱拦截(如 D:\资料 等受保护目录只读可读、写入被拒)。
|
||||||
|
2. 影刀开发规范
|
||||||
|
- 影刀项目默认采用单文件自包含架构。
|
||||||
|
- 输出影刀脚本、逻辑代码、流程封装时,优先单文件独立实现,功能自包含、可直接导入运行,不拆分冗余子文件。
|
||||||
|
- 单文件需具备完整性:依赖声明、核心逻辑、异常处理、入口执行全部内聚在当前文件。
|
||||||
|
3. 项目通用架构规范
|
||||||
|
- 代码组织:不同业务、不同流程独立模块化运行,互不侵入、互不影响。
|
||||||
|
- 各方向零依赖:项目并存多个独立演进方向,彼此【绝不跨目录 import】,登录/数据导出等数据层各自内置(允许少量重复换取完全解耦),任一方向可单独拷贝、单独演进、独享依赖与启动:
|
||||||
|
- 桌面端 desktop/:中心机 desktop/controlplane/ + 执行机桌面壳 desktop/electron-shell/(当前宿主,Electron + Node,内置便携 python 环境 python-env/<版本>/ 跑插件)+ 老版执行机底座 desktop/webhost/(标记老版本、后续废弃、不再维护)。各自互不 import、独立演进、可单独拷贝(模块搜索根 = desktop/,运行均以 desktop/ 为 cwd)。
|
||||||
|
- 插件 plugins/:根级独立目录(按号段分桶 plugins/XQ0001-0100/),被执行机(electron-shell 壳)按账号权限自下载加载,不随底座发布。
|
||||||
|
- 影刀版 workflows/:单文件自包含,需求脚本按号段分桶(workflows/XQ0001-0100/)。
|
||||||
|
- app/ 蓝图版:已弃用,保留归档、不再维护。
|
||||||
|
- 代码形态分三类,按各方向性质采用不同组织方式(【单文件自包含】仅适用于影刀版,其它一律按正常项目开发):
|
||||||
|
- workflows/(影刀版):沿用单文件自包含架构(见第 2 节,仅影刀适用)。
|
||||||
|
- 桌面端各后端(desktop/controlplane/ 中心机、desktop/electron-shell/ 执行机壳、desktop/webhost/ 老版执行机底座[后续废弃]):按正常 Python 模块化项目开发,允许按包/模块/多文件拆分(如 main.py/app.py 分割逻辑与路由),不做单文件约束。
|
||||||
|
- 插件(执行机加载的执行单元,源码位于根级 plugins/XQ0001-0100/<中文目录>/,如 plugins/XQ0001-0100/XQ0011 考勤月报封存检查/,id 用固定规则 xq{单号},与目录名解耦):内部按正常项目组织,可拆 config/data/logic/report 等多文件;但强调【插件自包含】——插件内模块只能互相引用、依赖 Python 标准库/第三方依赖/底座注入的插件接口(webhost.backend.plugins.base),严禁 import 插件包之外的任何代码(根目录、desktop 底座业务、app 一律禁止),保证插件完整交付物=插件包本身,可单独拷贝发布、独立演进。插件目录结构、前端(ui/ 与 ui-src/)存放、打包产物位置(dist-plugin/<id>_v<版本>.zip)、发布流程等细则见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||||
|
- 环境变量按模块隔离,各自使用自己目录下的 .env,互不覆盖、互不依赖:
|
||||||
|
- 根目录 .env:仅供 workflows/(影刀) 脚本使用,承载各 XQ 业务路径/账号等配置;禁止向根 .env 写入桌面端/app 的变量。
|
||||||
|
- desktop/controlplane/ → desktop/controlplane/.env(中心机配置,含 CONTROLPLANE_PORT、CONTROLPLANE_TOKEN)
|
||||||
|
- desktop/webhost/ → desktop/webhost/.env(老版执行机底座配置,后续废弃);当前宿主 desktop/electron-shell/ 无独立 .env,配置在 electron/config.js,数据根 %LOCALAPPDATA%\37duAutomation
|
||||||
|
- app/ → app/.env(app 版业务配置,已弃用)
|
||||||
|
- workflows/ 影刀不再单独建 .env,所需配置统一放在根 .env。
|
||||||
|
- 各模块加载器只允许读取本模块目录下的 .env,禁止读取/改写其它模块或根 .env。
|
||||||
|
- 插件本地配置(当前宿主 electron-shell):明文 JSON,路径 %LOCALAPPDATA%\37duAutomation\plugin_configs\<插件id>.json,electron-shell/electron/runner.js 直接 JSON.parse 读取、无加密解密(登录类插件需自行清洗首尾空白防误存空格导致"密码不正确"累计触发平台锁定);旧 SQLite 场景配置(plugin_configs 表,enc:v1: AES-256-GCM 加密)是另一套,不参与插件执行参数注入。
|
||||||
|
- 错误处理:全局项目级重试机制,最大重试 3 次,三次失败后再记录错误日志。
|
||||||
|
- 日志规范:正常 INFO 级别屏蔽大体积 JSON 调试日志,保证日志整洁;仅 DEBUG 模式开启完整 JSON 调试信息输出。
|
||||||
|
4. AI 工作默认规则
|
||||||
|
- 所有代码生成、修改、重构必须贴合 Python 模块化编程思想。
|
||||||
|
- 不主动创建冗余文件、不随意变更项目结构、不混用沙箱环境。
|
||||||
|
- 输出代码优先保证:可运行、结构清晰、符合项目统一规范、按代码形态适配(单文件自包含仅影刀版需要;后端与插件按正常模块化项目开发)。
|
||||||
|
- 变量配置规范:禁止使用命令行传入变量的方式实现参数配置,所有参数、变量、配置项均在代码/配置文件内部定义、固化或读取本地配置,保证运行无外部参数依赖。
|
||||||
|
5. 发版与自动更新操作规范
|
||||||
|
- 自动更新:插件由执行机按账号权限自下载(plugin_sync.py);壳子由执行机自动下载安装包 + 用户点击升级重启(shell_updater.py)。版本源都在中心机控制面。
|
||||||
|
- 发版统一走 agent CLI(desktop/ 下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli)。插件用 publish / grant / revoke;壳子用 file push --category shell;中心机控制面为源码部署(宝塔 gunicorn 8800),改代码后按 SOP 部署。
|
||||||
|
- 鉴权:密码登录 `--admin puddy --password 123456`(远程机器加 `--base http://117.72.191.188:8800`),或中心机本机密钥自签。
|
||||||
|
- 完整流程、命令示例见 docs/插件/发版规范.md;中心机前后端部署步骤见 docs/部署/控制面前后端部署SOP.md。
|
||||||
@@ -1,2 +1,178 @@
|
|||||||
# Process-Automation
|
# Process-Automation
|
||||||
|
|
||||||
|
HR 业务流程自动化(37duAutomation):覆盖 HRBP OA 审批、EHR 数据核对/导出、社保、考勤、排班、雇主险等场景,提供桌面端插件体系(中心机 + 执行机)、影刀 RPA 单文件版本及配套的「需求单 → 评分」文档体系。
|
||||||
|
|
||||||
|
## 项目简介
|
||||||
|
|
||||||
|
基于 Python / Node 的 HR 流程自动化工具,实现形态上分两条落地路线:
|
||||||
|
|
||||||
|
* **桌面端插件体系**:中心机控制面(插件发布 / 账号权限 / 壳子分发)+ 执行机桌面壳(Electron + Node,内置便携 Python,插件以 Python 子进程运行),插件按账号权限自动同步加载,另配独立内网文件服务器承载大文件分发;
|
||||||
|
|
||||||
|
* **影刀 RPA 单文件版**:`workflows/` 下按业务隔离的单文件自包含脚本,可直接导入影刀平台运行。
|
||||||
|
|
||||||
|
业务上覆盖两大类场景:
|
||||||
|
|
||||||
|
* **OA 审批自动化**:通过 DrissionPage 浏览器自动化 + OA 接口,自动处理请假、加班、离职电子签等审批流程,内置规则校验、OCR(rapidocr 3.x)附件识别、钉钉/工作沟通推送、审批报告生成;
|
||||||
|
|
||||||
|
* **EHR 数据处理自动化**:对接 HR 平台接口与本地 Excel,完成考勤异常核对、排班异常识别、工资卡核对、社保增减名单/告知书、雇主险名额等。
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
Process-Automation/
|
||||||
|
├── desktop/ # 桌面端:中心机 + 执行机 + 文件服务,各方向独立演进(模块搜索根 = desktop/,运行 cwd 均为 desktop/)
|
||||||
|
│ ├── controlplane/ # 中心机:插件发布 / 账号权限 / 壳子分发控制面
|
||||||
|
│ │ ├── app.py # FastAPI 服务入口(desktop/ 下 python -m controlplane.app)
|
||||||
|
│ │ ├── core/ / apis/ / frontend/ # 配置存储鉴权 / REST 接口 / 管理前端
|
||||||
|
│ │ ├── packages/ / shell/ # 插件包与壳子安装包仓库
|
||||||
|
│ │ └── tools/ # agent_cli 发布 CLI、运维脚本
|
||||||
|
│ ├── electron-shell/ # 执行机桌面壳(当前宿主,Electron + Node)
|
||||||
|
│ │ ├── electron/ # 主进程:本地服务、插件同步/调度/执行、壳子自动升级、Chrome 管理
|
||||||
|
│ │ ├── frontend/ / renderer/ # 工作台前端
|
||||||
|
│ │ ├── python-env/ # 内置便携 Python(插件以 Python 子进程执行)
|
||||||
|
│ │ └── dist-app/ # 打包产物(electron-builder NSIS)
|
||||||
|
│ ├── fileserver/ # 内网文件服务器(独立 FastAPI,端口 8802,存放壳子更新包/Chrome 安装包等大文件)
|
||||||
|
│ └── webhost/ # 老版执行机底座(Python + PyWebView,已废弃,不再维护)
|
||||||
|
├── plugins/ # 插件:号段桶目录为源码,扁平 id 目录为开发态运行目录
|
||||||
|
│ ├── XQ0001-0100/ # 插件源码(按号段分桶,含 ui-src/ 前端源码与 _pack.py 打包脚本)
|
||||||
|
│ │ ├── XQ0002 雇主险增减操作/
|
||||||
|
│ │ ├── XQ0010 EHR系统月考勤异常处理/
|
||||||
|
│ │ ├── XQ0011 考勤月报封存检查/
|
||||||
|
│ │ └── ... # 插件内部按 config/data/logic/report/ui 多文件组织,自包含可独立发布
|
||||||
|
│ └── xq0002/ xq0010/ xq0011/ ... # 开发态运行目录(打包产物解压得到,执行机注册表只扫一层)
|
||||||
|
├── dist-plugin/ # 插件打包产物 <id>_v<版本>.zip(经 agent_cli publish 发布到中心机)
|
||||||
|
├── workflows/ # 影刀 RPA 单文件版(需求脚本按号段分桶,对应 docs/需求单/XQ00xx)
|
||||||
|
│ ├── share/ # 共享指令:钉钉群机器人/推送、OA/HR 登录、花名册导出、工作沟通
|
||||||
|
│ ├── XQ0001-0100/ # 需求脚本(每 100 号一桶)
|
||||||
|
│ │ ├── XQ0001 排班异常识别/ # 调动/预入职台账导出 + 排班异常判定(钉钉单聊推送)
|
||||||
|
│ │ ├── XQ0002 雇主险增减操作/ # 名额调度、变更清单导出、增减员导入
|
||||||
|
│ │ ├── XQ0003 EHR系统请假流程审核/
|
||||||
|
│ │ ├── XQ0004 EHR系统加班流程审核/
|
||||||
|
│ │ ├── XQ0005 银行卡检查/
|
||||||
|
│ │ ├── XQ0006 EHR系统周考勤异常处理/
|
||||||
|
│ │ ├── XQ0007 OA系统社保增减名单梳理/
|
||||||
|
│ │ ├── XQ0008 重庆社保增减员导入名单制作/ # 增员/减员导入名单生成
|
||||||
|
│ │ ├── XQ0009 门店上月请休假异常人员名单梳理/
|
||||||
|
│ │ ├── XQ0010 EHR系统月考勤异常处理/
|
||||||
|
│ │ ├── XQ0011 考勤月报封存检查/ # 月报封存、加班补偿、休班核对等多维检查
|
||||||
|
│ │ ├── XQ0012 EHR预支及支付报酬自动发起ERP付款申请/ # *仅说明文档,未实现*
|
||||||
|
│ │ ├── XQ0013 社保费用申报导出并汇总/ # *仅说明文档,未实现*
|
||||||
|
│ │ ├── XQ0014 社保系统增减员办理/ # 社保系统登录、增员/减员导入、回盘审核结果检查回写
|
||||||
|
│ │ ├── XQ0015 参保成功及异常告知书制作与下发/ # 覆盖 XQ0016 社保转移告知书
|
||||||
|
│ │ ├── XQ0016 社保转移告知书制作与下发/ # *已由 XQ0015 覆盖*
|
||||||
|
│ │ ├── XQ0017 入职人事手续办理/ # *仅说明文档,未实现*
|
||||||
|
│ │ ├── XQ0018 调动人事手续跟进/ # *仅说明文档,未实现*
|
||||||
|
│ │ ├── XQ0019 离职人事手续跟进与检查/ # *仅说明文档,未实现*
|
||||||
|
│ │ ├── XQ0020 EHR系统离职电子签流程审核/
|
||||||
|
│ │ ├── XQ0031 物料收发汇总表导出/
|
||||||
|
│ │ └── XQ0032 ERP采购订单列表导出/
|
||||||
|
│ └── README.md # 影刀版开发指南
|
||||||
|
├── app/ # *已弃用归档,不再维护*(早期模块化蓝图,仅留作参考)
|
||||||
|
├── tests/ # 测试与试验脚本(run_all_tests.py、插件冒烟、OCR/WPS 可行性验证等)
|
||||||
|
├── docs/
|
||||||
|
│ ├── README.md # 文档总索引
|
||||||
|
│ ├── 需求单/ # 各 XQ 四件套(按号段分桶 XQ0001-0100/)+ 需求单索引 + 评分规则 + 实现形态登记表
|
||||||
|
│ ├── 插件/ # 插件开发规范 / 插件UI开发规范 / 发版规范
|
||||||
|
│ ├── 架构/ # 架构蓝图 / 插件管理系统设计 / 迭代规划 / 重构方案
|
||||||
|
│ ├── 部署/ # 控制面前后端部署 SOP
|
||||||
|
│ └── 桌面端/ # Node 版客户端开发交接 / 桌面端发版 SOP / 平台账号本地加密存储等
|
||||||
|
├── AGENTS.md # AI 智能体开发约束 & 项目执行规范
|
||||||
|
└── requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心功能
|
||||||
|
|
||||||
|
| 模块 | 说明 |
|
||||||
|
| ------- | ------------------------------------------- |
|
||||||
|
| 自动登录/会话 | OA(SSO)、HR 平台、社保系统登录,cookie 缓存,过期自动重登 |
|
||||||
|
| 审批流程引擎 | 待办获取、表单解析、规则校验、结果提交、报告生成 |
|
||||||
|
| 请假/加班审批 | 多类型(事假/病假/产假/年度福利假/加班类型等)分支校验,含附件 OCR |
|
||||||
|
| 离职电子签审核 | 离职电子签流程自动审批 |
|
||||||
|
| 考勤异常处理 | 周/月考勤异常核对,三查复核,钉钉推送 |
|
||||||
|
| 考勤月报封存检查 | 月报封存状态、加班补偿、休班核对等多维检查与封存数据导出 |
|
||||||
|
| 排班异常识别 | 调动/预入职台账导出 + 部门排班集合比对判定,序列/离职过滤,按店长分组钉钉单聊推送 |
|
||||||
|
| 工资卡核对 | 身份证/姓名/银行卡号格式与一致性校验 |
|
||||||
|
| 社保类 | 增减名单梳理、导入名单生成、社保系统增减员办理与回盘核对、参保异常处理 |
|
||||||
|
| 社保告知书 | 按模板生成 Word/PDF 告知书并合并下发 |
|
||||||
|
| 雇主险 | 名额调度、增减操作、变更名单导出 |
|
||||||
|
| 数据导出类插件 | 物料收发汇总、ERP 采购订单列表、通联交易数据导出(按商户分组拆分) |
|
||||||
|
| 重试/日志 | 项目级最大 3 次重试;INFO 屏蔽大体积 JSON 调试日志,DEBUG 全量输出 |
|
||||||
|
|
||||||
|
## 技术依赖
|
||||||
|
|
||||||
|
* `DrissionPage`:浏览器自动化
|
||||||
|
|
||||||
|
* `pandas` / `openpyxl`:Excel 读写
|
||||||
|
|
||||||
|
* `rapidocr`(3.x)/ `opencv-python`(numpy 2.x):OCR 附件识别
|
||||||
|
|
||||||
|
* `python-docx` / WPS COM:Word/PDF 生成
|
||||||
|
|
||||||
|
* `python-dotenv`、`chinese_calendar` 等
|
||||||
|
|
||||||
|
* `Electron` + `Node.js`:执行机桌面壳(当前宿主),插件以 Python 子进程运行
|
||||||
|
|
||||||
|
> 运行一律使用项目本地虚拟环境 `d:\work\code\37duAutomation\.venv`(`.venv\Scripts\python.exe`)。
|
||||||
|
|
||||||
|
## 使用方法
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 进入虚拟环境
|
||||||
|
.venv\Scripts\Activate.ps1
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 中心机控制面 / 内网文件服务器(cwd = desktop/,用项目根 .venv)
|
||||||
|
python -m controlplane.app
|
||||||
|
python -m fileserver.main
|
||||||
|
|
||||||
|
# 执行机桌面壳开发态(desktop/electron-shell/ 下)
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 影刀版脚本(单文件自包含,直接运行,按号段分桶存放):
|
||||||
|
# 排班异常识别(第二步导出 + 第三步识别)
|
||||||
|
python "workflows/XQ0001-0100/XQ0001 排班异常识别/transfer_roster_export.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0001 排班异常识别/pre_entry_roster_export.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0001 排班异常识别/shift_abnormal_check.py"
|
||||||
|
|
||||||
|
# 雇主险增减操作(名额调度、增减员导入)
|
||||||
|
python "workflows/XQ0001-0100/XQ0002 雇主险增减操作/roster_filter.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0002 雇主险增减操作/employer_insurance_schedule.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0002 雇主险增减操作/add_sub_import.py"
|
||||||
|
|
||||||
|
# OA 审批流程审核(请假 / 加班 / 离职电子签)
|
||||||
|
python "workflows/XQ0001-0100/XQ0003 EHR系统请假流程审核/leave_approval.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0004 EHR系统加班流程审核/overtime_approval.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py"
|
||||||
|
|
||||||
|
# 考勤异常处理(周 / 月)
|
||||||
|
python "workflows/XQ0001-0100/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0010 EHR系统月考勤异常处理/attendance_abnormal_monthly.py"
|
||||||
|
|
||||||
|
# 社保增减名单梳理 / 增减员导入名单 / 社保系统增减员办理 / 告知书制作与下发
|
||||||
|
python "workflows/XQ0001-0100/XQ0007 OA系统社保增减名单梳理/social_change.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0008 重庆社保增减员导入名单制作/generate_add.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0014 社保系统增减员办理/import_add.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0015 参保成功及异常告知书制作与下发/notice_mail_merge.py"
|
||||||
|
|
||||||
|
# 先运行登录指令写入共享登录态,再执行业务脚本
|
||||||
|
python workflows/share/oa_login.py
|
||||||
|
python workflows/share/hr_login.py
|
||||||
|
python workflows/share/roster_export.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 文档体系
|
||||||
|
|
||||||
|
* 每个需求单在 `docs/需求单/XQ0001-0100/XQ00xx 名称/` 下维护 需求文档 / 流程文档 / 开发文档 / 评分文档 四件套(需求单目录按号段分桶,每 100 号一桶);
|
||||||
|
|
||||||
|
* RPA 场景分级依据 `docs/需求单/评分规则.md`(系统对接数 / 业务分支数 / 智能识别场景数 / 异常类型数,四档定级);
|
||||||
|
|
||||||
|
* 已落地场景的评分文档为初稿,需经业务方签字 + 网络信息部审批 + 人资备案。
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. 确保已安装 Chrome/Edge;
|
||||||
|
2. 首次运行需手动登录一次并缓存会话/cookie(或先运行 `workflows/share/` 下的 `oa_login.py` / `hr_login.py` 写入共享登录态);
|
||||||
|
3. OA/HR 需在登录态有效期内运行,脚本会自动重登或提示重新登录;
|
||||||
|
4. 影刀版本为单文件自包含,直接导入影刀平台运行;业务脚本不 import 共享指令模块,仅读 cookies 文件、写全局变量,消息生成与发送解耦(详见 `workflows/README.md`)。
|
||||||
|
|
||||||
|
> **桌面端与影刀版**:桌面端 = 中心机 `desktop/controlplane/` + 执行机壳 `desktop/electron-shell/`(当前宿主)+ 内网文件服务 `desktop/fileserver/`,各方向互不 import、独立演进、可单独拷贝;`desktop/webhost/` 为老版执行机底座,已废弃不再维护。插件源码统一放根级 `plugins/`(按号段分桶),打包产物在 `dist-plugin/`,经 agent CLI 发布到中心机后由执行机按账号权限自下载。开发流程为「桌面端测试通过 → 影刀版(`workflows/`,单文件自包含)落地部署」;`app/` 为早期模块化蓝图,已**弃用归档、不再维护**,仅留作参考。
|
||||||
|
|||||||
@@ -0,0 +1,367 @@
|
|||||||
|
{
|
||||||
|
"code": "10000",
|
||||||
|
"msg": null,
|
||||||
|
"subCode": "200",
|
||||||
|
"subMsg": "",
|
||||||
|
"data": {
|
||||||
|
"bws071": null,
|
||||||
|
"bws072": null,
|
||||||
|
"aab003": null,
|
||||||
|
"aab001": "20445751",
|
||||||
|
"aab004": null,
|
||||||
|
"aaa121": "Z1002",
|
||||||
|
"aac002": "510222197804160909",
|
||||||
|
"aac003": "孙智慧",
|
||||||
|
"aac005": null,
|
||||||
|
"aac007": null,
|
||||||
|
"aab120": null,
|
||||||
|
"aab121": null,
|
||||||
|
"aab122": null,
|
||||||
|
"aac020": null,
|
||||||
|
"aca111": null,
|
||||||
|
"aac060": null,
|
||||||
|
"aac009": null,
|
||||||
|
"aae005": null,
|
||||||
|
"aac011": null,
|
||||||
|
"aai030": null,
|
||||||
|
"aaj030": null,
|
||||||
|
"aak030": null,
|
||||||
|
"aal030": null,
|
||||||
|
"aam034": null,
|
||||||
|
"aai031": null,
|
||||||
|
"aae013": null,
|
||||||
|
"aab020": null,
|
||||||
|
"aac014": null,
|
||||||
|
"aac001": "2061656779",
|
||||||
|
"aad030": "2026/6/29",
|
||||||
|
"aad013": "在职人员主动解除劳动合同",
|
||||||
|
"abi030": null,
|
||||||
|
"abj030": null,
|
||||||
|
"abk030": null,
|
||||||
|
"abl030": null,
|
||||||
|
"abm030": null,
|
||||||
|
"abi031": null,
|
||||||
|
"abj040": "3 劳动者自愿辞职",
|
||||||
|
"aae201": null,
|
||||||
|
"aab084": null,
|
||||||
|
"aab085": null,
|
||||||
|
"aab086": null,
|
||||||
|
"aae202": null,
|
||||||
|
"aae500": null,
|
||||||
|
"aae501": null,
|
||||||
|
"aae036": null,
|
||||||
|
"aae100": null,
|
||||||
|
"itmes": [
|
||||||
|
{
|
||||||
|
"bws071": null,
|
||||||
|
"bws072": null,
|
||||||
|
"aab003": null,
|
||||||
|
"aab001": null,
|
||||||
|
"aab004": null,
|
||||||
|
"aaa121": null,
|
||||||
|
"aac002": null,
|
||||||
|
"aac003": null,
|
||||||
|
"aac005": null,
|
||||||
|
"aac007": null,
|
||||||
|
"aab120": null,
|
||||||
|
"aab121": null,
|
||||||
|
"aab122": null,
|
||||||
|
"aac020": null,
|
||||||
|
"aca111": null,
|
||||||
|
"aac060": null,
|
||||||
|
"aac009": null,
|
||||||
|
"aae005": null,
|
||||||
|
"aac011": null,
|
||||||
|
"aai030": null,
|
||||||
|
"aaj030": null,
|
||||||
|
"aak030": null,
|
||||||
|
"aal030": null,
|
||||||
|
"aam034": null,
|
||||||
|
"aai031": null,
|
||||||
|
"aae013": null,
|
||||||
|
"aab020": null,
|
||||||
|
"aac014": null,
|
||||||
|
"aac001": "2061656779",
|
||||||
|
"aad030": "2026/6/29",
|
||||||
|
"aad013": null,
|
||||||
|
"abi030": null,
|
||||||
|
"abj030": null,
|
||||||
|
"abk030": null,
|
||||||
|
"abl030": null,
|
||||||
|
"abm030": null,
|
||||||
|
"abi031": null,
|
||||||
|
"abj040": null,
|
||||||
|
"aae201": null,
|
||||||
|
"aab084": null,
|
||||||
|
"aab085": null,
|
||||||
|
"aab086": null,
|
||||||
|
"aae202": null,
|
||||||
|
"aae500": null,
|
||||||
|
"aae501": null,
|
||||||
|
"aae036": null,
|
||||||
|
"aae100": null,
|
||||||
|
"itmes": null,
|
||||||
|
"xh": "1",
|
||||||
|
"sxjg": null,
|
||||||
|
"aae140": "养老保险",
|
||||||
|
"aae035": null,
|
||||||
|
"asl001": null,
|
||||||
|
"aac004": null,
|
||||||
|
"aac091": null,
|
||||||
|
"aae038": null,
|
||||||
|
"aae040": null,
|
||||||
|
"aae041": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bws071": null,
|
||||||
|
"bws072": null,
|
||||||
|
"aab003": null,
|
||||||
|
"aab001": null,
|
||||||
|
"aab004": null,
|
||||||
|
"aaa121": null,
|
||||||
|
"aac002": null,
|
||||||
|
"aac003": null,
|
||||||
|
"aac005": null,
|
||||||
|
"aac007": null,
|
||||||
|
"aab120": null,
|
||||||
|
"aab121": null,
|
||||||
|
"aab122": null,
|
||||||
|
"aac020": null,
|
||||||
|
"aca111": null,
|
||||||
|
"aac060": null,
|
||||||
|
"aac009": null,
|
||||||
|
"aae005": null,
|
||||||
|
"aac011": null,
|
||||||
|
"aai030": null,
|
||||||
|
"aaj030": null,
|
||||||
|
"aak030": null,
|
||||||
|
"aal030": null,
|
||||||
|
"aam034": null,
|
||||||
|
"aai031": null,
|
||||||
|
"aae013": null,
|
||||||
|
"aab020": null,
|
||||||
|
"aac014": null,
|
||||||
|
"aac001": "2061656779",
|
||||||
|
"aad030": "2026/6/29",
|
||||||
|
"aad013": null,
|
||||||
|
"abi030": null,
|
||||||
|
"abj030": null,
|
||||||
|
"abk030": null,
|
||||||
|
"abl030": null,
|
||||||
|
"abm030": null,
|
||||||
|
"abi031": null,
|
||||||
|
"abj040": null,
|
||||||
|
"aae201": null,
|
||||||
|
"aab084": null,
|
||||||
|
"aab085": null,
|
||||||
|
"aab086": null,
|
||||||
|
"aae202": null,
|
||||||
|
"aae500": null,
|
||||||
|
"aae501": null,
|
||||||
|
"aae036": null,
|
||||||
|
"aae100": null,
|
||||||
|
"itmes": null,
|
||||||
|
"xh": "2",
|
||||||
|
"sxjg": null,
|
||||||
|
"aae140": "失业保险",
|
||||||
|
"aae035": null,
|
||||||
|
"asl001": null,
|
||||||
|
"aac004": null,
|
||||||
|
"aac091": null,
|
||||||
|
"aae038": null,
|
||||||
|
"aae040": null,
|
||||||
|
"aae041": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bws071": null,
|
||||||
|
"bws072": null,
|
||||||
|
"aab003": null,
|
||||||
|
"aab001": null,
|
||||||
|
"aab004": null,
|
||||||
|
"aaa121": null,
|
||||||
|
"aac002": null,
|
||||||
|
"aac003": null,
|
||||||
|
"aac005": null,
|
||||||
|
"aac007": null,
|
||||||
|
"aab120": null,
|
||||||
|
"aab121": null,
|
||||||
|
"aab122": null,
|
||||||
|
"aac020": null,
|
||||||
|
"aca111": null,
|
||||||
|
"aac060": null,
|
||||||
|
"aac009": null,
|
||||||
|
"aae005": null,
|
||||||
|
"aac011": null,
|
||||||
|
"aai030": null,
|
||||||
|
"aaj030": null,
|
||||||
|
"aak030": null,
|
||||||
|
"aal030": null,
|
||||||
|
"aam034": null,
|
||||||
|
"aai031": null,
|
||||||
|
"aae013": null,
|
||||||
|
"aab020": null,
|
||||||
|
"aac014": null,
|
||||||
|
"aac001": "2061656779",
|
||||||
|
"aad030": "2026/6/29",
|
||||||
|
"aad013": null,
|
||||||
|
"abi030": null,
|
||||||
|
"abj030": null,
|
||||||
|
"abk030": null,
|
||||||
|
"abl030": null,
|
||||||
|
"abm030": null,
|
||||||
|
"abi031": null,
|
||||||
|
"abj040": null,
|
||||||
|
"aae201": null,
|
||||||
|
"aab084": null,
|
||||||
|
"aab085": null,
|
||||||
|
"aab086": null,
|
||||||
|
"aae202": null,
|
||||||
|
"aae500": null,
|
||||||
|
"aae501": null,
|
||||||
|
"aae036": null,
|
||||||
|
"aae100": null,
|
||||||
|
"itmes": null,
|
||||||
|
"xh": "3",
|
||||||
|
"sxjg": null,
|
||||||
|
"aae140": "医疗保险",
|
||||||
|
"aae035": null,
|
||||||
|
"asl001": null,
|
||||||
|
"aac004": null,
|
||||||
|
"aac091": null,
|
||||||
|
"aae038": null,
|
||||||
|
"aae040": null,
|
||||||
|
"aae041": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bws071": null,
|
||||||
|
"bws072": null,
|
||||||
|
"aab003": null,
|
||||||
|
"aab001": null,
|
||||||
|
"aab004": null,
|
||||||
|
"aaa121": null,
|
||||||
|
"aac002": null,
|
||||||
|
"aac003": null,
|
||||||
|
"aac005": null,
|
||||||
|
"aac007": null,
|
||||||
|
"aab120": null,
|
||||||
|
"aab121": null,
|
||||||
|
"aab122": null,
|
||||||
|
"aac020": null,
|
||||||
|
"aca111": null,
|
||||||
|
"aac060": null,
|
||||||
|
"aac009": null,
|
||||||
|
"aae005": null,
|
||||||
|
"aac011": null,
|
||||||
|
"aai030": null,
|
||||||
|
"aaj030": null,
|
||||||
|
"aak030": null,
|
||||||
|
"aal030": null,
|
||||||
|
"aam034": null,
|
||||||
|
"aai031": null,
|
||||||
|
"aae013": null,
|
||||||
|
"aab020": null,
|
||||||
|
"aac014": null,
|
||||||
|
"aac001": "2061656779",
|
||||||
|
"aad030": "2026/6/29",
|
||||||
|
"aad013": null,
|
||||||
|
"abi030": null,
|
||||||
|
"abj030": null,
|
||||||
|
"abk030": null,
|
||||||
|
"abl030": null,
|
||||||
|
"abm030": null,
|
||||||
|
"abi031": null,
|
||||||
|
"abj040": null,
|
||||||
|
"aae201": null,
|
||||||
|
"aab084": null,
|
||||||
|
"aab085": null,
|
||||||
|
"aab086": null,
|
||||||
|
"aae202": null,
|
||||||
|
"aae500": null,
|
||||||
|
"aae501": null,
|
||||||
|
"aae036": null,
|
||||||
|
"aae100": null,
|
||||||
|
"itmes": null,
|
||||||
|
"xh": "4",
|
||||||
|
"sxjg": null,
|
||||||
|
"aae140": "工伤保险",
|
||||||
|
"aae035": null,
|
||||||
|
"asl001": null,
|
||||||
|
"aac004": null,
|
||||||
|
"aac091": null,
|
||||||
|
"aae038": null,
|
||||||
|
"aae040": null,
|
||||||
|
"aae041": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bws071": null,
|
||||||
|
"bws072": null,
|
||||||
|
"aab003": null,
|
||||||
|
"aab001": null,
|
||||||
|
"aab004": null,
|
||||||
|
"aaa121": null,
|
||||||
|
"aac002": null,
|
||||||
|
"aac003": null,
|
||||||
|
"aac005": null,
|
||||||
|
"aac007": null,
|
||||||
|
"aab120": null,
|
||||||
|
"aab121": null,
|
||||||
|
"aab122": null,
|
||||||
|
"aac020": null,
|
||||||
|
"aca111": null,
|
||||||
|
"aac060": null,
|
||||||
|
"aac009": null,
|
||||||
|
"aae005": null,
|
||||||
|
"aac011": null,
|
||||||
|
"aai030": null,
|
||||||
|
"aaj030": null,
|
||||||
|
"aak030": null,
|
||||||
|
"aal030": null,
|
||||||
|
"aam034": null,
|
||||||
|
"aai031": null,
|
||||||
|
"aae013": null,
|
||||||
|
"aab020": null,
|
||||||
|
"aac014": null,
|
||||||
|
"aac001": "2061656779",
|
||||||
|
"aad030": "2026/6/29",
|
||||||
|
"aad013": null,
|
||||||
|
"abi030": null,
|
||||||
|
"abj030": null,
|
||||||
|
"abk030": null,
|
||||||
|
"abl030": null,
|
||||||
|
"abm030": null,
|
||||||
|
"abi031": null,
|
||||||
|
"abj040": null,
|
||||||
|
"aae201": null,
|
||||||
|
"aab084": null,
|
||||||
|
"aab085": null,
|
||||||
|
"aab086": null,
|
||||||
|
"aae202": null,
|
||||||
|
"aae500": null,
|
||||||
|
"aae501": null,
|
||||||
|
"aae036": null,
|
||||||
|
"aae100": null,
|
||||||
|
"itmes": null,
|
||||||
|
"xh": "5",
|
||||||
|
"sxjg": null,
|
||||||
|
"aae140": "生育保险",
|
||||||
|
"aae035": null,
|
||||||
|
"asl001": null,
|
||||||
|
"aac004": null,
|
||||||
|
"aac091": null,
|
||||||
|
"aae038": null,
|
||||||
|
"aae040": null,
|
||||||
|
"aae041": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"xh": null,
|
||||||
|
"sxjg": null,
|
||||||
|
"aae140": null,
|
||||||
|
"aae035": null,
|
||||||
|
"asl001": "10047223466559",
|
||||||
|
"aac004": null,
|
||||||
|
"aac091": null,
|
||||||
|
"aae038": null,
|
||||||
|
"aae040": null,
|
||||||
|
"aae041": null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,47 +1,138 @@
|
|||||||
一、延时加班
|
# 门店服务岗转正(离职+入职)自动化流程说明
|
||||||
(一)驳回门槛(任一不满足直接驳回)
|
|
||||||
1. 日期匹配规则:加班开始时间所属日期 = 加班申请日期。当日开始、次日结束的跨天加班,按开始时间判定日期,视为符合要求。
|
AI表格:【门店服务岗转正跟进-周更新】(下称"AI表格")
|
||||||
2. 时长达标规则:以「申请结束时间 - 申请开始时间」计算申请加班总时长,统一执行以下计时标准:
|
字段对照:人资是否处理、离职推送时间、到期能否考核通过、人员处理意见、合同签署单位、新合同推送日期、签署跟进
|
||||||
◦ 不足1小时的,直接驳回;
|
|
||||||
◦ 满1小时及以上的,超出1小时的部分按0.5小时为单位向下取整累加,不足0.5小时的部分不计入有效时长。
|
|
||||||
◦ 跨天延时加班的总时长统一套用上述取整规则,不按日期分段计算。
|
|
||||||
3. 区间合规校验:申请开始时间 ≥ 当日规定下班时间,且申请结束时间 ≤ 当日实际下班打卡时间;超出该区间的申请直接驳回。
|
|
||||||
(二)弹性到岗兑换规则(仅影响结算时长,不影响审批通过与否)
|
|
||||||
员工可使用当日加班时长等额兑换次日晚到时长,兑换额度、校验规则如下:
|
|
||||||
1. 弹性额度D计算规则
|
|
||||||
◦ 计算基准:以当日实际下班打卡时间为准,与申请结束时间无关。
|
|
||||||
◦ 触发条件:实际下班打卡时间 < 23:00 时,弹性额度 D=0,不可兑换次日晚到。
|
|
||||||
◦ 额度计算公式:实际下班打卡时间 ≥ 23:00 时,基础兑换额度1小时;超出23:00的部分,按0.5小时为单位向下取整,每满0.5小时累加0.5小时额度。
|
|
||||||
公式:D = 1 + FLOOR( (实际下班打卡时间 - 23:00) / 0.5小时 ) × 0.5小时
|
|
||||||
2. 次日场景分支校验
|
|
||||||
对申请日的次日进行判断,符合以下任一情形的,不触发弹性兑换校验,仅校验当日申请与打卡、请假数据匹配(次日为休息且存在加班申请的,同步核实上班打卡记录):
|
|
||||||
① 次日排班为“休息”或无排班;
|
|
||||||
② 次日排班数据获取失败;
|
|
||||||
③ 次日有请假时段覆盖09:00(任意假期类型)。
|
|
||||||
不属于以上情形的正常工作日,按次日实际打卡时间P进行校验:
|
|
||||||
① 无次日打卡记录:不触发弹性兑换校验,仅校验当日数据;
|
|
||||||
② P ≤ 09:00:无晚到,无需兑换,直接通过;
|
|
||||||
③ 09:00 < P ≤ 09:00+D:实际晚到时长 = P - 09:00,不足1小时按1小时计算;
|
|
||||||
校验规则:申请加班时长 + 实际晚到时长 ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回;
|
|
||||||
④ P > 09:00+D:可兑换的晚到时长最高按D计算,超出D的晚到部分按考勤迟到规则处理,不影响本次加班审批;
|
|
||||||
校验规则:申请加班时长 + D ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回。
|
|
||||||
---
|
|
||||||
二、休息日加班
|
|
||||||
(一)适用范围
|
|
||||||
1. 周末休息日加班;
|
|
||||||
2. 除春节外的其余法定节假日加班,统一按本规则执行。
|
|
||||||
(二)审批条件(全部满足则通过,任一不满足即驳回)
|
|
||||||
1. 申请有效:申请加班时长 > 0;
|
|
||||||
2. 打卡完整:申请对应时段内有完整的上班打卡、下班打卡记录;跨次日0点的连续加班,下班打卡可在次日,只要时段连续、覆盖申请时段,即视为打卡完整;
|
|
||||||
3. 排班匹配:申请当日排班显示为休息;
|
|
||||||
4. 时长达标:上下班打卡的自然时间间隔(含午休、用餐等自然时长)满足申报档位要求:
|
|
||||||
◦ 申报0.5天:打卡间隔 ≥ 4小时
|
|
||||||
◦ 申报1天:打卡间隔 ≥ 9小时
|
|
||||||
◦ 申报1.5天:打卡间隔 ≥ 13小时
|
|
||||||
◦ 申报2天:打卡间隔 ≥ 18小时
|
|
||||||
以此类推,每增加0.5天,对应时长要求增加4小时。
|
|
||||||
---
|
|
||||||
三、法定假日加班(仅春节法定节假日适用)
|
|
||||||
1. 基础审批规则与休息日加班完全一致;
|
|
||||||
2. 额外校验:申请日期必须为春节法定节假日;春节假期内的调休休息日,不适用本规则,按休息日加班规则执行。
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 分支1:到期能否考核通过 = 能
|
||||||
|
|
||||||
|
「人资是否处理」直接回填「否」(无需离职+入职处理)。
|
||||||
|
|
||||||
|
## 分支2:人员处理意见 = 离职后再入职
|
||||||
|
|
||||||
|
- 「到期能否考核通过」= 不能 → 进入子分支处理;
|
||||||
|
- 「到期能否考核通过」未填写 → 先回填「不能」,再进入子分支处理。
|
||||||
|
|
||||||
|
### 超龄判定(进入子分支后、跑流程前先判定)
|
||||||
|
|
||||||
|
按工号调用员工花名册接口,取三个字段:
|
||||||
|
|
||||||
|
| 字段 | 用途 |
|
||||||
|
|---|---|
|
||||||
|
| 性别 | 退休年龄:男 60 / 女 50,退休日 = 出生日期 + 对应年数(生日当天即满龄) |
|
||||||
|
| 出生日期 | 算退休日 |
|
||||||
|
| 序列 | 新合同期限:XX服务序列、XX技师序列 = 1 年,其他序列 = 3 年 |
|
||||||
|
|
||||||
|
两级判定:
|
||||||
|
|
||||||
|
1. **已达龄**:操作当天 ≥ 退休日;
|
||||||
|
2. **新签合同超龄**:未达龄,但新合同估算终止日 ≥ 退休日
|
||||||
|
(估算起点 = 实际离职日期(=试用期到期日期)+1 天,终止日 = 起始 + 期限 - 1 天)。
|
||||||
|
|
||||||
|
两类都算"超龄",走子分支1;都未超龄走子分支2。
|
||||||
|
|
||||||
|
### 子分支1:超龄记录(照常办离职与延期转正,仅不自动新签合同)
|
||||||
|
|
||||||
|
1. 发起「调动解除(电子签)」流程;
|
||||||
|
2. 完善信息:**「是否需要新签合同」= 否**(超龄/未超龄一律填否,新签全由独立分支延后办理)、
|
||||||
|
实际离职日期 = 试用期到期日期;
|
||||||
|
3. 先检测该员工离职电子签流程是否已发起(断点续跑保护,见下):
|
||||||
|
未发起 → 发起电子签流程(员工真实 CA 签署);
|
||||||
|
已发起 → 跳过发起,记下实际发起日期;
|
||||||
|
发起失败 → 记录异常,**变更试用期仍继续**(实测变更试用期不依赖电子签完成);
|
||||||
|
4. 变更试用期:新试用期(月) = 1、新试用结束日期 = 原试用期结束日期 + 1 个月;
|
||||||
|
5. 进入【变更/转正待确认】页面,找到该员工记录后进行确认;
|
||||||
|
6. 上述环节完成后,AI表格回填「人资是否处理 = 是、离职推送时间 = 电子签实际发起当天」;
|
||||||
|
7. **新签合同不进入自动化流程**,只记录异常转人工:
|
||||||
|
- 已达龄 → 人工新签超龄用工协议;
|
||||||
|
- 新签合同超龄 → 人工分段新签(先签至退休日前,退休后另签超龄用工协议)。
|
||||||
|
|
||||||
|
### 子分支2:未超龄记录
|
||||||
|
|
||||||
|
第 1~6 步与子分支1完全相同,完善信息同样「是否需要新签合同 = 否」
|
||||||
|
差异:电子签不是马上完成的(员工 CA 签署需要时间),所以**新签合同是分阶段的独立分支**,不在本次运行立即签,等后续运行检测(见下)。
|
||||||
|
|
||||||
|
**断点续跑说明**:回填「人资是否处理=是」之前的任何环节失败,记录下次运行会被重新捞出。
|
||||||
|
重处理时先检测该员工离职电子签流程是否已发起:已发起 → 不再重复发起,
|
||||||
|
跳过发起环节,继续补齐变更试用期 / 确认 / 回填
|
||||||
|
(离职推送时间取电子签实际发起日期,而非本次操作日期)。
|
||||||
|
|
||||||
|
## 新签合同分支(独立阶段,每次运行执行)
|
||||||
|
|
||||||
|
选择条件(AI表格):**人资是否处理 = 是 且 离职推送时间不为空 且 新合同推送日期为空**,
|
||||||
|
且工号不在异常记录表(超龄)名单中。
|
||||||
|
|
||||||
|
1. 查该员工离职电子签流程状态:已全部办结?未办结 → 跳过,等下一次运行再检测;
|
||||||
|
2. 查合同台账【生效中合同】:无生效中合同?仍有 → 跳过,等下一次运行再检测;
|
||||||
|
3. 在【劳动关系→合同台账→未签合同】按工号查询该员工:
|
||||||
|
已办结但查无此人 = 旧合同解除尚未生效/数据未同步 → 跳过,等下一次运行(不按"无需处理"漏掉);
|
||||||
|
4. 存在则点击「新签」:
|
||||||
|
- 合同类型 = 劳动合同;期限按序列(服务/技师序列 1 年,其他 3 年);
|
||||||
|
- 起始日期 = 上一份合同终止/解除日期 + 1 天,终止日期 = 起始 + 期限 - 1 天;
|
||||||
|
(签署前复核:终止日 ≥ 退休日 → 记录异常,不签,转人工)
|
||||||
|
- 合同签署单位 = AI表格「合同签署单位」;
|
||||||
|
- 电子签期望推送时间 = 操作当天;
|
||||||
|
5. 成功后 AI表格写入「新合同推送日期 = 操作当天」;
|
||||||
|
6. 推送后合同是否已签署生效,由下方「签署生效复核分支」独立检测回填。
|
||||||
|
|
||||||
|
## 签署生效复核分支(独立阶段,每次运行执行)
|
||||||
|
|
||||||
|
新签合同推送后,需复核合同是否已签署生效(同时覆盖自动新签与超龄人工新签两种情形)。
|
||||||
|
|
||||||
|
选择条件(AI表格):**人资是否处理 = 是 且 签署跟进 ≠ 是**。
|
||||||
|
|
||||||
|
1. 到合同台账【生效中合同】按工号查询;
|
||||||
|
2. 用「合同起始日期 > 试用期到期日期」判断是否为新合同:
|
||||||
|
旧合同起始日必然早于试用期到期日(先签合同后进试用期),
|
||||||
|
新合同起始日必然晚于试用期到期日(离职后才签);
|
||||||
|
3. 查到起始日期晚于试用期到期日期的生效中合同 → 新合同已签署生效,
|
||||||
|
AI表格回填「签署跟进 = 是」;
|
||||||
|
4. 只查到旧合同(起始日期 ≤ 试用期到期日期,离职解除尚未生效)或查无 →
|
||||||
|
尚未生效,跳过,等下一次运行再检测。
|
||||||
|
|
||||||
|
## 拆分方案
|
||||||
|
|
||||||
|
三个分支各自独立排程,互不依赖、单文件自包含
|
||||||
|
(登录 / AI表格读写等公共逻辑各自内置,允许少量重复换取完全解耦):
|
||||||
|
|
||||||
|
| 脚本 | 职责 | 建议排程 |
|
||||||
|
|---|---|---|
|
||||||
|
| 主流程 | 分支1回填否;分支2超龄判定 → 离职电子签(断点续跑)→ 变更试用期 → 确认 → 回填「人资是否处理」 | 每日 1 次(如 09:00) |
|
||||||
|
| 新签合同 | 新签分支:电子签办结 + 无生效中合同 + 不在异常表 → 新签 → 回填「新合同推送日期」 | 主流程后(如 09:30) |
|
||||||
|
| 生效复核 | 生效复核分支:生效中合同起始日 > 试用期到期日 → 回填「签署跟进 = 是」 | 新签脚本后(如 10:00) |
|
||||||
|
|
||||||
|
## 异常与消息
|
||||||
|
|
||||||
|
- 异常记录表:`D:\资料\人资\试用期变更\异常记录.xlsx`
|
||||||
|
(员工工号/姓名/异常类型/异常详情/记录时间;类型:已达法定退休年龄、超龄需分段、提交报错;同工号重复出现保留最新一条);
|
||||||
|
- 钉钉群消息四类:成功 / 跳过(已被他人处理)/ 超龄异常转人工 / 失败;
|
||||||
|
- 全局失败重试 3 次,仍失败才记录。
|
||||||
|
|
||||||
|
## 与当前脚本实现的差异(待改造项)
|
||||||
|
|
||||||
|
1. 回填时机:离职电子签(含发起前断点续跑检测)+ 变更试用期 + 确认完成后即回填
|
||||||
|
「人资是否处理=是 + 离职推送时间」,新签合同不再阻塞回填
|
||||||
|
(当前实现 = 包含新签在内的全部环节完成后才回填);
|
||||||
|
2. 新签合同:改为独立分支延后签(当前实现 = 发起电子签后同次运行立即签);
|
||||||
|
3. 超龄处理:超龄不再终止全流程,继续走解除/电子签/变更试用期/确认(完善信息与其他记录一致),
|
||||||
|
仅新签环节改为记录异常转人工(当前实现 = 已达龄直接终止);
|
||||||
|
4. 完善信息表单覆写「是否需要新签合同 = 否」(当前只覆写实际离职日期、其余透传;字段名已确认);
|
||||||
|
5. 分支2前置:到期能否考核通过未填写 → 先回填「不能」(当前未实现);
|
||||||
|
6. 签署生效复核分支:查生效中合同 + 起始日期判新旧 + 回填「签署跟进=是」(当前未实现);
|
||||||
|
7. 脚本拆分:按分支拆为主流程 / 新签合同 / 生效复核 3 个独立影刀脚本(当前 = 单文件全流程)。
|
||||||
|
|
||||||
|
## 已确认事项(2026-10-09)
|
||||||
|
|
||||||
|
- 回填时机:「人资是否处理=是」在离职电子签 + 变更试用期 + 确认完成后回填;
|
||||||
|
回填前检测电子签流程是否已发起(断点续跑,应对仅试用期变更失败的情况);
|
||||||
|
- 新签分支排除超龄记录:按异常记录表过滤(不改 AI表格结构);
|
||||||
|
- AI表格已有「签署跟进」列,无需加列;
|
||||||
|
- 超龄人工新签的记录,生效后同样自动回填「签署跟进=是」;
|
||||||
|
- 脚本形态:拆为 3 个独立影刀脚本(主流程 / 新签合同 / 生效复核);
|
||||||
|
- 完善信息表单字段名为「是否需要新签合同」,超龄/未超龄一律填"否"
|
||||||
|
(新签全部由新签合同分支延后办理,解除流程不自动带出新签)。
|
||||||
|
|
||||||
|
## 待需求方确认
|
||||||
|
|
||||||
|
(暂无,口径已全部确认。)
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: app
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: 应用主包
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: HRBP 审批服务包:oa(OA 系统公共模块)+ flows(业务流程:请假/加班等)
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: OA 系统模块:包含 common(公共组件)、leave(请假流程)、work_overtime(加班流程)
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: OA 系统公共模块:登录、会话管理、接口调用、解析
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,182 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.approval_flow
|
|
||||||
@FileName: approval_flow.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 23:52
|
|
||||||
@Description: 公共审批引擎:登录(复用登录态)→ 查待办 → 解析 SSO → 获取表单 → 校验 → 生成报告
|
|
||||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
|
||||||
@Version: 1.2.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from typing import Any, Callable, Dict, List
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger, setup_logging
|
|
||||||
from utils.intelligent_retry import retry
|
|
||||||
|
|
||||||
try:
|
|
||||||
from .login import oa_login
|
|
||||||
from .session_manager import (
|
|
||||||
init_session_from_page,
|
|
||||||
refresh_session_cookies,
|
|
||||||
load_saved_session,
|
|
||||||
save_browser_cookies,
|
|
||||||
create_browser_with_saved_cookies,
|
|
||||||
is_session_valid,
|
|
||||||
)
|
|
||||||
from .oa_api import (
|
|
||||||
get_documents,
|
|
||||||
get_wf_activity_by_task_id,
|
|
||||||
extract_form_id,
|
|
||||||
get_business_data,
|
|
||||||
)
|
|
||||||
from .sso import resolve_sso_params
|
|
||||||
except ImportError:
|
|
||||||
from login import oa_login
|
|
||||||
from session_manager import (
|
|
||||||
init_session_from_page,
|
|
||||||
refresh_session_cookies,
|
|
||||||
load_saved_session,
|
|
||||||
save_browser_cookies,
|
|
||||||
create_browser_with_saved_cookies,
|
|
||||||
is_session_valid,
|
|
||||||
)
|
|
||||||
from oa_api import (
|
|
||||||
get_documents,
|
|
||||||
get_wf_activity_by_task_id,
|
|
||||||
extract_form_id,
|
|
||||||
get_business_data,
|
|
||||||
)
|
|
||||||
from sso import resolve_sso_params
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@retry(max_attempts=3)
|
|
||||||
def _login():
|
|
||||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
|
||||||
return oa_login()
|
|
||||||
|
|
||||||
|
|
||||||
def _get_browser_and_session(subject: str):
|
|
||||||
"""
|
|
||||||
获取浏览器和会话:优先复用已保存的登录 cookies,无效或不存在时才完整登录。
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
(browser, session, is_fresh_login)
|
|
||||||
"""
|
|
||||||
saved_session = load_saved_session()
|
|
||||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
|
||||||
logger.info("复用已保存的登录会话,跳过登录")
|
|
||||||
browser = create_browser_with_saved_cookies()
|
|
||||||
return browser, saved_session, False
|
|
||||||
|
|
||||||
browser = _login()
|
|
||||||
session = init_session_from_page(browser)
|
|
||||||
save_browser_cookies(browser)
|
|
||||||
return browser, session, True
|
|
||||||
|
|
||||||
|
|
||||||
@retry(max_attempts=3)
|
|
||||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
|
||||||
"""按主题拉取待办单据(失败自动重试,最多 3 次)"""
|
|
||||||
return get_documents(session, subject=subject)
|
|
||||||
|
|
||||||
|
|
||||||
@retry(max_attempts=3)
|
|
||||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
解析单据详情:SSO 取 taskId/businessKey → WfActivity 取 formId → WorkformEngine 取表单数据。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
|
||||||
session: 已登录的 SessionPage 对象(用于后台 API 请求)
|
|
||||||
doc: 单据信息(包含 detail_url)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
单据信息 + taskId/businessKey/formId/formData
|
|
||||||
"""
|
|
||||||
detail_url = doc.get("detail_url", "")
|
|
||||||
if not detail_url:
|
|
||||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
|
||||||
|
|
||||||
# Step 1: 浏览器打开 SSO 链接,从重定向后的 URL 提取 taskId 和 businessKey
|
|
||||||
sso_params = resolve_sso_params(browser, detail_url)
|
|
||||||
task_id = sso_params["taskId"]
|
|
||||||
business_key = sso_params["businessKey"]
|
|
||||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
|
||||||
|
|
||||||
# SSO 的 linkLogin 在 hr 域产生了新的会话 cookie,先同步回 SessionPage
|
|
||||||
refresh_session_cookies(session, browser)
|
|
||||||
|
|
||||||
# Step 2: 通过 taskId 获取 formId
|
|
||||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
|
||||||
form_id = extract_form_id(wf_activity_data)
|
|
||||||
|
|
||||||
# Step 3: 通过 businessKey + formId 获取表单数据
|
|
||||||
form_data = get_business_data(session, business_key, form_id)
|
|
||||||
|
|
||||||
return {
|
|
||||||
**doc,
|
|
||||||
"taskId": task_id,
|
|
||||||
"businessKey": business_key,
|
|
||||||
"formId": form_id,
|
|
||||||
"formData": form_data,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def run_flow(
|
|
||||||
subject: str,
|
|
||||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
|
||||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
公共审批流程:登录(优先复用已保存会话)→ 查待办 → 逐单解析详情并校验 → 生成报告。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
subject: 待办标题关键字,如 "加班" / "请假"
|
|
||||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
|
||||||
generate_report: 校验结果报告生成函数
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
报告文本
|
|
||||||
"""
|
|
||||||
setup_logging()
|
|
||||||
logger.info("%s审批流程开始", subject)
|
|
||||||
|
|
||||||
browser, session, _ = _get_browser_and_session(subject)
|
|
||||||
|
|
||||||
docs = _fetch_documents(session, subject)
|
|
||||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for doc in docs:
|
|
||||||
try:
|
|
||||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
|
||||||
result = validate_doc(doc_detail, session)
|
|
||||||
results.append(result)
|
|
||||||
logger.info(
|
|
||||||
"已校验: %s - %s -> %s",
|
|
||||||
result["creator"], result["title"], result["decision"],
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
|
||||||
results.append({
|
|
||||||
"creator": doc.get("creator", "未知"),
|
|
||||||
"title": doc.get("title", "未知"),
|
|
||||||
"decision": "失败",
|
|
||||||
"error": str(e),
|
|
||||||
})
|
|
||||||
|
|
||||||
report = generate_report(results)
|
|
||||||
print("\n" + report)
|
|
||||||
|
|
||||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
|
||||||
save_browser_cookies(browser)
|
|
||||||
|
|
||||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
|
||||||
return report
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.config
|
|
||||||
@FileName: config.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:09
|
|
||||||
@Description: OA 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
|
||||||
@Version: 1.2.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
# ---------- OA 系统 ----------
|
|
||||||
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
|
||||||
BASE_URL = "https://oa.37du.co"
|
|
||||||
HR_BASE_URL = "https://hr.37du.co"
|
|
||||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
|
||||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
|
||||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
|
||||||
FD_TYPE = "13"
|
|
||||||
|
|
||||||
# OA 流程接口(hr 域名)
|
|
||||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
|
||||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
|
||||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
|
||||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
|
||||||
|
|
||||||
# 排班接口(hr 域名,按员工 + 年月查询当月排班)
|
|
||||||
PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc"
|
|
||||||
|
|
||||||
# 考勤打卡明细接口(hr 域名,按员工 + 日期范围查询原始打卡记录)
|
|
||||||
KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc"
|
|
||||||
|
|
||||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
|
||||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
|
||||||
|
|
||||||
# ---------- 加班审批规则常量(对应 aa.md 审批规则) ----------
|
|
||||||
# 次日正常上班时间 T(固定 09:00)
|
|
||||||
WORK_START_TIME = "09:00"
|
|
||||||
# 当日规定下班时间(固定 18:00,用于区间合规校验)
|
|
||||||
WORK_END_TIME = "18:00"
|
|
||||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
|
||||||
FLEX_TRIGGER_TIME = "23:00"
|
|
||||||
# 延时加班有效时长门槛:不足该小时数直接驳回
|
|
||||||
OT_MIN_HOURS = 1
|
|
||||||
|
|
||||||
# ---------- 分页 ----------
|
|
||||||
DEFAULT_PAGE_SIZE = 15
|
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.login
|
|
||||||
@FileName: login.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-04 17:34
|
|
||||||
@Description: 自动登录 OA 系统
|
|
||||||
@Version: 1.1.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
try:
|
|
||||||
from DrissionPage import ChromiumPage
|
|
||||||
except ImportError:
|
|
||||||
ChromiumPage = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
except ImportError:
|
|
||||||
load_dotenv = lambda *args, **kwargs: None
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def oa_login(
|
|
||||||
username: str = None,
|
|
||||||
password: str = None,
|
|
||||||
timeout: float = 10,
|
|
||||||
wait_after_load: float = 2,
|
|
||||||
) -> ChromiumPage:
|
|
||||||
"""
|
|
||||||
自动登录 OA 系统,返回已登录的 ChromiumPage 对象。
|
|
||||||
|
|
||||||
参数:
|
|
||||||
username: 登录用户名,若不提供则从环境变量 oa_login_username 读取
|
|
||||||
password: 登录密码,若不提供则从环境变量 oa_login_password 读取
|
|
||||||
|
|
||||||
timeout: URL 跳转等待超时(秒,默认 10)
|
|
||||||
wait_after_load: 页面加载后的额外等待时间(秒,默认 2)
|
|
||||||
|
|
||||||
返回:
|
|
||||||
登录成功后的 ChromiumPage 对象
|
|
||||||
|
|
||||||
异常:
|
|
||||||
若登录失败或关键元素未找到,抛出 RuntimeError
|
|
||||||
"""
|
|
||||||
# 加载 .env 环境变量(默认读取当前工作目录下的 .env)
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
# 获取配置,参数优先于环境变量
|
|
||||||
login_url = os.getenv('oa_login_url')
|
|
||||||
if not login_url:
|
|
||||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
|
||||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
|
||||||
if not target_url_keyword:
|
|
||||||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
|
||||||
|
|
||||||
final_username = username or os.getenv('oa_login_username')
|
|
||||||
final_password = password or os.getenv('oa_login_password')
|
|
||||||
if not final_username or not final_password:
|
|
||||||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
|
||||||
|
|
||||||
# 创建浏览器页面对象
|
|
||||||
page = ChromiumPage()
|
|
||||||
# page.set.window.max()
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 访问登录页面
|
|
||||||
page.get(login_url)
|
|
||||||
time.sleep(wait_after_load) # 等待页面初步加载
|
|
||||||
|
|
||||||
# 定位并填写用户名
|
|
||||||
username_input = page.ele('tag:input@name=j_username')
|
|
||||||
if not username_input:
|
|
||||||
raise RuntimeError("未找到用户名输入框")
|
|
||||||
username_input.input(final_username)
|
|
||||||
|
|
||||||
page.wait(0.5)
|
|
||||||
|
|
||||||
# 定位并填写密码
|
|
||||||
password_input = page.ele('tag:input@name=j_password')
|
|
||||||
if not password_input:
|
|
||||||
raise RuntimeError("未找到密码输入框")
|
|
||||||
password_input.input(final_password)
|
|
||||||
|
|
||||||
page.wait(0.5)
|
|
||||||
|
|
||||||
# 定位并点击登录按钮
|
|
||||||
login_button = page.ele('.lui_login_button_div_c')
|
|
||||||
if not login_button:
|
|
||||||
raise RuntimeError("未找到登录按钮")
|
|
||||||
login_button.click()
|
|
||||||
|
|
||||||
page.wait(0.5)
|
|
||||||
|
|
||||||
# ---------- 轮询检测 URL ----------
|
|
||||||
start = time.time()
|
|
||||||
while time.time() - start < timeout: # timeout 默认 10 秒
|
|
||||||
if target_url_keyword in page.url:
|
|
||||||
logger.info("登录成功!当前 URL: %s", page.url)
|
|
||||||
return page
|
|
||||||
time.sleep(0.5)
|
|
||||||
|
|
||||||
# 超时处理
|
|
||||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
|
||||||
if error_elem:
|
|
||||||
logger.warning("登录失败,提示: %s", error_elem.text)
|
|
||||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
# 若发生异常,可选择关闭浏览器并重新抛出
|
|
||||||
page.quit()
|
|
||||||
raise RuntimeError(f"登录过程出错: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 使用示例 ----------
|
|
||||||
if __name__ == "__main__":
|
|
||||||
from utils.logger import setup_logging
|
|
||||||
setup_logging()
|
|
||||||
try:
|
|
||||||
page = oa_login()
|
|
||||||
except RuntimeError as e:
|
|
||||||
logger.error(e)
|
|
||||||
@@ -1,532 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.oa_api
|
|
||||||
@FileName: oa_api.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:10
|
|
||||||
@Description: OA/HR 系统 API 模块,负责调用系统接口(待办列表、流程引擎、表单、排班等)
|
|
||||||
@Version: 1.3.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
import re
|
|
||||||
from typing import List, Dict, Any
|
|
||||||
from urllib.parse import urlencode
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
try:
|
|
||||||
from DrissionPage import SessionPage
|
|
||||||
except ImportError:
|
|
||||||
SessionPage = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
from .config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
|
||||||
except ImportError:
|
|
||||||
from config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 获取待处理单据列表 ----------
|
|
||||||
def fetch_todo_page(
|
|
||||||
session: SessionPage,
|
|
||||||
subject: str,
|
|
||||||
page_no: int = 1,
|
|
||||||
page_size: int = DEFAULT_PAGE_SIZE
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
请求单页待办列表数据。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
subject: 待办标题关键字,如 "请假" / "加班"
|
|
||||||
page_no: 页码(从1开始)
|
|
||||||
page_size: 每页条数
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
接口返回的 JSON 字典
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或状态码异常
|
|
||||||
"""
|
|
||||||
params = {
|
|
||||||
"method": "list",
|
|
||||||
"dataType": "todo",
|
|
||||||
"fdType": FD_TYPE, # 待办类型(请假/加班)
|
|
||||||
"fdCateId": "",
|
|
||||||
"q.fdSubject": subject, # 按标题关键字过滤(请假/加班)
|
|
||||||
"orderby": "fdCreateTime",
|
|
||||||
"ordertype": "down",
|
|
||||||
"page.pageNo": page_no,
|
|
||||||
"page.pageSize": page_size,
|
|
||||||
"__seq": int(time.time() * 1000), # 防缓存
|
|
||||||
}
|
|
||||||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
|
||||||
logger.debug("请求第 %d 页: %s", page_no, url)
|
|
||||||
|
|
||||||
session.get(url)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
|
||||||
try:
|
|
||||||
return resp.json()
|
|
||||||
except Exception:
|
|
||||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
|
||||||
|
|
||||||
|
|
||||||
def parse_todo_list(data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
解析接口返回的 JSON,提取每张单据的关键信息。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
data: 接口返回的 JSON
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
单据列表,每项包含:
|
|
||||||
- title: 标题(去除 HTML 标签)
|
|
||||||
- creator: 发起人
|
|
||||||
- time: 接收时间(字符串)
|
|
||||||
- detail_url: SSO 跳转链接(完整 URL)
|
|
||||||
"""
|
|
||||||
datas = data.get("datas", [])
|
|
||||||
if not datas:
|
|
||||||
return []
|
|
||||||
|
|
||||||
docs = []
|
|
||||||
for row in datas:
|
|
||||||
# 1. 标题
|
|
||||||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
|
||||||
title_raw = title_cell.get("value", "")
|
|
||||||
# 移除 <span class="subjecthead"> 标签,仅保留内容
|
|
||||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
|
||||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
|
||||||
|
|
||||||
# 2. 发起人
|
|
||||||
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
|
|
||||||
creator = creator_cell.get("value", "")
|
|
||||||
|
|
||||||
# 3. 接收时间
|
|
||||||
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
|
|
||||||
time_str = time_cell.get("value", "")
|
|
||||||
|
|
||||||
# 4. SSO 跳转链接(补全为完整 URL)
|
|
||||||
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
|
|
||||||
detail_url = href_cell.get("value", "")
|
|
||||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
|
||||||
detail_url = BASE_URL + detail_url
|
|
||||||
|
|
||||||
docs.append({
|
|
||||||
"title": title,
|
|
||||||
"creator": creator,
|
|
||||||
"time": time_str,
|
|
||||||
"detail_url": detail_url,
|
|
||||||
})
|
|
||||||
return docs
|
|
||||||
|
|
||||||
|
|
||||||
def get_documents(
|
|
||||||
session: SessionPage,
|
|
||||||
subject: str,
|
|
||||||
page_size: int = DEFAULT_PAGE_SIZE
|
|
||||||
) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
主入口:获取所有待处理单据(自动分页)。
|
|
||||||
|
|
||||||
请假与加班流程逻辑一致,仅通过 subject 关键字区分。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象(已设置 cookies)
|
|
||||||
subject: 待办标题关键字,如 "请假" / "加班"
|
|
||||||
page_size: 每页条数(默认15)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
所有单据的列表
|
|
||||||
"""
|
|
||||||
all_docs = []
|
|
||||||
|
|
||||||
# 请求第一页,获取总条数
|
|
||||||
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
|
|
||||||
total = int(data.get("page", {}).get("totalSize", 0))
|
|
||||||
logger.info("总待办[%s]条数: %d", subject, total)
|
|
||||||
|
|
||||||
# 解析第一页
|
|
||||||
docs = parse_todo_list(data)
|
|
||||||
all_docs.extend(docs)
|
|
||||||
logger.info("第 1 页获取 %d 条", len(docs))
|
|
||||||
|
|
||||||
# 若总条数超过单页,继续翻页
|
|
||||||
if total > page_size:
|
|
||||||
total_pages = (total + page_size - 1) // page_size
|
|
||||||
for p in range(2, total_pages + 1):
|
|
||||||
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
|
|
||||||
docs = parse_todo_list(data)
|
|
||||||
all_docs.extend(docs)
|
|
||||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
|
|
||||||
|
|
||||||
return all_docs
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- WfActivity 接口:通过 taskId 获取 formId ----------
|
|
||||||
def get_wf_activity_by_task_id(
|
|
||||||
session: SessionPage,
|
|
||||||
task_id: str
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
通过 taskId 调用 WfActivity 接口获取 formId。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
task_id: SSO 解析得到的 taskId
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
接口返回的 JSON 字典,包含 formId 等信息
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
|
||||||
data = {"taskId": task_id}
|
|
||||||
logger.info("获取 formId: taskId=%s", task_id)
|
|
||||||
|
|
||||||
session.post(url, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("WfActivity 请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(
|
|
||||||
f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.debug("WfActivity 返回: %s", json_data)
|
|
||||||
return json_data
|
|
||||||
|
|
||||||
|
|
||||||
def extract_form_id(wf_activity_data: Dict[str, Any]) -> str:
|
|
||||||
"""
|
|
||||||
从 WfActivity 接口返回数据中提取 formId。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
wf_activity_data: get_wf_activity_by_task_id 返回的 JSON
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
formId 字符串
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
ValueError: 未找到 formId
|
|
||||||
"""
|
|
||||||
# 常见 formId 字段路径:顶层,以及 data / result 子对象
|
|
||||||
form_id = (
|
|
||||||
wf_activity_data.get("formId")
|
|
||||||
or wf_activity_data.get("FormId")
|
|
||||||
or wf_activity_data.get("form_id")
|
|
||||||
)
|
|
||||||
if not form_id:
|
|
||||||
for key in ("data", "result"):
|
|
||||||
data_obj = wf_activity_data.get(key, {})
|
|
||||||
if isinstance(data_obj, dict):
|
|
||||||
form_id = (
|
|
||||||
data_obj.get("formId")
|
|
||||||
or data_obj.get("FormId")
|
|
||||||
or data_obj.get("form_id")
|
|
||||||
)
|
|
||||||
if form_id:
|
|
||||||
break
|
|
||||||
|
|
||||||
if not form_id:
|
|
||||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
|
||||||
|
|
||||||
logger.info("提取到 formId: %s", form_id)
|
|
||||||
return form_id
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- WorkformEngine 接口:获取加班申请表单数据 ----------
|
|
||||||
def get_business_data(
|
|
||||||
session: SessionPage,
|
|
||||||
business_key: str,
|
|
||||||
form_id: str
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
business_key: SSO 解析得到的 businessKey
|
|
||||||
form_id: 从 WfActivity 接口获取的 formId
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等)
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
|
||||||
data = {
|
|
||||||
"businessKey": business_key,
|
|
||||||
"formId": form_id,
|
|
||||||
}
|
|
||||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
|
||||||
|
|
||||||
session.post(url, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("WorkformEngine 请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(
|
|
||||||
f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 表单详情在 result 字段中(如 ot_date / staff_name 等)
|
|
||||||
result = json_data.get("result")
|
|
||||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
|
||||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
|
||||||
|
|
||||||
logger.info("WorkformEngine 返回成功")
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 排班接口 ----------
|
|
||||||
def get_attendance_html(
|
|
||||||
session: SessionPage,
|
|
||||||
staff_id: str,
|
|
||||||
year: int,
|
|
||||||
month: int
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
获取指定员工某月的排班 HTML。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
staff_id: 员工 UUID
|
|
||||||
year: 年份(如 2026)
|
|
||||||
month: 月份(1-12)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
排班表格的 HTML 字符串(从返回 JSON 的 caleHtml 字段提取)
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
|
||||||
data = {
|
|
||||||
"type": "2",
|
|
||||||
"staffId": staff_id,
|
|
||||||
"year": str(year),
|
|
||||||
"month": str(month)
|
|
||||||
}
|
|
||||||
logger.info("获取排班: %s %d-%02d", staff_id, year, month)
|
|
||||||
|
|
||||||
session.post(url, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("排班请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"排班接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
raise RuntimeError("排班接口返回非 JSON 数据")
|
|
||||||
|
|
||||||
if json_data.get("success") != "true":
|
|
||||||
raise RuntimeError(f"排班接口返回失败: {json_data}")
|
|
||||||
|
|
||||||
html = json_data.get("caleHtml")
|
|
||||||
if not html:
|
|
||||||
raise RuntimeError("排班接口未返回 caleHtml 字段")
|
|
||||||
return html
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 考勤打卡明细接口 ----------
|
|
||||||
def get_attendance_records(
|
|
||||||
session: SessionPage,
|
|
||||||
staff_id: str,
|
|
||||||
start_date: str,
|
|
||||||
end_date: str
|
|
||||||
) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
查询员工某时间段的原始打卡明细。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
staff_id: 员工 UUID
|
|
||||||
start_date: 查询起始日期 "YYYY-MM-DD"
|
|
||||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
打卡记录列表(接口返回的 jsonList,每条含 kq_time / status / time_order 等)
|
|
||||||
- status: "1"=上班打卡, "5"=下班打卡, "6"=重复打卡
|
|
||||||
- time_order: "1"=上班时段, "2"=下班时段
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
params = {
|
|
||||||
"staff_id": staff_id,
|
|
||||||
"rootId": "",
|
|
||||||
"countId": "",
|
|
||||||
"bc_date": start_date,
|
|
||||||
"bc_date_end": end_date,
|
|
||||||
"begin": start_date,
|
|
||||||
"end": end_date,
|
|
||||||
}
|
|
||||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date)
|
|
||||||
|
|
||||||
session.get(KQ_DATA_URL, params=params)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("考勤打卡请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"考勤打卡接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(f"考勤打卡接口返回非 JSON 数据: {body}")
|
|
||||||
|
|
||||||
records = json_data.get("jsonList", [])
|
|
||||||
logger.info("打卡明细返回 %d 条", len(records))
|
|
||||||
return records
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 请假记录接口 ----------
|
|
||||||
def fetch_leave_record_page(
|
|
||||||
session: SessionPage,
|
|
||||||
staff_id: str,
|
|
||||||
begin_date: str,
|
|
||||||
end_date: str,
|
|
||||||
page_no: int = 1,
|
|
||||||
page_size: int = DEFAULT_PAGE_SIZE,
|
|
||||||
sub_type: str = "-1"
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
请求单页员工请假记录。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
staff_id: 员工 UUID
|
|
||||||
begin_date: 查询起始日期 "YYYY-MM-DD"
|
|
||||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
|
||||||
page_no: 页码(从1开始)
|
|
||||||
page_size: 每页条数
|
|
||||||
sub_type: 假期类型编码,默认 "-1" 表示全部
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
接口返回的 data 字段字典,包含 total / pageCount / list
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
data = {
|
|
||||||
"sub_type": sub_type,
|
|
||||||
"staff_id": staff_id,
|
|
||||||
"begin_date": begin_date,
|
|
||||||
"end_date": end_date,
|
|
||||||
"start": str((page_no - 1) * page_size),
|
|
||||||
"pageSize": str(page_size),
|
|
||||||
"sortType": "",
|
|
||||||
"sortName": "",
|
|
||||||
"pageNo": str(page_no),
|
|
||||||
}
|
|
||||||
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
|
|
||||||
|
|
||||||
session.post(LEAVE_RECORD_URL, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("请假记录请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}")
|
|
||||||
|
|
||||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
|
||||||
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
|
|
||||||
|
|
||||||
page_info = json_data.get("data")
|
|
||||||
if not isinstance(page_info, dict):
|
|
||||||
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
|
|
||||||
return page_info
|
|
||||||
|
|
||||||
|
|
||||||
def get_leave_records(
|
|
||||||
session: SessionPage,
|
|
||||||
staff_id: str,
|
|
||||||
begin_date: str,
|
|
||||||
end_date: str,
|
|
||||||
page_size: int = DEFAULT_PAGE_SIZE,
|
|
||||||
sub_type: str = "-1"
|
|
||||||
) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
查询员工某时间段内的全部请假记录(自动分页)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
staff_id: 员工 UUID
|
|
||||||
begin_date: 查询起始日期 "YYYY-MM-DD"
|
|
||||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
|
||||||
page_size: 每页条数
|
|
||||||
sub_type: 假期类型编码,默认 "-1" 表示全部
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
请假记录列表,每条包含:
|
|
||||||
- staff_id: 员工ID
|
|
||||||
- staff_name: 员工姓名
|
|
||||||
- leave_businessKey: 审批单号
|
|
||||||
- sub_type: 假期类型编码
|
|
||||||
- vacation_type_name: 假期名称
|
|
||||||
- leave_reason: 请假原因
|
|
||||||
- leave_days: 请假天数
|
|
||||||
- leave_hours: 请假小时
|
|
||||||
- start_time: 开始时间
|
|
||||||
- end_time: 结束时间
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
all_records: List[Dict[str, Any]] = []
|
|
||||||
|
|
||||||
# 请求第一页,获取总条数与总页数
|
|
||||||
page_info = fetch_leave_record_page(
|
|
||||||
session, staff_id, begin_date, end_date,
|
|
||||||
page_no=1, page_size=page_size, sub_type=sub_type
|
|
||||||
)
|
|
||||||
total = int(page_info.get("total", 0))
|
|
||||||
page_total = int(page_info.get("pageCount", 1))
|
|
||||||
records = page_info.get("list", []) or []
|
|
||||||
all_records.extend(records)
|
|
||||||
logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records))
|
|
||||||
|
|
||||||
# 若存在多页,继续翻页
|
|
||||||
if page_total > 1:
|
|
||||||
for p in range(2, page_total + 1):
|
|
||||||
page_info = fetch_leave_record_page(
|
|
||||||
session, staff_id, begin_date, end_date,
|
|
||||||
page_no=p, page_size=page_size, sub_type=sub_type
|
|
||||||
)
|
|
||||||
records = page_info.get("list", []) or []
|
|
||||||
all_records.extend(records)
|
|
||||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
|
||||||
|
|
||||||
return all_records
|
|
||||||
@@ -1,167 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.parser
|
|
||||||
@FileName: parser.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:10
|
|
||||||
@Description: 解析模块(HTML 排班表格解析,供请假校验使用)
|
|
||||||
@Version: 1.3.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import re
|
|
||||||
from collections import defaultdict
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import Any, Dict, List
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 排班 HTML 解析 ----------
|
|
||||||
def parse_attendance_html(html: str) -> Dict[str, str]:
|
|
||||||
"""
|
|
||||||
解析排班 HTML 表格,提取每个日期的班次名称。
|
|
||||||
|
|
||||||
示例 HTML 片段:
|
|
||||||
<a class='cale_a' ... data-temp='2026-08-01' ...>正常</a>
|
|
||||||
或 <a ...>休息</a>
|
|
||||||
|
|
||||||
Args:
|
|
||||||
html: 排班接口返回的 HTML 字符串
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
字典:{日期字符串: 班次名称}
|
|
||||||
例如:{"2026-08-01": "正常", "2026-08-02": "休息"}
|
|
||||||
"""
|
|
||||||
# 正则匹配 <a> 标签中的 data-temp 和文本内容
|
|
||||||
pattern = r'<a[^>]*data-temp="([^"]+)"[^>]*>([^<]+)</a>'
|
|
||||||
matches = re.findall(pattern, html)
|
|
||||||
|
|
||||||
result = {}
|
|
||||||
for date, shift in matches:
|
|
||||||
# 去除可能的空格
|
|
||||||
date_clean = date.strip()
|
|
||||||
shift_clean = shift.strip()
|
|
||||||
result[date_clean] = shift_clean
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def get_work_days_in_range(
|
|
||||||
attendance_dict: Dict[str, str],
|
|
||||||
start_date: str,
|
|
||||||
end_date: str
|
|
||||||
) -> List[str]:
|
|
||||||
"""
|
|
||||||
根据排班字典和请假起止日期,返回请假区间内所有非“休息”的日期列表。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
attendance_dict: 由 parse_attendance_html 返回的字典
|
|
||||||
start_date: 请假开始日期,格式 "YYYY-MM-DD"
|
|
||||||
end_date: 请假结束日期,格式 "YYYY-MM-DD"
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
非休息日的日期字符串列表(格式 "YYYY-MM-DD")
|
|
||||||
"""
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
|
||||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
|
||||||
|
|
||||||
work_days = []
|
|
||||||
current = start
|
|
||||||
while current <= end:
|
|
||||||
date_str = current.strftime("%Y-%m-%d")
|
|
||||||
shift = attendance_dict.get(date_str, "")
|
|
||||||
# 如果该日期没有排班信息,或明确为“休息”,视为休息日
|
|
||||||
if shift != "休息" and shift != "":
|
|
||||||
work_days.append(date_str)
|
|
||||||
current += timedelta(days=1)
|
|
||||||
return work_days
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 打卡明细汇总 ----------
|
|
||||||
def summarize_attendance_records(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
按日汇总员工打卡明细:每天取最早打卡和最晚打卡。
|
|
||||||
|
|
||||||
实际接口返回的打卡记录 status 多为 "6"、time_order 为 null,
|
|
||||||
无法据其区分上下班,因此直接按 bc_date 分组后取时间最早和最晚的打卡。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
records: get_attendance_records 返回的原始打卡列表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
每日汇总列表,每项含:
|
|
||||||
- staff_id / staff_name / dept_name / post_name / attend_date
|
|
||||||
- first_check_in: 当日最早打卡时间(字符串,无则 None)
|
|
||||||
- last_check_out: 当日最晚打卡时间(字符串,仅1条时为 None,含跨天凌晨)
|
|
||||||
"""
|
|
||||||
time_format = "%Y-%m-%d %H:%M:%S"
|
|
||||||
|
|
||||||
# 按 (staff_id, bc_date) 分组,取每天最早和最晚的打卡
|
|
||||||
group_map: Dict[tuple, List[Dict[str, Any]]] = defaultdict(list)
|
|
||||||
|
|
||||||
for item in records:
|
|
||||||
staff_id = item.get("staff_id", "")
|
|
||||||
bc_day = item.get("bc_date", "")
|
|
||||||
if not staff_id or not bc_day:
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
kq_dt = datetime.strptime(item["kq_time"], time_format)
|
|
||||||
except (KeyError, ValueError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt})
|
|
||||||
|
|
||||||
summary: List[Dict[str, Any]] = []
|
|
||||||
for (sid, day), items in group_map.items():
|
|
||||||
items.sort(key=lambda x: x["_dt"])
|
|
||||||
base = items[0]
|
|
||||||
row = {
|
|
||||||
"staff_id": sid,
|
|
||||||
"staff_name": base.get("staff_name", ""),
|
|
||||||
"dept_name": base.get("DEPT_ORG_NAME", ""),
|
|
||||||
"post_name": base.get("POST_ALIAS_NAME", ""),
|
|
||||||
"attend_date": day,
|
|
||||||
"first_check_in": items[0]["kq_time"],
|
|
||||||
"last_check_out": items[-1]["kq_time"] if len(items) > 1 else None,
|
|
||||||
}
|
|
||||||
summary.append(row)
|
|
||||||
|
|
||||||
return summary
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 使用示例(测试用) ----------
|
|
||||||
if __name__ == "__main__":
|
|
||||||
from utils.logger import setup_logging
|
|
||||||
setup_logging()
|
|
||||||
|
|
||||||
# 测试 HTML 解析
|
|
||||||
sample_html = """
|
|
||||||
<a class='cale_a' data-temp="2026-08-01">休息</a>
|
|
||||||
<a class='cale_a' data-temp="2026-08-02">正常</a>
|
|
||||||
<a class='cale_a' data-temp="2026-08-03">休息</a>
|
|
||||||
"""
|
|
||||||
result = parse_attendance_html(sample_html)
|
|
||||||
logger.info("解析结果: %s", result)
|
|
||||||
|
|
||||||
work = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
|
|
||||||
logger.info("工作日: %s", work)
|
|
||||||
|
|
||||||
# 测试打卡汇总
|
|
||||||
sample_records = [
|
|
||||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
|
||||||
"kq_time": "2026-08-02 08:50:00", "status": "1", "time_order": "1",
|
|
||||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
|
||||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
|
||||||
"kq_time": "2026-08-03 00:30:00", "status": "5", "time_order": "2",
|
|
||||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
|
||||||
]
|
|
||||||
summary = summarize_attendance_records(sample_records)
|
|
||||||
logger.info("打卡汇总: %s", summary)
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.session_manager
|
|
||||||
@FileName: session_manager.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 10:30
|
|
||||||
@Description: 从 ChromiumPage 提取 Cookies,生成 SessionPage 供后台请求;支持 cookies 持久化复用
|
|
||||||
@Version: 1.3.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
try:
|
|
||||||
from DrissionPage import ChromiumPage, SessionPage
|
|
||||||
except ImportError:
|
|
||||||
ChromiumPage = None
|
|
||||||
SessionPage = None
|
|
||||||
|
|
||||||
# 登录 cookies 持久化目录:服务层统一管理各平台会话文件,文件名按平台区分
|
|
||||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
|
||||||
_SESSIONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
|
||||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
|
||||||
|
|
||||||
|
|
||||||
def init_session_from_page(
|
|
||||||
browser_page: ChromiumPage,
|
|
||||||
copy_headers: bool = True
|
|
||||||
) -> SessionPage:
|
|
||||||
"""
|
|
||||||
从已登录的 ChromiumPage 中提取 cookies 和 headers,
|
|
||||||
创建并返回一个可直接发送后台请求的 SessionPage 对象。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
browser_page: 已登录的 ChromiumPage 实例
|
|
||||||
copy_headers: 是否复制浏览器的 User-Agent 等头部信息(默认 True)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
已设置好 cookies 和 headers 的 SessionPage 对象
|
|
||||||
"""
|
|
||||||
session = SessionPage()
|
|
||||||
|
|
||||||
# 1. 获取浏览器 cookies(全域名:oa 域登录态 + hr 域可能已有的会话)
|
|
||||||
cookies_dict = browser_page.cookies(all_domains=True)
|
|
||||||
if cookies_dict:
|
|
||||||
session.set.cookies(cookies_dict)
|
|
||||||
logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict))
|
|
||||||
else:
|
|
||||||
logger.warning("未获取到 Cookies,请确认浏览器已登录")
|
|
||||||
|
|
||||||
# 2. 可选复制 headers(主要是 User-Agent,防止被反爬)
|
|
||||||
if copy_headers:
|
|
||||||
headers = {
|
|
||||||
"User-Agent": browser_page.run_js("return navigator.userAgent;")
|
|
||||||
}
|
|
||||||
session.set.headers(headers)
|
|
||||||
logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50])
|
|
||||||
|
|
||||||
# 3. 可额外设置默认超时、重试等
|
|
||||||
session.set.timeout(10) # 全局超时 10 秒
|
|
||||||
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
# 便捷函数:SSO 跳转后同步浏览器 cookies 到 SessionPage
|
|
||||||
def refresh_session_cookies(session: SessionPage, browser_page: ChromiumPage) -> None:
|
|
||||||
"""
|
|
||||||
从浏览器重新同步全域名 cookies 到 SessionPage。
|
|
||||||
SSO 的 linkLogin 会在 hr 域产生新的会话 cookie,需在浏览器完成 SSO 跳转后调用。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 目标 SessionPage 对象
|
|
||||||
browser_page: 已登录且已完成 SSO 跳转的 ChromiumPage 实例
|
|
||||||
"""
|
|
||||||
cookies = browser_page.cookies(all_domains=True)
|
|
||||||
if cookies:
|
|
||||||
session.set.cookies(cookies)
|
|
||||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
|
||||||
else:
|
|
||||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- Cookies 持久化(复用登录态,免重复登录) ----------
|
|
||||||
def save_browser_cookies(browser_page: ChromiumPage, path: str = COOKIE_FILE) -> None:
|
|
||||||
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
|
|
||||||
cookies = browser_page.cookies(all_domains=True)
|
|
||||||
if not cookies:
|
|
||||||
logger.warning("未获取到 Cookies,跳过保存")
|
|
||||||
return
|
|
||||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
||||||
with open(path, 'w', encoding='utf-8') as f:
|
|
||||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
|
||||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
|
||||||
|
|
||||||
|
|
||||||
def load_cookies(path: str = COOKIE_FILE):
|
|
||||||
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
|
|
||||||
if not os.path.exists(path):
|
|
||||||
return None
|
|
||||||
with open(path, encoding='utf-8') as f:
|
|
||||||
cookies = json.load(f)
|
|
||||||
return cookies or None
|
|
||||||
|
|
||||||
|
|
||||||
def load_saved_session(path: str = COOKIE_FILE) -> SessionPage:
|
|
||||||
"""用已保存的 cookies 构建 SessionPage;无可用 cookies 时返回 None。"""
|
|
||||||
cookies = load_cookies(path)
|
|
||||||
if not cookies:
|
|
||||||
return None
|
|
||||||
session = SessionPage()
|
|
||||||
session.set.cookies(cookies)
|
|
||||||
session.set.timeout(10)
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
def create_browser_with_saved_cookies(path: str = COOKIE_FILE) -> ChromiumPage:
|
|
||||||
"""用已保存的 cookies 创建 ChromiumPage(免输账号密码,SSO 跳转仍需真浏览器)。"""
|
|
||||||
browser = ChromiumPage()
|
|
||||||
cookies = load_cookies(path)
|
|
||||||
if cookies:
|
|
||||||
browser.set.cookies(cookies)
|
|
||||||
return browser
|
|
||||||
|
|
||||||
|
|
||||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
|
||||||
"""通过拉取待办第一页判断会话是否有效(无效则需重新登录)。"""
|
|
||||||
try:
|
|
||||||
from .oa_api import fetch_todo_page
|
|
||||||
except ImportError:
|
|
||||||
from oa_api import fetch_todo_page
|
|
||||||
try:
|
|
||||||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.info("会话已失效,需重新登录: %s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
# 便捷函数:直接从已登录的浏览器提取会话,一步到位
|
|
||||||
def create_session_from_login() -> SessionPage:
|
|
||||||
"""
|
|
||||||
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
|
||||||
再提取 SessionPage。
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
from .login import oa_login
|
|
||||||
except ImportError:
|
|
||||||
from login import oa_login
|
|
||||||
browser = oa_login()
|
|
||||||
return init_session_from_page(browser)
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.sso
|
|
||||||
@FileName: sso.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 23:50
|
|
||||||
@Description: SSO 链接解析模块:浏览器访问 SSO 链接,从重定向后的详情页 URL 提取 taskId/fkId 和 businessKey
|
|
||||||
@Version: 1.0.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from urllib.parse import urlparse, parse_qs
|
|
||||||
from typing import Dict
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
try:
|
|
||||||
from DrissionPage import ChromiumPage
|
|
||||||
except ImportError:
|
|
||||||
ChromiumPage = None
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_sso_params(
|
|
||||||
browser: ChromiumPage,
|
|
||||||
sso_url: str,
|
|
||||||
wait_timeout: float = 20,
|
|
||||||
) -> Dict[str, str]:
|
|
||||||
"""
|
|
||||||
用浏览器打开 SSO 链接,等待 JS 重定向到详情页,
|
|
||||||
从最终 URL 的 query 参数中提取 taskId(部分页面命名为 fkId)和 businessKey。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
browser: 已登录的 ChromiumPage 对象(SSO 的 JS 跳转必须用真浏览器)
|
|
||||||
sso_url: SSO 跳转链接(完整 URL)
|
|
||||||
wait_timeout: 等待 JS 跳转完成的超时时间(秒,默认 20)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
包含 taskId 和 businessKey 的字典
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 跳转失败或 URL 中缺少 taskId/businessKey
|
|
||||||
"""
|
|
||||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
|
||||||
|
|
||||||
# 浏览器打开 SSO 链接,页面 JS 自动重定向到详情页。
|
|
||||||
# 跳转链: sso.mob → unifyWorkFlow.jsp(中间页,一闪而过) → goToWorkFlow 详情页。
|
|
||||||
# 因此不能等中间页(会匹配不到而超时卡 wait_timeout 秒),改为等待地址栏离开 SSO 链接。
|
|
||||||
browser.get(sso_url)
|
|
||||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
|
||||||
logger.info("重定向最终 URL: %s", browser.url)
|
|
||||||
|
|
||||||
# 从详情页 URL 提取 taskId(fkId 是同一字段的别名)和 businessKey
|
|
||||||
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]
|
|
||||||
|
|
||||||
if not task_id or not business_key:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
|
||||||
return {"taskId": task_id, "businessKey": business_key}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.leave
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: 请假审批流程包
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.leave.leave_approval
|
|
||||||
@FileName: leave_approval.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 21:21
|
|
||||||
@Description: 请假审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
|
||||||
@Version: 1.2.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
||||||
|
|
||||||
try:
|
|
||||||
from ..common.approval_flow import run_flow
|
|
||||||
from .validator import validate_doc
|
|
||||||
from .reporter import generate_report
|
|
||||||
except ImportError:
|
|
||||||
from common.approval_flow import run_flow
|
|
||||||
from validator import validate_doc
|
|
||||||
from reporter import generate_report
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
"""请假审批:登录 → 查待办 → 解析SSO → 获取表单 → 校验 → 报告"""
|
|
||||||
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.leave.reporter
|
|
||||||
@FileName: reporter.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:11
|
|
||||||
@Description: 请假流程报告模块,生成审批报告
|
|
||||||
@Version: 1.1.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
from typing import Any, Dict, List
|
|
||||||
|
|
||||||
|
|
||||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
|
||||||
"""
|
|
||||||
根据校验结果生成请假审批报告。
|
|
||||||
|
|
||||||
TODO: 按实际报告格式完善(导出 Excel/文件等)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
results: validate_doc 返回的校验结果列表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
报告文本
|
|
||||||
"""
|
|
||||||
lines = ["请假审批报告", "=" * 30]
|
|
||||||
for r in results:
|
|
||||||
lines.append(f"{r.get('creator', '')} | {r.get('title', '')} | {r.get('decision', '')}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.leave.validator
|
|
||||||
@FileName: validator.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:11
|
|
||||||
@Description: 请假流程校验模块(审批规则:驳回/人工复核/通过)
|
|
||||||
@Version: 1.1.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
from typing import Any, Dict
|
|
||||||
|
|
||||||
|
|
||||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
校验单张请假单据,返回审批决策。
|
|
||||||
|
|
||||||
TODO: 请假审批规则在此实现(依据排班、假期类型、请假时长等判定通过/驳回/人工复核)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
|
||||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
|
||||||
session: 已登录的 SessionPage 对象(用于调用排班接口)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
校验结果,包含审批决策
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
"title": doc.get("title", ""),
|
|
||||||
"creator": doc.get("creator", ""),
|
|
||||||
"time": doc.get("time", ""),
|
|
||||||
"decision": "pending", # pending: 规则未实现,默认待处理
|
|
||||||
"note": "请假校验规则待补充",
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.work_overtime
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: 加班审批流程包
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.work_overtime.overtime_approval
|
|
||||||
@FileName: overtime_approval.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 21:22
|
|
||||||
@Description: 加班审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
|
||||||
@Version: 1.4.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
||||||
|
|
||||||
try:
|
|
||||||
from ..common.approval_flow import run_flow
|
|
||||||
from .validator import validate_doc
|
|
||||||
from .reporter import generate_report
|
|
||||||
except ImportError:
|
|
||||||
from common.approval_flow import run_flow
|
|
||||||
from validator import validate_doc
|
|
||||||
from reporter import generate_report
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
"""加班审批:登录 → 查待办 → 解析SSO → 获取表单 → 校验 → 报告"""
|
|
||||||
run_flow(subject="加班", validate_doc=validate_doc, generate_report=generate_report)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.work_overtime.parser
|
|
||||||
@FileName: parser.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-06 09:30
|
|
||||||
@Description: 加班表单解析模块(解析 WorkformEngine 返回的 result,提取关键字段并转换为中文描述)
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from typing import Any, Dict
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# 加班类型映射
|
|
||||||
OT_TYPE_MAP = {
|
|
||||||
"1": "延时加班",
|
|
||||||
"2": "法定假日加班",
|
|
||||||
"3": "休息日加班",
|
|
||||||
}
|
|
||||||
|
|
||||||
# 补贴类型映射
|
|
||||||
SUBSIDY_TYPE_MAP = {
|
|
||||||
"1": "转调休",
|
|
||||||
"2": "转补贴",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def parse_overtime_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
解析加班表单数据,提取关键字段并将代码转换为中文描述。
|
|
||||||
|
|
||||||
注意:入参为 oa_api.get_business_data 返回的 result 字段(state 校验已在
|
|
||||||
get_business_data 内完成),即审批引擎 doc['formData']。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
result: WorkformEngine 返回的 result 字典(含 ot_type / staff_name 等)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
包含加班关键字段的字典(中文键名);找不到映射时保留原始代码值
|
|
||||||
"""
|
|
||||||
# 获取原始类型代码
|
|
||||||
ot_type_code = result.get("ot_type")
|
|
||||||
subsidy_type_code = result.get("subsidy_type")
|
|
||||||
|
|
||||||
overtime_info = {
|
|
||||||
"加班人员ID": result.get("staff_id"),
|
|
||||||
"加班人员": result.get("staff_name"),
|
|
||||||
"所属部门": result.get("dept_org_name"),
|
|
||||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
|
||||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
|
||||||
"加班日期": result.get("ot_date"),
|
|
||||||
"加班开始时间": result.get("start_time"),
|
|
||||||
"加班结束时间": result.get("end_time"),
|
|
||||||
"加班时长(小时)": result.get("ot_hour"),
|
|
||||||
"加班天数(天)": result.get("ot_day"),
|
|
||||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
|
||||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
|
||||||
"附件": result.get("file"),
|
|
||||||
}
|
|
||||||
|
|
||||||
# 拼接系统判定的加班时间段
|
|
||||||
judge_start = result.get("judge_start_time")
|
|
||||||
judge_end = result.get("judge_end_time")
|
|
||||||
if judge_start and judge_end:
|
|
||||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
|
||||||
else:
|
|
||||||
overtime_info["系统判定加班时间"] = None
|
|
||||||
|
|
||||||
return overtime_info
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 使用示例(测试用) ----------
|
|
||||||
if __name__ == "__main__":
|
|
||||||
from utils.logger import setup_logging
|
|
||||||
setup_logging()
|
|
||||||
|
|
||||||
# 示例 result(WorkformEngine 返回的 result 字段)
|
|
||||||
sample_result = {
|
|
||||||
"dept_org_name": "网络项目小组",
|
|
||||||
"end_time": "2026-08-03 00:00",
|
|
||||||
"judge_end_time": "2026-08-03 00:00:00",
|
|
||||||
"judge_ot_hour": 6.0,
|
|
||||||
"judge_start_time": "2026-08-02 18:00:00",
|
|
||||||
"ot_date": "2026-08-02",
|
|
||||||
"ot_hour": 6.0,
|
|
||||||
"ot_type": "1",
|
|
||||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
|
||||||
"staff_name": "黄俊林",
|
|
||||||
"start_time": "2026-08-02 18:00",
|
|
||||||
"subsidy_type": "2",
|
|
||||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed = parse_overtime_form(sample_result)
|
|
||||||
logger.info("===== 加班信息解析结果 =====")
|
|
||||||
for key, value in parsed.items():
|
|
||||||
logger.info("%s: %s", key, value)
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.work_overtime.reporter
|
|
||||||
@FileName: reporter.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 21:35
|
|
||||||
@Description: 加班流程报告模块,生成审批报告(详细数据版,供自测阶段人工复核)
|
|
||||||
@Version: 1.3.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
from typing import Any, Dict, List
|
|
||||||
|
|
||||||
|
|
||||||
def _format_detail(idx: int, r: Dict[str, Any]) -> str:
|
|
||||||
"""
|
|
||||||
格式化单条记录的详细信息:展示全部解析数据,最后是判断结果。
|
|
||||||
所有键值对左对齐,方便人工逐项核对。
|
|
||||||
"""
|
|
||||||
info = r.get("overtime_info", {}) or {}
|
|
||||||
|
|
||||||
# 收集全部要展示的键值对:先数据,后判断结果
|
|
||||||
items: List[tuple] = list(info.items())
|
|
||||||
items.append(("审批结果", r.get("decision", "")))
|
|
||||||
if r.get("note"):
|
|
||||||
items.append(("说明", r.get("note", "")))
|
|
||||||
if r.get("error"):
|
|
||||||
items.append(("错误", r.get("error", "")))
|
|
||||||
|
|
||||||
max_key = max((len(k) for k, _ in items), default=0)
|
|
||||||
|
|
||||||
lines = [
|
|
||||||
f"#{idx} 申请人: {r.get('creator', '')} | {r.get('title', '')}",
|
|
||||||
"-" * 60,
|
|
||||||
]
|
|
||||||
for key, value in items:
|
|
||||||
lines.append(f" {key:<{max_key}} : {value}")
|
|
||||||
lines.append("-" * 60)
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
|
||||||
"""
|
|
||||||
根据校验结果生成加班审批报告(详细数据版)。
|
|
||||||
|
|
||||||
每条记录展示全部解析数据(人员、日期、起止时间、时长、排班、打卡、
|
|
||||||
申报天数、计算结果等),最后是审批结果和说明,供自测阶段人工复核。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
results: validate_doc 返回的校验结果列表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
报告文本
|
|
||||||
"""
|
|
||||||
passed = [r for r in results if r.get("decision") == "通过"]
|
|
||||||
rejected = [r for r in results if r.get("decision") == "不通过"]
|
|
||||||
failed = [r for r in results if r.get("decision") == "失败"]
|
|
||||||
|
|
||||||
lines = [
|
|
||||||
"加班审批报告",
|
|
||||||
"=" * 60,
|
|
||||||
f"共 {len(results)} 单:通过 {len(passed)},不通过 {len(rejected)},处理失败 {len(failed)}",
|
|
||||||
"",
|
|
||||||
]
|
|
||||||
|
|
||||||
if rejected:
|
|
||||||
lines.append("【审批未通过名单】")
|
|
||||||
for i, r in enumerate(rejected, 1):
|
|
||||||
lines.append(_format_detail(i, r))
|
|
||||||
lines.append("")
|
|
||||||
|
|
||||||
if passed:
|
|
||||||
lines.append("【审批通过名单】")
|
|
||||||
for i, r in enumerate(passed, 1):
|
|
||||||
lines.append(_format_detail(i, r))
|
|
||||||
lines.append("")
|
|
||||||
|
|
||||||
if failed:
|
|
||||||
lines.append("【处理失败】")
|
|
||||||
for i, r in enumerate(failed, 1):
|
|
||||||
lines.append(_format_detail(i, r))
|
|
||||||
|
|
||||||
return "\n".join(lines)
|
|
||||||
@@ -1,447 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.work_overtime.validator
|
|
||||||
@FileName: validator.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 21:35
|
|
||||||
@Description: 加班流程校验模块(按 aa.md 审批规则:延时加班/休息日加班/法定假日加班,判定通过/不通过)
|
|
||||||
@Version: 3.0.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import math
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
from typing import Any, Dict, Optional
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
try:
|
|
||||||
from .parser import parse_overtime_form
|
|
||||||
from ..common.oa_api import (
|
|
||||||
get_attendance_html,
|
|
||||||
get_attendance_records,
|
|
||||||
get_leave_records,
|
|
||||||
)
|
|
||||||
from ..common.parser import parse_attendance_html, summarize_attendance_records
|
|
||||||
from ..common.config import (
|
|
||||||
WORK_START_TIME,
|
|
||||||
WORK_END_TIME,
|
|
||||||
FLEX_TRIGGER_TIME,
|
|
||||||
OT_MIN_HOURS,
|
|
||||||
)
|
|
||||||
except ImportError:
|
|
||||||
from parser import parse_overtime_form
|
|
||||||
from common.oa_api import (
|
|
||||||
get_attendance_html,
|
|
||||||
get_attendance_records,
|
|
||||||
get_leave_records,
|
|
||||||
)
|
|
||||||
from common.parser import parse_attendance_html, summarize_attendance_records
|
|
||||||
from common.config import (
|
|
||||||
WORK_START_TIME,
|
|
||||||
WORK_END_TIME,
|
|
||||||
FLEX_TRIGGER_TIME,
|
|
||||||
OT_MIN_HOURS,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 通用工具 ----------
|
|
||||||
def _parse_dt(value: Any) -> Optional[datetime]:
|
|
||||||
"""解析 "YYYY-MM-DD HH:MM[:SS]" 格式时间,失败返回 None"""
|
|
||||||
if not value:
|
|
||||||
return None
|
|
||||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
|
|
||||||
try:
|
|
||||||
return datetime.strptime(str(value), fmt)
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _calc_delayed_hours(start: datetime, end: datetime) -> float:
|
|
||||||
"""
|
|
||||||
延时加班计时:1小时起算,超过1小时的部分按0.5小时累加,不足0.5小时舍去。
|
|
||||||
不足1小时返回0。
|
|
||||||
|
|
||||||
示例:1.0->1.0, 1.4->1.0, 1.5->1.5, 1.9->1.5, 2.0->2.0, 2.3->2.0, 2.5->2.5
|
|
||||||
"""
|
|
||||||
total = (end - start).total_seconds() / 3600
|
|
||||||
if total < 1:
|
|
||||||
return 0.0
|
|
||||||
return 1.0 + math.floor((total - 1) / 0.5) * 0.5
|
|
||||||
|
|
||||||
|
|
||||||
def _calc_flex_d(actual_checkout: datetime, flex_trigger: datetime) -> float:
|
|
||||||
"""
|
|
||||||
弹性额度 D 计算(基于实际下班打卡时间):
|
|
||||||
实际下班打卡 >= 23:00 时,D = 1 + floor((打卡-23:00)/0.5) * 0.5
|
|
||||||
"""
|
|
||||||
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
|
|
||||||
|
|
||||||
|
|
||||||
def _calc_day_ot_threshold(days: float) -> float:
|
|
||||||
"""
|
|
||||||
休息日/法定假日加班打卡间隔阈值:8 * days + int(days)。
|
|
||||||
0.5天->4h, 1天->9h, 1.5天->13h, 2天->18h, 2.5天->22h
|
|
||||||
"""
|
|
||||||
return 8.0 * days + int(days)
|
|
||||||
|
|
||||||
|
|
||||||
def _next_day(date_str: str) -> str:
|
|
||||||
"""日期字符串 +1 天"""
|
|
||||||
d = datetime.strptime(date_str, "%Y-%m-%d")
|
|
||||||
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
|
|
||||||
|
|
||||||
|
|
||||||
def _is_spring_festival(date_str: str) -> bool:
|
|
||||||
"""
|
|
||||||
判断日期是否为春节法定节假日(初一至初三)。
|
|
||||||
|
|
||||||
用 chinese_calendar 的 get_holiday_detail 判断 holiday_name == 'Spring Festival',
|
|
||||||
且 is_in_lieu=False(排除调休日),且非周末(排除正常周末)。
|
|
||||||
判定失败时按非春节处理(优雅降级)。
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
import chinese_calendar as cc
|
|
||||||
date = datetime.strptime(date_str, "%Y-%m-%d").date()
|
|
||||||
is_holiday, holiday_name = cc.get_holiday_detail(date)
|
|
||||||
return (is_holiday
|
|
||||||
and holiday_name == 'Spring Festival'
|
|
||||||
and not cc.is_in_lieu(date)
|
|
||||||
and date.weekday() < 5)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e))
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 排班 / 打卡 / 请假查询 ----------
|
|
||||||
def _get_shift(session: Any, staff_id: str, date_str: str) -> str:
|
|
||||||
"""获取指定日期员工的排班班次(自动处理跨月)"""
|
|
||||||
if not date_str or not staff_id:
|
|
||||||
return "未知"
|
|
||||||
try:
|
|
||||||
year = int(date_str[:4])
|
|
||||||
month = int(date_str[5:7])
|
|
||||||
html = get_attendance_html(session, staff_id, year, month)
|
|
||||||
attendance = parse_attendance_html(html)
|
|
||||||
return attendance.get(date_str, "无排班")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("获取排班失败(%s): %s", date_str, str(e))
|
|
||||||
return "获取失败"
|
|
||||||
|
|
||||||
|
|
||||||
def _check_attendance(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
|
|
||||||
"""查询员工在加班日期的排班班次"""
|
|
||||||
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
|
|
||||||
|
|
||||||
|
|
||||||
def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
查询员工在加班日及次日的打卡明细,按日汇总。
|
|
||||||
|
|
||||||
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日,因此查询
|
|
||||||
范围扩展到 ot_date 次日;次日最早打卡用于延时加班的弹性到岗兑换判定。
|
|
||||||
"""
|
|
||||||
if not ot_date or not staff_id:
|
|
||||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
|
||||||
"打卡备注": "缺少加班日期或员工ID"}
|
|
||||||
|
|
||||||
start = datetime.strptime(ot_date, "%Y-%m-%d")
|
|
||||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
|
||||||
|
|
||||||
try:
|
|
||||||
records = get_attendance_records(session, staff_id, ot_date, next_day)
|
|
||||||
summary = summarize_attendance_records(records)
|
|
||||||
day_summary = next((r for r in summary if r["attend_date"] == ot_date), None)
|
|
||||||
next_summary = next((r for r in summary if r["attend_date"] == next_day), None)
|
|
||||||
if not day_summary and not next_summary:
|
|
||||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
|
||||||
"打卡备注": "当天及次日无打卡记录"}
|
|
||||||
return {
|
|
||||||
"当日最早打卡": day_summary["first_check_in"] if day_summary else None,
|
|
||||||
"当日最晚打卡": day_summary["last_check_out"] if day_summary else None,
|
|
||||||
"次日最早打卡": next_summary["first_check_in"] if next_summary else None,
|
|
||||||
"打卡备注": "",
|
|
||||||
}
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("获取打卡明细失败: %s", str(e))
|
|
||||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
|
||||||
"打卡备注": f"获取失败: {e}"}
|
|
||||||
|
|
||||||
|
|
||||||
def _check_leave_covers_morning(session: Any, staff_id: str, date_str: str) -> bool:
|
|
||||||
"""
|
|
||||||
判断指定日期是否有请假覆盖早上上班时间(用于弹性兑换触发判定)。
|
|
||||||
|
|
||||||
只要任意请假区间覆盖了当日 WORK_START_TIME(如 09:00),即视为早上无需到岗,
|
|
||||||
不触发弹性兑换。查询范围向前一天扩展,确保能查到跨天请假。
|
|
||||||
"""
|
|
||||||
prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
|
|
||||||
try:
|
|
||||||
records = get_leave_records(session, staff_id, prev_day, date_str)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("获取请假记录失败: %s", str(e))
|
|
||||||
return False
|
|
||||||
|
|
||||||
morning = datetime.strptime(f"{date_str} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
|
|
||||||
for r in records:
|
|
||||||
start = _parse_dt(r.get("start_time"))
|
|
||||||
end = _parse_dt(r.get("end_time"))
|
|
||||||
if start and end and start <= morning <= end:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 规则一:延时加班 ----------
|
|
||||||
def _validate_delayed(
|
|
||||||
info: Dict[str, Any], punch: Dict[str, Any], session: Any, staff_id: str
|
|
||||||
) -> tuple:
|
|
||||||
"""
|
|
||||||
延时加班审批(按 aa.md 规则一):
|
|
||||||
|
|
||||||
(一)驳回门槛:
|
|
||||||
1. 日期匹配:加班开始时间所属日期 = 申请加班日期;
|
|
||||||
2. 时长达标:1小时起算,超1小时按0.5h累加,不足1h驳回;
|
|
||||||
3. 区间合规:开始时间 >= 规定下班时间(18:00),结束时间 <= 实际下班打卡时间。
|
|
||||||
|
|
||||||
(二)弹性到岗兑换(仅影响结算,校验不通过则驳回):
|
|
||||||
D 基于实际下班打卡时间计算,>= 23:00 时 D = 1 + floor((打卡-23:00)/0.5)*0.5。
|
|
||||||
次日休息/请假覆盖09:00/无打卡 -> 不触发兑换。
|
|
||||||
正常工作日按次日打卡 P 校验:P<=09:00 不扣;09:00<P<=09:00+D 扣 ceil(P-09:00);
|
|
||||||
P>09:00+D 扣 D。兑换校验:加班时长+晚到 <= 加班开始到次日打卡的总自然时长。
|
|
||||||
"""
|
|
||||||
ot_date = info.get("加班日期")
|
|
||||||
start = _parse_dt(info.get("加班开始时间"))
|
|
||||||
end = _parse_dt(info.get("加班结束时间"))
|
|
||||||
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
|
|
||||||
reasons = []
|
|
||||||
|
|
||||||
# 1. 日期校验
|
|
||||||
if start is None:
|
|
||||||
reasons.append("加班开始时间缺失")
|
|
||||||
elif start.strftime("%Y-%m-%d") != ot_date:
|
|
||||||
reasons.append(f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致")
|
|
||||||
|
|
||||||
# 2. 时长校验
|
|
||||||
hours = None
|
|
||||||
if end is None:
|
|
||||||
reasons.append("加班结束时间缺失")
|
|
||||||
elif start is not None:
|
|
||||||
hours = _calc_delayed_hours(start, end)
|
|
||||||
if hours < OT_MIN_HOURS:
|
|
||||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
|
||||||
|
|
||||||
# 3. 区间合规校验:开始 >= 规定下班时间,结束 <= 实际下班打卡时间
|
|
||||||
work_end = datetime.strptime(f"{ot_date} {WORK_END_TIME}", "%Y-%m-%d %H:%M")
|
|
||||||
if start is not None and start < work_end:
|
|
||||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})")
|
|
||||||
if end is not None:
|
|
||||||
if actual_checkout is None:
|
|
||||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
|
||||||
elif end > actual_checkout:
|
|
||||||
reasons.append(
|
|
||||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})"
|
|
||||||
)
|
|
||||||
|
|
||||||
info["计算加班时长(小时)"] = hours
|
|
||||||
if reasons:
|
|
||||||
info["弹性扣减(小时)"] = 0
|
|
||||||
info["有效加班时长(小时)"] = hours
|
|
||||||
info["弹性额度D(小时)"] = 0
|
|
||||||
return "不通过", ";".join(reasons)
|
|
||||||
|
|
||||||
# 4. 弹性到岗兑换(仅影响结算时长)
|
|
||||||
deduction = 0.0
|
|
||||||
flex_note = ""
|
|
||||||
d_hours = 0.0
|
|
||||||
flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M")
|
|
||||||
|
|
||||||
if actual_checkout is not None and actual_checkout >= flex_trigger:
|
|
||||||
d_hours = _calc_flex_d(actual_checkout, flex_trigger)
|
|
||||||
next_day = _next_day(ot_date)
|
|
||||||
next_shift = _get_shift(session, staff_id, next_day)
|
|
||||||
|
|
||||||
if next_shift in ("休息", "无排班"):
|
|
||||||
flex_note = f"次日({next_day})为休息日,不触发弹性兑换"
|
|
||||||
elif next_shift in ("获取失败", "未知"):
|
|
||||||
flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换"
|
|
||||||
elif _check_leave_covers_morning(session, staff_id, next_day):
|
|
||||||
flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换"
|
|
||||||
else:
|
|
||||||
work_start = datetime.strptime(f"{next_day} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
|
|
||||||
p = _parse_dt(punch.get("次日最早打卡"))
|
|
||||||
|
|
||||||
if p is None:
|
|
||||||
flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换"
|
|
||||||
elif p <= work_start:
|
|
||||||
flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换"
|
|
||||||
else:
|
|
||||||
# 有晚到,校验:加班时长 + 晚到 <= 加班开始到次日打卡的总自然时长
|
|
||||||
total_natural = (p - start).total_seconds() / 3600
|
|
||||||
|
|
||||||
if p <= work_start + timedelta(hours=d_hours):
|
|
||||||
# 09:00 < P <= 09:00+D:晚到时长 = ceil(P-09:00),不足1h按1h
|
|
||||||
late_hours = max(1, math.ceil((p - work_start).total_seconds() / 3600))
|
|
||||||
if hours + late_hours > total_natural:
|
|
||||||
info["弹性扣减(小时)"] = 0
|
|
||||||
info["有效加班时长(小时)"] = hours
|
|
||||||
info["弹性额度D(小时)"] = d_hours
|
|
||||||
return "不通过", (
|
|
||||||
f"弹性兑换校验不通过:申请加班{hours:g}h + 晚到{late_hours}h "
|
|
||||||
f"> 总自然时长{total_natural:.1f}h"
|
|
||||||
)
|
|
||||||
deduction = float(late_hours)
|
|
||||||
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
|
|
||||||
else:
|
|
||||||
# P > 09:00+D:兑换额度最高按D,超出部分交考勤处理
|
|
||||||
if hours + d_hours > total_natural:
|
|
||||||
info["弹性扣减(小时)"] = 0
|
|
||||||
info["有效加班时长(小时)"] = hours
|
|
||||||
info["弹性额度D(小时)"] = d_hours
|
|
||||||
return "不通过", (
|
|
||||||
f"弹性兑换校验不通过:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
|
|
||||||
f"> 总自然时长{total_natural:.1f}h"
|
|
||||||
)
|
|
||||||
deduction = float(d_hours)
|
|
||||||
flex_note = (
|
|
||||||
f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h),"
|
|
||||||
f"按D兑换,超出部分交考勤处理"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
if actual_checkout is not None:
|
|
||||||
flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0"
|
|
||||||
|
|
||||||
effective = max(0.0, float(hours) - deduction)
|
|
||||||
info["弹性扣减(小时)"] = deduction
|
|
||||||
info["有效加班时长(小时)"] = effective
|
|
||||||
info["弹性额度D(小时)"] = d_hours
|
|
||||||
note = f"审批通过,有效加班时长{effective:g}小时"
|
|
||||||
if flex_note:
|
|
||||||
note += f"({flex_note})"
|
|
||||||
return "通过", note
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 规则二/三:休息日 / 法定假日加班 ----------
|
|
||||||
def _validate_day_ot(
|
|
||||||
info: Dict[str, Any],
|
|
||||||
punch: Dict[str, Any],
|
|
||||||
session: Any,
|
|
||||||
staff_id: str,
|
|
||||||
require_holiday: bool,
|
|
||||||
) -> tuple:
|
|
||||||
"""
|
|
||||||
休息日/法定假日加班审批(任一条件不满足即不通过):
|
|
||||||
- 排班显示为休息;
|
|
||||||
- 法定假日(仅春节):申请日期必须为春节法定节假日;
|
|
||||||
- 加班时长 > 0;
|
|
||||||
- 当天有上下班打卡;
|
|
||||||
- 打卡时间间隔满足申报天数(0.5天>=4h, 1天>=9h, 1.5天>=13h, 2天>=18h...)。
|
|
||||||
"""
|
|
||||||
ot_date = info.get("加班日期")
|
|
||||||
reasons = []
|
|
||||||
|
|
||||||
# 排班须显示为休息;排班获取失败/未知时优雅降级
|
|
||||||
shift = info.get("加班当天班次", "")
|
|
||||||
if shift not in ("休息", "获取失败", "未知", "无排班"):
|
|
||||||
reasons.append(f"当天排班为'{shift}',非休息日")
|
|
||||||
|
|
||||||
if require_holiday and not _is_spring_festival(ot_date):
|
|
||||||
reasons.append(f"{ot_date}不在春节法定节假日列表中")
|
|
||||||
|
|
||||||
# 加班时长 > 0
|
|
||||||
ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)")
|
|
||||||
try:
|
|
||||||
ot_hour = float(ot_hour)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
ot_hour = 0.0
|
|
||||||
if ot_hour <= 0:
|
|
||||||
reasons.append("加班时长为0或缺失")
|
|
||||||
|
|
||||||
# 当天有上下班打卡,且打卡时间间隔满足申报天数
|
|
||||||
first = _parse_dt(punch.get("当日最早打卡"))
|
|
||||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
|
||||||
interval = None
|
|
||||||
if first is None or last is None:
|
|
||||||
reasons.append("当天缺少上班或下班打卡")
|
|
||||||
else:
|
|
||||||
interval = (last - first).total_seconds() / 3600
|
|
||||||
|
|
||||||
apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)")
|
|
||||||
try:
|
|
||||||
apply_days = float(apply_days)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
apply_days = 0.0
|
|
||||||
if apply_days <= 0:
|
|
||||||
reasons.append("申报天数缺失或为0")
|
|
||||||
elif interval is not None:
|
|
||||||
threshold = _calc_day_ot_threshold(apply_days)
|
|
||||||
if interval < threshold:
|
|
||||||
reasons.append(
|
|
||||||
f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时"
|
|
||||||
)
|
|
||||||
|
|
||||||
info["打卡时间间隔(小时)"] = interval
|
|
||||||
info["申报天数(天)"] = apply_days
|
|
||||||
if reasons:
|
|
||||||
return "不通过", ";".join(reasons)
|
|
||||||
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 主入口 ----------
|
|
||||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
校验单张加班单据,返回审批决策(通过 / 不通过)。
|
|
||||||
|
|
||||||
按加班类型分派规则:
|
|
||||||
ot_type=1 延时加班;
|
|
||||||
ot_type=3 休息日加班;
|
|
||||||
ot_type=2 法定假日加班(仅春节法定节假日走规则三,非春节按休息日规则执行)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
|
||||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
|
||||||
session: 已登录的 SessionPage 对象(用于调用排班/打卡/请假接口)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
校验结果,包含审批决策、原因说明及解析后的加班信息
|
|
||||||
"""
|
|
||||||
form_data = doc.get("formData", {}) or {}
|
|
||||||
overtime_info = parse_overtime_form(form_data)
|
|
||||||
|
|
||||||
staff_id = overtime_info.get("加班人员ID")
|
|
||||||
ot_date = overtime_info.get("加班日期")
|
|
||||||
|
|
||||||
attendance_info = _check_attendance(session, staff_id, ot_date)
|
|
||||||
punch_info = _check_punch_records(session, staff_id, ot_date)
|
|
||||||
overtime_info.update(attendance_info)
|
|
||||||
overtime_info.update(punch_info)
|
|
||||||
|
|
||||||
ot_type_code = str(form_data.get("ot_type") or "")
|
|
||||||
if ot_type_code == "1":
|
|
||||||
decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id)
|
|
||||||
elif ot_type_code == "3":
|
|
||||||
decision, note = _validate_day_ot(
|
|
||||||
overtime_info, punch_info, session, staff_id, require_holiday=False
|
|
||||||
)
|
|
||||||
elif ot_type_code == "2":
|
|
||||||
# 法定假日加班:仅春节法定节假日适用规则三,非春节按休息日规则执行
|
|
||||||
require_holiday = _is_spring_festival(ot_date)
|
|
||||||
decision, note = _validate_day_ot(
|
|
||||||
overtime_info, punch_info, session, staff_id, require_holiday=require_holiday
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
decision, note = "不通过", f"无法识别加班类型: {ot_type_code}"
|
|
||||||
|
|
||||||
return {
|
|
||||||
"title": doc.get("title", ""),
|
|
||||||
"creator": doc.get("creator", ""),
|
|
||||||
"time": doc.get("time", ""),
|
|
||||||
"decision": decision,
|
|
||||||
"note": note,
|
|
||||||
"overtime_info": overtime_info,
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: utils
|
|
||||||
@FileName: __init__.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:00
|
|
||||||
@Description: 项目级通用工具包
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.utils
|
|
||||||
@FileName: utils.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 21:30
|
|
||||||
@Description: 项目级通用工具(重试装饰器)
|
|
||||||
@Version: 1.1.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import functools
|
|
||||||
import os
|
|
||||||
import random
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from typing import Callable
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
from logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class RetryExhaustedError(Exception):
|
|
||||||
"""重试耗尽后抛出的异常,保留原始异常链。"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def retry(max_attempts: int = 3) -> Callable:
|
|
||||||
"""
|
|
||||||
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
|
|
||||||
|
|
||||||
内部行为(对调用方透明):
|
|
||||||
- 捕获所有 Exception;
|
|
||||||
- 延迟策略:第 n 次重试等待 1.0 * 2^(n-1) 秒,并乘以 [0.5, 1.5] 随机因子;
|
|
||||||
- 全部失败后抛出 RetryExhaustedError,可通过 __cause__ 获取原始异常。
|
|
||||||
"""
|
|
||||||
if max_attempts < 1:
|
|
||||||
raise ValueError("max_attempts must be >= 1")
|
|
||||||
|
|
||||||
def decorator(func: Callable) -> Callable:
|
|
||||||
@functools.wraps(func)
|
|
||||||
def wrapper(*args, **kwargs):
|
|
||||||
last_exc = None
|
|
||||||
base_delay = 1.0
|
|
||||||
backoff = 2.0
|
|
||||||
|
|
||||||
for attempt in range(1, max_attempts + 1):
|
|
||||||
try:
|
|
||||||
return func(*args, **kwargs)
|
|
||||||
except Exception as e:
|
|
||||||
last_exc = e
|
|
||||||
if attempt >= max_attempts:
|
|
||||||
logger.error(
|
|
||||||
"%s 连续 %d 次尝试失败,放弃并记录: %s",
|
|
||||||
func.__name__, max_attempts, e,
|
|
||||||
)
|
|
||||||
break
|
|
||||||
|
|
||||||
# 计算退避 + 抖动
|
|
||||||
delay = base_delay * (backoff ** (attempt - 1))
|
|
||||||
delay *= random.uniform(0.5, 1.5)
|
|
||||||
|
|
||||||
logger.warning(
|
|
||||||
"%s 第 %d 次执行失败: %s,%.2f 秒后重试",
|
|
||||||
func.__name__, attempt, e, delay,
|
|
||||||
)
|
|
||||||
time.sleep(delay)
|
|
||||||
|
|
||||||
raise RetryExhaustedError(
|
|
||||||
f"{func.__name__} failed after {max_attempts} attempts"
|
|
||||||
) from last_exc
|
|
||||||
|
|
||||||
return wrapper
|
|
||||||
return decorator
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: utils.logger
|
|
||||||
@FileName: logger.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05
|
|
||||||
@Description: 项目统一日志配置:控制台彩色输出 + 文件持久化
|
|
||||||
@Version: 1.0.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import logging.handlers
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
|
|
||||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
|
||||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
|
||||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
|
||||||
|
|
||||||
_initialized = False
|
|
||||||
|
|
||||||
|
|
||||||
class _ColoredFormatter(logging.Formatter):
|
|
||||||
"""控制台彩色日志格式,不修改 record 本身,避免污染文件输出"""
|
|
||||||
|
|
||||||
_colors = {
|
|
||||||
logging.DEBUG: "\033[36m",
|
|
||||||
logging.INFO: "\033[32m",
|
|
||||||
logging.WARNING: "\033[33m",
|
|
||||||
logging.ERROR: "\033[31m",
|
|
||||||
logging.CRITICAL: "\033[35m",
|
|
||||||
}
|
|
||||||
_reset = "\033[0m"
|
|
||||||
|
|
||||||
def format(self, record: logging.LogRecord) -> str:
|
|
||||||
color = self._colors.get(record.levelno, "")
|
|
||||||
orig_levelname = record.levelname
|
|
||||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
|
||||||
result = super().format(record)
|
|
||||||
record.levelname = orig_levelname
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def setup_logging(
|
|
||||||
level: int = logging.INFO,
|
|
||||||
log_dir: str = None,
|
|
||||||
log_file: bool = True,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
初始化项目统一日志配置。只需在入口调用一次。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
level: 日志级别,默认 INFO
|
|
||||||
log_dir: 日志文件目录,默认 app/logs/
|
|
||||||
log_file: 是否同时输出到文件,默认 True
|
|
||||||
"""
|
|
||||||
global _initialized
|
|
||||||
if _initialized:
|
|
||||||
return
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
logger.setLevel(level)
|
|
||||||
logger.handlers.clear()
|
|
||||||
|
|
||||||
console_handler = logging.StreamHandler(sys.stdout)
|
|
||||||
console_handler.setLevel(level)
|
|
||||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
|
||||||
logger.addHandler(console_handler)
|
|
||||||
|
|
||||||
if log_file:
|
|
||||||
if log_dir is None:
|
|
||||||
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")
|
|
||||||
os.makedirs(log_dir, exist_ok=True)
|
|
||||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
|
||||||
file_handler = logging.handlers.RotatingFileHandler(
|
|
||||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
|
||||||
)
|
|
||||||
file_handler.setLevel(logging.DEBUG)
|
|
||||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
|
||||||
logger.addHandler(file_handler)
|
|
||||||
|
|
||||||
_initialized = True
|
|
||||||
|
|
||||||
|
|
||||||
def get_logger(name: str) -> logging.Logger:
|
|
||||||
"""获取模块级 logger,用法:logger = get_logger(__name__)"""
|
|
||||||
return logging.getLogger(name)
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""controlplane —— 内网插件控制面(中心机)包。
|
||||||
|
|
||||||
|
业务领域实现已归入 core 子包。本 `__init__` 作为 facade 再导出 core 内各模块,
|
||||||
|
以兼容 `from controlplane import X` 的既有用法。
|
||||||
|
"""
|
||||||
|
from controlplane.core import ( # noqa: F401
|
||||||
|
auth,
|
||||||
|
config,
|
||||||
|
crypto,
|
||||||
|
db,
|
||||||
|
dingtalk,
|
||||||
|
pkgutil,
|
||||||
|
schemas,
|
||||||
|
)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""controlplane 路由子包:按领域组织 APIRouter,由 app.py 底层组装。"""
|
||||||
@@ -0,0 +1,795 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""管理侧路由(写操作,需正确 token):账号 CRUD / 插件上传与维护 / 授权 / 看板 / 审计 / 运行记录。
|
||||||
|
|
||||||
|
所有写操作均以 `_require_admin`(X-API-Token + X-Admin-Token 管理员票据)把关。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
from controlplane import config, schemas
|
||||||
|
from controlplane.core.auth import _identity, _require_admin, _revoke_account_tokens
|
||||||
|
from controlplane.core.crypto import _hash_password
|
||||||
|
from controlplane.core.db import _audit, _db, _now
|
||||||
|
from controlplane.core.notify import notify_account_created
|
||||||
|
from controlplane.core.paging import count_rows, page_bounds
|
||||||
|
from controlplane.core.pkgutil import (
|
||||||
|
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||||||
|
_validate_pkg_zip, _version_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||||
|
@router.get("/api/admin/accounts")
|
||||||
|
def admin_accounts(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, ge=1, le=1000),
|
||||||
|
q: str = Query(default=""),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""账号列表(统一分页 + 服务端搜索 q:账号/昵称/部门模糊,含已授权插件/可登录平台)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
where, args = "", []
|
||||||
|
if q.strip():
|
||||||
|
where = " WHERE (account LIKE %s OR nickname LIKE %s OR dept LIKE %s)"
|
||||||
|
args = ["%" + q.strip() + "%"] * 3
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM accounts" + where, args)
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd, "
|
||||||
|
" avatar, status, created_at "
|
||||||
|
"FROM accounts" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||||
|
for a in rows:
|
||||||
|
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||||
|
"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 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 = %s", (a["account"],))]
|
||||||
|
return {"items": rows, "total": total}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/account")
|
||||||
|
def admin_account_create(a: schemas.AccountCreateIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""新建账号:密码必填,可指定部门/昵称/是否管理员。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = a.account.strip()
|
||||||
|
if not account or not a.password:
|
||||||
|
raise HTTPException(400, "account 与 password 必填")
|
||||||
|
if len(a.password) < 8:
|
||||||
|
raise HTTPException(400, "密码至少 8 位")
|
||||||
|
with _db() as conn:
|
||||||
|
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 (%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()
|
||||||
|
# 钉钉工作通知(异步,失败不阻断建号):新用户收账号密码(按昵称解析),管理员收权限开通提醒
|
||||||
|
notify_account_created(account, (a.nickname or "").strip(), a.password, source="管理台")
|
||||||
|
_audit(login, "account-create", account,
|
||||||
|
f"is_admin={int(a.is_admin)}, dept={(a.dept or '').strip()}")
|
||||||
|
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||||||
|
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/account/update")
|
||||||
|
def admin_account_update(a: schemas.AccountUpdateIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""更新账号:改部门 / 昵称 / 授予或撤销管理员。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = a.account.strip()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(400, "account 必填")
|
||||||
|
with _db() as conn:
|
||||||
|
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||||
|
raise HTTPException(400, f"账号 {account} 不存在")
|
||||||
|
if a.dept is not None:
|
||||||
|
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 = %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 = %s", (account,))
|
||||||
|
else:
|
||||||
|
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 = %s WHERE account = %s",
|
||||||
|
(int(bool(a.status)), account))
|
||||||
|
conn.commit()
|
||||||
|
if a.status is not None and not a.status:
|
||||||
|
# 停用账号即吊销其云令牌,防止残留会话继续使用(P1 安全债)
|
||||||
|
_revoke_account_tokens(account)
|
||||||
|
_audit(login, "account-update", account,
|
||||||
|
f"dept={a.dept is not None}, nickname={a.nickname is not None}, "
|
||||||
|
f"is_admin={a.is_admin is not None}, status={a.status is not None}")
|
||||||
|
return {"ok": True, "account": account}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/account/reset_pwd")
|
||||||
|
def admin_account_reset(r: schemas.AccountResetIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""管理员重置任意账号密码(无需原密码)。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = r.account.strip()
|
||||||
|
if not account or not r.new_password:
|
||||||
|
raise HTTPException(400, "account 与新密码必填")
|
||||||
|
if len(r.new_password) < 8:
|
||||||
|
raise HTTPException(400, "新密码至少 8 位")
|
||||||
|
with _db() as conn:
|
||||||
|
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 = %s, salt = %s WHERE account = %s",
|
||||||
|
(_hex, _salt, account))
|
||||||
|
conn.commit()
|
||||||
|
_audit(login, "account-reset-pwd", account)
|
||||||
|
return {"ok": True, "account": account}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/account/delete")
|
||||||
|
def admin_account_delete(d: schemas.AccountDelIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""删除账号:不可删除自己;连带清除其插件授权。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = d.account.strip()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(400, "account 必填")
|
||||||
|
if account == login:
|
||||||
|
raise HTTPException(400, "不能删除当前登录的账号")
|
||||||
|
with _db() as conn:
|
||||||
|
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||||
|
raise HTTPException(400, f"账号 {account} 不存在")
|
||||||
|
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||||||
|
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||||||
|
conn.commit()
|
||||||
|
# 删除账号即吊销其云令牌(防残留令牌继续解析,P1 安全债)
|
||||||
|
_revoke_account_tokens(account)
|
||||||
|
_audit(login, "account-delete", account)
|
||||||
|
return {"ok": True, "account": account}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 头像(自服务可传自己;管理员可传任意账号) ====================
|
||||||
|
_AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/avatar")
|
||||||
|
def admin_avatar_upload(file: UploadFile = File(...),
|
||||||
|
account: str = Query(...),
|
||||||
|
authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||||
|
"""上传账号头像:自服务传自己;管理员可传任意账号。覆盖旧头像。"""
|
||||||
|
try:
|
||||||
|
login = _identity(authorization=authorization, x_admin_token=x_admin_token,
|
||||||
|
x_api_token=x_api_token, x_admin_user=x_admin_user)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||||
|
account = account.strip()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(400, "account 不能为空")
|
||||||
|
if not _SAFE_NAME_RE.match(account):
|
||||||
|
raise HTTPException(400, "account 含非法字符(仅允许字母数字及 . _ -,防止文件名穿越)")
|
||||||
|
if account != login:
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
ext = Path(file.filename or "").suffix.lower()
|
||||||
|
if ext not in _AVATAR_EXT:
|
||||||
|
raise HTTPException(400, "仅支持图片格式(jpg/png/gif/webp)")
|
||||||
|
content = file.file.read()
|
||||||
|
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 = %s", (account,)).fetchone():
|
||||||
|
raise HTTPException(400, f"账号 {account} 不存在")
|
||||||
|
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}"
|
||||||
|
(config.AVATAR_DIR / fname).write_bytes(content)
|
||||||
|
if old_name and old_name != fname: # 换扩展名时清掉旧文件,防残留
|
||||||
|
try:
|
||||||
|
(config.AVATAR_DIR / old_name).unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute("UPDATE accounts SET avatar = %s WHERE account = %s", (fname, account))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True, "account": account, "avatar": fname}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/avatar/{account}")
|
||||||
|
def admin_avatar_get(account: str) -> FileResponse:
|
||||||
|
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
|
||||||
|
with _db() as conn:
|
||||||
|
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"]
|
||||||
|
if not path.is_file():
|
||||||
|
raise HTTPException(404, "头像文件缺失")
|
||||||
|
return FileResponse(path)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 授权 / 插件维护 ====================
|
||||||
|
@router.post("/api/admin/account_plugins")
|
||||||
|
def admin_grant(g: schemas.GrantIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤。
|
||||||
|
|
||||||
|
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||||||
|
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||||||
|
"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = g.account.strip()
|
||||||
|
plugin_id = g.plugin_id.strip()
|
||||||
|
if not account or not plugin_id:
|
||||||
|
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||||||
|
with _db() as conn:
|
||||||
|
if g.granted:
|
||||||
|
if not conn.execute("SELECT 1 FROM accounts WHERE account = %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 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 = %s AND plugin_id = %s",
|
||||||
|
(account, plugin_id))
|
||||||
|
conn.commit()
|
||||||
|
# 审计 actor 用操作者 login(可追溯"谁操作的"),target 为插件、detail 记录被授权账号
|
||||||
|
_audit(login, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||||
|
f"account={account},can_download={g.can_download},can_run={g.can_run}")
|
||||||
|
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/account_platforms")
|
||||||
|
def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = g.account.strip()
|
||||||
|
platform_id = g.platform_id.strip()
|
||||||
|
if not account or not platform_id:
|
||||||
|
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||||||
|
with _db() as conn:
|
||||||
|
if g.granted:
|
||||||
|
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||||
|
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (%s, %s)",
|
||||||
|
(account, platform_id))
|
||||||
|
else:
|
||||||
|
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||||||
|
(account, platform_id))
|
||||||
|
conn.commit()
|
||||||
|
# 审计 actor 用操作者 login,target 为平台、detail 记录被授权账号
|
||||||
|
_audit(login, "grant-platform" if g.granted else "revoke-platform", platform_id, account)
|
||||||
|
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/pkg")
|
||||||
|
async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||||
|
plugin_id: str = Query(...), name: str = Query(...),
|
||||||
|
version: str = Query(...),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
plugin_id = plugin_id.strip()
|
||||||
|
name = name.strip() or plugin_id
|
||||||
|
version = version.strip()
|
||||||
|
if not plugin_id or not version:
|
||||||
|
raise HTTPException(400, "plugin_id 与 version 不能为空")
|
||||||
|
# 只允许安全字符(防止拼进文件路径造成目录穿越)
|
||||||
|
if not _SAFE_NAME_RE.match(plugin_id) or not _SAFE_NAME_RE.match(version):
|
||||||
|
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||||
|
filename = f"{plugin_id}_v{version}.zip"
|
||||||
|
target = config.PKG_DIR / filename
|
||||||
|
# 流式读取并限长(最大 200MB,与控制面插件包上限一致),避免整包先读入内存(P1 安全债)
|
||||||
|
_MAX_PKG_BYTES = 200 * 1024 * 1024
|
||||||
|
chunks: list[bytes] = []
|
||||||
|
total = 0
|
||||||
|
while True:
|
||||||
|
chunk = await upload.read(1024 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
total += len(chunk)
|
||||||
|
if total > _MAX_PKG_BYTES:
|
||||||
|
raise HTTPException(413, f"插件包超过大小上限({_MAX_PKG_BYTES // (1024 * 1024)}MB)")
|
||||||
|
chunks.append(chunk)
|
||||||
|
content = b"".join(chunks)
|
||||||
|
if not content:
|
||||||
|
raise HTTPException(400, "上传内容为空")
|
||||||
|
_validate_pkg_zip(content)
|
||||||
|
|
||||||
|
# manifest 为插件契约权威来源:plugin.json 内 id 与路径 plugin_id 不一致时拒绝,
|
||||||
|
# 否则以 manifest.metadata 覆盖 name/category/icon/description 并整份入库。
|
||||||
|
manifest = _extract_manifest(content)
|
||||||
|
if manifest:
|
||||||
|
mid = str((manifest.get("id") or "")).strip()
|
||||||
|
if mid and mid != plugin_id:
|
||||||
|
raise HTTPException(400, f"plugin.json 内 id「{mid}」与路径 plugin_id「{plugin_id}」不一致")
|
||||||
|
name = str(manifest.get("name") or name).strip() or plugin_id
|
||||||
|
manifest_json = json.dumps(manifest, ensure_ascii=False) if manifest else "{}"
|
||||||
|
|
||||||
|
target.write_bytes(content)
|
||||||
|
pkg_sha256 = hashlib.sha256(content).hexdigest() # 供部署端装包后防篡改校验
|
||||||
|
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||||||
|
"VALUES (%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", ""),
|
||||||
|
(manifest or {}).get("icon", ""),
|
||||||
|
manifest_json))
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, 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 = %s", (plugin_id,))
|
||||||
|
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||||
|
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 记录 + 清磁盘包
|
||||||
|
try:
|
||||||
|
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
_audit(login, "plugin-publish", plugin_id, f"version={version}, filename={filename}")
|
||||||
|
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/plugin/delete")
|
||||||
|
def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
plugin_id = d.plugin_id.strip()
|
||||||
|
if not plugin_id:
|
||||||
|
raise HTTPException(400, "plugin_id 必填")
|
||||||
|
with _db() as conn:
|
||||||
|
if not conn.execute("SELECT 1 FROM plugins WHERE id = %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 = %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:
|
||||||
|
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
_audit(login, "plugin-delete", plugin_id, f"files={len(files)}")
|
||||||
|
return {"ok": True, "plugin_id": plugin_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/plugin/patch")
|
||||||
|
def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||||
|
plugin_id: str = Query(...),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""更新插件元信息/状态/强制更新配置。
|
||||||
|
|
||||||
|
status: published=正常 / disabled=禁用(停止发布) / revoked=下架(拒绝运行)。
|
||||||
|
force_min_version + force_deadline 组合开启强制更新(deadline 已过联线拒启旧版);
|
||||||
|
clear_force=True 清除强制更新;仅给其一且未 clear 则报 400。
|
||||||
|
"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
pid = plugin_id.strip()
|
||||||
|
if not pid:
|
||||||
|
raise HTTPException(400, "plugin_id 必填")
|
||||||
|
fields = []
|
||||||
|
vals = []
|
||||||
|
if d.name is not None and d.name.strip():
|
||||||
|
fields.append("name = %s"); vals.append(d.name.strip())
|
||||||
|
if d.description:
|
||||||
|
fields.append("description = %s"); vals.append(d.description.strip())
|
||||||
|
if d.category:
|
||||||
|
fields.append("category = %s"); vals.append(d.category.strip())
|
||||||
|
if d.icon:
|
||||||
|
fields.append("icon = %s"); vals.append(d.icon.strip())
|
||||||
|
if d.status in ("published", "disabled", "revoked"):
|
||||||
|
fields.append("status = %s"); vals.append(d.status)
|
||||||
|
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||||||
|
if d.force_min_version and d.force_deadline:
|
||||||
|
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:
|
||||||
|
fields.append("force_min_version = NULL")
|
||||||
|
fields.append("force_deadline = NULL")
|
||||||
|
if not fields:
|
||||||
|
return {"ok": True} # 无更新项
|
||||||
|
vals.append(pid)
|
||||||
|
with _db() as conn:
|
||||||
|
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (pid,)).fetchone():
|
||||||
|
raise HTTPException(400, f"插件 {pid} 不存在")
|
||||||
|
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])) or "clear_force")
|
||||||
|
return {"ok": True, "plugin_id": pid}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||||
|
@router.get("/api/admin/plugins")
|
||||||
|
def admin_plugins(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, ge=1, le=1000),
|
||||||
|
q: str = Query(default=""),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""插件列表(统一分页 + 服务端搜索 q:ID/名称模糊;含状态/版本/强制更新/能力声明/版本历史/授权账号)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
where, args = "", []
|
||||||
|
if q.strip():
|
||||||
|
where = " WHERE (id LIKE %s OR name LIKE %s)"
|
||||||
|
args = ["%" + q.strip() + "%"] * 2
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM plugins" + where, args)
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||||
|
" force_min_version, force_deadline, manifest "
|
||||||
|
"FROM plugins" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||||
|
for p in rows:
|
||||||
|
m = _load_manifest(p.pop("manifest"))
|
||||||
|
p["manifest"] = m
|
||||||
|
p["capabilities"] = m.get("capabilities") or []
|
||||||
|
props = (m.get("fields") or {}).get("properties") or {}
|
||||||
|
p["field_count"] = len(props)
|
||||||
|
p["versions"] = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||||
|
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||||
|
p["accounts"] = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT ap.account, a.nickname FROM account_plugins ap "
|
||||||
|
"LEFT JOIN accounts a ON a.account = ap.account "
|
||||||
|
"WHERE ap.plugin_id = %s ORDER BY ap.account", (p["id"],))]
|
||||||
|
return {"items": rows, "total": total}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/overview")
|
||||||
|
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""管理台一次性拉取:全部插件(含元信息/状态/版本/被授权账号)+ 全部账号 + 管理员名单。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
plugins = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||||
|
" force_min_version, force_deadline, manifest "
|
||||||
|
"FROM plugins ORDER BY id")]
|
||||||
|
for p in plugins:
|
||||||
|
m = _load_manifest(p.pop("manifest"))
|
||||||
|
p["manifest"] = m
|
||||||
|
p["capabilities"] = m.get("capabilities") or []
|
||||||
|
p["permissions"] = m.get("permissions") or {}
|
||||||
|
props = (m.get("fields") or {}).get("properties") or {}
|
||||||
|
p["field_count"] = len(props)
|
||||||
|
p["versions"] = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||||
|
"WHERE plugin_id = %s ORDER BY version", (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 = %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}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/grant_data")
|
||||||
|
def admin_grant_data(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""授权页轻量数据:全部插件(id/name/status,一次查询无 N+1)+ 全部账号(含昵称/部门)。
|
||||||
|
替代授权页对 /overview 全量聚合的依赖,插件/账号多时依然轻快。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
plugins = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, name, status FROM plugins ORDER BY id")]
|
||||||
|
accounts = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT account, nickname, dept, status FROM accounts "
|
||||||
|
"WHERE status = 1 ORDER BY account")]
|
||||||
|
return {"plugins": plugins, "accounts": accounts}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/account_grants")
|
||||||
|
def admin_account_grants(account: str = Query(default=""),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""某账号的现有授权明细:已授权插件(含 can_run/can_download)+ 已授权平台。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
account = account.strip()
|
||||||
|
with _db() as conn:
|
||||||
|
grants = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT plugin_id, can_run, can_download FROM account_plugins "
|
||||||
|
"WHERE account = %s ORDER BY plugin_id", (account,))]
|
||||||
|
platforms = [dict(r)["platform_id"] for r in conn.execute(
|
||||||
|
"SELECT platform_id FROM account_platforms "
|
||||||
|
"WHERE account = %s ORDER BY platform_id", (account,))]
|
||||||
|
return {
|
||||||
|
"plugins": [{"plugin_id": g["plugin_id"],
|
||||||
|
"canRun": bool(g["can_run"]),
|
||||||
|
"canDownload": bool(g["can_download"])} for g in grants],
|
||||||
|
"platforms": platforms,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/stats")
|
||||||
|
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""数据看板:账号/插件规模 + 运行统计(次数/时长/成败)+ 近 14 天趋势 + 排行。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
users = dict(conn.execute(
|
||||||
|
"SELECT (SELECT COUNT(*) FROM accounts) AS total, "
|
||||||
|
"(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins, "
|
||||||
|
"(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized").fetchone())
|
||||||
|
plugins = dict(conn.execute(
|
||||||
|
"SELECT (SELECT COUNT(*) FROM plugins) AS total, "
|
||||||
|
"(SELECT COUNT(*) FROM plugins WHERE status = 'published') AS published, "
|
||||||
|
"(SELECT COUNT(*) FROM plugins WHERE status = 'disabled') AS disabled, "
|
||||||
|
"(SELECT COUNT(*) FROM plugins WHERE status = 'revoked') AS revoked").fetchone())
|
||||||
|
runs = dict(conn.execute(
|
||||||
|
"SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start') AS started, "
|
||||||
|
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success, "
|
||||||
|
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed, "
|
||||||
|
"(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec, "
|
||||||
|
"(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users, "
|
||||||
|
"(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins").fetchone())
|
||||||
|
|
||||||
|
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||||||
|
trend_rows = conn.execute(
|
||||||
|
"SELECT 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 >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day"
|
||||||
|
).fetchall()
|
||||||
|
trend_map = {r["day"]: r for r in trend_rows}
|
||||||
|
trend = []
|
||||||
|
day = datetime.now() - timedelta(days=13)
|
||||||
|
for _i in range(14):
|
||||||
|
key = day.strftime("%Y-%m-%d")
|
||||||
|
r = trend_map.get(key)
|
||||||
|
trend.append({"day": key[5:], "runs": int(r["runs"] or 0) if r else 0,
|
||||||
|
"success": int(r["success"] or 0) if r else 0,
|
||||||
|
"failed": int(r["failed"] or 0) if r else 0})
|
||||||
|
day = day + timedelta(days=1)
|
||||||
|
|
||||||
|
# 插件排行:按执行次数(以 status='start' 为一次完整触发)
|
||||||
|
top_plugins = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT plugin_id AS pluginId, "
|
||||||
|
" COUNT(*) AS runs, "
|
||||||
|
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS triggered, "
|
||||||
|
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||||
|
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed, "
|
||||||
|
" COALESCE(SUM(duration_sec),0) AS durationSec "
|
||||||
|
"FROM runtime_reports GROUP BY plugin_id "
|
||||||
|
"ORDER BY triggered DESC LIMIT 8")]
|
||||||
|
pnames = {dict(r)["id"]: dict(r)["name"] for r in conn.execute(
|
||||||
|
"SELECT id, name FROM plugins")}
|
||||||
|
for tp in top_plugins:
|
||||||
|
tp["name"] = pnames.get(tp["pluginId"]) or tp["pluginId"]
|
||||||
|
tp["runs"] = int(tp["triggered"] or 0)
|
||||||
|
|
||||||
|
# 活跃用户排行
|
||||||
|
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||||||
|
for r in conn.execute(
|
||||||
|
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||||||
|
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||||
|
"ORDER BY runs DESC LIMIT 8")]
|
||||||
|
|
||||||
|
# 活跃用户排行
|
||||||
|
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||||||
|
for r in conn.execute(
|
||||||
|
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||||||
|
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||||
|
"ORDER BY runs DESC LIMIT 8")]
|
||||||
|
|
||||||
|
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||||
|
"SELECT account, nickname FROM accounts")}
|
||||||
|
for tu in top_users:
|
||||||
|
tu["nickname"] = nick.get(tu["account"], "")
|
||||||
|
|
||||||
|
now_day = datetime.now().strftime("%Y-%m-%d")
|
||||||
|
return {
|
||||||
|
"users": {"total": int(users["total"] or 0), "admins": int(users["admins"] or 0),
|
||||||
|
"authorized": int(users["authorized"] or 0)},
|
||||||
|
"plugins": {"total": int(plugins["total"] or 0), "published": int(plugins["published"] or 0),
|
||||||
|
"disabled": int(plugins["disabled"] or 0), "revoked": int(plugins["revoked"] or 0)},
|
||||||
|
"runs": {"total": int(runs["started"] or 0), "success": int(runs["success"] or 0),
|
||||||
|
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||||||
|
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||||||
|
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||||||
|
"today": now_day,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 审计 / 运行上报(统一分页 + 服务端筛选) ====================
|
||||||
|
def _audit_where(action: str, q: str) -> tuple[str, list]:
|
||||||
|
"""审计筛选条件:action 精确 + q 模糊(账号/对象/详情)。"""
|
||||||
|
where, args = [], []
|
||||||
|
if action.strip():
|
||||||
|
where.append("action = %s")
|
||||||
|
args.append(action.strip())
|
||||||
|
if q.strip():
|
||||||
|
where.append("(account LIKE %s OR target LIKE %s OR detail LIKE %s)")
|
||||||
|
args += ["%" + q.strip() + "%"] * 3
|
||||||
|
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||||
|
|
||||||
|
|
||||||
|
def _report_where(status: str, q: str) -> tuple[str, list]:
|
||||||
|
"""运行上报筛选条件:status 支持逗号分隔多值(如 done,success)+ q 模糊(账号/设备/插件/消息)。"""
|
||||||
|
where, args = [], []
|
||||||
|
if status.strip():
|
||||||
|
vals = [s.strip() for s in status.split(",") if s.strip()]
|
||||||
|
if len(vals) == 1:
|
||||||
|
where.append("status = %s")
|
||||||
|
args.append(vals[0])
|
||||||
|
elif len(vals) > 1:
|
||||||
|
where.append("status IN (%s)" % ", ".join(["%s"] * len(vals)))
|
||||||
|
args += vals
|
||||||
|
if q.strip():
|
||||||
|
where.append("(account LIKE %s OR device_id LIKE %s OR plugin_id LIKE %s OR msg LIKE %s)")
|
||||||
|
args += ["%" + q.strip() + "%"] * 4
|
||||||
|
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/audit")
|
||||||
|
def admin_audit(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, ge=1, le=1000),
|
||||||
|
action: str = Query(default=""),
|
||||||
|
q: str = Query(default=""),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""审计日志(统一分页 + 服务端筛选:action 操作类型、q 账号/对象/详情关键字,today 今日条数)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
where, args = _audit_where(action, q)
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs" + where, args)
|
||||||
|
today = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs WHERE at >= CURDATE()")
|
||||||
|
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||||
|
"SELECT account, nickname FROM accounts")}
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, account, action, target, detail, at FROM audit_logs" + where +
|
||||||
|
" ORDER BY id DESC LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||||
|
for r in rows:
|
||||||
|
r["nickname"] = nick.get(r["account"], "")
|
||||||
|
return {"items": rows, "total": total, "today": today}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/reports")
|
||||||
|
def admin_reports(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, ge=1, le=1000),
|
||||||
|
status: str = Query(default=""),
|
||||||
|
q: str = Query(default=""),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""运行上报记录(统一分页 + 服务端筛选:status 状态、q 账号/设备/插件/消息,today 今日条数)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
where, args = _report_where(status, q)
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports" + where, args)
|
||||||
|
today = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports WHERE at >= CURDATE()")
|
||||||
|
failed = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports "
|
||||||
|
"WHERE status IN ('error','failed')")
|
||||||
|
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||||
|
"SELECT account, nickname FROM accounts")}
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, account, device_id AS deviceId, plugin_id AS pluginId, version, status, msg, "
|
||||||
|
"duration_sec AS durationSec, at "
|
||||||
|
"FROM runtime_reports" + where + " ORDER BY id DESC LIMIT %s OFFSET %s",
|
||||||
|
args + [limit, offset])]
|
||||||
|
for r in rows:
|
||||||
|
r["nickname"] = nick.get(r["account"], "")
|
||||||
|
return {"items": rows, "total": total, "today": today, "failed": failed}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/devices")
|
||||||
|
def admin_devices(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, 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)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices")
|
||||||
|
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 OFFSET %s", (limit, offset))]
|
||||||
|
return {"items": rows, "total": total}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/shell-release")
|
||||||
|
async def admin_shell_release(upload: UploadFile = File(...),
|
||||||
|
version: str = Query(...),
|
||||||
|
notes: str = Query(default=""),
|
||||||
|
sha256: str = Query(default=""),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""发布执行机壳子新版安装包:存到 shell/ + 写 version.json(管理员)。
|
||||||
|
|
||||||
|
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||||||
|
"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
version = version.strip()
|
||||||
|
if not version:
|
||||||
|
raise HTTPException(400, "version 不能为空")
|
||||||
|
if not _SAFE_NAME_RE.match(version):
|
||||||
|
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||||||
|
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
filename = f"setup-37du-host-{version}.exe"
|
||||||
|
# 流式读取并限长(壳子安装包上限 1GB,防磁盘/内存耗尽,P1 安全债)
|
||||||
|
_MAX_SHELL_BYTES = 1024 * 1024 * 1024
|
||||||
|
chunks: list[bytes] = []
|
||||||
|
total = 0
|
||||||
|
while True:
|
||||||
|
chunk = await upload.read(1024 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
total += len(chunk)
|
||||||
|
if total > _MAX_SHELL_BYTES:
|
||||||
|
raise HTTPException(413, f"壳子安装包超过大小上限({_MAX_SHELL_BYTES // (1024 * 1024)}MB)")
|
||||||
|
chunks.append(chunk)
|
||||||
|
content = b"".join(chunks)
|
||||||
|
if not content:
|
||||||
|
raise HTTPException(400, "上传内容为空")
|
||||||
|
if not sha256:
|
||||||
|
sha256 = hashlib.sha256(content).hexdigest()
|
||||||
|
(config.SHELL_DIR / filename).write_bytes(content)
|
||||||
|
(config.SHELL_DIR / "version.json").write_text(
|
||||||
|
json.dumps({"version": version, "filename": filename,
|
||||||
|
"sha256": sha256, "notes": notes},
|
||||||
|
ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
_audit(login, "shell-release", filename)
|
||||||
|
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""账号登录与身份路由:当前账号信息 / 可授权平台 / 账号密码登录 / 自助改密 / 员工端扫码换 token。
|
||||||
|
|
||||||
|
- 管理写操作(改他人账号/插件)统一走 apis.admin(_require_admin);
|
||||||
|
- 此处为"自助/登录"类只读或本账号操作。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException
|
||||||
|
|
||||||
|
from controlplane import config, schemas
|
||||||
|
from controlplane.core.auth import (
|
||||||
|
_auth_fail, _auth_gate, _auth_reset, _check_token,
|
||||||
|
_cloud_account, _identity, _issue_cloud_token,
|
||||||
|
_require_admin, _sign_admin_token,
|
||||||
|
)
|
||||||
|
from controlplane.core.crypto import _hash_password, _verify_password
|
||||||
|
from controlplane.core.db import _db
|
||||||
|
from controlplane.core.dingtalk import _dingtalk_userinfo
|
||||||
|
from controlplane.core.notify import notify_account_created
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
_CONTROLPLANE_PLATFORMS = [
|
||||||
|
{"id": "hr", "label": "HR 系统"},
|
||||||
|
{"id": "oa", "label": "OA 系统"},
|
||||||
|
] # 需与 webhost/backend/auth.py `_LABELS` 保持一致;新增平台时两侧同步
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/me")
|
||||||
|
def admin_me(authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||||
|
"""查询当前账号信息:管理员标识 + 部门 + 昵称 + 头像。
|
||||||
|
|
||||||
|
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
|
||||||
|
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||||
|
except Exception:
|
||||||
|
account = ""
|
||||||
|
if not account:
|
||||||
|
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||||
|
"must_change_pwd": False}
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT is_admin, dept, nickname, status, avatar, must_change_pwd "
|
||||||
|
"FROM accounts WHERE account = %s",
|
||||||
|
(account,)).fetchone()
|
||||||
|
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
|
||||||
|
if not row or not row["status"]:
|
||||||
|
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||||
|
"must_change_pwd": False}
|
||||||
|
return {"account": account,
|
||||||
|
"is_admin": bool(row["is_admin"]),
|
||||||
|
"dept": (row["dept"] if row else "") or "",
|
||||||
|
"nickname": (row["nickname"] if row else "") or "",
|
||||||
|
"avatar": (row["avatar"] if row else "") or "",
|
||||||
|
"must_change_pwd": bool(row["must_change_pwd"])}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/platforms")
|
||||||
|
def admin_platforms(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""可授权平台列表(只读,替代授权页写死 hr/oa)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
return {"platforms": _CONTROLPLANE_PLATFORMS}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/auth")
|
||||||
|
def admin_auth(a: schemas.AuthIn,
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。
|
||||||
|
登录接口为公开入口,不要求 X-API-Token(否则未登录无法着装鉴权)。"""
|
||||||
|
account = a.account.strip()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(400, "account 不能为空")
|
||||||
|
_auth_gate(account)
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT password_hash, salt, is_admin, dept, nickname, must_change_pwd, status, avatar "
|
||||||
|
"FROM accounts WHERE account = %s",
|
||||||
|
(account,)).fetchone()
|
||||||
|
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||||
|
_auth_fail(account)
|
||||||
|
raise HTTPException(401, "账号或密码错误")
|
||||||
|
if not row["status"]:
|
||||||
|
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||||
|
_auth_reset(account)
|
||||||
|
_nickname = (row["nickname"] or "")
|
||||||
|
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||||
|
"dept": (row["dept"] or ""), "nickname": _nickname,
|
||||||
|
"avatar": (row["avatar"] or ""),
|
||||||
|
"must_change_pwd": bool(row["must_change_pwd"]),
|
||||||
|
"token": _sign_admin_token(account),
|
||||||
|
"cloud_token": _issue_cloud_token(account, _nickname)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/password")
|
||||||
|
def admin_password(p: schemas.PwdIn,
|
||||||
|
authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||||
|
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||||
|
try:
|
||||||
|
login = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||||
|
if not p.account.strip() or not p.new_password:
|
||||||
|
raise HTTPException(400, "account 与新密码不能为空")
|
||||||
|
if len(p.new_password) < 8:
|
||||||
|
raise HTTPException(400, "新密码至少 8 位")
|
||||||
|
if p.account != login:
|
||||||
|
raise HTTPException(403, "只能修改自己的密码")
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = %s",
|
||||||
|
(login,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(401, "账号不存在")
|
||||||
|
# 旧密码校验(所有账号均带盐;首次改密的旧密码 = 钉钉通知下发的初始密码,同样必须输入)
|
||||||
|
if not row["salt"] or not _verify_password(p.old_password, row["salt"], row["password_hash"]):
|
||||||
|
raise HTTPException(401, "原密码错误")
|
||||||
|
_hex, _salt = _hash_password(p.new_password)
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s, must_change_pwd = 0 "
|
||||||
|
"WHERE account = %s", (_hex, _salt, login))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True, "account": login}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
|
||||||
|
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 找建账号
|
||||||
|
# (不存在则自动建号:空壳+默认密码+强制改密,并推送钉钉通知)→ 签发云端会话 token(供壳调
|
||||||
|
# /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在 core.auth(_issue_cloud_token 签发
|
||||||
|
# 落库 cloud_tokens 表、_cloud_account 解析),此处不再重复声明。
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/auth/exchange")
|
||||||
|
def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||||
|
"""壳 → 云端:壳 POST 钉钉授权码 code,换取员工工号 + 云端会话 token(找建账号)。"""
|
||||||
|
code = (d.code or "").strip()
|
||||||
|
if not code:
|
||||||
|
raise HTTPException(400, "缺少 code")
|
||||||
|
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||||
|
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||||
|
info = _dingtalk_userinfo(code)
|
||||||
|
account = (info.get("account") or "").strip()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||||
|
nickname = (info.get("nickname") or "").strip()
|
||||||
|
unionid = (info.get("unionid") or "").strip()
|
||||||
|
# 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT nickname, status, must_change_pwd, is_admin FROM accounts WHERE account = %s",
|
||||||
|
(account,)).fetchone()
|
||||||
|
if row:
|
||||||
|
if not row["status"]:
|
||||||
|
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||||
|
if nickname and nickname != (row["nickname"] or ""):
|
||||||
|
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||||||
|
(nickname, account))
|
||||||
|
conn.commit()
|
||||||
|
created, must_change = False, bool(row["must_change_pwd"])
|
||||||
|
is_admin = bool(row["is_admin"])
|
||||||
|
else:
|
||||||
|
# 自动建号(空壳):初始密码取默认值,强制首次改密
|
||||||
|
pwd = config.DINGTALK_DEFAULT_PASSWORD
|
||||||
|
_hex, _salt = _hash_password(pwd)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||||
|
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||||
|
(account, _hex, _salt, nickname, unionid))
|
||||||
|
conn.commit()
|
||||||
|
created, must_change, is_admin = True, True, False
|
||||||
|
notify_account_created(account, nickname, pwd, unionid, source="钉钉扫码")
|
||||||
|
token = _issue_cloud_token(account, nickname)
|
||||||
|
return {"token": token, "account": account, "nickname": nickname,
|
||||||
|
"exists": not created, "created": created, "must_change_pwd": must_change,
|
||||||
|
"is_admin": is_admin}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""客户端敏感凭证中心化拉取(服务端侧):公钥登记 / 敏感凭证加密拉取 / 明文源管理。
|
||||||
|
|
||||||
|
- 凭证明文源存服务端 MySQL `client_creds.creds`(JSON: {key: plaintext}),
|
||||||
|
明文源只由管理员经「敏感凭证」页面(/creds/manage 查看 + /creds/seed 保存)录入;
|
||||||
|
register 仅登记执行机 RSA 公钥,不自动填充默认值。
|
||||||
|
- 拉取 GET /api/admin/creds:**仅管理员可拉**(解析身份后校验 is_admin),服务端用该账号
|
||||||
|
上报的 RSA 公钥把每个明文值 OAEP 加密为 base64 返回;客户端本机私钥解密。
|
||||||
|
- 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉值,
|
||||||
|
链路保留供未来每账号敏感值下发能力使用。
|
||||||
|
- 仅含钉钉开放平台凭证;HR/OA 平台登录账号由客户端本地加密存储(platform_accounts),不经服务端。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Query
|
||||||
|
|
||||||
|
from controlplane import schemas
|
||||||
|
from controlplane.core.auth import _cloud_account, _identity, _require_admin
|
||||||
|
from controlplane.core.crypto import rsa_encrypt
|
||||||
|
from controlplane.core.db import _audit, _db, _now
|
||||||
|
from controlplane.core.paging import count_rows, page_bounds
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# 与 webhost/backend/core/creds_sync.py 的敏感键白名单保持一致(双重保障:下发限定范围)。
|
||||||
|
# 仅下发钉钉开放平台凭证;HR/OA 平台登录账号改由执行机本地加密存储(platform_accounts),不经中心机。
|
||||||
|
_ALLOWED_KEYS = (
|
||||||
|
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/creds/register")
|
||||||
|
def creds_register(b: schemas.CredsRegisterIn,
|
||||||
|
authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""登记/更新某账号的 RSA 公钥(明文源不变)。
|
||||||
|
|
||||||
|
鉴权双轨(对齐方案"admin 或云令牌关联账号"):
|
||||||
|
- 管理员(X-Admin-Token)可为任意账号登记;
|
||||||
|
- 登录云令牌(Bearer)账号只能登记本人公钥(公钥本身公开,本人登记安全)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
except HTTPException:
|
||||||
|
_self = _cloud_account(authorization)
|
||||||
|
if not _self or _self != b.account.strip():
|
||||||
|
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||||
|
account = b.account.strip()
|
||||||
|
pem = b.pubkey_pem.strip()
|
||||||
|
if not account or not pem:
|
||||||
|
raise HTTPException(400, "account 与 pubkey_pem 不能为空")
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT creds FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||||
|
# 明文源只由管理员 seed 创建/更新:register 仅登记公钥,保留现有明文源(无则空)
|
||||||
|
existing = (row["creds"] if row else None) or "{}"
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, %s, %s, %s) "
|
||||||
|
"ON DUPLICATE KEY UPDATE pubkey_pem = VALUES(pubkey_pem), "
|
||||||
|
"creds = VALUES(creds), updated_at = VALUES(updated_at)",
|
||||||
|
(account, pem, existing, _now()))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True, "account": account}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/creds/seed")
|
||||||
|
def creds_seed(b: schemas.CredsSeedIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""录入/更新某账号的敏感凭证明文源(管理员,只允许白名单内键)。
|
||||||
|
|
||||||
|
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
|
||||||
|
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
|
||||||
|
"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
account = b.account.strip()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(400, "account 不能为空")
|
||||||
|
allowed = {k: v for k, v in b.values.items() if k in _ALLOWED_KEYS}
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT pubkey_pem FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||||
|
if row:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE client_creds SET creds = %s, updated_at = %s WHERE account = %s",
|
||||||
|
(json.dumps(allowed, ensure_ascii=False), _now(), account))
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, '', %s, %s)",
|
||||||
|
(account, json.dumps(allowed, ensure_ascii=False), _now()))
|
||||||
|
conn.commit()
|
||||||
|
# 敏感明文源写入属高危操作,审计留痕(不记录明文值本身)
|
||||||
|
_audit(login, "creds-seed", account, f"keys={sorted(allowed)}")
|
||||||
|
return {"ok": True, "account": account, "seeded_keys": sorted(allowed)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/creds/manage")
|
||||||
|
def creds_manage(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, 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:
|
||||||
|
"""管理台:列出已注册账号及其敏感凭证明文源(统一分页,items/total;值仅管理台可见)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM client_creds")
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT c.account, c.pubkey_pem, c.creds, c.updated_at, a.nickname "
|
||||||
|
"FROM client_creds c LEFT JOIN accounts a ON a.account = c.account "
|
||||||
|
"ORDER BY c.account LIMIT %s OFFSET %s", (limit, offset)).fetchall()
|
||||||
|
return {
|
||||||
|
"items": [{
|
||||||
|
"account": r["account"],
|
||||||
|
"nickname": r["nickname"] or "",
|
||||||
|
"has_pubkey": bool(r["pubkey_pem"]),
|
||||||
|
"creds": json.loads(r["creds"] or "{}"),
|
||||||
|
"updated_at": str(r["updated_at"] or ""),
|
||||||
|
} for r in rows],
|
||||||
|
"total": total,
|
||||||
|
"allowed_keys": list(_ALLOWED_KEYS),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/creds")
|
||||||
|
def creds_fetch(authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||||
|
"""下发敏感凭证(**仅管理员可拉**)。鉴权:登录云令牌(Bearer) → 签名票据 → X-Admin-User。
|
||||||
|
|
||||||
|
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
|
||||||
|
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||||
|
except Exception:
|
||||||
|
account = ""
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||||
|
with _db() as conn:
|
||||||
|
admin = conn.execute(
|
||||||
|
"SELECT is_admin FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||||
|
if not admin or not admin["is_admin"]:
|
||||||
|
raise HTTPException(403, "仅管理员可拉取敏感凭证")
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT pubkey_pem, creds FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||||
|
if not row or not row["pubkey_pem"]:
|
||||||
|
return {"account": account, "creds": {}}
|
||||||
|
try:
|
||||||
|
source = json.loads(row["creds"] or "{}")
|
||||||
|
encrypted = {k: rsa_encrypt(row["pubkey_pem"], v)
|
||||||
|
for k, v in source.items() if v is not None}
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
raise HTTPException(500, f"凭证加密失败: {e}") from e
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute("UPDATE client_creds SET updated_at = %s WHERE account = %s",
|
||||||
|
(_now(), account))
|
||||||
|
conn.commit()
|
||||||
|
return {"account": account, "creds": encrypted}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""钉钉扫码路由:找建账号 / OAuth 扫码页 + 回调 / 内嵌二维码(DDLogin)。
|
||||||
|
|
||||||
|
- 账号建立/鉴权统一走 /api/admin/dingtalk/auth(find-or-create,仅底座 X-API-Token 可调);
|
||||||
|
- /scan→/cb 与 /sns 仅为可信扫码入口,仅换取身份不建号(建号仍由 auth 把关)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from urllib.parse import quote, urlencode, urlparse
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Query
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
|
|
||||||
|
from controlplane import config, schemas
|
||||||
|
from controlplane.core.auth import _check_token, _sign_admin_token
|
||||||
|
from controlplane.core.crypto import _hash_password
|
||||||
|
from controlplane.core.db import _db
|
||||||
|
from controlplane.core.dingtalk import _dingtalk_sns_userinfo, _dingtalk_userinfo
|
||||||
|
from controlplane.core.notify import notify_account_created
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_back_url(url: str) -> bool:
|
||||||
|
"""回跳地址白名单:仅允许 http(s) + 回环 / 内网私有网段 / 配置的控制面域名。
|
||||||
|
|
||||||
|
防止开放重定向钓鱼(原实现仅校验 http(s) 前缀,可被引导到任意站点并携带身份信息)。
|
||||||
|
"""
|
||||||
|
if not url or not (url.startswith("http://") or url.startswith("https://")):
|
||||||
|
return False
|
||||||
|
host = (urlparse(url).hostname or "").lower()
|
||||||
|
if host in ("localhost", "127.0.0.1", "::1"):
|
||||||
|
return True
|
||||||
|
if config.DINGTALK_CALLBACK:
|
||||||
|
cb_host = (urlparse(config.DINGTALK_CALLBACK).hostname or "").lower()
|
||||||
|
if host == cb_host:
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(host)
|
||||||
|
return bool(ip.is_loopback or ip.is_private)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/dingtalk/auth")
|
||||||
|
def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""钉钉扫码身份 → 找建统一账号(仅底座 X-API-Token 可调)。
|
||||||
|
|
||||||
|
返回 {ok, account, nickname, is_admin, created, must_change_pwd, token}。
|
||||||
|
created=True 表示本次新建;must_change_pwd=True 表示当前为默认密码,前端须提示改密。
|
||||||
|
"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
account = d.account.strip()
|
||||||
|
if not account or not account.isprintable() or re.search(r"[\s]", account):
|
||||||
|
raise HTTPException(400, "工号不能为空且不可包含空白字符")
|
||||||
|
nickname = (d.nickname or "").strip()
|
||||||
|
ding_uid = (d.dingtalk_uid or "").strip()
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT account, is_admin, must_change_pwd, nickname, 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 = %s WHERE account = %s",
|
||||||
|
(nickname, account))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True, "account": account,
|
||||||
|
"nickname": nickname or (row["nickname"] or ""),
|
||||||
|
"is_admin": bool(row["is_admin"]),
|
||||||
|
"created": False, "must_change_pwd": bool(row["must_change_pwd"]),
|
||||||
|
"token": _sign_admin_token(account)}
|
||||||
|
# 不存在:自动建号(空壳),初始密码取覆盖值或默认值,强制改密
|
||||||
|
pwd = (d.password.strip() if d.password else config.DINGTALK_DEFAULT_PASSWORD)
|
||||||
|
if len(pwd) < 6:
|
||||||
|
raise HTTPException(400, "初始密码至少 6 位")
|
||||||
|
_hex, _salt = _hash_password(pwd)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||||
|
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||||
|
(account, _hex, _salt, nickname, ding_uid))
|
||||||
|
conn.commit()
|
||||||
|
# 钉钉工作通知(异步,失败不阻断建号):新用户收默认账号密码,管理员收权限开通提醒
|
||||||
|
notify_account_created(account, nickname, pwd, ding_uid, source="钉钉扫码")
|
||||||
|
return {"ok": True, "account": account, "nickname": nickname,
|
||||||
|
"is_admin": False, "created": True, "must_change_pwd": True,
|
||||||
|
"token": _sign_admin_token(account)}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 钉钉真实扫码(OAuth):扫码页 + 回调换取身份 ====================
|
||||||
|
# 流程:部署机扫码按钮 → 本机 /api/admin/dingtalk/scan → 跳钉钉登录页(redirect_uri=本中心机回调)
|
||||||
|
# → 用户扫码确认 → 钉钉回调 /api/admin/dingtalk/cb?code → 换 token 拉工号/姓名 →
|
||||||
|
# 302 回部署机(state 中带回的 back)携带身份 → 部署机静默建会话。
|
||||||
|
@router.get("/api/admin/dingtalk/scan")
|
||||||
|
def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳地址")) -> RedirectResponse:
|
||||||
|
"""扫码入口:302 到钉钉扫码登录页;state 携带部署机回跳地址,扫码成功后由 /cb 带回。"""
|
||||||
|
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||||
|
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||||
|
if not _safe_back_url(back):
|
||||||
|
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名,防止开放重定向)")
|
||||||
|
if not config.DINGTALK_CALLBACK:
|
||||||
|
raise HTTPException(400, "未配置 DINGTALK_CALLBACK(钉钉后台登记的回调地址)")
|
||||||
|
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||||
|
"redirect_uri": f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb",
|
||||||
|
"response_type": "code",
|
||||||
|
"client_id": config.DINGTALK_APP_KEY,
|
||||||
|
"scope": "openid",
|
||||||
|
"prompt": "consent",
|
||||||
|
"state": back})
|
||||||
|
return RedirectResponse(login_url)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/dingtalk/cb")
|
||||||
|
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||||||
|
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||||||
|
if not _safe_back_url(state):
|
||||||
|
raise HTTPException(400, "非法回跳地址(仅允许回环/内网/控制面域名)")
|
||||||
|
info = _dingtalk_userinfo(code)
|
||||||
|
qs = urlencode({"account": info["account"] or "", "nickname": info["nickname"],
|
||||||
|
"unionid": info["unionid"] or ""})
|
||||||
|
sep = "&" if "?" in state else "?"
|
||||||
|
return RedirectResponse(f"{state}{sep}{qs}")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/dingtalk/sns")
|
||||||
|
def dingtalk_sns(d: schemas.SnsIn) -> dict:
|
||||||
|
"""内嵌二维码扫码换取身份:loginTmpCode → 工号/姓名/unionid。
|
||||||
|
|
||||||
|
与 /scan→/cb 同为可信扫码入口,仅换取身份(不建号),故与链接授权链路一致不强制 X-API-Token;
|
||||||
|
账号创建仍由 /api/admin/dingtalk(find-or-create, _check_token)把关。
|
||||||
|
"""
|
||||||
|
if not d.code.strip():
|
||||||
|
raise HTTPException(400, "缺少扫码截图码")
|
||||||
|
return _dingtalk_sns_userinfo(d.code.strip())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/dingtalk/inline_qr")
|
||||||
|
def dingtalk_inline_qr(back: str = Query(default="", description="(兼容保留,内嵌不直接跳转)")) -> dict:
|
||||||
|
"""构造内嵌二维码(DDLogin)所需的 goto:登录页在本页内渲染二维码,不弹新窗口。"""
|
||||||
|
if not config.DINGTALK_APP_KEY:
|
||||||
|
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||||
|
if not config.DINGTALK_CALLBACK:
|
||||||
|
raise HTTPException(503, "未配置中心机回调域名(DINGTALK_CALLBACK)")
|
||||||
|
auth_url = ("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=%s"
|
||||||
|
"&response_type=code&scope=snsapi_login&state=%s&redirect_uri=%s") % (
|
||||||
|
config.DINGTALK_APP_KEY, secrets.token_hex(8),
|
||||||
|
quote(f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb"))
|
||||||
|
return {"goto": quote(auth_url)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/dingtalk/login-url")
|
||||||
|
def dingtalk_login_url(back: str = Query(...),
|
||||||
|
state: str = Query(default=""),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""构造钉钉扫码授权 URL(执行机代理调用):执行机无需自带钉钉应用凭证。
|
||||||
|
|
||||||
|
back 为执行机本机回跳地址(如 http://localhost:8799/auth/done),state 由执行机生成防回跳伪造;
|
||||||
|
扫码后钉钉跳回 back,执行机再拿 code 走 /auth/exchange 换身份。
|
||||||
|
"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||||
|
raise HTTPException(503, "控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||||
|
if not _safe_back_url(back):
|
||||||
|
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名)")
|
||||||
|
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||||
|
"redirect_uri": back,
|
||||||
|
"response_type": "code",
|
||||||
|
"client_id": config.DINGTALK_APP_KEY,
|
||||||
|
"scope": "openid",
|
||||||
|
"prompt": "consent",
|
||||||
|
"state": state or back})
|
||||||
|
return {"url": login_url}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""大文件源管理 API(管理员):登记/更新内网直链、列表、启停、删除。
|
||||||
|
|
||||||
|
大文件(壳子安装包、Chrome 安装包等)走内网文件服务器,中心机只存其直链。
|
||||||
|
发布动作由 agent_cli 完成:先传文件服务器拿 url,再经本接口登记。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from controlplane.core.auth import _check_token, _require_admin
|
||||||
|
from controlplane.core.db import _audit, _db, _now
|
||||||
|
from controlplane.core.paging import page_bounds
|
||||||
|
from controlplane.core.pkgutil import _version_key
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class FileSourceIn(BaseModel):
|
||||||
|
"""登记/更新一条大文件源。同一 category+version 重复提交则覆盖 url/notes/sha256/enabled。"""
|
||||||
|
category: str = Field(default="", max_length=32)
|
||||||
|
version: str = Field(default="", max_length=32)
|
||||||
|
filename: str = Field(default="", max_length=255)
|
||||||
|
url: str = Field(default="", max_length=2000)
|
||||||
|
sha256: str = Field(default="", max_length=64)
|
||||||
|
notes: str = Field(default="", max_length=512)
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
class FileSourcePatch(BaseModel):
|
||||||
|
"""启停 / 改说明。"""
|
||||||
|
enabled: Optional[bool] = None
|
||||||
|
notes: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
def _rows_to_dicts(rows) -> list[dict]:
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
out.append({"id": r["id"], "category": r["category"], "version": r["version"],
|
||||||
|
"filename": r["filename"], "url": r["url"], "sha256": r["sha256"],
|
||||||
|
"notes": r["notes"], "enabled": bool(r["enabled"]),
|
||||||
|
"updated_at": str(r["updated_at"] or "")})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/file-sources")
|
||||||
|
def file_sources_list(category: str = "",
|
||||||
|
page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, 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:
|
||||||
|
"""按 category 列出大文件源(统一分页:先按版本号数值语义排序,再切片 items/total)。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
if category.strip():
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM file_sources WHERE category = %s", (category.strip(),)).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute("SELECT * FROM file_sources").fetchall()
|
||||||
|
# 版本号按数值语义排序("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||||
|
rows = sorted(rows, key=lambda r: (_version_key(r["version"]), r["id"]), reverse=True)
|
||||||
|
total = len(rows)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
return {"category": category, "items": _rows_to_dicts(rows[offset:offset + limit]), "total": total}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/admin/file-sources")
|
||||||
|
def file_sources_upsert(b: FileSourceIn,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""登记/覆盖一条大文件源(同一 category+version 去重)。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
category, version = b.category.strip(), b.version.strip()
|
||||||
|
url = b.url.strip()
|
||||||
|
if not category:
|
||||||
|
raise HTTPException(400, "category 不能为空")
|
||||||
|
if not url:
|
||||||
|
raise HTTPException(400, "url 不能为空")
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id FROM file_sources WHERE category = %s AND version = %s",
|
||||||
|
(category, version)).fetchone()
|
||||||
|
if row:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE file_sources SET filename=%s, url=%s, sha256=%s, notes=%s, "
|
||||||
|
"enabled=%s, updated_at=%s WHERE id=%s",
|
||||||
|
(b.filename.strip(), url, b.sha256.strip(), b.notes.strip(),
|
||||||
|
int(b.enabled), _now(), row["id"]))
|
||||||
|
fid = row["id"]
|
||||||
|
else:
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO file_sources(category, version, filename, url, sha256, notes, "
|
||||||
|
"enabled, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
|
||||||
|
(category, version, b.filename.strip(), url, b.sha256.strip(),
|
||||||
|
b.notes.strip(), int(b.enabled), _now()))
|
||||||
|
fid = cur.lastrowid
|
||||||
|
conn.commit()
|
||||||
|
_audit(login, "file-source-upsert", f"{category}@{version}", url)
|
||||||
|
return {"ok": True, "id": fid, "category": category, "version": version}
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/api/admin/file-sources/{fid}")
|
||||||
|
def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""启停 / 改说明。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
fields, vals = [], []
|
||||||
|
if b.enabled is not None:
|
||||||
|
fields.append("enabled = %s"); vals.append(int(b.enabled))
|
||||||
|
if b.notes is not None:
|
||||||
|
fields.append("notes = %s"); vals.append(b.notes.strip())
|
||||||
|
if not fields:
|
||||||
|
raise HTTPException(400, "无更新字段")
|
||||||
|
fields.append("updated_at = %s"); vals.append(_now())
|
||||||
|
with _db() as conn:
|
||||||
|
cur = conn.execute(f"UPDATE file_sources SET {', '.join(fields)} WHERE id=%s",
|
||||||
|
(*vals, fid))
|
||||||
|
conn.commit()
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
raise HTTPException(404, "记录不存在")
|
||||||
|
_audit(login, "file-source-patch", str(fid), f"enabled={b.enabled}, notes={b.notes is not None}")
|
||||||
|
return {"ok": True, "id": fid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/admin/file-sources/{fid}")
|
||||||
|
def file_sources_delete(fid: int,
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""删除一条大文件源(仅删中心机登记,不动内网服务器文件)。"""
|
||||||
|
login = _require_admin(x_admin_token, x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
cur = conn.execute("DELETE FROM file_sources WHERE id = %s", (fid,))
|
||||||
|
conn.commit()
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
raise HTTPException(404, "记录不存在")
|
||||||
|
_audit(login, "file-source-delete", str(fid))
|
||||||
|
return {"ok": True, "id": fid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/file-sources/{category}")
|
||||||
|
def file_sources_public_latest(category: str,
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""客户端只读取某 category 最新启用的一条大文件源(带 X-API-Token 即可,无需 admin 票据)。
|
||||||
|
|
||||||
|
供执行机消费内网大文件直链(如 Chrome 安装包)。返回最近 version 的一条;无则 available=False。
|
||||||
|
"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, category, version, filename, url, sha256, notes FROM file_sources "
|
||||||
|
"WHERE category = %s AND enabled = 1", (category.strip(),))]
|
||||||
|
if not rows:
|
||||||
|
return {"available": False, "category": category.strip()}
|
||||||
|
# 版本号按数值语义取最新("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||||
|
r = max(rows, key=lambda r: (_version_key(r["version"]), r["id"]))
|
||||||
|
return {
|
||||||
|
"available": True,
|
||||||
|
"category": r["category"], "version": r["version"],
|
||||||
|
"filename": r["filename"], "url": r["url"], "sha256": r["sha256"],
|
||||||
|
"notes": r["notes"] or "",
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""内网文件服务器状态 API:心跳上报接收 + 管理端状态查看。
|
||||||
|
|
||||||
|
- 文件服务器(fileserver,8802)周期主动上报心跳,本模块落库 fileserver_status;
|
||||||
|
- 中心机监控线程(core/monitor.py)依据 last_seen 超时判离线,并钉钉告警管理员;
|
||||||
|
- 心跳上报仅需 X-API-Token(底座凭证),查看需管理员票据。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from controlplane.core.auth import _check_token, _require_admin
|
||||||
|
from controlplane.core.db import _db, _now
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class FileserverHeartbeatIn(BaseModel):
|
||||||
|
"""文件服务器心跳载荷(主动上报状态)。host 为唯一标识,默认=对外下载根。"""
|
||||||
|
host: str = Field(default="", max_length=255)
|
||||||
|
base_url: str = Field(default="", max_length=255)
|
||||||
|
hostname: str = Field(default="", max_length=128)
|
||||||
|
ip: str = Field(default="", max_length=64)
|
||||||
|
port: int = 0
|
||||||
|
file_count: int = 0
|
||||||
|
total_size: int = 0
|
||||||
|
version: str = Field(default="", max_length=64)
|
||||||
|
uptime_sec: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/fileserver/heartbeat")
|
||||||
|
def fileserver_heartbeat(b: FileserverHeartbeatIn,
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""接收文件服务器心跳:upsert 状态快照,last_seen 刷新;离线中收到心跳则恢复在线。"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
host = b.host.strip()
|
||||||
|
if not host:
|
||||||
|
raise HTTPException(400, "host 不能为空")
|
||||||
|
now = _now()
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT status, offline_notified FROM fileserver_status WHERE host = %s",
|
||||||
|
(host,)).fetchone()
|
||||||
|
if row:
|
||||||
|
# 离线期间恢复上线:标记在线、清除离线告警标记(恢复时不再推送)
|
||||||
|
was_offline = (not row["status"]) or bool(row["offline_notified"])
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE fileserver_status SET base_url=%s, hostname=%s, ip=%s, port=%s, "
|
||||||
|
"file_count=%s, total_size=%s, version=%s, uptime_sec=%s, last_seen=%s, "
|
||||||
|
"status=1, offline_notified=0"
|
||||||
|
+ (", last_status_change=%s" if was_offline else "") +
|
||||||
|
" WHERE host=%s",
|
||||||
|
(b.base_url.strip(), b.hostname.strip(), b.ip.strip(), int(b.port or 0),
|
||||||
|
int(b.file_count or 0), int(b.total_size or 0), b.version.strip(),
|
||||||
|
int(b.uptime_sec or 0), now) +
|
||||||
|
((now, host) if was_offline else (host,)))
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO fileserver_status(host, base_url, hostname, ip, port, file_count, "
|
||||||
|
"total_size, version, uptime_sec, last_seen, status, offline_notified, "
|
||||||
|
"created_at, last_status_change) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 1, 0, %s, %s)",
|
||||||
|
(host, b.base_url.strip(), b.hostname.strip(), b.ip.strip(), int(b.port or 0),
|
||||||
|
int(b.file_count or 0), int(b.total_size or 0), b.version.strip(),
|
||||||
|
int(b.uptime_sec or 0), now, now, now))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True, "host": host, "last_seen": now}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/fileserver/status")
|
||||||
|
def fileserver_status_list(limit: int = Query(default=100, ge=1, le=1000),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""管理端查看文件服务器在线状态列表(按最近心跳倒序)。"""
|
||||||
|
_require_admin(x_admin_token, x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT id, host, base_url, hostname, ip, port, file_count, total_size, version, "
|
||||||
|
" uptime_sec, last_seen, status, last_status_change, offline_notified, "
|
||||||
|
" created_at "
|
||||||
|
"FROM fileserver_status ORDER BY last_seen DESC LIMIT %s", (limit,))]
|
||||||
|
for r in rows:
|
||||||
|
r["status"] = bool(r["status"])
|
||||||
|
r["offline_notified"] = bool(r["offline_notified"])
|
||||||
|
return {"fileservers": rows}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""基础元信息路由:健康检查。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health() -> dict:
|
||||||
|
"""健康检查:不泄露任何环境信息(原实现返回 MYSQL_HOST/库名,公网可探,P2 收敛)。"""
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
|
||||||
|
|
||||||
|
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Query
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
from controlplane import config, crypto, schemas
|
||||||
|
from controlplane.core.auth import _check_token, _cloud_account
|
||||||
|
from controlplane.core.db import _audit, _db, _now
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def _account_disabled(acct: str) -> bool:
|
||||||
|
"""账号是否已停用(停用后机器侧一律不给插件/授权)。"""
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute("SELECT status FROM accounts WHERE account = %s", (acct,)).fetchone()
|
||||||
|
return bool(row) and not bool(row["status"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/plugins", response_model=dict)
|
||||||
|
def plugins(account: str = Query(default="", description="账号(旧底座按此传)"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
authorization: str = Header(default="", alias="Authorization")) -> dict:
|
||||||
|
"""按账号返回可用插件清单(权限隔离):无权限的账号返回空列表。
|
||||||
|
|
||||||
|
§2.2:优先用云端会话 token(Authorization: Bearer <token>)解出工号,不再明文传 account;
|
||||||
|
兜底兼容旧底座 `account?` + X-API-Token 的调用方式。
|
||||||
|
"""
|
||||||
|
acct = _cloud_account(authorization)
|
||||||
|
if not acct:
|
||||||
|
_check_token(x_api_token)
|
||||||
|
acct = (account or "").strip()
|
||||||
|
if not acct:
|
||||||
|
raise HTTPException(400, "缺少有效会话或 account")
|
||||||
|
if _account_disabled(acct):
|
||||||
|
return {"account": acct, "plugins": []}
|
||||||
|
with _db() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id, p.name, p.latest_version AS version
|
||||||
|
FROM plugins p
|
||||||
|
JOIN account_plugins ap ON ap.plugin_id = p.id
|
||||||
|
WHERE ap.account = %s
|
||||||
|
ORDER BY p.id
|
||||||
|
""",
|
||||||
|
(acct,),
|
||||||
|
).fetchall()
|
||||||
|
return {"account": acct, "plugins": [schemas.PluginOut(**dict(r)).model_dump() for r in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/platforms/allowed", response_model=dict)
|
||||||
|
def platforms_allowed(account: str = Query(default="", description="账号(旧底座按此传)"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
authorization: str = Header(default="", alias="Authorization")) -> dict:
|
||||||
|
"""按账号返回可登录平台白名单(与插件权限同模式)。支持云端会话 token 或旧底座 account 两种身份来源。"""
|
||||||
|
acct = _cloud_account(authorization)
|
||||||
|
if not acct:
|
||||||
|
_check_token(x_api_token)
|
||||||
|
acct = (account or "").strip()
|
||||||
|
if not acct:
|
||||||
|
raise HTTPException(400, "缺少有效会话或 account")
|
||||||
|
if _account_disabled(acct):
|
||||||
|
return {"account": acct, "allowed": []}
|
||||||
|
with _db() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"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]}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 产品化:客户端(部署端)拉取接口 ====================
|
||||||
|
@router.get("/api/me/pubkey")
|
||||||
|
def me_pubkey() -> dict:
|
||||||
|
"""下发中心机公钥(PEM 文本),部署端首次联网时缓存用于离线验签。"""
|
||||||
|
return {"pub": crypto._pubkey_pem().decode("ascii"), "algo": "ed25519"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/me/license")
|
||||||
|
def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""签发离线授权票据:基于当前账号的插件级授权(can_run)快照,Ed25519 签名。
|
||||||
|
|
||||||
|
票据含 expiresAt(issuedAt + LICENSE_TTL_DAYS 天):执行机最多离线该天数,
|
||||||
|
超时须联网刷新票据后才可继续使用(每次刷新重置窗口)。
|
||||||
|
"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
if not account.strip():
|
||||||
|
raise HTTPException(400, "account 不能为空")
|
||||||
|
if _account_disabled(account.strip()):
|
||||||
|
raise HTTPException(403, "账号已停用,无法获取授权")
|
||||||
|
with _db() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT g.plugin_id, g.can_download, g.can_run, p.name, p.status, p.latest_version
|
||||||
|
FROM account_plugins g
|
||||||
|
JOIN plugins p ON p.id = g.plugin_id
|
||||||
|
WHERE g.account = %s
|
||||||
|
""",
|
||||||
|
(account.strip(),),
|
||||||
|
).fetchall()
|
||||||
|
plugins = [{"pluginId": r["plugin_id"], "name": r["name"],
|
||||||
|
"canDownload": bool(r["can_download"]), "canRun": bool(r["can_run"]),
|
||||||
|
"status": r["status"], "latestVersion": r["latest_version"]}
|
||||||
|
for r in rows]
|
||||||
|
issued_at = _now()
|
||||||
|
expires_at = int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600
|
||||||
|
blob = crypto._sign_blob({"userId": account.strip(), "deviceId": device or "",
|
||||||
|
"issuedAt": issued_at, "expiresAt": expires_at, "plugins": plugins})
|
||||||
|
return {"ticket": blob, "plugins": plugins, "issuedAt": issued_at, "expiresAt": expires_at}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/me/control-list")
|
||||||
|
def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""签发管控清单:下架(revoke)/禁用(disable)/强制更新(force-update)聚合,Ed25519 签名。
|
||||||
|
|
||||||
|
与授权票据同窗口携带 expiresAt:执行机刷新票据时一并刷新管控清单。
|
||||||
|
"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
revoked = []
|
||||||
|
disabled = []
|
||||||
|
forced = []
|
||||||
|
with _db() as conn:
|
||||||
|
for r in conn.execute(
|
||||||
|
"SELECT id, name, status, force_min_version, force_deadline FROM plugins"):
|
||||||
|
pid = r["id"]
|
||||||
|
if r["status"] == "revoked":
|
||||||
|
revoked.append(pid)
|
||||||
|
elif r["status"] == "disabled":
|
||||||
|
disabled.append(pid)
|
||||||
|
if r["force_min_version"] and r["force_deadline"]:
|
||||||
|
forced.append({"pluginId": pid, "minVersion": r["force_min_version"],
|
||||||
|
"deadline": r["force_deadline"]})
|
||||||
|
payload = {"revokedPlugins": revoked, "disabledPlugins": disabled,
|
||||||
|
"forcedUpdates": forced, "updatedAt": _now(),
|
||||||
|
"expiresAt": int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600}
|
||||||
|
return {"ticket": crypto._sign_blob(payload), "control": payload}
|
||||||
|
|
||||||
|
|
||||||
|
# 一次性下载票据落库(download_tickets 表):gunicorn 多 worker 下签发与兑换必须共享同一份状态,
|
||||||
|
# 否则 A worker 签发的票据落到 B/C/D worker 兑换会 404「票据无效」,3/4 概率下载失败(同云令牌坑)。
|
||||||
|
_DL_TICKET_TTL = 3600 # 票据有效期(秒):签发后 1 小时未兑换即清理
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/plugins/{plugin_id}/versions/{version}/download-ticket")
|
||||||
|
def download_ticket(plugin_id: str, version: str,
|
||||||
|
account: str = Query(...),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""签发一次性下载票据:校验账号对该插件的 can_download 授权后签发,票据仅可换一次。"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
if not account.strip():
|
||||||
|
raise HTTPException(400, "account 不能为空")
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT can_download FROM 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 = %s AND version = %s",
|
||||||
|
(plugin_id, version)).fetchone()
|
||||||
|
if not ver:
|
||||||
|
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||||
|
if not row or not row["can_download"]:
|
||||||
|
raise HTTPException(403, "无该插件的下载授权")
|
||||||
|
path = config.PKG_DIR / ver["filename"]
|
||||||
|
if not path.exists():
|
||||||
|
raise HTTPException(404, f"包文件缺失:{ver['filename']}")
|
||||||
|
# 票据内含可下载文件名与校验值;落库共享,兑换时原子置 used=1 作废
|
||||||
|
nonce = secrets.token_hex(16)
|
||||||
|
with _db() as conn:
|
||||||
|
# 顺手清理过期票据,防表无限增长
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM download_tickets WHERE created_at < DATE_SUB(NOW(), INTERVAL %d SECOND)"
|
||||||
|
% int(_DL_TICKET_TTL))
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO download_tickets(nonce, filename, sha256, used) VALUES (%s, %s, %s, 0)",
|
||||||
|
(nonce, ver["filename"], ver["sha256"] or ""))
|
||||||
|
url = f"/api/download/{nonce}"
|
||||||
|
return {"ticket": nonce, "url": url, "filename": ver["filename"],
|
||||||
|
"sha256": ver["sha256"] or "", "expiresAt": _now()}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/download/{ticket}")
|
||||||
|
def download(ticket: str, x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||||
|
"""兑换下载票据:一次性有效,兑换即作废并写审计。"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
# 原子占位:仅 used=0 才能改成 1,命中行数=0 说明票据不存在或已被兑换
|
||||||
|
cur = conn.execute(
|
||||||
|
"UPDATE download_tickets SET used = 1 WHERE nonce = %s AND used = 0", (ticket,))
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT filename FROM download_tickets WHERE nonce = %s", (ticket,)).fetchone()
|
||||||
|
if not cur.rowcount or not row:
|
||||||
|
raise HTTPException(404, "下载票据无效或已使用")
|
||||||
|
path = config.PKG_DIR / row["filename"]
|
||||||
|
if not path.exists():
|
||||||
|
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||||||
|
_audit("", "download-ticket", row["filename"])
|
||||||
|
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/runtime/report")
|
||||||
|
def runtime_report(b: schemas.RuntimeReportIn,
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""接收部署端运行上报(启动/完成/失败/离线补报),统一落库。"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO runtime_reports(account, device_id, plugin_id, version, status, msg, duration_sec, at) "
|
||||||
|
"VALUES (%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": "<可选,更新说明>"}
|
||||||
|
|
||||||
|
|
||||||
|
def _shell_meta() -> dict:
|
||||||
|
"""读 shell/version.json;缺失/非法返回空 dict。"""
|
||||||
|
vf = config.SHELL_DIR / "version.json"
|
||||||
|
if not vf.is_file():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
# utf-8-sig:防 version.json 带 UTF-8 BOM(否则 json.loads 抛 JSONDecodeError → 回退失败)
|
||||||
|
d = json.loads(vf.read_text(encoding="utf-8-sig"))
|
||||||
|
return d if isinstance(d, dict) else {}
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _shell_source_url() -> dict:
|
||||||
|
"""优先取 file_sources 表 category='shell' 的启用记录(最新一条),返回含 url 的字典;
|
||||||
|
无记录返回空 dict。大文件走内网文件服务器时,客户端据此直连下载。"""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT version, filename, url, sha256, notes FROM file_sources "
|
||||||
|
"WHERE category = 'shell' AND enabled = 1 ORDER BY id DESC LIMIT 1").fetchone()
|
||||||
|
except Exception: # noqa: BLE001 DB 未就绪等,回退 version.json
|
||||||
|
return {}
|
||||||
|
if not row or not row.get("url"):
|
||||||
|
return {}
|
||||||
|
return {"version": row.get("version") or "", "filename": row.get("filename") or "",
|
||||||
|
"url": row["url"], "sha256": row.get("sha256") or "",
|
||||||
|
"notes": row.get("notes") or ""}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/shell/version")
|
||||||
|
def shell_version(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||||
|
"""壳子版本清单:执行端启动时比对,判断是否需要自动下载升级包。
|
||||||
|
|
||||||
|
优先用 file_sources(category=shell) 的内网直链;未登记时回退 version.json。
|
||||||
|
响应含 url:客户端据此直连内网文件服务器下载大包;url 为空则回退中心机 /api/shell/pkg。
|
||||||
|
"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
source = _shell_source_url()
|
||||||
|
meta = _shell_meta()
|
||||||
|
if source.get("url"):
|
||||||
|
return {"available": True, "version": source.get("version") or meta.get("version", ""),
|
||||||
|
"filename": source.get("filename") or meta.get("filename", ""),
|
||||||
|
"url": source["url"], "sha256": source.get("sha256") or meta.get("sha256", ""),
|
||||||
|
"notes": source.get("notes") or meta.get("notes", "")}
|
||||||
|
m = meta
|
||||||
|
if not m.get("version"):
|
||||||
|
return {"available": False, "version": ""}
|
||||||
|
return {"available": True, "version": str(m["version"]),
|
||||||
|
"filename": m.get("filename", ""), "sha256": m.get("sha256", ""),
|
||||||
|
"notes": m.get("notes", ""), "url": ""}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/shell/pkg")
|
||||||
|
def shell_pkg(x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||||
|
"""下载壳子安装包(setup.exe),供执行端静默升级。"""
|
||||||
|
_check_token(x_api_token)
|
||||||
|
m = _shell_meta()
|
||||||
|
fn = m.get("filename", "")
|
||||||
|
path = config.SHELL_DIR / fn if fn else None
|
||||||
|
if not path or not path.exists():
|
||||||
|
raise HTTPException(404, "壳子安装包缺失,请联系管理员")
|
||||||
|
return FileResponse(path, filename=path.name, media_type="application/octet-stream")
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""壳子定时任务配置备份(服务端侧):执行机变更后全量推送,仅存数据防丢失。
|
||||||
|
|
||||||
|
- 中心机只做「备份/恢复」存储(schedule_backups 表,按账号一行),不做管理界面;
|
||||||
|
- 身份来源(对齐 webhost cpapi._cp_headers):登录云令牌 Bearer → 签名票据 →
|
||||||
|
X-API-Token + X-Admin-User 兜底(_resolve_login),与配置时登录账号一致;
|
||||||
|
- 推送/拉取同一账号自己的备份(身份即账号,不校验 is_admin,普通员工自助备份)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from controlplane.core.auth import _identity
|
||||||
|
from controlplane.core.db import _db, _now
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class _BackupIn(BaseModel):
|
||||||
|
data: dict = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _require_identity(authorization: str = "", x_admin_token: str = "",
|
||||||
|
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||||
|
"""统一身份解析(core.auth._identity),无效则抛 401。"""
|
||||||
|
try:
|
||||||
|
return _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/schedules/backup")
|
||||||
|
def sched_backup_save(b: _BackupIn,
|
||||||
|
authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||||
|
"""覆盖保存某账号的定时任务全量配置(执行机变更后异步推送)。"""
|
||||||
|
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||||
|
payload = b.data if isinstance(b.data, dict) else {}
|
||||||
|
if not isinstance(payload.get("schedules"), list):
|
||||||
|
raise HTTPException(400, "data.schedules 必须为数组")
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO schedule_backups(account, data, updated_at) VALUES (%s, %s, %s) "
|
||||||
|
"ON DUPLICATE KEY UPDATE data = VALUES(data), updated_at = VALUES(updated_at)",
|
||||||
|
(account, json.dumps(payload, ensure_ascii=False), _now()))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True, "account": account}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/schedules/backup")
|
||||||
|
def sched_backup_load(authorization: str = Header(default="", alias="Authorization"),
|
||||||
|
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||||
|
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||||
|
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||||
|
"""读取某账号备份的定时任务全量配置(执行机启动时合并恢复缺失任务)。"""
|
||||||
|
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT data FROM schedule_backups WHERE account = %s", (account,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return {"data": {"schedules": []}}
|
||||||
|
try:
|
||||||
|
data = json.loads(row["data"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
data = {}
|
||||||
|
if not isinstance(data, dict) or not isinstance(data.get("schedules"), list):
|
||||||
|
return {"data": {"schedules": []}}
|
||||||
|
return {"data": data}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""内网插件控制面(中心机)入口(组装层)。
|
||||||
|
|
||||||
|
业务逻辑已按领域拆到 sibling 模块,本文件仅承担:lifespan 初始化、创建 app、
|
||||||
|
装配各领域路由、挂载前端产物、uvicorn 启动。
|
||||||
|
- config.py 配置/路径/密钥 - db.py 数据层(建表/种子/审计)
|
||||||
|
- crypto.py 口令哈希/Ed25519 - auth.py 鉴权(凭证/票据/防爆破/云端会话)
|
||||||
|
- dingtalk.py 钉钉官方接口 - pkgutil.py 插件包校验/解析/版本
|
||||||
|
- schemas.py 请求体模型 - apis/ 路由子包(meta/plugins/auth/dingtalk/admin)
|
||||||
|
|
||||||
|
DB:MySQL(连接参数在 controlplane/.env 的 MYSQL_*,库 37du_center;首次启动自动建库建表+种子)。
|
||||||
|
包文件:packages/。可选:CONTROLPLANE_TOKEN 非空时客户端须带
|
||||||
|
X-API-Token 请求头。
|
||||||
|
|
||||||
|
运行(本地 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||||
|
python -m controlplane.app # 首次自动建表 + 种子 + 生成示例包
|
||||||
|
uvicorn controlplane.app:app --port 8800
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from controlplane import config
|
||||||
|
from controlplane.core.db import _init_db, _seed
|
||||||
|
from controlplane.core.monitor import start_fileserver_monitor
|
||||||
|
from controlplane.apis import admin as api_admin
|
||||||
|
from controlplane.apis import auth as api_auth
|
||||||
|
from controlplane.apis import config_push as api_config_push
|
||||||
|
from controlplane.apis import dingtalk as api_dingtalk
|
||||||
|
from controlplane.apis import file_sources as api_file_sources
|
||||||
|
from controlplane.apis import fileserver_status as api_fileserver_status
|
||||||
|
from controlplane.apis import meta as api_meta
|
||||||
|
from controlplane.apis import plugins as api_plugins
|
||||||
|
from controlplane.apis import schedules as api_schedules
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
if not config.CONTROLPLANE_TOKEN:
|
||||||
|
# 内部凭证为空时客户端接口无鉴权(P0 安全债)。不阻断本地开发,但生产必须配置:
|
||||||
|
# 公网部署时请务必在 controlplane/.env 设置 CONTROLPLANE_TOKEN。
|
||||||
|
_LOGGER.error(
|
||||||
|
"CONTROLPLANE_TOKEN 未配置:全部客户端接口将无鉴权放行,生产环境禁止!")
|
||||||
|
_init_db()
|
||||||
|
_seed()
|
||||||
|
# 内网文件服务器离线监控:心跳超时判离线并钉钉告警管理员(daemon 线程)
|
||||||
|
start_fileserver_monitor()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="37du 插件管理平台", lifespan=lifespan)
|
||||||
|
# CORS 收敛为白名单(原 allow_origins=["*"],控制面走公网时任何站点可跨域调接口)。
|
||||||
|
# 默认放行本地控制面前端(8090 静态站);公网/反代部署用 CORS_ALLOW_ORIGINS 配置实际来源。
|
||||||
|
_CORS_ORIGINS = [o.strip() for o in os.getenv(
|
||||||
|
"CORS_ALLOW_ORIGINS",
|
||||||
|
"http://127.0.0.1:8090,http://localhost:8090").split(",") if o.strip()]
|
||||||
|
app.add_middleware(CORSMiddleware, allow_origins=_CORS_ORIGINS,
|
||||||
|
allow_methods=["*"], allow_headers=["*"])
|
||||||
|
|
||||||
|
app.include_router(api_meta.router)
|
||||||
|
app.include_router(api_plugins.router)
|
||||||
|
app.include_router(api_auth.router)
|
||||||
|
app.include_router(api_config_push.router)
|
||||||
|
app.include_router(api_file_sources.router)
|
||||||
|
app.include_router(api_fileserver_status.router)
|
||||||
|
app.include_router(api_schedules.router)
|
||||||
|
app.include_router(api_dingtalk.router)
|
||||||
|
app.include_router(api_admin.router)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
# PyInstaller --noconsole 下 sys.stdout/stderr 可能为 None,
|
||||||
|
# uvicorn 默认 DefaultFormatter 会调用 isatty() 导致启动崩溃,故自定义日志配置绕开颜色检测。
|
||||||
|
LOG_CONFIG = {
|
||||||
|
"version": 1,
|
||||||
|
"disable_existing_loggers": False,
|
||||||
|
"formatters": {
|
||||||
|
"default": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||||||
|
"access": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||||||
|
},
|
||||||
|
"handlers": {
|
||||||
|
"default": {"class": "logging.StreamHandler", "formatter": "default"},
|
||||||
|
"access": {"class": "logging.StreamHandler", "formatter": "access"},
|
||||||
|
},
|
||||||
|
"loggers": {
|
||||||
|
"uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||||||
|
"uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||||||
|
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
if sys.stdout is None:
|
||||||
|
sys.stdout = open(os.devnull, "w")
|
||||||
|
if sys.stderr is None:
|
||||||
|
sys.stderr = open(os.devnull, "w")
|
||||||
|
|
||||||
|
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")
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 70 B |
@@ -0,0 +1,2 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""controlplane 领域逻辑核心(core)包:配置/数据/密码学/鉴权/插件包/钉钉/模型。"""
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机鉴权:内部凭证校验 + 管理员签名票据 + 登录防爆破 + 云端会话 token。
|
||||||
|
|
||||||
|
分层关系:
|
||||||
|
- 内部凭证 X-API-Token:底座→统一后端的调用凭证(TOKEN 为空则内网可信,不强制)。
|
||||||
|
- 管理员票据 X-Admin-Token:登录后签发的签名票据(签名密钥见 config._admin_secret),
|
||||||
|
是唯一可信的管理员身份(不再信任可伪造的 X-Admin-User 明文)。
|
||||||
|
- 云端会话 token:员工端扫码登录后持有的短期 token,调 /api/plugins 等作身份(§2.2)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from controlplane.core import config
|
||||||
|
from controlplane.core.db import _db
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 内部凭证 ====================
|
||||||
|
def _check_token(x_api_token: str = "") -> None:
|
||||||
|
"""底座→统一后端的内部调用凭证校验。TOKEN 空则不要求(内网可信场景)。"""
|
||||||
|
if config.CONTROLPLANE_TOKEN and x_api_token != config.CONTROLPLANE_TOKEN:
|
||||||
|
raise HTTPException(401, "鉴权失败:无效或缺失 X-API-Token")
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 管理员签名票据 ====================
|
||||||
|
def _sign_admin_token(account: str) -> str:
|
||||||
|
"""签发带过期时间的签名票据:<base64url(json)>.<hmac_sig>,内含账号,防篡改/防伪造。"""
|
||||||
|
payload = base64.urlsafe_b64encode(
|
||||||
|
json.dumps({"a": account, "e": int(time.time()) + config._ADMIN_TOKEN_TTL},
|
||||||
|
separators=(",", ":")).encode()).decode().rstrip("=")
|
||||||
|
sig = hmac.new(config._admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||||||
|
hashlib.sha256).hexdigest()
|
||||||
|
return f"{payload}.{sig}"
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_admin_token(tok: str) -> str:
|
||||||
|
"""还原票据中的账号;签名无效或过期抛 ValueError。"""
|
||||||
|
if "." not in tok:
|
||||||
|
raise ValueError("invalid token")
|
||||||
|
payload, sig = tok.rsplit(".", 1)
|
||||||
|
expect = hmac.new(config._admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||||||
|
hashlib.sha256).hexdigest()
|
||||||
|
if not secrets.compare_digest(expect, sig):
|
||||||
|
raise ValueError("bad signature")
|
||||||
|
pad = "=" * (-len(payload) % 4)
|
||||||
|
data = json.loads(base64.urlsafe_b64decode(payload + pad))
|
||||||
|
if int(data.get("e", 0)) < int(time.time()):
|
||||||
|
raise ValueError("expired")
|
||||||
|
return str(data.get("a", "") or "")
|
||||||
|
|
||||||
|
|
||||||
|
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||||
|
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。
|
||||||
|
|
||||||
|
停用账号立即失效(status=0 拒绝);must_change_pwd=1(仍持初始密码)拒绝管理操作,
|
||||||
|
强制先改密(P0/P1 安全债)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
account = _verify_admin_token(x_admin_token)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(401, "缺少有效登录态")
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT is_admin, status, must_change_pwd FROM accounts WHERE account = %s",
|
||||||
|
(account,)).fetchone()
|
||||||
|
if not row or not row["is_admin"]:
|
||||||
|
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||||
|
if not row["status"]:
|
||||||
|
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||||
|
if row["must_change_pwd"]:
|
||||||
|
raise HTTPException(403, "请先修改初始密码后再执行管理操作")
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||||
|
x_admin_user: str = "") -> str:
|
||||||
|
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin)。
|
||||||
|
|
||||||
|
1. 优先验签名票据 X-Admin-Token(控制台/浏览器直连场景,免 X-API-Token);
|
||||||
|
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||||||
|
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
account = _verify_admin_token(x_admin_token)
|
||||||
|
if account:
|
||||||
|
return account
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if (x_admin_user.strip() and config.CONTROLPLANE_TOKEN
|
||||||
|
and x_api_token == config.CONTROLPLANE_TOKEN):
|
||||||
|
return x_admin_user.strip()
|
||||||
|
raise ValueError("no identity")
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 登录防爆破(MySQL 共享计数,gunicorn 多 worker 通用) ====================
|
||||||
|
# 原进程内 dict 计数在多 worker 下可绕过、且无锁读写不原子;改落库 auth_fail_counts 表
|
||||||
|
# (原子 UPSERT),锁定到期后自动重置计数,避免"锁定过期仍累计导致永久锁定"。
|
||||||
|
_AUTH_FAIL_LIMIT = 5 # 连续失败 N 次后锁定
|
||||||
|
_AUTH_LOCK_SECS = 300 # 锁定 5 分钟
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_gate(account: str) -> None:
|
||||||
|
"""登录前检查:DB 记录处于锁定中则拒绝。计数失败不阻断(安全兜底:宁可放宽)。"""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT 1 FROM auth_fail_counts WHERE account = %s AND locked_until > NOW()",
|
||||||
|
(account,)).fetchone()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return
|
||||||
|
if row:
|
||||||
|
raise HTTPException(429, "失败次数过多,账号已临时锁定,请 5 分钟后再试")
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_fail(account: str) -> None:
|
||||||
|
"""记录一次登录失败;连续达到阈值则锁定(原子 UPSERT,多 worker 一致)。"""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO auth_fail_counts(account, fails, locked_until) VALUES (%s, 1, NULL) "
|
||||||
|
"ON DUPLICATE KEY UPDATE "
|
||||||
|
"fails = IF(locked_until IS NOT NULL AND locked_until <= NOW(), 1, fails + 1), "
|
||||||
|
"locked_until = IF(fails + 1 >= %s, "
|
||||||
|
"DATE_ADD(NOW(), INTERVAL %s SECOND), NULL)",
|
||||||
|
(account, _AUTH_FAIL_LIMIT, _AUTH_LOCK_SECS))
|
||||||
|
conn.commit()
|
||||||
|
except Exception: # noqa: BLE001 计数失败不阻断登录流程
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_reset(account: str) -> None:
|
||||||
|
"""登录成功后清除失败计数。"""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute("DELETE FROM auth_fail_counts WHERE account = %s", (account,))
|
||||||
|
conn.commit()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 云端会话 token(员工端扫码登录,§2.2) ====================
|
||||||
|
_CLOUD_TOKEN_TTL = 7 * 24 * 3600 # 云端会话 token 有效期(秒,7 天)
|
||||||
|
# 云令牌落库(cloud_tokens 表)而非进程内存:gunicorn 多 worker 下登录签发的令牌
|
||||||
|
# 必须能被任意 worker 解出,否则 Bearer 身份解析只有 1/N 概率命中。
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_account_lookup(account: str) -> dict:
|
||||||
|
"""仅查询统一账号是否存在(登录链路不建号,建号只在管理员入口 /api/admin/dingtalk/auth)。
|
||||||
|
|
||||||
|
返回 {"exists": bool, "nickname": 账号记录昵称或空},绝不 INSERT accounts。
|
||||||
|
"""
|
||||||
|
if not account.strip():
|
||||||
|
return {"exists": False, "nickname": ""}
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT nickname FROM accounts WHERE account = %s", (account.strip(),)).fetchone()
|
||||||
|
return {"exists": bool(row), "nickname": (row["nickname"] if row else "") or ""}
|
||||||
|
|
||||||
|
|
||||||
|
def _cloud_account(bearer: str) -> str:
|
||||||
|
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。
|
||||||
|
|
||||||
|
查 cloud_tokens 表(落库共享)并 JOIN accounts 校验账号存在且未停用:删号/停用后
|
||||||
|
残留令牌立即失效(P1 安全债)。库不可用时返回空串(身份解析失败不抛异常,
|
||||||
|
交由各路由的兜底逻辑处理)。
|
||||||
|
"""
|
||||||
|
token = (bearer or "").strip()
|
||||||
|
if token.lower().startswith("bearer "):
|
||||||
|
token = token[7:].strip()
|
||||||
|
if not token:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT t.account FROM cloud_tokens t "
|
||||||
|
"JOIN accounts a ON a.account = t.account "
|
||||||
|
"WHERE t.token = %s AND t.expires_at > NOW() AND a.status = 1",
|
||||||
|
(token,)).fetchone()
|
||||||
|
except Exception: # noqa: BLE001 库异常按“无身份”处理,不阻断请求
|
||||||
|
return ""
|
||||||
|
return str(row["account"]) if row else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _issue_cloud_token(account: str, nickname: str) -> str:
|
||||||
|
"""签发云端会话 token 并落库(与 _cloud_account 同源,供 apis/auth /auth/exchange 调用)。
|
||||||
|
|
||||||
|
之前用进程内存 dict,gunicorn 多 worker 下写读不通导致 Bearer 随机解不出账号;改为落库。
|
||||||
|
"""
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
expires = datetime.now() + timedelta(seconds=_CLOUD_TOKEN_TTL)
|
||||||
|
with _db() as conn:
|
||||||
|
# 顺手清理已过期令牌,防表无限增长
|
||||||
|
conn.execute("DELETE FROM cloud_tokens WHERE expires_at < NOW()")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO cloud_tokens(token, account, nickname, expires_at) VALUES (%s, %s, %s, %s)",
|
||||||
|
(token, account, nickname, expires.strftime("%Y-%m-%d %H:%M:%S")))
|
||||||
|
conn.commit()
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def _identity(authorization: str = "", x_admin_token: str = "",
|
||||||
|
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||||
|
"""统一身份解析(三源,消除各路由复制粘贴):Bearer 云令牌 → X-Admin-Token →
|
||||||
|
X-Admin-User(+X-API-Token)。返回账号;无有效身份抛 ValueError(调用方决定 401/空响应)。
|
||||||
|
"""
|
||||||
|
acct = _cloud_account(authorization)
|
||||||
|
if acct:
|
||||||
|
return acct
|
||||||
|
return _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||||
|
|
||||||
|
|
||||||
|
def _revoke_account_tokens(account: str) -> None:
|
||||||
|
"""吊销某账号全部云令牌(删号/停用时调用,防止残留令牌继续解析)。"""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute("DELETE FROM cloud_tokens WHERE account = %s", (account,))
|
||||||
|
conn.commit()
|
||||||
|
except Exception: # noqa: BLE001 吊销失败不阻断主流程
|
||||||
|
pass
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机(控制面)配置:路径定位 + 本模块 env 加载 + 固化常量。
|
||||||
|
|
||||||
|
路径定位兼容两种运行形态(统一落到持久目录,禁止用 PyInstaller 临时解压目录,重启会丢数据):
|
||||||
|
- 源码:uvicorn controlplane.app:app → APP_DIR = controlplane/
|
||||||
|
- 打包:PyInstaller --onefile exe → APP_DIR = exe 同目录(db/packages/.admin_secret 持久可写)
|
||||||
|
|
||||||
|
env 专属:只读 controlplane/.env(或 exe 同目录 .env),环境变量优先、不覆盖已存在值。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def _app_base() -> Path:
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
return Path(sys.executable).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" # 历史 SQLite 路径,仅作迁移数据源/备份,不再读写
|
||||||
|
PKG_DIR = APP_DIR / "packages"
|
||||||
|
AVATAR_DIR = APP_DIR / "avatars"
|
||||||
|
# 壳子(执行机主程序)更新源:version.json + setup 安装包,供执行端自动下载升级
|
||||||
|
SHELL_DIR = APP_DIR / "shell"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_dotenv() -> None:
|
||||||
|
"""读本模块专属 env。UTF-8、'#'注释/'空行'跳过;已存在的环境变量不覆盖。"""
|
||||||
|
env_path = APP_DIR / ".env"
|
||||||
|
if not env_path.is_file():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||||
|
_line = _ln.strip()
|
||||||
|
if not _line or _line.startswith("#") or "=" not in _line:
|
||||||
|
continue
|
||||||
|
_k, _v = _line.split("=", 1)
|
||||||
|
_k, _v = _k.strip(), _v.strip()
|
||||||
|
if _k and _k not in os.environ:
|
||||||
|
os.environ[_k] = _v
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
_load_dotenv()
|
||||||
|
|
||||||
|
# 内部凭证(底座→统一后端的调用凭证)。为空则不强制(内网可信场景)。
|
||||||
|
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||||
|
CONTROLPLANE_PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||||
|
# 离线授权票据有效期(天):执行机最多离线该天数,超时须联网刷新票据后才可继续使用。
|
||||||
|
LICENSE_TTL_DAYS = 7
|
||||||
|
# MySQL 数据层(控制面唯一存储,无 SQLite 回退)。连接参数在 controlplane/.env 配置。
|
||||||
|
MYSQL_HOST = os.getenv("MYSQL_HOST", "")
|
||||||
|
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
|
||||||
|
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_pwd(重启复用,保证未改密
|
||||||
|
# 用户拿到的初始密码稳定),经钉钉工作通知下发给本人。不再使用硬编码 123456(P0 安全债)。
|
||||||
|
def _dingtalk_default_password() -> str:
|
||||||
|
_v = os.getenv("DINGTALK_DEFAULT_PASSWORD", "").strip()
|
||||||
|
if _v:
|
||||||
|
return _v
|
||||||
|
_f = APP_DIR / ".dingtalk_default_pwd"
|
||||||
|
if _f.is_file():
|
||||||
|
return _f.read_text(encoding="utf-8").strip()
|
||||||
|
_pwd = secrets.token_urlsafe(9) # 约 12 位,大小写字母+数字,无易混淆字符
|
||||||
|
try:
|
||||||
|
_f.write_text(_pwd, encoding="utf-8")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return _pwd
|
||||||
|
|
||||||
|
|
||||||
|
DINGTALK_DEFAULT_PASSWORD = _dingtalk_default_password()
|
||||||
|
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||||
|
# 同一套 KEY/SECRET 即可:扫码换 unionid/昵称 → gettoken 企业内部 token
|
||||||
|
# → getbyunionid 取 userid → v2/user/get 取 job_number(工号),无需第二组凭证。
|
||||||
|
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "")
|
||||||
|
DINGTALK_APP_SECRET = os.getenv("DINGTALK_APP_SECRET", "")
|
||||||
|
# 钉钉扫码回调地址。网页扫码是"浏览器重定向"(非钉钉服务器回访),故可直接用内网 IP/域名,
|
||||||
|
# 只要与用户实际访问地址、钉钉后台登记的回调域名一致即可。留空禁用扫码。
|
||||||
|
DINGTALK_CALLBACK = os.getenv("DINGTALK_CALLBACK", "").rstrip("/")
|
||||||
|
# 钉钉群机器人通知(新账号创建等事件推送)。webhook 留空则静默跳过;加签密钥按机器人安全设置可选。
|
||||||
|
DINGTALK_WEBHOOK_URL = os.getenv("DINGTALK_WEBHOOK_URL", "")
|
||||||
|
DINGTALK_WEBHOOK_SECRET = os.getenv("DINGTALK_WEBHOOK_SECRET", "")
|
||||||
|
# 钉钉自建应用工作通知(corpconversation 异步推送)。AgentId 优先 DINGTALK_AGENT_ID,
|
||||||
|
# 兜底复用 CREDS_DINGTALK_AGENT_ID(同一套钉钉应用凭证);access_token 复用 DINGTALK_APP_KEY/SECRET。
|
||||||
|
DINGTALK_AGENT_ID = (os.getenv("DINGTALK_AGENT_ID", "")
|
||||||
|
or os.getenv("CREDS_DINGTALK_AGENT_ID", "")).strip()
|
||||||
|
# 权限开通提醒的管理员姓名(钉钉扫码自动建号时通知其开通权限),经「搜索用户」接口直查 userid。
|
||||||
|
DINGTALK_ADMIN_NAME = os.getenv("DINGTALK_ADMIN_NAME", "夏一平")
|
||||||
|
|
||||||
|
# 内网文件服务器离线监控:心跳超时判离线(秒)+ 监控扫描间隔(秒)。
|
||||||
|
# 文件服务器周期上报心跳(默认 60s),超过该阈值未上报则判离线并钉钉告警管理员。
|
||||||
|
FILESERVER_HEARTBEAT_TIMEOUT = int(os.getenv("FILESERVER_HEARTBEAT_TIMEOUT", "180") or "180")
|
||||||
|
FILESERVER_MONITOR_INTERVAL = int(os.getenv("FILESERVER_MONITOR_INTERVAL", "30") or "30")
|
||||||
|
|
||||||
|
# 客户端敏感凭证默认值参考(webhost 不再明文落盘,中心机 .env 为唯一可信明文源)。
|
||||||
|
# 明文源只由管理员经 /api/admin/creds/seed 录入;客户端 register 不再自动填充本默认值
|
||||||
|
# (防任何登录账号借 register 自证拿到全局密钥),本配置保留供管理台 seed 时参考/未来使用。
|
||||||
|
# 键名 = 下发白名单键(去掉 CREDS_ 前缀),留空则该键不下发,需管理员用 /api/admin/creds/seed 录入。
|
||||||
|
CREDS_DEFAULT = {
|
||||||
|
_k.removeprefix("CREDS_"): os.getenv(_k, "").strip()
|
||||||
|
for _k in ("CREDS_DINGTALK_APPKEY", "CREDS_DINGTALK_APPSECRET",
|
||||||
|
"CREDS_DINGTALK_AGENT_ID", "CREDS_DINGTALK_CORP_ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > .admin_secret 文件(首次随机生成并持久化,
|
||||||
|
# 保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||||
|
# 注意:不再回退 CONTROLPLANE_TOKEN —— 传输凭证与管理密钥必须分离,否则持 X-API-Token 的执行机
|
||||||
|
# 可本地 HMAC 自签任意管理员票据全量接管系统(P0 安全债)。变更该密钥会使已签发的管理票据
|
||||||
|
# 全部失效(管理员需重新登录一次),普通用户的云令牌与底座 X-API-Token 不受影响。
|
||||||
|
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||||
|
_ADMIN_SECRET_FALLBACK: str = ""
|
||||||
|
_ADMIN_TOKEN_TTL = 12 * 3600 # 票据有效期 12h
|
||||||
|
|
||||||
|
|
||||||
|
def _admin_secret() -> str:
|
||||||
|
if _ADMIN_SECRET_CANDIDATE:
|
||||||
|
return _ADMIN_SECRET_CANDIDATE
|
||||||
|
global _ADMIN_SECRET_FALLBACK
|
||||||
|
if _ADMIN_SECRET_FALLBACK:
|
||||||
|
return _ADMIN_SECRET_FALLBACK
|
||||||
|
_f = APP_DIR / ".admin_secret"
|
||||||
|
if _f.is_file():
|
||||||
|
_ADMIN_SECRET_FALLBACK = _f.read_text(encoding="utf-8").strip()
|
||||||
|
else:
|
||||||
|
_ADMIN_SECRET_FALLBACK = secrets.token_hex(32)
|
||||||
|
_f.write_text(_ADMIN_SECRET_FALLBACK, encoding="utf-8")
|
||||||
|
return _ADMIN_SECRET_FALLBACK
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机密码学:标准库口令哈希 + Ed25519 签名。
|
||||||
|
|
||||||
|
- 口令哈希:pbkdf2_hmac(sha256, 120_000 轮),盐随机 + 常数时间比较。
|
||||||
|
- 签名:中心机私钥签名一切下发给部署端的可执行数据(license/control-list/download-ticket),
|
||||||
|
部署端用缓存的公钥离线验签,保证离线环境下数据可信、防篡改、防伪造。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||||
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
|
||||||
|
from controlplane.core import config
|
||||||
|
|
||||||
|
_ITER = 120_000
|
||||||
|
|
||||||
|
|
||||||
|
def _hash_password(pwd: str, salt: str = "") -> tuple[str, str]:
|
||||||
|
salt = salt or secrets.token_hex(8)
|
||||||
|
dk = hashlib.pbkdf2_hmac("sha256", pwd.encode("utf-8"), salt.encode("utf-8"), _ITER)
|
||||||
|
return dk.hex(), salt
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_password(pwd: str, salt: str, hexdigest: str) -> bool:
|
||||||
|
dk = hashlib.pbkdf2_hmac("sha256", pwd.encode("utf-8"), salt.encode("utf-8"), _ITER)
|
||||||
|
return secrets.compare_digest(dk.hex(), hexdigest)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 产品化:Ed25519 密钥 + 签名票据 ====================
|
||||||
|
# 密钥持久化到 APP_DIR/keys(重启复用,不回退)。
|
||||||
|
_KEY_DIR = config.APP_DIR / "keys"
|
||||||
|
_PRIV_PATH = _KEY_DIR / "center_key.priv"
|
||||||
|
_PUB_PATH = _KEY_DIR / "center_key.pub"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_or_create_keypair() -> dict:
|
||||||
|
"""首次启动生成并持久化 Ed25519 私钥/公钥(PEM),重启复用。"""
|
||||||
|
_KEY_DIR.mkdir(exist_ok=True)
|
||||||
|
if _PRIV_PATH.is_file() and _PUB_PATH.is_file():
|
||||||
|
_priv = serialization.load_pem_private_key(_PRIV_PATH.read_bytes(), password=None)
|
||||||
|
_pub = serialization.load_pem_public_key(_PUB_PATH.read_bytes())
|
||||||
|
else:
|
||||||
|
_priv = Ed25519PrivateKey.generate()
|
||||||
|
_pub = _priv.public_key()
|
||||||
|
_PRIV_PATH.write_bytes(_priv.private_bytes(
|
||||||
|
serialization.Encoding.PEM,
|
||||||
|
serialization.PrivateFormat.PKCS8,
|
||||||
|
serialization.NoEncryption()))
|
||||||
|
_PUB_PATH.write_bytes(_pub.public_bytes(
|
||||||
|
serialization.Encoding.PEM,
|
||||||
|
serialization.PublicFormat.SubjectPublicKeyInfo))
|
||||||
|
return {"priv": _priv, "pub": _pub}
|
||||||
|
|
||||||
|
|
||||||
|
_KEYS = _load_or_create_keypair()
|
||||||
|
|
||||||
|
|
||||||
|
def _pubkey_pem() -> bytes:
|
||||||
|
"""中心机公钥 PEM(下发给部署端缓存用于离线验签)。"""
|
||||||
|
return _KEYS["pub"].public_bytes(
|
||||||
|
serialization.Encoding.PEM,
|
||||||
|
serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||||
|
|
||||||
|
|
||||||
|
def _sign_blob(payload: dict) -> str:
|
||||||
|
"""签名打包:{base64url(json)}.{base64url(ed25519sig)}。signature=bin(64B) 后 base64url。"""
|
||||||
|
canon = json.dumps(payload, ensure_ascii=False, separators=(",", ":"),
|
||||||
|
sort_keys=True).encode("utf-8")
|
||||||
|
sig = _KEYS["priv"].sign(canon)
|
||||||
|
return (f"{base64.urlsafe_b64encode(canon).decode().rstrip('=')}."
|
||||||
|
f"{base64.urlsafe_b64encode(sig).decode().rstrip('=')}")
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||||
|
"""验签并返回 payload;签名非法/结构错误抛 ValueError。"""
|
||||||
|
if "." not in blob:
|
||||||
|
raise ValueError("bad blob")
|
||||||
|
b64, sig64 = blob.rsplit(".", 1)
|
||||||
|
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
|
||||||
|
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
|
||||||
|
if len(sig) != 64:
|
||||||
|
raise ValueError("bad signature len")
|
||||||
|
pub.verify(sig, canon)
|
||||||
|
return json.loads(canon)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 执行机敏感凭证下发:RSA 加密 ====================
|
||||||
|
def rsa_encrypt(pubkey_pem: str | bytes, plaintext: str) -> str:
|
||||||
|
"""用执行机上报的 RSA 公钥加密敏感明文,返回 base64 密文串。
|
||||||
|
|
||||||
|
凭证值均为短串(口令/密钥),OAEP+SHA256 上限 ~190B(RSA-2048),已足够。
|
||||||
|
供中心机下发 `/api/admin/creds` 时对每个敏感值加密使用。
|
||||||
|
"""
|
||||||
|
pem = pubkey_pem.encode() if isinstance(pubkey_pem, str) else pubkey_pem
|
||||||
|
pub = serialization.load_pem_public_key(pem)
|
||||||
|
if not isinstance(pub, rsa.RSAPublicKey):
|
||||||
|
raise ValueError("pubkey 必须是 RSA 公钥")
|
||||||
|
ct = pub.encrypt(
|
||||||
|
plaintext.encode("utf-8"),
|
||||||
|
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(), label=None))
|
||||||
|
return base64.b64encode(ct).decode()
|
||||||
@@ -0,0 +1,405 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机数据层:MySQL 访问 + 幂等建表(DDL 内嵌) + 迁移版本 + 种子 + 审计 + 常用时间戳。
|
||||||
|
|
||||||
|
- 数据访问统一收敛到 `_db()`(PyMySQL DictCursor,commit+close 收口),路由只在本层之上组合读写。
|
||||||
|
- 建表 DDL 与 `desktop/controlplane/tools/schema_mysql.sql` 保持同步(该文件为人工建库权威源,
|
||||||
|
本文件为运行时幂等副本;新增表/字段需两处同步维护)。
|
||||||
|
- 数据库连接由 `controlplane/.env` 的 MYSQL_* 决定;控制面不再提供 SQLite 回退。
|
||||||
|
- 参数占位符统一 `%s`(PyMySQL),禁止 `?`(SQLite 语法)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime
|
||||||
|
import logging
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pymysql
|
||||||
|
from pymysql.cursors import DictCursor
|
||||||
|
|
||||||
|
from controlplane.core import config
|
||||||
|
from controlplane.core.crypto import _hash_password
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||||
|
_SCHEMA_VERSION = "20260920_001"
|
||||||
|
|
||||||
|
# 全量 DDL(15 张表,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='系统级键值配置'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS client_creds (
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||||
|
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||||
|
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (account)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS file_sources (
|
||||||
|
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||||
|
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||||
|
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||||
|
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||||
|
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||||
|
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||||
|
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
KEY idx_category (category)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||||
|
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||||
|
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||||
|
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||||
|
PRIMARY KEY (token),
|
||||||
|
KEY idx_expires (expires_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||||
|
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||||
|
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||||
|
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||||
|
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||||
|
PRIMARY KEY (nonce),
|
||||||
|
KEY idx_created (created_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS schedule_backups (
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',
|
||||||
|
data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (account)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS fileserver_status (
|
||||||
|
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||||
|
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
|
||||||
|
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
|
||||||
|
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||||
|
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||||
|
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
|
||||||
|
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
|
||||||
|
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
|
||||||
|
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
|
||||||
|
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
|
||||||
|
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
|
||||||
|
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
|
||||||
|
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
|
||||||
|
offline_notified TINYINT(1) NOT NULL DEFAULT 0 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_host (host),
|
||||||
|
KEY idx_status (status),
|
||||||
|
KEY idx_last_seen (last_seen)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)'
|
||||||
|
""",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_fail_counts (
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,主键)',
|
||||||
|
fails INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '连续失败次数',
|
||||||
|
locked_until DATETIME NULL COMMENT '锁定截止时间(NULL=未锁定)',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (account)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录防爆破共享计数(落库,gunicorn 多 worker 通用)'
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _connect(server: bool = False) -> pymysql.connections.Connection:
|
||||||
|
"""建立 PyMySQL 连接(带连接超时,防 MySQL 挂起时无限阻塞);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,
|
||||||
|
connect_timeout=10)
|
||||||
|
|
||||||
|
|
||||||
|
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():
|
||||||
|
"""打开连接(建立失败自动重试 3 次)并在退出时 commit + close(统一收口)。
|
||||||
|
|
||||||
|
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚;仅连接建立阶段重试,
|
||||||
|
业务块内异常不重试(语义不变),避免把业务失败误当连接故障无限重放。
|
||||||
|
"""
|
||||||
|
if not config.MYSQL_HOST:
|
||||||
|
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||||
|
conn = None
|
||||||
|
last_exc = None
|
||||||
|
for _attempt in range(3):
|
||||||
|
try:
|
||||||
|
conn = _connect()
|
||||||
|
break
|
||||||
|
except Exception as _exc: # noqa: BLE001 连接失败重试(对齐 AGENTS.md 最大重试 3 次)
|
||||||
|
last_exc = _exc
|
||||||
|
conn = None
|
||||||
|
if _attempt < 2:
|
||||||
|
time.sleep(0.5 * (_attempt + 1))
|
||||||
|
if conn is None:
|
||||||
|
raise RuntimeError(f"MySQL 连接失败(重试 3 次后放弃):{last_exc}")
|
||||||
|
try:
|
||||||
|
yield _DbConn(conn)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
for ddl in _DDL_TABLES:
|
||||||
|
conn.execute(ddl)
|
||||||
|
for _ver in ("20260916_001", "20260919_001", _SCHEMA_VERSION):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||||
|
(_ver,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed() -> None:
|
||||||
|
"""首次启动写入默认管理员(puddy)。
|
||||||
|
|
||||||
|
不再种子 demo 普通账号(alice/bob 曾带弱口令入生产库),普通账号一律由管理员建号。
|
||||||
|
曾有的 seal_check 占位插件种子已移除(demo 遗留,会随服务重启复活,对真实插件清单造成干扰)。
|
||||||
|
"""
|
||||||
|
config.PKG_DIR.mkdir(exist_ok=True)
|
||||||
|
with _db() as conn:
|
||||||
|
# 默认管理员:仅作首次引导,密码随机生成并记入日志(不再硬编码 123456,P0 安全债)。
|
||||||
|
# 已有库不重跑本种子(INSERT IGNORE 幂等);生产环境建号后应立即改密。
|
||||||
|
for _acc, _dept in (("puddy", "IT"),):
|
||||||
|
_pwd = secrets.token_urlsafe(9) # 约 12 位随机密码
|
||||||
|
_hex, _salt = _hash_password(_pwd)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s)", (_acc, _hex, _salt, 1, _dept))
|
||||||
|
_LOGGER.warning("首次引导:初始管理员 %s 初始密码为 %s(请立即登录修改)", _acc, _pwd)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _audit(account: str, action: str, target: str = "", detail: str = "") -> None:
|
||||||
|
"""写入一条审计日志(下载/授权/管控/上报等关键操作);审计失败不阻断主流程。"""
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"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
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机钉钉官方接口封装:OAuth 扫码换身份 + 内嵌二维码(DDLogin)+ 工号解析。
|
||||||
|
|
||||||
|
与 webhost 扫码登录共用一套凭证语义:DINGTALK_APP_KEY/SECRET 即可完成
|
||||||
|
扫码换 unionid/昵称 → gettoken 企业内部 token → getbyunionid 取 userid → v2/user/get 取工号。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from controlplane.core import config
|
||||||
|
|
||||||
|
|
||||||
|
def _dingtalk_get_json(url: str, headers: dict | None = None) -> dict:
|
||||||
|
req = Request(url, method="GET")
|
||||||
|
for k, v in (headers or {}).items():
|
||||||
|
req.add_header(k, v)
|
||||||
|
try:
|
||||||
|
with urlopen(req, timeout=10) as resp:
|
||||||
|
return json.loads(resp.read().decode("utf-8"))
|
||||||
|
except OSError as _e:
|
||||||
|
raise HTTPException(502, f"钉钉接口访问失败:{getattr(_e, 'reason', _e)}")
|
||||||
|
|
||||||
|
|
||||||
|
def _dingtalk_post_json(url: str, payload: dict) -> dict:
|
||||||
|
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||||
|
req.add_header("Content-Type", "application/json")
|
||||||
|
try:
|
||||||
|
with urlopen(req, timeout=10) as resp:
|
||||||
|
return json.loads(resp.read().decode("utf-8"))
|
||||||
|
except OSError as _e:
|
||||||
|
raise HTTPException(502, f"钉钉接口访问失败:{getattr(_e, 'reason', _e)}")
|
||||||
|
|
||||||
|
|
||||||
|
# 企业内部 token 缓存(gettoken 的 access_token 有 TTL,缓存到临近过期)
|
||||||
|
_DINGTALK_TOPAPI = {"at": "", "exp": 0.0}
|
||||||
|
|
||||||
|
|
||||||
|
def _dingtalk_topapi_token() -> str:
|
||||||
|
"""获取企业内部应用 access_token(取工号链路用)。复用 DINGTALK_APP_KEY/SECRET。"""
|
||||||
|
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||||
|
return ""
|
||||||
|
now = time.time()
|
||||||
|
if _DINGTALK_TOPAPI["at"] and _DINGTALK_TOPAPI["exp"] > now + 60:
|
||||||
|
return _DINGTALK_TOPAPI["at"]
|
||||||
|
try:
|
||||||
|
info = _dingtalk_get_json(
|
||||||
|
"https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s"
|
||||||
|
% (config.DINGTALK_APP_KEY, config.DINGTALK_APP_SECRET))
|
||||||
|
at = info.get("access_token", "")
|
||||||
|
if not at:
|
||||||
|
return ""
|
||||||
|
_DINGTALK_TOPAPI["at"] = at
|
||||||
|
_DINGTALK_TOPAPI["exp"] = now + int(info.get("expires_in", 7200))
|
||||||
|
return at
|
||||||
|
except Exception: # noqa: BLE001 取企业内部 token 失败不阻断扫码登录
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _dingtalk_userinfo(auth_code: str) -> dict:
|
||||||
|
"""用钉钉扫码回调的 authCode 换取当前钉钉用户工号/姓名/unionid。"""
|
||||||
|
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||||
|
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||||
|
# Step1: authCode -> accessToken -> unionid + nick
|
||||||
|
tok = _dingtalk_post_json(
|
||||||
|
"https://api.dingtalk.com/v1.0/oauth2/userAccessToken",
|
||||||
|
{"clientId": config.DINGTALK_APP_KEY, "clientSecret": config.DINGTALK_APP_SECRET,
|
||||||
|
"code": auth_code, "grantType": "authorization_code"})
|
||||||
|
at = tok.get("accessToken")
|
||||||
|
if not at:
|
||||||
|
raise HTTPException(401, "钉钉授权码无效或已过期,请重新扫码")
|
||||||
|
me = _dingtalk_get_json(
|
||||||
|
"https://api.dingtalk.com/v1.0/contact/users/me",
|
||||||
|
{"x-acs-dingtalk-access-token": at})
|
||||||
|
unionid = me.get("unionId") or me.get("unionid") or ""
|
||||||
|
nickname = me.get("nick") or ""
|
||||||
|
account = me.get("jobNumber") or me.get("userId") or unionid
|
||||||
|
# Step2/3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
|
||||||
|
top_at = _dingtalk_topapi_token()
|
||||||
|
if top_at and unionid:
|
||||||
|
try:
|
||||||
|
byunion = _dingtalk_post_json(
|
||||||
|
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % top_at,
|
||||||
|
{"unionid": unionid})
|
||||||
|
ures = byunion.get("result") or {}
|
||||||
|
userid = ures.get("userid") or ures.get("userId") or ""
|
||||||
|
if userid:
|
||||||
|
ud = _dingtalk_post_json(
|
||||||
|
"https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s" % top_at,
|
||||||
|
{"userid": userid})
|
||||||
|
res = ud.get("result") or {}
|
||||||
|
job = res.get("job_number") or res.get("jobNumber") or ""
|
||||||
|
nickname = nickname or res.get("name") or ""
|
||||||
|
account = job or userid or account
|
||||||
|
except Exception: # noqa: BLE001 取工号失败不阻断登录,回退已得字段
|
||||||
|
pass
|
||||||
|
return {"account": account, "nickname": nickname, "unionid": unionid}
|
||||||
|
|
||||||
|
|
||||||
|
def _dingtalk_sns_userinfo(login_tmp_code: str) -> dict:
|
||||||
|
"""内嵌二维码扫码(钉钉 DDLogin):loginTmpCode → sns unionid/nick → 企业内部取工号。
|
||||||
|
|
||||||
|
与 _dingtalk_userinfo 的区别仅在于换码入口:OAuth 用 userAccessToken(code),
|
||||||
|
内嵌二维码用 sns/gettoken + sns/getuserinfo_bycode(loginTmpCode)。取工号链路共用。
|
||||||
|
"""
|
||||||
|
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||||
|
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||||
|
# Step1: loginTmpCode -> sns access_token
|
||||||
|
tok = _dingtalk_get_json(
|
||||||
|
"https://oapi.dingtalk.com/sns/gettoken?access_key=%s&access_secret=%s"
|
||||||
|
% (config.DINGTALK_APP_KEY, config.DINGTALK_APP_SECRET))
|
||||||
|
at = tok.get("access_token")
|
||||||
|
if not at:
|
||||||
|
raise HTTPException(401, "钉钉扫码码无效或已过期,请重新扫码")
|
||||||
|
# Step2: sns access_token -> unionid + nick
|
||||||
|
info = _dingtalk_post_json(
|
||||||
|
"https://oapi.dingtalk.com/sns/getuserinfo_bycode?access_token=%s" % at,
|
||||||
|
{"tmp_auth_code": login_tmp_code})
|
||||||
|
ui = info.get("user_info") or info.get("userInfo") or info
|
||||||
|
unionid = ui.get("unionid") or ui.get("unionId") or ""
|
||||||
|
nickname = ui.get("nick") or ""
|
||||||
|
# Step3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
|
||||||
|
account = unionid
|
||||||
|
top_at = _dingtalk_topapi_token()
|
||||||
|
if top_at and unionid:
|
||||||
|
try:
|
||||||
|
byunion = _dingtalk_post_json(
|
||||||
|
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % top_at,
|
||||||
|
{"unionid": unionid})
|
||||||
|
ures = byunion.get("result") or {}
|
||||||
|
userid = ures.get("userid") or ures.get("userId") or ""
|
||||||
|
if userid:
|
||||||
|
ud = _dingtalk_post_json(
|
||||||
|
"https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s" % top_at,
|
||||||
|
{"userid": userid})
|
||||||
|
res = ud.get("result") or {}
|
||||||
|
job = res.get("job_number") or res.get("jobNumber") or ""
|
||||||
|
account = job or userid or account
|
||||||
|
except Exception: # noqa: BLE001 取工号失败不阻断,回退已得字段
|
||||||
|
pass
|
||||||
|
return {"account": account, "nickname": nickname, "unionid": unionid}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机后台监控:内网文件服务器心跳超时判离线 → 钉钉告警管理员。
|
||||||
|
|
||||||
|
- 文件服务器周期主动上报心跳(/api/fileserver/heartbeat,默认 60s 一次,落库 last_seen);
|
||||||
|
- 本模块后台线程按 FILESERVER_MONITOR_INTERVAL 扫描「在线且未告警」的记录,
|
||||||
|
对 last_seen 超过 FILESERVER_HEARTBEAT_TIMEOUT 的判定离线并推送钉钉;
|
||||||
|
- 离线转换用「带条件的原子 UPDATE」认领(status=1 且 offline_notified=0 且 last_seen 超时),
|
||||||
|
gunicorn 多 worker 并发下仅一个 worker 认领成功,避免重复告警;
|
||||||
|
- 恢复上线由心跳接口处理:收到心跳即翻转在线并清除告警标记,无需本线程干预。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from controlplane.core import config
|
||||||
|
from controlplane.core.db import _db, _now
|
||||||
|
from controlplane.core.notify import notify_fileserver_down
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_once() -> None:
|
||||||
|
"""扫描一次:将心跳超时的在线文件服务器翻转为离线并告警(幂等 / 并发安全)。"""
|
||||||
|
if not config.MYSQL_HOST:
|
||||||
|
return
|
||||||
|
cutoff = (datetime.now() - timedelta(seconds=config.FILESERVER_HEARTBEAT_TIMEOUT)) \
|
||||||
|
.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
with _db() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT host, hostname, ip, last_seen FROM fileserver_status "
|
||||||
|
"WHERE status = 1 AND offline_notified = 0").fetchall()
|
||||||
|
for r in rows:
|
||||||
|
host = r["host"]
|
||||||
|
try:
|
||||||
|
with _db() as conn:
|
||||||
|
cur = conn.execute(
|
||||||
|
"UPDATE fileserver_status SET status = 0, offline_notified = 1, "
|
||||||
|
"last_status_change = %s "
|
||||||
|
"WHERE host = %s AND status = 1 AND offline_notified = 0 AND last_seen < %s",
|
||||||
|
(_now(), host, cutoff))
|
||||||
|
conn.commit()
|
||||||
|
claimed = cur.rowcount > 0
|
||||||
|
except Exception: # noqa: BLE001 单条认领失败不影响其余扫描
|
||||||
|
log.exception("文件服务器离线认领失败(host=%s)", host)
|
||||||
|
continue
|
||||||
|
if not claimed:
|
||||||
|
continue # 已被其它 worker 认领,或刚恢复心跳
|
||||||
|
log.warning("检测到文件服务器离线:%s(最后心跳 %s)", host, r["last_seen"])
|
||||||
|
notify_fileserver_down(host, r["hostname"] or "", r["ip"] or "",
|
||||||
|
str(r["last_seen"] or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _monitor_loop() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
_scan_once()
|
||||||
|
except Exception: # noqa: BLE001 监控异常不退出线程,下轮重试
|
||||||
|
log.exception("文件服务器监控扫描异常")
|
||||||
|
time.sleep(max(5, config.FILESERVER_MONITOR_INTERVAL))
|
||||||
|
|
||||||
|
|
||||||
|
def start_fileserver_monitor() -> None:
|
||||||
|
"""启动文件服务器离线监控线程(daemon,随进程退出)。"""
|
||||||
|
threading.Thread(target=_monitor_loop, daemon=True,
|
||||||
|
name="fileserver-monitor").start()
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
|
||||||
|
|
||||||
|
后台线程发送,失败仅记日志不阻断业务。
|
||||||
|
|
||||||
|
配置项(controlplane/.env):
|
||||||
|
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
|
||||||
|
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
|
||||||
|
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
|
||||||
|
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
from controlplane.core import config
|
||||||
|
from controlplane.core.dingtalk import _dingtalk_topapi_token
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
|
||||||
|
_SIGN_NAME = "37du 自动化平台"
|
||||||
|
_STATUS_COLORS = {
|
||||||
|
"info": "#0077ff", # 蓝色
|
||||||
|
"success": "#00b300", # 绿色
|
||||||
|
"warning": "#ff9900", # 橙色
|
||||||
|
"error": "#ff0000", # 红色
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _footer() -> str:
|
||||||
|
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||||
|
|
||||||
|
|
||||||
|
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
|
||||||
|
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||||
|
req.add_header("Content-Type", "application/json")
|
||||||
|
for k, v in (headers or {}).items():
|
||||||
|
req.add_header(k, v)
|
||||||
|
with urlopen(req, timeout=10) as resp:
|
||||||
|
return json.loads(resp.read().decode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
|
||||||
|
def _userid_by_unionid(at: str, unionid: str) -> str:
|
||||||
|
"""unionid → userid(精确,无重名歧义)。"""
|
||||||
|
try:
|
||||||
|
body = _post_json(
|
||||||
|
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
|
||||||
|
{"unionid": unionid})
|
||||||
|
return ((body.get("result") or {}).get("userid")) or ""
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _userid_by_name(at: str, name: str) -> str:
|
||||||
|
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
|
||||||
|
try:
|
||||||
|
body = _post_json(
|
||||||
|
"https://api.dingtalk.com/v1.0/contact/users/search",
|
||||||
|
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
|
||||||
|
headers={"x-acs-dingtalk-access-token": at})
|
||||||
|
lst = body.get("list") or []
|
||||||
|
return str(lst[0]) if lst else ""
|
||||||
|
except Exception as e: # noqa: BLE001 查询失败不阻断业务
|
||||||
|
log.warning("钉钉搜索用户失败(%s):%s", name, e)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
|
||||||
|
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
|
||||||
|
status: str = "info") -> bool:
|
||||||
|
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
|
||||||
|
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
|
||||||
|
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||||
|
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||||
|
text += content.strip() + "\n"
|
||||||
|
text += f"\n\n---\n\n{_footer()}"
|
||||||
|
try:
|
||||||
|
body = _post_json(
|
||||||
|
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
|
||||||
|
{"agent_id": agent_id, "userid_list": userid,
|
||||||
|
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
|
||||||
|
if body.get("errcode") != 0:
|
||||||
|
log.warning("钉钉工作通知被拒: %s", body)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||||
|
log.warning("钉钉工作通知异常: %s", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
|
||||||
|
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
|
||||||
|
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||||
|
if not agent_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
at = _dingtalk_topapi_token()
|
||||||
|
if not at:
|
||||||
|
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
|
||||||
|
return
|
||||||
|
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
|
||||||
|
uid = _userid_by_unionid(at, unionid) if unionid else ""
|
||||||
|
if not uid and nickname:
|
||||||
|
uid = _userid_by_name(at, nickname)
|
||||||
|
if uid:
|
||||||
|
_send_work_to(
|
||||||
|
at, agent_id, uid, "账号开通通知",
|
||||||
|
f"**🔹 {nickname or account}‑账号开通**\n\n"
|
||||||
|
f"> 账号:{account}\n\n"
|
||||||
|
f"> 初始密码:{password}\n\n"
|
||||||
|
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
|
||||||
|
status="success")
|
||||||
|
else:
|
||||||
|
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
|
||||||
|
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
|
||||||
|
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
|
||||||
|
admin_uid = _userid_by_name(at, admin_name)
|
||||||
|
if admin_uid:
|
||||||
|
_send_work_to(
|
||||||
|
at, agent_id, admin_uid, "新账号待开通权限",
|
||||||
|
f"> 账号:{account}\n\n"
|
||||||
|
f"> 姓名:{nickname or '—'}\n\n"
|
||||||
|
f"> 来源:{source}\n\n"
|
||||||
|
"> 备注:请到管理台为该账号开通插件权限",
|
||||||
|
status="warning")
|
||||||
|
else:
|
||||||
|
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
|
||||||
|
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||||
|
log.warning("钉钉建号通知异常: %s", e)
|
||||||
|
|
||||||
|
|
||||||
|
def notify_account_created(account: str, nickname: str = "", password: str = "",
|
||||||
|
unionid: str = "", source: str = "管理台") -> None:
|
||||||
|
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
|
||||||
|
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
|
||||||
|
daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
|
||||||
|
def _signed_webhook_url() -> str:
|
||||||
|
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
|
||||||
|
if not url:
|
||||||
|
return ""
|
||||||
|
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
|
||||||
|
if secret:
|
||||||
|
ts = str(int(time.time() * 1000))
|
||||||
|
sign = base64.b64encode(hmac.new(
|
||||||
|
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
|
||||||
|
hashlib.sha256).digest()).decode("utf-8")
|
||||||
|
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def _send_robot(title: str, text: str) -> None:
|
||||||
|
url = _signed_webhook_url()
|
||||||
|
if not url:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
|
||||||
|
if body.get("errcode") != 0:
|
||||||
|
log.warning("钉钉群通知被拒: %s", body)
|
||||||
|
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||||
|
log.warning("钉钉群通知异常: %s", e)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
|
||||||
|
def _admin_names() -> list[str]:
|
||||||
|
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
|
||||||
|
try:
|
||||||
|
from controlplane.core.db import _db
|
||||||
|
with _db() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
|
||||||
|
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
|
||||||
|
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
|
||||||
|
log.warning("取管理员名单失败,离线告警回退群机器人")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
|
||||||
|
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
|
||||||
|
title = "内网文件服务器下线告警"
|
||||||
|
content = (
|
||||||
|
f"> 服务:{hostname or '—'}\n\n"
|
||||||
|
f"> 地址:{host}\n\n"
|
||||||
|
f"> IP:{ip or '—'}\n\n"
|
||||||
|
f"> 最后心跳:{last_seen or '—'}\n\n"
|
||||||
|
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
|
||||||
|
"服务恢复后将自动解除告警")
|
||||||
|
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||||
|
at = _dingtalk_topapi_token() if agent_id else ""
|
||||||
|
sent_any = False
|
||||||
|
if at:
|
||||||
|
for name in _admin_names():
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
uid = _userid_by_name(at, name)
|
||||||
|
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
|
||||||
|
sent_any = True
|
||||||
|
if not sent_any:
|
||||||
|
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
|
||||||
|
if not sent_any:
|
||||||
|
_send_robot(title, content)
|
||||||
|
|
||||||
|
|
||||||
|
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
|
||||||
|
last_seen: str = "") -> None:
|
||||||
|
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
|
||||||
|
threading.Thread(target=_work_fileserver_down,
|
||||||
|
args=(host, hostname, ip, last_seen), daemon=True).start()
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""统一分页规范(控制面管理端列表接口)。
|
||||||
|
|
||||||
|
约定:
|
||||||
|
- 请求参数统一:``page``(第 1 页起)、``page_size``(默认 20,上限 1000)
|
||||||
|
- 响应统一:``{"items": [...], "total": int}``
|
||||||
|
|
||||||
|
路由用法示例:
|
||||||
|
from fastapi import Query
|
||||||
|
from controlplane.core.paging import page_bounds
|
||||||
|
|
||||||
|
@router.get("/api/admin/xxx")
|
||||||
|
def admin_xxx(page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, ge=1, le=1000), ...):
|
||||||
|
_require_admin(...)
|
||||||
|
limit, offset = page_bounds(page, page_size)
|
||||||
|
with _db() as conn:
|
||||||
|
total = count_rows(conn, "SELECT COUNT(*) AS c FROM t")
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT ... ORDER BY id DESC LIMIT %s OFFSET %s", (limit, offset))]
|
||||||
|
return {"items": rows, "total": total}
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def page_bounds(page: int, page_size: int) -> tuple[int, int]:
|
||||||
|
"""page(1 起) 与 page_size -> (limit, offset),带防抖(page>=1,page_size 1..1000)。"""
|
||||||
|
page = max(1, int(page))
|
||||||
|
page_size = min(max(1, int(page_size)), 1000)
|
||||||
|
return page_size, (page - 1) * page_size
|
||||||
|
|
||||||
|
|
||||||
|
def count_rows(conn, sql: str, args=()) -> int:
|
||||||
|
"""统一取总数:sql 为 ``SELECT COUNT(*) AS c ...``,返回 int。"""
|
||||||
|
return int(conn.execute(sql, args).fetchone()["c"])
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机插件包工具:ZIP 完整性校验、manifest 解析、版本保留裁剪、版本比较。
|
||||||
|
|
||||||
|
纯计算/解析逻辑,不触碰文件系统与 DB(文件落盘/删除由路由层按返回结果执行)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
# 插件包约束:大小上限 / 必含文件 / 保留版本数 / 安全文件名
|
||||||
|
_PKG_MAX_BYTES = 200 * 1024 * 1024
|
||||||
|
# webhost 执行端插件为 __init__.py 注册风格,故仅强制 plugin.json(manifest 契约);
|
||||||
|
# main.py 仅作为通用入口可选,不再必含。
|
||||||
|
_PKG_REQUIRED_FILES = ("plugin.json",)
|
||||||
|
_KEEP_VERSIONS = 3
|
||||||
|
_SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_manifest(raw: str) -> dict:
|
||||||
|
"""读取存储的插件 manifest(异常安全,回空 dict)。"""
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
d = json.loads(raw)
|
||||||
|
return d if isinstance(d, dict) else {}
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_pkg_zip(content: bytes) -> None:
|
||||||
|
"""插件包完整性校验:体积上限 + ZIP 结构 + 必含文件 + plugin.json 可解析。"""
|
||||||
|
if len(content) > _PKG_MAX_BYTES:
|
||||||
|
raise HTTPException(400, f"插件包超过大小上限({_PKG_MAX_BYTES // 1024 // 1024}MB)")
|
||||||
|
try:
|
||||||
|
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||||
|
except zipfile.BadZipFile:
|
||||||
|
raise HTTPException(400, "上传内容不是有效的 ZIP 包")
|
||||||
|
with zf:
|
||||||
|
if zf.testzip() is not None:
|
||||||
|
raise HTTPException(400, "ZIP 包校验失败(存在损坏条目)")
|
||||||
|
names = set(zf.namelist())
|
||||||
|
missing = [f for f in _PKG_REQUIRED_FILES if f not in names]
|
||||||
|
if missing:
|
||||||
|
raise HTTPException(
|
||||||
|
400, f"插件包缺少必需文件:{', '.join(missing)}(包根目录需含 plugin.json / main.py / requirements.txt)")
|
||||||
|
try:
|
||||||
|
json.loads(zf.read("plugin.json").decode("utf-8"))
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(400, "plugin.json 不是合法 JSON")
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_manifest(content: bytes) -> dict | None:
|
||||||
|
"""从插件包读取 plugin.json 并解析为 manifest(存在且合法才返回)。
|
||||||
|
|
||||||
|
作为插件契约的权威来源:元数据 + JSON-Schema 表单 + capabilities/permissions。
|
||||||
|
缺文件或解析失败返回 None,交由上层决定是否拒绝。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||||
|
with zf:
|
||||||
|
raw = zf.read("plugin.json").decode("utf-8")
|
||||||
|
data = json.loads(raw)
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return None
|
||||||
|
return data
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_versions(conn, plugin_id: str) -> list:
|
||||||
|
"""仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。"""
|
||||||
|
rows = conn.execute(
|
||||||
|
"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 = %s AND version = %s",
|
||||||
|
(plugin_id, r["version"]))
|
||||||
|
return [r["filename"] for r in stale]
|
||||||
|
|
||||||
|
|
||||||
|
def _version_key(v: str):
|
||||||
|
"""版本比较键:数字段转 (1, int),非数字段转 (0, str),保证段间可比较(1.0.0-beta 不触发 int/str 类型错误)。"""
|
||||||
|
def to_key(s):
|
||||||
|
try:
|
||||||
|
return (1, int(s))
|
||||||
|
except ValueError:
|
||||||
|
return (0, str(s).lower())
|
||||||
|
return tuple(to_key(x) for x in str(v).split("."))
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""中心机请求体模型(Pydantic),路由层统一复用。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class PluginOut(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
version: str
|
||||||
|
|
||||||
|
|
||||||
|
class RuntimeReportIn(BaseModel):
|
||||||
|
account: str = ""
|
||||||
|
device_id: str = ""
|
||||||
|
plugin_id: str = ""
|
||||||
|
version: str = ""
|
||||||
|
status: str = ""
|
||||||
|
msg: str = ""
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class CredsRegisterIn(BaseModel):
|
||||||
|
"""执行机上报 RSA 公钥(一次注册后中心机用其加密敏感凭证下发)。"""
|
||||||
|
account: str
|
||||||
|
pubkey_pem: str
|
||||||
|
|
||||||
|
|
||||||
|
class CredsSeedIn(BaseModel):
|
||||||
|
"""管理员录入/更新某执行机账号的敏感凭证明文源(集中存中心机 DB)。"""
|
||||||
|
account: str
|
||||||
|
values: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
class DingTalkIn(BaseModel):
|
||||||
|
account: str # 工号(作为统一账号)
|
||||||
|
nickname: str = ""
|
||||||
|
dingtalk_uid: str = ""
|
||||||
|
password: str = "" # 可选:覆盖默认初始密码(一般留空走 DINGTALK_DEFAULT_PASSWORD)
|
||||||
|
|
||||||
|
|
||||||
|
class SnsIn(BaseModel):
|
||||||
|
code: str # 内嵌二维码扫码后前端拿到的 loginTmpCode
|
||||||
|
|
||||||
|
|
||||||
|
class AuthExchangeIn(BaseModel):
|
||||||
|
code: str
|
||||||
|
|
||||||
|
|
||||||
|
class PwdIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
old_password: str
|
||||||
|
new_password: str
|
||||||
|
|
||||||
|
|
||||||
|
class AccountCreateIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
password: str
|
||||||
|
dept: str = ""
|
||||||
|
nickname: str = ""
|
||||||
|
is_admin: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class AccountUpdateIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
dept: str | None = None
|
||||||
|
nickname: str | None = None
|
||||||
|
is_admin: bool | None = None
|
||||||
|
status: bool | None = None # 是否启用(True=启用,False=停用)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountResetIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
new_password: str
|
||||||
|
|
||||||
|
|
||||||
|
class AccountDelIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
|
||||||
|
|
||||||
|
class GrantIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
plugin_id: str
|
||||||
|
granted: bool
|
||||||
|
can_download: bool = True # 可选:插件级下载授权(默认授予)
|
||||||
|
can_run: bool = True # 可选:插件级运行授权(默认授予)
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformGrantIn(BaseModel):
|
||||||
|
account: str
|
||||||
|
platform_id: str
|
||||||
|
granted: bool
|
||||||
|
|
||||||
|
|
||||||
|
class PluginDelIn(BaseModel):
|
||||||
|
plugin_id: str
|
||||||
|
|
||||||
|
|
||||||
|
class PluginPatchIn(BaseModel):
|
||||||
|
name: str = ""
|
||||||
|
description: str = ""
|
||||||
|
category: str = ""
|
||||||
|
icon: str = ""
|
||||||
|
status: str = "" # 空=不改;published / disabled / revoked
|
||||||
|
force_min_version: str = "" # 与 deadline 成对生效;二者齐全=开启,否则看 clear_force
|
||||||
|
force_deadline: str = "" # ISO 时间串
|
||||||
|
clear_force: bool = False # True = 清除强制更新配置
|
||||||
Binary file not shown.
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>37du 插件管理平台</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+1602
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "37du-controlplane-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
|
"echarts": "^6.1.0",
|
||||||
|
"element-plus": "^2.14.5",
|
||||||
|
"vue": "^3.5.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
|
"vite": "^6.0.3"
|
||||||
|
},
|
||||||
|
"allowScripts": {
|
||||||
|
"esbuild@0.25.12": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
<template>
|
||||||
|
<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>
|
||||||
|
<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 menu" :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" :force="pwdForce" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document, Files } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message } from 'element-plus'
|
||||||
|
import LoginPage from './components/LoginPage.vue'
|
||||||
|
import PasswordDialog from './components/PasswordDialog.vue'
|
||||||
|
import OverviewView from './views/OverviewView.vue'
|
||||||
|
import PluginManageView from './views/PluginManageView.vue'
|
||||||
|
import AccountManageView from './views/AccountManageView.vue'
|
||||||
|
import GrantManageView from './views/GrantManageView.vue'
|
||||||
|
import StatsView from './views/StatsView.vue'
|
||||||
|
import AuditView from './views/AuditView.vue'
|
||||||
|
import CredsManageView from './views/CredsManageView.vue'
|
||||||
|
import FileSourceManageView from './views/FileSourceManageView.vue'
|
||||||
|
import { store, clearSession } from './store'
|
||||||
|
import { adminMe } from './api'
|
||||||
|
|
||||||
|
const menuOptions = [
|
||||||
|
{ 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: 'creds', icon: Lock, admin: true },
|
||||||
|
{ label: '大文件源', key: 'files', icon: Files, admin: true },
|
||||||
|
{ label: '审计报表', key: 'audit', icon: Document },
|
||||||
|
]
|
||||||
|
const menu = computed(() => menuOptions.filter(m => !m.admin || store.isAdmin))
|
||||||
|
|
||||||
|
// 轻量 hash 路由:静态站刷新安全,零后端改动
|
||||||
|
const KEY = {
|
||||||
|
'#/overview': 'overview',
|
||||||
|
'#/stats': 'stats',
|
||||||
|
'#/plugins': 'plugins',
|
||||||
|
'#/accounts': 'accounts',
|
||||||
|
'#/grants': 'grants',
|
||||||
|
'#/creds': 'creds',
|
||||||
|
'#/files': 'files',
|
||||||
|
'#/audit': 'audit',
|
||||||
|
}
|
||||||
|
const VIEWS = {
|
||||||
|
'#/overview': OverviewView,
|
||||||
|
'#/stats': StatsView,
|
||||||
|
'#/plugins': PluginManageView,
|
||||||
|
'#/accounts': AccountManageView,
|
||||||
|
'#/grants': GrantManageView,
|
||||||
|
'#/creds': CredsManageView,
|
||||||
|
'#/files': FileSourceManageView,
|
||||||
|
'#/audit': AuditView,
|
||||||
|
}
|
||||||
|
const route = ref(VIEWS[location.hash] ? location.hash : '#/overview')
|
||||||
|
window.addEventListener('hashchange', () => {
|
||||||
|
if (VIEWS[location.hash]) route.value = location.hash
|
||||||
|
})
|
||||||
|
const viewComp = computed(() => VIEWS[route.value] || OverviewView)
|
||||||
|
const activeKey = computed(() => KEY[route.value] || 'overview')
|
||||||
|
|
||||||
|
function onMenu(key) {
|
||||||
|
const h = '#/' + key
|
||||||
|
location.hash = h
|
||||||
|
route.value = h
|
||||||
|
}
|
||||||
|
|
||||||
|
const initial = computed(() => (store.nickname || store.current || '')[0]?.toUpperCase() || '?')
|
||||||
|
|
||||||
|
const pwdOpen = ref(false)
|
||||||
|
const pwdForce = ref(false)
|
||||||
|
function onCommand(cmd) {
|
||||||
|
if (cmd === 'pwd') { pwdForce.value = false; pwdOpen.value = true }
|
||||||
|
else if (cmd === 'logout') {
|
||||||
|
clearSession()
|
||||||
|
message.success('已退出登录')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onLogin(r) {
|
||||||
|
route.value = '#/overview'
|
||||||
|
location.hash = '#/overview'
|
||||||
|
// 服务端强制:仍持初始密码(must_change_pwd=1)时拒绝一切管理操作,必须先改密
|
||||||
|
if (r && r.must_change_pwd) {
|
||||||
|
pwdForce.value = true
|
||||||
|
pwdOpen.value = true
|
||||||
|
message.warning('首次登录请先修改初始密码,修改成功后才能使用管理功能')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
// 已本地标记登录时,校验登录票据仍有效且为管理员(票据过期/权限变更后回登录页)
|
||||||
|
if (!store.current) return
|
||||||
|
try {
|
||||||
|
const me = await adminMe()
|
||||||
|
if (!me.account || !me.is_admin) clearSession()
|
||||||
|
else {
|
||||||
|
store.isAdmin = true; store.nickname = me.nickname || ''
|
||||||
|
// 刷新后仍需先改初始密码(服务端拒绝一切管理操作)
|
||||||
|
if (me.must_change_pwd) {
|
||||||
|
pwdForce.value = true
|
||||||
|
pwdOpen.value = true
|
||||||
|
message.warning('请先修改初始密码,修改成功后才能使用管理功能')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) { /* 后端 down:保持本地态 */ }
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<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 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(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, var(--cp-blue) 0%, var(--cp-teal) 140%);
|
||||||
|
color: #fff; font-size: 14px; font-weight: 800; letter-spacing: .5px;
|
||||||
|
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, .3); }
|
||||||
|
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||||
|
.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 12px; border-radius: 12px; border: 1px solid transparent;
|
||||||
|
transition: background .18s, border-color .18s;
|
||||||
|
}
|
||||||
|
.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, var(--cp-blue), var(--cp-teal));
|
||||||
|
color: #fff; font-size: 13px; font-weight: 700;
|
||||||
|
}
|
||||||
|
.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: 12px; padding: 14px 18px 22px; min-height: 0; }
|
||||||
|
.aside {
|
||||||
|
width: 192px; flex-shrink: 0;
|
||||||
|
display: flex; flex-direction: column;
|
||||||
|
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; }
|
||||||
|
.main { flex: 1; min-width: 0; overflow: auto; padding: 0 2px 8px; }
|
||||||
|
|
||||||
|
/* 页面切换过渡:轻微上浮淡入 */
|
||||||
|
.view-fade-enter-active { transition: opacity .22s ease, transform .22s ease; }
|
||||||
|
.view-fade-leave-active { transition: opacity .12s ease; }
|
||||||
|
.view-fade-enter-from { opacity: 0; transform: translateY(8px); }
|
||||||
|
.view-fade-leave-to { opacity: 0; }
|
||||||
|
|
||||||
|
/* ---------- 侧栏菜单:纸面导航 ---------- */
|
||||||
|
.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>
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
// 与 FastAPI 后端交互,控制面前端直连 /api/*
|
||||||
|
import { store } from './store.js'
|
||||||
|
|
||||||
|
async function req(url, opts) {
|
||||||
|
const res = await fetch(url, opts)
|
||||||
|
if (!res.ok) {
|
||||||
|
let msg = `HTTP ${res.status}`
|
||||||
|
try {
|
||||||
|
const detail = (await res.json()).detail
|
||||||
|
// FastAPI 422 的 detail 是 [{loc,msg,type},…] 数组;普通错误是字符串/含 msg 的对象
|
||||||
|
if (typeof detail === 'string') msg = detail
|
||||||
|
else if (Array.isArray(detail)) {
|
||||||
|
msg = detail.map((d) => {
|
||||||
|
const where = Array.isArray(d.loc) ? d.loc.filter((p) => p !== 'body').join('.') : ''
|
||||||
|
return where ? `${where}: ${d.msg}` : (d.msg || JSON.stringify(d))
|
||||||
|
}).join(';')
|
||||||
|
} else if (detail && typeof detail === 'object') msg = detail.msg || JSON.stringify(detail)
|
||||||
|
} catch (_) { /* 非 JSON 响应,保留 HTTP 状态码提示 */ }
|
||||||
|
throw new Error(msg)
|
||||||
|
}
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 管理接口无状态鉴权:携带登录后签发的签名票据(X-Admin-Token),后端验票解得当前账号
|
||||||
|
function adminHeaders(extra = {}) {
|
||||||
|
return { 'X-Admin-Token': store.token || '', ...extra }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 统一分页规范:所有列表接口 page(page≥1) + page_size,返回 {items, total}
|
||||||
|
function pagedQuery(params = {}) {
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
if (params.page) qs.set('page', params.page)
|
||||||
|
if (params.page_size) qs.set('page_size', params.page_size)
|
||||||
|
return qs.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminLogin(account, password) {
|
||||||
|
return req('/api/admin/auth', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ account, password })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminPassword(body) {
|
||||||
|
return req('/api/admin/password', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminMe() {
|
||||||
|
return req('/api/admin/me', { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminOverview() {
|
||||||
|
return req('/api/admin/overview', { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminGrantData() {
|
||||||
|
return req('/api/admin/grant_data', { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminAccountGrants(account) {
|
||||||
|
return req('/api/admin/account_grants?account=' + encodeURIComponent(account), { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminPlatforms() {
|
||||||
|
return req('/api/admin/platforms', { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminGrant(body) {
|
||||||
|
return req('/api/admin/account_plugins', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminPlatformGrant(body) {
|
||||||
|
return req('/api/admin/account_platforms', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminAccounts(page = 1, pageSize = 20, q = '') {
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
qs.set('page', page); qs.set('page_size', pageSize)
|
||||||
|
if (q) qs.set('q', q)
|
||||||
|
return req('/api/admin/accounts?' + qs.toString(), { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminPlugins(page = 1, pageSize = 20, q = '') {
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
qs.set('page', page); qs.set('page_size', pageSize)
|
||||||
|
if (q) qs.set('q', q)
|
||||||
|
return req('/api/admin/plugins?' + qs.toString(), { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminAccountCreate(body) {
|
||||||
|
return req('/api/admin/account', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminAccountUpdate(body) {
|
||||||
|
return req('/api/admin/account/update', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminAccountReset(body) {
|
||||||
|
return req('/api/admin/account/reset_pwd', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminAccountDelete(body) {
|
||||||
|
return req('/api/admin/account/delete', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminAvatarUpload(account, file) {
|
||||||
|
const fd = new FormData()
|
||||||
|
fd.append('file', file)
|
||||||
|
const qs = new URLSearchParams({ account })
|
||||||
|
return req('/api/admin/avatar?' + qs.toString(), { method: 'POST', headers: adminHeaders(), body: fd })
|
||||||
|
}
|
||||||
|
export async function adminPluginDelete(body) {
|
||||||
|
return req('/api/admin/plugin/delete', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminPluginPatch(pluginId, body) {
|
||||||
|
const qs = new URLSearchParams({ plugin_id: pluginId })
|
||||||
|
return req('/api/admin/plugin/patch?' + qs.toString(), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminAudit(page = 1, pageSize = 20, filters = {}) {
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
qs.set('page', page); qs.set('page_size', pageSize)
|
||||||
|
if (filters.action) qs.set('action', filters.action)
|
||||||
|
if (filters.q) qs.set('q', filters.q)
|
||||||
|
return req('/api/admin/audit?' + qs.toString(), { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminReports(page = 1, pageSize = 20, filters = {}) {
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
qs.set('page', page); qs.set('page_size', pageSize)
|
||||||
|
if (filters.status) qs.set('status', filters.status)
|
||||||
|
if (filters.q) qs.set('q', filters.q)
|
||||||
|
return req('/api/admin/reports?' + qs.toString(), { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminStats() {
|
||||||
|
return req('/api/admin/stats', { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminCredsList(page = 1, pageSize = 20) {
|
||||||
|
return req('/api/admin/creds/manage?' + pagedQuery({ page, page_size: pageSize }), { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminCredsSeed(body) {
|
||||||
|
return req('/api/admin/creds/seed', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminFileSources(category = '', page = 1, pageSize = 20) {
|
||||||
|
const parts = []
|
||||||
|
if (category) parts.push('category=' + encodeURIComponent(category))
|
||||||
|
const pq = pagedQuery({ page, page_size: pageSize })
|
||||||
|
if (pq) parts.push(pq)
|
||||||
|
const qs = parts.length ? '?' + parts.join('&') : ''
|
||||||
|
return req('/api/admin/file-sources' + qs, { headers: adminHeaders() })
|
||||||
|
}
|
||||||
|
export async function adminFileSourceCreate(body) {
|
||||||
|
return req('/api/admin/file-sources', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminFileSourcePatch(id, body) {
|
||||||
|
return req(`/api/admin/file-sources/${id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminFileSourceDelete(id) {
|
||||||
|
return req(`/api/admin/file-sources/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: adminHeaders({ 'Content-Type': 'application/json' })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export async function adminUpload(pluginId, name, version, file) {
|
||||||
|
const fd = new FormData()
|
||||||
|
fd.append('upload', file)
|
||||||
|
const qs = new URLSearchParams({ plugin_id: pluginId, name, version })
|
||||||
|
return req('/api/admin/pkg?' + qs.toString(), { method: 'POST', headers: adminHeaders(), body: fd })
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
<template>
|
||||||
|
<div class="login">
|
||||||
|
<div class="card cp-rise">
|
||||||
|
<div class="brand">
|
||||||
|
<span class="logo">37</span>
|
||||||
|
<div class="brand-meta">
|
||||||
|
<h1>{{ appName }}</h1>
|
||||||
|
<p>中心机统一账户登录</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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 ? '登录中…' : '登 录' }}
|
||||||
|
</el-button>
|
||||||
|
</el-form>
|
||||||
|
|
||||||
|
<div class="foot">内网管理面 · 请使用管理员账号登录</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<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'
|
||||||
|
|
||||||
|
const props = defineProps({ appName: { type: String, default: '37du 自动化工作台' } })
|
||||||
|
const emit = defineEmits(['ok'])
|
||||||
|
|
||||||
|
const account = ref('')
|
||||||
|
const password = ref('')
|
||||||
|
const busy = ref(false)
|
||||||
|
|
||||||
|
async function doLogin() {
|
||||||
|
if (busy.value) return
|
||||||
|
const acct = account.value.trim()
|
||||||
|
if (!acct || !password.value) { message.warning('请输入账号与密码'); return }
|
||||||
|
busy.value = true
|
||||||
|
try {
|
||||||
|
const r = await adminLogin(acct, password.value)
|
||||||
|
if (!r.ok) throw new Error('登录失败')
|
||||||
|
if (!r.is_admin) { throw new Error('该账号无管理权限') }
|
||||||
|
store.current = acct
|
||||||
|
store.token = r.token || ''
|
||||||
|
store.isAdmin = true
|
||||||
|
store.nickname = r.nickname || ''
|
||||||
|
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) { }
|
||||||
|
message.success(`欢迎,${store.nickname || acct}`)
|
||||||
|
emit('ok', r)
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e.message || String(e))
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.login {
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 24px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
width: 404px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
inset: 2px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, .3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-meta h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 800;
|
||||||
|
color: var(--cp-ink-1);
|
||||||
|
letter-spacing: .2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<template>
|
||||||
|
<div class="pager-bar" v-if="total > 0">
|
||||||
|
<el-pagination background layout="total, sizes, prev, pager, next"
|
||||||
|
:total="total" :current-page="page" :page-size="pageSize"
|
||||||
|
:page-sizes="[10, 20, 50, 100]"
|
||||||
|
@current-change="p => emit('change', p, pageSize)"
|
||||||
|
@size-change="s => emit('change', 1, s)" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
// 统一分页条:配合后端 page/page_size 分页接口({items,total})。
|
||||||
|
// 用法:<PagerBar :total="total" :page="page" :page-size="pageSize"
|
||||||
|
// @change="(p, s) => { page = p; pageSize = s; load() }" />
|
||||||
|
defineProps({ total: { type: Number, default: 0 }, page: { type: Number, default: 1 }, pageSize: { type: Number, default: 20 } })
|
||||||
|
const emit = defineEmits(['change'])
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.pager-bar { display: flex; justify-content: flex-end; padding: 12px 4px 2px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<template>
|
||||||
|
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close
|
||||||
|
:close-on-click-modal="!force" :close-on-press-escape="!force" :show-close="!force"
|
||||||
|
@closed="onClosed">
|
||||||
|
<el-alert v-if="force" type="warning" :closable="false" class="force-tip" show-icon>
|
||||||
|
首次登录请先修改初始密码,修改成功后才能使用管理功能。
|
||||||
|
</el-alert>
|
||||||
|
<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="至少 8 位,不与原密码相同" 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>
|
||||||
|
<div class="modal-foot">
|
||||||
|
<el-button v-if="!force" @click="visible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="busy" @click="submit">保存</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</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'
|
||||||
|
|
||||||
|
// force=true 强制改密模式(首次登录 must_change_pwd):不可取消/关闭,改密成功前不允许进入管理面
|
||||||
|
const props = defineProps({ force: { type: Boolean, default: false } })
|
||||||
|
const visible = defineModel({ type: Boolean, default: false })
|
||||||
|
const formRef = ref()
|
||||||
|
const busy = ref(false)
|
||||||
|
const changed = ref(false)
|
||||||
|
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||||
|
|
||||||
|
const rules = {
|
||||||
|
oldPwd: { required: true, message: '请输入原密码' },
|
||||||
|
newPwd: [
|
||||||
|
{ required: true, message: '请输入新密码' },
|
||||||
|
{ min: 8, message: '新密码至少 8 位' },
|
||||||
|
{ validator: (_r, v, cb) => (v && v === form.oldPwd ? cb(new Error('新密码不能与原密码相同')) : cb()), message: '新密码不能与原密码相同' },
|
||||||
|
],
|
||||||
|
newPwd2: [
|
||||||
|
{ required: true, message: '请再次输入新密码' },
|
||||||
|
{ validator: (_r, v, cb) => (v !== form.newPwd ? cb(new Error('两次输入的密码不一致')) : cb()), message: '两次输入的密码不一致' },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||||
|
formRef.value?.resetFields()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onClosed() {
|
||||||
|
// 强制模式下未改密成功不允许关闭:自动重新打开
|
||||||
|
if (props.force && !changed.value) visible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
try { await formRef.value.validate() } catch (_) { return }
|
||||||
|
busy.value = true
|
||||||
|
try {
|
||||||
|
await adminPassword({ account: store.current, old_password: form.oldPwd, new_password: form.newPwd })
|
||||||
|
changed.value = true
|
||||||
|
message.success('密码已修改,下次登录请使用新密码')
|
||||||
|
visible.value = false
|
||||||
|
} catch (e) {
|
||||||
|
message.error('修改失败:' + (e.message || e))
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.force-tip { margin-bottom: 14px; }
|
||||||
|
.acct-tip { margin-bottom: 16px; }
|
||||||
|
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// 统一分页列表 composable:对接后端 page/page_size → {items,total} 契约。
|
||||||
|
//
|
||||||
|
// 统一管理:items/total/page/pageSize/busy 状态 + load/onPageChange/reset 行为;
|
||||||
|
// 自动处理越界回退(删除/筛选后当前页为空时回到最后一页);
|
||||||
|
// 请求竞态控制(快速翻页/切筛选时丢弃过期响应);
|
||||||
|
// 错误统一走 onError 回调(不向上抛),各页面不再各自 try/catch。
|
||||||
|
//
|
||||||
|
// 用法:
|
||||||
|
// const { items: accounts, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } =
|
||||||
|
// usePagedList((p, s) => adminAccounts(p, s), {
|
||||||
|
// onError: e => message.error('读取失败:' + (e.message || e)),
|
||||||
|
// })
|
||||||
|
// 模板中直接使用解构出的 ref(自动解包),PagerBar 绑定 :total :page :page-size @change="onPageChange"。
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export function usePagedList(fetcher, opts = {}) {
|
||||||
|
const onError = typeof opts.onError === 'function' ? opts.onError : () => {}
|
||||||
|
const items = ref([])
|
||||||
|
const total = ref(0)
|
||||||
|
const page = ref(1)
|
||||||
|
const size = ref(opts.pageSize || 20)
|
||||||
|
const busy = ref(false)
|
||||||
|
// 响应里除 items/total 外的附加字段(如 today/failed)透传到 meta
|
||||||
|
const meta = ref({})
|
||||||
|
// 请求序号:只接受最后一次发起的响应,丢弃过期响应
|
||||||
|
let seq = 0
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const my = ++seq
|
||||||
|
busy.value = true
|
||||||
|
try {
|
||||||
|
const r = await fetcher(page.value, size.value)
|
||||||
|
if (my !== seq) return // 已过期(期间又发起了新请求)
|
||||||
|
items.value = r.items || []
|
||||||
|
total.value = r.total || 0
|
||||||
|
meta.value = r
|
||||||
|
// 越界回退:数据被删/筛选变化导致当前页为空,且总数>0 → 回到最后一页
|
||||||
|
if (!items.value.length && page.value > 1 && total.value > 0) {
|
||||||
|
const last = Math.max(1, Math.ceil(total.value / size.value))
|
||||||
|
if (last !== page.value) {
|
||||||
|
page.value = last
|
||||||
|
return load()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (my === seq) onError(e)
|
||||||
|
} finally {
|
||||||
|
if (my === seq) busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPageChange(p, s) {
|
||||||
|
if (p === page.value && s === size.value) return
|
||||||
|
page.value = p
|
||||||
|
size.value = s
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 筛选条件/外部数据变化后回到第一页重新加载
|
||||||
|
function reset() {
|
||||||
|
page.value = 1
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
|
return { items, total, page, size, busy, meta, load, onPageChange, reset }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||||
|
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件)
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
import App from './App.vue'
|
||||||
|
import './style.css'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
// 全量注册图标,模板中可直接用图标名,概览页卡片动态渲染需要
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
// 中文语言包:日期选择器等组件的月份/按钮文案默认是英文,必须显式指定 locale
|
||||||
|
app.use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { reactive, ref } from 'vue'
|
||||||
|
import { adminOverview } from './api'
|
||||||
|
|
||||||
|
export const store = reactive({
|
||||||
|
appName: '37du 插件管理平台',
|
||||||
|
isAdmin: false,
|
||||||
|
current: _get('cp_account'),
|
||||||
|
token: _get('cp_token'),
|
||||||
|
nickname: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
// 概览数据缓存:各管理页共用一份 adminOverview 结果,避免切页重复拉取
|
||||||
|
export const overview = ref(null)
|
||||||
|
export const overviewBusy = ref(false)
|
||||||
|
|
||||||
|
export async function loadOverview(force = false) {
|
||||||
|
if (overview.value && !force) return overview.value
|
||||||
|
overviewBusy.value = true
|
||||||
|
try {
|
||||||
|
overview.value = await adminOverview()
|
||||||
|
return overview.value
|
||||||
|
} finally {
|
||||||
|
overviewBusy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resetOverview() {
|
||||||
|
overview.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
function _get(key) {
|
||||||
|
try { return localStorage.getItem(key) || '' } catch (_) { return '' }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearSession() {
|
||||||
|
store.current = ''
|
||||||
|
store.token = ''
|
||||||
|
store.isAdmin = false
|
||||||
|
store.nickname = ''
|
||||||
|
resetOverview()
|
||||||
|
try { localStorage.removeItem('cp_account'); localStorage.removeItem('cp_token') } catch (_) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
/* ============================================================
|
||||||
|
37du 插件管理平台 · 全局样式(Element Plus)
|
||||||
|
设计语言:纸张 + 墨色 · 编辑部数据台
|
||||||
|
- 暖白纸感画布 + 细网格底纹
|
||||||
|
- 深墨色文字 + 钴蓝/琥珀强调色
|
||||||
|
- 数字/ID/时间用等宽字体,营造精密仪表感
|
||||||
|
============================================================ */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* ---------- 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; }
|
||||||
|
html, body, #app { height: 100%; margin: 0; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: "HarmonyOS Sans SC", "Microsoft YaHei UI", "PingFang SC", -apple-system, "Segoe UI", sans-serif;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--cp-ink);
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
background-color: var(--cp-bg);
|
||||||
|
/* 纸感画布:暖白底 + 低透明细网格 + 两侧轻微墨晕 */
|
||||||
|
background-image:
|
||||||
|
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(47, 92, 240, .16); }
|
||||||
|
|
||||||
|
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||||
|
::-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; }
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 输入类 ---------- */
|
||||||
|
.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: 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); letter-spacing: .2px; }
|
||||||
|
.block { margin-bottom: 18px; }
|
||||||
|
.dim { color: var(--cp-ink-3); }
|
||||||
|
.who { color: var(--cp-blue); font-weight: 700; }
|
||||||
|
|
||||||
|
/* 面板卡片 */
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 小标题(带竖线标记) */
|
||||||
|
.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; }
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>账号管理 <span class="badge">Accounts</span></h3>
|
||||||
|
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||||
|
</div>
|
||||||
|
<div class="head-acts">
|
||||||
|
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
<el-button type="primary" :icon="Plus" @click="openCreate">新建账号</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 账号搜索(服务端模糊:账号/昵称/部门) -->
|
||||||
|
<div class="search-bar cp-card cp-rise">
|
||||||
|
<el-input v-model="kw" placeholder="搜索账号 / 昵称 / 部门" clearable :prefix-icon="Search" style="width: 300px" @keyup.enter="onSearch" @clear="onSearch" />
|
||||||
|
<span v-if="kw" class="dim-sm">搜索中:{{ kw }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 账号卡片 -->
|
||||||
|
<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, 2)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||||
|
<span v-if="a.plugins.length > 2" class="more mono">+{{ a.plugins.length - 2 }}</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="!busy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||||
|
<PagerBar v-if="total > 0" :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||||
|
|
||||||
|
<!-- 新建账号 -->
|
||||||
|
<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="至少 8 位" 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>
|
||||||
|
<div class="modal-foot">
|
||||||
|
<el-button @click="createOpen = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="creating" @click="createAccount">建号</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</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>
|
||||||
|
|
||||||
|
<!-- 重置密码 -->
|
||||||
|
<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> 设置新密码(至少 8 位)
|
||||||
|
</el-alert>
|
||||||
|
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 8 位)" show-password @keyup.enter="confirmReset" />
|
||||||
|
<template #footer>
|
||||||
|
<div class="modal-foot">
|
||||||
|
<el-button @click="resetOpen = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="resetting" @click="confirmReset">确认重置</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, onMounted, reactive, ref } from 'vue'
|
||||||
|
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||||
|
import { Refresh, Plus, Camera, EditPen, Edit, Delete, Search } from '@element-plus/icons-vue'
|
||||||
|
import { store } from '../store'
|
||||||
|
import { adminAccounts, adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||||
|
import { fmtTime } from '../format'
|
||||||
|
import PagerBar from '../components/PagerBar.vue'
|
||||||
|
import { usePagedList } from '../composables/usePagedList'
|
||||||
|
|
||||||
|
const current = computed(() => store.current || '')
|
||||||
|
const kw = ref('')
|
||||||
|
const list = usePagedList((p, s) => adminAccounts(p, s, kw.value), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||||
|
const { items: accounts, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } = list
|
||||||
|
const busySwitch = ref('')
|
||||||
|
function onSearch() { reset() }
|
||||||
|
|
||||||
|
// ---------- 头像(显示 + 上传) ----------
|
||||||
|
const _fileInput = (() => {
|
||||||
|
const el = document.createElement('input')
|
||||||
|
el.type = 'file'
|
||||||
|
el.accept = 'image/*'
|
||||||
|
return el
|
||||||
|
})()
|
||||||
|
function pickAvatar(a) {
|
||||||
|
_fileInput.onchange = async () => {
|
||||||
|
const f = _fileInput.files && _fileInput.files[0]
|
||||||
|
_fileInput.value = ''
|
||||||
|
if (!f) return
|
||||||
|
try {
|
||||||
|
await adminAvatarUpload(a.account, f)
|
||||||
|
message.success(`已更新 ${a.account} 的头像`)
|
||||||
|
await refresh()
|
||||||
|
} catch (e) { message.error(e.message || e) }
|
||||||
|
}
|
||||||
|
_fileInput.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
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 createOpen = ref(false)
|
||||||
|
const creating = ref(false)
|
||||||
|
const createFormRef = ref()
|
||||||
|
const form = reactive({ account: '', password: '', dept: '', nickname: '', is_admin: false })
|
||||||
|
const rules = {
|
||||||
|
account: { required: true, message: '请输入账号' },
|
||||||
|
password: [
|
||||||
|
{ required: true, message: '请输入初始密码' },
|
||||||
|
{ min: 8, message: '密码至少 8 位' },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
function openCreate() { createOpen.value = true }
|
||||||
|
function resetCreate() {
|
||||||
|
form.account = form.password = form.dept = form.nickname = ''
|
||||||
|
form.is_admin = false
|
||||||
|
createFormRef.value?.resetFields()
|
||||||
|
}
|
||||||
|
async function createAccount() {
|
||||||
|
try { await createFormRef.value.validate() } catch (_) { return }
|
||||||
|
creating.value = true
|
||||||
|
try {
|
||||||
|
await adminAccountCreate({ ...form, account: form.account.trim() })
|
||||||
|
message.success(`已建号 ${form.account.trim()}`)
|
||||||
|
createOpen.value = false
|
||||||
|
await refresh()
|
||||||
|
} catch (e) { message.error('建号失败:' + (e.message || e)) }
|
||||||
|
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(a) {
|
||||||
|
resetTarget.value = a.account
|
||||||
|
resetPwdVal.value = ''
|
||||||
|
resetOpen.value = true
|
||||||
|
}
|
||||||
|
async function confirmReset() {
|
||||||
|
const p = resetPwdVal.value
|
||||||
|
if (p.length < 8) { message.warning('密码至少 8 位'); return }
|
||||||
|
resetting.value = true
|
||||||
|
try {
|
||||||
|
await adminAccountReset({ account: resetTarget.value, new_password: p })
|
||||||
|
message.success(`已重置 ${resetTarget.value} 密码`)
|
||||||
|
resetOpen.value = false
|
||||||
|
} catch (e) { message.error(e.message || e) }
|
||||||
|
finally { resetting.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
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(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(refresh)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.head-acts { display: flex; gap: 10px; }
|
||||||
|
|
||||||
|
.search-bar { display: flex; align-items: center; gap: 12px; padding: 14px 18px; margin-bottom: 16px; }
|
||||||
|
.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>
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>审计与运行报表 <span class="badge">Audit</span></h3>
|
||||||
|
<p>操作审计 · 部署端运行上报记录(最新在前)</p>
|
||||||
|
</div>
|
||||||
|
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 顶部摘要 -->
|
||||||
|
<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" @change="onAuditFilter">
|
||||||
|
<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" @keyup.enter="onAuditFilter" @clear="onAuditFilter" />
|
||||||
|
</div>
|
||||||
|
<el-table :data="audits" size="small" v-loading="auditBusy" :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>
|
||||||
|
<PagerBar :total="auditTotal" :page="auditPage" :page-size="auditPageSize" @change="onAuditPage" />
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<el-tab-pane label="运行上报" name="report">
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-select v-model="statusFilter" clearable placeholder="状态" style="width: 130px" @change="onReportFilter">
|
||||||
|
<el-option label="成功" value="done,success" />
|
||||||
|
<el-option label="失败" value="error,failed" />
|
||||||
|
<el-option label="运行中" value="running" />
|
||||||
|
<el-option label="已触发" value="start" />
|
||||||
|
</el-select>
|
||||||
|
<el-input v-model="reportSearch" placeholder="搜索账号 / 设备 / 插件 / 消息" clearable :prefix-icon="Search" style="width: 260px" @keyup.enter="onReportFilter" @clear="onReportFilter" />
|
||||||
|
</div>
|
||||||
|
<el-table :data="reports" size="small" v-loading="reportBusy" :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) }">{{ 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 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.pluginId || '—' }}</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.durationSec === 'number' ? fmtDur(row.durationSec) : '—' }}</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>
|
||||||
|
<PagerBar :total="reportTotal" :page="reportPage" :page-size="reportPageSize" @change="onReportPage" />
|
||||||
|
</el-tab-pane>
|
||||||
|
</el-tabs>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { Refresh, Search, Document, DataLine, CircleCloseFilled } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message } from 'element-plus'
|
||||||
|
import { adminAudit, adminReports } from '../api'
|
||||||
|
import { fmtTime } from '../format'
|
||||||
|
import PagerBar from '../components/PagerBar.vue'
|
||||||
|
import { usePagedList } from '../composables/usePagedList'
|
||||||
|
|
||||||
|
const tab = ref('audit')
|
||||||
|
const busy = ref(false)
|
||||||
|
const loaded = ref(false)
|
||||||
|
|
||||||
|
// 两个分页列表(服务端筛选:筛选/搜索条件作为闭包实时传给 fetcher)
|
||||||
|
const actionFilter = ref('')
|
||||||
|
const search = ref('')
|
||||||
|
const statusFilter = ref('')
|
||||||
|
const reportSearch = ref('')
|
||||||
|
|
||||||
|
const auditsList = usePagedList((p, s) => adminAudit(p, s, { action: actionFilter.value, q: search.value }), { onError: e => message.error('读取审计失败:' + (e.message || e)) })
|
||||||
|
const reportsList = usePagedList((p, s) => adminReports(p, s, { status: statusFilter.value, q: reportSearch.value }), { onError: e => message.error('读取上报失败:' + (e.message || e)) })
|
||||||
|
const { items: audits, total: auditTotal, page: auditPage, size: auditPageSize, busy: auditBusy, meta: auditMeta } = auditsList
|
||||||
|
const { items: reports, total: reportTotal, page: reportPage, size: reportPageSize, busy: reportBusy, meta: reportMeta } = reportsList
|
||||||
|
|
||||||
|
const DETAIL_LABEL = {
|
||||||
|
// 新命名(2026-09 服务端重构后)
|
||||||
|
'account-reset-pwd': '重置密码', 'grant-platform': '平台授权', 'revoke-platform': '撤销平台授权',
|
||||||
|
'plugin-publish': '上传发布', 'plugin-delete': '删除插件',
|
||||||
|
'creds-seed': '更新凭证',
|
||||||
|
'file-source-upsert': '登记文件源', 'file-source-patch': '更新文件源', 'file-source-delete': '删除文件源',
|
||||||
|
'shell-release': '发布壳子',
|
||||||
|
// 历史命名(旧版本审计记录兼容)
|
||||||
|
grant: '授权', 'revoke-grant': '撤销授权', 'plugin-patch': '更新插件',
|
||||||
|
'download-ticket': '下载', 'upload-pkg': '上传', 'account-create': '建号',
|
||||||
|
'account-update': '改号', 'account-reset': '重置密码', 'account-delete': '删除',
|
||||||
|
'platform-grant': '平台授权', login: '登录',
|
||||||
|
}
|
||||||
|
function actType(a) {
|
||||||
|
return { grant: 'primary', 'revoke-grant': 'danger', 'plugin-patch': 'warning',
|
||||||
|
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary',
|
||||||
|
'plugin-publish': 'success', 'plugin-delete': 'danger',
|
||||||
|
'grant-platform': 'primary', 'revoke-platform': 'danger',
|
||||||
|
'account-reset-pwd': 'warning', 'creds-seed': 'warning',
|
||||||
|
'shell-release': 'success' }[a] || 'info'
|
||||||
|
}
|
||||||
|
function statusColor(s) {
|
||||||
|
return { start: '#2f5cf0', running: '#2f5cf0', done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d' }[s] || '#9aa2b4'
|
||||||
|
}
|
||||||
|
function statusLabel(s) {
|
||||||
|
return ({ done: '成功', success: '成功', error: '失败', failed: '失败', running: '运行中', start: '已触发' })[s] || s
|
||||||
|
}
|
||||||
|
function fmtDur(sec) {
|
||||||
|
sec = +sec || 0
|
||||||
|
if (sec < 60) return sec + 's'
|
||||||
|
const m = Math.floor(sec / 60), s = sec % 60
|
||||||
|
if (m < 60) return `${m}m${s ? s + 's' : ''}`
|
||||||
|
return `${Math.floor(m / 60)}h${m % 60}m`
|
||||||
|
}
|
||||||
|
|
||||||
|
// KPI 全用后端统计值(total/today/failed),不依赖当前页 slice,保证分页后口径不变
|
||||||
|
const kpis = computed(() => [
|
||||||
|
{ label: '审计记录', value: auditTotal.value, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||||
|
{ label: '今日操作', value: auditMeta.value.today || 0, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||||
|
{ label: '运行上报', value: reportTotal.value, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||||
|
{ label: '今日上报', value: reportMeta.value.today || 0, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||||
|
{ label: '上报失败', value: reportMeta.value.failed || 0, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||||
|
])
|
||||||
|
|
||||||
|
// 筛选变化 → 回到第一页(服务端重新查询)
|
||||||
|
function onAuditFilter() { auditsList.reset() }
|
||||||
|
function onReportFilter() { reportsList.reset() }
|
||||||
|
function onAuditPage(p, s) { auditsList.onPageChange(p, s) }
|
||||||
|
function onReportPage(p, s) { reportsList.onPageChange(p, s) }
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
busy.value = true
|
||||||
|
try {
|
||||||
|
await Promise.all([auditsList.load(), reportsList.load()])
|
||||||
|
loaded.value = true
|
||||||
|
} catch (_) { /* 子加载器已提示 */ }
|
||||||
|
finally { busy.value = false }
|
||||||
|
}
|
||||||
|
onMounted(refresh)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.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>
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>敏感凭证 <span class="badge">Creds</span></h3>
|
||||||
|
<p>执行机敏感凭证的明文源(钉钉开放平台)。保存后客户端下次启动用 RSA 私钥解密拉取;留空 = 该键不下发</p>
|
||||||
|
</div>
|
||||||
|
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cp-card panel cp-rise">
|
||||||
|
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||||
|
<el-table-column prop="account" label="执行机账号" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="mono">{{ row.nickname ? `${row.nickname} · ${row.account}` : row.account }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="公钥" width="90">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.has_pubkey ? 'success' : 'info'" size="small" effect="light">
|
||||||
|
{{ row.has_pubkey ? '已上报' : '未上报' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column v-for="k in keyCols" :key="k.key" :label="k.label" min-width="170" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="mono dim" :class="{ empty: !row.creds[k.key] }">{{ row.creds[k.key] || '(未配置)' }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="updated_at" label="更新时间" width="170" />
|
||||||
|
<el-table-column label="操作" width="90" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button link type="primary" :icon="EditPen" @click="openEdit(row)">编辑</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<template #empty>
|
||||||
|
<el-empty description="暂无账号,客户端启动注册后自动出现" :image-size="80" />
|
||||||
|
</template>
|
||||||
|
</el-table>
|
||||||
|
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-dialog v-model="dlg" :title="`编辑凭证 · ${editing?.account || ''}`" width="540px">
|
||||||
|
<div class="form">
|
||||||
|
<div class="fitem" v-for="k in keyCols" :key="k.key">
|
||||||
|
<label>{{ k.label }} <span class="dim mono">({{ k.key }})</span></label>
|
||||||
|
<el-input v-model="form[k.key]" :type="k.key.includes('SECRET') ? 'password' : 'text'"
|
||||||
|
:show-password="k.key.includes('SECRET')" placeholder="留空 = 不下发该键" />
|
||||||
|
</div>
|
||||||
|
<p class="tip">值仅管理台可见;保存后客户端下次启动拉取更新(离线用本地加密缓存)。</p>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dlg = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { Refresh, EditPen } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message } from 'element-plus'
|
||||||
|
import { adminCredsList, adminCredsSeed } from '../api'
|
||||||
|
import PagerBar from '../components/PagerBar.vue'
|
||||||
|
import { usePagedList } from '../composables/usePagedList'
|
||||||
|
|
||||||
|
const KEY_COLS = [
|
||||||
|
{ key: 'DINGTALK_APPKEY', label: 'AppKey' },
|
||||||
|
{ key: 'DINGTALK_APPSECRET', label: 'AppSecret' },
|
||||||
|
{ key: 'DINGTALK_AGENT_ID', label: 'AgentId' },
|
||||||
|
{ key: 'DINGTALK_CORP_ID', label: 'CorpId' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const keyCols = KEY_COLS
|
||||||
|
const list = usePagedList((p, s) => adminCredsList(p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||||
|
const { items: rows, total, page, size: pageSize, busy, load: refresh, onPageChange } = list
|
||||||
|
const dlg = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const editing = ref(null)
|
||||||
|
const form = ref({})
|
||||||
|
|
||||||
|
function openEdit(row) {
|
||||||
|
editing.value = row
|
||||||
|
form.value = {}
|
||||||
|
keyCols.forEach(c => { form.value[c.key] = row.creds?.[c.key] || '' })
|
||||||
|
dlg.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (!editing.value) return
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
const values = {}
|
||||||
|
keyCols.forEach(c => { if (form.value[c.key]) values[c.key] = String(form.value[c.key]).trim() })
|
||||||
|
const r = await adminCredsSeed({ account: editing.value.account, values })
|
||||||
|
message.success(`已保存 ${r.seeded_keys.length} 个键(留空键已清除)`)
|
||||||
|
dlg.value = false
|
||||||
|
await refresh()
|
||||||
|
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||||
|
finally { saving.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(refresh)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.panel { padding: 22px 24px 26px; }
|
||||||
|
.form { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.fitem { display: flex; flex-direction: column; gap: 7px; }
|
||||||
|
.fitem label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||||
|
.fitem .dim { font-weight: 500; font-size: 12px; }
|
||||||
|
.empty { color: var(--cp-ink-3); }
|
||||||
|
.tip { font-size: 12px; color: var(--cp-ink-3); margin: 2px 0 0; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>大文件源 <span class="badge">File Sources</span></h3>
|
||||||
|
<p>内网大文件(壳子/Chrome 等)直链登记。中心机只存链接,文件本身走内网文件服务器</p>
|
||||||
|
</div>
|
||||||
|
<div class="head-actions">
|
||||||
|
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="onFilterChange">
|
||||||
|
<el-option v-for="c in categories" :key="c" :label="c" :value="c" />
|
||||||
|
</el-select>
|
||||||
|
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
<el-button type="primary" :icon="Plus" @click="openCreate">登记链接</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cp-card panel cp-rise">
|
||||||
|
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||||
|
<el-table-column prop="category" label="分类" width="110">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="catType(row.category)" size="small" effect="light">{{ row.category }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="version" label="版本" width="90">
|
||||||
|
<template #default="{ row }"><span class="mono">{{ row.version }}</span></template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="filename" label="文件" min-width="150" show-overflow-tooltip />
|
||||||
|
<el-table-column label="内网直链" min-width="260" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="mono dim url">{{ row.url }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="SHA256" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button v-if="row.sha256" link type="primary" @click="copy(row.sha256, 'SHA256')">
|
||||||
|
{{ row.sha256.slice(0, 8) }}…
|
||||||
|
</el-button>
|
||||||
|
<span v-else class="dim">—</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="说明" min-width="140" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">{{ row.notes || '—' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="updated_at" label="更新时间" width="160" />
|
||||||
|
<el-table-column label="启用" width="70" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch :model-value="!!row.enabled" :loading="row._tog" @change="(v) => toggle(row, v)" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="130" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button link type="primary" @click="copy(row.url, '链接')">复制</el-button>
|
||||||
|
<el-button link type="danger" :icon="Delete" @click="remove(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<template #empty>
|
||||||
|
<el-empty description="暂无登记的大文件源" :image-size="80" />
|
||||||
|
</template>
|
||||||
|
</el-table>
|
||||||
|
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-dialog v-model="dlg" title="登记内网直链" width="560px">
|
||||||
|
<div class="form">
|
||||||
|
<div class="fitem">
|
||||||
|
<label>分类 <span class="dim">(shell / chrome / …)</span></label>
|
||||||
|
<el-input v-model="form.category" placeholder="如 chrome" />
|
||||||
|
</div>
|
||||||
|
<div class="fitem">
|
||||||
|
<label>版本</label>
|
||||||
|
<el-input v-model="form.version" placeholder="如 1.0.0" />
|
||||||
|
</div>
|
||||||
|
<div class="fitem">
|
||||||
|
<label>文件名</label>
|
||||||
|
<el-input v-model="form.filename" placeholder="如 ChromeStandaloneSetup64.exe" />
|
||||||
|
</div>
|
||||||
|
<div class="fitem">
|
||||||
|
<label>内网直链 url</label>
|
||||||
|
<el-input v-model="form.url" placeholder="http://内网IP:8802/files/..." />
|
||||||
|
</div>
|
||||||
|
<div class="fitem">
|
||||||
|
<label>SHA256 <span class="dim">(可选)</span></label>
|
||||||
|
<el-input v-model="form.sha256" placeholder="文件校验值,客户端下载后校验" />
|
||||||
|
</div>
|
||||||
|
<div class="fitem">
|
||||||
|
<label>说明 <span class="dim">(可选)</span></label>
|
||||||
|
<el-input v-model="form.notes" type="textarea" :rows="2" placeholder="备注" />
|
||||||
|
</div>
|
||||||
|
<p class="tip">同一 分类+版本 会覆盖旧记录;删除仅移除中心机登记,不影响内网文件服务器上的文件。</p>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dlg = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { onMounted, ref, watch } from 'vue'
|
||||||
|
import { Refresh, Plus, Delete } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message, ElMessageBox } from 'element-plus'
|
||||||
|
import { adminFileSources, adminFileSourceCreate, adminFileSourcePatch, adminFileSourceDelete } from '../api'
|
||||||
|
import PagerBar from '../components/PagerBar.vue'
|
||||||
|
import { usePagedList } from '../composables/usePagedList'
|
||||||
|
|
||||||
|
const CATS = ['shell', 'chrome-x64', 'chrome-x86']
|
||||||
|
const categories = CATS
|
||||||
|
const filter = ref('')
|
||||||
|
const list = usePagedList((p, s) => adminFileSources(filter.value || '', p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||||
|
const { items: rows, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } = list
|
||||||
|
const dlg = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const form = ref({})
|
||||||
|
|
||||||
|
function onFilterChange() { reset() }
|
||||||
|
// 分类下拉:由当前页数据补充实际出现的分类
|
||||||
|
watch(rows, () => {
|
||||||
|
const seen = new Set(CATS)
|
||||||
|
;(rows.value || []).forEach((f) => seen.add(f.category))
|
||||||
|
categories.length = 0
|
||||||
|
;[...seen].sort().forEach((c) => categories.push(c))
|
||||||
|
})
|
||||||
|
|
||||||
|
function catType(c) {
|
||||||
|
return { shell: 'success', 'chrome-x64': 'warning', 'chrome-x86': 'warning', chrome: 'warning' }[c] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
form.value = { category: '', version: '', filename: '', url: '', sha256: '', notes: '', enabled: true }
|
||||||
|
dlg.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (!form.value.category || !form.value.category.trim()) return message.error('分类不能为空')
|
||||||
|
if (!form.value.url || !form.value.url.trim()) return message.error('内网直链不能为空')
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
const { enabled, ...rest } = form.value
|
||||||
|
const body = { ...rest, category: form.value.category.trim(), url: form.value.url.trim(), enabled: true }
|
||||||
|
await adminFileSourceCreate(body)
|
||||||
|
message.success('已登记')
|
||||||
|
dlg.value = false
|
||||||
|
await refresh()
|
||||||
|
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||||
|
finally { saving.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggle(row, v) {
|
||||||
|
row._tog = true
|
||||||
|
try { await adminFileSourcePatch(row.id, { enabled: v }); row.enabled = v; message.success(v ? '已启用' : '已停用') }
|
||||||
|
catch (e) { message.error('操作失败:' + (e.message || e)) }
|
||||||
|
finally { row._tog = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(row) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`删除「${row.category} ${row.version}」的登记?此操作仅移除中心机登记,不影响内网文件。`, '确认删除', { type: 'warning' })
|
||||||
|
} catch (_) { return }
|
||||||
|
try {
|
||||||
|
await adminFileSourceDelete(row.id)
|
||||||
|
message.success('已删除')
|
||||||
|
await refresh()
|
||||||
|
} catch (e) { message.error('删除失败:' + (e.message || e)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copy(text, what) {
|
||||||
|
try { await navigator.clipboard.writeText(text); message.success(what + '已复制') }
|
||||||
|
catch (_) { message.error('复制失败,请手动选择') }
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(refresh)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.panel { padding: 22px 24px 26px; }
|
||||||
|
.head-actions { display: flex; gap: 10px; align-items: center; }
|
||||||
|
.form { display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
.fitem { display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.fitem label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||||
|
.fitem .dim { font-weight: 500; font-size: 12px; }
|
||||||
|
.dim { color: var(--cp-ink-3); }
|
||||||
|
.url { font-size: 12px; }
|
||||||
|
.tip { font-size: 12px; color: var(--cp-ink-3); margin: 0; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>权限授权 <span class="badge">Grants</span></h3>
|
||||||
|
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||||
|
</div>
|
||||||
|
<el-button :loading="grantDataBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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">
|
||||||
|
<!-- 插件授权 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-head">
|
||||||
|
<div class="card-title">插件授权</div>
|
||||||
|
<div class="gh-sec-right">
|
||||||
|
<el-input v-model="pluginKw" placeholder="搜索插件 ID / 名称" clearable :prefix-icon="Search" size="small" style="width: 210px" />
|
||||||
|
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<el-checkbox-group v-model="grantedIds" class="plist" v-loading="grantsBusy">
|
||||||
|
<div class="prow" v-for="p in visiblePlugins" :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="!visiblePlugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 平台授权 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-head">
|
||||||
|
<div class="card-title">平台授权</div>
|
||||||
|
</div>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<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, Search, User, Check } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message } from 'element-plus'
|
||||||
|
import { adminGrant, adminPlatformGrant, adminPlatforms, adminGrantData, adminAccountGrants } from '../api'
|
||||||
|
|
||||||
|
const PLATFORM_OPTS = ref([])
|
||||||
|
const grantDataBusy = ref(false)
|
||||||
|
const grantsBusy = ref(false)
|
||||||
|
|
||||||
|
// 轻量数据源(/grant_data 一次查询,不依赖 overview 全量聚合)
|
||||||
|
const plugins = ref([]) // {id,name,status}
|
||||||
|
const accounts = ref([]) // {account,nickname,dept,status}
|
||||||
|
const accountOptions = computed(() => accounts.value.map(a => ({
|
||||||
|
label: [a.nickname, a.account, a.dept].filter(Boolean).join(' · '),
|
||||||
|
value: a.account,
|
||||||
|
})))
|
||||||
|
// 插件搜索(数据为全量,前端过滤安全)
|
||||||
|
const pluginKw = ref('')
|
||||||
|
const visiblePlugins = computed(() => {
|
||||||
|
const kw = pluginKw.value.trim().toLowerCase()
|
||||||
|
if (!kw) return plugins.value
|
||||||
|
return plugins.value.filter(p => [p.id, p.name].join(' ').toLowerCase().includes(kw))
|
||||||
|
})
|
||||||
|
|
||||||
|
const account = ref('')
|
||||||
|
const grantedIds = ref([])
|
||||||
|
const grantState = ref({}) // plugin_id -> { granted, canRun, canDownload }
|
||||||
|
const platChecked = ref([])
|
||||||
|
const saving = ref(false)
|
||||||
|
let heldGrantState = {} // 已保存快照,用于差异比对
|
||||||
|
let heldPlatforms = new Set()
|
||||||
|
|
||||||
|
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(() => visiblePlugins.value.length > 0 &&
|
||||||
|
visiblePlugins.value.every(p => grantedIds.value.includes(p.id)))
|
||||||
|
const someChecked = computed(() => visiblePlugins.value.some(p => grantedIds.value.includes(p.id)) && !allChecked.value)
|
||||||
|
function toggleAll(v) {
|
||||||
|
const visible = visiblePlugins.value.map(p => p.id)
|
||||||
|
grantedIds.value = v
|
||||||
|
? [...new Set([...grantedIds.value, ...visible])]
|
||||||
|
: grantedIds.value.filter(id => !visible.includes(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 选中账号即拉取其现有授权(按账号 2 次查询,无 N+1)
|
||||||
|
watch(account, async (acc) => {
|
||||||
|
if (!acc) {
|
||||||
|
grantState.value = {}; grantedIds.value = []; platChecked.value = []
|
||||||
|
heldGrantState = {}; heldPlatforms = new Set()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
grantsBusy.value = true
|
||||||
|
try {
|
||||||
|
const r = await adminAccountGrants(acc)
|
||||||
|
const state = {}
|
||||||
|
;(r.plugins || []).forEach(g => {
|
||||||
|
state[g.plugin_id] = { granted: true, canRun: g.canRun !== false, canDownload: g.canDownload !== false }
|
||||||
|
})
|
||||||
|
heldGrantState = JSON.parse(JSON.stringify(state))
|
||||||
|
grantState.value = JSON.parse(JSON.stringify(state))
|
||||||
|
grantedIds.value = [...(r.plugins || []).map(g => g.plugin_id)]
|
||||||
|
heldPlatforms = new Set(r.platforms || [])
|
||||||
|
platChecked.value = [...heldPlatforms]
|
||||||
|
} catch (e) { message.error('读取授权失败:' + (e.message || e)) }
|
||||||
|
finally { grantsBusy.value = false }
|
||||||
|
})
|
||||||
|
|
||||||
|
// 勾选/取消勾选插件时同步 granted 状态
|
||||||
|
watch(grantedIds, (ids) => {
|
||||||
|
const state = { ...grantState.value }
|
||||||
|
ids.forEach(pid => {
|
||||||
|
if (!state[pid]) state[pid] = { granted: true, canRun: true, canDownload: true }
|
||||||
|
else state[pid].granted = true
|
||||||
|
})
|
||||||
|
Object.keys(state).forEach(pid => {
|
||||||
|
if (!ids.includes(pid)) state[pid].granted = false
|
||||||
|
})
|
||||||
|
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() {
|
||||||
|
grantDataBusy.value = true
|
||||||
|
try {
|
||||||
|
const [gd, pf] = await Promise.all([adminGrantData(), adminPlatforms()])
|
||||||
|
plugins.value = gd.plugins || []
|
||||||
|
accounts.value = gd.accounts || []
|
||||||
|
PLATFORM_OPTS.value = (pf.platforms || []).map(p => ({ id: p.id, label: p.label }))
|
||||||
|
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||||
|
finally { grantDataBusy.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
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()
|
||||||
|
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||||
|
finally { saving.value = false }
|
||||||
|
}
|
||||||
|
onMounted(refresh)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.panel { padding: 22px 24px 26px; }
|
||||||
|
|
||||||
|
.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; }
|
||||||
|
.gh-sec-right { display: flex; align-items: center; gap: 14px; }
|
||||||
|
|
||||||
|
/* 插件授权行 */
|
||||||
|
.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: var(--cp-panel);
|
||||||
|
transition: border-color .18s, background .18s, box-shadow .18s;
|
||||||
|
}
|
||||||
|
.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);
|
||||||
|
}
|
||||||
|
.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>
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>概览 <span class="badge">Dashboard</span></h3>
|
||||||
|
<p>中心机 · 插件分发与账号权限 · 当前账号 <b class="who">{{ store.nickname || store.current }}</b></p>
|
||||||
|
</div>
|
||||||
|
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="ov">
|
||||||
|
<!-- 统计卡(4 列,与下方图表区对齐) -->
|
||||||
|
<div class="stat-grid">
|
||||||
|
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||||
|
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||||
|
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||||
|
</div>
|
||||||
|
<div class="stat-meta">
|
||||||
|
<div class="stat-num mono">{{ s.value }}</div>
|
||||||
|
<div class="stat-label">{{ s.label }}</div>
|
||||||
|
</div>
|
||||||
|
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 图表区(两列独立高度,不拉伸) -->
|
||||||
|
<div class="ov-grid">
|
||||||
|
<div class="cp-card cp-rise chart-card">
|
||||||
|
<div class="card-title">插件状态分布 <span class="sub">已发布 / 停用 / 已撤销</span></div>
|
||||||
|
<div ref="pieEl" class="pie-chart"></div>
|
||||||
|
<div class="pie-legend">
|
||||||
|
<span v-for="c in pieLegend" :key="c.name">
|
||||||
|
<i :style="{ background: c.color }"></i>{{ c.name }} <b class="mono">{{ c.value }}</b>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cp-card cp-rise chart-card">
|
||||||
|
<div class="card-title">授权覆盖 <span class="sub">已授权插件账号 / 账号总数</span></div>
|
||||||
|
<div ref="gaugeEl" class="gauge-chart"></div>
|
||||||
|
<div class="gauge-num mono">
|
||||||
|
<b>{{ authCount }}</b><span class="dim"> / {{ (ov.accounts || []).length }} 个账号已授权插件</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 最近动态 -->
|
||||||
|
<div class="page-head sub cp-rise">
|
||||||
|
<div><h4>最近动态</h4></div>
|
||||||
|
</div>
|
||||||
|
<div class="cp-card cp-rise feed-card">
|
||||||
|
<div class="feed-item" v-for="v in recentUploads" :key="v.key">
|
||||||
|
<span class="feed-dot"></span>
|
||||||
|
<span class="feed-text mono">{{ v.plugin }}</span>
|
||||||
|
<el-tag size="small" effect="plain" round type="primary" class="mono">v{{ v.version }}</el-tag>
|
||||||
|
<span class="feed-time mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="!recentUploads.length" class="empty">暂无上传记录</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<el-skeleton v-else-if="overviewBusy" animated :rows="3" style="margin-top: 20px" />
|
||||||
|
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
|
import { Refresh, InfoFilled, Box, Collection, User, UserFilled } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message } from 'element-plus'
|
||||||
|
// ECharts 按需引入(环图)
|
||||||
|
import * as echarts from 'echarts/core'
|
||||||
|
import { PieChart } from 'echarts/charts'
|
||||||
|
import { TooltipComponent, LegendComponent } from 'echarts/components'
|
||||||
|
import { CanvasRenderer } from 'echarts/renderers'
|
||||||
|
echarts.use([PieChart, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||||
|
|
||||||
|
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||||
|
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: '#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)' },
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
// 最近上传(按时间倒序取 6 条)
|
||||||
|
const recentUploads = computed(() => {
|
||||||
|
const items = []
|
||||||
|
for (const p of ov.value?.plugins || []) {
|
||||||
|
for (const v of p.versions || []) {
|
||||||
|
items.push({ key: p.id + v.version, plugin: p.id, version: v.version, uploaded_at: v.uploaded_at })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items.filter(i => i.uploaded_at).sort((a, b) => (a.uploaded_at < b.uploaded_at ? 1 : -1)).slice(0, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
const authCount = computed(() => (ov.value?.accounts || []).filter(a => a.plugins?.length).length)
|
||||||
|
const pieLegend = computed(() => [
|
||||||
|
{ name: '已发布', color: '#1d9d5c', value: countStatus('published') },
|
||||||
|
{ name: '停用', color: '#d97706', value: countStatus('disabled') },
|
||||||
|
{ name: '已撤销', color: '#d6453d', value: countStatus('revoked') },
|
||||||
|
])
|
||||||
|
function countStatus(s) { return (ov.value?.plugins || []).filter(p => p.status === s).length }
|
||||||
|
|
||||||
|
// ---------- ECharts ----------
|
||||||
|
const pieEl = ref(null)
|
||||||
|
const gaugeEl = ref(null)
|
||||||
|
let pieChart = null
|
||||||
|
let gaugeChart = null
|
||||||
|
|
||||||
|
function renderCharts() {
|
||||||
|
if (!ov.value) return
|
||||||
|
const pieData = pieLegend.value.filter(c => c.value > 0)
|
||||||
|
if (pieEl.value) {
|
||||||
|
if (!pieChart) pieChart = echarts.init(pieEl.value)
|
||||||
|
pieChart.setOption({
|
||||||
|
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||||
|
series: [{
|
||||||
|
type: 'pie', radius: ['58%', '78%'], center: ['50%', '50%'],
|
||||||
|
avoidLabelOverlap: true,
|
||||||
|
itemStyle: { borderRadius: 6, borderColor: '#fffdf8', borderWidth: 2 },
|
||||||
|
label: { show: false }, emphasis: { label: { show: false } },
|
||||||
|
data: pieData.map(c => ({ name: c.name, value: c.value, itemStyle: { color: c.color } })),
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const acc = (ov.value.accounts || []).length
|
||||||
|
const authed = authCount.value
|
||||||
|
const rate = acc ? Math.round(authed / acc * 100) : 0
|
||||||
|
if (gaugeEl.value) {
|
||||||
|
if (!gaugeChart) gaugeChart = echarts.init(gaugeEl.value)
|
||||||
|
gaugeChart.setOption({
|
||||||
|
series: [{
|
||||||
|
type: 'pie', radius: ['62%', '80%'], center: ['50%', '50%'],
|
||||||
|
silent: true,
|
||||||
|
label: { show: true, position: 'center', formatter: rate + '%', fontSize: 26, fontWeight: 800, color: '#232a3a' },
|
||||||
|
data: [
|
||||||
|
{ value: authed, itemStyle: { color: '#2f5cf0' } },
|
||||||
|
{ value: acc - authed, itemStyle: { color: 'rgba(35,42,58,.08)' } },
|
||||||
|
],
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// immediate:overview 有缓存(store 模块级)且 force 重拉失败时,ov 不变化也能渲染已有数据
|
||||||
|
watch(ov, () => nextTick(renderCharts), { immediate: true })
|
||||||
|
const onResize = () => { pieChart && pieChart.resize(); gaugeChart && gaugeChart.resize() }
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||||
|
}
|
||||||
|
onMounted(() => { refresh(); window.addEventListener('resize', onResize) })
|
||||||
|
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); pieChart && pieChart.dispose(); gaugeChart && gaugeChart.dispose(); pieChart = gaugeChart = null })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.stat-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 18px; }
|
||||||
|
@media (max-width: 1100px) { .stat-grid { grid-template-columns: repeat(2, 1fr); } }
|
||||||
|
.stat-card { display: flex; align-items: center; gap: 16px; padding: 20px; overflow: hidden; }
|
||||||
|
.stat-ic { 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, .7); }
|
||||||
|
.stat-meta { min-width: 0; }
|
||||||
|
.stat-num { font-size: 27px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink-1); }
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
/* 图表区两列独立高度 */
|
||||||
|
.ov-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin: 18px 0 0; align-items: start; }
|
||||||
|
@media (max-width: 1100px) { .ov-grid { grid-template-columns: 1fr; } }
|
||||||
|
.chart-card { padding: 20px; }
|
||||||
|
.card-title { margin-bottom: 10px; }
|
||||||
|
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||||
|
.pie-chart { height: 210px; }
|
||||||
|
.gauge-chart { height: 210px; }
|
||||||
|
.pie-legend { display: flex; justify-content: center; gap: 20px; margin-top: 4px; font-size: 12.5px; color: var(--cp-ink-2); }
|
||||||
|
.pie-legend i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||||
|
.pie-legend b { margin-left: 3px; color: var(--cp-ink-1); }
|
||||||
|
.gauge-num { text-align: center; margin-top: 2px; font-size: 13px; color: var(--cp-ink-2); }
|
||||||
|
.gauge-num b { font-size: 20px; color: var(--cp-blue); }
|
||||||
|
|
||||||
|
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||||
|
.feed-card { padding: 8px 18px; }
|
||||||
|
.feed-item { display: flex; align-items: center; gap: 10px; padding: 9px 0; border-bottom: 1px dashed var(--cp-line); }
|
||||||
|
.feed-item:last-child { border-bottom: none; }
|
||||||
|
.feed-dot { width: 8px; height: 8px; border-radius: 50%; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); flex: none; }
|
||||||
|
.feed-text { font-size: 13px; color: var(--cp-ink-1); min-width: 120px; }
|
||||||
|
.feed-time { margin-left: auto; }
|
||||||
|
.empty { color: var(--cp-ink-3); font-size: 12px; padding: 14px 0; text-align: center; }
|
||||||
|
|
||||||
|
.tip-card { margin-top: 20px; display: flex; gap: 14px; padding: 20px 22px; background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel); }
|
||||||
|
.tip-ic { width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0; display: grid; place-items: center; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6); }
|
||||||
|
.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); }
|
||||||
|
.dim-sm { color: var(--cp-ink-3); font-size: 12px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>插件管理 <span class="badge">Plugins</span></h3>
|
||||||
|
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||||
|
</div>
|
||||||
|
<el-button :loading="listBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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 包' }}
|
||||||
|
</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>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cp-card block cp-rise list-card">
|
||||||
|
<div class="list-head">
|
||||||
|
<div class="card-title">插件列表</div>
|
||||||
|
<el-input v-model="kw" placeholder="搜索插件 ID / 名称" clearable :prefix-icon="Search" size="small" style="width: 230px" @keyup.enter="onSearch" @clear="onSearch" />
|
||||||
|
</div>
|
||||||
|
<el-table :data="plugins" size="small" :loading="listBusy" :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>
|
||||||
|
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 编辑插件 -->
|
||||||
|
<el-dialog v-model="editShow" width="720px" align-center destroy-on-close>
|
||||||
|
<template #header>
|
||||||
|
<div class="ed-head">
|
||||||
|
<span class="ed-avatar">{{ (edit.name || edit.pid || '?').slice(0, 1) }}</span>
|
||||||
|
<div class="ed-headmeta">
|
||||||
|
<div class="ed-title mono">{{ edit.pid }}</div>
|
||||||
|
<div class="ed-sub">修改基础信息、发布状态与强制更新策略</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<el-form label-position="top" class="ed-form">
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">基本信息</div>
|
||||||
|
<div class="form-2col">
|
||||||
|
<el-form-item label="插件名称">
|
||||||
|
<el-input v-model="edit.name" placeholder="插件显示名" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="分类">
|
||||||
|
<el-input v-model="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">插件描述</div>
|
||||||
|
<el-form-item>
|
||||||
|
<el-input v-model="edit.description" type="textarea" :autosize="{ minRows: 5, maxRows: 12 }"
|
||||||
|
maxlength="500" show-word-limit placeholder="插件用途说明(支持换行,执行端与详情页均会展示)" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">发布状态</div>
|
||||||
|
<el-form-item>
|
||||||
|
<el-radio-group v-model="edit.status">
|
||||||
|
<el-radio-button value="published">正常发布</el-radio-button>
|
||||||
|
<el-radio-button value="disabled">禁用(停止分发)</el-radio-button>
|
||||||
|
<el-radio-button value="revoked">下架(禁止运行)</el-radio-button>
|
||||||
|
</el-radio-group>
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">强制更新 <span class="ed-opt">可选 · 两项都填才会生效</span></div>
|
||||||
|
<div class="force-box">
|
||||||
|
<div class="force-line">
|
||||||
|
<el-input v-model="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 190px" class="mono" />
|
||||||
|
<el-date-picker v-model="edit.force_dl" type="datetime" value-format="YYYY-MM-DD[T]HH:mm"
|
||||||
|
format="YYYY-MM-DD HH:mm" placeholder="截止时间" style="width: 220px" class="mono" />
|
||||||
|
</div>
|
||||||
|
<div class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动;留空表示不强制</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<div class="modal-foot">
|
||||||
|
<el-button @click="editShow = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="saveEdit">保存修改</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- 插件详情 -->
|
||||||
|
<el-dialog v-model="detailShow" width="780px" align-center destroy-on-close>
|
||||||
|
<template #header>
|
||||||
|
<div class="dt-head" v-if="detail">
|
||||||
|
<span class="dt-avatar">{{ (detail.name || detail.id || '?').slice(0, 1) }}</span>
|
||||||
|
<div class="dt-headmeta">
|
||||||
|
<div class="dt-title-row">
|
||||||
|
<span class="dt-id mono">{{ detail.id }}</span>
|
||||||
|
<el-tag size="small" round effect="light" :type="statusMeta[detail.status]?.type || 'info'">
|
||||||
|
{{ statusMeta[detail.status]?.label || detail.status || '—' }}
|
||||||
|
</el-tag>
|
||||||
|
<el-tag v-if="detail.category" size="small" round effect="plain" type="info">{{ detail.category }}</el-tag>
|
||||||
|
</div>
|
||||||
|
<div class="dt-name">{{ detail.name || '未命名插件' }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div v-if="detail" class="plg-detail">
|
||||||
|
<div class="dt-grid">
|
||||||
|
<div class="dt-item">
|
||||||
|
<el-icon class="dt-ic"><Box /></el-icon>
|
||||||
|
<div><label>最新版本</label><span class="mono">{{ detail.latest_version || '—' }}</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="dt-item">
|
||||||
|
<el-icon class="dt-ic"><Files /></el-icon>
|
||||||
|
<div><label>表单字段</label><span class="mono">{{ detail.field_count || 0 }} 项</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="dt-item">
|
||||||
|
<el-icon class="dt-ic"><User /></el-icon>
|
||||||
|
<div><label>授权账号</label><span class="mono">{{ detail.accounts?.length || 0 }} 个</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="dt-item">
|
||||||
|
<el-icon class="dt-ic" :class="{ 'dt-ic-on': detail.force_min_version && detail.force_deadline }"><Clock /></el-icon>
|
||||||
|
<div><label>强制更新</label><span>{{ forceText(detail) }}</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dt-sec">
|
||||||
|
<div class="ed-sec-title">插件描述</div>
|
||||||
|
<p class="dt-desc">{{ detail.description || '暂无描述' }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dt-sec">
|
||||||
|
<div class="ed-sec-title">能力声明</div>
|
||||||
|
<div class="tags" v-if="detail.capabilities?.length">
|
||||||
|
<el-tag v-for="c in detail.capabilities" :key="c" size="small" effect="plain" round class="mono">{{ c }}</el-tag>
|
||||||
|
</div>
|
||||||
|
<span v-else class="dim">—</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dt-cols">
|
||||||
|
<div class="dt-sec">
|
||||||
|
<div class="ed-sec-title">版本历史</div>
|
||||||
|
<div class="vlist" v-if="detail.versions?.length">
|
||||||
|
<div class="vrow" v-for="v in detail.versions" :key="v.version">
|
||||||
|
<el-tag size="small" round effect="light" class="mono"
|
||||||
|
:type="v.version === detail.latest_version ? 'primary' : 'info'">{{ v.version }}</el-tag>
|
||||||
|
<el-tag v-if="v.version === detail.latest_version" size="small" round effect="plain"
|
||||||
|
type="success" class="v-latest">当前</el-tag>
|
||||||
|
<span class="vtime mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span v-else class="dim">暂无版本</span>
|
||||||
|
</div>
|
||||||
|
<div class="dt-sec">
|
||||||
|
<div class="ed-sec-title">授权账号</div>
|
||||||
|
<div class="tags" v-if="detail.accounts?.length">
|
||||||
|
<el-tag v-for="a in detail.accounts" :key="a.account" size="small" effect="plain" type="success" round class="mono">{{ a.nickname ? `${a.nickname} · ${a.account}` : a.account }}</el-tag>
|
||||||
|
</div>
|
||||||
|
<span v-else class="dim">未授权任何账号,执行端不可见</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="detailShow = false">关闭</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { onMounted, reactive, ref } from 'vue'
|
||||||
|
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||||
|
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock, Search } from '@element-plus/icons-vue'
|
||||||
|
import { adminPlugins, adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||||
|
import { fmtTime } from '../format'
|
||||||
|
import PagerBar from '../components/PagerBar.vue'
|
||||||
|
import { usePagedList } from '../composables/usePagedList'
|
||||||
|
|
||||||
|
const kw = ref('')
|
||||||
|
const list = usePagedList((p, s) => adminPlugins(p, s, kw.value), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||||
|
const { items: plugins, total, page, size: pageSize, busy: listBusy, load: refresh, onPageChange, reset } = list
|
||||||
|
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||||
|
function onSearch() { reset() }
|
||||||
|
const uploading = ref(false)
|
||||||
|
const upRef = ref()
|
||||||
|
|
||||||
|
// 状态徽标文案与配色
|
||||||
|
const statusMeta = {
|
||||||
|
published: { label: '正常', type: 'success' },
|
||||||
|
disabled: { label: '禁用', type: 'warning' },
|
||||||
|
revoked: { label: '已下架', type: 'danger' },
|
||||||
|
}
|
||||||
|
|
||||||
|
function onFileChange(uploadFile) {
|
||||||
|
pfile.value = uploadFile.raw || null
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— 详情弹窗 ——
|
||||||
|
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 '无'
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— 编辑弹窗状态 ——
|
||||||
|
const editShow = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const edit = reactive({ pid: '', name: '', category: '', description: '', status: 'published', force_min: '', force_dl: '' })
|
||||||
|
function openEdit(row) {
|
||||||
|
edit.pid = row.id
|
||||||
|
edit.name = row.name || ''
|
||||||
|
edit.category = row.category || ''
|
||||||
|
edit.description = row.description || ''
|
||||||
|
edit.status = row.status || 'published'
|
||||||
|
edit.force_min = row.force_min_version || ''
|
||||||
|
edit.force_dl = toLocalInput(row.force_deadline)
|
||||||
|
editShow.value = true
|
||||||
|
}
|
||||||
|
// ISO 时间 → datetime-local 输入框可识别的本地格式
|
||||||
|
function toLocalInput(iso) {
|
||||||
|
if (!iso) return ''
|
||||||
|
const d = new Date(iso.endsWith('Z') ? iso : iso + 'Z')
|
||||||
|
return isNaN(d) ? '' : `${String(d.getFullYear()).padStart(4, '0')}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
async function saveEdit() {
|
||||||
|
if (!edit.pid) return
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
const body = { name: edit.name, category: edit.category, description: edit.description, status: edit.status }
|
||||||
|
// 强制更新:min 与 deadline 均填则成对下发;否则清除强制更新。
|
||||||
|
// 注意:后端 PluginPatchIn 的 str 字段不接受 null,空值必须传 ''(否则 422 保存失败)
|
||||||
|
body.force_min_version = edit.force_min || ''
|
||||||
|
body.force_deadline = edit.force_dl ? new Date(edit.force_dl).toISOString() : ''
|
||||||
|
body.clear_force = !(edit.force_min && edit.force_dl)
|
||||||
|
await adminPluginPatch(edit.pid, body)
|
||||||
|
message.success(`已更新插件 ${edit.pid}`)
|
||||||
|
editShow.value = false
|
||||||
|
await refresh()
|
||||||
|
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||||
|
finally { saving.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upload() {
|
||||||
|
if (!pid.value || !pver.value || !pfile.value) { message.warning('请填写插件 ID / 版本并选择 ZIP 包'); return }
|
||||||
|
uploading.value = true
|
||||||
|
try {
|
||||||
|
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.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>
|
||||||
|
.up-card, .list-card { padding: 20px 22px; }
|
||||||
|
.up-card .card-title { margin-bottom: 16px; }
|
||||||
|
.list-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||||
|
.list-head .card-title { margin-bottom: 0; }
|
||||||
|
.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-line { display: flex; gap: 10px; }
|
||||||
|
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||||
|
.cell-ops { display: flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||||
|
.cell-ops .el-button { padding: 0 4px; }
|
||||||
|
.cell-ops .el-button + .el-button { margin-left: 0; }
|
||||||
|
|
||||||
|
/* 弹窗通用 */
|
||||||
|
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||||
|
.form-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
|
||||||
|
.hint { font-size: 12px; color: var(--cp-ink-3); line-height: 1.7; }
|
||||||
|
|
||||||
|
/* 编辑弹窗:分区卡片 */
|
||||||
|
.ed-head { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.ed-avatar { width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center; color: #fff; font-size: 18px; font-weight: 800; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); box-shadow: var(--cp-shadow); flex-shrink: 0; }
|
||||||
|
.ed-headmeta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||||
|
.ed-title { font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||||
|
.ed-sub { font-size: 12px; color: var(--cp-ink-3); }
|
||||||
|
.ed-sec { margin-bottom: 12px; padding: 13px 16px 3px; background: var(--cp-panel-2); border-radius: 12px; }
|
||||||
|
.ed-sec :deep(.el-form-item) { margin-bottom: 13px; }
|
||||||
|
.ed-sec-title { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 800; color: var(--cp-ink-2); letter-spacing: .5px; margin-bottom: 10px; }
|
||||||
|
.ed-sec-title::before { content: ''; width: 3px; height: 13px; border-radius: 2px; background: var(--cp-blue); }
|
||||||
|
.ed-opt { font-weight: 500; color: var(--cp-ink-3); letter-spacing: 0; }
|
||||||
|
.force-box { display: flex; flex-direction: column; gap: 8px; padding-bottom: 13px; }
|
||||||
|
.force-line { display: flex; gap: 10px; }
|
||||||
|
|
||||||
|
/* 详情弹窗:头部 + 统计卡 + 分区 */
|
||||||
|
.plg-detail { display: flex; flex-direction: column; gap: 14px; max-height: 66vh; overflow-y: auto; padding-right: 6px; }
|
||||||
|
.dt-head { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.dt-avatar { width: 46px; height: 46px; border-radius: 13px; display: grid; place-items: center; color: #fff; font-size: 20px; font-weight: 800; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); box-shadow: var(--cp-shadow); flex-shrink: 0; }
|
||||||
|
.dt-headmeta { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||||
|
.dt-title-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.dt-id { font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||||
|
.dt-name { font-size: 13px; color: var(--cp-ink-2); }
|
||||||
|
.dt-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
|
||||||
|
.dt-item { display: flex; align-items: center; gap: 10px; padding: 12px 14px; background: var(--cp-panel-2); border-radius: 12px; min-width: 0; }
|
||||||
|
.dt-ic { font-size: 20px; color: var(--cp-ink-3); flex-shrink: 0; }
|
||||||
|
.dt-ic-on { color: var(--cp-amber); }
|
||||||
|
.dt-item div { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||||
|
.dt-item label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||||
|
.dt-item span { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.dt-sec { display: flex; flex-direction: column; }
|
||||||
|
.dt-desc { margin: 0; font-size: 13px; line-height: 1.9; color: var(--cp-ink); background: var(--cp-panel-2); padding: 12px 16px; border-radius: 10px; white-space: pre-wrap; word-break: break-word; }
|
||||||
|
.dt-cols { display: grid; grid-template-columns: 1.15fr .85fr; gap: 14px; align-items: start; }
|
||||||
|
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.vlist { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.vrow { display: flex; align-items: center; gap: 8px; padding: 7px 10px; background: var(--cp-panel-2); border-radius: 9px; }
|
||||||
|
.vtime { font-size: 12px; margin-left: auto; }
|
||||||
|
.dim-sm { color: var(--cp-ink-3); }
|
||||||
|
.dim { font-size: 12px; color: var(--cp-ink-3); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<div class="page-head cp-rise">
|
||||||
|
<div>
|
||||||
|
<h3>数据看板 <span class="badge">Stats</span></h3>
|
||||||
|
<p>运行统计 · 近 14 天趋势曲线 · 插件/用户排行 · 最近运行记录(分页)</p>
|
||||||
|
</div>
|
||||||
|
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="st">
|
||||||
|
<!-- KPI -->
|
||||||
|
<div class="kpis cp-rise">
|
||||||
|
<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 cp-rise chart-card">
|
||||||
|
<div class="card-title">近 14 天运行趋势 <span class="sub">成功 / 失败 · 平滑曲线</span></div>
|
||||||
|
<div ref="trendEl" class="chart"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 排行(两列左右分布) -->
|
||||||
|
<div class="rank-grid">
|
||||||
|
<div class="cp-card cp-rise rank-card">
|
||||||
|
<div class="card-title">插件排行 <span class="sub">按触发次数</span></div>
|
||||||
|
<ul class="rank" v-if="st.topPlugins.length">
|
||||||
|
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||||
|
<span class="rk" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||||
|
<div class="rbody">
|
||||||
|
<div class="rhead">
|
||||||
|
<span class="rname">{{ p.name }}</span>
|
||||||
|
<em>{{ p.runs }} 次</em>
|
||||||
|
</div>
|
||||||
|
<div class="rbar"><i :style="{ width: Math.round(p.runs / rankMax(st.topPlugins) * 100) + '%' }"></i></div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-else class="empty">暂无运行数据</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cp-card cp-rise rank-card">
|
||||||
|
<div class="card-title">活跃用户 <span class="sub">按执行次数</span></div>
|
||||||
|
<ul class="rank" v-if="st.topUsers.length">
|
||||||
|
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||||
|
<span class="rk" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||||
|
<div class="rbody">
|
||||||
|
<div class="rhead">
|
||||||
|
<span class="rname mono">{{ u.nickname ? `${u.nickname} · ${u.account}` : u.account }}</span>
|
||||||
|
<em>{{ u.runs }} 次</em>
|
||||||
|
</div>
|
||||||
|
<div class="rbar"><i :style="{ width: Math.round(u.runs / rankMax(st.topUsers) * 100) + '%' }"></i></div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-else class="empty">暂无执行记录</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 最近运行(后端分页) -->
|
||||||
|
<div class="page-head sub cp-rise">
|
||||||
|
<div><h4>最近运行</h4></div>
|
||||||
|
</div>
|
||||||
|
<div class="cp-card cp-rise recent-card">
|
||||||
|
<el-table :data="recent" size="small" v-loading="recentBusy" :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) }">{{ statusLabel(row.status) }}</span></span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="账号" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="mono">{{ row.nickname ? `${row.nickname} · ${row.account}` : (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="200" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }"><span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span></template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<PagerBar :total="recentTotal" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<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 { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
|
import { Refresh, User, Box, VideoPlay, CircleCheckFilled, CircleCloseFilled, Timer } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage as message } from 'element-plus'
|
||||||
|
// ECharts 按需引入(折线图),避免全量包
|
||||||
|
import * as echarts from 'echarts/core'
|
||||||
|
import { LineChart } from 'echarts/charts'
|
||||||
|
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
|
||||||
|
import { CanvasRenderer } from 'echarts/renderers'
|
||||||
|
echarts.use([LineChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||||
|
|
||||||
|
import { adminStats, adminReports } from '../api'
|
||||||
|
import { fmtTime } from '../format'
|
||||||
|
import PagerBar from '../components/PagerBar.vue'
|
||||||
|
|
||||||
|
const busy = ref(false)
|
||||||
|
const st = ref(null)
|
||||||
|
|
||||||
|
// 最近运行:独立走 /api/admin/reports 后端分页(数据增长无压力)
|
||||||
|
import { usePagedList } from '../composables/usePagedList'
|
||||||
|
const recentList = usePagedList((p, s) => adminReports(p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||||
|
const { items: recent, total: recentTotal, page, size: pageSize, busy: recentBusy, load: loadRecent, onPageChange } = recentList
|
||||||
|
|
||||||
|
const kpis = computed(() => {
|
||||||
|
if (!st.value) return []
|
||||||
|
const r = st.value
|
||||||
|
// 累计执行 = 成功 + 失败(已完成任务数,口径一致);触发数 start(含运行中/中断残留)不作为累计
|
||||||
|
const finished = (r.runs.success || 0) + (r.runs.failed || 0)
|
||||||
|
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: finished, 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 statusLabel(s) {
|
||||||
|
return ({ done: '成功', success: '成功', error: '失败', failed: '失败', running: '运行中', start: '已触发' })[s] || s
|
||||||
|
}
|
||||||
|
function fmtDur(sec) {
|
||||||
|
sec = +sec || 0
|
||||||
|
if (sec < 60) return sec + 's'
|
||||||
|
const m = Math.floor(sec / 60), s = sec % 60
|
||||||
|
if (m < 60) return `${m}m${s ? s + 's' : ''}`
|
||||||
|
const hh = Math.floor(m / 60)
|
||||||
|
return `${hh}h${m % 60}m`
|
||||||
|
}
|
||||||
|
const rankMax = list => Math.max(1, ...(list || []).map(x => x.runs || 1))
|
||||||
|
|
||||||
|
// ---------- ECharts 趋势曲线 ----------
|
||||||
|
const trendEl = ref(null)
|
||||||
|
let chart = null
|
||||||
|
|
||||||
|
function renderTrend() {
|
||||||
|
if (!st.value || !trendEl.value) return
|
||||||
|
if (!chart) chart = echarts.init(trendEl.value)
|
||||||
|
chart.setOption({
|
||||||
|
tooltip: { trigger: 'axis', backgroundColor: 'rgba(35,42,58,.92)', borderWidth: 0, textStyle: { color: '#fff', fontSize: 12 } },
|
||||||
|
legend: { data: ['成功', '失败'], right: 4, top: 0, icon: 'roundRect', itemWidth: 14, itemHeight: 5, textStyle: { color: '#6b7488', fontSize: 12 } },
|
||||||
|
grid: { left: 36, right: 16, top: 36, bottom: 24 },
|
||||||
|
xAxis: { type: 'category', boundaryGap: false, data: st.value.trend.map(t => t.day),
|
||||||
|
axisLine: { lineStyle: { color: 'rgba(35,42,58,.16)' } }, axisTick: { show: false },
|
||||||
|
axisLabel: { fontSize: 10.5, color: '#9aa2b4' } },
|
||||||
|
yAxis: { type: 'value', minInterval: 1, splitLine: { lineStyle: { color: 'rgba(35,42,58,.07)' } },
|
||||||
|
axisLabel: { fontSize: 10.5, color: '#9aa2b4' } },
|
||||||
|
series: [
|
||||||
|
{ name: '成功', type: 'line', smooth: true, symbolSize: 6, data: st.value.trend.map(t => t.success || 0),
|
||||||
|
lineStyle: { width: 2.6, color: '#1d9d5c' }, itemStyle: { color: '#1d9d5c' },
|
||||||
|
areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
|
||||||
|
{ offset: 0, color: 'rgba(29,157,92,.20)' }, { offset: 1, color: 'rgba(29,157,92,.01)' }] } } },
|
||||||
|
{ name: '失败', type: 'line', smooth: true, symbolSize: 6, data: st.value.trend.map(t => t.failed || 0),
|
||||||
|
lineStyle: { width: 2.6, color: '#d6453d' }, itemStyle: { color: '#d6453d' },
|
||||||
|
areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
|
||||||
|
{ offset: 0, color: 'rgba(214,69,61,.16)' }, { offset: 1, color: 'rgba(214,69,61,.01)' }] } } },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
watch(st, () => nextTick(renderTrend))
|
||||||
|
const onResize = () => chart && chart.resize()
|
||||||
|
|
||||||
|
// ---------- 数据 ----------
|
||||||
|
async function refresh() {
|
||||||
|
busy.value = true
|
||||||
|
try {
|
||||||
|
const r = await adminStats()
|
||||||
|
st.value = {
|
||||||
|
users: r.users || {}, plugins: r.plugins || {}, runs: r.runs || {},
|
||||||
|
trend: r.trend || [], topPlugins: r.topPlugins || [], topUsers: r.topUsers || [],
|
||||||
|
}
|
||||||
|
await loadRecent()
|
||||||
|
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||||
|
finally { busy.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { refresh(); window.addEventListener('resize', onResize) })
|
||||||
|
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); chart && chart.dispose(); chart = null })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
/* 趋势图全宽置顶 */
|
||||||
|
.chart-card { padding: 20px; margin-bottom: 18px; }
|
||||||
|
.chart { height: 320px; }
|
||||||
|
|
||||||
|
/* 排行两列左右分布 */
|
||||||
|
.rank-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||||
|
@media (max-width: 900px) { .rank-grid { grid-template-columns: 1fr; } }
|
||||||
|
.rank-card { padding: 20px; }
|
||||||
|
.card-title { margin-bottom: 14px; }
|
||||||
|
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||||
|
|
||||||
|
.rank { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.rank li { display: flex; align-items: center; gap: 11px; padding: 7px 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; display: flex; }
|
||||||
|
.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); font-size: 12px; }
|
||||||
|
.status-dot { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; }
|
||||||
|
.status-dot i { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
|
||||||
|
</style>
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
|
||||||
|
// dev 时把 /api 代理到控制面后端(8800),实现前后端分离开发;生产由 FastAPI 挂载 dist
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
strictPort: true,
|
||||||
|
proxy: {
|
||||||
|
'/api': { target: 'http://127.0.0.1:8800', changeOrigin: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
build: {
|
||||||
|
outDir: 'dist',
|
||||||
|
emptyOutDir: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"version": "1.0.0",
|
||||||
|
"filename": "setup-37du-host-1.0.0.exe",
|
||||||
|
"sha256": "57ee9cb4d10b25914276a277bfe42b0751f4c26c3c408af1293f723c7b4488a0",
|
||||||
|
"notes": "初始版本"
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""controlplane 运维/构建工具集(CLI、数据库迁移、Windows 防火墙脚本)。"""
|
||||||
@@ -0,0 +1,585 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。
|
||||||
|
|
||||||
|
用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可:
|
||||||
|
- 发布 / 删除插件包(按最近 3 版自动裁剪保留)
|
||||||
|
- 变更插件状态(published / disabled / revoked)与强制更新阈值
|
||||||
|
- 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号
|
||||||
|
- 按账号授予 / 撤销插件与平台权限
|
||||||
|
- 发布执行机壳子(主程序)新版安装包 / 大文件源(shell、chrome 等,先传内网文件服务器再登记中心机)
|
||||||
|
- 查看插件 / 账号 / 运行统计 / 连通性预检
|
||||||
|
|
||||||
|
鉴权:
|
||||||
|
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||||
|
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||||
|
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||||
|
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||||
|
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||||
|
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||||
|
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||||
|
|
||||||
|
管理员账号:默认 puddy(可用 --admin 或环境变量 AGENT_ADMIN_ACCOUNT 覆盖),该账号须 is_admin=1。
|
||||||
|
密码:--password 或环境变量 AGENT_ADMIN_PASSWORD(与中心机管理台一致,如 123456)。
|
||||||
|
|
||||||
|
agent 友好:
|
||||||
|
- 全局 --json:列表/统计/执行结果以 JSON 输出,便于 agent 机器解析
|
||||||
|
- ping:连通性与健康预检(发版前先确认中心机在线)
|
||||||
|
- file push / rm 支持 --fs-base/--fs-token 覆盖文件服务器地址(默认读 controlplane/.env)
|
||||||
|
|
||||||
|
运行(项目 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||||
|
python -m controlplane.tools.agent_cli --admin puddy --password 123456 ping
|
||||||
|
python -m controlplane.tools.agent_cli --admin puddy --password 123456 publish plugin.zip --id report --version 1.2.0
|
||||||
|
python -m controlplane.tools.agent_cli --admin puddy --password 123456 --json plugins
|
||||||
|
python -m controlplane.tools.agent_cli --admin puddy --password 123456 grant alice report # 默认授予 download+run
|
||||||
|
python -m controlplane.tools.agent_cli --admin puddy --password 123456 file push setup.exe --category shell --version 2.1.0
|
||||||
|
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_dotenv() -> None:
|
||||||
|
"""读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。"""
|
||||||
|
env_path = APP_DIR / ".env"
|
||||||
|
if not env_path.is_file():
|
||||||
|
return
|
||||||
|
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||||
|
_line = _ln.strip()
|
||||||
|
if not _line or _line.startswith("#") or "=" not in _line:
|
||||||
|
continue
|
||||||
|
_k, _v = _line.split("=", 1)
|
||||||
|
k, v = _k.strip(), _v.strip()
|
||||||
|
if k and k not in os.environ:
|
||||||
|
os.environ[k] = v
|
||||||
|
|
||||||
|
|
||||||
|
_load_dotenv()
|
||||||
|
|
||||||
|
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||||
|
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||||
|
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||||
|
# 内网文件服务器:上传直链来源(复用 controlplane/.env;可用 file 子命令的 --fs-base/--fs-token 覆盖)
|
||||||
|
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||||
|
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||||
|
|
||||||
|
|
||||||
|
def _admin_secret() -> str:
|
||||||
|
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||||
|
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||||
|
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||||
|
if cand:
|
||||||
|
return cand
|
||||||
|
_f = APP_DIR / ".admin_secret"
|
||||||
|
if _f.is_file():
|
||||||
|
return _f.read_text(encoding="utf-8").strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _mint_admin_token(account: str, secret: str) -> str:
|
||||||
|
"""临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。"""
|
||||||
|
payload = base64.urlsafe_b64encode(
|
||||||
|
json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode()
|
||||||
|
).decode().rstrip("=")
|
||||||
|
sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||||
|
return f"{payload}.{sig}"
|
||||||
|
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||||
|
|
||||||
|
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||||
|
self.base = base
|
||||||
|
self.api_token = api_token
|
||||||
|
self.admin = admin
|
||||||
|
self.secret = secret
|
||||||
|
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||||
|
|
||||||
|
def _headers(self, json_body: bool = True) -> dict:
|
||||||
|
h = {}
|
||||||
|
if self.api_token:
|
||||||
|
h["X-API-Token"] = self.api_token
|
||||||
|
if self.admin and self.token:
|
||||||
|
h["X-Admin-Token"] = self.token
|
||||||
|
elif self.admin and self.secret:
|
||||||
|
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||||
|
if json_body:
|
||||||
|
h["Content-Type"] = "application/json"
|
||||||
|
return h
|
||||||
|
|
||||||
|
def call(self, method: str, path: str, json_body: Optional[dict] = None,
|
||||||
|
_hdrs_json: Optional[bool] = None) -> dict:
|
||||||
|
import requests
|
||||||
|
url = self.base + path # path 已是完整路径(含 query)
|
||||||
|
try:
|
||||||
|
if json_body is not None:
|
||||||
|
r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30)
|
||||||
|
else:
|
||||||
|
r = requests.request(method, url, headers=self._headers(False), timeout=30)
|
||||||
|
except requests.ConnectionError as exc:
|
||||||
|
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。")
|
||||||
|
try:
|
||||||
|
data = r.json()
|
||||||
|
except ValueError:
|
||||||
|
data = {"raw": r.text[:300]}
|
||||||
|
if r.status_code >= 400:
|
||||||
|
detail = data.get("detail") if isinstance(data, dict) else data
|
||||||
|
if isinstance(detail, dict):
|
||||||
|
detail = detail.get("msg") or detail
|
||||||
|
raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}")
|
||||||
|
return data if isinstance(data, dict) else {"result": data}
|
||||||
|
|
||||||
|
def ping(self) -> dict:
|
||||||
|
"""连通性与健康预检:GET /(无鉴权)。"""
|
||||||
|
import requests
|
||||||
|
try:
|
||||||
|
r = requests.get(f"{self.base}/", timeout=10)
|
||||||
|
except requests.ConnectionError as exc:
|
||||||
|
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。")
|
||||||
|
try:
|
||||||
|
return r.json()
|
||||||
|
except ValueError:
|
||||||
|
return {"http": r.status_code, "raw": r.text[:200]}
|
||||||
|
|
||||||
|
def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict:
|
||||||
|
import requests
|
||||||
|
import urllib.parse
|
||||||
|
qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version})
|
||||||
|
with open(path, "rb") as fp:
|
||||||
|
r = requests.post(f"{self.base}/api/admin/pkg?{qs}",
|
||||||
|
headers=self._headers(False),
|
||||||
|
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||||
|
timeout=60)
|
||||||
|
try:
|
||||||
|
data = r.json()
|
||||||
|
except ValueError:
|
||||||
|
data = {"raw": r.text[:300]}
|
||||||
|
if r.status_code >= 400:
|
||||||
|
detail = data.get("detail") if isinstance(data, dict) else data
|
||||||
|
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||||
|
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||||
|
import requests
|
||||||
|
import urllib.parse
|
||||||
|
qs = urllib.parse.urlencode({"version": version, "notes": notes, "sha256": sha256})
|
||||||
|
with open(path, "rb") as fp:
|
||||||
|
r = requests.post(f"{self.base}/api/admin/shell-release?{qs}",
|
||||||
|
headers=self._headers(False),
|
||||||
|
files={"upload": (Path(path).name, fp, "application/octet-stream")},
|
||||||
|
timeout=600)
|
||||||
|
try:
|
||||||
|
data = r.json()
|
||||||
|
except ValueError:
|
||||||
|
data = {"raw": r.text[:300]}
|
||||||
|
if r.status_code >= 400:
|
||||||
|
detail = data.get("detail") if isinstance(data, dict) else data
|
||||||
|
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------ 输出辅助 ------------------------------
|
||||||
|
def _emit(args: argparse.Namespace, obj: dict, human: str) -> None:
|
||||||
|
"""--json 时输出机器可读 JSON,否则输出人类可读文本。"""
|
||||||
|
if getattr(args, "json", False):
|
||||||
|
print(json.dumps(obj, ensure_ascii=False, indent=2))
|
||||||
|
else:
|
||||||
|
print(human)
|
||||||
|
|
||||||
|
|
||||||
|
def _plugin_rows(plugins) -> None:
|
||||||
|
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||||
|
rows = plugins if isinstance(plugins, list) else \
|
||||||
|
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||||
|
if not rows:
|
||||||
|
print("(暂无插件)")
|
||||||
|
return
|
||||||
|
print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数")
|
||||||
|
for p in rows:
|
||||||
|
if not isinstance(p, dict):
|
||||||
|
continue
|
||||||
|
print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}"
|
||||||
|
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||||
|
|
||||||
|
|
||||||
|
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||||
|
"""file push / list / rm:内网大文件源管理。"""
|
||||||
|
try:
|
||||||
|
import requests as _rq
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||||
|
fcmd = args.file_cmd
|
||||||
|
|
||||||
|
if fcmd == "push":
|
||||||
|
path = Path(args.path)
|
||||||
|
if not path.is_file():
|
||||||
|
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||||
|
fs_base = (getattr(args, "fs_base", "") or FILESERVER_BASE_URL).rstrip("/")
|
||||||
|
fs_token = getattr(args, "fs_token", "") or FILESERVER_TOKEN
|
||||||
|
if not fs_base or not fs_token:
|
||||||
|
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||||
|
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN,或用 --fs-base/--fs-token 指定。")
|
||||||
|
# 第一步:传到文件服务器
|
||||||
|
try:
|
||||||
|
with open(path, "rb") as fp:
|
||||||
|
r = _rq.post(f"{fs_base}/api/upload",
|
||||||
|
headers={"X-API-Token": fs_token},
|
||||||
|
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||||
|
timeout=600)
|
||||||
|
except _rq.ConnectionError as exc:
|
||||||
|
raise SystemExit(f"[x] 无法连接内网文件服务器 {fs_base}({exc})")
|
||||||
|
if r.status_code >= 400:
|
||||||
|
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||||
|
up = r.json()
|
||||||
|
url = up.get("url", "")
|
||||||
|
if not url:
|
||||||
|
raise SystemExit("[x] 文件服务器未返回 url")
|
||||||
|
sha256 = args.sha256 or up.get("sha256", "")
|
||||||
|
# 第二步:登记到中心机 file_sources
|
||||||
|
body = {"category": args.category, "version": args.version,
|
||||||
|
"filename": up.get("filename", path.name), "url": url,
|
||||||
|
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||||
|
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||||
|
_emit(args, {"ok": True, "category": args.category, "version": args.version,
|
||||||
|
"filename": path.name, "url": url, "sha256": sha256,
|
||||||
|
"file_source_id": rec.get("id")},
|
||||||
|
f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}\n"
|
||||||
|
f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if fcmd == "list":
|
||||||
|
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||||
|
files = data.get("items") or [] # 管理端返回 items/total(旧版误读 files 导致恒为空)
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps({"files": files}, ensure_ascii=False, indent=2))
|
||||||
|
return 0
|
||||||
|
if not files:
|
||||||
|
print("(暂无大文件源)")
|
||||||
|
return 0
|
||||||
|
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||||
|
for f in files:
|
||||||
|
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||||
|
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||||
|
f"{f.get('filename') or ''}")
|
||||||
|
print(f" {f.get('url') or ''}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if fcmd == "rm":
|
||||||
|
rec_url = ""
|
||||||
|
if getattr(args, "purge", False):
|
||||||
|
fs_base = (getattr(args, "fs_base", "") or FILESERVER_BASE_URL).rstrip("/")
|
||||||
|
fs_token = getattr(args, "fs_token", "") or FILESERVER_TOKEN
|
||||||
|
data = c.call("GET", "/api/admin/file-sources", None, False)
|
||||||
|
for f in (data.get("items") or []):
|
||||||
|
if int(f.get("id") or 0) == args.id:
|
||||||
|
rec_url = f.get("url") or ""
|
||||||
|
break
|
||||||
|
if not rec_url:
|
||||||
|
raise SystemExit(f"[x] 未找到登记 id={args.id}(无法 purge,请先 file list 确认 id)")
|
||||||
|
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||||
|
_emit(args, {"ok": True, "removed_id": args.id, "purged": bool(getattr(args, "purge", False))},
|
||||||
|
f"[ok] 已删除登记 id={args.id}")
|
||||||
|
if getattr(args, "purge", False):
|
||||||
|
m = re.search(r"/files/([A-Za-z0-9_-]{1,64})", rec_url)
|
||||||
|
if not m:
|
||||||
|
print(f"[warn] 无法从 url 解析 fid({rec_url}),未删除文件服务器文件")
|
||||||
|
return 0
|
||||||
|
fid = m.group(1)
|
||||||
|
try:
|
||||||
|
rr = _rq.delete(f"{fs_base}/api/files/{fid}",
|
||||||
|
headers={"X-API-Token": fs_token}, timeout=30)
|
||||||
|
if rr.status_code < 400:
|
||||||
|
print(f"[ok] 已从文件服务器删除文件 {fid}")
|
||||||
|
else:
|
||||||
|
print(f"[warn] 文件服务器删除失败 HTTP {rr.status_code}:{rr.text[:150]}")
|
||||||
|
except _rq.ConnectionError as exc:
|
||||||
|
print(f"[warn] 无法连接文件服务器删除文件:{exc}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||||
|
|
||||||
|
|
||||||
|
# ================================ main ================================
|
||||||
|
def _build_parser() -> argparse.ArgumentParser:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="agent_cli",
|
||||||
|
description="37du 中心机 · agent 插件发布与管理 CLI",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||||
|
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", "puddy"),
|
||||||
|
help="管理员账号(默认 puddy,须 is_admin=1)")
|
||||||
|
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||||
|
dest="admin_password",
|
||||||
|
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||||
|
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||||
|
parser.add_argument("--json", action="store_true", help="结果以 JSON 输出(便于 agent 机器解析)")
|
||||||
|
sub = parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
|
p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)")
|
||||||
|
p_pub.add_argument("pkg", help="插件 zip 路径")
|
||||||
|
p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)")
|
||||||
|
p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)")
|
||||||
|
p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0")
|
||||||
|
|
||||||
|
sub.add_parser("plugins", help="列出插件清单")
|
||||||
|
|
||||||
|
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||||
|
p_del.add_argument("plugin_id")
|
||||||
|
|
||||||
|
p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值")
|
||||||
|
p_status.add_argument("plugin_id")
|
||||||
|
p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="",
|
||||||
|
help="新状态(留空不改变)")
|
||||||
|
p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)")
|
||||||
|
p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)")
|
||||||
|
p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置")
|
||||||
|
|
||||||
|
sub.add_parser("users", help="列出账号清单")
|
||||||
|
|
||||||
|
p_user = sub.add_parser("user-add", help="新建账号")
|
||||||
|
p_user.add_argument("account")
|
||||||
|
p_user.add_argument("--password", required=True)
|
||||||
|
p_user.add_argument("--dept", default="")
|
||||||
|
p_user.add_argument("--nickname", default="")
|
||||||
|
p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员")
|
||||||
|
|
||||||
|
p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)")
|
||||||
|
p_upd.add_argument("account")
|
||||||
|
p_upd.add_argument("--dept", default=None)
|
||||||
|
p_upd.add_argument("--nickname", default=None)
|
||||||
|
p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"),
|
||||||
|
default=None)
|
||||||
|
|
||||||
|
p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码")
|
||||||
|
p_rp.add_argument("account")
|
||||||
|
p_rp.add_argument("--password", required=True)
|
||||||
|
|
||||||
|
p_del_u = sub.add_parser("user-del", help="删除账号")
|
||||||
|
p_del_u.add_argument("account")
|
||||||
|
|
||||||
|
p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)")
|
||||||
|
p_grant.add_argument("account")
|
||||||
|
p_grant.add_argument("plugin_id")
|
||||||
|
p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限")
|
||||||
|
p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限")
|
||||||
|
|
||||||
|
p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限")
|
||||||
|
p_revoke.add_argument("account")
|
||||||
|
p_revoke.add_argument("plugin_id")
|
||||||
|
|
||||||
|
p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限")
|
||||||
|
p_gp.add_argument("account")
|
||||||
|
p_gp.add_argument("platform_id")
|
||||||
|
|
||||||
|
p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限")
|
||||||
|
p_rp_plt.add_argument("account")
|
||||||
|
p_rp_plt.add_argument("platform_id")
|
||||||
|
|
||||||
|
sub.add_parser("ping", help="中心机连通性与健康检查(GET /)")
|
||||||
|
sub.add_parser("stats", help="运行统计看板")
|
||||||
|
|
||||||
|
sub.add_parser("me", help="校验当前管理身份")
|
||||||
|
|
||||||
|
p_shell = sub.add_parser("shell-release", help="发布执行机壳子新版安装包(更新 shell 源 + version.json)")
|
||||||
|
p_shell.add_argument("pkg", help="新安装包路径(setup-37du-host-<v>.exe)")
|
||||||
|
p_shell.add_argument("--version", required=True, help="壳子版本号(须高于执行机本地 shell.version)")
|
||||||
|
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||||
|
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||||
|
|
||||||
|
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||||
|
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||||
|
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||||
|
p_fpush.add_argument("path", help="本地文件路径")
|
||||||
|
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||||
|
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||||
|
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||||
|
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||||
|
p_fpush.add_argument("--fs-base", default="", help="文件服务器地址(默认 controlplane/.env 的 FILESERVER_BASE_URL)")
|
||||||
|
p_fpush.add_argument("--fs-token", default="", help="文件服务器 token(默认 controlplane/.env 的 FILESERVER_TOKEN)")
|
||||||
|
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||||
|
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||||
|
p_frm = file_sub.add_parser("rm", help="删除中心机登记(--purge 连内网服务器文件一起删)")
|
||||||
|
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||||
|
p_frm.add_argument("--purge", action="store_true", help="同时从内网文件服务器删除实际文件")
|
||||||
|
p_frm.add_argument("--fs-base", default="", help="文件服务器地址(默认 controlplane/.env 的 FILESERVER_BASE_URL)")
|
||||||
|
p_frm.add_argument("--fs-token", default="", help="文件服务器 token(默认 controlplane/.env 的 FILESERVER_TOKEN)")
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def _run(args: argparse.Namespace) -> int:
|
||||||
|
if not args.admin:
|
||||||
|
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||||
|
if args.admin_password.strip():
|
||||||
|
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||||
|
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||||
|
r = c.call("POST", "/api/admin/auth",
|
||||||
|
{"account": args.admin, "password": args.admin_password})
|
||||||
|
if not r.get("token"):
|
||||||
|
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||||
|
if not r.get("is_admin"):
|
||||||
|
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||||
|
c.token = str(r["token"])
|
||||||
|
if not args.json:
|
||||||
|
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||||
|
else:
|
||||||
|
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||||
|
secret = _admin_secret()
|
||||||
|
if not secret:
|
||||||
|
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||||
|
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||||
|
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||||
|
cmd = args.command
|
||||||
|
|
||||||
|
if cmd == "ping":
|
||||||
|
data = c.ping()
|
||||||
|
_emit(args, {"ok": True, "base": args.base, **data},
|
||||||
|
f"[ok] 中心机在线 {args.base}:{data.get('service') or ''} v{data.get('version') or ''}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if cmd == "shell-release":
|
||||||
|
r = c.shell_release(args.pkg, args.version, args.notes, args.sha256)
|
||||||
|
_emit(args, {"ok": True, "version": r.get("version"), "filename": r.get("filename"),
|
||||||
|
"sha256": r.get("sha256", "")},
|
||||||
|
f"[ok] 已发布壳子 v{r.get('version')} → {r.get('filename')}\n"
|
||||||
|
f" sha256={str(r.get('sha256') or '')[:16]}… notes={args.notes or '(无)'}\n"
|
||||||
|
f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if cmd == "file":
|
||||||
|
return _run_file(args, c)
|
||||||
|
|
||||||
|
if cmd == "publish":
|
||||||
|
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||||
|
_emit(args, {"ok": True, "plugin_id": r.get("plugin_id"), "version": r.get("version"),
|
||||||
|
"filename": r.get("filename")},
|
||||||
|
f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||||
|
|
||||||
|
elif cmd == "plugins":
|
||||||
|
data = c.call("GET", "/api/admin/overview")
|
||||||
|
rows = data.get("plugins", {})
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps(rows, ensure_ascii=False, indent=2))
|
||||||
|
else:
|
||||||
|
_plugin_rows(rows)
|
||||||
|
|
||||||
|
elif cmd == "plugin-del":
|
||||||
|
r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id})
|
||||||
|
_emit(args, {"ok": True, "plugin_id": r.get("plugin_id")},
|
||||||
|
f"[ok] 已删除插件 {r.get('plugin_id')}")
|
||||||
|
|
||||||
|
elif cmd == "plugin-status":
|
||||||
|
import urllib.parse as _q
|
||||||
|
body = {}
|
||||||
|
if args.status:
|
||||||
|
body["status"] = args.status
|
||||||
|
if args.force_min_version and args.force_deadline:
|
||||||
|
body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline})
|
||||||
|
elif args.clear_force:
|
||||||
|
body["clear_force"] = True
|
||||||
|
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||||
|
_emit(args, {"ok": True, **r}, "[ok] " + json.dumps(r, ensure_ascii=False))
|
||||||
|
|
||||||
|
elif cmd == "users":
|
||||||
|
data = c.call("GET", "/api/admin/accounts")
|
||||||
|
accounts = data.get("accounts", "")
|
||||||
|
if isinstance(accounts, dict):
|
||||||
|
accounts = list(accounts.values())
|
||||||
|
accounts = [a for a in (accounts or []) if isinstance(a, dict)]
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps({"accounts": accounts}, ensure_ascii=False, indent=2))
|
||||||
|
return 0
|
||||||
|
if not accounts:
|
||||||
|
print("(暂无账号)")
|
||||||
|
return 0
|
||||||
|
print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}")
|
||||||
|
for a in accounts:
|
||||||
|
print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}"
|
||||||
|
f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}")
|
||||||
|
|
||||||
|
elif cmd == "user-add":
|
||||||
|
r = c.call("POST", "/api/admin/account", {
|
||||||
|
"account": args.account, "password": args.password,
|
||||||
|
"dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account"), "is_admin": r.get("is_admin")},
|
||||||
|
f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else ""))
|
||||||
|
|
||||||
|
elif cmd == "user-update":
|
||||||
|
body = {"account": args.account}
|
||||||
|
for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)):
|
||||||
|
if v is not None:
|
||||||
|
body[k] = v
|
||||||
|
r = c.call("POST", "/api/admin/account/update", body)
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account")}, f"[ok] 已更新 {r.get('account')}")
|
||||||
|
|
||||||
|
elif cmd == "user-reset-pwd":
|
||||||
|
r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account")}, f"[ok] 已重置 {r.get('account')} 密码")
|
||||||
|
|
||||||
|
elif cmd == "user-del":
|
||||||
|
r = c.call("POST", "/api/admin/account/delete", {"account": args.account})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account")}, f"[ok] 已删除账号 {r.get('account')}")
|
||||||
|
|
||||||
|
elif cmd == "grant":
|
||||||
|
r = c.call("POST", "/api/admin/account_plugins", {
|
||||||
|
"account": args.account, "plugin_id": args.plugin_id, "granted": True,
|
||||||
|
"can_download": not args.no_download, "can_run": not args.no_run})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account"), "plugin_id": r.get("plugin_id"),
|
||||||
|
"can_download": not args.no_download, "can_run": not args.no_run},
|
||||||
|
f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}"
|
||||||
|
f"/run={'y' if not args.no_run else 'n'})")
|
||||||
|
|
||||||
|
elif cmd == "revoke":
|
||||||
|
r = c.call("POST", "/api/admin/account_plugins", {
|
||||||
|
"account": args.account, "plugin_id": args.plugin_id, "granted": False})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account"), "plugin_id": r.get("plugin_id")},
|
||||||
|
f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}")
|
||||||
|
|
||||||
|
elif cmd == "grant-platform":
|
||||||
|
r = c.call("POST", "/api/admin/account_platforms", {
|
||||||
|
"account": args.account, "platform_id": args.platform_id, "granted": True})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account"), "platform_id": r.get("platform_id")},
|
||||||
|
f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||||
|
|
||||||
|
elif cmd == "revoke-platform":
|
||||||
|
r = c.call("POST", "/api/admin/account_platforms", {
|
||||||
|
"account": args.account, "platform_id": args.platform_id, "granted": False})
|
||||||
|
_emit(args, {"ok": True, "account": r.get("account"), "platform_id": r.get("platform_id")},
|
||||||
|
f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||||
|
|
||||||
|
elif cmd == "stats":
|
||||||
|
data = c.call("GET", "/api/admin/stats")
|
||||||
|
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||||
|
|
||||||
|
elif cmd == "me":
|
||||||
|
data = c.call("GET", "/api/admin/me")
|
||||||
|
_emit(args, {"account": data.get("account"), "is_admin": data.get("is_admin"),
|
||||||
|
"dept": data.get("dept") or ""},
|
||||||
|
f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} "
|
||||||
|
f"部门:{data.get('dept') or ''}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
args = _build_parser().parse_args()
|
||||||
|
try:
|
||||||
|
_run(args)
|
||||||
|
except SystemExit as exc:
|
||||||
|
if exc.code:
|
||||||
|
print(str(exc.code))
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
@echo off
|
||||||
|
rem ============================================================
|
||||||
|
rem 37du center control-plane firewall script
|
||||||
|
rem opens TCP port 8800. Run as Administrator.
|
||||||
|
rem ============================================================
|
||||||
|
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||||
|
|
||||||
|
netsh advfirewall firewall delete rule name="37du-center-8800" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-8800" dir=in action=allow protocol=TCP localport=8800
|
||||||
|
|
||||||
|
echo [OK] Firewall rule created: TCP 8800 open.
|
||||||
|
pause
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
@echo off
|
||||||
|
rem ============================================================
|
||||||
|
rem 37du center SMB firewall script
|
||||||
|
rem opens SMB/NetBIOS ports so the deploy machine can reach
|
||||||
|
rem the \\...\code share. Run as Administrator.
|
||||||
|
rem ============================================================
|
||||||
|
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||||
|
|
||||||
|
netsh advfirewall firewall delete rule name="37du-center-smb445" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-smb445" dir=in action=allow protocol=TCP localport=445
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-smb445udp" dir=in action=allow protocol=UDP localport=445
|
||||||
|
|
||||||
|
netsh advfirewall firewall delete rule name="37du-center-nb139" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-nb139" dir=in action=allow protocol=TCP localport=139
|
||||||
|
netsh advfirewall firewall delete rule name="37du-center-nb137" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-nb137" dir=in action=allow protocol=UDP localport=137
|
||||||
|
netsh advfirewall firewall delete rule name="37du-center-nb138" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-nb138" dir=in action=allow protocol=UDP localport=138
|
||||||
|
netsh advfirewall firewall delete rule name="37du-center-nb135" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="37du-center-nb135" dir=in action=allow protocol=UDP localport=135
|
||||||
|
|
||||||
|
echo [OK] Firewall rules created: SMB/NetBIOS open.
|
||||||
|
pause
|
||||||
@@ -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())
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- 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='系统级键值配置';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS client_creds (
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||||
|
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||||
|
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (account)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS file_sources (
|
||||||
|
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||||
|
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||||
|
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||||
|
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||||
|
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||||
|
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||||
|
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
KEY idx_category (category)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 云端会话令牌:落库共享(gunicorn 多 worker 下 Bearer 身份解析通用)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||||
|
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||||
|
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||||
|
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||||
|
PRIMARY KEY (token),
|
||||||
|
KEY idx_expires (expires_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 一次性插件下载票据:落库共享,多 worker 通用(进程内存版在 4 worker 下 3/4 概率查不到票据)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||||
|
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||||
|
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||||
|
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||||
|
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||||
|
PRIMARY KEY (nonce),
|
||||||
|
KEY idx_created (created_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 壳子定时任务配置备份:执行机变更后全量推送,仅存数据防丢失(不做管理界面)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS schedule_backups (
|
||||||
|
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',
|
||||||
|
data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (account)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 内网文件服务器状态:心跳上报 + 离线监控(超时判离线并钉钉告警)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS fileserver_status (
|
||||||
|
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||||
|
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
|
||||||
|
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
|
||||||
|
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||||
|
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||||
|
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
|
||||||
|
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
|
||||||
|
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
|
||||||
|
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
|
||||||
|
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
|
||||||
|
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
|
||||||
|
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
|
||||||
|
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
|
||||||
|
offline_notified TINYINT(1) NOT NULL DEFAULT 0 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_host (host),
|
||||||
|
KEY idx_status (status),
|
||||||
|
KEY idx_last_seen (last_seen)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)';
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# 37du Electron 壳:开发环境配置(拷贝为 .env 并修改)
|
||||||
|
# =============================================================
|
||||||
|
# 服务端地址(中心机控制面)
|
||||||
|
CONTROLPLANE_URL=http://117.72.191.188:8800
|
||||||
|
|
||||||
|
# 内部凭证(与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 保持一致;非空时发 X-API-Token)
|
||||||
|
CONTROLPLANE_TOKEN=
|
||||||
|
|
||||||
|
# 插件执行子进程的 Python 解释器(解析优先级:本变量 > 环境包 python-env/current.json > 系统 python)
|
||||||
|
# 开发推荐显式指定项目 .venv;正式打包后不设即可自动使用随包/下发的环境包
|
||||||
|
# PYTHON_EXE=D:\work\code\37duAutomation\.venv\Scripts\python.exe
|
||||||
|
|
||||||
|
# 环境包目录的显式覆盖(默认:打包态 exe 同级 python-env/;dev electron-shell/python-env/)
|
||||||
|
# SHELL_PYTHON_ENV_ROOT=D:\work\code\37duAutomation\desktop\electron-shell\python-env
|
||||||
|
|
||||||
|
# 插件执行超时(秒,浏览器类默认 30min)
|
||||||
|
RUN_TIMEOUT=1800
|
||||||
|
|
||||||
|
# 插件进程作业级内存上限(MB,环境包模式经 job_guard/Job Object 生效,默认 2048)
|
||||||
|
# RUN_MAX_MEM_MB=2048
|
||||||
|
|
||||||
|
# 调试:1 开启完整 JSON 调试日志
|
||||||
|
# DEBUG=1
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
node_modules/
|
||||||
|
dist-app/
|
||||||
|
renderer/dist/
|
||||||
|
*.log
|
||||||
|
_cp_sessions.json
|
||||||
|
.env
|
||||||
|
|
||||||
|
# 便携 Python 环境包产物(体积大,构建/下载生成,不入库)
|
||||||
|
build/
|
||||||
|
dist-env/
|
||||||
|
python-env/
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
# 37du 执行机客户端(Node/Electron 版)
|
||||||
|
|
||||||
|
替代旧 Python `desktop/webhost/` 底座的新一代执行机客户端。**换壳不换插件**:
|
||||||
|
- 壳与底座:Electron + Node.js(主进程纯 Node,可无 Electron 运行)
|
||||||
|
- 插件执行机制:**保持 Python**,Node 壳负责生命周期/调度/权限,以子进程跑 `plugin_runner.py`(协议逐字节兼容)
|
||||||
|
- 服务端契约:以 [docs/桌面端/Node版客户端开发交接文档.md](../../docs/桌面端/Node版客户端开发交接文档.md) §5 为准,向后兼容,不改服务端公开接口
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
desktop/electron-shell/
|
||||||
|
├── package.json # 依赖 ws(WS 服务) / adm-zip(插件包解压);devDeps electron
|
||||||
|
├── .env # 本模块配置(CONTROLPLANE_URL/TOKEN、PYTHON_EXE、RUN_TIMEOUT)
|
||||||
|
├── .env.example # 配置样例
|
||||||
|
├── frontend/ # 壳自有的 Vue3 前端源码(从 webhost/frontend 复制独立演进,老版本不受影响)
|
||||||
|
│ └── src/ # - style.css:设计令牌(token 层)+ [data-skin] 皮肤机制,默认 cream 奶油风
|
||||||
|
│ # - main.js:皮肤应用(localStorage['37du.skin'])+ 涂鸦装饰层(localStorage['37du.doodles'])
|
||||||
|
│ # - components/LoginPage.vue:登录页(浅天蓝强调 + 手写标题字体)
|
||||||
|
├── renderer/dist/ # 前端构建产物(npm run copy-renderer 从 frontend/ 构建,自包含)
|
||||||
|
├── scripts/
|
||||||
|
│ ├── copy-renderer.ps1 # 构建 frontend/ → renderer/dist
|
||||||
|
│ └── build-python-env.ps1 # 构建便携 Python 环境包(python-env-<ver>.zip + 本地安装)
|
||||||
|
├── python-env/ # 便携 Python 环境包(build-python-env 产物;dev 联调用)
|
||||||
|
│ └── current.json # 指向当前版本目录(客户端自动探测)
|
||||||
|
└── electron/ # 主进程(CommonJS,纯 Node 可跑)
|
||||||
|
├── main.js # 入口:--cli 无 Electron 运行 / electron . 窗口模式
|
||||||
|
├── config.js # .env 加载 + 路径常量(对齐 Python config.py)
|
||||||
|
├── logger.js # 日志(INFO 屏蔽大 JSON,DEBUG=1 全开)
|
||||||
|
├── state.js # 运行会话/白名单/平台表(对齐 state.py)
|
||||||
|
├── hub.js # 事件枢纽 → WS /ws 广播(对齐 hub.py)
|
||||||
|
├── session.js # cp_session cookie 会话 + 落盘 + 云令牌(对齐 session.py)
|
||||||
|
├── cpclient.js # 中心机 REST 客户端(_cp_call 等价)
|
||||||
|
├── crypto.js # Ed25519 验签 / RSA-OAEP / sha256 / 版本比较
|
||||||
|
├── licensing.js # 授权票据/管控清单/公钥缓存 + 验签 + 运行上报 + 设备上报
|
||||||
|
├── registry.js # 插件元数据注册表(plugin.json 驱动)
|
||||||
|
├── plugin-sync.js # 插件自下载/更新/清理(download-ticket + sha256 + 原子安装)
|
||||||
|
├── runner.js # 插件执行:spawn python plugin_runner + 整树强杀 + 事件转发
|
||||||
|
├── run-history.js # 运行历史:run_history.jsonl 索引 + run_history/<run_id>.jsonl 日志
|
||||||
|
├── last-fields.js # 上次执行参数回填(按账号+插件,password 字段不落盘)
|
||||||
|
├── scheduler.js # 设备级单活(active.json)+ 平台命名空间并发闸
|
||||||
|
├── tasks.js # 5 段 cron 定时任务 + 中心机备份/恢复
|
||||||
|
├── platform-auth.js # HR/OA 登录/登出/在线校验(登录走 Python 子进程)
|
||||||
|
├── meta.js # /api/meta 聚合
|
||||||
|
├── creds-sync.js # 敏感凭证下发(RSA 密钥对 + OAEP 解密 + 密文缓存)
|
||||||
|
├── shell-updater.js # 壳子自更新(检查/下载/静默升级)
|
||||||
|
├── chrome-manager.js # Chrome 检测/下载/静默安装
|
||||||
|
├── server.js # 本地 HTTP/WS 兼容层(127.0.0.1:8799)
|
||||||
|
├── app.js # 启动组装
|
||||||
|
├── env-sync.js # 环境包(便携 Python)检查/下载/解压/切换/回滚
|
||||||
|
├── electron-main.js # Electron 窗口/托盘/单实例/自启(已移除默认英文菜单)
|
||||||
|
└── preload.js # contextBridge(渲染层主通道走 HTTP)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 运行
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 1. 安装依赖
|
||||||
|
cd desktop/electron-shell
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 2. 构建前端静态资源(源码在 frontend/,产物 → renderer/dist;旧 webhost 前端不受影响)
|
||||||
|
npm run copy-renderer
|
||||||
|
|
||||||
|
# 3a. 无窗口 CLI 模式(调试/无人值守)
|
||||||
|
node electron/main.js --cli
|
||||||
|
|
||||||
|
# 3b. Electron 窗口模式
|
||||||
|
npm run electron
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置(.env)
|
||||||
|
|
||||||
|
| 变量 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `CONTROLPLANE_URL` | 中心机控制面地址(如 `http://117.72.191.188:8800`) |
|
||||||
|
| `CONTROLPLANE_TOKEN` | 内部凭证(与 controlplane/.env 一致;非空时发 X-API-Token) |
|
||||||
|
| `PYTHON_EXE` | 插件执行子进程的 Python 解释器。**解析优先级**:显式 `PYTHON_EXE` > 环境包 `python-env/current.json` 指向的 `python.exe` > 系统 `python`(不设即可用环境包) |
|
||||||
|
| `SHELL_PYTHON_ENV_ROOT` | 环境包目录的显式覆盖(默认:打包态 exe 同级 `python-env/`,dev `electron-shell/python-env/`) |
|
||||||
|
| `RUN_TIMEOUT` | 插件执行超时秒数(默认 1800) |
|
||||||
|
| `RUN_MAX_MEM_MB` | 插件进程作业级内存上限(默认 2048,环境包模式经 job_guard 生效) |
|
||||||
|
| `DEBUG=1` | 开启完整 JSON 调试日志 |
|
||||||
|
|
||||||
|
## 便携 Python 环境包(python-env)
|
||||||
|
|
||||||
|
正式打包的客户端**开箱即用**:不依赖用户机器上安装的任何 Python。环境包 = 便携解释器
|
||||||
|
(embeddable 3.11.9)+ 全部插件依赖(与 .venv 验证版本钉死)+ webhost 运行时子集
|
||||||
|
(`plugin_runner` / `plugins` / `shared` / `core.auth`)。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 构建(本地联调会同时安装到 electron-shell/python-env/)
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 [-EnvVersion 1.0.0]
|
||||||
|
# 产物:dist-env/python-env-<version>.zip + .sha256
|
||||||
|
```
|
||||||
|
|
||||||
|
- **加载**:`config.pythonEnvRoot()` 读 `python-env/current.json` → 版本目录;插件执行走
|
||||||
|
`python-exe -u webhost/backend/core/job_guard.py --mem <MB> --timeout <s> -- python -u plugin_runner.py ...`
|
||||||
|
—— Job Object 整树托管 + 内存上限(对齐旧 Python 底座 winjob 能力);stdin/stdout/stderr
|
||||||
|
逐字节透传,执行协议不变。
|
||||||
|
- **下发**:中心机 `agent_cli file push <zip> --category python-env --version <ver>` 登记后,
|
||||||
|
客户端启动/每 30 分钟检查 `/api/file-sources/python-env`,有新版自动下载 → sha256 →
|
||||||
|
解压 `python-env/<version>/` → 切 `current.json` → 保留上一版供回滚。
|
||||||
|
- **本地 API**:`GET /api/env/status`(版本/云端/进度)、`POST /api/env/sync`(手动检查更新)、
|
||||||
|
`POST /api/env/rollback`(回滚上一版);`/api/meta` 增加 `env.version` 字段。
|
||||||
|
|
||||||
|
## 跨端共享数据(%LOCALAPPDATA%\37duAutomation)
|
||||||
|
|
||||||
|
与旧 Python 底座/影刀版**同路径同格式**(换壳不破坏数据):
|
||||||
|
|
||||||
|
| 文件/目录 | 用途 |
|
||||||
|
|---|---|
|
||||||
|
| `license.json` / `control.json` / `keys/pub.pem` | 离线授权票据/管控清单/公钥(Ed25519 验签) |
|
||||||
|
| `active.json` | 设备级单活运行状态 |
|
||||||
|
| `schedules.json` | 定时任务配置(按账号隔离);每条含 `last_status/last_duration/last_error` 最近一次结论。触发语义:**错过不补跑**(壳子停机/离线期间到点的任务直接跳过,要补就人工运行一次);触发失败(授权被拒/插件缺失)跳过本次到点,等下一个 cron 点再试 |
|
||||||
|
| `run_history.jsonl` + `run_history/<run_id>.jsonl` | 运行历史:索引(结论,最近 300~350 条)+ 每次运行独立日志文件 |
|
||||||
|
| `last_run_fields.json` | 上次执行参数(按账号+插件,用于表单回填;`password` 类型字段不写入) |
|
||||||
|
| `plugin_configs/` | 插件个性化配置(账号密码等) |
|
||||||
|
| `.sessions/` | HR/OA 平台登录 cookies(三方共享) |
|
||||||
|
| `creds/id_rsa.pem` + `creds/cache.json` | RSA 私钥 + 加密凭证缓存 |
|
||||||
|
| `offline_reports.jsonl` | 离线上报暂存(重连补报) |
|
||||||
|
| `plugin_allow.json` | 插件权限清单缓存(离线兜底) |
|
||||||
|
| `plugin_rollback/` | 插件回滚备份:升级前自动保留上一版(`<id>@<version>/`,每插件仅最新一版),坏包可在运行台一键回滚 |
|
||||||
|
| `window-state.json` | 主窗口位置/尺寸(重启还原;显示器变更后自动避让屏幕外) |
|
||||||
|
|
||||||
|
## 插件安全基线
|
||||||
|
|
||||||
|
- **插件 UI 加固**:`/pui/<id>/` 响应带 Content-Security-Policy(仅同源资源,阻断外联脚本/图片与外域跳转);壳内嵌 iframe 带 `sandbox="allow-scripts allow-same-origin allow-forms"`(禁止 top 跳转与弹窗)
|
||||||
|
- **版本兼容校验**:插件 `plugin.json` 可声明 `minRuntimeVersion`(要求的最小壳运行时版本);安装时校验,不满足拒绝安装并提示先升级客户端
|
||||||
|
- **回滚**:升级前自动备份上一版到 `plugin_rollback/`,设备空闲时可在运行台回滚(回滚后再次同步可回到最新版)
|
||||||
|
- WS 心跳:30s ping 巡检,僵尸/半开连接自动 terminate
|
||||||
|
|
||||||
|
## 插件执行协议(★ 与旧底座逐字节兼容)
|
||||||
|
|
||||||
|
```
|
||||||
|
<PYTHON_EXE> -u <plugin_runner.py> --plugin <id> --run <run_id> [--allowed a,b]
|
||||||
|
stdin : 单行 JSON fields(UTF-8)
|
||||||
|
stdout : JSON 事件行 {ev: log|progress|result}
|
||||||
|
stderr : 诊断通道(转发为 ERROR 日志)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 设备级单活:整机同时只跑一个插件(active.json 门闩)
|
||||||
|
- 平台命名空间并发闸:同平台(hr/oa)任务串行,保护共享 cookies
|
||||||
|
- 超时强杀:`taskkill /pid <pid> /T /F` 整树终止(含浏览器孙进程)
|
||||||
|
- 授权门禁:启动前验签本地授权票据 + 下架/禁用/强制更新校验
|
||||||
|
|
||||||
|
## 本地 HTTP 兼容层(127.0.0.1:8799)
|
||||||
|
|
||||||
|
路由与返回结构与旧底座 `backend/apis/*` 一致:`/api/meta`、`/api/admin/*`、`/api/runs*`、
|
||||||
|
`/api/schedules*`、`/api/plugins/sync`、`/api/plugin-config/{pid}`、`/pui/{pid}`、`/api/shell/*`、
|
||||||
|
`/api/chrome/*`、`/api/platforms/*`、钉钉登录链路(`/api/auth/dingtalk`、`/auth/done`)、
|
||||||
|
WS `/ws`(登录会话鉴权,广播 log/progress/run_done)。
|
||||||
|
|
||||||
|
新增(向后兼容,均为追加):
|
||||||
|
- `GET /api/runs?limit=N` —— 运行历史列表(按当前账号,最新在前)。返回 `{runs:[{run_id, plugin_id, name,
|
||||||
|
version, trigger, schedule_id, status, ok, error, summary, started, finished, duration_sec}]}`,
|
||||||
|
**不含 logs**(列表页不解析历史日志,避免大文件拖慢);`trigger` 为 `manual` / `schedule`。
|
||||||
|
- `GET /api/runs/{id}` —— 运行详情。内存中已结束的运行会回落 `run_history`,因此重启后仍可回看日志。
|
||||||
|
- `GET /api/plugins/{id}/last-fields` —— 上次执行参数回填,返回 `{fields, at}`。
|
||||||
|
写入时机为 `POST /api/runs`(发起执行时自动记忆);`fields` schema 中 `type/format` 为 `password`
|
||||||
|
的键**永不落盘、永不下发**(插件字段可能含凭据)。
|
||||||
|
|
||||||
|
## 打包(electron-builder)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm install # 含 electron + electron-builder(首次需放行 electron postinstall)
|
||||||
|
npm run pack # → dist-app/setup-37du-shell-<version>.exe(NSIS 静默升级兼容)
|
||||||
|
```
|
||||||
|
|
||||||
|
打包后:插件根目录 = exe 同级 `plugins/`;壳子版本文件 = exe 同级 `shell.version`
|
||||||
|
(参与自更新的前提,与旧壳一致);`apply_update` 以 `/VERYSILENT /SUPPRESSMSGBOXES /NORESTART`
|
||||||
|
运行新安装包后退出,由 Inno `[Run]` 重启新版本。
|
||||||
|
|
||||||
|
## 验证记录(2026-09-23,线上控制面)
|
||||||
|
|
||||||
|
- 登录/登出/改密、`/api/admin/me` 昵称补齐 ✓
|
||||||
|
- `/api/meta` 授权票据驱动插件可见性(2 个授权插件 + 字段/UI 元数据)✓
|
||||||
|
- 授权票据 Ed25519 离线验签 ✓;运行门禁 404/403 路径 ✓
|
||||||
|
- 插件同步(清单 diff → 已有最新,无下载)✓;Chrome 检测(本机已装 154.x)✓
|
||||||
|
- 定时任务 CRUD + 非法 cron 拒绝 + 删除 ✓;WS 鉴权握手 ✓
|
||||||
|
- 执行协议三态自测:成功回传 / 异常回传(含 stderr Traceback 转发)/ 超时强杀 ✓
|
||||||
|
- 奶油极简治愈风前端(frontend/ 自持源码):登录页浅天蓝强调 + 手写标题字体 + 可开关涂鸦装饰层 ✓
|
||||||
|
|
||||||
|
## 前端主题(token 层 + 可换肤)
|
||||||
|
|
||||||
|
壳自带 `frontend/` 前端源码(从 webhost 复制后独立演进)。**样式与皮肤已分层**:
|
||||||
|
|
||||||
|
- **token 层**:`frontend/src/style.css` 的 `:root` 是唯一色值来源(111 个 token,含
|
||||||
|
`--primary-rgb` / `--ok-rgb` / `--text-rgb` 这类分量变量,供 `rgba()` 拼装)。
|
||||||
|
组件(`.vue`)里**不写任何字面色值**,只用 `var(--token)`;`password`/`#000` 掩码等
|
||||||
|
非主题色与 SVG `data:` URI 内的色值除外(后者无法用 `var()`)。
|
||||||
|
改动样式请先加 token 再引用,不要再写字面值。
|
||||||
|
- **皮肤层**:`[data-skin="..."]` 块只重映射同名 token,组件代码零改动。
|
||||||
|
- `cream`(默认):奶油极简治愈风,背景 `#F9F7F2` / 文本 `#222`·`#666` / 强调 `#7CC3E8`,
|
||||||
|
卡片 16px、登录卡 22px、按钮输入 12–14px 大圆角,仅极柔和浅阴影。
|
||||||
|
- `precision`:冷灰画布 + 压深天蓝(`#1E6FA8`)的"精密工作台"。**2026-09 已完成对比度审计**:
|
||||||
|
正文/次级/弱化文字、按钮白字、磁贴图标、成功/警告/失败徽章等 19 组关键配对全部达到
|
||||||
|
WCAG 阈值(正文 ≥4.5、徽章/图标 ≥3.0,实测 3.27~16.03);cream 的 5 处偏低(弱化文字、
|
||||||
|
粉彩徽章、淡红失败图标)是奶油风**刻意保留的柔和粉彩设计**,非缺陷。
|
||||||
|
- 切换:`localStorage['37du.skin'] = 'cream' | 'precision'`(`main.js` 挂载前写入
|
||||||
|
`<html data-skin>`,避免首屏闪烁)。皮肤同时重映射 element-plus 的 `--el-color-primary*`,
|
||||||
|
否则内置表单/表格会残留奶油浅蓝。
|
||||||
|
- 磁贴类(场景图标/头像)前景色走 `--tile-fg`:cream 为白色(配深渐变),
|
||||||
|
precision 为深蓝(配淡色底)——**换肤时若把 `--grad-*` 改成淡色,必须同步改 `--tile-fg`**;
|
||||||
|
2026-09 已把左栏场景图标/统计图标/场景卡图标/运行台 hero 头像统一到 `--tile-fg`,
|
||||||
|
修掉 precision 下"白字落在淡色底上"的不可读问题(cream 取值同为白色,观感不变)。
|
||||||
|
- **涂鸦装饰层**:手绘涂鸦 SVG fixed 浮于页面顶层,`pointer-events:none` 不拦截交互;
|
||||||
|
登录页右上角 ✿ 按钮或 `localStorage['37du.doodles']='off'` 可整体关闭;
|
||||||
|
它是奶油皮肤专属装饰,`precision` 皮肤下由 CSS 整体隐藏。
|
||||||
|
- 标题可用圆润手写装饰字体(`--font-doodle`:Segoe Script → Comic Sans → 楷体),正文固定无衬线 Inter。
|
||||||
|
|
||||||
|
产品化界面(2026-09 三栏版,对齐 design-preview-v2 的信息架构):
|
||||||
|
- **三栏骨架**:左栏场景导轨 + 中栏内容区(总览/运行台/计划)+ 右栏活动流(<1240px 自动收起)
|
||||||
|
+ 底部状态栏。三栏与状态栏为静态面板,不做悬停抬升;顶栏保留浏览器检测 CTA 与运行进度。
|
||||||
|
- **左栏**:总览 / 计划 主导航 + 场景库(浅天蓝激活态,点击进运行台)
|
||||||
|
- **右栏活动流**:当前运行(运行中显示场景名/进度条/最近日志,空闲显示"当前空闲")
|
||||||
|
+ 最近运行(最近 8 次,点击直达该场景运行台);运行态由 WS 事件驱动,
|
||||||
|
定时任务触发的运行同样点亮(`store.running` 在 `run_start` 置位,日志归属本次运行)
|
||||||
|
- **状态栏**:授权状态(剩余天数/异常)/ 本地服务连接 / 本地地址 / 平台在线 N/M /
|
||||||
|
壳子版本 + 检查更新;授权异常态标红提示
|
||||||
|
- **运行台**:Hero 卡(大图标/版本徽章/平台登录态)+ 一键执行大按钮(执行中显示进度环)
|
||||||
|
+ 结果横幅(成功/失败);下方标签页:有专属界面的插件默认「插件界面」内嵌 iframe,
|
||||||
|
其余默认「参数配置」白卡,运行日志独立标签(LIVE 呼吸点 + 级别过滤,圆角交给卡片容器)
|
||||||
|
- **运行台 · 历史运行**:第三标签页列出本场景最近 30 次运行(手动/定时、成功/失败、时间/耗时),
|
||||||
|
点击任一条**回看该次运行**:结果徽章 + 触发方式 + 摘要 + 该次完整日志(`GET /api/runs/{id}`
|
||||||
|
落回 `run_history/` 的逐次日志文件);右栏「最近运行」、总览「最近动态」点击直达对应回看
|
||||||
|
- 视图切换:`store.view` 取值 `overview`(总览)/ `run`(运行台)/ `plans`(计划)
|
||||||
|
|
||||||
|
## 行为变更(2026-09,需知悉)
|
||||||
|
|
||||||
|
| 项 | 变更 | 影响 |
|
||||||
|
|---|---|---|
|
||||||
|
| cron 星期编号 | `tasks.js cronDow` 原为 `(getDay()+6)%7`(周一=0),与 Python 底座 `tasks.py _cron_dow`(`(weekday()+1)%7`,周日=0,标准 cron)**差一天** | 已修正为 `dt.getDay()`。**存量排程会平移**:`0 8 * * 1-5`(工作日)原先实际在**周二~周六**触发,修正后按界面标注的**周一~周五**触发;`0`/`7`(周日)原先落在周一,修正后落在周日;`* * * * 6`(周六)原先无法命中周六 |
|
||||||
|
| 运行历史 | 新增 `run_history.jsonl` + `run_history/` | 首次运行自动创建,无需迁移;上限最近 300~350 条,超出按批裁剪并清理孤儿日志文件 |
|
||||||
|
|
||||||
|
## 平台登录(HR/OA)按账号隔离
|
||||||
|
|
||||||
|
- 每个人的 HR/OA 账号密码由本人在「个人中心 → 平台账号」填写(AES-256-GCM 本机加密,
|
||||||
|
存 `%LOCALAPPDATA%\37duAutomation\platform-creds\creds.json`),顶栏不再显示设备级平台徽章
|
||||||
|
- 平台会话 cookies 按账号隔离:`.sessions/<账号>/hr_cookies.json`、`oa_cookies.json`;
|
||||||
|
Python 共享模块(hr_login_api / oa_login_api / seal_data_export / roster_export_api / org_export /
|
||||||
|
core.auth)通过 `PLATFORM_ACCOUNT` 环境变量解析各自的会话目录,未设置时沿用共享目录(兼容旧逻辑)
|
||||||
|
- 登录/登出:壳端 `platform-auth` 拉起 Python 登录子进程时注入 `PLATFORM_ACCOUNT`
|
||||||
|
与账号的 `hr_login_username/password`(个人账号密码优先,未配置回退共享 .env);
|
||||||
|
登录为纯 requests 接口版(HR 含滑块接口破解),全程无浏览器
|
||||||
|
- 插件执行:runner 子进程同样注入 `PLATFORM_ACCOUNT`,插件内数据导出按当前登录账号的身份执行;
|
||||||
|
同平台并发闸键改为(账号, 平台)
|
||||||
|
- 接口:`GET /api/meta` 平台在线按当前账号返回;`GET /api/platforms/status` 返回当前账号
|
||||||
|
的平台在线/是否已配置个人账号/已存用户名;`PUT /api/platforms/creds` 保存个人账号密码
|
||||||
|
|
||||||
|
## 已知差异(相对旧 Python 底座)
|
||||||
|
|
||||||
|
| 项 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 进程内存上限 | 环境包模式已实现(job_guard + Job Object,`RUN_MAX_MEM_MB`);无环境包直拉 .venv 的 dev 链路未做(超时强杀已覆盖主要风险) |
|
||||||
|
| 定时任务错过触发 | 旧底座重启后逐点补跑错过的触发点;Node 版**错过不补跑**(停机/离线期间到点直接跳过,要补就人工运行一次) |
|
||||||
|
| 平台登录 | 登录自动化仍为 Python 子进程(DrissionPage 滑块);在线校验改为 Node 直接 HTTP 校验(复刻同逻辑,短缓存) |
|
||||||
|
| 渲染层 | 复用 webhost Vue3 前端产物(本地 HTTP 主通道);IPC 通道为后续演进预留(preload 已就位) |
|
||||||
|
| 云令牌持久化 | 旧底座仅内存;Node 版随 `_cp_sessions.json` 落盘,重启后 Bearer 仍可用 |
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
@@ -0,0 +1,168 @@
|
|||||||
|
// 应用组装层:启动初始化(单活复位/权限/授权/插件同步/壳子检查/定时任务/设备上报)+ 本地服务。
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const os = require("os");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const config = require("./config");
|
||||||
|
const state = require("./state");
|
||||||
|
const session = require("./session");
|
||||||
|
const scheduler = require("./scheduler");
|
||||||
|
const licensing = require("./licensing");
|
||||||
|
const registry = require("./registry");
|
||||||
|
const pluginSync = require("./plugin-sync");
|
||||||
|
const tasks = require("./tasks");
|
||||||
|
const shellUpdater = require("./shell-updater");
|
||||||
|
const chromeManager = require("./chrome-manager");
|
||||||
|
const envSync = require("./env-sync");
|
||||||
|
const { HUB } = require("./hub");
|
||||||
|
const { makeLogger, setLogFile } = require("./logger");
|
||||||
|
|
||||||
|
const logger = makeLogger("app");
|
||||||
|
|
||||||
|
// 设备 ID:持久化 uuid(跨重启稳定,供 device/report)
|
||||||
|
function deviceId() {
|
||||||
|
const f = path.join(config.APP_DATA, "device_id");
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(f)) {
|
||||||
|
const v = fs.readFileSync(f, "utf-8").trim();
|
||||||
|
if (v) return v;
|
||||||
|
}
|
||||||
|
const id = crypto.randomUUID();
|
||||||
|
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||||
|
fs.writeFileSync(f, id, "utf-8");
|
||||||
|
return id;
|
||||||
|
} catch (e) {
|
||||||
|
return "dev-" + crypto.randomBytes(8).toString("hex");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function localIp() {
|
||||||
|
try {
|
||||||
|
const ifs = os.networkInterfaces();
|
||||||
|
for (const list of Object.values(ifs)) {
|
||||||
|
for (const it of list || []) {
|
||||||
|
if (it.family === "IPv4" && !it.internal) return it.address;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
/* 忽略 */
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设备环境上报(心跳 + Chrome 环境):Node 版新增接入(旧 Python 底座无调用方)
|
||||||
|
async function reportDevice(account) {
|
||||||
|
const chrome = await chromeManager.detectLocal();
|
||||||
|
await licensing.deviceReport(deviceId(), account, {
|
||||||
|
hostname: os.hostname(),
|
||||||
|
os: process.platform,
|
||||||
|
ip: localIp(),
|
||||||
|
chromeInstalled: chrome.installed,
|
||||||
|
chromeVersion: chrome.version,
|
||||||
|
chromeOk: chrome.installed,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function init(options = {}) {
|
||||||
|
// 崩溃现场落盘(窗口模式无控制台时排查唯一窗口):Electron 运行时都落盘(含打包版),
|
||||||
|
// CLI 纯 Node 模式日志走 stdout 即可。不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。
|
||||||
|
// ★ 日志放数据根 %LOCALAPPDATA%\37duAutomation\logs\(打包态 SHELL_ROOT 在 app.asar 内只读,不能写)
|
||||||
|
if (process.versions && process.versions.electron) {
|
||||||
|
setLogFile(path.join(config.APP_DATA, "logs", "shell.log"));
|
||||||
|
}
|
||||||
|
|
||||||
|
state.setBootStep("加载配置与本地服务");
|
||||||
|
scheduler.initActive();
|
||||||
|
|
||||||
|
// 账号:优先 .env,其次最近活跃本机会话
|
||||||
|
const account = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount();
|
||||||
|
if (config.CONTROLPLANE_URL) {
|
||||||
|
// 权限白名单(fail-closed)
|
||||||
|
try {
|
||||||
|
state.setBootStep("同步权限白名单");
|
||||||
|
const allowed = await pluginSync.resolveAllowed(account);
|
||||||
|
state.setAllowed(allowed);
|
||||||
|
} catch (e) {
|
||||||
|
state.setAllowed(new Set());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 敏感凭证中心化下发(在线拉取 RSA 解密 / 本地缓存兜底;失败不阻断启动)
|
||||||
|
try {
|
||||||
|
state.setBootStep("下发敏感凭证");
|
||||||
|
const creds = await require("./creds-sync").load(account);
|
||||||
|
if (creds && Object.keys(creds).length) {
|
||||||
|
config.applyCreds(creds);
|
||||||
|
logger.info(`中心机敏感凭证下发完成(${Object.keys(creds).length} 个键)`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`加载中心机敏感凭证失败:${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动同步离线授权票据
|
||||||
|
if (account) {
|
||||||
|
try {
|
||||||
|
state.setBootStep("同步授权票据");
|
||||||
|
await licensing.syncLicensing(account);
|
||||||
|
logger.info(`启动同步离线授权票据成功(账号 ${account})`);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`启动同步离线授权票据失败:${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动即检查插件更新(后台,不阻塞启动)
|
||||||
|
const accts = session.accountSet();
|
||||||
|
if (accts.size > 0) {
|
||||||
|
const firstAcct = accts.values().next().value;
|
||||||
|
void pluginSync
|
||||||
|
.withSyncLock(async () => {
|
||||||
|
await pluginSync.syncPlugins(firstAcct);
|
||||||
|
const manifest = await pluginSync.cloudPluginManifest(firstAcct);
|
||||||
|
if (manifest !== null) state.setAllowed(new Set(manifest.map((p) => p.id)));
|
||||||
|
logger.info(`启动插件更新完成(账号 ${firstAcct})`);
|
||||||
|
try { HUB.publish({ t: "plugins_synced" }); } catch (e) { /* 忽略 */ }
|
||||||
|
})
|
||||||
|
.catch((e) => logger.warning(`启动插件更新失败:${e.message}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 环境包(便携 Python 运行时):启动即检查(异步不阻塞),缺失/有新版本自动下载;
|
||||||
|
// 插件执行/平台登录在环境包就绪前会报"环境包未就绪",由设置页提供状态与手动更新
|
||||||
|
state.setBootStep("检查便携环境包");
|
||||||
|
envSync.migrateLegacyEnvRoot(); // 一次性:把旧版装在安装目录的环境包迁到 APP_DATA(重装不丢)
|
||||||
|
void envSync
|
||||||
|
.checkAndSync()
|
||||||
|
.then((r) => logger.info(`环境包检查:${r.ok ? `就绪 v${r.version || ""}` : `未就绪(${r.reason})`}`))
|
||||||
|
.catch((e) => logger.warning(`环境包启动检查异常:${e.message}`));
|
||||||
|
// 常驻周期检查(30 分钟,与壳子更新同频)
|
||||||
|
setInterval(() => {
|
||||||
|
void envSync.checkAndSync().catch((e) => logger.warning(`环境包周期检查异常:${e.message}`));
|
||||||
|
}, 30 * 60 * 1000);
|
||||||
|
|
||||||
|
// 壳子更新:启动检查 + 常驻周期检查(顺带清扫升级遗留的安装包/批处理)
|
||||||
|
shellUpdater.cleanupStalePackages();
|
||||||
|
shellUpdater.startCheck();
|
||||||
|
shellUpdater.startPeriodicCheck();
|
||||||
|
|
||||||
|
// 定时任务:加载 + 后台触发 + 云端合并恢复
|
||||||
|
tasks.init();
|
||||||
|
|
||||||
|
// 设备上报(Chrome 环境 + 心跳;失败静默)
|
||||||
|
void reportDevice(account)
|
||||||
|
.then(() => logger.info("设备环境上报完成"))
|
||||||
|
.catch(() => {});
|
||||||
|
} else {
|
||||||
|
logger.info("未配置中心机地址(CONTROLPLANE_URL),进入离线本地模式");
|
||||||
|
state.setAllowed(new Set());
|
||||||
|
tasks.load();
|
||||||
|
tasks.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`插件根目录:${registry.pluginRoot()}`);
|
||||||
|
logger.info(`数据根目录:${config.APP_DATA}`);
|
||||||
|
state.setBootStep("启动就绪", "本地服务已就绪");
|
||||||
|
state.setBootDone();
|
||||||
|
return { deviceId: deviceId(), account };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, deviceId };
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
// 浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||||
|
// 对齐 Python chrome_manager.py 的状态结构与流程。
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const { spawn, execFile } = require("child_process");
|
||||||
|
const cp = require("./cpclient");
|
||||||
|
const config = require("./config");
|
||||||
|
const { makeLogger } = require("./logger");
|
||||||
|
|
||||||
|
const logger = makeLogger("chrome-manager");
|
||||||
|
|
||||||
|
const CHROME_CACHE = path.join(config.APP_DATA, "chrome");
|
||||||
|
let _pendingPkg = null;
|
||||||
|
|
||||||
|
const _STATE = {
|
||||||
|
installed: true,
|
||||||
|
version: "",
|
||||||
|
checking: false,
|
||||||
|
check_error: "",
|
||||||
|
cloud_available: true,
|
||||||
|
dl_status: "idle",
|
||||||
|
dl_received: 0,
|
||||||
|
dl_total: 0,
|
||||||
|
dl_pct: 0,
|
||||||
|
dl_error: "",
|
||||||
|
installing: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const VERSION_RE = /^\d+\.\d+\.\d+\.\d+$/;
|
||||||
|
|
||||||
|
// 系统位数:Chrome 安装包按位数分发(登记分类 chrome-x64 / chrome-x86)
|
||||||
|
function detectArch() {
|
||||||
|
const pa = (process.env.PROCESSOR_ARCHITECTURE || "").toLowerCase();
|
||||||
|
if (process.env.PROCESSOR_ARCHITEW6432) return "x64"; // 32 位进程跑在 64 位系统
|
||||||
|
if (pa === "amd64" || pa === "arm64" || pa === "ia64") return "x64";
|
||||||
|
if (pa === "x86") return "x86";
|
||||||
|
return "x64"; // 未知默认按 64 位
|
||||||
|
}
|
||||||
|
const ARCH = detectArch();
|
||||||
|
|
||||||
|
// 本机检测缓存:前端轮询 status 时避免每 2s 反复 spawn reg/powershell
|
||||||
|
let _localCache = { ts: 0, value: null };
|
||||||
|
const LOCAL_CACHE_TTL = 30 * 1000;
|
||||||
|
|
||||||
|
async function detectLocal(force = false) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (!force && _localCache.value && now - _localCache.ts < LOCAL_CACHE_TTL) {
|
||||||
|
return _localCache.value;
|
||||||
|
}
|
||||||
|
const exe = await findChromeExe();
|
||||||
|
let value;
|
||||||
|
if (!exe) value = { installed: false, version: "" };
|
||||||
|
else value = { installed: true, version: await readVersion(exe) };
|
||||||
|
_localCache = { ts: now, value };
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function execFileAsync(file, args, timeout = 8000) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
execFile(file, args, { timeout, windowsHide: true }, (err, stdout, stderr) => {
|
||||||
|
if (err) resolve({ err, stdout: stdout || "", stderr: stderr || "" });
|
||||||
|
else resolve({ err: null, stdout: stdout || "", stderr: stderr || "" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注册表探测 Chrome.exe 路径(64/32 位)
|
||||||
|
async function findChromeExe() {
|
||||||
|
const roots = [
|
||||||
|
["HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
|
||||||
|
["HKLM", "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
|
||||||
|
["HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
|
||||||
|
];
|
||||||
|
for (const [hive, key] of roots) {
|
||||||
|
const r = await execFileAsync("reg", ["query", `${hive}\\${key}`, "/ve"]);
|
||||||
|
if (!r.err) {
|
||||||
|
// 输出形如: (默认) REG_SZ C:\...\chrome.exe
|
||||||
|
const m = /REG_SZ\s+(.+)$/m.exec(r.stdout);
|
||||||
|
if (m && fs.existsSync(m[1].trim())) return m[1].trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 目录扫描兜底
|
||||||
|
const dirs = [
|
||||||
|
path.join(process.env.PROGRAMFILES || "C:/Program Files", "Google", "Chrome", "Application"),
|
||||||
|
path.join(process.env["PROGRAMFILES(X86)"] || "C:/Program Files (x86)", "Google", "Chrome", "Application"),
|
||||||
|
path.join(config.APP_DATA, "..", "Google", "Chrome", "Application"),
|
||||||
|
];
|
||||||
|
for (const d of dirs) {
|
||||||
|
const p = path.join(d, "chrome.exe");
|
||||||
|
if (fs.existsSync(p)) return p;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readVersion(exe) {
|
||||||
|
const r = await execFileAsync(
|
||||||
|
"powershell",
|
||||||
|
["-NoProfile", "-NonInteractive", "-Command", `(Get-Item -LiteralPath '${exe}').VersionInfo.ProductVersion`],
|
||||||
|
8000
|
||||||
|
);
|
||||||
|
if (r.err) return "";
|
||||||
|
const v = r.stdout.trim();
|
||||||
|
return VERSION_RE.test(v) ? v : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cloudInfo() {
|
||||||
|
if (!config.CONTROLPLANE_URL) return null;
|
||||||
|
// 按位数请求对应分类:64 位 → chrome-x64,32 位 → chrome-x86;
|
||||||
|
// 未按位数登记时回退旧分类 chrome(兼容历史登记),保证老记录仍可用。
|
||||||
|
const cats = ARCH === "x86" ? ["chrome-x86", "chrome"] : ["chrome-x64", "chrome"];
|
||||||
|
for (const cat of cats) {
|
||||||
|
try {
|
||||||
|
const r = await cp.request("GET", `/api/file-sources/${cat}`, { headers: cp.machineHeaders(), timeout: 5 });
|
||||||
|
if (r.available) {
|
||||||
|
_STATE.cloud_available = true;
|
||||||
|
return { ...r, arch: ARCH, category: cat };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.info(`获取浏览器云端信息失败(${cat}):${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_STATE.cloud_available = false;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function status() {
|
||||||
|
const local = await detectLocal();
|
||||||
|
if (local.installed) {
|
||||||
|
_STATE.installed = true;
|
||||||
|
_STATE.version = local.version;
|
||||||
|
_STATE.check_error = "";
|
||||||
|
} else {
|
||||||
|
_STATE.installed = false;
|
||||||
|
_STATE.version = "";
|
||||||
|
}
|
||||||
|
const pkgOk = !!_pendingPkg && fs.existsSync(_pendingPkg);
|
||||||
|
return {
|
||||||
|
arch: ARCH,
|
||||||
|
installed: !!_STATE.installed,
|
||||||
|
version: _STATE.version || "",
|
||||||
|
// 已安装时不再暴露"安装包已就绪",避免前端误触发重新安装
|
||||||
|
downloaded: !_STATE.installed && !!pkgOk,
|
||||||
|
cloud_available: !!_STATE.cloud_available,
|
||||||
|
error: _STATE.check_error || "",
|
||||||
|
installing: !!_STATE.installing,
|
||||||
|
dl: {
|
||||||
|
status: _STATE.installed && _STATE.dl_status === "downloaded" ? "idle" : (_STATE.dl_status || "idle"),
|
||||||
|
received: _STATE.dl_received || 0,
|
||||||
|
total: _STATE.dl_total || 0,
|
||||||
|
pct: _STATE.dl_pct || 0,
|
||||||
|
error: _STATE.dl_error || "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
_STATE.checking = true;
|
||||||
|
try {
|
||||||
|
await detectLocal();
|
||||||
|
await cloudInfo();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`浏览器检测异常:${e.message}`);
|
||||||
|
} finally {
|
||||||
|
_STATE.checking = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let _downloading = false;
|
||||||
|
|
||||||
|
async function startDownload() {
|
||||||
|
if (_STATE.dl_status === "downloading") return;
|
||||||
|
if (_STATE.dl_status === "downloaded" && _pendingPkg && fs.existsSync(_pendingPkg)) return;
|
||||||
|
const info = await cloudInfo();
|
||||||
|
if (!info || !info.url) return;
|
||||||
|
const url = String(info.url).trim();
|
||||||
|
const expect = String(info.sha256 || "").toLowerCase();
|
||||||
|
const filename = String(info.filename || (ARCH === "x86" ? "ChromeStandaloneSetup.exe" : "ChromeStandaloneSetup64.exe")).trim();
|
||||||
|
if (_downloading) return;
|
||||||
|
_downloading = true;
|
||||||
|
_STATE.dl_status = "downloading";
|
||||||
|
_STATE.dl_received = 0;
|
||||||
|
_STATE.dl_total = 0;
|
||||||
|
_STATE.dl_pct = 0;
|
||||||
|
_STATE.dl_error = "";
|
||||||
|
try {
|
||||||
|
await download(url, expect, filename);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`下载 Chrome 安装包失败:${e.message}`);
|
||||||
|
_STATE.dl_status = "failed";
|
||||||
|
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
|
||||||
|
cleanupPart();
|
||||||
|
} finally {
|
||||||
|
_downloading = false;
|
||||||
|
}
|
||||||
|
logger.info(`开始下载 Chrome 安装包:${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function download(url, expect, filename) {
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const sha = crypto.createHash("sha256");
|
||||||
|
const tmp = path.join(CHROME_CACHE, `${filename}.part`);
|
||||||
|
const pkg = path.join(CHROME_CACHE, filename);
|
||||||
|
fs.mkdirSync(CHROME_CACHE, { recursive: true });
|
||||||
|
const out = fs.createWriteStream(tmp);
|
||||||
|
let received = 0;
|
||||||
|
let total = 0;
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
|
||||||
|
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||||
|
total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
out.write(value);
|
||||||
|
sha.update(value);
|
||||||
|
received += value.length;
|
||||||
|
_STATE.dl_received = received;
|
||||||
|
_STATE.dl_total = total;
|
||||||
|
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||||
|
}
|
||||||
|
clearTimeout(timer);
|
||||||
|
await new Promise((res2, rej2) => out.end((e) => (e ? rej2(e) : res2())));
|
||||||
|
const digest = sha.digest("hex");
|
||||||
|
if (expect && digest !== expect) {
|
||||||
|
logger.error("Chrome 安装包 sha256 校验失败");
|
||||||
|
_STATE.dl_status = "failed";
|
||||||
|
_STATE.dl_error = "安装包校验失败,请重试";
|
||||||
|
cleanupPart();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
fs.renameSync(tmp, pkg);
|
||||||
|
} catch (e) {
|
||||||
|
_STATE.dl_status = "failed";
|
||||||
|
_STATE.dl_error = "安装包保存失败";
|
||||||
|
cleanupPart();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_pendingPkg = pkg;
|
||||||
|
_STATE.dl_status = "downloaded";
|
||||||
|
_STATE.dl_pct = 100;
|
||||||
|
_STATE.dl_received = received;
|
||||||
|
_STATE.dl_total = total;
|
||||||
|
logger.info(`Chrome 安装包下载完成:${pkg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupPart() {
|
||||||
|
try {
|
||||||
|
for (const f of fs.readdirSync(CHROME_CACHE)) {
|
||||||
|
if (f.endsWith(".part")) fs.unlinkSync(path.join(CHROME_CACHE, f));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
/* 忽略 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function install() {
|
||||||
|
if (!_pendingPkg || !fs.existsSync(_pendingPkg)) {
|
||||||
|
throw Object.assign(new Error("未找到已下载的 Chrome 安装包"), { status: 404 });
|
||||||
|
}
|
||||||
|
_STATE.installing = true;
|
||||||
|
logger.info(`启动 Chrome 安装器(弹出窗口由用户完成安装):${_pendingPkg}`);
|
||||||
|
// 直接弹出官方安装器窗口、由用户点击完成安装(不下发静默参数):
|
||||||
|
// 新版 Chrome 安装器会静默忽略未知参数(旧版 /silent /install 组合),
|
||||||
|
// 后台无窗口执行会表现为「静默失败/灰屏无法点击」,交互式安装可根治该问题。
|
||||||
|
const child = spawn(_pendingPkg, [], {
|
||||||
|
cwd: path.dirname(_pendingPkg),
|
||||||
|
windowsHide: false, // 保证安装器窗口可见,用户能正常操作
|
||||||
|
stdio: "ignore",
|
||||||
|
detached: true,
|
||||||
|
});
|
||||||
|
child.on("error", (e) => {
|
||||||
|
_STATE.installing = false;
|
||||||
|
logger.warning(`启动 Chrome 安装器失败:${e.message}`);
|
||||||
|
});
|
||||||
|
child.unref();
|
||||||
|
void pollInstall();
|
||||||
|
return { ok: true, installing: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollInstall() {
|
||||||
|
for (let i = 0; i < 120; i++) { // 交互式安装由用户人工操作,时限放宽到 10 分钟
|
||||||
|
await new Promise((r) => setTimeout(r, 5000));
|
||||||
|
const local = await detectLocal();
|
||||||
|
if (local.installed) {
|
||||||
|
_STATE.installing = false;
|
||||||
|
_STATE.installed = true;
|
||||||
|
_STATE.version = local.version;
|
||||||
|
_STATE.dl_status = "idle"; // 已安装,安装包不再参与状态,避免重复安装
|
||||||
|
_pendingPkg = null; // 释放安装包句柄,后续点击走「重新检测」而非再装
|
||||||
|
logger.info(`Chrome 安装完成:${_STATE.version}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_STATE.installing = false;
|
||||||
|
logger.warning("等待 Chrome 安装完成超时(可能用户未完成安装器窗口操作)");
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { status, refresh, startDownload, install, detectLocal };
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// 37du Electron 壳:配置固化(.env 加载 + 路径 + 常量)
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
// 打包态判定:Electron 运行时 + resources 下存在 app.asar(打包版独有,dev `electron .` 无 asar)。
|
||||||
|
// 不能依赖 ELECTRON_RENDERER_URL(那是 electron-vite 等 dev-server 工具的变量,本工程从不设置)。
|
||||||
|
const IS_FROZEN =
|
||||||
|
!!process.versions &&
|
||||||
|
!!process.versions.electron &&
|
||||||
|
!!process.resourcesPath &&
|
||||||
|
!process.env.ELECTRON_RUN_AS_NODE &&
|
||||||
|
fs.existsSync(path.join(process.resourcesPath, "app.asar"));
|
||||||
|
|
||||||
|
// 本模块目录:desktop/electron-shell/electron → parents
|
||||||
|
const SHELL_ROOT = path.resolve(__dirname, "..");
|
||||||
|
|
||||||
|
// 仓库根:electron/../.. = 37duAutomation(dev 模式定位 plugins/)
|
||||||
|
const REPO_ROOT = path.resolve(SHELL_ROOT, "..", "..");
|
||||||
|
|
||||||
|
// ==================== 轻量 .env 加载(仅本模块目录,变量已存在则不覆盖) ====================
|
||||||
|
function loadDotEnv() {
|
||||||
|
// 开发/CLI:读本模块 .env;打包态额外读 resources/.env(electron-builder extraResources 带入,
|
||||||
|
// 位于 asar 外的真实文件,可随包分发或按机器覆盖)
|
||||||
|
const candidates = [path.join(SHELL_ROOT, ".env")];
|
||||||
|
if (IS_FROZEN) candidates.push(path.join(process.resourcesPath, ".env"));
|
||||||
|
for (const envPath of candidates) {
|
||||||
|
if (!fs.existsSync(envPath)) continue;
|
||||||
|
try {
|
||||||
|
const text = fs.readFileSync(envPath, "utf-8");
|
||||||
|
for (const rawLine of text.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (!line || line.startsWith("#") || !line.includes("=")) continue;
|
||||||
|
const idx = line.indexOf("=");
|
||||||
|
const key = line.slice(0, idx).trim();
|
||||||
|
const value = line.slice(idx + 1).trim();
|
||||||
|
if (key && process.env[key] === undefined) process.env[key] = value;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 读取失败静默(与 Python 实现一致)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadDotEnv();
|
||||||
|
|
||||||
|
// ==================== 基础常量 ====================
|
||||||
|
const PORT = 8799;
|
||||||
|
|
||||||
|
// 数据根目录:与影刀版 / 旧 Python 底座共享 %LOCALAPPDATA%\37duAutomation(跨端契约)
|
||||||
|
function localAppData() {
|
||||||
|
return process.env.LOCALAPPDATA || process.env.APPDATA || require("os").homedir();
|
||||||
|
}
|
||||||
|
const APP_DATA = path.join(localAppData(), "37duAutomation");
|
||||||
|
|
||||||
|
// 插件本地配置目录:per-plugin JSON 持久化
|
||||||
|
const PLUGIN_CONFIG_DIR = path.join(APP_DATA, "plugin_configs");
|
||||||
|
|
||||||
|
// 插件源码/安装根:dev = 仓库根 plugins/;打包 = exe 同级 plugins/
|
||||||
|
function pluginRoot() {
|
||||||
|
if (process.env.SHELL_PLUGIN_ROOT) return process.env.SHELL_PLUGIN_ROOT;
|
||||||
|
if (IS_FROZEN) {
|
||||||
|
return path.join(path.dirname(process.execPath), "plugins");
|
||||||
|
}
|
||||||
|
return path.join(REPO_ROOT, "plugins");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行时版本:打包态读 exe 同级 shell.version(发版文件);开发/CLI 回退 package.json 版本。
|
||||||
|
// 插件 plugin.json 可声明 minRuntimeVersion 做版本兼容校验(不满足则拒绝安装)。
|
||||||
|
function runtimeVersion() {
|
||||||
|
try {
|
||||||
|
if (!process.env.ELECTRON_RUN_AS_NODE && process.resourcesPath) {
|
||||||
|
const vf = path.join(path.dirname(process.execPath), "shell.version");
|
||||||
|
if (fs.existsSync(vf)) {
|
||||||
|
const v = fs.readFileSync(vf, "utf-8").trim();
|
||||||
|
if (v) return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const pkg = JSON.parse(fs.readFileSync(path.join(SHELL_ROOT, "package.json"), "utf-8"));
|
||||||
|
return String(pkg.version || "").trim();
|
||||||
|
} catch (e) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 控制面配置 ====================
|
||||||
|
const CONTROLPLANE_URL = (process.env.CONTROLPLANE_URL || "").replace(/\/+$/, "");
|
||||||
|
const CONTROLPLANE_ACCOUNT = process.env.CONTROLPLANE_ACCOUNT || "";
|
||||||
|
const CONTROLPLANE_TOKEN = process.env.CONTROLPLANE_TOKEN || "";
|
||||||
|
|
||||||
|
// ==================== 插件执行子进程配置 ====================
|
||||||
|
// Python 解释器:优先 env,默认 python(PATH 中的 venv/系统 Python)
|
||||||
|
const PYTHON_EXE = process.env.PYTHON_EXE || "python";
|
||||||
|
const RUN_TIMEOUT = parseInt(process.env.RUN_TIMEOUT || "1800", 10);
|
||||||
|
const RUN_MAX_MEM_MB = parseInt(process.env.RUN_MAX_MEM_MB || "2048", 10);
|
||||||
|
|
||||||
|
// ==================== 便携 Python 环境包(python-env) ====================
|
||||||
|
// 版本化目录(python-env/<version>/)+ current.json 指向当前版本,保留上一版供回滚。
|
||||||
|
// 目录位置:打包态 = %LOCALAPPDATA%\37duAutomation\python-env——NSIS 重装/升级会清空安装目录,
|
||||||
|
// 放 exe 同级会导致环境包每次陪葬重新下载解压(其余持久化数据本就都在 APP_DATA);
|
||||||
|
// 开发态 = electron-shell/python-env/(可本地构建联调)。
|
||||||
|
function envRootDir() {
|
||||||
|
if (process.env.SHELL_PYTHON_ENV_ROOT) return path.resolve(process.env.SHELL_PYTHON_ENV_ROOT);
|
||||||
|
if (IS_FROZEN) return path.join(APP_DATA, "python-env");
|
||||||
|
return path.join(SHELL_ROOT, "python-env");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前环境包目录(current.json → 版本目录);无环境包返回 ""
|
||||||
|
function pythonEnvRoot() {
|
||||||
|
const dir = envRootDir();
|
||||||
|
try {
|
||||||
|
const raw = fs.readFileSync(path.join(dir, "current.json"), "utf-8").replace(/^\uFEFF/, "");
|
||||||
|
const cur = JSON.parse(raw);
|
||||||
|
const ver = String((cur || {}).version || "").trim();
|
||||||
|
if (ver && fs.existsSync(path.join(dir, ver, "python.exe"))) return path.join(dir, ver);
|
||||||
|
} catch (e) {
|
||||||
|
/* 尚无环境包 */
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 环境包解析的 Python 解释器:显式 PYTHON_EXE 优先,其次环境包,最后系统 python
|
||||||
|
function pythonExe() {
|
||||||
|
if (process.env.PYTHON_EXE) return process.env.PYTHON_EXE;
|
||||||
|
const envRoot = pythonEnvRoot();
|
||||||
|
if (envRoot) return path.join(envRoot, "python.exe");
|
||||||
|
return "python";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行时根(webhost 包所在目录):环境包模式 = 环境包根;否则 = 壳内置 python/(vendor 子集)
|
||||||
|
function runtimeRoot() {
|
||||||
|
const envRoot = pythonEnvRoot();
|
||||||
|
if (envRoot) return envRoot;
|
||||||
|
return path.join(SHELL_ROOT, "python");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 插件执行入口:环境包模式 = 环境包内 plugin_runner.py;打包态 = exe 同级;dev = 壳内置 python/
|
||||||
|
function runnerScript() {
|
||||||
|
if (process.env.SHELL_RUNNER_SCRIPT) return process.env.SHELL_RUNNER_SCRIPT;
|
||||||
|
const envRoot = pythonEnvRoot();
|
||||||
|
if (envRoot) return path.join(envRoot, "webhost", "backend", "core", "plugin_runner.py");
|
||||||
|
if (IS_FROZEN) {
|
||||||
|
return path.join(path.dirname(process.execPath), "plugin_runner.py");
|
||||||
|
}
|
||||||
|
return path.join(SHELL_ROOT, "python", "webhost", "backend", "core", "plugin_runner.py");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Job Object 守护(环境包模式启用内存上限 + 整树托管):无环境包返回 ""
|
||||||
|
function jobGuardScript() {
|
||||||
|
const envRoot = pythonEnvRoot();
|
||||||
|
if (envRoot) return path.join(envRoot, "webhost", "backend", "core", "job_guard.py");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 前端静态资源:壳自带 renderer/dist(自包含;缺失时先跑 scripts/copy-renderer.ps1 构建)
|
||||||
|
function frontendDist() {
|
||||||
|
return path.join(SHELL_ROOT, "renderer", "dist");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 敏感凭证中心化下发:进程级覆盖存储(唯一来源:中心机下发 / 本地加密缓存)
|
||||||
|
const _CREDS_OVERRIDE = {};
|
||||||
|
|
||||||
|
function applyCreds(values) {
|
||||||
|
if (values && typeof values === "object") {
|
||||||
|
Object.assign(_CREDS_OVERRIDE, values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCred(name) {
|
||||||
|
if (_CREDS_OVERRIDE[name] !== undefined) return _CREDS_OVERRIDE[name];
|
||||||
|
return process.env[name] !== undefined ? process.env[name] : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
SHELL_ROOT,
|
||||||
|
REPO_ROOT,
|
||||||
|
PORT,
|
||||||
|
APP_DATA,
|
||||||
|
PLUGIN_CONFIG_DIR,
|
||||||
|
CONTROLPLANE_URL,
|
||||||
|
CONTROLPLANE_ACCOUNT,
|
||||||
|
CONTROLPLANE_TOKEN,
|
||||||
|
PYTHON_EXE,
|
||||||
|
RUN_TIMEOUT,
|
||||||
|
RUN_MAX_MEM_MB,
|
||||||
|
IS_FROZEN,
|
||||||
|
pluginRoot,
|
||||||
|
runnerScript,
|
||||||
|
frontendDist,
|
||||||
|
runtimeVersion,
|
||||||
|
applyCreds,
|
||||||
|
getCred,
|
||||||
|
envRootDir,
|
||||||
|
pythonEnvRoot,
|
||||||
|
pythonExe,
|
||||||
|
runtimeRoot,
|
||||||
|
jobGuardScript,
|
||||||
|
};
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// 中心机 REST 客户端:_cp_call 等价(头规则一致、超时、错误透传 detail)。
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const { makeLogger } = require("./logger");
|
||||||
|
const config = require("./config");
|
||||||
|
|
||||||
|
const logger = makeLogger("cpclient");
|
||||||
|
|
||||||
|
class HttpError extends Error {
|
||||||
|
constructor(status, detail) {
|
||||||
|
super(typeof detail === "string" && detail ? detail : `中心机 ${status}`);
|
||||||
|
this.status = status;
|
||||||
|
this.detail = detail;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseUrl() {
|
||||||
|
if (!config.CONTROLPLANE_URL) {
|
||||||
|
const err = new Error("统一后端未配置(CONTROLPLANE_URL)");
|
||||||
|
err.status = 503;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return config.CONTROLPLANE_URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 机器凭证头(X-API-Token)
|
||||||
|
function machineHeaders() {
|
||||||
|
const h = {};
|
||||||
|
if (config.CONTROLPLANE_TOKEN) h["X-API-Token"] = config.CONTROLPLANE_TOKEN;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
// params: {a: 1} → query string
|
||||||
|
function qs(params) {
|
||||||
|
if (!params) return "";
|
||||||
|
const parts = Object.entries(params)
|
||||||
|
.filter(([, v]) => v !== undefined && v !== null)
|
||||||
|
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
|
||||||
|
return parts.length ? `?${parts.join("&")}` : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(method, urlPath, opts = {}) {
|
||||||
|
const { headers = {}, json, params, body, timeout = 30, raw = false } = opts;
|
||||||
|
const url = `${baseUrl()}${urlPath}${qs(params)}`;
|
||||||
|
const h = { ...headers };
|
||||||
|
let payload;
|
||||||
|
if (json !== undefined) {
|
||||||
|
h["Content-Type"] = "application/json";
|
||||||
|
payload = JSON.stringify(json);
|
||||||
|
} else if (body !== undefined) {
|
||||||
|
payload = body;
|
||||||
|
}
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers: h,
|
||||||
|
body: payload,
|
||||||
|
signal: ctrl.signal,
|
||||||
|
redirect: "follow",
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
const err = new Error(`中心机不可达: ${e.message}`);
|
||||||
|
err.status = 502;
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
const buf = Buffer.from(await res.arrayBuffer());
|
||||||
|
if (res.status >= 400) {
|
||||||
|
let detail = buf.toString("utf-8").slice(0, 300);
|
||||||
|
try {
|
||||||
|
detail = JSON.parse(detail).detail || detail;
|
||||||
|
} catch (e) {
|
||||||
|
/* 非 JSON 错误体 */
|
||||||
|
}
|
||||||
|
throw new HttpError(res.status, detail);
|
||||||
|
}
|
||||||
|
if (raw) {
|
||||||
|
return { status: res.status, headers: res.headers, body: buf };
|
||||||
|
}
|
||||||
|
// JSON(二进制接口用 raw)
|
||||||
|
const text = buf.toString("utf-8");
|
||||||
|
try {
|
||||||
|
return JSON.parse(text);
|
||||||
|
} catch (e) {
|
||||||
|
return { detail: text.slice(0, 300) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 流式下载(shell/chrome 大包,带进度回调):返回 {status, sha, contentLength}
|
||||||
|
async function streamDownload(urlPath, opts = {}) {
|
||||||
|
const { headers = {}, timeout = 600, onProgress, onData } = opts;
|
||||||
|
const url = `${baseUrl()}${urlPath}`;
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
|
||||||
|
} catch (e) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
const err = new Error(`下载失败: ${e.message}`);
|
||||||
|
err.status = 502;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const sha = crypto.createHash("sha256");
|
||||||
|
const total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||||
|
let received = 0;
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
sha.update(value);
|
||||||
|
received += value.length;
|
||||||
|
if (onData) onData(value);
|
||||||
|
if (onProgress) onProgress(received, total);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`下载中断: ${e.message}`);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
if (res.status >= 400) {
|
||||||
|
throw new HttpError(res.status, `下载失败 HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
return { status: res.status, sha256: sha.digest("hex"), contentLength: total, received };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { HttpError, request, machineHeaders, qs, streamDownload, baseUrl };
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// 执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。
|
||||||
|
// 对齐 Python creds_sync.py:RSA-2048 密钥对 + OAEP-SHA256 解密 + cache.json 密文缓存。
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const cp = require("./cpclient");
|
||||||
|
const config = require("./config");
|
||||||
|
const session = require("./session");
|
||||||
|
const { loadOrCreateRsaKey, rsaDecrypt } = require("./crypto");
|
||||||
|
const { makeLogger } = require("./logger");
|
||||||
|
|
||||||
|
const logger = makeLogger("creds-sync");
|
||||||
|
|
||||||
|
// 与服务端 config_push._ALLOWED_KEYS 保持一致(双重保障:下发限定范围)
|
||||||
|
const ALLOWED_KEYS = new Set([
|
||||||
|
"DINGTALK_APPKEY",
|
||||||
|
"DINGTALK_APPSECRET",
|
||||||
|
"DINGTALK_AGENT_ID",
|
||||||
|
"DINGTALK_CORP_ID",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const CREDS_DIR = path.join(config.APP_DATA, "creds");
|
||||||
|
const PRIV_PATH = path.join(CREDS_DIR, "id_rsa.pem");
|
||||||
|
const CACHE_FILE = path.join(CREDS_DIR, "cache.json");
|
||||||
|
|
||||||
|
let _priv = null;
|
||||||
|
|
||||||
|
function privateKey() {
|
||||||
|
if (!_priv) _priv = loadOrCreateRsaKey(PRIV_PATH);
|
||||||
|
return _priv;
|
||||||
|
}
|
||||||
|
|
||||||
|
function publicKeyPem() {
|
||||||
|
const key = privateKey();
|
||||||
|
return crypto.createPublicKey(key).export({ type: "spki", format: "pem" }).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function decrypt(cipherB64) {
|
||||||
|
return rsaDecrypt(privateKey(), cipherB64);
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveCache(encrypted) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(CREDS_DIR, { recursive: true });
|
||||||
|
fs.writeFileSync(CACHE_FILE, JSON.stringify(encrypted), "utf-8");
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`敏感凭证缓存写入失败: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadCache() {
|
||||||
|
if (!fs.existsSync(CACHE_FILE)) return {};
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
|
||||||
|
const out = {};
|
||||||
|
for (const [k, b64] of Object.entries(raw || {})) {
|
||||||
|
if (!ALLOWED_KEYS.has(k)) continue;
|
||||||
|
try {
|
||||||
|
out[k] = decrypt(b64);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`敏感凭证缓存解密失败: ${k}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
} catch (e) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 中心机在线拉取并解密敏感凭证;不可用返回 null(走缓存兜底)
|
||||||
|
async function sync(account) {
|
||||||
|
if (!config.CONTROLPLANE_URL || !account || !session.cloudToken(account)) return null;
|
||||||
|
try {
|
||||||
|
const headers = {
|
||||||
|
Authorization: `Bearer ${session.cloudToken(account)}`,
|
||||||
|
};
|
||||||
|
if (config.CONTROLPLANE_TOKEN) headers["X-API-Token"] = config.CONTROLPLANE_TOKEN;
|
||||||
|
// 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发)
|
||||||
|
await cp.request("POST", "/api/admin/creds/register", {
|
||||||
|
headers,
|
||||||
|
json: { account, pubkey_pem: publicKeyPem() },
|
||||||
|
timeout: 10,
|
||||||
|
});
|
||||||
|
// 2. 拉取加密后的敏感凭证
|
||||||
|
const r = await cp.request("GET", "/api/admin/creds", { headers, timeout: 10 });
|
||||||
|
const encrypted = r.creds || {};
|
||||||
|
if (Object.keys(encrypted).length === 0) return {};
|
||||||
|
// 3. 本机私钥逐个解密
|
||||||
|
const out = {};
|
||||||
|
for (const [k, b64] of Object.entries(encrypted)) {
|
||||||
|
if (!ALLOWED_KEYS.has(k)) continue;
|
||||||
|
try {
|
||||||
|
out[k] = decrypt(b64);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`敏感凭证解密失败: ${k}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 4. 密文原样落盘缓存(离线复用)
|
||||||
|
saveCache(encrypted);
|
||||||
|
return out;
|
||||||
|
} catch (e) {
|
||||||
|
logger.warning(`中心机敏感凭证拉取失败(用本地缓存): ${e.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(account = "") {
|
||||||
|
account = account || config.CONTROLPLANE_ACCOUNT;
|
||||||
|
if (!account) account = session.sessActiveAccount();
|
||||||
|
const synced = await sync(account);
|
||||||
|
if (synced !== null) return synced;
|
||||||
|
const cached = loadCache();
|
||||||
|
if (Object.keys(cached).length) logger.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)");
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { load, sync, publicKeyPem, decrypt, ALLOWED_KEYS, PRIV_PATH };
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// 密码学与通用工具:Ed25519 验签 / RSA-OAEP 解密 / sha256 / base64url / 版本比较。
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
// ==================== base64url(无填充解码,对齐 Python urlsafe_b64decode) ====================
|
||||||
|
function b64urlDecode(s) {
|
||||||
|
// JS 中 -len % 4 为负数(Python 为正补数),显式换算补位数
|
||||||
|
const pad = (4 - (s.length % 4)) % 4;
|
||||||
|
return Buffer.from(s + "=".repeat(pad), "base64url");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Ed25519 票据验签 ====================
|
||||||
|
// 票据格式:base64url(canonical_json).base64url(64B 签名);验签返回 payload 对象。
|
||||||
|
function verifyBlob(blob, publicKeyPem) {
|
||||||
|
if (typeof blob !== "string" || !blob.includes(".")) throw new Error("bad blob");
|
||||||
|
const idx = blob.lastIndexOf(".");
|
||||||
|
const b64 = blob.slice(0, idx);
|
||||||
|
const sig64 = blob.slice(idx + 1);
|
||||||
|
const canon = b64urlDecode(b64);
|
||||||
|
const sig = b64urlDecode(sig64);
|
||||||
|
if (sig.length !== 64) throw new Error("bad signature len");
|
||||||
|
const key = crypto.createPublicKey(publicKeyPem);
|
||||||
|
const ok = crypto.verify(null, canon, key, sig);
|
||||||
|
if (!ok) throw new Error("signature verification failed");
|
||||||
|
return JSON.parse(canon.toString("utf-8"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== RSA-2048 密钥对(creds 下发) ====================
|
||||||
|
// 私钥 PKCS8 PEM 落盘 %LOCALAPPDATA%\37duAutomation\creds\id_rsa.pem;公钥上报中心机。
|
||||||
|
function loadOrCreateRsaKey(privPath) {
|
||||||
|
if (fs.existsSync(privPath)) {
|
||||||
|
try {
|
||||||
|
const pem = fs.readFileSync(privPath, "utf-8");
|
||||||
|
return crypto.createPrivateKey(pem);
|
||||||
|
} catch (e) {
|
||||||
|
// 损坏则重新生成
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
|
||||||
|
modulusLength: 2048,
|
||||||
|
publicExponent: 0x10001,
|
||||||
|
publicKeyEncoding: { type: "spki", format: "pem" },
|
||||||
|
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
||||||
|
});
|
||||||
|
fs.mkdirSync(path.dirname(privPath), { recursive: true });
|
||||||
|
fs.writeFileSync(privPath, privateKey, { encoding: "utf-8", mode: 0o600 });
|
||||||
|
return privateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAEP-SHA256 解密 base64 密文 → 明文(与服务端 rsa_encrypt 对称)
|
||||||
|
function rsaDecrypt(privateKey, cipherB64) {
|
||||||
|
const ct = Buffer.from(cipherB64, "base64");
|
||||||
|
const pt = crypto.privateDecrypt(
|
||||||
|
{ key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
|
||||||
|
ct
|
||||||
|
);
|
||||||
|
return pt.toString("utf-8");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 通用工具 ====================
|
||||||
|
function sha256Hex(data) {
|
||||||
|
return crypto.createHash("sha256").update(data).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版本比较:数字段按 int,非数字段按 str 小写(对齐 Python licensing._version_lt)
|
||||||
|
function versionKey(s) {
|
||||||
|
return String(s)
|
||||||
|
.split(".")
|
||||||
|
.map((x) => (/^\d+$/.test(x) ? [1, parseInt(x, 10)] : [0, x.toLowerCase()]));
|
||||||
|
}
|
||||||
|
function versionLt(a, b) {
|
||||||
|
const ka = versionKey(a);
|
||||||
|
const kb = versionKey(b);
|
||||||
|
for (let i = 0; i < Math.max(ka.length, kb.length); i++) {
|
||||||
|
const x = ka[i] || [0, ""];
|
||||||
|
const y = kb[i] || [0, ""];
|
||||||
|
if (x[0] !== y[0]) return x[0] < y[0];
|
||||||
|
if (x[0] === 1) {
|
||||||
|
if (x[1] !== y[1]) return x[1] < y[1];
|
||||||
|
} else if (x[1] !== y[1]) return x[1] < y[1];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deadlinePassed(deadline) {
|
||||||
|
if (!deadline) return false;
|
||||||
|
const t = Date.parse(String(deadline).replace("Z", "+00:00"));
|
||||||
|
if (Number.isNaN(t)) return false;
|
||||||
|
return Date.now() > t;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nowStr() {
|
||||||
|
const d = new Date();
|
||||||
|
const p = (n) => String(n).padStart(2, "0");
|
||||||
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function newId() {
|
||||||
|
return Date.now().toString(16) + crypto.randomBytes(4).toString("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((r) => setTimeout(r, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
b64urlDecode,
|
||||||
|
verifyBlob,
|
||||||
|
loadOrCreateRsaKey,
|
||||||
|
rsaDecrypt,
|
||||||
|
sha256Hex,
|
||||||
|
versionLt,
|
||||||
|
deadlinePassed,
|
||||||
|
nowStr,
|
||||||
|
newId,
|
||||||
|
sleep,
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user