# -*- coding: utf-8 -*- """中心机插件包工具:ZIP 完整性校验、manifest 解析、版本保留裁剪、版本比较。 纯计算/解析逻辑,不触碰文件系统与 DB(文件落盘/删除由路由层按返回结果执行)。 """ from __future__ import annotations import io import json import re import zipfile from fastapi import HTTPException # 插件包约束:大小上限 / 必含文件 / 保留版本数 / 安全文件名 _PKG_MAX_BYTES = 200 * 1024 * 1024 # webhost 执行端插件为 __init__.py 注册风格,故仅强制 plugin.json(manifest 契约); # main.py 仅作为通用入口可选,不再必含。 _PKG_REQUIRED_FILES = ("plugin.json",) _KEEP_VERSIONS = 3 _SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") def _load_manifest(raw: str) -> dict: """读取存储的插件 manifest(异常安全,回空 dict)。""" if not raw: return {} try: d = json.loads(raw) return d if isinstance(d, dict) else {} except Exception: # noqa: BLE001 return {} def _validate_pkg_zip(content: bytes) -> None: """插件包完整性校验:体积上限 + ZIP 结构 + 必含文件 + plugin.json 可解析。""" if len(content) > _PKG_MAX_BYTES: raise HTTPException(400, f"插件包超过大小上限({_PKG_MAX_BYTES // 1024 // 1024}MB)") try: zf = zipfile.ZipFile(io.BytesIO(content)) except zipfile.BadZipFile: raise HTTPException(400, "上传内容不是有效的 ZIP 包") with zf: if zf.testzip() is not None: raise HTTPException(400, "ZIP 包校验失败(存在损坏条目)") names = set(zf.namelist()) missing = [f for f in _PKG_REQUIRED_FILES if f not in names] if missing: raise HTTPException( 400, f"插件包缺少必需文件:{', '.join(missing)}(包根目录需含 plugin.json / main.py / requirements.txt)") try: json.loads(zf.read("plugin.json").decode("utf-8")) except Exception: raise HTTPException(400, "plugin.json 不是合法 JSON") def _extract_manifest(content: bytes) -> dict | None: """从插件包读取 plugin.json 并解析为 manifest(存在且合法才返回)。 作为插件契约的权威来源:元数据 + JSON-Schema 表单 + capabilities/permissions。 缺文件或解析失败返回 None,交由上层决定是否拒绝。 """ try: zf = zipfile.ZipFile(io.BytesIO(content)) with zf: raw = zf.read("plugin.json").decode("utf-8") data = json.loads(raw) if not isinstance(data, dict): return None return data except Exception: # noqa: BLE001 return None def _prune_versions(conn, plugin_id: str) -> list: """仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。""" rows = conn.execute( "SELECT version, filename FROM plugin_versions WHERE plugin_id = %s", (plugin_id,)).fetchall() stale = sorted(rows, key=lambda r: _version_key(r["version"]), reverse=True)[_KEEP_VERSIONS:] for r in stale: conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s AND version = %s", (plugin_id, r["version"])) return [r["filename"] for r in stale] def _version_key(v: str): """版本比较键:数字段转 (1, int),非数字段转 (0, str),保证段间可比较(1.0.0-beta 不触发 int/str 类型错误)。""" def to_key(s): try: return (1, int(s)) except ValueError: return (0, str(s).lower()) return tuple(to_key(x) for x in str(v).split("."))