# -*- 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", [])}