From 584c4fff6f38aa2d95803ffb083d1a3457c15cd6 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 27 Nov 2026 06:02:08 +0800 Subject: [PATCH] chore(release): publish v3.2.15 with read-only plugin widget endpoints --- app/api/dependencies/widget.py | 24 ++ app/api/endpoints/plugin.py | 44 +++ app/api/endpoints/widget.py | 73 +++- app/application/widget.py | 414 +++++++++++++++++++- app/runtime/extensions/plugin/manager.py | 18 + app/runtime/extensions/plugin/projection.py | 262 +++++++++++++ app/schemas/plugin.py | 21 + app/schemas/widget.py | 83 +++- app/sdk/plugin/base.py | 23 ++ docs/mcp-api.md | 2 +- docs/widgets.md | 8 + tests/integration/dashboard/test_widget.py | 107 +++++ version.py | 4 +- 13 files changed, 1076 insertions(+), 7 deletions(-) diff --git a/app/api/dependencies/widget.py b/app/api/dependencies/widget.py index 6d73f5fd3..e3814f8f8 100644 --- a/app/api/dependencies/widget.py +++ b/app/api/dependencies/widget.py @@ -13,6 +13,7 @@ from app.api.dependencies.dashboard import sample_downloader, sample_system from app.api.dependencies.history import get_history_query_service from app.application.configuration import ApiRuntimeConfig from app.application.history import HistoryQueryService +from app.application.plugin.runtime import get_existing_plugin_manager from app.application.query import get_configured_data_query_service from app.application.security.widget import WidgetAccessError, WidgetAuthService, WidgetGrant from app.application.widget import WidgetSnapshotService @@ -71,6 +72,27 @@ def get_widget_grant( widget_http_error(error) +def _list_plugin_widgets() -> list[dict[str, object]]: + """ + 从已就绪的插件运行时读取桌面小组件目录;运行时尚未物化时返回空列表。 + """ + manager = get_existing_plugin_manager() + if manager is None: + return [] + return list(manager.get_plugin_widget_meta() or []) + + +def _read_plugin_widget_data(plugin_id: str, widget_key: str) -> dict[str, object] | None: + """ + 从已就绪的插件运行时读取单个桌面小组件快照;运行时尚未物化时返回 None。 + """ + manager = get_existing_plugin_manager() + if manager is None: + return None + raw = manager.get_plugin_widget_data(plugin_id, widget_key) + return dict(raw) if isinstance(raw, dict) else None + + def get_widget_snapshot_service( history: HistoryQueryService = Depends(get_history_query_service), runtime_config: ApiRuntimeConfig = Depends(get_api_runtime_config), @@ -88,4 +110,6 @@ def get_widget_snapshot_service( system=sample_system, downloads=partial(DownloadChain().downloading, require_source=True), downloader=partial(sample_downloader, btrfs_fsid_dedup=runtime_config.btrfs_fsid_dedup, require_source=True), + plugin_widgets=_list_plugin_widgets, + plugin_widget_data=_read_plugin_widget_data, ) diff --git a/app/api/endpoints/plugin.py b/app/api/endpoints/plugin.py index d5d3b5aba..f851d0367 100644 --- a/app/api/endpoints/plugin.py +++ b/app/api/endpoints/plugin.py @@ -68,6 +68,7 @@ from app.schemas.plugin import Plugin as _SchemaPlugin from app.schemas.plugin import PluginAgentPet as _SchemaPluginAgentPet from app.schemas.plugin import PluginDashboard as _SchemaPluginDashboard from app.schemas.plugin import PluginDashboardMetaItem as _SchemaPluginDashboardMetaItem +from app.schemas.plugin import PluginWidgetMetaItem as _SchemaPluginWidgetMetaItem from app.schemas.plugin import PluginDataSummary as _SchemaPluginDataSummary from app.schemas.plugin import PluginDocumentation as _SchemaPluginDocumentation from app.schemas.plugin import PluginInstallOutcome as _SchemaPluginInstallOutcome @@ -771,6 +772,49 @@ def plugin_dashboard( return plugin_dashboard_by_key(plugin_id, "", user_agent) +@router.get( + "/widgets/meta", + summary="获取所有已启用插件的桌面小组件元信息", + response_model=List[_SchemaPluginWidgetMetaItem], +) +def plugin_widgets_meta( + _: ApiPrincipal = Depends(get_current_active_superuser), +) -> List[dict[str, Any]]: + """ + 查询运行中插件声明的移动端桌面小组件目录及仪表板兜底入口。 + + :return: 已启用插件的小组件元信息列表 + """ + return cast(List[dict[str, Any]], get_plugin_manager().get_plugin_widget_meta()) + + +@router.get( + "/widgets/{plugin_id}", + summary="获取单个插件的桌面小组件数据", + response_model=Optional[_SchemaJsonObject], +) +def plugin_widget_data( + plugin_id: str, + key: str = "", + _: ApiPrincipal = Depends(get_current_active_superuser), +) -> Optional[dict[str, Any]]: + """ + 查询指定运行中插件的桌面小组件原始快照(未声明专属方法时自动投影仪表板)。 + + :param plugin_id: 运行态插件标识 + :param key: 插件内小组件键名,缺省为空字符串 + :return: 插件小组件字典;无内容时返回 None + :raises HTTPException: 插件不存在或执行失败 + """ + try: + raw = get_plugin_manager().get_plugin_widget_data(plugin_id, key) + return dict(raw) if isinstance(raw, dict) else None + except PluginNotFoundError as error: + raise HTTPException(status_code=404, detail=str(error)) from error + except PluginDashboardError as error: + raise HTTPException(status_code=500, detail=str(error)) from error + + @router.get("/reset/{plugin_id}", summary="重置插件配置及数据", response_model=_SchemaResponse[None]) def reset_plugin( plugin_id: str, diff --git a/app/api/endpoints/widget.py b/app/api/endpoints/widget.py index 5e3ab1eeb..74a292309 100644 --- a/app/api/endpoints/widget.py +++ b/app/api/endpoints/widget.py @@ -20,7 +20,14 @@ from app.application.security.widget import WidgetAccessError, WidgetAuthService from app.application.widget import WidgetSnapshotService from app.runtime.execution import run_in_threadpool from app.schemas.response import Response as ApiResponse -from app.schemas.widget import WidgetContext, WidgetRegistrationRequest, WidgetRegistrationResponse, WidgetSnapshot +from app.schemas.widget import ( + PluginWidgetCatalog, + PluginWidgetSnapshot, + WidgetContext, + WidgetRegistrationRequest, + WidgetRegistrationResponse, + WidgetSnapshot, +) router = ResponseAPIRouter() @@ -144,3 +151,67 @@ async def widget_snapshot( except ValueError as error: raise HTTPException(503, "小组件快照暂不可用", headers=WIDGET_CACHE_HEADERS) from error return result + + +@router.get( + "/plugins", + summary="读取可绑定的插件桌面小组件目录", + response_model=PluginWidgetCatalog, + response_model_exclude_none=True, + openapi_extra={RAW_RESPONSE_OPENAPI_KEY: True}, +) +async def widget_plugin_catalog( + grant: WidgetGrant = Depends(get_widget_grant), + service: WidgetSnapshotService = Depends(get_widget_snapshot_service), + auth: WidgetAuthService = Depends(get_widget_auth_service), +) -> PluginWidgetCatalog: + """ + 仅向具备超级管理员权限的小组件专用 Bearer 返回已启用插件的桌面小组件清单。 + + :param grant: 当前用户及有限期专用授权 + :param service: 小组件只读投影服务 + :param auth: 返回前复核撤销、到期和最新管理员权限 + :return: 不超过 32 KiB 的插件小组件目录模型 + """ + try: + result = await service.plugin_catalog(grant) + await run_in_threadpool(auth.revalidate, grant) + except WidgetAccessError as error: + widget_http_error(error) + except ValueError as error: + raise HTTPException(503, "插件小组件目录暂不可用", headers=WIDGET_CACHE_HEADERS) from error + return result + + +@router.get( + "/plugins/{plugin_id}", + summary="读取单个插件桌面小组件的只读快照", + response_model=PluginWidgetSnapshot, + response_model_exclude_none=True, + openapi_extra={RAW_RESPONSE_OPENAPI_KEY: True}, +) +async def widget_plugin_snapshot( + plugin_id: str, + key: str = "", + grant: WidgetGrant = Depends(get_widget_grant), + service: WidgetSnapshotService = Depends(get_widget_snapshot_service), + auth: WidgetAuthService = Depends(get_widget_auth_service), +) -> PluginWidgetSnapshot: + """ + 使用专用只读 Bearer 读取单个插件小组件的预设指标、列表或经清洗的声明式自定义布局。 + + :param plugin_id: 运行态插件标识 + :param key: 插件内小组件子键,缺省为空字符串 + :param grant: 当前用户及有限期专用授权 + :param service: 小组件只读投影服务 + :param auth: 返回前复核撤销、到期和最新管理员权限 + :return: 不超过 32 KiB 的单个插件小组件只读快照 + """ + try: + result = await service.plugin_snapshot(grant, plugin_id, key) + await run_in_threadpool(auth.revalidate, grant) + except WidgetAccessError as error: + widget_http_error(error) + except ValueError as error: + raise HTTPException(503, "插件小组件快照暂不可用", headers=WIDGET_CACHE_HEADERS) from error + return result diff --git a/app/application/widget.py b/app/application/widget.py index ad584dcaa..63d0f51cf 100644 --- a/app/application/widget.py +++ b/app/application/widget.py @@ -3,14 +3,21 @@ """ import math +import re import time import unicodedata -from collections.abc import Callable +from collections.abc import Callable, Mapping +from typing import Any, Literal from app.application.history import HistoryQueryService from app.application.query import DataQueryService from app.application.security.user import UserSnapshot -from app.application.security.widget import WidgetGrant, available_widget_contents, widget_subscription_features +from app.application.security.widget import ( + WidgetAccessError, + WidgetGrant, + available_widget_contents, + widget_subscription_features, +) from app.foundation.size import format_size from app.runtime.execution import run_in_threadpool from app.runtime.log import logger @@ -20,6 +27,13 @@ from app.schemas.subscribe import Subscribe from app.schemas.transfer import DownloaderTorrent from app.schemas.types import MediaType from app.schemas.widget import ( + PluginWidgetCatalog, + PluginWidgetDescriptor, + PluginWidgetKind, + PluginWidgetListItem, + PluginWidgetMetricItem, + PluginWidgetSnapshot, + PluginWidgetTone, WidgetContent, WidgetIcon, WidgetItem, @@ -31,6 +45,19 @@ from app.schemas.widget import ( # 与 Swift 共享协议一致,单次最多六条,不随业务总数增加传输体积。 WIDGET_ITEM_LIMIT = 6 WIDGET_SNAPSHOT_MAX_BYTES = 32 * 1024 +# 插件声明式自定义布局节点树的最大递归深度与单卡片最大节点总数。 +PLUGIN_WIDGET_MAX_DEPTH = 5 +PLUGIN_WIDGET_MAX_NODES = 40 +_PLUGIN_ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,127}\Z") +_WIDGET_KEY_RE = re.compile(r"^[A-Za-z0-9_-]{0,64}\Z") +_HEX_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}\Z") +_ALLOWED_KINDS: frozenset[str] = frozenset({"metrics", "list", "poster", "nowPlaying", "custom"}) +_ALLOWED_TONES: frozenset[str] = frozenset( + {"default", "primary", "secondary", "muted", "accent", "success", "warning", "danger"} +) +_ALLOWED_NODE_TYPES: frozenset[str] = frozenset( + {"column", "row", "stack", "box", "text", "icon", "image", "progress", "badge", "button", "spacer", "divider"} +) _TITLES: dict[WidgetContent, str] = { "overview": "实例概览", "downloads": "下载状态", @@ -89,6 +116,8 @@ class WidgetSnapshotService: system: Callable[[], tuple[float, DashboardMemoryInfo, list[int]]], downloads: Callable[[], list[DownloaderTorrent] | None], downloader: Callable[[], DownloaderInfo], + plugin_widgets: Callable[[], list[dict[str, Any]]] | None = None, + plugin_widget_data: Callable[[str, str], dict[str, Any] | None] | None = None, clock: Callable[[], float] = time.time, ) -> None: """ @@ -99,6 +128,8 @@ class WidgetSnapshotService: :param system: 既有管理员 CPU、内存和网络系统采样回调 :param downloads: 原有下载链的采样回调,仅在工作线程内执行 :param downloader: 共用下载器字节统计;只由管理员在工作线程内读取 + :param plugin_widgets: 可选的运行态插件小组件元信息回调,仅超级管理员可调用 + :param plugin_widget_data: 可选的运行态插件单卡片数据回调,仅超级管理员在工作线程内读取 :param clock: 可信 UTC Unix 秒来源 """ self._data = data @@ -106,6 +137,8 @@ class WidgetSnapshotService: self._system = system self._downloads = downloads self._downloader = downloader + self._plugin_widgets = plugin_widgets + self._plugin_widget_data = plugin_widget_data self._clock = clock async def snapshot(self, grant: WidgetGrant) -> WidgetSnapshot: @@ -348,3 +381,380 @@ class WidgetSnapshotService: _metric("memoryTotal", "总内存", format_size(memory.total), "memory"), ], ) + + async def plugin_catalog(self, grant: WidgetGrant) -> PluginWidgetCatalog: + """ + 向拥有超级管理员权限的小组件授权返回可绑定的已启用插件小组件目录。 + + :param grant: 已核验有效的专用只读授权 + :return: 不超过 32 KiB 的插件小组件目录模型 + :raises WidgetAccessError: 当前账号不具备管理员插件查看权限 + :raises ValueError: 凭据已到期或响应超出协议体积上限 + """ + if not grant.user.is_superuser: + raise WidgetAccessError(403, "当前账号无权读取插件小组件") + raw_items = ( + await run_in_threadpool(self._plugin_widgets) + if self._plugin_widgets is not None + else [] + ) + descriptors: list[PluginWidgetDescriptor] = [] + for raw in (raw_items or [])[:64]: + if not isinstance(raw, Mapping): + continue + pid = str(raw.get("plugin_id") or "").strip() + key = str(raw.get("key") or "").strip() + if not _PLUGIN_ID_RE.fullmatch(pid) or not _WIDGET_KEY_RE.fullmatch(key): + continue + pname = _text(str(raw.get("plugin_name") or pid), 120, pid) + wname = _text(str(raw.get("name") or pname), 120, pname) + raw_desc = raw.get("description") + desc = _text(str(raw_desc), 240) if isinstance(raw_desc, str) and raw_desc.strip() else None + raw_kind = str(raw.get("kind") or "metrics").strip() + kind: PluginWidgetKind = raw_kind if raw_kind in _ALLOWED_KINDS else "metrics" # type: ignore[assignment] + source: Literal["widget", "dashboard"] = "dashboard" if raw.get("source") == "dashboard" else "widget" + descriptors.append( + PluginWidgetDescriptor( + pluginId=pid, + pluginName=pname, + widgetKey=key, + name=wname, + description=desc, + kind=kind, + source=source, + hasPage=bool(raw.get("has_page")), + ) + ) + generated_at = self._clock() + expires_at = min(generated_at + 86400, grant.registration.expires_at) + if expires_at <= generated_at: + raise ValueError("小组件凭据已到期") + catalog = PluginWidgetCatalog( + owner=grant.registration.owner, + generatedAt=generated_at, + expiresAt=expires_at, + widgets=descriptors, + ) + if len(catalog.model_dump_json(exclude_none=True).encode("utf-8")) > WIDGET_SNAPSHOT_MAX_BYTES: + raise ValueError("插件小组件目录超过协议体积") + return catalog + + async def plugin_snapshot( + self, + grant: WidgetGrant, + plugin_id: str, + widget_key: str = "", + ) -> PluginWidgetSnapshot: + """ + 读取单个插件小组件的有界只读快照,对预设字段和声明式自定义布局执行严格清洗。 + + :param grant: 已核验有效的专用只读授权 + :param plugin_id: 目标运行态插件标识 + :param widget_key: 插件内小组件标识,缺省为空字符串 + :return: 不超过 32 KiB 的单卡片只读快照 + :raises WidgetAccessError: 权限不足或插件标识格式非法 + :raises ValueError: 凭据已到期或清洗后快照仍超出协议体积上限 + """ + if not grant.user.is_superuser: + raise WidgetAccessError(403, "当前账号无权读取插件小组件") + clean_pid = plugin_id.strip() + clean_key = widget_key.strip() + if not _PLUGIN_ID_RE.fullmatch(clean_pid) or not _WIDGET_KEY_RE.fullmatch(clean_key): + raise WidgetAccessError(404, "目标插件小组件不存在") + generated_at = self._clock() + expires_at = min(generated_at + 86400, grant.registration.expires_at) + if expires_at <= generated_at: + raise ValueError("小组件凭据已到期") + if self._plugin_widget_data is None: + return self._unavailable_plugin_snapshot(grant, clean_pid, clean_key, generated_at, expires_at) + try: + raw = await run_in_threadpool(self._plugin_widget_data, clean_pid, clean_key) + except Exception as error: + logger.warning(f"插件小组件 {clean_pid}/{clean_key} 读取失败({type(error).__name__})") + return self._unavailable_plugin_snapshot(grant, clean_pid, clean_key, generated_at, expires_at) + if raw is None or not isinstance(raw, Mapping): + return PluginWidgetSnapshot( + owner=grant.registration.owner, + generatedAt=generated_at, + expiresAt=expires_at, + pluginId=clean_pid, + pluginName=clean_pid, + widgetKey=clean_key, + state="empty", + updatedAt=generated_at, + kind="metrics", + title=clean_pid, + message="当前暂无可展示的小组件数据", + ) + return self._project_plugin_snapshot(grant, clean_pid, clean_key, raw, generated_at, expires_at) + + @staticmethod + def _unavailable_plugin_snapshot( + grant: WidgetGrant, + plugin_id: str, + widget_key: str, + generated_at: float, + expires_at: float, + ) -> PluginWidgetSnapshot: + """ + 构造不包含内部异常细节或虚假采样时间的不可用插件小组件快照。 + """ + return PluginWidgetSnapshot( + owner=grant.registration.owner, + generatedAt=generated_at, + expiresAt=expires_at, + pluginId=plugin_id, + pluginName=plugin_id, + widgetKey=widget_key, + state="unavailable", + kind="metrics", + title=plugin_id, + message="暂时无法读取插件小组件,请稍后刷新", + ) + + def _project_plugin_snapshot( + self, + grant: WidgetGrant, + plugin_id: str, + widget_key: str, + raw: Mapping[str, Any], + generated_at: float, + expires_at: float, + ) -> PluginWidgetSnapshot: + """ + 将插件返回的原始映射规范化为受体积和层级约束的只读快照。 + """ + pname = _text(str(raw.get("plugin_name") or plugin_id), 120, plugin_id) + title = _text(str(raw.get("title") or pname), 240, pname) + raw_sub = raw.get("subtitle") + subtitle = _text(str(raw_sub), 240) if isinstance(raw_sub, str) and raw_sub.strip() else None + raw_kind = str(raw.get("kind") or "metrics").strip() + kind: PluginWidgetKind = raw_kind if raw_kind in _ALLOWED_KINDS else "metrics" # type: ignore[assignment] + + metrics = self._sanitize_plugin_metrics(raw.get("metrics")) + items = self._sanitize_plugin_items(raw.get("items")) + layout = self._sanitize_layout_root(raw.get("layout")) + layouts_raw = raw.get("layouts") + layouts: dict[str, dict[str, Any]] | None = None + if isinstance(layouts_raw, Mapping): + cleaned_layouts: dict[str, dict[str, Any]] = {} + for size_key in ("small", "medium", "large"): + sanitized_tree = self._sanitize_layout_root(layouts_raw.get(size_key)) + if sanitized_tree is not None: + cleaned_layouts[size_key] = sanitized_tree + if cleaned_layouts: + layouts = cleaned_layouts + + has_content = bool(metrics or items or layout or layouts or kind in {"poster", "nowPlaying"}) + snapshot = PluginWidgetSnapshot( + owner=grant.registration.owner, + generatedAt=generated_at, + expiresAt=expires_at, + pluginId=plugin_id, + pluginName=pname, + widgetKey=widget_key, + state="ready" if has_content else "empty", + updatedAt=generated_at, + kind=kind, + title=title, + subtitle=subtitle, + metrics=metrics, + items=items, + layout=layout, + layouts=layouts, + ) + if len(snapshot.model_dump_json(exclude_none=True).encode("utf-8")) > WIDGET_SNAPSHOT_MAX_BYTES: + raise ValueError("插件小组件快照超过协议体积") + return snapshot + + @staticmethod + def _sanitize_plugin_metrics(raw_metrics: Any) -> list[PluginWidgetMetricItem]: + """ + 清洗预设指标数组,限制最多八项并剔除未知色调与控制字符。 + """ + if not isinstance(raw_metrics, list): + return [] + out: list[PluginWidgetMetricItem] = [] + seen_ids: set[str] = set() + for idx, entry in enumerate(raw_metrics[:8]): + if not isinstance(entry, Mapping): + continue + mid = _text(str(entry.get("id") or f"m-{idx}"), 64, f"m-{idx}") + if mid in seen_ids: + mid = f"{mid}-{idx}" + seen_ids.add(mid) + label = _text(str(entry.get("label") or entry.get("title") or "指标"), 120, "指标") + val = _text(str(entry.get("value") or "—"), 96, "—") + raw_sub = entry.get("subValue") + sub_val = _text(str(raw_sub), 120) if isinstance(raw_sub, str) and raw_sub.strip() else None + raw_icon = entry.get("icon") + icon = _text(str(raw_icon), 48) if isinstance(raw_icon, str) and raw_icon.strip() else None + raw_tone = str(entry.get("tone") or "").strip() + tone: PluginWidgetTone | None = raw_tone if raw_tone in _ALLOWED_TONES else None # type: ignore[assignment] + out.append( + PluginWidgetMetricItem( + id=mid, + label=label, + value=val, + subValue=sub_val, + icon=icon, + tone=tone, + ) + ) + return out + + @staticmethod + def _sanitize_plugin_items(raw_items: Any) -> list[PluginWidgetListItem]: + """ + 清洗预设列表条目,限制最多六项并校验进度处于自然百分比区间。 + """ + if not isinstance(raw_items, list): + return [] + out: list[PluginWidgetListItem] = [] + seen_ids: set[str] = set() + for idx, entry in enumerate(raw_items[:WIDGET_ITEM_LIMIT]): + if not isinstance(entry, Mapping): + continue + iid = _text(str(entry.get("id") or f"i-{idx}"), 64, f"i-{idx}") + if iid in seen_ids: + iid = f"{iid}-{idx}" + seen_ids.add(iid) + title = _text(str(entry.get("title") or "未命名条目"), 240, "未命名条目") + raw_sub = entry.get("subtitle") + subtitle = _text(str(raw_sub), 320) if isinstance(raw_sub, str) and raw_sub.strip() else None + raw_trailing = entry.get("trailing") + trailing = _text(str(raw_trailing), 64) if isinstance(raw_trailing, str) and raw_trailing.strip() else None + raw_prog = entry.get("progress") + progress: float | None = None + if isinstance(raw_prog, (int, float)) and not isinstance(raw_prog, bool): + prog_val = float(raw_prog) + if math.isfinite(prog_val) and 0.0 <= prog_val <= 1.0: + progress = prog_val + out.append( + PluginWidgetListItem( + id=iid, + title=title, + subtitle=subtitle, + trailing=trailing, + progress=progress, + ) + ) + return out + + @classmethod + def _sanitize_layout_root(cls, raw_node: Any) -> dict[str, Any] | None: + """ + 对声明式自定义小组件节点树执行深度不超过五层、总节点不超过四十个的白名单清洗。 + """ + budget = [PLUGIN_WIDGET_MAX_NODES] + return cls._sanitize_layout_node(raw_node, depth=0, budget=budget) + + @classmethod + def _sanitize_layout_node( + cls, + raw_node: Any, + *, + depth: int, + budget: list[int], + ) -> dict[str, Any] | None: + """ + 递归校验单个声明式布局节点,剔除未知属性、外部任意地址与越界数值。 + """ + if depth > PLUGIN_WIDGET_MAX_DEPTH or budget[0] <= 0 or not isinstance(raw_node, Mapping): + return None + node_type = str(raw_node.get("type") or "").strip() + if node_type not in _ALLOWED_NODE_TYPES: + return None + budget[0] -= 1 + out: dict[str, Any] = {"type": node_type} + + for str_key, max_bytes in ( + ("text", 240), + ("label", 120), + ("name", 64), + ("size", 16), + ("weight", 16), + ("align", 16), + ("justify", 24), + ("style", 16), + ): + val = raw_node.get(str_key) + if isinstance(val, str) and val.strip(): + out[str_key] = _text(val, max_bytes) + + raw_tone = raw_node.get("tone") + if isinstance(raw_tone, str): + clean_tone = raw_tone.strip() + if clean_tone in _ALLOWED_TONES or _HEX_COLOR_RE.fullmatch(clean_tone): + out["tone"] = clean_tone + + for num_key, low, high in ( + ("gap", 0.0, 32.0), + ("padding", 0.0, 32.0), + ("radius", 0.0, 32.0), + ("width", 8.0, 360.0), + ("height", 8.0, 360.0), + ("flex", 0.0, 10.0), + ("maxLines", 1.0, 6.0), + ("value", 0.0, 1.0), + ("minLength", 0.0, 64.0), + ): + num_val = raw_node.get(num_key) + if isinstance(num_val, (int, float)) and not isinstance(num_val, bool) and math.isfinite(float(num_val)): + clamped = min(max(float(num_val), low), high) + out[num_key] = int(clamped) if num_key == "maxLines" else clamped + + if isinstance(raw_node.get("tabularNums"), bool): + out["tabularNums"] = raw_node["tabularNums"] + if isinstance(raw_node.get("scrim"), bool): + out["scrim"] = raw_node["scrim"] + + for url_key in ("url", "backgroundUrl"): + raw_url = raw_node.get(url_key) + safe_url = cls._sanitize_plugin_asset_path(raw_url) + if safe_url: + out[url_key] = safe_url + + raw_action = raw_node.get("action") + if isinstance(raw_action, Mapping): + action_kind = str(raw_action.get("type") or "openPlugin").strip() + if action_kind in {"openPlugin", "pluginAction"}: + act_obj: dict[str, str] = {"type": action_kind} + surface = str(raw_action.get("surface") or "data").strip() + if surface in {"data", "config"}: + act_obj["surface"] = surface + act_id = raw_action.get("actionId") + if isinstance(act_id, str) and _WIDGET_KEY_RE.fullmatch(act_id.strip()): + act_obj["actionId"] = act_id.strip() + out["action"] = act_obj + + if node_type in {"column", "row", "stack", "box"} and depth < PLUGIN_WIDGET_MAX_DEPTH: + raw_children = raw_node.get("children") + if isinstance(raw_children, list): + children: list[dict[str, Any]] = [] + for child in raw_children[:16]: + if budget[0] <= 0: + break + clean_child = cls._sanitize_layout_node(child, depth=depth + 1, budget=budget) + if clean_child is not None: + children.append(clean_child) + out["children"] = children + return out + + @staticmethod + def _sanitize_plugin_asset_path(raw_url: Any) -> str | None: + """ + 仅放行同源插件静态资源路径 `/api/v1/plugin/file/...`,拒绝外部任意地址或路径穿越。 + """ + if not isinstance(raw_url, str): + return None + candidate = raw_url.strip() + if ( + not candidate.startswith("/api/v1/plugin/file/") + or ".." in candidate + or "\\" in candidate + or any(ch in candidate for ch in ("\r", "\n", "\x00", " ")) + or len(candidate.encode("utf-8")) > 512 + ): + return None + return candidate diff --git a/app/runtime/extensions/plugin/manager.py b/app/runtime/extensions/plugin/manager.py index 5e3f9c3b3..aaca466d2 100644 --- a/app/runtime/extensions/plugin/manager.py +++ b/app/runtime/extensions/plugin/manager.py @@ -1248,6 +1248,24 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton): """ return self._plugin_projection().dashboard(pid, key, user_agent) + def get_plugin_widget_meta(self) -> List[Dict[str, Any]]: + """ + 获取所有已启用插件的桌面小组件元信息。 + + :return: 插件桌面小组件声明与仪表板兜底目录 + """ + return self._plugin_projection().widget_metadata() + + def get_plugin_widget_data(self, pid: str, key: str = "") -> Optional[Dict[str, Any]]: + """ + 获取指定插件桌面小组件的数据快照。 + + :param pid: 运行态插件标识 + :param key: 插件内小组件或仪表板键名 + :return: 小组件原始数据字典;无内容时返回 None + """ + return self._plugin_projection().widget_data(pid, key) + def get_plugin_attr(self, pid: str, attr: str) -> Any: """ 获取插件属性。 diff --git a/app/runtime/extensions/plugin/projection.py b/app/runtime/extensions/plugin/projection.py index d0288323b..70c83fe0b 100644 --- a/app/runtime/extensions/plugin/projection.py +++ b/app/runtime/extensions/plugin/projection.py @@ -25,6 +25,9 @@ _AGENT_PET_MODES = frozenset({"stage", "renderer"}) _AGENT_PET_BUBBLES = frozenset({"host", "self"}) # 预览图与头像允许原样透传的绝对地址前缀,其余一律视为相对联邦产物目录的路径 _AGENT_PET_ABSOLUTE_PREVIEW_PREFIXES = ("http://", "https://", "data:") +# 桌面小组件标识与形态枚举白名单 +_WIDGET_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +_WIDGET_KINDS = frozenset({"metrics", "list", "poster", "nowPlaying", "custom"}) class _InvalidAgentPet(ValueError): @@ -651,3 +654,262 @@ class PluginProjection: "virtual" if getattr(plugin, "plugin_source_id", None) else None ), ) + + def widget_metadata(self) -> List[Dict[str, Any]]: + """ + 投影启用插件声明的桌面小组件目录,并为仅实现仪表板的插件提供自动降级入口。 + + :return: 已启用插件的小组件元信息列表 + """ + items: list[dict[str, Any]] = [] + declared_pairs: set[tuple[str, str]] = set() + for plugin_id, plugin in sorted(self._items(None), key=lambda pair: pair[0]): + if not plugin.get_state(): + continue + has_page = bool(supports_plugin_hook(plugin, "get_page")) + plugin_name = getattr(plugin, "plugin_name", None) or plugin_id + if supports_plugin_hook(plugin, "get_widgets"): + try: + raw_list = plugin.get_widgets() or [] + except Exception as error: + self._logger.error(f"获取插件[{plugin_id}]桌面小组件元信息出错:{error}") + raw_list = [] + if isinstance(raw_list, list): + for raw in raw_list: + if not isinstance(raw, Mapping): + continue + raw_key = str(raw.get("key") or "").strip() + if not _WIDGET_KEY_PATTERN.match(raw_key): + self._logger.warning( + f"插件[{plugin_id}]桌面小组件 key 无效,已跳过:{raw_key!r}" + ) + continue + if (plugin_id, raw_key) in declared_pairs: + continue + name = str(raw.get("name") or "").strip() or plugin_name + kind = str(raw.get("kind") or "metrics").strip() + if kind not in _WIDGET_KINDS: + kind = "metrics" + description = raw.get("description") + desc_str = description.strip() if isinstance(description, str) and description.strip() else None + declared_pairs.add((plugin_id, raw_key)) + items.append({ + "plugin_id": plugin_id, + "plugin_name": plugin_name, + "key": raw_key, + "name": name, + "description": desc_str, + "kind": kind, + "source": "widget", + "has_page": has_page, + }) + if supports_plugin_hook(plugin, "get_dashboard"): + try: + dash_metas = ( + plugin.get_dashboard_meta() + if supports_plugin_hook(plugin, "get_dashboard_meta") + else None + ) + except Exception as error: + self._logger.error(f"获取插件[{plugin_id}]仪表盘兜底小组件元信息出错:{error}") + continue + entries = dash_metas if dash_metas else [{"key": "", "name": plugin_name}] + for entry in entries: + if not isinstance(entry, Mapping): + continue + dash_key = str(entry.get("key") or "").strip() + if dash_key and not _WIDGET_KEY_PATTERN.match(dash_key): + continue + if (plugin_id, dash_key) in declared_pairs: + continue + declared_pairs.add((plugin_id, dash_key)) + items.append({ + "plugin_id": plugin_id, + "plugin_name": plugin_name, + "key": dash_key, + "name": str(entry.get("name") or "").strip() or plugin_name, + "description": None, + "kind": "metrics", + "source": "dashboard", + "has_page": has_page, + }) + return items + + def widget_data(self, plugin_id: str, key: str = "") -> Optional[Dict[str, Any]]: + """ + 读取插件专属桌面小组件快照;未实现专属方法时自动投影该插件的仪表板结构。 + + :param plugin_id: 运行态插件标识 + :param key: 小组件或仪表板子键 + :return: 原始小组件字典;插件当前无小组件内容时返回 None + :raises PluginNotFoundError: 插件未加载或未启用 + :raises PluginDashboardError: 插件方法执行失败或返回非法结构 + """ + plugin = self._running_plugins.get(plugin_id) + if not plugin or not plugin.get_state(): + raise PluginNotFoundError(f"插件 {plugin_id} 不存在或未启用") + plugin_name = getattr(plugin, "plugin_name", None) or plugin_id + if supports_plugin_hook(plugin, "get_widget_data"): + try: + method = plugin.get_widget_data + param_count = len(inspect.signature(method).parameters) + raw = method(key) if param_count > 0 else method() + except Exception as error: # noqa: BLE001 + self._logger.error(f"插件 {plugin_id} 调用方法 get_widget_data 出错: {error}") + raise PluginDashboardError( + f"插件 {plugin_id} 调用方法 get_widget_data 出错" + ) from error + if raw is None: + return None + if not isinstance(raw, Mapping): + raise PluginDashboardError(f"插件 {plugin_id} 返回的小组件数据格式错误") + payload = dict(raw) + payload.setdefault("plugin_id", plugin_id) + payload.setdefault("plugin_name", plugin_name) + payload.setdefault("widget_key", key) + payload.setdefault("title", plugin_name) + return payload + if supports_plugin_hook(plugin, "get_dashboard"): + dash = self.dashboard(plugin_id, key) + if dash is None: + return None + return self._dashboard_to_widget_payload(plugin_id, plugin_name, key, dash) + return None + + @classmethod + def _dashboard_to_widget_payload( + cls, + plugin_id: str, + plugin_name: str, + key: str, + dash: PluginDashboard, + ) -> Dict[str, Any]: + """ + 把存量插件的 Vuetify 仪表板元素树提取为桌面小组件可消费的指标与摘要列表。 + """ + attrs = dash.attrs if isinstance(dash.attrs, Mapping) else {} + title = str(attrs.get("title") or dash.name or plugin_name).strip() or plugin_name + subtitle = str(attrs.get("subtitle") or "").strip() or None + if dash.render_mode == "vue": + return { + "plugin_id": plugin_id, + "plugin_name": plugin_name, + "widget_key": key, + "kind": "poster", + "title": title, + "subtitle": subtitle or "交互式联邦仪表盘 · 点击在 App 中打开", + "metrics": [], + "items": [], + } + metrics: list[dict[str, Any]] = [] + lines: list[str] = [] + cls._extract_vuetify_snippets(dash.elements, metrics, lines, depth=0) + dedup_lines = list(dict.fromkeys(line for line in lines if line))[:6] + if metrics: + return { + "plugin_id": plugin_id, + "plugin_name": plugin_name, + "widget_key": key, + "kind": "metrics", + "title": title, + "subtitle": subtitle, + "metrics": metrics[:8], + "items": [ + {"id": f"item-{idx}", "title": text} + for idx, text in enumerate(dedup_lines[:4]) + ], + } + return { + "plugin_id": plugin_id, + "plugin_name": plugin_name, + "widget_key": key, + "kind": "list", + "title": title, + "subtitle": subtitle, + "metrics": [], + "items": [ + {"id": f"item-{idx}", "title": text} + for idx, text in enumerate(dedup_lines[:6]) + ], + } + + @classmethod + def _extract_vuetify_snippets( + cls, + node: Any, + metrics: list[dict[str, Any]], + lines: list[str], + depth: int, + ) -> None: + """ + 有界递归扫描仪表板 Vuetify JSON 树,识别成对的「指标名/数值」与可读文本行。 + """ + if depth > 14 or (len(metrics) >= 8 and len(lines) >= 12): + return + if isinstance(node, str): + cleaned = " ".join(node.split()).strip() + if ( + cleaned + and cleaned != "null" + and not cleaned.startswith(("mdi-", "ri-", "#", "{", ".")) + and len(cleaned) <= 80 + ): + lines.append(cleaned) + return + if isinstance(node, list): + for child in node: + cls._extract_vuetify_snippets(child, metrics, lines, depth + 1) + return + if not isinstance(node, Mapping): + return + comp = str(node.get("component") or "") + if comp.lower() in {"style", "script", "vicon"}: + return + props = node.get("props") + if isinstance(props, Mapping): + prop_title = str(props.get("title") or props.get("label") or "").strip() + prop_value = str(props.get("value") or props.get("subtitle") or "").strip() + if ( + prop_title + and prop_value + and len(prop_title) <= 24 + and len(prop_value) <= 32 + and not prop_title.startswith("mdi-") + and not prop_value.startswith("mdi-") + and len(metrics) < 8 + ): + metrics.append({ + "id": f"m-{len(metrics)}", + "label": prop_title, + "value": prop_value, + }) + else: + for field in ("title", "subtitle", "label", "text", "value"): + val = props.get(field) + if isinstance(val, str): + cls._extract_vuetify_snippets(val, metrics, lines, depth + 1) + direct_text = node.get("text") + if isinstance(direct_text, str): + cls._extract_vuetify_snippets(direct_text, metrics, lines, depth + 1) + content = node.get("content") + if isinstance(content, list): + local_lines: list[str] = [] + local_metrics: list[dict[str, Any]] = [] + for child in content: + cls._extract_vuetify_snippets(child, local_metrics, local_lines, depth + 1) + for item in local_metrics: + if len(metrics) < 8: + metrics.append(item) + if ( + len(local_lines) == 2 + and len(local_lines[0]) <= 20 + and len(local_lines[1]) <= 28 + and len(metrics) < 8 + ): + metrics.append({ + "id": f"m-{len(metrics)}", + "label": local_lines[0], + "value": local_lines[1], + }) + else: + lines.extend(local_lines) diff --git a/app/schemas/plugin.py b/app/schemas/plugin.py index 9c6ef24b8..f355c9c12 100644 --- a/app/schemas/plugin.py +++ b/app/schemas/plugin.py @@ -845,3 +845,24 @@ class PluginDashboardMetaItem(BaseModel): id: str = Field(description="记录标识") name: Optional[str] = Field(default=None, description="显示名称") key: Optional[str] = Field(default=None, description="缓存条目的键") + + +class PluginWidgetMetaItem(BaseModel): + """ + 插件移动端桌面小组件入口摘要。 + """ + + plugin_id: str = Field(description="运行态插件标识") + plugin_name: str = Field(description="插件显示名称") + key: str = Field(default="", description="插件内唯一的小组件键名,默认单卡片为空字符串") + name: str = Field(description="小组件展示标题") + description: Optional[str] = Field(default=None, description="小组件用途简述") + kind: Literal["metrics", "list", "poster", "nowPlaying", "custom"] = Field( + default="metrics", + description="小组件形态类别,支持预设指标、列表、海报、正在播放与声明式自定义树", + ) + source: Literal["widget", "dashboard"] = Field( + default="widget", + description="数据来源类型,widget 表示插件专属声明,dashboard 表示从存量仪表板自动投影", + ) + has_page: bool = Field(default=False, description="插件是否提供可跳转的数据详情页") diff --git a/app/schemas/widget.py b/app/schemas/widget.py index 679976810..9a1e8e336 100644 --- a/app/schemas/widget.py +++ b/app/schemas/widget.py @@ -2,7 +2,7 @@ 小组件专用登记与有界只读快照协议;不包含业务命令或主登录凭据。 """ -from typing import Literal +from typing import Any, Literal from uuid import UUID from pydantic import BaseModel, ConfigDict, Field @@ -13,6 +13,8 @@ WidgetContent = Literal[ WidgetIcon = Literal[ "movie", "television", "episodes", "music", "download", "upload", "storage", "items", "clock", "cpu", "memory" ] +PluginWidgetKind = Literal["metrics", "list", "poster", "nowPlaying", "custom"] +PluginWidgetTone = Literal["default", "primary", "secondary", "muted", "accent", "success", "warning", "danger"] class WidgetContext(BaseModel): @@ -105,3 +107,82 @@ class WidgetSnapshot(BaseModel): ) availableContents: list[WidgetContent] = Field(max_length=6, description="最新授权的内容集合,与 sections 一一对应") sections: list[WidgetSection] = Field(max_length=6, description="独立来源结果,权限不足的内容不在此出现") + + +class PluginWidgetDescriptor(BaseModel): + """ + 已启用插件可供系统桌面绑定的单个小组件描述。 + """ + + pluginId: str = Field(min_length=1, max_length=128, description="运行态插件标识") + pluginName: str = Field(min_length=1, max_length=120, description="插件展示名称") + widgetKey: str = Field(default="", max_length=64, description="插件内唯一的小组件键名") + name: str = Field(min_length=1, max_length=120, description="小组件卡片名称") + description: str | None = Field(default=None, max_length=240, description="小组件可选说明文字") + kind: PluginWidgetKind = Field(default="metrics", description="小组件渲染形态") + source: Literal["widget", "dashboard"] = Field(default="widget", description="声明来源,支持专属协议或仪表板兜底") + hasPage: bool = Field(default=False, description="插件是否具备数据详情页面") + + +class PluginWidgetCatalog(BaseModel): + """ + 小组件专用凭据可读的已启用插件小组件目录。 + """ + + version: Literal[1] = Field(default=1, description="插件小组件目录协议版本") + owner: str = Field(pattern=r"^[0-9a-f]{32}$", description="不可变管理员身份标识") + generatedAt: float = Field(gt=0, allow_inf_nan=False, description="目录生成的 UTC Unix 秒") + expiresAt: float = Field(gt=0, allow_inf_nan=False, description="目录有效期的 UTC Unix 秒") + widgets: list[PluginWidgetDescriptor] = Field(default_factory=list, max_length=64, description="可绑定的插件小组件清单") + + +class PluginWidgetMetricItem(BaseModel): + """ + 插件小组件预设模板中的单项统计指标。 + """ + + id: str = Field(min_length=1, max_length=64, description="卡片内唯一的指标标识") + label: str = Field(min_length=1, max_length=120, description="指标标题") + value: str = Field(min_length=1, max_length=96, description="已格式化的指标数值") + subValue: str | None = Field(default=None, max_length=120, description="可选趋势或辅助值") + icon: str | None = Field(default=None, max_length=48, description="可选语义图标名称") + tone: PluginWidgetTone | None = Field(default=None, description="可选语义着色角色") + + +class PluginWidgetListItem(BaseModel): + """ + 插件小组件预设列表模板中的单行条目。 + """ + + id: str = Field(min_length=1, max_length=64, description="卡片内唯一的条目标识") + title: str = Field(min_length=1, max_length=240, description="条目主标题") + subtitle: str | None = Field(default=None, max_length=320, description="条目辅助说明") + trailing: str | None = Field(default=None, max_length=64, description="右侧简短状态或数值") + progress: float | None = Field(default=None, ge=0, le=1, allow_inf_nan=False, description="可选自然完成度比例,范围 0 至 1") + + +class PluginWidgetSnapshot(BaseModel): + """ + 单个插件桌面小组件的有界只读快照,完整序列化体积不超过 32 KiB。 + """ + + version: Literal[1] = Field(default=1, description="插件小组件快照协议版本") + owner: str = Field(pattern=r"^[0-9a-f]{32}$", description="不可变管理员身份标识") + generatedAt: float = Field(gt=0, allow_inf_nan=False, description="快照生成的 UTC Unix 秒") + expiresAt: float = Field(gt=0, allow_inf_nan=False, description="快照展示上限的 UTC Unix 秒") + pluginId: str = Field(min_length=1, max_length=128, description="所属运行态插件标识") + pluginName: str = Field(min_length=1, max_length=120, description="所属插件显示名称") + widgetKey: str = Field(default="", max_length=64, description="插件内小组件标识") + state: Literal["ready", "empty", "unavailable"] = Field(description="读取成功、成功但为空或暂不可用") + updatedAt: float | None = Field(default=None, gt=0, allow_inf_nan=False, description="成功采样的 UTC Unix 秒;不可用时为空") + kind: PluginWidgetKind = Field(default="metrics", description="小组件渲染形态") + title: str = Field(min_length=1, max_length=240, description="卡片主标题") + subtitle: str | None = Field(default=None, max_length=240, description="卡片副标题") + metrics: list[PluginWidgetMetricItem] = Field(default_factory=list, max_length=8, description="预设模板指标集合,最多八项") + items: list[PluginWidgetListItem] = Field(default_factory=list, max_length=6, description="预设模板条目集合,最多六项") + layout: dict[str, Any] | None = Field(default=None, description="通用声明式自定义布局根节点,已经过层级与字段清洗") + layouts: dict[str, dict[str, Any]] | None = Field( + default=None, + description="按 small、medium、large 尺寸分别声明的自定义布局根节点映射", + ) + message: str | None = Field(default=None, max_length=240, description="可公开展示的状态说明文字") diff --git a/app/sdk/plugin/base.py b/app/sdk/plugin/base.py index db38a184d..76fc28bdd 100644 --- a/app/sdk/plugin/base.py +++ b/app/sdk/plugin/base.py @@ -191,6 +191,29 @@ class _PluginBase(metaclass=ABCMeta): """ pass + def get_widgets(self) -> Optional[List[Dict[str, Any]]]: + """ + 声明插件提供的移动端桌面小组件元信息。 + + 每项至少包含插件内唯一的 ``key`` 与展示名称 ``name``,可选提供 ``description``、 + ``kind``(``metrics``、``list``、``poster``、``nowPlaying`` 或 ``custom``)和建议刷新秒数 ``refresh``。 + + :return: 小组件声明字典列表;未提供专属声明时返回 None + """ + pass + + def get_widget_data(self, key: str = "") -> Optional[Dict[str, Any]]: + """ + 返回指定桌面小组件的只读展示数据或声明式布局节点树。 + + 返回字典可包含 ``title``、``subtitle``、``kind``、``metrics``、``items``、 + ``layout`` 或按尺寸区分的 ``layouts``;宿主会对体积、层级深度和链接执行有界清洗。 + + :param key: 插件内声明的小组件标识,缺省为空字符串以兼容单卡片实现 + :return: 小组件快照字典;当前无可展示数据时返回 None + """ + pass + def get_auth_providers(self) -> Optional[List[Dict[str, Any]]]: """ 声明插件提供的登录认证入口。 diff --git a/docs/mcp-api.md b/docs/mcp-api.md index 99d205bb9..6ce4c4b31 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -325,7 +325,7 @@ Web 影视精确与标题 SSE 的 `manual_paging=true` 模式在最终 `done` ### App 小组件只读接口 主 App 使用既有登录通过 `/api/v1/widget/context` 核对账号、`/api/v1/widget/registrations` 登记。 -扩展使用独立的有限期只读 Bearer 通过 `/api/v1/widget/snapshot` 刷新。 +扩展使用独立的有限期只读 Bearer 通过 `/api/v1/widget/snapshot` 刷新主体快照,超级管理员还可通过 `/api/v1/widget/plugins` 与 `/api/v1/widget/plugins/{plugin_id}` 只读刷新插件桌面小组件。 该凭据不适用于普通 REST/MCP,小组件接口也不加入 Agent 工具目录; 详见[授权、权限与快照协议](widgets.md)。主登录凭据不得交给系统扩展。 diff --git a/docs/widgets.md b/docs/widgets.md index 1b21a18c7..97d255cdc 100644 --- a/docs/widgets.md +++ b/docs/widgets.md @@ -83,3 +83,11 @@ Cookie、主登录 JWT、资源令牌或 `API_TOKEN`。小组件凭据也不能 入库保留成功历史的总数,追加按媒体类型计数及最近六条成功记录的季集、年份和原时间文字。小卡片显示总数,中卡片显示类别/状态统计,大卡片才显示真实名称和列表进度;媒体名称默认显示,可由用户关闭。下载小尺寸保留上传/下载速度,中大尺寸增加剩余空间、任务/状态数量,大尺寸追加任务名称、进度、单任务速度与预计剩余时间。 更新后的 App 和前端须一起升级以识别合并订阅内容、系统图标与八指标投影;旧客户端不能把未知指标当媒体数量显示。普通 Web/PWA 业务请求不变。 + +## 插件桌面小组件只读接口 + +超级管理员绑定的小组件专用 Bearer 可额外读取插件桌面小组件只读接口,普通成员调用时返回 `403`: + +- `GET /api/v1/widget/plugins`:返回当前已启用插件可绑定的桌面小组件目录 `PluginWidgetCatalog`(优先读取插件实现的 `get_widgets()`,未实现时自动把 `get_dashboard()` 投影为 `source="dashboard"` 的候选卡片)。 +- `GET /api/v1/widget/plugins/{plugin_id}?key=...`:返回单个插件小组件的只读快照 `PluginWidgetSnapshot`(支持 `metrics`、`list`、`poster`、`nowPlaying` 预设数据与层级不超过五层、总节点不超过四十个的 `custom` 声明式布局树;仅放行 `/api/v1/plugin/file/...` 同源静态资源路径,完整响应不超过 32 KiB)。 +- 前台已登录超级管理员亦可通过 `GET /api/v1/plugin/widgets/meta` 与 `GET /api/v1/plugin/widgets/{plugin_id}?key=...` 在配置界面预览插件小组件清单与实时快照。 diff --git a/tests/integration/dashboard/test_widget.py b/tests/integration/dashboard/test_widget.py index 672448aab..cec6f834a 100644 --- a/tests/integration/dashboard/test_widget.py +++ b/tests/integration/dashboard/test_widget.py @@ -828,3 +828,110 @@ def test_widget_system_sampler_reuses_existing_sources_in_order(monkeypatch): cpu, memory, network = dashboard_dependencies.sample_system() assert cpu == 42 and network == [1024, 2048] and memory.available == 30 assert [call[0] for call in source.mock_calls] == ["cpu_usage", "network_usage", "cpu_usage", "memory_usage"] + + +def test_widget_plugin_catalog_and_custom_snapshot_enforce_admin_and_bounds(widget_case): + """ + 仅超级管理员可读插件小组件;支持自定义节点树清洗、仪表板兜底与采样期撤权拦截。 + """ + case = widget_case + case.snapshots._plugin_widgets = lambda: [ + { + "plugin_id": "MusicBox", + "plugin_name": "音乐盒", + "key": "card_main", + "name": "实时播控卡", + "description": "展示曲目与自定义布局", + "kind": "custom", + "source": "widget", + "has_page": True, + }, + { + "plugin_id": "SiteStat", + "plugin_name": "站点统计", + "key": "", + "name": "站点统计", + "kind": "metrics", + "source": "dashboard", + "has_page": False, + }, + { + "plugin_id": "../bad", + "key": "ignored", + "name": "非法插件ID", + }, + ] + + def fake_widget_data(pid: str, key: str): + """ + 返回含越界属性与外部 URL 的自定义树,验证服务端白名单清洗。 + """ + if pid == "MusicBox" and key == "card_main": + return { + "title": "夜曲\n\x00", + "subtitle": "周杰伦", + "kind": "custom", + "metrics": [{"id": "m1", "label": "播放量", "value": "1,024", "tone": "accent"}], + "items": [{"id": "i1", "title": "七里香", "progress": 0.5}], + "layout": { + "type": "column", + "gap": 8, + "evil": "dropped", + "children": [ + {"type": "text", "text": "正在播放", "size": "md", "tone": "accent", "tabularNums": True}, + {"type": "image", "url": "https://evil.example/steal?token=1", "width": 48, "height": 48}, + {"type": "image", "url": "/api/v1/plugin/file/musicbox/cover.png", "width": 48, "height": 48}, + { + "type": "button", + "label": "下一首", + "action": {"type": "pluginAction", "surface": "data", "actionId": "next_track"}, + }, + ], + }, + } + if pid == "SiteStat": + return None + raise RuntimeError("secret-plugin-dsn://password") + + case.snapshots._plugin_widget_data = fake_widget_data + + # 普通用户凭据访问插件小组件目录或快照均返回 403 + member_issued = _register(case, user_id=101) + with _client(case) as client: + member_headers = {"Authorization": f"Bearer {member_issued.secret}"} + assert client.get("/api/v1/widget/plugins", headers=member_headers).status_code == 403 + assert client.get("/api/v1/widget/plugins/MusicBox?key=card_main", headers=member_headers).status_code == 403 + + # 升级为超级管理员后允许访问并执行清洗 + _update_user(case, user_id=101, is_superuser=True) + admin_issued = _register(case, user_id=101) + admin_headers = {"Authorization": f"Bearer {admin_issued.secret}"} + + cat_resp = client.get("/api/v1/widget/plugins", headers=admin_headers) + assert cat_resp.status_code == 200 + cat_json = cat_resp.json() + assert len(cat_json["widgets"]) == 2 + assert cat_json["widgets"][0]["pluginId"] == "MusicBox" + assert cat_json["widgets"][1]["source"] == "dashboard" + + snap_resp = client.get("/api/v1/widget/plugins/MusicBox?key=card_main", headers=admin_headers) + assert snap_resp.status_code == 200 + snap_json = snap_resp.json() + assert snap_json["state"] == "ready" + assert snap_json["kind"] == "custom" + assert "\x00" not in snap_json["title"] + assert "evil" not in snap_json["layout"] + children = snap_json["layout"]["children"] + assert "url" not in children[1] + assert children[2]["url"] == "/api/v1/plugin/file/musicbox/cover.png" + assert children[3]["action"]["actionId"] == "next_track" + + empty_resp = client.get("/api/v1/widget/plugins/SiteStat", headers=admin_headers) + assert empty_resp.status_code == 200 + assert empty_resp.json()["state"] == "empty" + + fail_resp = client.get("/api/v1/widget/plugins/BrokenPlugin", headers=admin_headers) + assert fail_resp.status_code == 200 + assert fail_resp.json()["state"] == "unavailable" + assert "secret-plugin-dsn" not in fail_resp.text + assert client.get("/api/v1/widget/plugins/bad..id", headers=admin_headers).status_code == 404 diff --git a/version.py b/version.py index 771e7928d..6acb260fe 100644 --- a/version.py +++ b/version.py @@ -2,8 +2,8 @@ 声明后端与前端发布版本。 """ -APP_VERSION = 'v3.2.14' -FRONTEND_VERSION = 'v3.2.14' +APP_VERSION = 'v3.2.15' +FRONTEND_VERSION = 'v3.2.15' # 本版本要求的最低 Docker 镜像系统基线(ISO 日期),与镜像内 /etc/moviepilot/system-baseline 比较。 # 低于该值的镜像拒绝应用内更新,提示用户先更新 Docker 镜像。只在修复严重系统级漏洞时提高, # 且在同一发布中把 docker/system-baseline 改成相同日期,保证新镜像自身满足要求。