lingshu-skill 5.66.0 → 5.68.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.
@@ -1,627 +1,651 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """灵枢 云端面板市场:Gitee(主)/ GitHub(镜像)仓库当云端,纯标准库 urllib。
4
-
5
- 云端约定(仓库布局):
6
- - panels/<面板名>.zip 面板安装包(≤50MB,安装时解压校验 manifest)
7
- - shots/<面板名>.<ext> 截图(png/jpg/webp,≤2MB),可选但强烈建议
8
- - index.json 目录清单:{"panels":[{name,title,version,author,
9
- description,screenshot,size,updated}]}
10
-
11
- 接口要点(调研结论,2026-11):
12
- - Gitee v5:GET/POST/PUT https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}
13
- 新建 POST、更新 PUT(需带原文件 sha),content 一律 base64;access_token 放 body/查询。
14
- - GitHub:PUT https://api.github.com/repos/{owner}/{repo}/contents/{path}
15
- 新建不带 sha、更新带 sha;下载用 Accept: application/vnd.github.raw(>1MB 时
16
- contents 接口的 content 字段为空,必须走 raw 头)。
17
- - token 只存本机 config.json,API 响应一律脱敏;公开仓库浏览不需要 token。
18
-
19
- 离线/未配置/网络失败一律降级:列表返回空并带 error 提示,不影响本机市场。
20
- """
21
-
22
- from __future__ import annotations
23
-
24
- import base64
25
- import hashlib
26
- import json
27
- import os
28
- import time
29
- import urllib.error
30
- import urllib.request
31
- from pathlib import Path
32
-
33
- import brain
34
- import panels
35
-
36
-
37
- def _resolve_token(value: str) -> str:
38
- """token 支持 "env:变量名" 引用:不落盘明文,运行时从环境变量读取。
39
-
40
- 直接填的明文 token 仍兼容(不推荐;备份时会脱敏剥离,见 cli._sanitize_config_json)。
41
- """
42
- v = str(value or "").strip()
43
- if v.lower().startswith("env:"):
44
- return os.environ.get(v[4:].strip(), "").strip()
45
- return v
46
-
47
- # 截图白名单扩展名与大小上限(≤2MB),zip 上限沿用 panels.ZIP_MAX_TOTAL
48
- SHOT_WHITELIST = {".png", ".jpg", ".jpeg", ".webp"}
49
- SHOT_MAX = 2 * 1024 * 1024
50
- _CLOUD_TIMEOUT = 20 # 秒;Gitee 稳定,GitHub 国内不稳,超时即降级
51
-
52
- # 官方商店源兜底:用户没配置 panel.cloud 时,默认浏览灵枢官方镜像仓库的
53
- # index.json(面板/拓展都发布在这里)。用户配置了自己的仓库后以配置优先。
54
- DEFAULT_GITEE_REPO = "htmcwy_0/lingshu-skill"
55
- DEFAULT_GITHUB_REPO = "Q2667671398/lingshu-skill"
56
- DEFAULT_BRANCH = "main"
57
-
58
-
59
- # ---------------------------------------------------------------- 配置
60
-
61
- def _cfg(resolve_tokens: bool = True) -> dict:
62
- """读云端配置:panel.cloud.{gitee_repo,gitee_token,github_repo,github_token,branch}
63
- 未配置时回退官方商店源(gitee_repo / branch;GitHub 同理)。
64
- resolve_tokens=False 时保留 "env:VAR" 原样(set_config 回写用,防明文落盘)。"""
65
- try:
66
- c = brain.load_config().get("panel.cloud") or {}
67
- except Exception:
68
- c = {}
69
- c = dict(c) if isinstance(c, dict) else {}
70
- if not c.get("gitee_repo") and not c.get("github_repo"):
71
- c.setdefault("gitee_repo", DEFAULT_GITEE_REPO)
72
- c.setdefault("github_repo", DEFAULT_GITHUB_REPO)
73
- c.setdefault("branch", DEFAULT_BRANCH)
74
- # token 环境变量引用在读取侧解析,落盘的可以是 "env:VAR" 而非明文
75
- if resolve_tokens:
76
- for _k in ("gitee_token", "github_token"):
77
- if c.get(_k):
78
- c[_k] = _resolve_token(c[_k])
79
- return c
80
-
81
-
82
- def set_config(gitee_repo: str = "", gitee_token: str = "",
83
- github_repo: str = "", github_token: str = "",
84
- branch: str = "") -> dict:
85
- """保存云端配置(空串=清除该项)。token 属敏感信息:写 config.json 前校验格式;
86
- 填 "env:变量名" 则不落盘明文,运行时从环境变量读取。"""
87
- c = _cfg(resolve_tokens=False)
88
- if gitee_repo:
89
- if gitee_repo.count("/") != 1:
90
- raise ValueError("Gitee 仓库要填 owner/repo 形式,例如 yourname/lingshu-panels")
91
- c["gitee_repo"] = gitee_repo.strip()
92
- else:
93
- c.pop("gitee_repo", None)
94
- if gitee_token:
95
- c["gitee_token"] = gitee_token.strip()
96
- else:
97
- c.pop("gitee_token", None)
98
- if github_repo:
99
- if github_repo.count("/") != 1:
100
- raise ValueError("GitHub 仓库要填 owner/repo 形式")
101
- c["github_repo"] = github_repo.strip()
102
- else:
103
- c.pop("github_repo", None)
104
- if github_token:
105
- c["github_token"] = github_token.strip()
106
- else:
107
- c.pop("github_token", None)
108
- if branch:
109
- c["branch"] = branch.strip()
110
- with brain._locked(brain.HOME / "config.json"):
111
- full = brain.load_config()
112
- full["panel.cloud"] = c
113
- brain.atomic_json(brain.HOME / "config.json", full)
114
- return status()
115
-
116
-
117
- def status() -> dict:
118
- """云端配置状态(token 脱敏:只露前 4 位,让用户能认出是哪个 token)。
119
- browse 用默认官方源兜底(未配置也能逛商店);publish 必须显式配置 token。"""
120
- c = _cfg()
121
- user_cloud = brain.load_config().get("panel.cloud") or {}
122
- user_repo = bool(user_cloud.get("gitee_repo"))
123
-
124
- def mask(t: str) -> str:
125
- t = str(t or "")
126
- if t.lower().startswith("env:"):
127
- return t # 环境变量引用不含密文,原样展示便于辨认
128
- return (t[:4] + "****") if t else ""
129
-
130
- return {
131
- "gitee_repo": c.get("gitee_repo", ""),
132
- "gitee_token_mask": mask(user_cloud.get("gitee_token", "")),
133
- "github_repo": c.get("github_repo", ""),
134
- "github_token_mask": mask(user_cloud.get("github_token", "")),
135
- "branch": c.get("branch", "master"),
136
- "gitee_ready": user_repo, # 用户显式配置了自己的 Gitee 仓库
137
- "browse_ready": bool(c.get("gitee_repo") or c.get("github_repo")), # 能逛商店(含官方兜底源)
138
- "using_default_source": not user_repo, # 浏览的是官方兜底源还是自己的配置
139
- "publish_ready": bool(user_cloud.get("gitee_repo") and user_cloud.get("gitee_token")),
140
- }
141
-
142
-
143
- # ---------------------------------------------------------------- HTTP 底座
144
-
145
- def _http(method: str, url: str, *, token: str = "", headers: dict | None = None,
146
- body: bytes | None = None) -> bytes:
147
- """一次 HTTP 请求 → 响应字节。非 2xx 抛 RuntimeError(带状态码与响应摘要)。"""
148
- h = {"User-Agent": "lingshu-panel-market/1.0"}
149
- if token:
150
- h["Authorization"] = f"token {token}"
151
- if headers:
152
- h.update(headers)
153
- req = urllib.request.Request(url, data=body, headers=h, method=method)
154
- try:
155
- with urllib.request.urlopen(req, timeout=_CLOUD_TIMEOUT) as resp:
156
- return resp.read()
157
- except urllib.error.HTTPError as exc:
158
- detail = ""
159
- try:
160
- detail = exc.read()[:200].decode("utf-8", "replace")
161
- except Exception:
162
- pass
163
- raise RuntimeError(f"HTTP {exc.code}:{detail or exc.reason}") from exc
164
- except (urllib.error.URLError, OSError, TimeoutError) as exc:
165
- raise RuntimeError(f"网络请求失败:{exc}") from exc
166
-
167
-
168
- def _gitee_get(repo: str, path: str, token: str, branch: str) -> bytes | None:
169
- """Gitee 取单文件原始字节(contents 接口 → base64 解码)。不存在 → None。"""
170
- from urllib.parse import quote
171
- url = (f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}"
172
- f"?ref={quote(branch)}")
173
- if token:
174
- url += f"&access_token={quote(token)}"
175
- try:
176
- raw = _http("GET", url)
177
- except RuntimeError as exc:
178
- if "HTTP 404" in str(exc):
179
- return None
180
- # API 匿名限流(403)等场景:公开仓库退回 raw 页面直连(不走 contents API 配额)
181
- try:
182
- return _http("GET", f"https://gitee.com/{repo}/raw/{branch}/{quote(path)}",
183
- token=token)
184
- except RuntimeError:
185
- raise exc
186
- data = json.loads(raw.decode("utf-8"))
187
- if data.get("encoding") == "base64" and data.get("content"):
188
- return base64.b64decode(data["content"])
189
- # Gitee 大文件 encoding 可能是 none:退回 raw 页面下载
190
- return _http("GET", f"https://gitee.com/{repo}/raw/{branch}/{quote(path)}",
191
- token=token)
192
-
193
-
194
- def _commit_author(c: dict) -> dict | None:
195
- """从配置取自定义 commit 作者(author_name/author_email)。
196
-
197
- 未配置时返回 None——远端 API 默认用 token 所属账号作为提交者。
198
- """
199
- name = str(c.get("author_name", "")).strip()
200
- email = str(c.get("author_email", "")).strip()
201
- if not name:
202
- return None
203
- return {"name": name, "email": email or "lingshu@local"}
204
-
205
-
206
- def _gitee_put(repo: str, path: str, token: str, branch: str,
207
- content: bytes, message: str,
208
- author: dict | None = None) -> None:
209
- """Gitee 新建/更新单文件:先探 sha,有则 PUT 更新,无则 POST 新建。"""
210
- from urllib.parse import quote
211
- b64 = base64.b64encode(content).decode("ascii")
212
- payload = {"access_token": token, "content": b64, "branch": branch,
213
- "message": message}
214
- if author:
215
- payload["author_name"] = author["name"]
216
- payload["author_email"] = author["email"]
217
- payload["committer_name"] = author["name"]
218
- payload["committer_email"] = author["email"]
219
- old = _gitee_get(repo, path, token, branch)
220
- if old is not None:
221
- # 拿 sha 需要再查一次(_gitee_get 返回的是内容本身),单独请求元数据
222
- url = (f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}"
223
- f"?ref={quote(branch)}")
224
- if token:
225
- url += f"&access_token={quote(token)}"
226
- sha = json.loads(_http("GET", url).decode("utf-8")).get("sha")
227
- payload["sha"] = sha
228
- _http("PUT", f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}",
229
- headers={"Content-Type": "application/json"},
230
- body=json.dumps(payload).encode("utf-8"))
231
- else:
232
- _http("POST", f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}",
233
- headers={"Content-Type": "application/json"},
234
- body=json.dumps(payload).encode("utf-8"))
235
-
236
-
237
- def _github_put(repo: str, path: str, token: str, branch: str,
238
- content: bytes, message: str,
239
- author: dict | None = None) -> None:
240
- """GitHub 新建/更新单文件(contents API:不带 sha=新建,带 sha=更新)。"""
241
- from urllib.parse import quote
242
- b64 = base64.b64encode(content).decode("ascii")
243
- payload = {"content": b64, "message": message, "branch": branch}
244
- if author:
245
- payload["author"] = {"name": author["name"], "email": author["email"]}
246
- payload["committer"] = {"name": author["name"], "email": author["email"]}
247
- url = f"https://api.github.com/repos/{repo}/contents/{quote(path)}"
248
- # 先探测是否已存在(拿 sha);404/网络抖动都按"新建"处理
249
- try:
250
- meta = json.loads(_http("GET", url + f"?ref={quote(branch)}",
251
- token=token).decode("utf-8"))
252
- payload["sha"] = meta.get("sha")
253
- except RuntimeError:
254
- pass
255
- _http("PUT", url, headers={"Content-Type": "application/json"},
256
- body=json.dumps(payload).encode("utf-8"))
257
-
258
-
259
- def _github_get(repo: str, path: str, token: str, branch: str) -> bytes | None:
260
- """GitHub 取单文件原始字节(Accept raw,>1MB 文件也直接返回二进制)。"""
261
- from urllib.parse import quote
262
- url = f"https://api.github.com/repos/{repo}/contents/{quote(path)}?ref={quote(branch)}"
263
- try:
264
- return _http("GET", url, token=token,
265
- headers={"Accept": "application/vnd.github.raw"})
266
- except RuntimeError as exc:
267
- if "HTTP 404" in str(exc):
268
- return None
269
- raise
270
-
271
-
272
- # ---------------------------------------------------------------- 读取(浏览/下载)
273
-
274
- def _repo_list(repo: str, branch: str, getter) -> dict:
275
- """拉 index.json 并解析;文件不存在 → 空市场,网络错 → 抛错由上层降级。
276
-
277
- index.json 结构:{"panels": [...], "extensions": [...]}(extensions 可缺省)。
278
- """
279
- raw = getter(repo, "index.json", branch)
280
- if raw is None:
281
- return {"panels": [], "extensions": []}
282
- data = json.loads(raw.decode("utf-8"))
283
- if isinstance(data, dict):
284
- return {
285
- "panels": data.get("panels") if isinstance(data.get("panels"), list) else [],
286
- "extensions": data.get("extensions") if isinstance(data.get("extensions"), list) else [],
287
- }
288
- return {"panels": [], "extensions": []}
289
-
290
-
291
- def cloud_list(force: bool = False) -> dict:
292
- """GET /api/panels/cloud 的返回体:云端目录清单 + 配置状态。
293
-
294
- 优先 Gitee;失败再试 GitHub;都失败 → 返回 error 与提示,前端仍可用本机市场。
295
- 60 秒内存缓存(force=True 强制刷新),避免每次打开标签页都打 API。
296
- """
297
- global _CACHE
298
- c = _cfg()
299
- st = status()
300
- if not force and _CACHE and time.time() - _CACHE[0] < 60:
301
- return {**_CACHE[1], "status": st, "cached": True}
302
- gitee_repo = c.get("gitee_repo", "")
303
- gh_repo = c.get("github_repo", "")
304
- branch = c.get("branch", "master")
305
- gt, gh = c.get("gitee_token", ""), c.get("github_token", "")
306
- errors: list[str] = []
307
- items: dict = {}
308
- if gitee_repo:
309
- try:
310
- items = _repo_list(gitee_repo, branch,
311
- lambda r, p, b: _gitee_get(r, p, gt, b))
312
- except Exception as exc: # noqa: BLE001 —— 网络失败降级,不让市场页挂掉
313
- errors.append(f"Gitee:{exc}")
314
- if not items.get("panels") and gh_repo:
315
- try:
316
- items = _repo_list(gh_repo, branch,
317
- lambda r, p, b: _github_get(r, p, gh, b))
318
- except Exception as exc: # noqa: BLE001
319
- errors.append(f"GitHub:{exc}")
320
- errors = [e for e in errors if e]
321
- panels = items.get("panels", [])
322
- exts = items.get("extensions", [])
323
- out = {"panels": panels, "extensions": exts, "status": st, "errors": errors,
324
- "offline": bool(errors) and not panels and not exts}
325
- if panels or exts:
326
- _CACHE = (time.time(), out)
327
- return out
328
-
329
-
330
- _CACHE: tuple[float, dict] | None = (0.0, {})
331
-
332
-
333
- def cloud_download(name: str) -> dict:
334
- """从云端下载面板 zip → 存进本机市场目录(当离线缓存)→ 复用 install 校验落位。"""
335
- # 落盘前统一过 _safe_name(install 内有校验,但 zip 落盘在 install 之前)
336
- if not _safe_name(name):
337
- raise ValueError(f"非法面板名:{name!r}")
338
- raw = _fetch(f"panels/{name}.zip", name)
339
- _verify_sha256(name, raw) # 清单带 sha256 字段时校验,不匹配拒绝安装
340
- zpath = panels.market_dir() / f"{name}.zip"
341
- brain.atomic_bytes(zpath, raw)
342
- return panels.install(name)
343
-
344
-
345
- def _verify_sha256(name: str, raw: bytes, kind_key: str = "panels") -> None:
346
- """下载的 zip 必须与云端 index.json 清单里的 sha256 比对,否则拒绝安装。
347
-
348
- fail-closed:清单拉取失败、清单无此条目、条目缺 sha256,一律拒绝。
349
- 自建源也要提供带 sha256 的 index.json(见 docs/panel-api.md)。
350
-
351
- kind_key:`panels`(面板包)/ `extensions`(拓展包)。两种包都必须校验——
352
- 拓展解压即可用、权限等同插件,不校验等于给远程任意代码开后门。
353
- """
354
- label = "面板" if kind_key == "panels" else "拓展"
355
- try:
356
- items = cloud_list(force=False).get(kind_key, [])
357
- except Exception as exc: # noqa: BLE001 —— 统一转成拒绝安装的 ValueError
358
- raise ValueError(f"{label} {name} 的云端校验清单获取失败({exc}),已拒绝安装") from exc
359
- id_key = "id" if kind_key == "extensions" else "name"
360
- entry = next((p for p in items if p.get(id_key) == name), None)
361
- if not entry:
362
- raise ValueError(f"{label} {name} 不在云端清单中,已拒绝安装")
363
- if not entry.get("sha256"):
364
- raise ValueError(f"{label} {name} 的清单条目缺少 sha256,已拒绝安装")
365
- if hashlib.sha256(raw).hexdigest().lower() != str(entry["sha256"]).lower():
366
- raise ValueError(f"{label} {name} 下载校验失败(sha256 不匹配),已拒绝安装")
367
-
368
-
369
- def cloud_extension_download(ext_id: str) -> dict:
370
- """从云端下载拓展 zip(extensions/<id>.zip)→ 解压到拓展已安装目录。
371
-
372
- 与面板下载分开:面板走 panels.install(有 manifest 校验),
373
- 拓展是宿主适配插件目录,解压即用,只做路径安全校验。
374
- """
375
- # 落盘前统一过 _safe_name:拒绝 `..`、路径分隔符、Windows 盘符冒号(防路径穿越)
376
- if not _safe_name(ext_id):
377
- raise ValueError(f"非法拓展名:{ext_id!r}")
378
- raw = _fetch(f"extensions/{ext_id}.zip", ext_id)
379
- # 拓展也是"解压即用"的可执行代码,必须像面板包一样校验 sha256(fail-closed)
380
- _verify_sha256(ext_id, raw, kind_key="extensions")
381
- import io
382
- import zipfile
383
-
384
- import panels # noqa: PLC0415 —— 校验常量在 panels 里,函数内局部引入
385
- root = brain.HOME / "extensions" / "installed"
386
- root.mkdir(parents=True, exist_ok=True)
387
- dst = root / ext_id
388
- if dst.exists():
389
- raise FileExistsError("该拓展已安装,请先删除 extensions/installed 下同名目录")
390
- with zipfile.ZipFile(io.BytesIO(raw)) as z:
391
- names = z.namelist()
392
- if len(names) > panels.ZIP_MAX_FILES:
393
- raise ValueError("拓展包文件数超限")
394
- total = sum(i.file_size for i in z.infolist())
395
- if total > panels.ZIP_MAX_TOTAL:
396
- raise ValueError("拓展包超过 50MB")
397
- dst_real = dst.resolve()
398
- for n in names: # 防 zip 路径逃逸(../ 绝对路径 + 解析后必须仍在目标目录内)
399
- if n.startswith("/") or ".." in Path(n).parts:
400
- raise ValueError("拓展包含非法路径")
401
- if not (dst_real / n).resolve().is_relative_to(dst_real):
402
- raise ValueError(f"拓展包路径逃逸:{n!r}")
403
- z.extractall(dst)
404
- brain.log_event("panel", f"云端下载拓展 {ext_id} → {dst}")
405
- return {"ok": True, "id": ext_id, "dir": str(dst)}
406
-
407
-
408
- def _fetch(path: str, label: str) -> bytes:
409
- """按路径从云端拉文件字节:先 Gitee 后 GitHub,都失败抛 ValueError。"""
410
- c = _cfg()
411
- branch = c.get("branch", "master")
412
- raw = None
413
- errs = []
414
- if c.get("gitee_repo"):
415
- try:
416
- raw = _gitee_get(c["gitee_repo"], path, c.get("gitee_token", ""), branch)
417
- except Exception as exc: # noqa: BLE001
418
- errs.append(f"Gitee:{exc}")
419
- if raw is None and c.get("github_repo"):
420
- try:
421
- raw = _github_get(c["github_repo"], path, c.get("github_token", ""), branch)
422
- except Exception as exc: # noqa: BLE001
423
- errs.append(f"GitHub:{exc}")
424
- if raw is None:
425
- raise ValueError(f"云端没有该文件或下载失败({label}):{';'.join(errs) or path}")
426
- return raw
427
-
428
-
429
- def _safe_name(name: str) -> bool:
430
- """拓展 id/面板名安全校验:复用 panels._NAME_RE(防路径分隔符与越界)。
431
-
432
- _NAME_RE 白名单本身不含冒号/斜杠,天然拒绝 `..`、路径分隔符与
433
- Windows 盘符冒号(`C:`);这里显式再挡一层,与 panels._extract_zip_safe
434
- 的三重防护口径保持一致。
435
- """
436
- if not name or name.startswith("/") or "\\" in name or ".." in name \
437
- or (len(name) > 1 and name[1] == ":"):
438
- return False
439
- return bool(panels._NAME_RE.match(name))
440
-
441
-
442
- def cloud_shot(name: str, ext: str) -> bytes:
443
- """取云端截图字节(前端 <img> 直连本机代理端点,避免跨域/混合内容问题)。"""
444
- if ext not in SHOT_WHITELIST:
445
- raise ValueError("截图扩展名不支持")
446
- c = _cfg()
447
- branch = c.get("branch", "master")
448
- path = f"shots/{name}{ext}"
449
- raw = None
450
- if c.get("gitee_repo"):
451
- try:
452
- raw = _gitee_get(c["gitee_repo"], path, c.get("gitee_token", ""), branch)
453
- except Exception: # noqa: BLE001
454
- raw = None
455
- if raw is None and c.get("github_repo"):
456
- try:
457
- raw = _github_get(c["github_repo"], path, c.get("github_token", ""), branch)
458
- except Exception: # noqa: BLE001
459
- raw = None
460
- if raw is None:
461
- raise FileNotFoundError("云端没有该截图")
462
- return raw
463
-
464
-
465
- # ---------------------------------------------------------------- 发布
466
-
467
- def cloud_publish(name: str, screenshot: bytes | None = None,
468
- shot_ext: str = ".png") -> dict:
469
- """把已安装面板发布到云端(Gitee 必配;GitHub 配了就同步镜像)。
470
-
471
- 流程:校验 manifest → 打 zip → 传 panels/<name>.zip →(可选)传截图 →
472
- 读 index.json 合并本面板条目后回写。任一远端失败则该远端报错,另一端照常。
473
- """
474
- import io
475
- import zipfile
476
-
477
- import panels
478
- src = panels._panel_path(panels.panels_dir(), name)
479
- if not src.exists():
480
- raise ValueError(f"已安装面板不存在:{name}")
481
- mf = panels._load_manifest(src) # 损坏面板不允许发布
482
- if screenshot is not None:
483
- if len(screenshot) > SHOT_MAX:
484
- raise ValueError("截图超过 2MB,请压缩后再上传")
485
- if shot_ext not in SHOT_WHITELIST:
486
- raise ValueError("截图只支持 png/jpg/webp")
487
- # 打 zip:内存打包(总量受 ZIP_MAX_TOTAL 保护,超限抛 ValueError)
488
- buf = io.BytesIO()
489
- total = 0
490
- with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
491
- for f in sorted(src.rglob("*")):
492
- if f.is_file():
493
- rel = f.relative_to(src).as_posix()
494
- if rel in ("panel.json",) or not rel.startswith("."):
495
- total += f.stat().st_size
496
- if total > panels.ZIP_MAX_TOTAL:
497
- raise ValueError("面板超过 50MB,不适合云端分发")
498
- z.write(f, rel)
499
- zbytes = buf.getvalue()
500
- now = time.strftime("%Y-%m-%d %H:%M", time.localtime())
501
- entry = {"name": mf["name"], "title": mf["title"], "version": mf["version"],
502
- "author": mf.get("author", ""), "description": mf.get("description", ""),
503
- "screenshot": (f"{name}{shot_ext}" if screenshot is not None else ""),
504
- "size": len(zbytes), "sha256": hashlib.sha256(zbytes).hexdigest(), "updated": now}
505
- c = _cfg()
506
- branch = c.get("branch", "master")
507
- author = _commit_author(c)
508
- msg = f"lingshu: publish panel {name} v{mf['version']}"
509
- pushed, errors = [], []
510
- if c.get("gitee_repo") and c.get("gitee_token"):
511
- try:
512
- _push_one("gitee", c["gitee_repo"], c["gitee_token"], branch,
513
- name, zbytes, screenshot, shot_ext, entry, msg,
514
- kind_key="panels", author=author)
515
- pushed.append("Gitee")
516
- except Exception as exc: # noqa: BLE001
517
- errors.append(f"Gitee:{exc}")
518
- else:
519
- errors.append("Gitee 未配置仓库或 token(发布需要 Gitee)")
520
- if c.get("github_repo") and c.get("github_token"):
521
- try:
522
- _push_one("github", c["github_repo"], c["github_token"], branch,
523
- name, zbytes, screenshot, shot_ext, entry, msg,
524
- kind_key="panels", author=author)
525
- pushed.append("GitHub")
526
- except Exception as exc: # noqa: BLE001
527
- errors.append(f"GitHub:{exc}")
528
- global _CACHE
529
- _CACHE = None # 发布后清缓存,下次列表强制刷新
530
- if not pushed:
531
- raise RuntimeError(f"发布失败:{';'.join(errors)}")
532
- return {"ok": True, "pushed": pushed,
533
- "errors": errors, "entry": entry}
534
-
535
-
536
- def cloud_extension_publish(ext_id: str) -> dict:
537
- """把拓展已安装目录发布到云端 extensions/<id>.zip + index.json 的 extensions 数组。
538
-
539
- 结构与面板发布平行:同一个 index.json,两个子清单互不干扰。
540
- """
541
- import io
542
- import zipfile
543
-
544
- src = brain.HOME / "extensions" / "installed" / ext_id
545
- if not src.is_dir() or not _safe_name(ext_id):
546
- raise ValueError(f"已安装拓展不存在或 id 不合法:{ext_id}")
547
- meta = panels._extension_meta(src) if hasattr(panels, "_extension_meta") else {}
548
- buf = io.BytesIO()
549
- total = 0
550
- with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
551
- for f in sorted(src.rglob("*")):
552
- if f.is_file() and not f.name.startswith("."):
553
- total += f.stat().st_size
554
- if total > panels.ZIP_MAX_TOTAL:
555
- raise ValueError("拓展超过 50MB,不适合云端分发")
556
- z.write(f, f.relative_to(src).as_posix())
557
- zbytes = buf.getvalue()
558
- now = time.strftime("%Y-%m-%d %H:%M", time.localtime())
559
- entry = {"id": ext_id, "title": ext_id,
560
- "version": meta.get("version", "0.0.0"),
561
- "author": meta.get("author", ""),
562
- "size": len(zbytes), "sha256": hashlib.sha256(zbytes).hexdigest(), "updated": now}
563
- c = _cfg()
564
- branch = c.get("branch", "master")
565
- author = _commit_author(c)
566
- msg = f"lingshu: publish extension {ext_id} v{entry['version']}"
567
- pushed, errors = [], []
568
- for kind in ("gitee", "github"):
569
- repo = c.get(f"{kind}_repo", "")
570
- token = c.get(f"{kind}_token", "")
571
- if repo and token:
572
- try:
573
- _push_one(kind, repo, token, branch, ext_id, zbytes,
574
- None, ".png", entry, msg, kind_key="extensions",
575
- author=author)
576
- pushed.append("Gitee" if kind == "gitee" else "GitHub")
577
- except Exception as exc: # noqa: BLE001
578
- errors.append(f"{'Gitee' if kind == 'gitee' else 'GitHub'}:{exc}")
579
- global _CACHE
580
- _CACHE = None
581
- if not pushed:
582
- raise RuntimeError(f"发布失败:{';'.join(errors)}")
583
- return {"ok": True, "pushed": pushed, "errors": errors, "entry": entry}
584
-
585
-
586
- def _push_one(kind: str, repo: str, token: str, branch: str, name: str,
587
- zbytes: bytes, shot: bytes | None, shot_ext: str,
588
- entry: dict, msg: str, kind_key: str = "panels",
589
- author: dict | None = None) -> None:
590
- """向一个远端推 zip + 截图 + index.json 条目。
591
-
592
- kind_key 决定子目录与清单键:panels → panels/xxx.zip + index.json.panels,
593
- extensions → extensions/xxx.zip + index.json.extensions(同一份 index.json)。
594
- """
595
- put = _gitee_put if kind == "gitee" else _github_put
596
- get = _gitee_get if kind == "gitee" else _github_get
597
- put(repo, f"{kind_key}/{name}.zip", token, branch, zbytes, msg, author)
598
- if shot is not None:
599
- put(repo, f"shots/{name}{shot_ext}", token, branch, shot, msg, author)
600
- # index.json 合并回写:读旧清单 → 覆盖同名条目 → 写回(并发竞争可接受,个人市场)
601
- #
602
- # ⚠ fail-closed:**只有"清单确实不存在"才可以新建空清单**。
603
- # 若清单拉到了但解析失败(被改坏、传输截断、编码问题),旧代码会重建空清单再回写,
604
- # 等于**把整个市场目录清空**,只留刚发布这一条——这是不可接受的静默数据丢失。
605
- # 现在:解析失败一律抛错中止(zip 已经传上去了,只是清单不动,仍是安全状态)。
606
- raw = get(repo, "index.json", token, branch)
607
- if raw:
608
- try:
609
- data = json.loads(raw.decode("utf-8"))
610
- except Exception as exc: # noqa: BLE001
611
- raise ValueError(
612
- f"云端 index.json 解析失败,已中止清单回写(避免清空市场目录):{exc}") from exc
613
- if not isinstance(data, dict):
614
- raise ValueError("云端 index.json 结构异常(不是对象),已中止清单回写")
615
- else:
616
- # 清单不存在 = 首次发布,允许新建
617
- data = {"panels": [], "extensions": []}
618
- # key 名:面板条目按 name 匹配,拓展条目按 id 匹配
619
- id_key = "id" if kind_key == "extensions" else "name"
620
- items = [p for p in (data.get(kind_key) or []) if p.get(id_key) != name]
621
- items.append(entry)
622
- items.sort(key=lambda p: str(p.get("updated", "")), reverse=True)
623
- data[kind_key] = items
624
- data.setdefault("panels", data.get("panels", []))
625
- put(repo, "index.json", token, branch,
626
- json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8"),
627
- msg, author)
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢 云端面板市场:Gitee(主)/ GitHub(镜像)仓库当云端,纯标准库 urllib。
4
+
5
+ 云端约定(仓库布局):
6
+ - panels/<面板名>.zip 面板安装包(≤50MB,安装时解压校验 manifest)
7
+ - shots/<面板名>.<ext> 截图(png/jpg/webp,≤2MB),可选但强烈建议
8
+ - index.json 目录清单:{"panels":[{name,title,version,author,
9
+ description,screenshot,size,updated}]}
10
+
11
+ 接口要点(调研结论,2026-11):
12
+ - Gitee v5:GET/POST/PUT https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}
13
+ 新建 POST、更新 PUT(需带原文件 sha),content 一律 base64;access_token 放 body/查询。
14
+ - GitHub:PUT https://api.github.com/repos/{owner}/{repo}/contents/{path}
15
+ 新建不带 sha、更新带 sha;下载用 Accept: application/vnd.github.raw(>1MB 时
16
+ contents 接口的 content 字段为空,必须走 raw 头)。
17
+ - token 只存本机 config.json,API 响应一律脱敏;公开仓库浏览不需要 token。
18
+
19
+ 离线/未配置/网络失败一律降级:列表返回空并带 error 提示,不影响本机市场。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import base64
25
+ import hashlib
26
+ import json
27
+ import os
28
+ import time
29
+ import urllib.error
30
+ import urllib.request
31
+ from pathlib import Path
32
+
33
+ import brain
34
+ import panels
35
+
36
+
37
+ def _resolve_token(value: str) -> str:
38
+ """token 支持 "env:变量名" 引用:不落盘明文,运行时从环境变量读取。
39
+
40
+ 直接填的明文 token 仍兼容(不推荐;备份时会脱敏剥离,见 cli._sanitize_config_json)。
41
+ """
42
+ v = str(value or "").strip()
43
+ if v.lower().startswith("env:"):
44
+ return os.environ.get(v[4:].strip(), "").strip()
45
+ return v
46
+
47
+ # 截图白名单扩展名与大小上限(≤2MB),zip 上限沿用 panels.ZIP_MAX_TOTAL
48
+ SHOT_WHITELIST = {".png", ".jpg", ".jpeg", ".webp"}
49
+ SHOT_MAX = 2 * 1024 * 1024
50
+ _CLOUD_TIMEOUT = 20 # 秒;Gitee 稳定,GitHub 国内不稳,超时即降级
51
+
52
+ # 官方商店源兜底:用户没配置 panel.cloud 时,默认浏览灵枢官方镜像仓库的
53
+ # index.json(面板/拓展都发布在这里)。用户配置了自己的仓库后以配置优先。
54
+ DEFAULT_GITEE_REPO = "htmcwy_0/lingshu-skill"
55
+ DEFAULT_GITHUB_REPO = "Q2667671398/lingshu-skill"
56
+ DEFAULT_BRANCH = "main"
57
+
58
+
59
+ # ---------------------------------------------------------------- 配置
60
+
61
+ def _cfg(resolve_tokens: bool = True) -> dict:
62
+ """读云端配置:panel.cloud.{gitee_repo,gitee_token,github_repo,github_token,branch}
63
+ 未配置时回退官方商店源(gitee_repo / branch;GitHub 同理)。
64
+ resolve_tokens=False 时保留 "env:VAR" 原样(set_config 回写用,防明文落盘)。"""
65
+ try:
66
+ c = brain.load_config().get("panel.cloud") or {}
67
+ except Exception:
68
+ c = {}
69
+ c = dict(c) if isinstance(c, dict) else {}
70
+ if not c.get("gitee_repo") and not c.get("github_repo"):
71
+ c.setdefault("gitee_repo", DEFAULT_GITEE_REPO)
72
+ c.setdefault("github_repo", DEFAULT_GITHUB_REPO)
73
+ c.setdefault("branch", DEFAULT_BRANCH)
74
+ # token 环境变量引用在读取侧解析,落盘的可以是 "env:VAR" 而非明文
75
+ if resolve_tokens:
76
+ for _k in ("gitee_token", "github_token"):
77
+ if c.get(_k):
78
+ c[_k] = _resolve_token(c[_k])
79
+ return c
80
+
81
+
82
+ def set_config(gitee_repo: str = "", gitee_token: str = "",
83
+ github_repo: str = "", github_token: str = "",
84
+ branch: str = "") -> dict:
85
+ """保存云端配置(空串=清除该项)。token 属敏感信息:写 config.json 前校验格式;
86
+ 填 "env:变量名" 则不落盘明文,运行时从环境变量读取。"""
87
+ c = _cfg(resolve_tokens=False)
88
+ if gitee_repo:
89
+ if gitee_repo.count("/") != 1:
90
+ raise ValueError("Gitee 仓库要填 owner/repo 形式,例如 yourname/lingshu-panels")
91
+ c["gitee_repo"] = gitee_repo.strip()
92
+ else:
93
+ c.pop("gitee_repo", None)
94
+ if gitee_token:
95
+ c["gitee_token"] = gitee_token.strip()
96
+ else:
97
+ c.pop("gitee_token", None)
98
+ if github_repo:
99
+ if github_repo.count("/") != 1:
100
+ raise ValueError("GitHub 仓库要填 owner/repo 形式")
101
+ c["github_repo"] = github_repo.strip()
102
+ else:
103
+ c.pop("github_repo", None)
104
+ if github_token:
105
+ c["github_token"] = github_token.strip()
106
+ else:
107
+ c.pop("github_token", None)
108
+ # LS-065(v5.67):清除云配置时同时重置 branch!
109
+ # 旧代码只在 branch 非空时设置,清除时旧 branch 残留——自定义 dev 分支会污染官方兜底源。
110
+ if branch:
111
+ c["branch"] = branch.strip()
112
+ else:
113
+ c.pop("branch", None)
114
+ with brain._locked(brain.HOME / "config.json"):
115
+ full = brain.load_config()
116
+ full["panel.cloud"] = c
117
+ brain.atomic_json(brain.HOME / "config.json", full)
118
+ return status()
119
+
120
+
121
+ def status() -> dict:
122
+ """云端配置状态。
123
+ LS-063(v5.67):status 覆盖 GitHub 发布能力!
124
+ 旧代码只检查 gitee_repo,仅配置 GitHub 时误显示不可发布。
125
+ """
126
+ c = _cfg()
127
+ user_cloud = brain.load_config().get("panel.cloud") or {}
128
+ user_repo = bool(user_cloud.get("gitee_repo") or user_cloud.get("github_repo"))
129
+
130
+ def mask(t: str) -> str:
131
+ t = str(t or "")
132
+ if t.lower().startswith("env:"):
133
+ return t # 环境变量引用不含密文,原样展示便于辨认
134
+ return (t[:4] + "****") if t else ""
135
+
136
+ return {
137
+ "gitee_repo": c.get("gitee_repo", ""),
138
+ "gitee_token_mask": mask(user_cloud.get("gitee_token", "")),
139
+ "github_repo": c.get("github_repo", ""),
140
+ "github_token_mask": mask(user_cloud.get("github_token", "")),
141
+ "branch": c.get("branch", "master"),
142
+ "gitee_ready": user_repo, # 用户显式配置了自己的 Gitee 仓库
143
+ "browse_ready": bool(c.get("gitee_repo") or c.get("github_repo")), # 能逛商店(含官方兜底源)
144
+ "using_default_source": not user_repo, # 浏览的是官方兜底源还是自己的配置
145
+ "publish_ready": bool(user_cloud.get("gitee_repo") and user_cloud.get("gitee_token")),
146
+ }
147
+
148
+
149
+ # ---------------------------------------------------------------- HTTP 底座
150
+
151
+ def _http(method: str, url: str, *, token: str = "", headers: dict | None = None,
152
+ body: bytes | None = None) -> bytes:
153
+ """一次 HTTP 请求 → 响应字节。非 2xx 抛 RuntimeError(带状态码与响应摘要)。"""
154
+ h = {"User-Agent": "lingshu-panel-market/1.0"}
155
+ if token:
156
+ h["Authorization"] = f"token {token}"
157
+ if headers:
158
+ h.update(headers)
159
+ req = urllib.request.Request(url, data=body, headers=h, method=method)
160
+ try:
161
+ with urllib.request.urlopen(req, timeout=_CLOUD_TIMEOUT) as resp:
162
+ return resp.read()
163
+ except urllib.error.HTTPError as exc:
164
+ detail = ""
165
+ try:
166
+ detail = exc.read()[:200].decode("utf-8", "replace")
167
+ except Exception:
168
+ pass
169
+ raise RuntimeError(f"HTTP {exc.code}:{detail or exc.reason}") from exc
170
+ except (urllib.error.URLError, OSError, TimeoutError) as exc:
171
+ raise RuntimeError(f"网络请求失败:{exc}") from exc
172
+
173
+
174
+ def _gitee_get(repo: str, path: str, token: str, branch: str) -> bytes | None:
175
+ """Gitee 取单文件原始字节(contents 接口 → base64 解码)。不存在 → None。"""
176
+ from urllib.parse import quote
177
+ url = (f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}"
178
+ f"?ref={quote(branch)}")
179
+ if token:
180
+ url += f"&access_token={quote(token)}"
181
+ try:
182
+ raw = _http("GET", url)
183
+ except RuntimeError as exc:
184
+ if "HTTP 404" in str(exc):
185
+ return None
186
+ # API 匿名限流(403)等场景:公开仓库退回 raw 页面直连(不走 contents API 配额)
187
+ try:
188
+ return _http("GET", f"https://gitee.com/{repo}/raw/{branch}/{quote(path)}",
189
+ token=token)
190
+ except RuntimeError:
191
+ raise exc
192
+ data = json.loads(raw.decode("utf-8"))
193
+ if data.get("encoding") == "base64" and data.get("content"):
194
+ return base64.b64decode(data["content"])
195
+ # Gitee 大文件 encoding 可能是 none:退回 raw 页面下载
196
+ return _http("GET", f"https://gitee.com/{repo}/raw/{branch}/{quote(path)}",
197
+ token=token)
198
+
199
+
200
+ def _commit_author(c: dict) -> dict | None:
201
+ """从配置取自定义 commit 作者(author_name/author_email)。
202
+
203
+ 未配置时返回 None——远端 API 默认用 token 所属账号作为提交者。
204
+ """
205
+ name = str(c.get("author_name", "")).strip()
206
+ email = str(c.get("author_email", "")).strip()
207
+ if not name:
208
+ return None
209
+ return {"name": name, "email": email or "lingshu@local"}
210
+
211
+
212
+ def _gitee_put(repo: str, path: str, token: str, branch: str,
213
+ content: bytes, message: str,
214
+ author: dict | None = None) -> None:
215
+ """Gitee 新建/更新单文件:先探 sha,有则 PUT 更新,无则 POST 新建。"""
216
+ from urllib.parse import quote
217
+ b64 = base64.b64encode(content).decode("ascii")
218
+ payload = {"access_token": token, "content": b64, "branch": branch,
219
+ "message": message}
220
+ if author:
221
+ payload["author_name"] = author["name"]
222
+ payload["author_email"] = author["email"]
223
+ payload["committer_name"] = author["name"]
224
+ payload["committer_email"] = author["email"]
225
+ old = _gitee_get(repo, path, token, branch)
226
+ if old is not None:
227
+ # 拿 sha 需要再查一次(_gitee_get 返回的是内容本身),单独请求元数据
228
+ url = (f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}"
229
+ f"?ref={quote(branch)}")
230
+ if token:
231
+ url += f"&access_token={quote(token)}"
232
+ sha = json.loads(_http("GET", url).decode("utf-8")).get("sha")
233
+ payload["sha"] = sha
234
+ _http("PUT", f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}",
235
+ headers={"Content-Type": "application/json"},
236
+ body=json.dumps(payload).encode("utf-8"))
237
+ else:
238
+ _http("POST", f"https://gitee.com/api/v5/repos/{repo}/contents/{quote(path)}",
239
+ headers={"Content-Type": "application/json"},
240
+ body=json.dumps(payload).encode("utf-8"))
241
+
242
+
243
+ def _github_put(repo: str, path: str, token: str, branch: str,
244
+ content: bytes, message: str,
245
+ author: dict | None = None) -> None:
246
+ """GitHub 新建/更新单文件(contents API:不带 sha=新建,带 sha=更新)。"""
247
+ from urllib.parse import quote
248
+ b64 = base64.b64encode(content).decode("ascii")
249
+ payload = {"content": b64, "message": message, "branch": branch}
250
+ if author:
251
+ payload["author"] = {"name": author["name"], "email": author["email"]}
252
+ payload["committer"] = {"name": author["name"], "email": author["email"]}
253
+ url = f"https://api.github.com/repos/{repo}/contents/{quote(path)}"
254
+ # 先探测是否已存在(拿 sha);404/网络抖动都按"新建"处理
255
+ try:
256
+ meta = json.loads(_http("GET", url + f"?ref={quote(branch)}",
257
+ token=token).decode("utf-8"))
258
+ payload["sha"] = meta.get("sha")
259
+ except RuntimeError:
260
+ pass
261
+ _http("PUT", url, headers={"Content-Type": "application/json"},
262
+ body=json.dumps(payload).encode("utf-8"))
263
+
264
+
265
+ def _github_get(repo: str, path: str, token: str, branch: str) -> bytes | None:
266
+ """GitHub 取单文件原始字节(Accept raw,>1MB 文件也直接返回二进制)。"""
267
+ from urllib.parse import quote
268
+ url = f"https://api.github.com/repos/{repo}/contents/{quote(path)}?ref={quote(branch)}"
269
+ try:
270
+ return _http("GET", url, token=token,
271
+ headers={"Accept": "application/vnd.github.raw"})
272
+ except RuntimeError as exc:
273
+ if "HTTP 404" in str(exc):
274
+ return None
275
+ raise
276
+
277
+
278
+ # ---------------------------------------------------------------- 读取(浏览/下载)
279
+
280
+ def _repo_list(repo: str, branch: str, getter) -> dict:
281
+ """拉 index.json 并解析;文件不存在 → 空市场,网络错 → 抛错由上层降级。
282
+
283
+ index.json 结构:{"panels": [...], "extensions": [...]}(extensions 可缺省)。
284
+ """
285
+ raw = getter(repo, "index.json", branch)
286
+ if raw is None:
287
+ return {"panels": [], "extensions": []}
288
+ data = json.loads(raw.decode("utf-8"))
289
+ if isinstance(data, dict):
290
+ return {
291
+ "panels": data.get("panels") if isinstance(data.get("panels"), list) else [],
292
+ "extensions": data.get("extensions") if isinstance(data.get("extensions"), list) else [],
293
+ }
294
+ return {"panels": [], "extensions": []}
295
+
296
+
297
+ def cloud_list(force: bool = False) -> dict:
298
+ """GET /api/panels/cloud 的返回体:云端目录清单 + 配置状态。
299
+
300
+ 优先 Gitee;失败再试 GitHub;都失败 → 返回 error 与提示,前端仍可用本机市场。
301
+ 60 秒内存缓存(force=True 强制刷新),避免每次打开标签页都打 API。
302
+ """
303
+ global _CACHE
304
+ c = _cfg()
305
+ st = status()
306
+ # LS-064(v5.67):将云仓库身份纳入缓存键!
307
+ # 旧缓存只有时间戳——切换或保存配置(换仓库/分支/token)后,
308
+ # 60 秒内仍返回旧仓库的清单(缓存脏数据)。缓存键改为 (time, repo+branch+token_hash)。
309
+ gitee_repo = c.get("gitee_repo", "")
310
+ gh_repo = c.get("github_repo", "")
311
+ branch = c.get("branch", "master")
312
+ gt, gh = c.get("gitee_token", ""), c.get("github_token", "")
313
+ import hashlib as _hl
314
+ _repo_id = _hl.sha256(f"{gitee_repo}|{gh_repo}|{branch}".encode()).hexdigest()[:16]
315
+ if not force and _CACHE and _CACHE[0] == _repo_id and time.time() - _CACHE[1] < 60:
316
+ return {**_CACHE[2], "status": st, "cached": True}
317
+ gt, gh = c.get("gitee_token", ""), c.get("github_token", "")
318
+ errors: list[str] = []
319
+ items: dict = {}
320
+ if gitee_repo:
321
+ try:
322
+ items = _repo_list(gitee_repo, branch,
323
+ lambda r, p, b: _gitee_get(r, p, gt, b))
324
+ except Exception as exc: # noqa: BLE001 —— 网络失败降级,不让市场页挂掉
325
+ _hint = ""
326
+ _es = str(exc)
327
+ if "HTTP 403" in _es or "HTTP 429" in _es:
328
+ _hint = "(限流或 token 权限不足,请检查 token 或稍后重试)"
329
+ elif "HTTP 5" in _es or "connect" in _es.lower():
330
+ _hint = "(网络或服务端故障)"
331
+ errors.append(f"Gitee:{exc}{_hint}")
332
+ if not items.get("panels") and gh_repo:
333
+ try:
334
+ items = _repo_list(gh_repo, branch,
335
+ lambda r, p, b: _github_get(r, p, gh, b))
336
+ except Exception as exc: # noqa: BLE001
337
+ _hint = ""
338
+ _es = str(exc)
339
+ if "HTTP 403" in _es or "HTTP 429" in _es:
340
+ _hint = "(限流或 token 权限不足,请检查 token 或稍后重试)"
341
+ elif "HTTP 5" in _es or "connect" in _es.lower():
342
+ _hint = "(网络或服务端故障)"
343
+ errors.append(f"GitHub:{exc}{_hint}")
344
+ errors = [e for e in errors if e]
345
+ panels = items.get("panels", [])
346
+ exts = items.get("extensions", [])
347
+ out = {"panels": panels, "extensions": exts, "status": st, "errors": errors,
348
+ "offline": bool(errors) and not panels and not exts}
349
+ if panels or exts:
350
+ _CACHE = (_repo_id, time.time(), out)
351
+ return out
352
+
353
+
354
+ _CACHE: tuple[float, dict] | None = (0.0, {})
355
+
356
+
357
+ def cloud_download(name: str) -> dict:
358
+ """从云端下载面板 zip → 存进本机市场目录(当离线缓存)→ 复用 install 校验落位。"""
359
+ # 落盘前统一过 _safe_name(install 内有校验,但 zip 落盘在 install 之前)
360
+ if not _safe_name(name):
361
+ raise ValueError(f"非法面板名:{name!r}")
362
+ raw = _fetch(f"panels/{name}.zip", name)
363
+ _verify_sha256(name, raw) # 清单带 sha256 字段时校验,不匹配拒绝安装
364
+ zpath = panels.market_dir() / f"{name}.zip"
365
+ brain.atomic_bytes(zpath, raw)
366
+ return panels.install(name)
367
+
368
+
369
+ def _verify_sha256(name: str, raw: bytes, kind_key: str = "panels") -> None:
370
+ """下载的 zip 必须与云端 index.json 清单里的 sha256 比对,否则拒绝安装。
371
+
372
+ fail-closed:清单拉取失败、清单无此条目、条目缺 sha256,一律拒绝。
373
+ 自建源也要提供带 sha256 的 index.json(见 docs/panel-api.md)。
374
+
375
+ kind_key:`panels`(面板包)/ `extensions`(拓展包)。两种包都必须校验——
376
+ 拓展解压即可用、权限等同插件,不校验等于给远程任意代码开后门。
377
+ """
378
+ label = "面板" if kind_key == "panels" else "拓展"
379
+ try:
380
+ items = cloud_list(force=False).get(kind_key, [])
381
+ except Exception as exc: # noqa: BLE001 —— 统一转成拒绝安装的 ValueError
382
+ raise ValueError(f"{label} {name} 的云端校验清单获取失败({exc}),已拒绝安装") from exc
383
+ id_key = "id" if kind_key == "extensions" else "name"
384
+ entry = next((p for p in items if p.get(id_key) == name), None)
385
+ if not entry:
386
+ raise ValueError(f"{label} {name} 不在云端清单中,已拒绝安装")
387
+ if not entry.get("sha256"):
388
+ raise ValueError(f"{label} {name} 的清单条目缺少 sha256,已拒绝安装")
389
+ if hashlib.sha256(raw).hexdigest().lower() != str(entry["sha256"]).lower():
390
+ raise ValueError(f"{label} {name} 下载校验失败(sha256 不匹配),已拒绝安装")
391
+
392
+
393
+ def cloud_extension_download(ext_id: str) -> dict:
394
+ """从云端下载拓展 zip(extensions/<id>.zip)→ 解压到拓展已安装目录。
395
+
396
+ 与面板下载分开:面板走 panels.install(有 manifest 校验),
397
+ 拓展是宿主适配插件目录,解压即用,只做路径安全校验。
398
+ """
399
+ # 落盘前统一过 _safe_name:拒绝 `..`、路径分隔符、Windows 盘符冒号(防路径穿越)
400
+ if not _safe_name(ext_id):
401
+ raise ValueError(f"非法拓展名:{ext_id!r}")
402
+ raw = _fetch(f"extensions/{ext_id}.zip", ext_id)
403
+ # 拓展也是"解压即用"的可执行代码,必须像面板包一样校验 sha256(fail-closed)
404
+ _verify_sha256(ext_id, raw, kind_key="extensions")
405
+ import io
406
+ import zipfile
407
+
408
+ import panels # noqa: PLC0415 —— 校验常量在 panels 里,函数内局部引入
409
+ root = brain.HOME / "extensions" / "installed"
410
+ root.mkdir(parents=True, exist_ok=True)
411
+ dst = root / ext_id
412
+ if dst.exists():
413
+ raise FileExistsError("该拓展已安装,请先删除 extensions/installed 下同名目录")
414
+ with zipfile.ZipFile(io.BytesIO(raw)) as z:
415
+ names = z.namelist()
416
+ if len(names) > panels.ZIP_MAX_FILES:
417
+ raise ValueError("拓展包文件数超限")
418
+ total = sum(i.file_size for i in z.infolist())
419
+ if total > panels.ZIP_MAX_TOTAL:
420
+ raise ValueError("拓展包超过 50MB")
421
+ dst_real = dst.resolve()
422
+ for n in names: # 防 zip 路径逃逸(../ 绝对路径 + 解析后必须仍在目标目录内)
423
+ if n.startswith("/") or ".." in Path(n).parts:
424
+ raise ValueError("拓展包含非法路径")
425
+ if not (dst_real / n).resolve().is_relative_to(dst_real):
426
+ raise ValueError(f"拓展包路径逃逸:{n!r}")
427
+ z.extractall(dst)
428
+ brain.log_event("panel", f"云端下载拓展 {ext_id} → {dst}")
429
+ return {"ok": True, "id": ext_id, "dir": str(dst)}
430
+
431
+
432
+ def _fetch(path: str, label: str) -> bytes:
433
+ """按路径从云端拉文件字节:先 Gitee 后 GitHub,都失败抛 ValueError。"""
434
+ c = _cfg()
435
+ branch = c.get("branch", "master")
436
+ raw = None
437
+ errs = []
438
+ if c.get("gitee_repo"):
439
+ try:
440
+ raw = _gitee_get(c["gitee_repo"], path, c.get("gitee_token", ""), branch)
441
+ except Exception as exc: # noqa: BLE001
442
+ errs.append(f"Gitee:{exc}")
443
+ if raw is None and c.get("github_repo"):
444
+ try:
445
+ raw = _github_get(c["github_repo"], path, c.get("github_token", ""), branch)
446
+ except Exception as exc: # noqa: BLE001
447
+ errs.append(f"GitHub:{exc}")
448
+ if raw is None:
449
+ raise ValueError(f"云端没有该文件或下载失败({label}):{';'.join(errs) or path}")
450
+ return raw
451
+
452
+
453
+ def _safe_name(name: str) -> bool:
454
+ """拓展 id/面板名安全校验:复用 panels._NAME_RE(防路径分隔符与越界)。
455
+
456
+ _NAME_RE 白名单本身不含冒号/斜杠,天然拒绝 `..`、路径分隔符与
457
+ Windows 盘符冒号(`C:`);这里显式再挡一层,与 panels._extract_zip_safe
458
+ 的三重防护口径保持一致。
459
+ """
460
+ if not name or name.startswith("/") or "\\" in name or ".." in name \
461
+ or (len(name) > 1 and name[1] == ":"):
462
+ return False
463
+ return bool(panels._NAME_RE.match(name))
464
+
465
+
466
+ def cloud_shot(name: str, ext: str) -> bytes:
467
+ """取云端截图字节(前端 <img> 直连本机代理端点,避免跨域/混合内容问题)。"""
468
+ if ext not in SHOT_WHITELIST:
469
+ raise ValueError("截图扩展名不支持")
470
+ c = _cfg()
471
+ branch = c.get("branch", "master")
472
+ path = f"shots/{name}{ext}"
473
+ raw = None
474
+ if c.get("gitee_repo"):
475
+ try:
476
+ raw = _gitee_get(c["gitee_repo"], path, c.get("gitee_token", ""), branch)
477
+ except Exception: # noqa: BLE001
478
+ raw = None
479
+ if raw is None and c.get("github_repo"):
480
+ try:
481
+ raw = _github_get(c["github_repo"], path, c.get("github_token", ""), branch)
482
+ except Exception: # noqa: BLE001
483
+ raw = None
484
+ if raw is None:
485
+ raise FileNotFoundError("云端没有该截图")
486
+ return raw
487
+
488
+
489
+ # ---------------------------------------------------------------- 发布
490
+
491
+ def cloud_publish(name: str, screenshot: bytes | None = None,
492
+ shot_ext: str = ".png") -> dict:
493
+ """把已安装面板发布到云端(Gitee 必配;GitHub 配了就同步镜像)。
494
+
495
+ 流程:校验 manifest → 打 zip → 传 panels/<name>.zip →(可选)传截图 →
496
+ 读 index.json 合并本面板条目后回写。任一远端失败则该远端报错,另一端照常。
497
+ """
498
+ import io
499
+ import zipfile
500
+
501
+ import panels
502
+ src = panels._panel_path(panels.panels_dir(), name)
503
+ if not src.exists():
504
+ raise ValueError(f"已安装面板不存在:{name}")
505
+ mf = panels._load_manifest(src) # 损坏面板不允许发布
506
+ if screenshot is not None:
507
+ if len(screenshot) > SHOT_MAX:
508
+ raise ValueError("截图超过 2MB,请压缩后再上传")
509
+ if shot_ext not in SHOT_WHITELIST:
510
+ raise ValueError("截图只支持 png/jpg/webp")
511
+ # 打 zip:内存打包(总量受 ZIP_MAX_TOTAL 保护,超限抛 ValueError)
512
+ buf = io.BytesIO()
513
+ total = 0
514
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
515
+ for f in sorted(src.rglob("*")):
516
+ if f.is_file():
517
+ rel = f.relative_to(src).as_posix()
518
+ if rel in ("panel.json",) or not rel.startswith("."):
519
+ total += f.stat().st_size
520
+ if total > panels.ZIP_MAX_TOTAL:
521
+ raise ValueError("面板超过 50MB,不适合云端分发")
522
+ z.write(f, rel)
523
+ zbytes = buf.getvalue()
524
+ now = time.strftime("%Y-%m-%d %H:%M", time.localtime())
525
+ entry = {"name": mf["name"], "title": mf["title"], "version": mf["version"],
526
+ "author": mf.get("author", ""), "description": mf.get("description", ""),
527
+ "screenshot": (f"{name}{shot_ext}" if screenshot is not None else ""),
528
+ "size": len(zbytes), "sha256": hashlib.sha256(zbytes).hexdigest(), "updated": now}
529
+ c = _cfg()
530
+ branch = c.get("branch", "master")
531
+ author = _commit_author(c)
532
+ msg = f"lingshu: publish panel {name} v{mf['version']}"
533
+ pushed, errors = [], []
534
+ if c.get("gitee_repo") and c.get("gitee_token"):
535
+ try:
536
+ _push_one("gitee", c["gitee_repo"], c["gitee_token"], branch,
537
+ name, zbytes, screenshot, shot_ext, entry, msg,
538
+ kind_key="panels", author=author)
539
+ pushed.append("Gitee")
540
+ except Exception as exc: # noqa: BLE001
541
+ errors.append(f"Gitee:{exc}")
542
+ else:
543
+ errors.append("Gitee 未配置仓库或 token(发布需要 Gitee)")
544
+ if c.get("github_repo") and c.get("github_token"):
545
+ try:
546
+ _push_one("github", c["github_repo"], c["github_token"], branch,
547
+ name, zbytes, screenshot, shot_ext, entry, msg,
548
+ kind_key="panels", author=author)
549
+ pushed.append("GitHub")
550
+ except Exception as exc: # noqa: BLE001
551
+ errors.append(f"GitHub:{exc}")
552
+ global _CACHE
553
+ _CACHE = None # 发布后清缓存,下次列表强制刷新
554
+ if not pushed:
555
+ raise RuntimeError(f"发布失败:{';'.join(errors)}")
556
+ return {"ok": True, "pushed": pushed,
557
+ "errors": errors, "entry": entry}
558
+
559
+
560
+ def cloud_extension_publish(ext_id: str) -> dict:
561
+ """把拓展已安装目录发布到云端 extensions/<id>.zip + index.json 的 extensions 数组。
562
+
563
+ 结构与面板发布平行:同一个 index.json,两个子清单互不干扰。
564
+ """
565
+ import io
566
+ import zipfile
567
+
568
+ src = brain.HOME / "extensions" / "installed" / ext_id
569
+ if not src.is_dir() or not _safe_name(ext_id):
570
+ raise ValueError(f"已安装拓展不存在或 id 不合法:{ext_id}")
571
+ meta = panels._extension_meta(src) if hasattr(panels, "_extension_meta") else {}
572
+ buf = io.BytesIO()
573
+ total = 0
574
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
575
+ for f in sorted(src.rglob("*")):
576
+ if f.is_file() and not f.name.startswith("."):
577
+ total += f.stat().st_size
578
+ if total > panels.ZIP_MAX_TOTAL:
579
+ raise ValueError("拓展超过 50MB,不适合云端分发")
580
+ z.write(f, f.relative_to(src).as_posix())
581
+ zbytes = buf.getvalue()
582
+ now = time.strftime("%Y-%m-%d %H:%M", time.localtime())
583
+ entry = {"id": ext_id, "title": ext_id,
584
+ "version": meta.get("version", "0.0.0"),
585
+ "author": meta.get("author", ""),
586
+ "size": len(zbytes), "sha256": hashlib.sha256(zbytes).hexdigest(), "updated": now}
587
+ c = _cfg()
588
+ branch = c.get("branch", "master")
589
+ author = _commit_author(c)
590
+ msg = f"lingshu: publish extension {ext_id} v{entry['version']}"
591
+ pushed, errors = [], []
592
+ for kind in ("gitee", "github"):
593
+ repo = c.get(f"{kind}_repo", "")
594
+ token = c.get(f"{kind}_token", "")
595
+ if repo and token:
596
+ try:
597
+ _push_one(kind, repo, token, branch, ext_id, zbytes,
598
+ None, ".png", entry, msg, kind_key="extensions",
599
+ author=author)
600
+ pushed.append("Gitee" if kind == "gitee" else "GitHub")
601
+ except Exception as exc: # noqa: BLE001
602
+ errors.append(f"{'Gitee' if kind == 'gitee' else 'GitHub'}:{exc}")
603
+ global _CACHE
604
+ _CACHE = None
605
+ if not pushed:
606
+ raise RuntimeError(f"发布失败:{';'.join(errors)}")
607
+ return {"ok": True, "pushed": pushed, "errors": errors, "entry": entry}
608
+
609
+
610
+ def _push_one(kind: str, repo: str, token: str, branch: str, name: str,
611
+ zbytes: bytes, shot: bytes | None, shot_ext: str,
612
+ entry: dict, msg: str, kind_key: str = "panels",
613
+ author: dict | None = None) -> None:
614
+ """向一个远端推 zip + 截图 + index.json 条目。
615
+
616
+ kind_key 决定子目录与清单键:panels → panels/xxx.zip + index.json.panels,
617
+ extensions → extensions/xxx.zip + index.json.extensions(同一份 index.json)。
618
+ """
619
+ put = _gitee_put if kind == "gitee" else _github_put
620
+ get = _gitee_get if kind == "gitee" else _github_get
621
+ put(repo, f"{kind_key}/{name}.zip", token, branch, zbytes, msg, author)
622
+ if shot is not None:
623
+ put(repo, f"shots/{name}{shot_ext}", token, branch, shot, msg, author)
624
+ # index.json 合并回写:读旧清单 → 覆盖同名条目 → 写回(并发竞争可接受,个人市场)
625
+ #
626
+ # ⚠ fail-closed:**只有"清单确实不存在"才可以新建空清单**。
627
+ # 若清单拉到了但解析失败(被改坏、传输截断、编码问题),旧代码会重建空清单再回写,
628
+ # 等于**把整个市场目录清空**,只留刚发布这一条——这是不可接受的静默数据丢失。
629
+ # 现在:解析失败一律抛错中止(zip 已经传上去了,只是清单不动,仍是安全状态)。
630
+ raw = get(repo, "index.json", token, branch)
631
+ if raw:
632
+ try:
633
+ data = json.loads(raw.decode("utf-8"))
634
+ except Exception as exc: # noqa: BLE001
635
+ raise ValueError(
636
+ f"云端 index.json 解析失败,已中止清单回写(避免清空市场目录):{exc}") from exc
637
+ if not isinstance(data, dict):
638
+ raise ValueError("云端 index.json 结构异常(不是对象),已中止清单回写")
639
+ else:
640
+ # 清单不存在 = 首次发布,允许新建
641
+ data = {"panels": [], "extensions": []}
642
+ # key 名:面板条目按 name 匹配,拓展条目按 id 匹配
643
+ id_key = "id" if kind_key == "extensions" else "name"
644
+ items = [p for p in (data.get(kind_key) or []) if p.get(id_key) != name]
645
+ items.append(entry)
646
+ items.sort(key=lambda p: str(p.get("updated", "")), reverse=True)
647
+ data[kind_key] = items
648
+ data.setdefault("panels", data.get("panels", []))
649
+ put(repo, "index.json", token, branch,
650
+ json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8"),
651
+ msg, author)