1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据 2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置 3. 新增敏感凭证RSA加密下发能力与存储结构 4. 新增大文件源管理表与相关API 5. 优化登录流程与会话管理,新增Chrome自动化安装工具链 6. 清理废弃插件与示例代码 7. 更新版本号至1.1.3,完善安装包与.gitignore配置
123 lines
5.2 KiB
Python
123 lines
5.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""webhost 宿主「插件配置 + 插件 UI」路由:带 UI 插件的底座通用约定。
|
||
|
||
两块能力(插件包内 ui/ 目录 + 本地配置存取):
|
||
- GET/POST /api/plugin-config/{pid} per-plugin JSON 配置存取(落执行机本机
|
||
%LOCALAPPDATA%\\37duAutomation\\plugin_configs\\,账号密码等个性化配置改一次永久生效)
|
||
- GET /pui/{pid}[/path] 插件自带前端静态托管(源码态与打包态都从
|
||
plugins/<pid>/ui/ 现读,插件 UI 更新只发插件包、不随壳子发版)
|
||
鉴权与其他 API 一致:统一账户 cookie 会话(壳子内嵌 iframe 同源自动携带)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import logging
|
||
import mimetypes
|
||
|
||
from fastapi import APIRouter, HTTPException, Request
|
||
from fastapi.responses import FileResponse
|
||
|
||
from webhost.backend import config
|
||
from webhost.backend import state as _st
|
||
from webhost.backend.core.session import _require_login
|
||
from webhost.backend.plugins import PLUGINS, _PLUGINS_ROOT # noqa: SLF001 插件根单一真源
|
||
|
||
router = APIRouter()
|
||
_LOGGER = logging.getLogger(__name__)
|
||
|
||
_UI_DIRNAME = "ui" # 插件包内前端目录名(与 plugin.json 的 "ui": true 声明配套)
|
||
_MIME = {".html": "text/html", ".js": "application/javascript",
|
||
".mjs": "application/javascript", ".css": "text/css",
|
||
".json": "application/json", ".map": "application/json",
|
||
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg",
|
||
".gif": "image/gif", ".ico": "image/x-icon", ".woff": "font/woff",
|
||
".woff2": "font/woff2", ".ttf": "font/ttf", ".txt": "text/plain"}
|
||
|
||
|
||
def _check_ui_allowed(plugin_id: str) -> None:
|
||
"""托管/配置读写的前置校验:插件已加载且在账号白名单内,否则 404(不泄露存在性)。"""
|
||
try:
|
||
PLUGINS.find(plugin_id)
|
||
except KeyError:
|
||
raise HTTPException(404, "插件不存在")
|
||
if _st.ALLOWED is not None and plugin_id not in _st.ALLOWED:
|
||
raise HTTPException(404, "插件不存在")
|
||
|
||
|
||
# ==================== per-plugin 本地配置存取 ====================
|
||
def _config_path(plugin_id: str):
|
||
return config.PLUGIN_CONFIG_DIR / f"{plugin_id}.json"
|
||
|
||
|
||
@router.get("/api/plugin-config/{plugin_id}")
|
||
def get_plugin_config(plugin_id: str, request: Request):
|
||
"""读取插件本地配置;从未保存过返回空对象(前端用默认值兜底)。"""
|
||
_require_login(request)
|
||
_check_ui_allowed(plugin_id)
|
||
path = _config_path(plugin_id)
|
||
if not path.is_file():
|
||
return {}
|
||
try:
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
return data if isinstance(data, dict) else {}
|
||
except (OSError, ValueError):
|
||
return {}
|
||
|
||
|
||
@router.post("/api/plugin-config/{plugin_id}")
|
||
async def save_plugin_config(plugin_id: str, request: Request):
|
||
"""整体保存插件配置(前端提交完整表单对象,本地原子落盘)。"""
|
||
_require_login(request)
|
||
_check_ui_allowed(plugin_id)
|
||
try:
|
||
data = await request.json()
|
||
except Exception:
|
||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||
if not isinstance(data, dict):
|
||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||
path = _config_path(plugin_id)
|
||
try:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
tmp = path.with_suffix(".json.tmp")
|
||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
tmp.replace(path) # 原子替换,避免写一半被读到
|
||
except OSError as exc:
|
||
_LOGGER.warning("插件 %s 配置保存失败:%s", plugin_id, exc)
|
||
raise HTTPException(500, "配置保存失败")
|
||
return {"ok": True}
|
||
|
||
|
||
# ==================== 插件 UI 静态托管 ====================
|
||
def _serve_ui(plugin_id: str, rel: str, request: Request) -> FileResponse:
|
||
_require_login(request)
|
||
_check_ui_allowed(plugin_id)
|
||
ui_root = (_PLUGINS_ROOT / plugin_id / _UI_DIRNAME).resolve()
|
||
if not ui_root.is_dir():
|
||
raise HTTPException(404, "该插件未提供前端界面")
|
||
target = (ui_root / rel).resolve() if rel.strip() else ui_root / "index.html"
|
||
if not target.is_relative_to(ui_root): # 防路径穿越(..、绝对路径拼接等)
|
||
raise HTTPException(404, "not found")
|
||
if target.is_dir():
|
||
target = target / "index.html"
|
||
if not target.is_file():
|
||
# SPA 兜底:未知路径回 index.html(history 路由可用)
|
||
target = ui_root / "index.html"
|
||
if not target.is_file():
|
||
raise HTTPException(404, "not found")
|
||
media_type = (_MIME.get(target.suffix.lower())
|
||
or mimetypes.guess_type(str(target))[0] or "application/octet-stream")
|
||
# index.html 不缓存(插件更新后刷新即生效);带 hash 的静态资源可长缓存
|
||
headers = {"Cache-Control": "no-cache" if target.name == "index.html"
|
||
else "public, max-age=86400"}
|
||
return FileResponse(str(target), media_type=media_type, headers=headers)
|
||
|
||
|
||
@router.get("/pui/{plugin_id}")
|
||
def plugin_ui_root(plugin_id: str, request: Request):
|
||
return _serve_ui(plugin_id, "", request)
|
||
|
||
|
||
@router.get("/pui/{plugin_id}/{path:path}")
|
||
def plugin_ui_file(plugin_id: str, path: str, request: Request):
|
||
return _serve_ui(plugin_id, path, request)
|