# -*- 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 _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), "ui": bool((manifest or {}).get("ui")), "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"] elif t == "string" and prop.get("format") == "password": item["type"] = "password" elif t == "array": # 多选:items.enum 为预设选项;无 enum 则纯自由输入(前端 tags 可自建条目) item["type"] = "multiselect" if isinstance(prop.get("items"), dict) and "enum" in prop["items"]: item["options"] = prop["items"]["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