refactor: 重构项目目录结构与代码组织
1. 重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包 2. 移动并整理工具脚本到tools子目录,统一管理运维脚本 3. 重构插件运行时、调度、作业管理等核心模块到core子包 4. 更新AGENTS.md文档,明确各代码形态的组织规范 5. 清理重复的旧文件与冗余代码
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
# 后端完整模块化拆分方案(controlplane / webhost)
|
||||
|
||||
## Context(为什么做)
|
||||
|
||||
中心机 [controlplane/app.py](file:///d:/work/code/37duAutomation/controlplane/app.py)(1808 行)与执行机 [webhost/backend/main.py](file:///d:/work/code/37duAutomation/webhost/backend/main.py)(930 行)是两个单文件 FastAPI 后端。代码本身**组织清晰**(`_xxx` 私有函数 + `@app` 路由直挂、职责分段明确),但在用链路里承载了多个领域(DB、鉴权、密钥签名、插件托管、license、钉钉扫码、run 执行、会话……),单文件承载多职责导致定位/协同/演进困难。
|
||||
|
||||
按 AGENTS.md 第 3 节「代码形态分三类」——各后端按正常模块化项目开发、允许多文件拆分。用户已确认:**完整模块化拆分**,且**插件保持自包含、不引用插件包外代码**(本次不涉及插件改造)。
|
||||
|
||||
关键前提(已核实,决定方案可行性):
|
||||
- 两处均用 `app = FastAPI(...)` 后 `@app.*` 直接绑定路由,**非 APIRouter** → 需机械改写为 `APIRouter` + 入口 `include_router`。
|
||||
- controlplane 用 PyInstaller 打包,[37du-center.spec](file:///d:/work/code/37duAutomation/controlplane/37du-center.spec) 以 `app.py` 为 Analysis 入口、`hiddenimports=[]` → 只要**保留入口文件名 `app.py`(webhost 为 `main.py`)不变、全部用静态 import**,打包自动跟随 import 图收集子模块,兼容不受影响。
|
||||
|
||||
## 目标与硬性原则
|
||||
|
||||
1. **行为零变化**:所有路由路径、HTTP 方法、路径参数、请求/响应体、鉴权依赖、状态迁移逻辑**一字不改**,只做「移动 + APIRouter 改写 + 静态 import」。不允许顺手改逻辑。
|
||||
2. **保留入口文件名**:controlplane 仍是 `app.py`,webhost 仍是 `main.py`,作为「组装层」(建 app / lifespan / include_router / 静态挂载 / uvicorn)。兼容启动命令与 spec。
|
||||
3. **静态 import 导出依赖**:所有跨模块传引用一律显式 `import`,**禁止动态 import / 字符串 import**(否则 PyInstaller hiddenimports 失效)。
|
||||
4. **避免环形 import**:依赖方向单向 —— `routes/apis/* → 领域逻辑模块 → config/state → (stdlib)`;assembler 层是唯一 include 各路由的地方。
|
||||
5. **共享状态集中**:原模块级可变全局(DB 连接、RUNS、_SESS 等)抽到 `state.py`/`config.py`,各模块 import,杜绝重复定义导致状态分叉。
|
||||
6. **AGENTS.md 约束**:仅操作本地 `.venv`;不污染全局;环境变量仍各读本模块 `.env`。
|
||||
|
||||
## 阶段 A:执行机 webhost/backend(先行,930 行小、先固化套路)
|
||||
|
||||
将 `main.py` 拆为:入口 `main.py` + 配置/状态 + 领域逻辑 + `apis/` 路由子包。
|
||||
|
||||
```
|
||||
webhost/backend/
|
||||
main.py # 组装层:lifespan、app=FastAPI、include_router、static mount、uvicorn(原 L258-276、L909-930)
|
||||
config.py # 配置固化:_load_dotenv、PORT、DIST、控制面/钉钉环境常量(原 L46-95 配置文件段)
|
||||
state.py # 模块级可变全局:_SESS/_SESS_LOCK、PLATFORMS、RUNS、RUN_LOCK、ALLOWED、_NS_LOCKS、_port_free
|
||||
session.py # 会话:_sess_persist/_sess_load/_sess_account/_require_login/_login_state_new/_login_state_take(原 L87-142、L418-432 纯逻辑)
|
||||
cpapi.py # 控制面集成:_resolve_allowed/_cp_headers/_cp_call/_sync_licensing(原 L183-229、L234)
|
||||
runner.py # run 执行:RunReq/_set_run/_run_target/_report_run(原 L170-204、L719-827、L829-844)
|
||||
meta.py # 插件元数据/平台权限:_plugin_schema/_read_own_manifest/_fields_from_schema/_account_allowed_platforms/_cloud_plugin_ids(原 L569-663)
|
||||
apis/
|
||||
__init__.py
|
||||
admin.py # router=APIRouter:/api/admin/me、/login、/logout、/password、/overview(原路由改写)
|
||||
dingtalk.py # router:/api/admin/dingtalk/*、/api/auth/dingtalk、/auth/done(原 L331-536 路由段)
|
||||
meta.py # router:/api/meta、/api/platforms/{pid}/login|logout(原 L666-717 路由段)
|
||||
runs.py # router:/api/runs、/api/runs/{run_id}、@app.websocket(/ws)(原 L846-915 路由段)
|
||||
```
|
||||
|
||||
- APIRouter 支持 `websocket`(`APIRouter(websocket=...)`),`/ws` 原样迁移,HUB 逻辑不动。
|
||||
- main.py 需 `from webhost.backend import auth as platform_auth`(现有 [auth.py](file:///d:/work/code/37duAutomation/webhost/backend/auth.py))保留不动;新增 `session.py` 只接管 main.py 内会话逻辑,避免与现有 auth.py 混淆。
|
||||
|
||||
## 阶段 B:中心机 controlplane(后做,1808 行大)
|
||||
|
||||
将 `app.py` 拆为:入口 `app.py` + 配置/状态/领域逻辑 + `apis/` 路由子包。保留入口 `app.py` 以保证 spec 兼容。
|
||||
|
||||
```
|
||||
controlplane/
|
||||
app.py # 组装层:lifespan、app=FastAPI、include_router、static mount、LOG_CONFIG、uvicorn(原 L463、L1767-1808)
|
||||
config.py # 配置固化:_load_dotenv、APP_DIR/DB_PATH/PKG_DIR、CONTROLPLANE_TOKEN、钉钉常量、DIST(原 L48-94、L1767-1772)
|
||||
db.py # DB 层:_db()/_ensure_col/_init_db/_load_or_create_keypair 及全部建表(原 L166-283)
|
||||
crypto.py # 密码学:_sign_admin_token/_verify/_hash_password/_verify_password/_sign_blob/_verify_blob/_pubkey_pem(原 L103-168、L284-335)
|
||||
auth.py # 鉴权:_check_token/_require_admin/_resolve_login/_auth_gate/_auth_fail/_audit/_seed(原 L337-447)
|
||||
pkgutil.py # 插件包:_load_manifest/_validate_pkg_zip/_extract_manifest/_prune_versions/_version_key(原 L521、L718-777)
|
||||
dingtalk.py # 钉钉纯逻辑:_dingtalk_get_json/_dingtalk_post_json/_dingtalk_topapi_token/_dingtalk_userinfo/_dingtalk_sns_userinfo(原 L904-1036)
|
||||
schemas.py # pydantic 模型:PluginOut/AuthIn/DingTalkIn/SnsIn/RuntimeReportIn 等(原散落)
|
||||
apis/
|
||||
__init__.py
|
||||
plugins.py # /api/plugins、/platforms/allowed、/api/manifest、/api/pkg、/api/me/pubkey、/api/me/license、/api/me/control-list、/download-ticket、/api/download、/api/runtime/report
|
||||
auth.py # /auth/exchange、/api/admin/dingtalk/auth(登录与会话侧)
|
||||
dingtalk.py # /api/admin/dingtalk/scan、/cb、/sns
|
||||
admin.py # /api/admin/me、platforms、auth、overview、accounts、/api/admin/pkg、account_plugins
|
||||
```
|
||||
|
||||
- 控制面路由相对收敛,按「公开分发面 / 登录与会话 / 钉钉扫码 / admin 管理面」归并为 4 个路由模块,避免过度碎片化。
|
||||
- 控制面 `_auth_gate`/`_base45` 等被多路由复用的鉴权依赖统一由 `auth.py` 导出。
|
||||
|
||||
## 验证方案(每个阶段独立,先 A 后 B)
|
||||
|
||||
1. **静态校验**:`.venv\Scripts\python -m py_compile` 所有改动文件;`python -c "import ..."` 确认无循环 import。
|
||||
2. **行为对照**:用 `git diff` 逐项核对路由路径、方法、装饰器改写无丢失;对外签名(函数/类名)保持不变。
|
||||
3. **启动冒烟(执行机)**:启动 uvicorn(`python -m webhost.backend.main` 或对应入口),打 `/api/admin/me`、`/api/meta`、`/health`,确认返回与原一致;`/ws` 能握手。
|
||||
4. **启动冒烟(控制面)**:`python controlplane/app.py`,打 `/health`、`/api/manifest`、`/api/plugins`,确认正常。
|
||||
5. **前端回归**:两个仓库各自 `frontend/dist` 挂载,浏览器访问首页正常、登录/插件页可用(需用户配合手动点验,或由用户执行)。
|
||||
6. **打包回归(控制面)**:最后用现有 spec 重打 exe,确认新子模块被收集(`hiddenimports` 无需补)。此项用户如暂不打包可延后。
|
||||
|
||||
## 风险与注意
|
||||
|
||||
- **最大风险是机械改写遗漏**:1808 行 route 迁移量大。缓解:每阶段用 `git diff` 做「路径清单对照表」(改前 grep `@app.` 全集 vs 改后各 `APIRouter` 全集,逐条核对)。
|
||||
- **状态 split brain**:不能把共享全局复制到多处。所有可变状态只允许放 `state.py`/`config.py` 单点。
|
||||
- **不要顺手改逻辑**:重构期间发现的小 bug 只登记不改,避免混淆「重构」与「修复」的验证边界(符合 AGENTS 稳妥演进)。
|
||||
- **分阶段提交**:阶段 A(执行机)独立验证通过后,再进入阶段 B(控制面),每个阶段一个 commit,降低回归面。
|
||||
@@ -13,6 +13,10 @@ AI 智能体开发约束 & 项目执行规范
|
||||
3. 项目通用架构规范
|
||||
- 代码组织:不同业务、不同流程独立模块化运行,互不侵入、互不影响。
|
||||
- 四方向零依赖:项目同时存在四个独立演进方向,各自目录(controlplane/ 中心机、webhost/ 部署机底座、app/ 蓝图版、workflows/ 影刀版)之间【绝不跨目录 import】,登录/数据导出等数据层各自内置(允许少量重复换取完全解耦),任一方向可单独拷贝、单独演进、独享依赖与启动。
|
||||
- 代码形态分三类,按各方向性质采用不同组织方式(【单文件自包含】仅适用于影刀版,其它一律按正常项目开发):
|
||||
- workflows/(影刀版):沿用单文件自包含架构(见第 2 节,仅影刀适用)。
|
||||
- 各后端(controlplane/ 中心机、webhost/ 执行机底座、app/ 蓝图版):按正常 Python 模块化项目开发,允许按包/模块/多文件拆分(如 main.py/app.py 分割逻辑与路由),不做单文件约束。
|
||||
- 插件(webhost 加载的执行单元,如 plugins/seal_check/):内部按正常项目组织,可拆 config/data/logic/report 等多文件;但强调【插件自包含】——插件内模块只能互相引用、依赖 Python 标准库/第三方依赖/底座注入的插件接口,严禁 import 插件包之外的任何代码(根目录、webhost 底座业务、controlplane、app 一律禁止),保证插件完整交付物=插件包本身,可单独拷贝发布、独立演进。
|
||||
- 环境变量按模块隔离,各自使用自己目录下的 .env,互不覆盖、互不依赖:
|
||||
- 根目录 .env:仅供 workflows/(影刀) 脚本使用,承载各 XQ 业务路径/账号等配置;禁止向根 .env 写入 webhost/app/controlplane 的变量。
|
||||
- app/ → app/.env(app 版业务配置)
|
||||
@@ -25,5 +29,5 @@ AI 智能体开发约束 & 项目执行规范
|
||||
4. AI 工作默认规则
|
||||
- 所有代码生成、修改、重构必须贴合 Python 模块化编程思想。
|
||||
- 不主动创建冗余文件、不随意变更项目结构、不混用沙箱环境。
|
||||
- 输出代码优先保证:可运行、结构清晰、符合项目统一规范、适配影刀单文件自包含特性。
|
||||
- 变量配置规范:禁止使用命令行传入变量的方式实现参数配置,所有参数、变量、配置项均在代码/配置文件内部定义、固化或读取本地配置,保证单文件自包含、运行无外部参数依赖。
|
||||
- 输出代码优先保证:可运行、结构清晰、符合项目统一规范、按代码形态适配(单文件自包含仅影刀版需要;后端与插件按正常模块化项目开发)。
|
||||
- 变量配置规范:禁止使用命令行传入变量的方式实现参数配置,所有参数、变量、配置项均在代码/配置文件内部定义、固化或读取本地配置,保证运行无外部参数依赖。
|
||||
@@ -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,508 @@
|
||||
# -*- 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 fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _require_admin
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
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(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 account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd "
|
||||
"FROM accounts ORDER BY account")]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
a["grants"] = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@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:
|
||||
"""新建账号:密码必填,可指定部门/昵称/是否管理员。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
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) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||||
(a.nickname or "").strip()))
|
||||
conn.commit()
|
||||
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 = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
if a.dept is not None:
|
||||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||||
((a.dept or "").strip(), account))
|
||||
if a.nickname is not None:
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
((a.nickname or "").strip(), account))
|
||||
if a.is_admin is not None:
|
||||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||||
if a.is_admin:
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||||
else:
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||||
(account, login))
|
||||
conn.commit()
|
||||
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:
|
||||
"""管理员重置任意账号密码(无需原密码)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
_hex, _salt = _hash_password(r.new_password)
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
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 = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
# ==================== 授权 / 插件维护 ====================
|
||||
@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 撤;同时维护插件级授权表。"""
|
||||
_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 = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
(account, plugin_id))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
|
||||
"can_download = excluded.can_download, can_run = excluded.can_run",
|
||||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"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 撤。"""
|
||||
_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 = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||||
(account, platform_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
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 个版本。"""
|
||||
_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
|
||||
content = await upload.read()
|
||||
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 (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
|
||||
"name = excluded.name, manifest = excluded.manifest"
|
||||
+ (", description = excluded.description" if manifest else "")
|
||||
+ (", category = excluded.category" if manifest else "")
|
||||
+ (", icon = excluded.icon" if manifest else ""),
|
||||
(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 (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
|
||||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (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
|
||||
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:
|
||||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||||
_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 = ?", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||||
files = [dict(r)["filename"] for r in conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.commit()
|
||||
for fn in files:
|
||||
try:
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
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 = ?"); vals.append(d.name.strip())
|
||||
if d.description:
|
||||
fields.append("description = ?"); vals.append(d.description.strip())
|
||||
if d.category:
|
||||
fields.append("category = ?"); vals.append(d.category.strip())
|
||||
if d.icon:
|
||||
fields.append("icon = ?"); vals.append(d.icon.strip())
|
||||
if d.status in ("published", "disabled", "revoked"):
|
||||
fields.append("status = ?"); vals.append(d.status)
|
||||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||||
if d.force_min_version and d.force_deadline:
|
||||
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
|
||||
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 = ?", (pid,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
return {"ok": True, "plugin_id": pid}
|
||||
|
||||
|
||||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||
@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 = ? ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM plugin_grants "
|
||||
"WHERE plugin_id = ?", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT account, is_admin, dept, nickname FROM accounts ORDER BY account")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants "
|
||||
"WHERE account = ?", (a["account"],))}
|
||||
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/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 substr(at,1,10) AS day, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||||
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
|
||||
).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")]
|
||||
|
||||
# 最近运行列表
|
||||
recent = [dict(r) for r in conn.execute(
|
||||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||||
"FROM runtime_reports WHERE status <> 'start' "
|
||||
"ORDER BY id DESC LIMIT 20")]
|
||||
|
||||
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"], "")
|
||||
for rc in recent:
|
||||
rc["nickname"] = nick.get(rc.get("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,
|
||||
"recent": recent, "today": now_day,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/audit")
|
||||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
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 "
|
||||
"ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
|
||||
|
||||
@router.get("/api/admin/reports")
|
||||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""运行上报记录(最新在前)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
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, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
@@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""账号登录与身份路由:当前账号信息 / 可授权平台 / 账号密码登录 / 自助改密 / 员工端扫码换 token。
|
||||
|
||||
- 管理写操作(改他人账号/插件)统一走 apis.admin(_require_admin);
|
||||
- 此处为"自助/登录"类只读或本账号操作。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_account_lookup, _auth_fail, _auth_gate, _check_token,
|
||||
_resolve_login, _require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
from controlplane.core.dingtalk import _dingtalk_userinfo
|
||||
|
||||
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(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""查询当前账号信息:管理员标识 + 部门 + 昵称。"""
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
return {"account": account,
|
||||
"is_admin": bool(row and row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or "",
|
||||
"nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
@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 决定。"""
|
||||
_check_token(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, must_change_pwd FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||
_auth_fail(account)
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(p: schemas.PwdIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
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 = ?",
|
||||
(login,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "账号不存在")
|
||||
# 首次登录(must_change_pwd=1,钉钉自动建号的默认密码)允许免旧密码直接改密
|
||||
if not row["must_change_pwd"] and (
|
||||
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 = ?, salt = ?, must_change_pwd = 0 "
|
||||
"WHERE account = ?", (_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)。
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600
|
||||
_cloud_tokens: dict = {}
|
||||
_cloud_lock = threading.Lock()
|
||||
|
||||
|
||||
@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, "扫码未解析到有效账号,请重新扫码")
|
||||
acct = _auth_account_lookup(account)
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
# 惰性清理过期云端会话,防内存无限增长
|
||||
for k in [k for k, v in _cloud_tokens.items() if v["exp"] < now]:
|
||||
_cloud_tokens.pop(k, None)
|
||||
_cloud_tokens[token] = {"exp": now + _CLOUD_TOKEN_TTL, "account": account,
|
||||
"nickname": acct["nickname"] or (info.get("nickname") or "")}
|
||||
return {"token": token,
|
||||
"account": account, "nickname": acct["nickname"] or (info.get("nickname") or ""),
|
||||
"exists": bool(acct["exists"]), "is_admin": False}
|
||||
@@ -0,0 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉扫码路由:找建账号 / OAuth 扫码页 + 回调 / 内嵌二维码(DDLogin)。
|
||||
|
||||
- 账号建立/鉴权统一走 /api/admin/dingtalk/auth(find-or-create,仅底座 X-API-Token 可调);
|
||||
- /scan→/cb 与 /sns 仅为可信扫码入口,仅换取身份不建号(建号仍由 auth 把关)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import secrets
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
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
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@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 FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
|
||||
if nickname and nickname != (row["nickname"] or ""):
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
(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 (?, ?, ?, 0, '', ?, ?, 1)",
|
||||
(account, _hex, _salt, nickname, ding_uid))
|
||||
conn.commit()
|
||||
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 (back.startswith("http://") or back.startswith("https://")):
|
||||
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 (state.startswith("http://") or state.startswith("https://")):
|
||||
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)}
|
||||
@@ -0,0 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""基础元信息路由:健康检查。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from controlplane import config
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": config.DB_PATH.name}
|
||||
@@ -0,0 +1,235 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
|
||||
|
||||
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
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
|
||||
from controlplane.core.pkgutil import _load_manifest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@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")
|
||||
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 = ?
|
||||
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")
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
|
||||
(acct,),
|
||||
).fetchall()
|
||||
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
|
||||
|
||||
|
||||
@router.get("/api/manifest")
|
||||
def manifest(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全量插件版本清单:客户端据此比对是否需要拉新包。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT p.id, p.name, p.latest_version AS version, pv.uploaded_at,
|
||||
p.status, p.category, pv.sha256 AS pkg_sha256, p.manifest
|
||||
FROM plugins p
|
||||
LEFT JOIN plugin_versions pv ON pv.plugin_id = p.id AND pv.version = p.latest_version
|
||||
ORDER BY p.id
|
||||
"""
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
m = _load_manifest(item.pop("manifest"))
|
||||
item["manifest"] = m
|
||||
item["capabilities"] = m.get("capabilities") or []
|
||||
item["permissions"] = m.get("permissions") or {}
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
item["field_count"] = len(props)
|
||||
out.append(item)
|
||||
return {"plugins": out, "generated_at": _now()}
|
||||
|
||||
|
||||
@router.get("/api/pkg/{plugin_id}/{version}")
|
||||
def pkg(plugin_id: str, version: str,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||
"""下载指定版本插件包。包文件存磁盘,DB 记 filename 索引。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
(plugin_id, version),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||
path = config.PKG_DIR / row["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||||
_audit("", "download", f"{plugin_id}@{version}")
|
||||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
# ==================== 产品化:客户端(部署端)拉取接口 ====================
|
||||
@router.get("/api/me/pubkey")
|
||||
def me_pubkey() -> dict:
|
||||
"""下发中心机公钥(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 签名。
|
||||
|
||||
票据无硬过期——部署端离线时凭缓存副本持续可用(符合"不联网一直能用")。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
if not account.strip():
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
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 plugin_grants g
|
||||
JOIN plugins p ON p.id = g.plugin_id
|
||||
WHERE g.account = ?
|
||||
""",
|
||||
(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]
|
||||
blob = crypto._sign_blob({"userId": account.strip(), "deviceId": device or "",
|
||||
"issuedAt": _now(), "plugins": plugins})
|
||||
return {"ticket": blob, "plugins": plugins, "issuedAt": _now()}
|
||||
|
||||
|
||||
@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 签名。"""
|
||||
_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()}
|
||||
return {"ticket": crypto._sign_blob(payload), "control": payload}
|
||||
|
||||
|
||||
# 一次性下载票据(内存态,兑换后失效)
|
||||
_DL_TICKETS: dict = {}
|
||||
|
||||
|
||||
@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 plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
(account.strip(), plugin_id)).fetchone()
|
||||
ver = conn.execute(
|
||||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
(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']}")
|
||||
# 票据内含可下载文件名与校验值;用一次性 nonce 存内存,兑换后失效
|
||||
nonce = secrets.token_hex(16)
|
||||
_DL_TICKETS[nonce] = {"filename": ver["filename"], "sha256": ver["sha256"] or "",
|
||||
"used": False}
|
||||
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)
|
||||
item = _DL_TICKETS.get(ticket)
|
||||
if not item or item["used"]:
|
||||
raise HTTPException(404, "下载票据无效或已使用")
|
||||
item["used"] = True
|
||||
path = config.PKG_DIR / item["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{item['filename']}")
|
||||
_audit("", "download-ticket", item["filename"])
|
||||
return FileResponse(path, filename=item["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 (?,?,?,?,?,?,?,?)",
|
||||
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
+30
-1747
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 领域逻辑核心(core)包:配置/数据/密码学/鉴权/插件包/钉钉/模型。"""
|
||||
@@ -0,0 +1,152 @@
|
||||
# -*- 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 threading
|
||||
import time
|
||||
|
||||
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-API-Token) + 登录票据(X-Admin-Token)对应账号 is_admin=1。返回账号。"""
|
||||
_check_token(x_api_token)
|
||||
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 1 FROM accounts WHERE account = ? AND is_admin = 1", (account,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||
return account
|
||||
|
||||
|
||||
def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
x_admin_user: str = "") -> str:
|
||||
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin)。
|
||||
|
||||
1. 优先验签名票据 X-Admin-Token(控制台直连场景);
|
||||
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||||
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
if account:
|
||||
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")
|
||||
|
||||
|
||||
# ==================== 登录防爆破(进程内计数,失败锁定退避) ====================
|
||||
_AUTH_FAILS: dict = {} # account -> [连续失败次数, 锁定截止时间戳]
|
||||
_AUTH_FAIL_LIMIT = 5 # 连续失败 N 次后锁定
|
||||
_AUTH_LOCK_SECS = 300 # 锁定 5 分钟
|
||||
|
||||
|
||||
def _auth_gate(account: str) -> None:
|
||||
fails, locked_until = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
if locked_until > time.time():
|
||||
raise HTTPException(429, f"失败次数过多,账号已临时锁定,请 {int(locked_until - time.time())} 秒后重试")
|
||||
|
||||
|
||||
def _auth_fail(account: str) -> None:
|
||||
fails, _ = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
fails += 1
|
||||
if fails >= _AUTH_FAIL_LIMIT:
|
||||
_AUTH_FAILS[account] = (0, time.time() + _AUTH_LOCK_SECS)
|
||||
else:
|
||||
_AUTH_FAILS[account] = (fails, 0.0)
|
||||
|
||||
|
||||
# ==================== 云端会话 token(员工端扫码登录,§2.2) ====================
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600 # 云端会话 token 有效期(秒,7 天)
|
||||
_cloud_tokens: dict = {} # token -> {exp, account, nickname};壳持此调云端 API
|
||||
_cloud_lock = threading.Lock()
|
||||
|
||||
|
||||
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 = ?", (account.strip(),)).fetchone()
|
||||
return {"exists": bool(row), "nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
def _cloud_account(bearer: str) -> str:
|
||||
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。"""
|
||||
token = (bearer or "").strip()
|
||||
if token.lower().startswith("bearer "):
|
||||
token = token[7:].strip()
|
||||
if not token:
|
||||
return ""
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
rec = _cloud_tokens.get(token)
|
||||
if rec and rec["exp"] >= now:
|
||||
return rec["account"]
|
||||
if rec: # 过期顺手清理,防内存无限增长
|
||||
_cloud_tokens.pop(token, None)
|
||||
return ""
|
||||
@@ -0,0 +1,86 @@
|
||||
# -*- 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
|
||||
return Path(__file__).resolve().parent
|
||||
|
||||
|
||||
APP_DIR = _app_base()
|
||||
DB_PATH = APP_DIR / "controlplane.db"
|
||||
PKG_DIR = APP_DIR / "packages"
|
||||
|
||||
|
||||
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"))
|
||||
# 钉钉扫码自动建号的初始密码;新号无插件权限、仅空壳,首次登录须改密。
|
||||
DINGTALK_DEFAULT_PASSWORD = os.getenv("DINGTALK_DEFAULT_PASSWORD", "123456")
|
||||
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||
# 同一套 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("/")
|
||||
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > 首次随机生成并
|
||||
# 持久化到 .admin_secret(保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") 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
|
||||
|
||||
|
||||
# 前端产物目录:源码 controlplane/frontend/dist;打包 _MEIPASS/frontend/dist(打进 exe)
|
||||
DIST = Path(getattr(sys, "_MEIPASS", APP_DIR)) / "frontend" / "dist"
|
||||
@@ -0,0 +1,89 @@
|
||||
# -*- 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.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机数据层:SQLite 访问 + 建表 + 种子 + 审计 + 常用时间戳。
|
||||
|
||||
数据访问统一收敛到 `_db()` 连接(commit+close 收口),路由只在本层之上组合读写。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(统一收口,避免长运行服务累积连接)。
|
||||
|
||||
sqlite3 原生 with 语义只 commit 不 close,这里补 close;异常时不 commit 等价于回滚。
|
||||
"""
|
||||
conn = sqlite3.connect(config.DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _ensure_col(conn: sqlite3.Connection, table: str, col: str, ddl: str) -> None:
|
||||
"""幂等给表补列:列已存在则忽略(sqlite 无 ADD COLUMN IF NOT EXISTS)。"""
|
||||
cols = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
if col not in cols:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
|
||||
|
||||
|
||||
def _init_db() -> None:
|
||||
"""建表(幂等)。基础表 + 产品化扩展表(插件授权/审计/运行上报),并兼容旧库补列。"""
|
||||
with _db() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
latest_version TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
plugin_id TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
uploaded_at TEXT NOT NULL,
|
||||
PRIMARY KEY (plugin_id, version)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, platform_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
account TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
dept TEXT DEFAULT '',
|
||||
nickname TEXT DEFAULT '',
|
||||
dingtalk_uid TEXT DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_grants (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
can_download INTEGER DEFAULT 1,
|
||||
can_run INTEGER DEFAULT 1,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
target TEXT DEFAULT '',
|
||||
detail TEXT DEFAULT '',
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
device_id TEXT DEFAULT '',
|
||||
plugin_id TEXT DEFAULT '',
|
||||
version TEXT DEFAULT '',
|
||||
status TEXT DEFAULT '',
|
||||
msg TEXT DEFAULT '',
|
||||
duration_sec INTEGER DEFAULT 0,
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
# 幂等补齐旧表可能缺失的可选列(sqlite ALTER 不支持 ADD COLUMN IF NOT EXISTS)
|
||||
_ensure_col(conn, "plugins", "description", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "category", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "icon", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "status", "TEXT DEFAULT 'published'")
|
||||
_ensure_col(conn, "plugins", "force_min_version", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "force_deadline", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "manifest", "TEXT DEFAULT '{}'")
|
||||
_ensure_col(conn, "plugin_versions", "sha256", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "runtime_reports", "duration_sec", "INTEGER DEFAULT 0")
|
||||
_ensure_col(conn, "accounts", "nickname", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "dingtalk_uid", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "must_change_pwd", "INTEGER DEFAULT 0")
|
||||
# 回填:老库 account_plugins 已有授权但 plugin_grants 为空,则按"全权限"补录,
|
||||
# 保证离线票据 license 不会漏掉存量授权(can_download=1, can_run=1)。
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"SELECT ap.account, ap.plugin_id, 1, 1 FROM account_plugins ap "
|
||||
"LEFT JOIN plugin_grants g ON g.account = ap.account AND g.plugin_id = ap.plugin_id "
|
||||
"WHERE g.account IS NULL"
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _seed() -> None:
|
||||
"""首次启动写入插件种子 + 默认管理员(puddy),并生成示例包。
|
||||
|
||||
不再种子 demo 普通账号(alice/bob 曾带弱口令入生产库),普通账号一律由管理员建号。
|
||||
"""
|
||||
config.PKG_DIR.mkdir(exist_ok=True)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugins(id, name, latest_version) VALUES (?, ?, ?)",
|
||||
("seal_check", "考勤月报封存检查", "1.0.0"),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||||
for _acc, _dept in (("puddy", "IT"),):
|
||||
_hex, _salt = _hash_password("123456")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (?, ?, ?, ?, ?)", (_acc, _hex, _salt, 1, _dept))
|
||||
conn.commit()
|
||||
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
pkg.write_bytes(b"# placeholder controlplane package v1.0.0\n")
|
||||
|
||||
|
||||
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 (?,?,?,?,?)",
|
||||
(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,3 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MC4CAQAwBQYDK2VwBCIEINebsZBPVReZkreG8WzWLbqQ1YCfQixhfvbDhAg8NUM7
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,3 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEAixXXpXRAdY3HDgNzmP5wETRTCwGpcBV8NRVy79RylTU=
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,91 @@
|
||||
# -*- 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
|
||||
_PKG_REQUIRED_FILES = ("plugin.json", "main.py", "requirements.txt")
|
||||
_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 = ?", (plugin_id,)).fetchall()
|
||||
stale = sorted(rows, key=lambda r: _version_key(r["version"]), reverse=True)[_KEEP_VERSIONS:]
|
||||
for r in stale:
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
(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,100 @@
|
||||
# -*- 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 AuthIn(BaseModel):
|
||||
account: str
|
||||
password: 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
|
||||
|
||||
|
||||
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 = 清除强制更新配置
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 运维/构建工具集(CLI、PyInstaller spec、Windows 运维脚本)。"""
|
||||
@@ -19,10 +19,10 @@
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
运行(项目 .venv):
|
||||
python -m controlplane.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.agent_cli plugins
|
||||
python -m controlplane.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.agent_cli users
|
||||
python -m controlplane.tools.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.tools.agent_cli plugins
|
||||
python -m controlplane.tools.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.tools.agent_cli users
|
||||
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -37,7 +37,7 @@ import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent
|
||||
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
@@ -10,11 +10,11 @@ net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & ex
|
||||
|
||||
set "TARGET=D:\code\controlplane"
|
||||
|
||||
rem locate exe: same folder as this bat, or under dist\ subfolder
|
||||
if exist "%~dp037du-center.exe" (
|
||||
set "SRC=%~dp037du-center.exe"
|
||||
rem locate exe: parent folder (controlplane/), or its dist\ subfolder
|
||||
if exist "%~dp0..\37du-center.exe" (
|
||||
set "SRC=%~dp0..\37du-center.exe"
|
||||
) else (
|
||||
set "SRC=%~dp0dist\37du-center.exe"
|
||||
set "SRC=%~dp0..\dist\37du-center.exe"
|
||||
)
|
||||
if not exist "%SRC%" (echo [ERROR] Not found: 37du-center.exe & pause & exit /b 1)
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端:场景插件宿主
|
||||
"""
|
||||
"""webhost 后端(执行机底座):场景插件宿主。
|
||||
|
||||
组装层 main.py 之外的领域逻辑已归入 core 子包。本 `__init__` 作为 facade 再导出
|
||||
core 内各模块,以兼容 `from webhost.backend import X` 的既有用法(含插件 `auth` 引用)。
|
||||
"""
|
||||
from webhost.backend.core import ( # noqa: F401
|
||||
auth,
|
||||
config,
|
||||
cpapi,
|
||||
hub,
|
||||
licensing,
|
||||
meta,
|
||||
runner,
|
||||
scheduler,
|
||||
session,
|
||||
state,
|
||||
winjob,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 API 路由子包:各领域路由模块导出 APIRouter,由 backend/main.py 组装 include。"""
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
@router.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(b.account.strip())
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
@router.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
|
||||
|
||||
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
|
||||
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _ACCT_CLOUD_TOKEN, _SESS,
|
||||
_SESS_LOCK, _sess_persist)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 登录回跳 state 有效期与缓存(防 CSRF 回跳伪造)
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class _DingTalkIn(BaseModel):
|
||||
account: str # 钉钉工号(作为统一账号)
|
||||
nickname: str = "" # 钉钉姓名
|
||||
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
|
||||
|
||||
|
||||
class _InlineIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
|
||||
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
|
||||
|
||||
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
|
||||
"""
|
||||
r = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/auth",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
|
||||
acct = r.get("account") or account
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (acct, time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/login")
|
||||
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
|
||||
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
|
||||
if not d.account:
|
||||
raise HTTPException(400, "工号不能为空")
|
||||
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/inline")
|
||||
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
|
||||
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
|
||||
|
||||
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
|
||||
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
info = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/sns",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"code": d.code.strip()})
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return _cp_call(
|
||||
"GET", "/api/admin/dingtalk/inline_qr",
|
||||
params={"back": back},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
|
||||
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
|
||||
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
|
||||
<script>
|
||||
(async function(){
|
||||
var q = new URLSearchParams(location.search);
|
||||
var account = q.get('account') || '';
|
||||
var nickname = q.get('nickname') || '';
|
||||
if (account) {
|
||||
try {
|
||||
await fetch('/api/admin/dingtalk/login', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ account: account, nickname: nickname })
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
try { window.opener && window.opener.location.reload(); } catch (e) {}
|
||||
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
|
||||
})();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/qr")
|
||||
def dingtalk_qr(request: Request) -> dict:
|
||||
"""返回中心机扫码登录 URL。
|
||||
|
||||
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
|
||||
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
|
||||
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return {"url": ""}
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return {"url": f"{config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb() -> HTMLResponse:
|
||||
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
|
||||
return HTMLResponse(_DINGTALK_CB_HTML)
|
||||
@@ -0,0 +1,67 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「业务元数据与平台登录」路由:/api/meta 聚合 + 平台真实登录/登出。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
|
||||
online = licensing.is_online()
|
||||
deny = licensing.run_check_allowed(plugin.id, account, online)
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端领域逻辑核心(core)包。
|
||||
|
||||
鉴权/会话/调度/执行/控制面集成/单活/Job 托管等实现模块集合。
|
||||
"""
|
||||
@@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主配置固化:加载本模块 env(webhost/.env) 并输出全部环境常量与路径。
|
||||
|
||||
依赖方向:config ← 所有领域逻辑与路由模块(只读,不含业务逻辑)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/config.py,parents[1]=webhost)
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
PORT = 8799
|
||||
DIST = _HOST_ROOT / "frontend" / "dist"
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = _HOST_ROOT / ".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 as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 .env 失败: %s", _exc)
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
|
||||
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
|
||||
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
|
||||
@@ -0,0 +1,85 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 ↔ 中心机(统一后端) 集成:权限白名单解析 + 数据库 API 代理 + 离线授权同步。
|
||||
|
||||
底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if config.PLUGIN_SOURCE != "controlplane" or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
if not config.CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": config.CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", config.CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{config.CONTROLPLANE_URL}{path}", timeout=30, **kw)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
body = {"detail": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
|
||||
return body
|
||||
|
||||
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
licensing.flush_offline_reports()
|
||||
@@ -0,0 +1,114 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主插件元数据 / 平台权限解析。
|
||||
|
||||
- 插件元数据由 plugin.json(manifest) 驱动,离线与旧插件兼容
|
||||
- 平台/插件白名单来自中心机,按账号过滤(三态降级:授权集 / 空集防越权 / None 离线兜底全量)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
"""组装插件元数据(manifest 驱动)。
|
||||
|
||||
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
|
||||
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
|
||||
"""
|
||||
manifest = _read_own_manifest(p)
|
||||
name = (manifest or {}).get("name") or p.name
|
||||
description = (manifest or {}).get("description")
|
||||
if description is None:
|
||||
description = p.description
|
||||
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
|
||||
if fields is None:
|
||||
fields = p.fields
|
||||
caps = (manifest or {}).get("capabilities") or p.capabilities
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
def _read_own_manifest(p) -> dict | None:
|
||||
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
|
||||
try:
|
||||
mod = sys.modules.get(type(p).__module__)
|
||||
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
|
||||
if not jar or not jar.is_file():
|
||||
return None
|
||||
return json.loads(jar.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _fields_from_schema(schema: dict) -> list | None:
|
||||
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
|
||||
if not schema or schema.get("type") != "object" or not schema.get("properties"):
|
||||
return None
|
||||
out = []
|
||||
for key, prop in schema["properties"].items():
|
||||
item = {"key": key, "label": prop.get("title", key),
|
||||
"default": prop.get("default", "")}
|
||||
t = prop.get("type", "string")
|
||||
if t == "integer" or t == "number":
|
||||
item["type"] = "int"
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
if d:
|
||||
item["description"] = d
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/platforms/allowed",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _cloud_plugin_ids(account: str) -> set | None:
|
||||
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
|
||||
|
||||
降级策略(三态):
|
||||
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
|
||||
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
|
||||
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
|
||||
"""
|
||||
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
|
||||
if not token or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
|
||||
return None
|
||||
if r.status_code == 401:
|
||||
return set()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return {p["id"] for p in r.json().get("plugins", [])}
|
||||
@@ -1,7 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件执行子进程入口(进程级隔离)。
|
||||
|
||||
由底座 main 以 `python -m webhost.backend.plugin_runner --plugin <id>` 拉起,
|
||||
由底座 main 以 `python -m webhost.backend.core.plugin_runner --plugin <id>` 拉起,
|
||||
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
|
||||
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
|
||||
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
|
||||
@@ -16,7 +16,8 @@ import sys
|
||||
|
||||
def _bootstrap_paths() -> str:
|
||||
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__))))) # core/plugin_runner.py → 项目根
|
||||
if root not in sys.path:
|
||||
sys.path.insert(0, root)
|
||||
return root
|
||||
@@ -46,7 +47,7 @@ def _run() -> int:
|
||||
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 解析参数
|
||||
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
|
||||
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 run 执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||||
|
||||
进程级隔离:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀;
|
||||
由 Windows Job Object 整树托管(含浏览器孙进程)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import scheduler as _scheduler
|
||||
from webhost.backend.core import winjob as _winjob
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import state as _st
|
||||
from webhost.backend.core.hub import HUB
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||||
"""
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[3] # core/runner.py → 项目根
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if _st.ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(_st.ALLOWED))]
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
job.assign(proc)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_st._set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
if t == "log":
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||||
elif t == "progress":
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
def _drain_out():
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev.get("ev") in ("log", "progress"):
|
||||
_publish_event(ev)
|
||||
elif ev.get("ev") == "result":
|
||||
with _rlock:
|
||||
_result.update(ev)
|
||||
|
||||
def _drain_err():
|
||||
for line in proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "ERROR", "msg": line})
|
||||
|
||||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||||
t_out.start(); t_err.start()
|
||||
|
||||
try:
|
||||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||||
proc.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_st._set_run(run_id, status="done" if ok else "error",
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
|
||||
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
def _report_run(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
|
||||
try:
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id) or {}
|
||||
account = run.get("account", "")
|
||||
status = "done" if run.get("status") == "done" else \
|
||||
("running" if run.get("status") == "running" else "error")
|
||||
msg = run.get("error") or ""
|
||||
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
|
||||
licensing.report(account=account, device_id="",
|
||||
plugin_id=plugin_id, version=run.get("version", ""),
|
||||
status=status, msg=msg, duration_sec=duration)
|
||||
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
|
||||
_LOGGER.warning("运行上报失败:%s", _exc)
|
||||
@@ -34,7 +34,7 @@ def init_active() -> None:
|
||||
防止 request_start 的死等条件永远不满足导致所有插件永久排队。"""
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
if not ACTIVE_PATH.is_file():
|
||||
write_active(user="", plugin="", version="", status="idle")
|
||||
write_active(userId="", pluginId="", version="", status="idle")
|
||||
elif read_active().get("status") in ("running", "switching"):
|
||||
_LOGGER.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲")
|
||||
write_active(status="idle", userId="", pluginId="", version="", runId="", startedAt="")
|
||||
@@ -0,0 +1,87 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
|
||||
|
||||
会话状态(token->account 活跃ts)只在此模块定义;admin/dingtalk/meta 等路由经本模块访问。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
|
||||
_SESS_TTL = 7 * 24 * 3600
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
|
||||
_SESS_FILE = Path(__file__).resolve().parents[1] / "_cp_sessions.json"
|
||||
|
||||
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
|
||||
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
|
||||
|
||||
|
||||
def _sess_persist():
|
||||
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
|
||||
try:
|
||||
with _SESS_LOCK:
|
||||
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
|
||||
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("本机会话持久化失败: %s", _exc)
|
||||
|
||||
|
||||
def _sess_load():
|
||||
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
|
||||
if not _SESS_FILE.is_file():
|
||||
return
|
||||
try:
|
||||
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
_now = time.time()
|
||||
with _SESS_LOCK:
|
||||
for _t, _it in (_raw or {}).items():
|
||||
try:
|
||||
_a, _ts = _it[0], float(_it[1])
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
continue
|
||||
if _now - _ts <= _SESS_TTL:
|
||||
_SESS[_t] = (_a, _ts)
|
||||
|
||||
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
account = ""
|
||||
with _SESS_LOCK:
|
||||
item = _SESS.get(token)
|
||||
if item:
|
||||
_account, _ts = item
|
||||
if time.time() - _ts <= _SESS_TTL:
|
||||
_SESS[token] = (_account, time.time()) # 滑动续期
|
||||
account = _account
|
||||
else:
|
||||
_SESS.pop(token, None)
|
||||
if account:
|
||||
_sess_persist() # 滑动续期也落盘,重启后仍有效
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录:请先登录统一账户")
|
||||
return account
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主运行时共享状态:模块级可变全局的唯一真源(单一 owner,禁止他处另建副本)。
|
||||
|
||||
- ALLOWED 在启动(lifespan)时决定且会被整体重新赋值,故一律经 state 模块引用读写
|
||||
(`from webhost.backend import state as st; st.ALLOWED / st.set_allowed(v)`),
|
||||
避免 from-import 复制绑定读不到最新值。
|
||||
- RUNS/RUN_LOCK/_NS_LOCKS/PLATFORMS 均为可变对象,跨模块传的是同一引用。
|
||||
依赖方向:state ← 领域逻辑与路由模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
|
||||
def set_allowed(v: set | None) -> None:
|
||||
global ALLOWED
|
||||
ALLOWED = v
|
||||
|
||||
|
||||
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
|
||||
_NS_LOCKS: dict[str, threading.Lock] = {}
|
||||
_NS_GUARD = threading.Lock()
|
||||
|
||||
|
||||
def _ns_gate(platform: str) -> threading.Lock:
|
||||
key = (platform or "").strip() or "local"
|
||||
with _NS_GUARD:
|
||||
if key not in _NS_LOCKS:
|
||||
_NS_LOCKS[key] = threading.Lock()
|
||||
return _NS_LOCKS[key]
|
||||
|
||||
|
||||
def _set_run(run_id: str, **kw) -> None:
|
||||
"""更新运行记录字段(保留 account 等既有键)。"""
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run.update(kw)
|
||||
+30
-883
@@ -1,273 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主:FastAPI 后端。
|
||||
"""webhost 宿主(组装层):创建 FastAPI app,装配各领域路由,执行重启初始化。
|
||||
|
||||
- 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验)
|
||||
- 场景插件注册表 + 表单 schema
|
||||
- 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成
|
||||
- 挂载前端构建产物(frontend/dist)实现单产物
|
||||
业务逻辑已按领域拆到 sibling 模块:
|
||||
- config.py 环境配置 - state.py 共享可变状态 - session.py 统一账户会话
|
||||
- cpapi.py 中心机代理 - runner.py run 执行 - meta.py 插件元数据/平台权限
|
||||
- apis/ 路由子包(admin / dingtalk / meta / runs)
|
||||
本文件仅承担:lifespan 初始化、创建 app、include_router、静态前端挂载、uvicorn 启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import secrets
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
|
||||
from pydantic import BaseModel
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import winjob as _winjob
|
||||
from webhost.backend.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
|
||||
|
||||
PORT = 8799
|
||||
DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist"
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.cpapi import _resolve_allowed, _sync_licensing
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ==================== 配置固化:加载本模块 env(webhost/.env;免命令行传参;环境变量优先) ====================
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = Path(__file__).resolve().parents[1] / ".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 as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 .env 失败: %s", _exc)
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
|
||||
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
|
||||
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
|
||||
_SESS_TTL = 7 * 24 * 3600
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
|
||||
_SESS_FILE = Path(__file__).resolve().parents[1] / "_cp_sessions.json"
|
||||
|
||||
|
||||
def _sess_persist():
|
||||
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
|
||||
try:
|
||||
with _SESS_LOCK:
|
||||
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
|
||||
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("本机会话持久化失败: %s", _exc)
|
||||
|
||||
|
||||
def _sess_load():
|
||||
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
|
||||
if not _SESS_FILE.is_file():
|
||||
return
|
||||
try:
|
||||
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
_now = time.time()
|
||||
with _SESS_LOCK:
|
||||
for _t, _it in (_raw or {}).items():
|
||||
try:
|
||||
_a, _ts = _it[0], float(_it[1])
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
continue
|
||||
if _now - _ts <= _SESS_TTL:
|
||||
_SESS[_t] = (_a, _ts)
|
||||
|
||||
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
account = ""
|
||||
with _SESS_LOCK:
|
||||
item = _SESS.get(token)
|
||||
if item:
|
||||
_account, _ts = item
|
||||
if time.time() - _ts <= _SESS_TTL:
|
||||
_SESS[token] = (_account, time.time()) # 滑动续期
|
||||
account = _account
|
||||
else:
|
||||
_SESS.pop(token, None)
|
||||
if account:
|
||||
_sess_persist() # 滑动续期也落盘,重启后仍有效
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录:请先登录统一账户")
|
||||
return account
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
|
||||
_NS_LOCKS: dict[str, threading.Lock] = {}
|
||||
_NS_GUARD = threading.Lock()
|
||||
|
||||
|
||||
def _ns_gate(platform: str) -> threading.Lock:
|
||||
key = (platform or "").strip() or "local"
|
||||
with _NS_GUARD:
|
||||
if key not in _NS_LOCKS:
|
||||
_NS_LOCKS[key] = threading.Lock()
|
||||
return _NS_LOCKS[key]
|
||||
|
||||
|
||||
def _set_run(run_id: str, **kw) -> None:
|
||||
"""更新运行记录字段(保留 account 等既有键)。"""
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run.update(kw)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if PLUGIN_SOURCE != "controlplane" or not CONTROLPLANE_URL:
|
||||
return None
|
||||
if not CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 统一后端(数据库 API)代理:底座前端访问统一后端的唯一通道 ====================
|
||||
# 底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
if CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{CONTROLPLANE_URL}{path}", timeout=30, **kw)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
body = {"detail": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
|
||||
return body
|
||||
|
||||
|
||||
# ==================== 产品化:离线授权同步 + 单活调度终止注册表 ====================
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
|
||||
"""
|
||||
if not CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
licensing.flush_offline_reports()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
global ALLOWED
|
||||
ALLOWED = _resolve_allowed()
|
||||
load_plugins(ALLOWED)
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(CONTROLPLANE_URL, threading.Lock())
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if CONTROLPLANE_URL:
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", CONTROLPLANE_ACCOUNT)
|
||||
_sync_licensing(config.CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", config.CONTROLPLANE_ACCOUNT)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
yield
|
||||
@@ -276,646 +55,14 @@ async def lifespan(app: FastAPI):
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
|
||||
@app.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
@app.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(b.account.strip())
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
class _DingTalkIn(BaseModel):
|
||||
account: str # 钉钉工号(作为统一账号)
|
||||
nickname: str = "" # 钉钉姓名
|
||||
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
|
||||
|
||||
|
||||
@app.post("/api/admin/dingtalk/login")
|
||||
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
|
||||
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
|
||||
if not d.account:
|
||||
raise HTTPException(400, "工号不能为空")
|
||||
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
|
||||
|
||||
|
||||
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
|
||||
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
|
||||
|
||||
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
|
||||
"""
|
||||
r = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/auth",
|
||||
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
|
||||
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
|
||||
acct = r.get("account") or account
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (acct, time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
if CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
|
||||
class _InlineIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
|
||||
|
||||
|
||||
@app.post("/api/admin/dingtalk/inline")
|
||||
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
|
||||
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
|
||||
|
||||
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
|
||||
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
info = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/sns",
|
||||
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
|
||||
json={"code": d.code.strip()})
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
|
||||
|
||||
|
||||
@app.get("/api/admin/dingtalk/inline_qr")
|
||||
def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return _cp_call(
|
||||
"GET", "/api/admin/dingtalk/inline_qr",
|
||||
params={"back": back},
|
||||
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}))
|
||||
|
||||
|
||||
# ==================== v3 钉钉直连接登录:/api/auth/dingtalk + /auth/done(§2.1,待 §0 验证后实测) ====================
|
||||
# 浏览器跳转模型:壳生成 state → 打开钉钉授权URL(redirect_uri=http://localhost:8799/auth/done)
|
||||
# → 用户本机浏览器带回 code+state → 壳校验 state → POST 云端 /auth/exchange{code} 换工号+云端token → 建本机会话。
|
||||
# 云端只参与换 token,AppSecret 不出云端;会话存本机、重启不掉(见上方 _SESS 持久化)。
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
|
||||
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
@app.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@app.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
# ==================== 钉钉真实扫码:扫码URL + 静默回调页 ====================
|
||||
# 扫码 URL 指向中心机 /api/admin/dingtalk/scan(back 回跳到本机 /cb);
|
||||
# 扫码成功 → 中心机 /cb 302 回本机 /cb?account=&nickname= → 本页静默调 dingtalk/login 建会话
|
||||
# → 刷新父窗口(登录完成)。身份源为钉钉+中心机(可信),与账号密码登录同会话机制。
|
||||
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
|
||||
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
|
||||
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
|
||||
<script>
|
||||
(async function(){
|
||||
var q = new URLSearchParams(location.search);
|
||||
var account = q.get('account') || '';
|
||||
var nickname = q.get('nickname') || '';
|
||||
if (account) {
|
||||
try {
|
||||
await fetch('/api/admin/dingtalk/login', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ account: account, nickname: nickname })
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
try { window.opener && window.opener.location.reload(); } catch (e) {}
|
||||
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
|
||||
})();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
@app.get("/api/admin/dingtalk/qr")
|
||||
def dingtalk_qr(request: Request) -> dict:
|
||||
"""返回中心机扫码登录 URL。
|
||||
|
||||
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
|
||||
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
|
||||
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
|
||||
"""
|
||||
if not CONTROLPLANE_URL:
|
||||
return {"url": ""}
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return {"url": f"{CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
|
||||
|
||||
|
||||
@app.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb() -> HTMLResponse:
|
||||
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
|
||||
return HTMLResponse(_DINGTALK_CB_HTML)
|
||||
|
||||
|
||||
@app.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@app.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@app.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
"""组装插件元数据(manifest 驱动)。
|
||||
|
||||
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
|
||||
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
|
||||
"""
|
||||
manifest = _read_own_manifest(p)
|
||||
name = (manifest or {}).get("name") or p.name
|
||||
description = (manifest or {}).get("description")
|
||||
if description is None:
|
||||
description = p.description
|
||||
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
|
||||
if fields is None:
|
||||
fields = p.fields
|
||||
caps = (manifest or {}).get("capabilities") or p.capabilities
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
def _read_own_manifest(p) -> dict | None:
|
||||
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
|
||||
try:
|
||||
mod = sys.modules.get(type(p).__module__)
|
||||
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
|
||||
if not jar or not jar.is_file():
|
||||
return None
|
||||
return json.loads(jar.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _fields_from_schema(schema: dict) -> list | None:
|
||||
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
|
||||
if not schema or schema.get("type") != "object" or not schema.get("properties"):
|
||||
return None
|
||||
out = []
|
||||
for key, prop in schema["properties"].items():
|
||||
item = {"key": key, "label": prop.get("title", key),
|
||||
"default": prop.get("default", "")}
|
||||
t = prop.get("type", "string")
|
||||
if t == "integer" or t == "number":
|
||||
item["type"] = "int"
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
if d:
|
||||
item["description"] = d
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/platforms/allowed",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _cloud_plugin_ids(account: str) -> set | None:
|
||||
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
|
||||
|
||||
降级策略(三态):
|
||||
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
|
||||
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
|
||||
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
|
||||
"""
|
||||
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
|
||||
if not token or not CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/plugins",
|
||||
headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
|
||||
return None
|
||||
if r.status_code == 401:
|
||||
return set()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return {p["id"] for p in r.json().get("plugins", [])}
|
||||
|
||||
|
||||
@app.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _cloud_plugin_ids(account)
|
||||
plugins = ([_plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/login")
|
||||
def login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||||
"""
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(ALLOWED))]
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
job.assign(proc)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
if t == "log":
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||||
elif t == "progress":
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
def _drain_out():
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev.get("ev") in ("log", "progress"):
|
||||
_publish_event(ev)
|
||||
elif ev.get("ev") == "result":
|
||||
with _rlock:
|
||||
_result.update(ev)
|
||||
|
||||
def _drain_err():
|
||||
for line in proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "ERROR", "msg": line})
|
||||
|
||||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||||
t_out.start(); t_err.start()
|
||||
|
||||
try:
|
||||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||||
proc.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_set_run(run_id, status="done" if ok else "error",
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
_set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
|
||||
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
def _report_run(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
|
||||
try:
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id) or {}
|
||||
account = run.get("account", "")
|
||||
status = "done" if run.get("status") == "done" else \
|
||||
("running" if run.get("status") == "running" else "error")
|
||||
msg = run.get("error") or ""
|
||||
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
|
||||
licensing.report(account=account, device_id="",
|
||||
plugin_id=plugin_id, version=run.get("version", ""),
|
||||
status=status, msg=msg, duration_sec=duration)
|
||||
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
|
||||
_LOGGER.warning("运行上报失败:%s", _exc)
|
||||
|
||||
|
||||
@app.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
|
||||
online = licensing.is_online()
|
||||
deny = licensing.run_check_allowed(plugin.id, account, online)
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
run_id = uuid.uuid4().hex
|
||||
with RUN_LOCK:
|
||||
if len(RUNS) >= MAX_RUNS:
|
||||
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
|
||||
RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
|
||||
|
||||
if DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
|
||||
if config.DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
def _port_free(port: int) -> bool:
|
||||
@@ -926,5 +73,5 @@ def _port_free(port: int) -> bool:
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
print(f"[webhost] port {PORT} free = {_port_free(PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")
|
||||
print(f"[webhost] port {config.PORT} free = {_port_free(config.PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=config.PORT, log_level="info")
|
||||
Reference in New Issue
Block a user