qqbot-cli 1.0.0__tar.gz → 1.0.2__tar.gz

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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: qqbot-cli
3
- Version: 1.0.0
3
+ Version: 1.0.2
4
4
  Summary: QQBotMerged 启动器:一条命令装好并启动 QQ 官方机器人多开后台
5
5
  Author: L-web666
6
6
  License-Expression: AGPL-3.0-or-later
@@ -22,7 +22,7 @@ Classifier: Intended Audience :: End Users/Desktop
22
22
  Requires-Python: >=3.9
23
23
  Description-Content-Type: text/markdown
24
24
  License-File: LICENSE
25
- Requires-Dist: requests>=2.28.0
25
+ Requires-Dist: requests>=2.32.4
26
26
  Provides-Extra: dev
27
27
  Requires-Dist: pytest>=7; extra == "dev"
28
28
  Dynamic: license-file
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "qqbot-cli"
7
- version = "1.0.0"
7
+ version = "1.0.2"
8
8
  description = "QQBotMerged 启动器:一条命令装好并启动 QQ 官方机器人多开后台"
9
9
  readme = "PACKAGING.md"
10
10
  requires-python = ">=3.9"
@@ -28,7 +28,7 @@ classifiers = [
28
28
  ]
29
29
  # **启动器自己只依赖 requests**:主程序的 flask/werkzeug 等装进它自己的虚拟环境,
30
30
  # 不污染安装启动器的那个环境(这也正是推荐用 pipx 的原因)。
31
- dependencies = ["requests>=2.28.0"]
31
+ dependencies = ["requests>=2.32.4"]
32
32
 
33
33
  [project.optional-dependencies]
34
34
  dev = ["pytest>=7"]
@@ -13,4 +13,4 @@
13
13
  自动更新、插件机制全都照常工作,不需要改任何一行代码。
14
14
  """
15
15
 
16
- __version__ = "1.0.0"
16
+ __version__ = "1.0.2"
@@ -119,6 +119,51 @@ def _confirm_target_dir(install_dir: str) -> bool:
119
119
  return False
120
120
 
121
121
 
122
+ def _finish_config_only(install_dir: str, marker: Dict) -> int:
123
+ """装好的目录只差配置(上次向导被取消):跑向导 + 出结果,不重新下载。
124
+
125
+ 程序文件、虚拟环境、依赖都已经就位,重跑一遍下载既慢又浪费;
126
+ 这里只补 `config.json`,然后照常打印地址/令牌并问要不要启动。
127
+ """
128
+ print()
129
+ _info("这个目录已经装好了,只差配置文件(不会重新下载)。")
130
+ tag = str(marker.get("tag") or "未知")
131
+ config_path = os.path.join(install_dir, "config.json")
132
+ existing: Dict = {}
133
+ try:
134
+ config = wizard.run_wizard(install_dir, tag, existing)
135
+ except (EOFError, KeyboardInterrupt):
136
+ print()
137
+ _info("向导已取消,配置还没写。之后运行 `qqbot init` 可以接着补。")
138
+ return 0
139
+ wizard.write_config(install_dir, config)
140
+ _ok("已生成 config.json")
141
+
142
+ # 清掉 needs_config:配置有了,下次 `qqbot` 直接启动
143
+ payload = dict(marker)
144
+ payload.pop("needs_config", None)
145
+ runner.write_marker(install_dir, payload)
146
+ paths.remember_install_dir(install_dir)
147
+
148
+ python = paths.venv_python(install_dir)
149
+ versions: Dict = {}
150
+ if os.path.exists(python):
151
+ try:
152
+ versions = runner.verify_dependencies(python)
153
+ except runner.SetupError:
154
+ versions = {}
155
+ wizard.show_summary(install_dir, config, versions)
156
+
157
+ try:
158
+ if wizard.ask_yes("现在启动吗?", default=True):
159
+ return do_run(install_dir)
160
+ except (EOFError, KeyboardInterrupt):
161
+ print()
162
+ print()
163
+ _info("之后运行 `qqbot` 就能启动。")
164
+ return 0
165
+
166
+
122
167
  def do_install(install_dir: str = "", force_wizard: bool = False,
123
168
  upgrade: bool = False, dir_given: bool = False) -> int:
124
169
  """下载 + 建环境 + 向导。返回进程退出码。
@@ -137,6 +182,14 @@ def do_install(install_dir: str = "", force_wizard: bool = False,
137
182
  if already and not upgrade and not force_wizard:
138
183
  return do_run(install_dir)
139
184
 
185
+ # **装好了但还缺配置**(上次向导被取消)→ 只补配置,不重新下载。
186
+ # 这也是 `qqbot` auto 模式在那种情况下的目标路径。
187
+ if already and not upgrade:
188
+ marker = runner.read_marker(install_dir)
189
+ config_path = os.path.join(install_dir, "config.json")
190
+ if marker.get("needs_config") and not os.path.exists(config_path):
191
+ return _finish_config_only(install_dir, marker)
192
+
140
193
  # 目录里有东西但不是本程序 → 问清楚再动,避免覆盖用户别的文件
141
194
  if not already and not upgrade:
142
195
  if not _confirm_target_dir(install_dir):
@@ -185,6 +238,14 @@ def do_install(install_dir: str = "", force_wizard: bool = False,
185
238
  print()
186
239
  python = runner.ensure_venv(install_dir, progress=_info)
187
240
  _ok("虚拟环境就绪")
241
+ # 装依赖之前先看 pip 版本:太旧的 pip 可能信任已出事的证书,
242
+ # 在不可信网络里装包有被中间人顶替的风险(见 runner.MIN_PIP_VERSION)。
243
+ pip_info = runner.check_pip(python)
244
+ if pip_info.get("ok"):
245
+ if pip_info.get("version"):
246
+ _ok("pip 版本 %s" % pip_info["version"])
247
+ else:
248
+ _info("注意:pip 版本偏低,见上面的说明(不影响继续安装)")
188
249
  runner.install_requirements(install_dir, python, progress=_info)
189
250
  versions = runner.verify_dependencies(python)
190
251
  _ok("依赖安装完成")
@@ -207,9 +268,24 @@ def do_install(install_dir: str = "", force_wizard: bool = False,
207
268
  try:
208
269
  config = wizard.run_wizard(install_dir, tag, existing)
209
270
  except (EOFError, KeyboardInterrupt):
271
+ # 用户中途按了 Ctrl+C / 输入被关掉(管道里跑、CI)。
272
+ # **程序文件已经装好了,必须照常写 marker**,否则 `is_installed()`
273
+ # 判为没装,下次 `qqbot` 会重新下载一遍 —— 白费一次下载和装依赖。
274
+ # 但 config.json 没写成,所以一个劲儿启动也没用,改为提示补配置。
210
275
  print()
276
+ runner.write_marker(install_dir, {
277
+ "tag": tag,
278
+ "sha256": result.get("sha256") or "",
279
+ "cli_version": __version__,
280
+ "needs_config": True,
281
+ "python": "%d.%d.%d" % sys.version_info[:3],
282
+ "pip": pip_info.get("version") or "",
283
+ "dependencies": versions,
284
+ })
285
+ paths.remember_install_dir(install_dir)
211
286
  _info("向导已取消,程序文件已经装好了。")
212
- _info("之后运行 qqbot 会继续问配置。")
287
+ _info("还没写配置,所以暂时不能直接启动。")
288
+ _info("运行 `qqbot init` 补完配置即可(不会重新下载)。")
213
289
  return 0
214
290
  wizard.write_config(install_dir, config)
215
291
  _ok("已生成 config.json")
@@ -221,6 +297,10 @@ def do_install(install_dir: str = "", force_wizard: bool = False,
221
297
  "tag": tag,
222
298
  "sha256": result.get("sha256") or "",
223
299
  "cli_version": __version__,
300
+ # 把运行环境记下来:审计和安全排查时不用再猜装的是什么版本
301
+ "python": "%d.%d.%d" % sys.version_info[:3],
302
+ "pip": pip_info.get("version") or "",
303
+ "dependencies": versions,
224
304
  })
225
305
  # 记下装到了哪:下次 `qqbot` 不带参数就知道去哪启动
226
306
  paths.remember_install_dir(install_dir)
@@ -497,6 +577,13 @@ def main(argv: Optional[List[str]] = None) -> int:
497
577
  remembered = paths.remembered_install_dir()
498
578
  if not dir_given and remembered and runner.is_installed(remembered) \
499
579
  and not args.upgrade:
580
+ # 装过但上次向导被取消了(没写 config.json)→ 补配置,而不是启动个空程序
581
+ marker = runner.read_marker(remembered)
582
+ if marker.get("needs_config") and \
583
+ not os.path.exists(os.path.join(remembered, "config.json")):
584
+ _info("上次没写配置,先补一下(不会重新下载)。")
585
+ return do_install(remembered, force_wizard=True,
586
+ upgrade=False, dir_given=True)
500
587
  return do_run(remembered)
501
588
  return do_install(install_dir, upgrade=args.upgrade, dir_given=dir_given)
502
589
  except KeyboardInterrupt:
@@ -10,6 +10,7 @@
10
10
  import hashlib
11
11
  import io
12
12
  import json
13
+ import logging
13
14
  import os
14
15
  import re
15
16
  import shutil
@@ -17,10 +18,14 @@ import tarfile
17
18
  import tempfile
18
19
  import zipfile
19
20
  from typing import Callable, Dict, List, Optional, Tuple
20
- from urllib.parse import urlparse
21
+ from urllib.parse import urljoin, urlparse
21
22
 
22
23
  from . import paths
23
24
 
25
+ logger = logging.getLogger("qqbot_cli")
26
+ if not logger.handlers:
27
+ logger.addHandler(logging.NullHandler())
28
+
24
29
  # 压缩包上限:程序本体约 1~2 MB,给足余量但不允许无限大
25
30
  MAX_ARCHIVE_BYTES = 64 * 1024 * 1024
26
31
  MAX_MEMBERS = 5000
@@ -42,23 +47,78 @@ def _requests():
42
47
  return requests
43
48
 
44
49
 
50
+ # 内网/回环地址前缀:即使出现在白名单主机的 Location 里也要拒绝。
51
+ # (白名单主机不会重定向到这些地址;出现就是异常或攻击。)
52
+ _PRIVATE_PREFIXES = (
53
+ "10.", "127.", "0.", "169.254.", # 私有网段 / 回环 / 链路本地
54
+ "192.168.", "172.16.", "172.17.", "172.18.", "172.19.",
55
+ "172.20.", "172.21.", "172.22.", "172.23.", "172.24.", "172.25.",
56
+ "172.26.", "172.27.", "172.28.", "172.29.", "172.30.", "172.31.",
57
+ )
58
+
59
+
60
+ def _host_looks_private(host: str) -> bool:
61
+ host = (host or "").lower().strip("[]")
62
+ if host in ("localhost", "::1", "0.0.0.0"):
63
+ return True
64
+ return any(host.startswith(prefix) for prefix in _PRIVATE_PREFIXES)
65
+
66
+
45
67
  def _check_host(url: str) -> None:
68
+ """校验一个 URL 是否可以从这里发起请求。
69
+
70
+ **只允许 HTTPS**,且主机必须在白名单里、不能是内网地址。
71
+ 重定向的每一跳都要单独过这个检查(见 `_get_following_redirects`)。
72
+ """
46
73
  parsed = urlparse(str(url or ""))
47
- if parsed.scheme not in ("https", "http"):
48
- raise FetchError("只允许 http/https 地址:%s" % url)
74
+ if parsed.scheme != "https":
75
+ raise FetchError("只允许 https 地址:%s" % url)
49
76
  host = (parsed.hostname or "").lower()
77
+ if not host:
78
+ raise FetchError("地址里没有主机名:%s" % url)
79
+ if _host_looks_private(host):
80
+ raise FetchError("拒绝访问内网地址:%s" % host)
50
81
  if host not in paths.ALLOWED_HOSTS:
51
82
  raise FetchError("拒绝从非白名单主机下载:%s" % host)
52
83
 
53
84
 
85
+ def _get_following_redirects(requests, url: str, timeout: int,
86
+ stream: bool = False, headers: Optional[Dict] = None,
87
+ max_hops: int = 5):
88
+ """GET 一个 URL,**手动**跟随重定向,每一跳都重新校验。
89
+
90
+ 为什么不直接用 `requests` 的自动重定向:它只校验第一次请求的地址,
91
+ 白名单主机返回一个 `Location: http://内网/...` 时会被静默跟随 ——
92
+ 白名单形同虚设。这里关掉自动跟随,逐跳 `_check_host()`。
93
+ """
94
+ current = url
95
+ for _hop in range(max_hops + 1):
96
+ _check_host(current)
97
+ response = requests.get(current, timeout=timeout, stream=stream,
98
+ headers=headers, allow_redirects=False)
99
+ if response.status_code not in (301, 302, 303, 307, 308):
100
+ return response
101
+ location = response.headers.get("Location") or ""
102
+ try:
103
+ response.close()
104
+ except Exception:
105
+ pass
106
+ if not location:
107
+ raise FetchError("重定向缺少 Location 头:%s" % current)
108
+ current = urljoin(current, location)
109
+ raise FetchError("重定向次数过多(超过 %d 次)" % max_hops)
110
+
111
+
54
112
  def list_releases(timeout: int = 30) -> List[Dict]:
55
113
  """取发布列表(新的在前)。"""
56
114
  requests = _requests()
57
- _check_host(paths.RELEASES_API)
58
115
  try:
59
- response = requests.get(paths.RELEASES_API, timeout=timeout,
60
- headers={"User-Agent": USER_AGENT,
61
- "Accept": "application/vnd.github+json"})
116
+ response = _get_following_redirects(
117
+ requests, paths.RELEASES_API, timeout,
118
+ headers={"User-Agent": USER_AGENT,
119
+ "Accept": "application/vnd.github+json"})
120
+ except FetchError:
121
+ raise
62
122
  except Exception as exc:
63
123
  raise FetchError("连不上 GitHub:%s" % exc)
64
124
  if response.status_code == 404:
@@ -112,12 +172,18 @@ def pick_latest(releases: List[Dict]) -> Optional[Dict]:
112
172
  # ---------------------------------------------------------------- 下载
113
173
  def download(url: str, target: str, timeout: int = 60,
114
174
  progress: Optional[Callable[[int, int], None]] = None) -> str:
115
- """把 url 下载到 target,返回 sha256。超过上限立即中止。"""
175
+ """把 url 下载到 target,返回 sha256。超过上限立即中止。
176
+
177
+ 重定向**逐跳校验**(见 `_get_following_redirects`),不会跟着
178
+ 白名单主机跳到内网或别的主机去。
179
+ """
116
180
  requests = _requests()
117
- _check_host(url)
118
181
  try:
119
- response = requests.get(url, timeout=timeout, stream=True,
120
- headers={"User-Agent": USER_AGENT})
182
+ response = _get_following_redirects(
183
+ requests, url, timeout, stream=True,
184
+ headers={"User-Agent": USER_AGENT})
185
+ except FetchError:
186
+ raise
121
187
  except Exception as exc:
122
188
  raise FetchError("下载失败:%s" % exc)
123
189
  if response.status_code != 200:
@@ -165,19 +231,95 @@ def _quiet_remove(path: str) -> None:
165
231
 
166
232
 
167
233
  # ---------------------------------------------------------------- 解压
234
+ # Windows 保留设备名(组件名主干命中即拒绝,带扩展名也算:NUL.txt 同样是设备)
235
+ _WINDOWS_DEVICE_NAMES = {
236
+ "con", "prn", "aux", "nul",
237
+ "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9",
238
+ "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
239
+ }
240
+ # 上标数字写法也算设备名(COM¹ / LPT² …)
241
+ _SUPERSCRIPT_DIGITS = {"\u00b9": "1", "\u00b2": "2", "\u00b3": "3"}
242
+
243
+
244
+ def _bad_component(part: str) -> bool:
245
+ """单个路径组件是否危险(盘符、ADS、设备名、控制字符、尾随点空格等)。
246
+
247
+ **必须逐组件检查,不能只看整个路径的开头**。反例:
248
+ `a/D:outside.txt` 开头不是盘符,但 Windows 的 `ntpath.join('C:\\x', 'a',
249
+ 'D:outside.txt')` 会得到 `'D:outside.txt'` —— **直接跳出目标目录**。
250
+ 同类还有 `dir/C:/x.txt`、`a/b/c:stream`(ADS)。
251
+ """
252
+ if not part:
253
+ return True
254
+ if part in (".", ".."):
255
+ return True
256
+ # 盘符 / ADS / 任何位置的冒号
257
+ if ":" in part:
258
+ return True
259
+ # 控制字符
260
+ if any(ord(ch) < 32 for ch in part):
261
+ return True
262
+ # Windows 会静默去掉尾随的点与空格,导致"看起来不同其实是同一个文件"
263
+ if part != part.rstrip(" ."):
264
+ return True
265
+ # 设备名:主干(第一个点之前)归一化后命中就是设备
266
+ stem = part.split(".")[0]
267
+ normalized = "".join(_SUPERSCRIPT_DIGITS.get(ch, ch) for ch in stem).lower()
268
+ if normalized in _WINDOWS_DEVICE_NAMES:
269
+ return True
270
+ return False
271
+
272
+
168
273
  def _safe_member(name: str) -> str:
169
- """把压缩包成员名规范化成相对路径;不安全的返回空串。"""
274
+ """把压缩包成员名规范化成相对路径;不安全的返回空串。
275
+
276
+ **每个组件都要单独过一遍 `_bad_component()`** —— 只看开头会漏掉
277
+ 「中间组件是盘符」这种能把路径带出目标目录的写法。
278
+ """
170
279
  raw = str(name or "").replace("\\", "/")
171
280
  if not raw or raw.startswith("/") or raw.startswith("~"):
172
281
  return ""
173
- if re.match(r"^[A-Za-z]:", raw):
174
- return ""
175
282
  parts = [part for part in raw.split("/") if part not in ("", ".")]
176
- if any(part == ".." for part in parts):
283
+ if not parts:
177
284
  return ""
285
+ for part in parts:
286
+ if _bad_component(part):
287
+ return ""
178
288
  return "/".join(parts)
179
289
 
180
290
 
291
+ def _within(root: str, target: str) -> bool:
292
+ """target 规范化后是否仍在 root 之内(防 `..`、盘符、符号链接绕过)。"""
293
+ try:
294
+ real_root = os.path.realpath(root)
295
+ real_target = os.path.realpath(target)
296
+ return os.path.commonpath([real_root, real_target]) == real_root
297
+ except (ValueError, OSError):
298
+ # 不同盘符时 commonpath 会抛 ValueError → 一定不在同一棵树里
299
+ return False
300
+
301
+
302
+ def _has_symlink_parent(root: str, target: str) -> bool:
303
+ """target 的任一父目录(相对 root)是否是符号链接。
304
+
305
+ 攻击者可以事先在安装目录里布置 `data -> /etc` 这样的链接,
306
+ 解压时文件就顺着链接写到了外面。
307
+ """
308
+ try:
309
+ root_real = os.path.realpath(root)
310
+ except OSError:
311
+ return True
312
+ current = os.path.dirname(os.path.abspath(target))
313
+ while True:
314
+ if os.path.islink(current):
315
+ return True
316
+ if os.path.abspath(current) == root_real or \
317
+ os.path.dirname(current) == current:
318
+ break
319
+ current = os.path.dirname(current)
320
+ return False
321
+
322
+
181
323
  def _strip_root(names: List[str]) -> str:
182
324
  """识别 GitHub 压缩包的顶层壳目录(如 `L-web666-QQBotMerged-abc123/`)。
183
325
 
@@ -253,6 +395,15 @@ def _extract_tar(archive: str, target_dir: str) -> None:
253
395
  if not relative:
254
396
  continue
255
397
  destination = os.path.join(target_dir, *relative.split("/"))
398
+ # **落盘前必须确认没跑出 target_dir**。`_safe_member()` 已经逐组件
399
+ # 挡了盘符/ADS/设备名,但这里再做一次真实路径包含性检查 ——
400
+ # 双保险,防止任何没想到的写法把文件写到安装目录外面。
401
+ if not _within(target_dir, destination):
402
+ logger.debug("拒绝越界的解压目标:%r -> %r", name, destination)
403
+ continue
404
+ if _has_symlink_parent(target_dir, destination):
405
+ logger.debug("拒绝经过符号链接的解压目标:%r", destination)
406
+ continue
256
407
  if info.isdir():
257
408
  os.makedirs(destination, exist_ok=True)
258
409
  continue
@@ -294,6 +445,12 @@ def _extract_zip(archive: str, target_dir: str) -> None:
294
445
  if not relative:
295
446
  continue
296
447
  destination = os.path.join(target_dir, *relative.split("/"))
448
+ if not _within(target_dir, destination):
449
+ logger.debug("拒绝越界的解压目标:%r -> %r", name, destination)
450
+ continue
451
+ if _has_symlink_parent(target_dir, destination):
452
+ logger.debug("拒绝经过符号链接的解压目标:%r", destination)
453
+ continue
297
454
  if info.is_dir():
298
455
  os.makedirs(destination, exist_ok=True)
299
456
  continue
@@ -28,13 +28,19 @@ MARKER_FILE = ".qqbot-install.json"
28
28
  # 虚拟环境目录名(放在安装目录下)
29
29
  VENV_DIR = ".venv"
30
30
 
31
+ # "记住装在哪"的状态文件名(放在用户配置目录 / 主目录 / 安装目录里)
32
+ STATE_FILENAME = ".qqbot-cli.json"
33
+
31
34
  # 主程序需要的依赖(和主程序 requirements.txt 保持一致;
32
35
  # 启动器自己只需要 requests)
33
36
  PROGRAM_REQUIRES = (
34
37
  "flask>=2.0",
35
38
  "Werkzeug>=3.1.9",
36
- "requests>=2.28.0",
39
+ "requests>=2.32.4",
37
40
  "websocket-client>=1.5.0",
41
+ # 插件的 metadata.yaml 要靠它解析;缺了会退化成只认 "key: value",
42
+ # 遇到 YAML 多行块(description: |)就解析错
43
+ "PyYAML>=6.0",
38
44
  )
39
45
 
40
46
  # 最低 Python 版本:Werkzeug 3.1.9 要求 >=3.9
@@ -120,18 +126,23 @@ def current_python() -> str:
120
126
 
121
127
  # ---------------------------------------------------------------- 记住装在哪
122
128
  def _state_files(install_dir: str = "") -> list:
123
- """启动器记住"装到哪"的几个候选位置,按优先级排列。
124
-
125
- **为什么要好几个**:`%APPDATA%` / `$XDG_CONFIG_HOME` 在有些环境里不可写
126
- (受限的用户目录、容器、CI);用户主目录也可能只读(只读家目录、企业策略)。
127
- 只记一处,用户在向导里选的目录下次就找不到 —— `qqbot` 会默默回落到默认目录,
128
- 看起来像"装丢了"。
129
-
130
- 所以依次尝试几个位置,任何一处写成功就够用:
131
- ① 用户配置目录(最"正规"的位置)
132
- ② 用户主目录下的隐藏文件(配置目录写不了时的兜底)
133
- ③ **当前工作目录**下的隐藏文件(前两处都写不了时用;用户一般在自己
134
- 常用的目录里运行 `qqbot`,下次也在那儿跑,所以找得回来)
129
+ """启动器记住"装到哪"的位置,按优先级排列。
130
+
131
+ **只用受保护的用户目录 + 安装目录本身,绝不读当前工作目录。**
132
+ 曾经加过 `cwd/.qqbot-cli.json` 作为兜底(前两处不可写时用),
133
+ 但那是个安全漏洞:攻击者只要放一个伪造的状态文件到一个目录里,
134
+ 用户从那儿运行 `qqbot` 就会去执行攻击者指定的目录 —— 本地代码执行。
135
+ 便利性不能换安全性,这个兜底已移除。
136
+
137
+ 现在的候选:
138
+ ① 用户配置目录(`%APPDATA%` / `$XDG_CONFIG_HOME`)
139
+ ② 用户主目录下的隐藏文件(配置目录写不了时兜底)
140
+ ③ **安装目录里面**(前两处都写不了时用;安装目录一定可写,
141
+ 否则程序也装不进去)
142
+
143
+ ③ 是"受限环境"(只读家目录、CI、容器)下唯一能成的那个。
144
+ 下一轮 `qqbot` 不带参数时怎么找到它?靠 `_find_state_by_default_dir()`
145
+ 去默认安装目录里找 —— 因为那样装的用户几乎都是装在默认位置。
135
146
  """
136
147
  home = os.path.expanduser("~")
137
148
  if os.name == "nt":
@@ -142,17 +153,10 @@ def _state_files(install_dir: str = "") -> list:
142
153
  os.path.join(base, "qqbot-cli", "state.json"),
143
154
  os.path.join(home, ".qqbot-cli.json"),
144
155
  ]
145
- try:
146
- cwd = os.getcwd()
147
- except OSError:
148
- cwd = ""
149
- if cwd:
150
- candidates.append(os.path.join(cwd, ".qqbot-cli.json"))
151
156
  if install_dir:
152
- parent = os.path.dirname(os.path.abspath(install_dir).rstrip("/\\")) or "."
153
- marker = os.path.join(parent, ".qqbot-cli.json")
154
- if marker not in candidates:
155
- candidates.append(marker)
157
+ inside = os.path.join(os.path.abspath(install_dir), STATE_FILENAME)
158
+ if inside not in candidates:
159
+ candidates.append(inside)
156
160
  return candidates
157
161
 
158
162
 
@@ -161,29 +165,79 @@ def _state_file() -> str:
161
165
  return _state_files()[0]
162
166
 
163
167
 
168
+ def _write_state_file(path: str, payload: dict) -> bool:
169
+ """安全地写状态文件:拒绝符号链接、原子替换、POSIX 下 0600。"""
170
+ import json
171
+ directory = os.path.dirname(path)
172
+ try:
173
+ os.makedirs(directory, exist_ok=True)
174
+ except OSError:
175
+ return False
176
+ # 已存在且是符号链接 → 拒绝(否则会写到链接指向的文件,可能覆盖别人的东西)
177
+ if os.path.islink(path):
178
+ return False
179
+ temp = path + ".tmp"
180
+ try:
181
+ if os.path.islink(temp):
182
+ os.remove(temp)
183
+ if os.name != "nt":
184
+ # 先建好再写权限,避免中间态被别人读到
185
+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
186
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
187
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
188
+ else:
189
+ with open(temp, "w", encoding="utf-8") as handle:
190
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
191
+ os.replace(temp, path)
192
+ return True
193
+ except OSError:
194
+ try:
195
+ if os.path.exists(temp):
196
+ os.remove(temp)
197
+ except OSError:
198
+ pass
199
+ return False
200
+
201
+
164
202
  def remember_install_dir(install_dir: str) -> bool:
165
203
  """记下这次装到了哪,下次 `qqbot` 不带参数就能直接启动。
166
204
 
167
205
  返回是否至少有一处写成功(写失败不影响本次使用,只是下次要带 --dir)。
168
206
  """
169
- import json
170
- payload = {"install_dir": install_dir}
207
+ payload = {"install_dir": os.path.abspath(str(install_dir))}
171
208
  written = False
172
209
  for path in _state_files(install_dir):
173
- try:
174
- os.makedirs(os.path.dirname(path), exist_ok=True)
175
- with open(path, "w", encoding="utf-8") as handle:
176
- json.dump(payload, handle, ensure_ascii=False, indent=2)
210
+ if _write_state_file(path, payload):
177
211
  written = True
178
- except OSError:
179
- continue
180
212
  return written
181
213
 
182
214
 
215
+ def _scan_state_dir(root: str) -> str:
216
+ """在 root 下找 `.qqbot-cli.json`,读回它记的安装目录;找不到返回空串。"""
217
+ import json
218
+ candidate = os.path.join(root, STATE_FILENAME)
219
+ if os.path.islink(candidate):
220
+ return ""
221
+ try:
222
+ with open(candidate, "r", encoding="utf-8") as handle:
223
+ data = json.load(handle)
224
+ except Exception:
225
+ return ""
226
+ value = str((data or {}).get("install_dir") or "")
227
+ return value if value and os.path.isdir(value) else ""
228
+
229
+
183
230
  def remembered_install_dir(install_dir: str = "") -> str:
184
- """读回上次装的目录;没有就返回空串。多个位置依次尝试。"""
231
+ """读回上次装的目录;没有就返回空串。多个位置依次尝试。
232
+
233
+ **读到之后不做信任判断**:调用方还要过 `runner.is_installed()` +
234
+ marker 校验,才会真的去执行那个目录里的东西。
235
+ """
185
236
  import json
186
237
  for path in _state_files(install_dir):
238
+ # 状态文件本身是符号链接 → 不信任(可能是攻击者做的跳板)
239
+ if os.path.islink(path):
240
+ continue
187
241
  try:
188
242
  with open(path, "r", encoding="utf-8") as handle:
189
243
  data = json.load(handle)
@@ -192,6 +246,19 @@ def remembered_install_dir(install_dir: str = "") -> str:
192
246
  return value
193
247
  except Exception:
194
248
  continue
249
+
250
+ # 前两处都写不了时(受限环境),状态会落在**安装目录里面**(第 ③ 处)。
251
+ # 那种情况下一轮不知道装在哪,所以直接去"默认安装目录"里看一眼 ——
252
+ # 受限环境下用到的几乎都是默认位置。找到之后仍有 marker 校验兜底。
253
+ try:
254
+ fallback_dir = default_install_dir()
255
+ except Exception:
256
+ return ""
257
+ found = _scan_state_dir(fallback_dir)
258
+ if found:
259
+ return found
260
+ # 用户用 --dir 装到了默认位置以外时,这里找不到就会回落到默认目录,
261
+ # 由调用方提示"要不要重新指定"(见 cli 的 auto 分支)。
195
262
  return ""
196
263
 
197
264
 
@@ -8,6 +8,7 @@
8
8
 
9
9
  import json
10
10
  import os
11
+ import re
11
12
  import subprocess
12
13
  import sys
13
14
  from typing import Callable, Dict, List, Optional
@@ -49,6 +50,65 @@ def check_python() -> None:
49
50
  sys.version_info[0], sys.version_info[1]))
50
51
 
51
52
 
53
+ # pip 的安全下限。低于它的 pip 内置 certifi 仍信任一批已出事的根/中间证书
54
+ # (CVE-2026-133949 / GHSA-jg88-vh4g-v698),在攻击者能站在网络路径上时
55
+ # 可能被伪造证书骗去装篡改过的包。这不是本项目特有的问题,但**首次装依赖
56
+ # 之前**至少要把它报出来,让用户知道风险、可以自己决定怎么办。
57
+ MIN_PIP_VERSION = (26, 2, 2)
58
+
59
+
60
+ def _parse_version(text: str) -> tuple:
61
+ """从 `pip 24.3.1 from ...` 里取出版本号元组;取不到返回空元组。"""
62
+ match = re.search(r"(\d+)\.(\d+)(?:\.(\d+))?", str(text or ""))
63
+ if not match:
64
+ return ()
65
+ parts = [int(match.group(1)), int(match.group(2))]
66
+ parts.append(int(match.group(3)) if match.group(3) else 0)
67
+ return tuple(parts)
68
+
69
+
70
+ def pip_version(python: str) -> tuple:
71
+ """读虚拟环境里的 pip 版本;读不到返回空元组。"""
72
+ try:
73
+ completed = subprocess.run([python, "-m", "pip", "--version"],
74
+ capture_output=True, text=True,
75
+ encoding="utf-8", errors="replace", timeout=60)
76
+ if completed.returncode != 0:
77
+ return ()
78
+ return _parse_version(completed.stdout)
79
+ except Exception:
80
+ return ()
81
+
82
+
83
+ def check_pip(python: str, progress: Optional[Callable[[str], None]] = None) -> dict:
84
+ """检查 pip 版本;太旧就**提示**(不静默强行升级)。
85
+
86
+ 为什么只是提示而不是自动升级:升级 pip 本身要联网下载一个包,
87
+ 在信任链有问题的情况下"自动去装一个包"反而扩大风险面。
88
+ 这里把版本和风险说清楚,选择权交给用户。
89
+
90
+ 返回 {version, ok, message}。
91
+ """
92
+ found = pip_version(python)
93
+ if not found:
94
+ return {"version": "", "ok": True, "message": ""}
95
+ text = ".".join(str(x) for x in found)
96
+ if found >= MIN_PIP_VERSION:
97
+ return {"version": text, "ok": True, "message": ""}
98
+ wanted = ".".join(str(x) for x in MIN_PIP_VERSION)
99
+ message = (
100
+ "pip 版本偏旧:%s(建议 %s 或更高)。\n"
101
+ " 低于 %s 的 pip 内置的证书库仍信任某些已出事的证书,\n"
102
+ " 在不可信网络里装依赖时可能被中间人伪造的包索引骗过。\n"
103
+ " 想升级可以执行:\n"
104
+ " \"%s\" -m pip install --upgrade pip\n"
105
+ " (不自动升级是刻意的:升级本身也要联网,把这个选择留给你)"
106
+ % (text, wanted, wanted, python))
107
+ if progress:
108
+ progress(message)
109
+ return {"version": text, "ok": False, "message": message}
110
+
111
+
52
112
  def ensure_venv(install_dir: str, progress: Optional[Callable[[str], None]] = None) -> str:
53
113
  """建好 `<安装目录>/.venv`,返回里面的 python 路径。已存在就直接用。"""
54
114
  python = paths.venv_python(install_dir)
@@ -87,12 +147,16 @@ def install_requirements(install_dir: str, python: str,
87
147
 
88
148
 
89
149
  def verify_dependencies(python: str) -> Dict[str, str]:
90
- """确认关键依赖真的能导入;返回 {包名: 版本}。"""
150
+ """确认关键依赖真的能导入;返回 {包名: 版本}。
151
+
152
+ PyYAML 也要查:插件的 metadata.yaml 靠它解析,缺了不报错但会**静默解析错**
153
+ (退回"只认 key: value"的兜底,YAML 多行块会读成字面量)。
154
+ """
91
155
  script = (
92
156
  "import json\n"
93
157
  "from importlib.metadata import version\n"
94
158
  "out = {}\n"
95
- "for name in ('Flask', 'Werkzeug', 'requests', 'websocket-client'):\n"
159
+ "for name in ('Flask', 'Werkzeug', 'requests', 'websocket-client', 'PyYAML'):\n"
96
160
  " try:\n"
97
161
  " out[name] = version(name)\n"
98
162
  " except Exception:\n"
@@ -115,23 +179,68 @@ def verify_dependencies(python: str) -> Dict[str, str]:
115
179
 
116
180
 
117
181
  def launch(install_dir: str, python: str, extra_args: Optional[List[str]] = None) -> int:
118
- """在当前进程里直接跑主程序(前台运行,Ctrl+C 退出)。"""
182
+ """在当前进程里直接跑主程序(前台运行,Ctrl+C 退出)。
183
+
184
+ **执行前再核一遍路径**:`python`(虚拟环境解释器)和 `run.py` 都必须
185
+ 真实落在 `install_dir` 里面。这样即便前面某处判断被绕过(比如状态文件、
186
+ marker 被伪造),也不会去执行安装目录外的程序。
187
+ """
119
188
  entry = os.path.join(install_dir, "run.py")
120
189
  if not os.path.exists(entry):
121
190
  raise SetupError("安装目录里找不到 run.py:%s" % install_dir)
191
+ root = os.path.realpath(os.path.abspath(install_dir))
192
+ for label, target in (("run.py", entry), ("虚拟环境解释器", python)):
193
+ real = os.path.realpath(os.path.abspath(target))
194
+ try:
195
+ inside = os.path.commonpath([root, real]) == root
196
+ except ValueError:
197
+ inside = False
198
+ if not inside:
199
+ raise SetupError(
200
+ "%s 不在安装目录里,拒绝执行:\n 安装目录 %s\n 实际路径 %s"
201
+ % (label, root, real))
122
202
  cmd = [python, entry] + list(extra_args or [])
123
203
  try:
124
204
  # 前台交接:让主程序直接接管这个终端(能看到彩色日志、能 Ctrl+C)
125
205
  return subprocess.call(cmd, cwd=install_dir)
126
206
  except KeyboardInterrupt:
127
207
  return 0
208
+ except OSError as exc:
209
+ # 解释器文件存在但跑不起来(损坏、架构不符、权限不足)
210
+ raise SetupError("启动失败:%s\n 解释器:%s" % (exc, python))
211
+
212
+
213
+ def _same_path(left: str, right: str) -> bool:
214
+ """两个路径是否指向同一个真实位置(消掉符号链接/大小写/相对路径差异)。"""
215
+ try:
216
+ a = os.path.realpath(os.path.abspath(left))
217
+ b = os.path.realpath(os.path.abspath(right))
218
+ except OSError:
219
+ return False
220
+ if os.name == "nt":
221
+ return a.lower() == b.lower()
222
+ return a == b
128
223
 
129
224
 
130
225
  def is_installed(install_dir: str) -> bool:
131
- """判断这个目录里是否已经装好了主程序。"""
226
+ """判断这个目录里是否已经装好了主程序。
227
+
228
+ **只检查文件存在是不够的**:marker 里记了 `install_dir`,必须和实际路径
229
+ 对得上才算数。否则任何人拿一份 marker + run.py 放到一个目录里,
230
+ 就会被当成"已安装" —— 自动模式随后会执行那个目录的 run.py(本地代码执行)。
231
+ """
132
232
  marker = os.path.join(install_dir, paths.MARKER_FILE)
133
233
  entry = os.path.join(install_dir, "run.py")
134
- return os.path.exists(marker) and os.path.exists(entry)
234
+ if not (os.path.exists(marker) and os.path.exists(entry)):
235
+ return False
236
+ # marker 与 run.py 本身是符号链接 → 不信任
237
+ if os.path.islink(marker) or os.path.islink(entry):
238
+ return False
239
+ data = read_marker(install_dir)
240
+ recorded = str(data.get("install_dir") or "")
241
+ if not recorded:
242
+ return False
243
+ return _same_path(recorded, install_dir)
135
244
 
136
245
 
137
246
  def read_marker(install_dir: str) -> Dict:
@@ -145,8 +254,9 @@ def read_marker(install_dir: str) -> Dict:
145
254
 
146
255
 
147
256
  def write_marker(install_dir: str, data: Dict) -> None:
257
+ """写安装记录。记录里存**规范化后的绝对路径**,供 `is_installed()` 校验。"""
148
258
  marker = os.path.join(install_dir, paths.MARKER_FILE)
149
259
  payload = dict(data or {})
150
- payload["install_dir"] = install_dir
260
+ payload["install_dir"] = os.path.realpath(os.path.abspath(install_dir))
151
261
  with open(marker, "w", encoding="utf-8") as handle:
152
262
  json.dump(payload, handle, ensure_ascii=False, indent=2)
@@ -148,21 +148,50 @@ def export_data(install_dir: str, target: str,
148
148
  progress("正在打包配置与数据 …")
149
149
  files = 0
150
150
  skipped: List[str] = []
151
+ root_real = os.path.realpath(os.path.abspath(install_dir))
152
+
153
+ def _safe_to_export(full: str) -> bool:
154
+ """这个文件能不能进备份包。
155
+
156
+ **符号链接一律拒绝**:链接指向可能是安装目录外的任意文件,
157
+ 打进备份后用户一分享就泄露了。用 `islink`(即 lstat 语义)而不是
158
+ `exists` —— 后者会跟随链接,看起来"存在"就把外部内容读进来了。
159
+ """
160
+ try:
161
+ if os.path.islink(full):
162
+ return False
163
+ real = os.path.realpath(full)
164
+ if os.path.commonpath([root_real, real]) != root_real:
165
+ return False
166
+ except (OSError, ValueError):
167
+ return False
168
+ return True
169
+
151
170
  try:
152
171
  with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED,
153
172
  compresslevel=6) as bundle:
154
- if os.path.exists(config):
155
- try:
156
- bundle.write(config, "config.json")
157
- files += 1
158
- except OSError:
159
- skipped.append("config.json")
173
+ if os.path.lexists(config):
174
+ if not _safe_to_export(config):
175
+ # 是符号链接或越界:不导,但要让用户知道
176
+ skipped.append("config.json(符号链接或越界,已跳过)")
177
+ else:
178
+ try:
179
+ bundle.write(config, "config.json")
180
+ files += 1
181
+ except OSError:
182
+ skipped.append("config.json")
160
183
  if os.path.isdir(data_dir):
161
184
  for base, dirs, names in os.walk(data_dir):
162
- dirs[:] = [d for d in dirs if d not in EXPORT_SKIP_DIRS]
185
+ # 目录这一层也挡:链接目录不进去(否则会遍历到外部)
186
+ dirs[:] = [d for d in dirs
187
+ if d not in EXPORT_SKIP_DIRS
188
+ and not os.path.islink(os.path.join(base, d))]
163
189
  for name in names:
164
190
  full = os.path.join(base, name)
165
191
  relative = os.path.relpath(full, install_dir).replace("\\", "/")
192
+ if not _safe_to_export(full):
193
+ skipped.append("%s(符号链接或越界,已跳过)" % relative)
194
+ continue
166
195
  try:
167
196
  bundle.write(full, relative)
168
197
  files += 1
@@ -198,23 +227,74 @@ def uninstall(install_dir: str, progress: Optional[Callable[[str], None]] = None
198
227
  install_dir = os.path.abspath(install_dir)
199
228
  if not os.path.isdir(install_dir):
200
229
  raise UninstallError("安装目录不存在:%s" % install_dir)
201
- # 安全检查:必须是本程序的安装目录
202
- looks_like_ours = (
203
- os.path.exists(os.path.join(install_dir, "run.py"))
204
- or os.path.exists(os.path.join(install_dir, paths.MARKER_FILE))
205
- or os.path.exists(os.path.join(install_dir, "config.json")))
206
- if not looks_like_ours:
230
+
231
+ # **安全检查:必须是本程序真正的安装目录**
232
+ #
233
+ # 以前这里是「run.py / 安装记录 / config.json 有一个就算」—— 太松了:
234
+ # `run.py` 和 `config.json` 都是很常见的文件名,用户 `--dir` 指错目录
235
+ # (比如某个恰好有 run.py 的项目)再带上 `-y`,就会把整个目录删掉。
236
+ #
237
+ # 现在要求:
238
+ # ① 有 `.qqbot-install.json`(启动器自己的安装记录);
239
+ # ② 记录里的 install_dir 与目标路径指向同一个真实位置;
240
+ # ③ run.py 也在,且不是符号链接。
241
+ # 三条同时满足才算「是本程序的安装目录」。
242
+ marker_file = os.path.join(install_dir, paths.MARKER_FILE)
243
+ entry_file = os.path.join(install_dir, "run.py")
244
+ if not os.path.exists(marker_file):
207
245
  raise UninstallError(
208
- "这个目录看起来不是 QQBotMerged 的安装目录(没有 run.py / 安装记录),"
209
- "为安全起见没有删除:%s" % install_dir)
210
- # 再挡一次:不允许删到根目录/盘符/用户主目录
211
- guarded = {os.path.abspath(os.sep), os.path.abspath(os.path.expanduser("~"))}
246
+ "这个目录没有 QQBotMerged 的安装记录(%s),无法确认是本程序的安装目录,"
247
+ "为安全起见没有删除:\n %s\n"
248
+ "如果确实要删,请手动删除这个目录。"
249
+ % (paths.MARKER_FILE, install_dir))
250
+ if os.path.islink(marker_file):
251
+ raise UninstallError("安装记录是符号链接,拒绝据此删除:%s" % marker_file)
252
+
253
+ import json as _json
254
+ try:
255
+ with open(marker_file, "r", encoding="utf-8") as handle:
256
+ recorded_data = _json.load(handle)
257
+ recorded = str((recorded_data or {}).get("install_dir") or "")
258
+ except Exception:
259
+ raise UninstallError("安装记录读不出来(可能已损坏),为安全起见没有删除:\n"
260
+ " %s" % marker_file)
261
+ if not recorded:
262
+ raise UninstallError("安装记录里没有 install_dir,无法确认是本程序的安装目录,"
263
+ "没有删除:\n %s" % install_dir)
264
+ # 用真实路径比较:消掉符号链接、大小写、相对路径带来的差异
265
+ real_target = os.path.realpath(install_dir)
266
+ real_recorded = os.path.realpath(os.path.abspath(recorded))
267
+ if os.name == "nt":
268
+ same = real_target.lower() == real_recorded.lower()
269
+ else:
270
+ same = real_target == real_recorded
271
+ if not same:
272
+ raise UninstallError(
273
+ "安装记录指向的是别的目录,拒绝删除:\n"
274
+ " 要删的 %s\n 记录里是 %s\n"
275
+ "(如果这是从别处复制来的安装记录,这个目录不是有效的安装。)"
276
+ % (real_target, real_recorded))
277
+ if not os.path.exists(entry_file) or os.path.islink(entry_file):
278
+ raise UninstallError("安装目录里没有正常的 run.py,拒绝删除:\n %s"
279
+ % install_dir)
280
+
281
+ # 再挡一次:不允许删到根目录/盘符/用户主目录(用真实路径比较,
282
+ # 这样符号链接指向这些位置时也能挡住)
283
+ guarded = {
284
+ os.path.realpath(os.sep),
285
+ os.path.abspath(os.sep),
286
+ os.path.realpath(os.path.expanduser("~")),
287
+ os.path.abspath(os.path.expanduser("~")),
288
+ }
212
289
  try:
213
- guarded.add(os.path.abspath(os.path.dirname(os.path.expanduser("~"))))
290
+ home_parent = os.path.expanduser("~")
291
+ guarded.add(os.path.realpath(os.path.dirname(home_parent)))
292
+ guarded.add(os.path.abspath(os.path.dirname(home_parent)))
214
293
  except Exception:
215
294
  pass
216
- if install_dir in guarded or len(install_dir) <= 3:
217
- raise UninstallError("拒绝删除这个路径(太靠近根目录):%s" % install_dir)
295
+ if (real_target in guarded or os.path.abspath(install_dir) in guarded
296
+ or len(real_target) <= 3):
297
+ raise UninstallError("拒绝删除这个路径(太靠近根目录):%s" % real_target)
218
298
 
219
299
  if progress:
220
300
  progress("正在删除 …")
@@ -137,7 +137,14 @@ def run_wizard(install_dir: str, tag: str = "",
137
137
 
138
138
 
139
139
  def write_config(install_dir: str, config: Dict) -> str:
140
- """写 config.json;已有的先备份一份。返回文件路径。"""
140
+ """写 config.json;已有的先备份一份。返回文件路径。
141
+
142
+ **文件里是机器人的 AppSecret、AI 的 API Key 和后台访问令牌**,
143
+ 所以不能按默认 umask(常见 022)建成 0644 —— 共享主机上别的本地用户
144
+ 就能读到。POSIX 下用 `os.open(..., 0o600)` 一步创建,不留中间窗口;
145
+ Windows 上 `os.open` 的 mode 不影响 ACL,退化为普通写(那边的权限
146
+ 由目录 ACL 决定,不是 umask)。
147
+ """
141
148
  target = os.path.join(install_dir, "config.json")
142
149
  if os.path.exists(target):
143
150
  backup = target + ".bak"
@@ -146,8 +153,20 @@ def write_config(install_dir: str, config: Dict) -> str:
146
153
  print(" 原 config.json 已备份为 config.json.bak")
147
154
  except OSError:
148
155
  pass
149
- with open(target, "w", encoding="utf-8") as handle:
150
- json.dump(config, handle, ensure_ascii=False, indent=2)
156
+ payload = json.dumps(config, ensure_ascii=False, indent=2)
157
+ if os.name == "nt":
158
+ with open(target, "w", encoding="utf-8") as handle:
159
+ handle.write(payload)
160
+ else:
161
+ # 0600:只有自己能读写。O_TRUNC 保证覆盖旧内容。
162
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
163
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
164
+ handle.write(payload)
165
+ # 文件已存在时 O_CREAT 不会改权限,这里补一次
166
+ try:
167
+ os.chmod(target, 0o600)
168
+ except OSError:
169
+ pass
151
170
  return target
152
171
 
153
172
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes