lingshu-skill 5.65.0 → 5.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +1 -1
- package/cordis-plugin/lingshu-guard/plugin.js +6 -1
- package/manifest.json +30 -30
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +15 -15
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +282 -259
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +215 -209
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_exchange.py +217 -171
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +651 -627
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +32 -13
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +610 -602
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +219 -195
- package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +190 -181
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +148 -123
- package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +131 -124
- package/scripts/mem_dialogue.py +282 -259
- package/scripts/mem_embed.py +215 -209
- package/scripts/mem_exchange.py +217 -171
- package/scripts/panel_cloud.py +651 -627
- package/scripts/panel_server.py +32 -13
- package/scripts/panels.py +610 -602
- package/scripts/retriever.py +219 -195
- package/scripts/rss_ingest.py +190 -181
- package/scripts/session_summary.py +148 -123
- package/scripts/web_research.py +131 -124
|
@@ -1,602 +1,610 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""灵枢 自定义面板管理:目录扫描、manifest 校验、激活、本机市场、上传/安装/删除。
|
|
4
|
-
|
|
5
|
-
面板约定(规范详见 docs/panel-api.md):
|
|
6
|
-
- 已安装目录:brain.HOME / "panels",每个面板一个子目录 <面板名>/;
|
|
7
|
-
- 面板市场目录:brain.HOME / "panel-market"(本机共享库,拷贝目录即可流通,
|
|
8
|
-
本项目无云端后端,市场 = 本机目录,不假装有真云市场);
|
|
9
|
-
- 子目录必须含 panel.json(manifest):{"name","title","version","entry","lingshu_api"};
|
|
10
|
-
- 内置默认面板是 assets/panel.html,永远存在、不可删除(name = "default");
|
|
11
|
-
- 激活状态记在 config.json 的 "panel.active"(缺省 = 内置默认面板);
|
|
12
|
-
- 前端外壳(默认面板)启动时拉 /api/panels,active 非 default 就用 iframe 热加载
|
|
13
|
-
自定义面板,出错/超时自动回退——后端只负责如实报告面板状态,兜底在前端。
|
|
14
|
-
|
|
15
|
-
只依赖标准库 + brain(core),供 panel_server.py 转发调用。
|
|
16
|
-
"""
|
|
17
|
-
|
|
18
|
-
from __future__ import annotations
|
|
19
|
-
|
|
20
|
-
import io
|
|
21
|
-
import html
|
|
22
|
-
import json
|
|
23
|
-
import os
|
|
24
|
-
import re
|
|
25
|
-
import shutil
|
|
26
|
-
import subprocess
|
|
27
|
-
import sys
|
|
28
|
-
import time
|
|
29
|
-
import zipfile
|
|
30
|
-
from pathlib import Path
|
|
31
|
-
|
|
32
|
-
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
33
|
-
import brain # noqa: E402 (core.py 的 re-export,含 HOME / load_config / atomic_json)
|
|
34
|
-
|
|
35
|
-
# 内置默认面板名:面板列表里排在最前,标记「内置」,不可删除/上传
|
|
36
|
-
DEFAULT_NAME = "default"
|
|
37
|
-
# 静态文件白名单扩展名:超出者 GET /api/panels/file 一律 403(防源码/凭据外带)
|
|
38
|
-
FILE_WHITELIST = {".html", ".htm", ".js", ".css", ".json", ".png", ".jpg", ".jpeg",
|
|
39
|
-
".svg", ".ico", ".gif", ".webp", ".woff", ".woff2", ".ttf", ".map"}
|
|
40
|
-
# manifest name 规则:小写字母/数字/连字符/下划线/中文,1~32 字符
|
|
41
|
-
# 中文允许是产品决定:面板名直接当目录名,用户可见可读比纯 ASCII 更友好
|
|
42
|
-
_NAME_RE = re.compile(r"^[a-z0-9-_\u4e00-\u9fff]{1,32}$")
|
|
43
|
-
# 当前支持的 API 版本:manifest.lingshu_api 必须等于 1(未来不兼容时升版本号)
|
|
44
|
-
SUPPORTED_API = 1
|
|
45
|
-
# zip 解压防护:解压后总大小 ≤ 50MB、文件数 ≤ 500(zip bomb / 磁盘塞爆)
|
|
46
|
-
ZIP_MAX_TOTAL = 50 * 1024 * 1024
|
|
47
|
-
ZIP_MAX_FILES = 500
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
# ---------------------------------------------------------------- 目录与路径
|
|
51
|
-
|
|
52
|
-
def panels_dir() -> Path:
|
|
53
|
-
"""已安装面板根目录:brain.HOME/panels(懒创建,只读模式下不创建)。"""
|
|
54
|
-
d = brain.HOME / "panels"
|
|
55
|
-
if not brain.READONLY:
|
|
56
|
-
try:
|
|
57
|
-
d.mkdir(parents=True, exist_ok=True)
|
|
58
|
-
except OSError:
|
|
59
|
-
pass
|
|
60
|
-
return d
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def market_dir() -> Path:
|
|
64
|
-
"""面板市场(本机共享库)目录:brain.HOME/panel-market。
|
|
65
|
-
|
|
66
|
-
流通方式:整目录拷贝 / zip 互相传——文档里写清楚,不假装有云端市场。
|
|
67
|
-
"""
|
|
68
|
-
d = brain.HOME / "panel-market"
|
|
69
|
-
if not brain.READONLY:
|
|
70
|
-
try:
|
|
71
|
-
d.mkdir(parents=True, exist_ok=True)
|
|
72
|
-
except OSError:
|
|
73
|
-
pass
|
|
74
|
-
return d
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
def _panel_path(root: Path, name: str) -> Path:
|
|
78
|
-
"""面板目录拼路径。name 已过正则校验,天然无路径分隔符,这里再防一层。"""
|
|
79
|
-
if not _NAME_RE.match(name or ""):
|
|
80
|
-
raise ValueError("非法面板名")
|
|
81
|
-
return root / name
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def _safe_rel(panel_root: Path, rel: str) -> Path:
|
|
85
|
-
"""相对路径规范化后必须仍在 panel_root 内(防 .. 逃逸),返回绝对路径。"""
|
|
86
|
-
p = (panel_root / rel).resolve()
|
|
87
|
-
if not (p == panel_root.resolve() or panel_root.resolve() in p.parents):
|
|
88
|
-
raise PermissionError("路径越出面板目录")
|
|
89
|
-
return p
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
# ---------------------------------------------------------------- manifest
|
|
93
|
-
|
|
94
|
-
def _load_manifest(panel_root: Path) -> dict:
|
|
95
|
-
"""读并校验 panel.json。任何问题抛 ValueError(调用方转为 invalid 状态)。"""
|
|
96
|
-
mf = panel_root / "panel.json"
|
|
97
|
-
if not mf.exists():
|
|
98
|
-
raise ValueError("缺少 panel.json")
|
|
99
|
-
try:
|
|
100
|
-
data = json.loads(mf.read_text(encoding="utf-8-sig"))
|
|
101
|
-
except Exception as exc:
|
|
102
|
-
raise ValueError(f"panel.json 解析失败:{exc}")
|
|
103
|
-
if not isinstance(data, dict):
|
|
104
|
-
raise ValueError("panel.json 必须是对象")
|
|
105
|
-
name = str(data.get("name") or "")
|
|
106
|
-
if not _NAME_RE.match(name):
|
|
107
|
-
raise ValueError(f"name 不合法(小写字母/数字/-/_/中文,1~32 字符):{name!r}")
|
|
108
|
-
if name != panel_root.name:
|
|
109
|
-
raise ValueError(f"name ({name}) 与目录名 ({panel_root.name}) 不一致")
|
|
110
|
-
if not str(data.get("title") or "").strip():
|
|
111
|
-
raise ValueError("缺少 title(展示名)")
|
|
112
|
-
api_ver = data.get("lingshu_api")
|
|
113
|
-
if api_ver != SUPPORTED_API:
|
|
114
|
-
raise ValueError(f"lingshu_api 必须为 {SUPPORTED_API},当前是 {api_ver!r}")
|
|
115
|
-
entry = str(data.get("entry") or "index.html")
|
|
116
|
-
if entry.startswith(("/", "\\")) or ".." in Path(entry).parts or Path(entry).is_absolute():
|
|
117
|
-
raise ValueError(f"entry 不允许绝对路径或 ..:{entry!r}")
|
|
118
|
-
if not (panel_root / entry).is_file():
|
|
119
|
-
raise ValueError(f"entry 文件不存在:{entry}")
|
|
120
|
-
return {
|
|
121
|
-
"name": name,
|
|
122
|
-
"title": str(data.get("title") or name),
|
|
123
|
-
"version": str(data.get("version") or "0.0.0"),
|
|
124
|
-
"author": str(data.get("author") or ""),
|
|
125
|
-
"description": str(data.get("description") or ""),
|
|
126
|
-
"entry": entry,
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
def _scan_dir(root: Path, source: str) -> list:
|
|
131
|
-
"""扫描一个面板根目录(installed 或 market)→ 面板条目列表。
|
|
132
|
-
|
|
133
|
-
坏面板 valid=False 照样列出(用户能看见并删除),绝不抛异常影响其他面板。
|
|
134
|
-
"""
|
|
135
|
-
items: list = []
|
|
136
|
-
if not root.exists():
|
|
137
|
-
return items
|
|
138
|
-
for d in sorted(root.iterdir()):
|
|
139
|
-
if d.name.startswith(".") or not d.is_dir():
|
|
140
|
-
continue # 隐藏目录/文件、zip 都不按面板目录算
|
|
141
|
-
try:
|
|
142
|
-
mf = _load_manifest(d)
|
|
143
|
-
items.append({**mf, "valid": True, "invalid_reason": "", "source": source,
|
|
144
|
-
"dir": str(d), "has_entry": True})
|
|
145
|
-
except ValueError as exc:
|
|
146
|
-
# 损坏面板:不参与加载,但留在管理列表里供用户删除/修复
|
|
147
|
-
items.append({"name": d.name, "title": d.name, "version": "?", "author": "",
|
|
148
|
-
"description": "", "entry": "", "valid": False,
|
|
149
|
-
"invalid_reason": str(exc), "source": source,
|
|
150
|
-
"dir": str(d), "has_entry": False})
|
|
151
|
-
except OSError:
|
|
152
|
-
continue # 目录读不了(权限/被占用):跳过,不影响其他面板
|
|
153
|
-
return items
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
def _scan_market_zips(root: Path) -> list:
|
|
157
|
-
"""市场目录里的 zip 也列出来(source=market-zip),安装时现场解压校验。"""
|
|
158
|
-
items: list = []
|
|
159
|
-
if not root.exists():
|
|
160
|
-
return items
|
|
161
|
-
for f in sorted(root.glob("*.zip")):
|
|
162
|
-
try:
|
|
163
|
-
# zip 名去扩展名当展示名;真实 name 安装时从包内 manifest 读
|
|
164
|
-
items.append({"name": f.stem, "title": f.stem, "version": "?", "author": "",
|
|
165
|
-
"description": "zip 安装包(安装时解压校验)", "entry": "",
|
|
166
|
-
"valid": True, "invalid_reason": "", "source": "market-zip",
|
|
167
|
-
"dir": str(f), "has_entry": False, "zip": True})
|
|
168
|
-
except OSError:
|
|
169
|
-
continue
|
|
170
|
-
return items
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
# ---------------------------------------------------------------- 列表/读取
|
|
174
|
-
|
|
175
|
-
def list_panels() -> dict:
|
|
176
|
-
"""GET /api/panels 的返回体:active + 已安装列表 + 目录路径。"""
|
|
177
|
-
builtin = {
|
|
178
|
-
"name": DEFAULT_NAME, "title": "内置默认面板", "version": "builtin",
|
|
179
|
-
"author": "灵枢", "description": "随灵枢本体发布的默认面板(assets/panel.html)",
|
|
180
|
-
"entry": "panel.html", "valid": True, "invalid_reason": "",
|
|
181
|
-
"source": "builtin", "dir": "assets", "has_entry": True,
|
|
182
|
-
}
|
|
183
|
-
items = [builtin] + _scan_dir(panels_dir(), "installed")
|
|
184
|
-
active = _active_name()
|
|
185
|
-
return {
|
|
186
|
-
"active": active or DEFAULT_NAME,
|
|
187
|
-
"panels": items,
|
|
188
|
-
"installed_dir": str(panels_dir()),
|
|
189
|
-
"market_dir": str(market_dir()),
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
def list_market() -> dict:
|
|
194
|
-
"""GET /api/panels/market 的返回体:本机市场目录扫描结果(无云端,纯本机)。"""
|
|
195
|
-
root = market_dir()
|
|
196
|
-
return {"market_dir": str(root), "panels": _scan_dir(root, "market"),
|
|
197
|
-
"zips": _scan_market_zips(root)}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
def _active_name() -> str | None:
|
|
201
|
-
"""当前激活的自定义面板名;未激活/激活的是默认面板 → None。"""
|
|
202
|
-
try:
|
|
203
|
-
v = brain.load_config().get("panel.active")
|
|
204
|
-
except Exception:
|
|
205
|
-
return None
|
|
206
|
-
return str(v) if v else None
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
def check_entry(name: str) -> str:
|
|
210
|
-
"""activate 前预检:manifest+entry 都能过则返回 "",否则返回错误原因。"""
|
|
211
|
-
try:
|
|
212
|
-
_load_manifest(_panel_path(panels_dir(), name))
|
|
213
|
-
return ""
|
|
214
|
-
except Exception as exc:
|
|
215
|
-
return str(exc)
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
# ---------------------------------------------------------------- 动作
|
|
219
|
-
|
|
220
|
-
def _save_active(name: str | None) -> None:
|
|
221
|
-
"""把激活面板写进 config.json(加锁读改写,与 CLI 并发写安全)。"""
|
|
222
|
-
with brain._locked(brain.HOME / "config.json"):
|
|
223
|
-
cfg = brain.load_config()
|
|
224
|
-
if name:
|
|
225
|
-
cfg["panel.active"] = name
|
|
226
|
-
else:
|
|
227
|
-
cfg.pop("panel.active", None)
|
|
228
|
-
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
def activate(name: str) -> None:
|
|
232
|
-
"""激活自定义面板(热切换:前端拉列表后换 iframe,服务进程不动)。"""
|
|
233
|
-
if name in ("", DEFAULT_NAME, "None"):
|
|
234
|
-
_save_active(None)
|
|
235
|
-
return
|
|
236
|
-
err = check_entry(name)
|
|
237
|
-
if err:
|
|
238
|
-
raise ValueError(f"面板无法加载:{err}")
|
|
239
|
-
_save_active(name)
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
def deactivate() -> None:
|
|
243
|
-
"""回到内置默认面板。"""
|
|
244
|
-
_save_active(None)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
def delete(name: str, source: str) -> None:
|
|
248
|
-
"""删除 installed 或 market 里的面板目录;激活中的面板不允许删(400)。"""
|
|
249
|
-
if name == DEFAULT_NAME:
|
|
250
|
-
raise ValueError("内置默认面板不可删除")
|
|
251
|
-
root = panels_dir() if source == "installed" else market_dir()
|
|
252
|
-
d = _panel_path(root, name)
|
|
253
|
-
if not d.exists():
|
|
254
|
-
raise ValueError(f"面板不存在:{name}")
|
|
255
|
-
if source == "installed" and _active_name() == name:
|
|
256
|
-
raise ValueError("该面板正在使用中,请先切换回默认面板再删除")
|
|
257
|
-
# 只移不删:面板目录整棵移进程序目录的「垃圾桶」,带时间戳,用户自己清。
|
|
258
|
-
# (原先是 shutil.rmtree —— 违反「只移不删」的规矩,删了无法捞回。)
|
|
259
|
-
trash_root = _panel_trash_dir()
|
|
260
|
-
dst = trash_root / f"{time.strftime('%Y%m%d-%H%M%S')}_{d.name}"
|
|
261
|
-
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
262
|
-
shutil.move(str(d), str(dst))
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
def _panel_trash_dir() -> Path:
|
|
266
|
-
"""垃圾桶根目录:程序目录下的「垃圾桶/panels」。"""
|
|
267
|
-
return Path(__file__).resolve().parent.parent / "垃圾桶" / "panels"
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
def upload(name: str) -> dict:
|
|
271
|
-
"""上传 = 把已安装面板「剪切移动」到市场目录(shutil.move)。
|
|
272
|
-
|
|
273
|
-
目标已存在 → FileExistsError(server 层转 409,提示改名)。
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if
|
|
281
|
-
raise
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
"""
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
"""
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
if
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
"
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
"
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
entry
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
"
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
"""
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
"""
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
<
|
|
581
|
-
<
|
|
582
|
-
<
|
|
583
|
-
<
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
api(
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
""
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢 自定义面板管理:目录扫描、manifest 校验、激活、本机市场、上传/安装/删除。
|
|
4
|
+
|
|
5
|
+
面板约定(规范详见 docs/panel-api.md):
|
|
6
|
+
- 已安装目录:brain.HOME / "panels",每个面板一个子目录 <面板名>/;
|
|
7
|
+
- 面板市场目录:brain.HOME / "panel-market"(本机共享库,拷贝目录即可流通,
|
|
8
|
+
本项目无云端后端,市场 = 本机目录,不假装有真云市场);
|
|
9
|
+
- 子目录必须含 panel.json(manifest):{"name","title","version","entry","lingshu_api"};
|
|
10
|
+
- 内置默认面板是 assets/panel.html,永远存在、不可删除(name = "default");
|
|
11
|
+
- 激活状态记在 config.json 的 "panel.active"(缺省 = 内置默认面板);
|
|
12
|
+
- 前端外壳(默认面板)启动时拉 /api/panels,active 非 default 就用 iframe 热加载
|
|
13
|
+
自定义面板,出错/超时自动回退——后端只负责如实报告面板状态,兜底在前端。
|
|
14
|
+
|
|
15
|
+
只依赖标准库 + brain(core),供 panel_server.py 转发调用。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import io
|
|
21
|
+
import html
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
import zipfile
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
33
|
+
import brain # noqa: E402 (core.py 的 re-export,含 HOME / load_config / atomic_json)
|
|
34
|
+
|
|
35
|
+
# 内置默认面板名:面板列表里排在最前,标记「内置」,不可删除/上传
|
|
36
|
+
DEFAULT_NAME = "default"
|
|
37
|
+
# 静态文件白名单扩展名:超出者 GET /api/panels/file 一律 403(防源码/凭据外带)
|
|
38
|
+
FILE_WHITELIST = {".html", ".htm", ".js", ".css", ".json", ".png", ".jpg", ".jpeg",
|
|
39
|
+
".svg", ".ico", ".gif", ".webp", ".woff", ".woff2", ".ttf", ".map"}
|
|
40
|
+
# manifest name 规则:小写字母/数字/连字符/下划线/中文,1~32 字符
|
|
41
|
+
# 中文允许是产品决定:面板名直接当目录名,用户可见可读比纯 ASCII 更友好
|
|
42
|
+
_NAME_RE = re.compile(r"^[a-z0-9-_\u4e00-\u9fff]{1,32}$")
|
|
43
|
+
# 当前支持的 API 版本:manifest.lingshu_api 必须等于 1(未来不兼容时升版本号)
|
|
44
|
+
SUPPORTED_API = 1
|
|
45
|
+
# zip 解压防护:解压后总大小 ≤ 50MB、文件数 ≤ 500(zip bomb / 磁盘塞爆)
|
|
46
|
+
ZIP_MAX_TOTAL = 50 * 1024 * 1024
|
|
47
|
+
ZIP_MAX_FILES = 500
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------- 目录与路径
|
|
51
|
+
|
|
52
|
+
def panels_dir() -> Path:
|
|
53
|
+
"""已安装面板根目录:brain.HOME/panels(懒创建,只读模式下不创建)。"""
|
|
54
|
+
d = brain.HOME / "panels"
|
|
55
|
+
if not brain.READONLY:
|
|
56
|
+
try:
|
|
57
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
return d
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def market_dir() -> Path:
|
|
64
|
+
"""面板市场(本机共享库)目录:brain.HOME/panel-market。
|
|
65
|
+
|
|
66
|
+
流通方式:整目录拷贝 / zip 互相传——文档里写清楚,不假装有云端市场。
|
|
67
|
+
"""
|
|
68
|
+
d = brain.HOME / "panel-market"
|
|
69
|
+
if not brain.READONLY:
|
|
70
|
+
try:
|
|
71
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
except OSError:
|
|
73
|
+
pass
|
|
74
|
+
return d
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _panel_path(root: Path, name: str) -> Path:
|
|
78
|
+
"""面板目录拼路径。name 已过正则校验,天然无路径分隔符,这里再防一层。"""
|
|
79
|
+
if not _NAME_RE.match(name or ""):
|
|
80
|
+
raise ValueError("非法面板名")
|
|
81
|
+
return root / name
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _safe_rel(panel_root: Path, rel: str) -> Path:
|
|
85
|
+
"""相对路径规范化后必须仍在 panel_root 内(防 .. 逃逸),返回绝对路径。"""
|
|
86
|
+
p = (panel_root / rel).resolve()
|
|
87
|
+
if not (p == panel_root.resolve() or panel_root.resolve() in p.parents):
|
|
88
|
+
raise PermissionError("路径越出面板目录")
|
|
89
|
+
return p
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---------------------------------------------------------------- manifest
|
|
93
|
+
|
|
94
|
+
def _load_manifest(panel_root: Path) -> dict:
|
|
95
|
+
"""读并校验 panel.json。任何问题抛 ValueError(调用方转为 invalid 状态)。"""
|
|
96
|
+
mf = panel_root / "panel.json"
|
|
97
|
+
if not mf.exists():
|
|
98
|
+
raise ValueError("缺少 panel.json")
|
|
99
|
+
try:
|
|
100
|
+
data = json.loads(mf.read_text(encoding="utf-8-sig"))
|
|
101
|
+
except Exception as exc:
|
|
102
|
+
raise ValueError(f"panel.json 解析失败:{exc}")
|
|
103
|
+
if not isinstance(data, dict):
|
|
104
|
+
raise ValueError("panel.json 必须是对象")
|
|
105
|
+
name = str(data.get("name") or "")
|
|
106
|
+
if not _NAME_RE.match(name):
|
|
107
|
+
raise ValueError(f"name 不合法(小写字母/数字/-/_/中文,1~32 字符):{name!r}")
|
|
108
|
+
if name != panel_root.name:
|
|
109
|
+
raise ValueError(f"name ({name}) 与目录名 ({panel_root.name}) 不一致")
|
|
110
|
+
if not str(data.get("title") or "").strip():
|
|
111
|
+
raise ValueError("缺少 title(展示名)")
|
|
112
|
+
api_ver = data.get("lingshu_api")
|
|
113
|
+
if api_ver != SUPPORTED_API:
|
|
114
|
+
raise ValueError(f"lingshu_api 必须为 {SUPPORTED_API},当前是 {api_ver!r}")
|
|
115
|
+
entry = str(data.get("entry") or "index.html")
|
|
116
|
+
if entry.startswith(("/", "\\")) or ".." in Path(entry).parts or Path(entry).is_absolute():
|
|
117
|
+
raise ValueError(f"entry 不允许绝对路径或 ..:{entry!r}")
|
|
118
|
+
if not (panel_root / entry).is_file():
|
|
119
|
+
raise ValueError(f"entry 文件不存在:{entry}")
|
|
120
|
+
return {
|
|
121
|
+
"name": name,
|
|
122
|
+
"title": str(data.get("title") or name),
|
|
123
|
+
"version": str(data.get("version") or "0.0.0"),
|
|
124
|
+
"author": str(data.get("author") or ""),
|
|
125
|
+
"description": str(data.get("description") or ""),
|
|
126
|
+
"entry": entry,
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _scan_dir(root: Path, source: str) -> list:
|
|
131
|
+
"""扫描一个面板根目录(installed 或 market)→ 面板条目列表。
|
|
132
|
+
|
|
133
|
+
坏面板 valid=False 照样列出(用户能看见并删除),绝不抛异常影响其他面板。
|
|
134
|
+
"""
|
|
135
|
+
items: list = []
|
|
136
|
+
if not root.exists():
|
|
137
|
+
return items
|
|
138
|
+
for d in sorted(root.iterdir()):
|
|
139
|
+
if d.name.startswith(".") or not d.is_dir():
|
|
140
|
+
continue # 隐藏目录/文件、zip 都不按面板目录算
|
|
141
|
+
try:
|
|
142
|
+
mf = _load_manifest(d)
|
|
143
|
+
items.append({**mf, "valid": True, "invalid_reason": "", "source": source,
|
|
144
|
+
"dir": str(d), "has_entry": True})
|
|
145
|
+
except ValueError as exc:
|
|
146
|
+
# 损坏面板:不参与加载,但留在管理列表里供用户删除/修复
|
|
147
|
+
items.append({"name": d.name, "title": d.name, "version": "?", "author": "",
|
|
148
|
+
"description": "", "entry": "", "valid": False,
|
|
149
|
+
"invalid_reason": str(exc), "source": source,
|
|
150
|
+
"dir": str(d), "has_entry": False})
|
|
151
|
+
except OSError:
|
|
152
|
+
continue # 目录读不了(权限/被占用):跳过,不影响其他面板
|
|
153
|
+
return items
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _scan_market_zips(root: Path) -> list:
|
|
157
|
+
"""市场目录里的 zip 也列出来(source=market-zip),安装时现场解压校验。"""
|
|
158
|
+
items: list = []
|
|
159
|
+
if not root.exists():
|
|
160
|
+
return items
|
|
161
|
+
for f in sorted(root.glob("*.zip")):
|
|
162
|
+
try:
|
|
163
|
+
# zip 名去扩展名当展示名;真实 name 安装时从包内 manifest 读
|
|
164
|
+
items.append({"name": f.stem, "title": f.stem, "version": "?", "author": "",
|
|
165
|
+
"description": "zip 安装包(安装时解压校验)", "entry": "",
|
|
166
|
+
"valid": True, "invalid_reason": "", "source": "market-zip",
|
|
167
|
+
"dir": str(f), "has_entry": False, "zip": True})
|
|
168
|
+
except OSError:
|
|
169
|
+
continue
|
|
170
|
+
return items
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# ---------------------------------------------------------------- 列表/读取
|
|
174
|
+
|
|
175
|
+
def list_panels() -> dict:
|
|
176
|
+
"""GET /api/panels 的返回体:active + 已安装列表 + 目录路径。"""
|
|
177
|
+
builtin = {
|
|
178
|
+
"name": DEFAULT_NAME, "title": "内置默认面板", "version": "builtin",
|
|
179
|
+
"author": "灵枢", "description": "随灵枢本体发布的默认面板(assets/panel.html)",
|
|
180
|
+
"entry": "panel.html", "valid": True, "invalid_reason": "",
|
|
181
|
+
"source": "builtin", "dir": "assets", "has_entry": True,
|
|
182
|
+
}
|
|
183
|
+
items = [builtin] + _scan_dir(panels_dir(), "installed")
|
|
184
|
+
active = _active_name()
|
|
185
|
+
return {
|
|
186
|
+
"active": active or DEFAULT_NAME,
|
|
187
|
+
"panels": items,
|
|
188
|
+
"installed_dir": str(panels_dir()),
|
|
189
|
+
"market_dir": str(market_dir()),
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def list_market() -> dict:
|
|
194
|
+
"""GET /api/panels/market 的返回体:本机市场目录扫描结果(无云端,纯本机)。"""
|
|
195
|
+
root = market_dir()
|
|
196
|
+
return {"market_dir": str(root), "panels": _scan_dir(root, "market"),
|
|
197
|
+
"zips": _scan_market_zips(root)}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _active_name() -> str | None:
|
|
201
|
+
"""当前激活的自定义面板名;未激活/激活的是默认面板 → None。"""
|
|
202
|
+
try:
|
|
203
|
+
v = brain.load_config().get("panel.active")
|
|
204
|
+
except Exception:
|
|
205
|
+
return None
|
|
206
|
+
return str(v) if v else None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def check_entry(name: str) -> str:
|
|
210
|
+
"""activate 前预检:manifest+entry 都能过则返回 "",否则返回错误原因。"""
|
|
211
|
+
try:
|
|
212
|
+
_load_manifest(_panel_path(panels_dir(), name))
|
|
213
|
+
return ""
|
|
214
|
+
except Exception as exc:
|
|
215
|
+
return str(exc)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# ---------------------------------------------------------------- 动作
|
|
219
|
+
|
|
220
|
+
def _save_active(name: str | None) -> None:
|
|
221
|
+
"""把激活面板写进 config.json(加锁读改写,与 CLI 并发写安全)。"""
|
|
222
|
+
with brain._locked(brain.HOME / "config.json"):
|
|
223
|
+
cfg = brain.load_config()
|
|
224
|
+
if name:
|
|
225
|
+
cfg["panel.active"] = name
|
|
226
|
+
else:
|
|
227
|
+
cfg.pop("panel.active", None)
|
|
228
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def activate(name: str) -> None:
|
|
232
|
+
"""激活自定义面板(热切换:前端拉列表后换 iframe,服务进程不动)。"""
|
|
233
|
+
if name in ("", DEFAULT_NAME, "None"):
|
|
234
|
+
_save_active(None)
|
|
235
|
+
return
|
|
236
|
+
err = check_entry(name)
|
|
237
|
+
if err:
|
|
238
|
+
raise ValueError(f"面板无法加载:{err}")
|
|
239
|
+
_save_active(name)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def deactivate() -> None:
|
|
243
|
+
"""回到内置默认面板。"""
|
|
244
|
+
_save_active(None)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def delete(name: str, source: str) -> None:
|
|
248
|
+
"""删除 installed 或 market 里的面板目录;激活中的面板不允许删(400)。"""
|
|
249
|
+
if name == DEFAULT_NAME:
|
|
250
|
+
raise ValueError("内置默认面板不可删除")
|
|
251
|
+
root = panels_dir() if source == "installed" else market_dir()
|
|
252
|
+
d = _panel_path(root, name)
|
|
253
|
+
if not d.exists():
|
|
254
|
+
raise ValueError(f"面板不存在:{name}")
|
|
255
|
+
if source == "installed" and _active_name() == name:
|
|
256
|
+
raise ValueError("该面板正在使用中,请先切换回默认面板再删除")
|
|
257
|
+
# 只移不删:面板目录整棵移进程序目录的「垃圾桶」,带时间戳,用户自己清。
|
|
258
|
+
# (原先是 shutil.rmtree —— 违反「只移不删」的规矩,删了无法捞回。)
|
|
259
|
+
trash_root = _panel_trash_dir()
|
|
260
|
+
dst = trash_root / f"{time.strftime('%Y%m%d-%H%M%S')}_{d.name}"
|
|
261
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
262
|
+
shutil.move(str(d), str(dst))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _panel_trash_dir() -> Path:
|
|
266
|
+
"""垃圾桶根目录:程序目录下的「垃圾桶/panels」。"""
|
|
267
|
+
return Path(__file__).resolve().parent.parent / "垃圾桶" / "panels"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def upload(name: str) -> dict:
|
|
271
|
+
"""上传 = 把已安装面板「剪切移动」到市场目录(shutil.move)。
|
|
272
|
+
|
|
273
|
+
目标已存在 → FileExistsError(server 层转 409,提示改名)。
|
|
274
|
+
LS-072(v5.67):禁止上传当前激活面板!
|
|
275
|
+
"""
|
|
276
|
+
# LS-072: 激活面板不允许上传(移走后 config 指向不存在的目录)
|
|
277
|
+
if _active_name() == name:
|
|
278
|
+
raise ValueError("该面板正在使用中,请先切换回默认面板再上传")
|
|
279
|
+
src = _panel_path(panels_dir(), name)
|
|
280
|
+
if not src.exists():
|
|
281
|
+
raise ValueError(f"已安装面板不存在:{name}")
|
|
282
|
+
_load_manifest(src) # 损坏面板不允许上传分享
|
|
283
|
+
dst = _panel_path(market_dir(), name)
|
|
284
|
+
if dst.exists():
|
|
285
|
+
raise FileExistsError(f"市场里已有同名面板:{name}")
|
|
286
|
+
shutil.move(str(src), str(dst))
|
|
287
|
+
return {"ok": True, "market": str(dst)}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def install(name: str) -> dict:
|
|
291
|
+
"""从市场安装到已安装目录。
|
|
292
|
+
|
|
293
|
+
市场里的分享源用「复制」保留(供本机其他用户/下次继续安装);
|
|
294
|
+
目标已存在 → FileExistsError(409);zip 形式则现场解压校验后落位。
|
|
295
|
+
"""
|
|
296
|
+
mroot = market_dir()
|
|
297
|
+
mdir = _panel_path(mroot, name)
|
|
298
|
+
if mdir.exists():
|
|
299
|
+
mf = _load_manifest(mdir) # 先校验再装:坏面板不落盘
|
|
300
|
+
dst = _panel_path(panels_dir(), mf["name"])
|
|
301
|
+
if dst.exists():
|
|
302
|
+
raise FileExistsError(f"已安装目录里已有同名面板:{mf['name']}")
|
|
303
|
+
shutil.copytree(mdir, dst)
|
|
304
|
+
return {"ok": True, "name": mf["name"], "title": mf["title"],
|
|
305
|
+
"version": mf["version"]}
|
|
306
|
+
zpath = _panel_path(mroot, name)
|
|
307
|
+
if not zpath.exists():
|
|
308
|
+
zpath = mroot / f"{name}.zip"
|
|
309
|
+
if zpath.suffix.lower() != ".zip" or not zpath.exists():
|
|
310
|
+
raise ValueError(f"市场里没有该面板(目录或 zip):{name}")
|
|
311
|
+
# zip 安装:解到临时目录校验 manifest 通过后再落位(坏包不留垃圾)
|
|
312
|
+
return _install_zip(zpath)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _install_zip(zpath: Path) -> dict:
|
|
316
|
+
"""解压市场 zip 安装:总量/文件数/路径三重防护,manifest 校验后才落位。"""
|
|
317
|
+
data = zpath.read_bytes()
|
|
318
|
+
# LS-070(v5.67):为每次面板安装使用独立临时目录!
|
|
319
|
+
# 旧代码用固定 ".tmp-install",并发安装会互删或交叉读取内容。
|
|
320
|
+
import uuid
|
|
321
|
+
tmp = panels_dir() / f".tmp-install-{uuid.uuid4().hex[:8]}"
|
|
322
|
+
tmp.mkdir(parents=True)
|
|
323
|
+
try:
|
|
324
|
+
_extract_zip_safe(data, tmp)
|
|
325
|
+
# 定位 zip 里的 panel.json:根目录/顶层目录都兼容
|
|
326
|
+
for cand in [tmp, *sorted(tmp.iterdir())]:
|
|
327
|
+
if (cand / "panel.json").is_file():
|
|
328
|
+
try:
|
|
329
|
+
mf = _load_manifest(cand)
|
|
330
|
+
except ValueError:
|
|
331
|
+
continue
|
|
332
|
+
dst = _panel_path(panels_dir(), mf["name"])
|
|
333
|
+
if dst.exists():
|
|
334
|
+
raise FileExistsError(f"已安装目录里已有同名面板:{mf['name']}")
|
|
335
|
+
shutil.move(str(cand), str(dst))
|
|
336
|
+
return {"ok": True, "name": mf["name"], "title": mf["title"],
|
|
337
|
+
"version": mf["version"]}
|
|
338
|
+
raise ValueError("zip 内未��到有效的 panel.json")
|
|
339
|
+
finally:
|
|
340
|
+
# 仅清理本次安装自身的临时目录,绝不影响并发安装的其他实例
|
|
341
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _extract_zip_safe(data: bytes, dest: Path) -> None:
|
|
345
|
+
"""安全解压 zip:总量/文件数/路径/扩展名四重防护(zip bomb 与路径逃逸)。"""
|
|
346
|
+
# LS-069(v5.67):允许面板包包含合法 JavaScript 资源!
|
|
347
|
+
# 旧代码遗漏了 .js(面板可能需要 app.js),但 FILE_WHITELIST 和静态服务
|
|
348
|
+
# 的扩展名映射里已有 .js——统一安装与静态服务白名单。
|
|
349
|
+
allowed_ext = {".json", ".html", ".htm", ".css", ".js", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".txt", ".md"}
|
|
350
|
+
total = 0
|
|
351
|
+
count = 0
|
|
352
|
+
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
|
353
|
+
dest_real = dest.resolve()
|
|
354
|
+
for info in z.infolist():
|
|
355
|
+
nm = info.filename
|
|
356
|
+
if nm.startswith("/") or ".." in Path(nm).parts or (len(nm) > 1 and nm[1] == ":"):
|
|
357
|
+
raise ValueError(f"zip 内含非法路径:{nm!r}")
|
|
358
|
+
# 白名单校验:解析后的绝对路径必须仍在目标目录内(双写绕过/链接条目兜底)
|
|
359
|
+
if not (dest_real / nm).resolve().is_relative_to(dest_real):
|
|
360
|
+
raise ValueError(f"zip 内路径逃逸:{nm!r}")
|
|
361
|
+
if not nm.endswith("/"):
|
|
362
|
+
ext = Path(nm).suffix.lower()
|
|
363
|
+
if ext not in allowed_ext:
|
|
364
|
+
raise ValueError(f"zip 内含不允许的文件类型:{nm!r}(仅允许静态资源)")
|
|
365
|
+
total += info.file_size
|
|
366
|
+
if total > ZIP_MAX_TOTAL:
|
|
367
|
+
raise ValueError("zip 解压后超过 50MB 上限")
|
|
368
|
+
count += 1
|
|
369
|
+
if count > ZIP_MAX_FILES:
|
|
370
|
+
raise ValueError("zip 文件数超过 500 上限")
|
|
371
|
+
z.extractall(dest)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
# ---------------------------------------------------------------- 拓展商店(宿主适配插件)
|
|
375
|
+
|
|
376
|
+
# 项目内随包分发的适配插件目录:kind → (相对路径, 宿主名)
|
|
377
|
+
# usage = 装完之后的接入教程(面板拓展卡片展示);复制路径等操作由用户手动完成
|
|
378
|
+
_BUILTIN_EXTENSIONS = [
|
|
379
|
+
{"id": "astrbot_plugin_lingshu", "host": "AstrBot", "rel": "scripts/astrbot_plugin_lingshu",
|
|
380
|
+
"title": "灵枢记忆桥", "desc": "把群聊/私聊记忆接入 AstrBot,含群友隐私保护"
|
|
381
|
+
"(本人同意才能对外分享关于自己的记忆)。subprocess 进程隔离调用灵枢 CLI。",
|
|
382
|
+
"usage": "① 点击「安装」→ 插件被导出到 ~/.brain-memory/extensions/installed/"
|
|
383
|
+
"astrbot_plugin_lingshu/;② 把整个目录复制到 AstrBot 的 data/plugins/ 下;"
|
|
384
|
+
"③ 在 AstrBot 插件管理页重载(或重启 AstrBot);④ 群/私聊发送"
|
|
385
|
+
"「lingshu 帮助」验证接入,可用指令:lingshu 记住/找回/同意/拒绝/忘记。"},
|
|
386
|
+
{"id": "lingshu-startup", "host": "cordis (Koishi)", "rel": "cordis-plugin/lingshu-startup",
|
|
387
|
+
"title": "灵枢启动器", "desc": "宿主启动时通过 brain.py startup 注入灵枢会话上下文。",
|
|
388
|
+
"usage": "① 点击「安装」→ 插件被导出到 ~/.brain-memory/extensions/installed/"
|
|
389
|
+
"lingshu-startup/;② 把整个目录复制到 Koishi/cordis 的插件目录并安装依赖;"
|
|
390
|
+
"③ 在 Koishi 控制台「插件配置」里启用 lingshu-startup;"
|
|
391
|
+
"④ 重启后机器人收到首条消息即自动注入灵枢记忆上下文。"},
|
|
392
|
+
]
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _extension_meta(d: Path) -> dict:
|
|
396
|
+
"""尽力读一个适配插件的元信息(yaml/py 头注释),读不到给默认值。"""
|
|
397
|
+
meta = {"version": "?", "author": ""}
|
|
398
|
+
y = d / "metadata.yaml"
|
|
399
|
+
if y.is_file():
|
|
400
|
+
try:
|
|
401
|
+
txt = y.read_text(encoding="utf-8-sig")
|
|
402
|
+
m = re.search(r"^version:\s*(\S+)", txt, re.M)
|
|
403
|
+
if m:
|
|
404
|
+
meta["version"] = m.group(1)
|
|
405
|
+
m = re.search(r"^author:\s*(\S+)", txt, re.M)
|
|
406
|
+
if m:
|
|
407
|
+
meta["author"] = m.group(1)
|
|
408
|
+
except OSError:
|
|
409
|
+
pass
|
|
410
|
+
return meta
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def list_extensions() -> dict:
|
|
414
|
+
"""GET /api/extensions:拓展商店清单。
|
|
415
|
+
|
|
416
|
+
两类来源:
|
|
417
|
+
1. 内置(随灵枢本体发布):项目 scripts/ / cordis-plugin/ 下的适配插件;
|
|
418
|
+
2. 自定义(用户/第三方):brain.HOME/extensions/<kind>/ 目录,整目录拷进来即可,
|
|
419
|
+
manifest 元信息尽力读取,读不到也能展示/安装。
|
|
420
|
+
「安装」= 把插件目录复制到对应宿主的插件目录之外的可分发位置再由用户搬运,
|
|
421
|
+
这里只负责把内置插件导出到 brain.HOME/extensions/installed/(zip 不参与,纯目录),
|
|
422
|
+
真正接入宿主(如 AstrBot 的 plugins 目录)仍需用户手动放置——面板里写清楚。
|
|
423
|
+
"""
|
|
424
|
+
root = brain.HOME / "extensions"
|
|
425
|
+
installed = root / "installed"
|
|
426
|
+
items = []
|
|
427
|
+
proj = brain.PROJECT_ROOT if hasattr(brain, "PROJECT_ROOT") else Path(__file__).resolve().parent.parent
|
|
428
|
+
for spec in _BUILTIN_EXTENSIONS:
|
|
429
|
+
src = proj / spec["rel"]
|
|
430
|
+
entry = {
|
|
431
|
+
"id": spec["id"], "title": spec["title"], "host": spec["host"],
|
|
432
|
+
"desc": spec["desc"], "usage": spec.get("usage", ""), "source": "builtin",
|
|
433
|
+
"dir": str(src), "exists": src.is_dir(),
|
|
434
|
+
}
|
|
435
|
+
if src.is_dir():
|
|
436
|
+
entry.update(_extension_meta(src))
|
|
437
|
+
# 已导出过?标记 installed,面板上显示「已安装」而不是重复导出
|
|
438
|
+
entry["exported"] = (installed / spec["id"]).is_dir()
|
|
439
|
+
if entry["exported"]:
|
|
440
|
+
entry["dir"] = str(installed / spec["id"])
|
|
441
|
+
items.append(entry)
|
|
442
|
+
if installed.is_dir():
|
|
443
|
+
for d in sorted(installed.iterdir()):
|
|
444
|
+
if d.name.startswith(".") or not d.is_dir():
|
|
445
|
+
continue
|
|
446
|
+
if any(x["id"] == d.name for x in _BUILTIN_EXTENSIONS):
|
|
447
|
+
continue # 内置同名已列过
|
|
448
|
+
e = {"id": d.name, "title": d.name, "host": "自定义", "desc": "",
|
|
449
|
+
"source": "custom", "dir": str(d), "exists": True, "exported": True}
|
|
450
|
+
e.update(_extension_meta(d))
|
|
451
|
+
items.append(e)
|
|
452
|
+
# 云端商店条目:Gitee/GitHub 仓库 index.json 的 extensions 数组(同仓库 panels/ 子目录平级)。
|
|
453
|
+
# 单独展示为 source:"cloud",点下载走 cloud_extension_download 单独拉 zip,不拉整个仓库。
|
|
454
|
+
cloud_ids = {x["id"] for x in items}
|
|
455
|
+
cloud: list = []
|
|
456
|
+
try:
|
|
457
|
+
import panel_cloud # 延迟导入:无云端配置时零开销
|
|
458
|
+
data = panel_cloud.cloud_list()
|
|
459
|
+
for ce in data.get("extensions", []):
|
|
460
|
+
cid = str(ce.get("id") or ce.get("name") or "")
|
|
461
|
+
if not cid or cid in cloud_ids:
|
|
462
|
+
continue
|
|
463
|
+
cloud_ids.add(cid)
|
|
464
|
+
cloud.append({
|
|
465
|
+
"id": cid, "title": str(ce.get("title") or cid),
|
|
466
|
+
"host": str(ce.get("host") or "云端"),
|
|
467
|
+
"desc": str(ce.get("description") or ce.get("desc") or ""),
|
|
468
|
+
"usage": str(ce.get("usage") or ""),
|
|
469
|
+
"version": str(ce.get("version") or ""),
|
|
470
|
+
"author": str(ce.get("author") or ""),
|
|
471
|
+
"source": "cloud", "exists": True,
|
|
472
|
+
"exported": (root / "installed" / cid).is_dir(),
|
|
473
|
+
"size": ce.get("size", 0),
|
|
474
|
+
})
|
|
475
|
+
if data.get("errors"):
|
|
476
|
+
cloud.append({"id": "", "source": "cloud-error",
|
|
477
|
+
"desc": ";".join(data["errors"])})
|
|
478
|
+
except Exception:
|
|
479
|
+
pass # 没配置云端/网络失败:商店照常显示本机条目
|
|
480
|
+
return {"extensions": items + cloud, "installed_dir": str(installed),
|
|
481
|
+
"readonly": bool(brain.READONLY)}
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def export_extension(ext_id: str) -> dict:
|
|
485
|
+
"""把内置适配插件复制到 brain.HOME/extensions/installed/(「从商店下载安装」)。"""
|
|
486
|
+
if not _NAME_RE.match(ext_id or ""):
|
|
487
|
+
raise ValueError("非法拓展名")
|
|
488
|
+
spec = next((s for s in _BUILTIN_EXTENSIONS if s["id"] == ext_id), None)
|
|
489
|
+
if not spec:
|
|
490
|
+
raise ValueError(f"商店里没有这个拓展:{ext_id}")
|
|
491
|
+
if brain.READONLY:
|
|
492
|
+
raise PermissionError("记忆库当前只读,无法安装拓展。")
|
|
493
|
+
proj = brain.PROJECT_ROOT if hasattr(brain, "PROJECT_ROOT") else Path(__file__).resolve().parent.parent
|
|
494
|
+
src = proj / spec["rel"]
|
|
495
|
+
if not src.is_dir():
|
|
496
|
+
raise ValueError(f"拓展源目录不存在:{spec['rel']}")
|
|
497
|
+
dst = brain.HOME / "extensions" / "installed" / ext_id
|
|
498
|
+
if dst.exists():
|
|
499
|
+
raise FileExistsError(f"已经安装过:{ext_id}(先删除再重装)")
|
|
500
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
501
|
+
shutil.copytree(src, dst)
|
|
502
|
+
return {"ok": True, "id": ext_id, "host": spec["host"], "installed_dir": str(dst)}
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def open_folder(which: str) -> str:
|
|
506
|
+
"""用资源管理器打开 panels / panel-market 目录,返回路径。
|
|
507
|
+
|
|
508
|
+
os.startfile 仅 Windows;其他平台 subprocess 调 open/xdg-open,失败静默
|
|
509
|
+
(路径照常返回,用户可以自己导航过去)。
|
|
510
|
+
"""
|
|
511
|
+
if which == "market":
|
|
512
|
+
d = market_dir()
|
|
513
|
+
elif which == "extensions":
|
|
514
|
+
d = brain.HOME / "extensions" / "installed"
|
|
515
|
+
else:
|
|
516
|
+
d = panels_dir()
|
|
517
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
518
|
+
try:
|
|
519
|
+
if hasattr(os, "startfile"):
|
|
520
|
+
os.startfile(str(d)) # noqa: S606 Windows 专属,路径来自本机数据目录
|
|
521
|
+
elif sys.platform == "darwin":
|
|
522
|
+
subprocess.Popen(["open", str(d)])
|
|
523
|
+
else:
|
|
524
|
+
subprocess.Popen(["xdg-open", str(d)])
|
|
525
|
+
except Exception:
|
|
526
|
+
pass # 打不开不报错:路径已在响应里,用户可手动前往
|
|
527
|
+
return str(d)
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def scaffold(name: str, title: str) -> dict:
|
|
531
|
+
"""生成最小合法面板骨架:panel.json + index.html(含 api() helper 示例)。
|
|
532
|
+
|
|
533
|
+
AI/用户一键起步:POST /api/panels/scaffold → 改文件 → 即刻可在管理界面启用。
|
|
534
|
+
"""
|
|
535
|
+
if not _NAME_RE.match(name or ""):
|
|
536
|
+
raise ValueError("面板名不合法(小写字母/数字/-/_/中文,1~32 字符)")
|
|
537
|
+
d = _panel_path(panels_dir(), name)
|
|
538
|
+
if d.exists():
|
|
539
|
+
raise FileExistsError(f"面板已存在:{name}")
|
|
540
|
+
d.mkdir(parents=True)
|
|
541
|
+
(d / "panel.json").write_text(json.dumps({
|
|
542
|
+
"name": name, "title": title or name, "version": "0.1.0",
|
|
543
|
+
"author": "", "description": "脚手架生成的最小面板",
|
|
544
|
+
"entry": "index.html", "lingshu_api": 1,
|
|
545
|
+
}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
546
|
+
# 标题进 HTML 文本位前做转义,防 XSS(模板结构占位符原样替换不受影响)
|
|
547
|
+
safe_title = html.escape(title or name, quote=False)
|
|
548
|
+
(d / "index.html").write_text(_SCAFFOLD_HTML.replace("__TITLE__", safe_title),
|
|
549
|
+
encoding="utf-8")
|
|
550
|
+
return {"ok": True, "name": name, "path": str(d)}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
# ---------------------------------------------------------------- 静态文件
|
|
554
|
+
|
|
555
|
+
def read_panel_file(name: str, rel: str) -> tuple[bytes, str]:
|
|
556
|
+
"""读面板目录内静态文件 → (内容, Content-Type)。越界/白名单外抛异常。"""
|
|
557
|
+
d = _panel_path(panels_dir(), name)
|
|
558
|
+
p = _safe_rel(d, rel)
|
|
559
|
+
if not p.is_file():
|
|
560
|
+
raise FileNotFoundError(f"文件不存在:{rel}")
|
|
561
|
+
ext = p.suffix.lower()
|
|
562
|
+
if ext not in FILE_WHITELIST:
|
|
563
|
+
raise PermissionError(f"扩展名不在白名单:{ext}")
|
|
564
|
+
ctype = {
|
|
565
|
+
".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8",
|
|
566
|
+
".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
|
|
567
|
+
".json": "application/json; charset=utf-8", ".png": "image/png",
|
|
568
|
+
".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
|
569
|
+
".webp": "image/webp", ".svg": "image/svg+xml", ".ico": "image/x-icon",
|
|
570
|
+
".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf",
|
|
571
|
+
".map": "application/json; charset=utf-8",
|
|
572
|
+
}[ext]
|
|
573
|
+
return p.read_bytes(), ctype
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
# 脚手架骨架 HTML:含 PANEL_TOKEN 占位符 + api() helper + /api/overview 调用示例,
|
|
577
|
+
# AI/用户起步即改即用;token 由服务端下发 HTML 时注入(替换占位符)
|
|
578
|
+
_SCAFFOLD_HTML = """<!DOCTYPE html>
|
|
579
|
+
<html lang="zh">
|
|
580
|
+
<head>
|
|
581
|
+
<meta charset="utf-8">
|
|
582
|
+
<title>__TITLE__</title>
|
|
583
|
+
<style>
|
|
584
|
+
body{font-family:system-ui;background:#14181e;color:#e6e1d5;margin:0;padding:32px}
|
|
585
|
+
.card{background:#1b2028;border:1px solid #2a3140;border-radius:12px;padding:20px;max-width:640px}
|
|
586
|
+
</style>
|
|
587
|
+
</head>
|
|
588
|
+
<body>
|
|
589
|
+
<h1>__TITLE__</h1>
|
|
590
|
+
<div class="card"><div id="out">加载中…</div></div>
|
|
591
|
+
<script>
|
|
592
|
+
const PANEL_TOKEN = "/*__PANEL_TOKEN__*/";
|
|
593
|
+
// 统一 API helper:Bearer token 已由服务端注入(见 docs/panel-api.md)
|
|
594
|
+
async function api(path, opts){
|
|
595
|
+
opts = opts || {};
|
|
596
|
+
opts.headers = Object.assign({}, opts.headers || {}, {Authorization: "Bearer " + PANEL_TOKEN});
|
|
597
|
+
const r = await fetch(path, opts);
|
|
598
|
+
const d = await r.json().catch(() => ({}));
|
|
599
|
+
if (!r.ok || d.error) throw new Error(d.error || ("HTTP " + r.status));
|
|
600
|
+
return d;
|
|
601
|
+
}
|
|
602
|
+
api("/api/overview").then(d => {
|
|
603
|
+
document.getElementById("out").textContent =
|
|
604
|
+
"记忆总数:" + (d.stats && d.stats.total != null ? d.stats.total : "?") +
|
|
605
|
+
",海马体层:" + (d.layer_counts ? d.layer_counts.hippo : "?");
|
|
606
|
+
}).catch(e => document.getElementById("out").textContent = "加载失败:" + e.message);
|
|
607
|
+
</script>
|
|
608
|
+
</body>
|
|
609
|
+
</html>
|
|
610
|
+
"""
|