qqbot-cli 1.0.1__tar.gz → 1.0.3__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.
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/PKG-INFO +2 -2
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/pyproject.toml +8 -3
- qqbot_cli-1.0.3/qqbot_cli/PACKAGING.md +119 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/__init__.py +1 -1
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/cli.py +76 -1
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/fetch.py +172 -15
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/paths.py +99 -32
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/runner.py +116 -6
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/uninstall.py +100 -20
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/wizard.py +22 -3
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli.egg-info/SOURCES.txt +1 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/LICENSE +0 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/MANIFEST.in +0 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/PACKAGING.md +0 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/README.md +0 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/qqbot_cli/py.typed +0 -0
- {qqbot_cli-1.0.1 → qqbot_cli-1.0.3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: qqbot-cli
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.3
|
|
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.
|
|
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.
|
|
7
|
+
version = "1.0.3"
|
|
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.
|
|
31
|
+
dependencies = ["requests>=2.32.4"]
|
|
32
32
|
|
|
33
33
|
[project.optional-dependencies]
|
|
34
34
|
dev = ["pytest>=7"]
|
|
@@ -49,4 +49,9 @@ qqbot = "qqbot_cli.cli:main"
|
|
|
49
49
|
packages = ["qqbot_cli"]
|
|
50
50
|
|
|
51
51
|
[tool.setuptools.package-data]
|
|
52
|
-
qqbot_cli = [
|
|
52
|
+
qqbot_cli = [
|
|
53
|
+
"py.typed",
|
|
54
|
+
# 包里也放一份启动器说明:装完后用户在本地就能读到(命令、卸载、常见问题),
|
|
55
|
+
# 不用回 GitHub 找。内容与仓库根的 PACKAGING.md 相同,有测试校验一致性。
|
|
56
|
+
"PACKAGING.md",
|
|
57
|
+
]
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# QQBotMerged 启动器(`qqbot-cli`)
|
|
2
|
+
|
|
3
|
+
一条命令装好并运行 [QQBotMerged](https://github.com/L-web666/QQBotMerged) —— 一个可多开的
|
|
4
|
+
QQ 官方机器人后台。
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pipx install qqbot-cli # 或: pip install --user qqbot-cli
|
|
8
|
+
qqbot
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
第一次运行会依次完成:**选安装目录 → 下载最新版 → 建虚拟环境 → 装依赖 → 几个必填项 → 启动**。
|
|
12
|
+
之后再运行 `qqbot` 就是直接启动。
|
|
13
|
+
|
|
14
|
+
**安装目录由你自己选**:向导第一步就问(直接回车用默认的 `~/QQBotMerged`),
|
|
15
|
+
也可以一开始就用 `--dir` 指定。配置、数据、日志都在这个目录里,
|
|
16
|
+
想查看或改东西直接打开它即可 —— 装完向导会把 `cd` 命令打印出来。
|
|
17
|
+
|
|
18
|
+
## 命令
|
|
19
|
+
|
|
20
|
+
| 命令 | 作用 |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `qqbot` | 没装过就走向导,装过了就直接启动 |
|
|
23
|
+
| `qqbot init` | 重新走向导(不会删 `data/` 里的数据) |
|
|
24
|
+
| `qqbot run` | 只启动,不问任何问题 |
|
|
25
|
+
| `qqbot export` | 把 `config.json` 和 `data/` 导出成 zip 备份 |
|
|
26
|
+
| `qqbot uninstall` | 卸载(会问要不要先导出数据) |
|
|
27
|
+
| `qqbot --dir D:\bots\qq` | 直接指定安装目录(不追问;可以在一台机器上装多份) |
|
|
28
|
+
| `qqbot --upgrade` | 重新下载最新版,保留 `config.json` 和 `data/` |
|
|
29
|
+
| `qqbot --version` | 显示启动器版本 |
|
|
30
|
+
|
|
31
|
+
安装目录会被**记住**,所以之后直接 `qqbot` 就能找到它;要换一份就用 `--dir`。
|
|
32
|
+
|
|
33
|
+
### 卸载
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
qqbot uninstall
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
会先列出装了什么、占多大,然后问:
|
|
40
|
+
|
|
41
|
+
1. **要不要先导出 `config.json` 和 `data/`?**(默认要)
|
|
42
|
+
导出成一个 zip,里面**只有**这两样 —— 不含程序代码、不含 `.venv`、不含 `__pycache__`。
|
|
43
|
+
2. **确认删除吗?**(默认否)
|
|
44
|
+
|
|
45
|
+
只想备份不卸载就 `qqbot export`:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
qqbot export # 导到安装目录旁边的 xxx-backup-时间.zip
|
|
49
|
+
qqbot export --output D:\bak.zip # 指定位置
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
脚本里用可以跳过询问:`qqbot uninstall --no-export -y`。
|
|
53
|
+
|
|
54
|
+
**恢复**:把备份解压回一个目录,`qqbot --dir <那个目录> run` 就能继续用。
|
|
55
|
+
|
|
56
|
+
> 装了启动器不等于装了程序:`pipx uninstall qqbot-cli` 只移除启动器本身,
|
|
57
|
+
> 各安装目录里的程序和数据都不动。
|
|
58
|
+
|
|
59
|
+
## 支持的系统
|
|
60
|
+
|
|
61
|
+
| 系统 | 支持 | 说明 |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| Windows 10/11 | ✅ | `cd /d`、`Scripts\python.exe`、`activate.bat` |
|
|
64
|
+
| Linux | ✅ | `cd`、`bin/python`、`source activate` |
|
|
65
|
+
| macOS | ✅ | 同 Linux |
|
|
66
|
+
|
|
67
|
+
要求 Python **3.9+**(Werkzeug 3.1.9 的要求)。
|
|
68
|
+
Linux 上如果建不了虚拟环境,装一下系统包:`apt install python3-venv`。
|
|
69
|
+
|
|
70
|
+
## 它做了什么、没做什么
|
|
71
|
+
|
|
72
|
+
**做了什么**
|
|
73
|
+
|
|
74
|
+
- **先问装到哪个目录**(回车用默认值;相对路径按当前目录解析;带引号也能识别)。
|
|
75
|
+
目录里已有别的东西时会先提示、要求确认,不会闷头覆盖
|
|
76
|
+
- 从 GitHub Release 下载**正式版**(自动跳过草稿和预发布),校验大小上限、限制成员数、
|
|
77
|
+
拒绝绝对路径与 `..`,防止压缩包搞坏事
|
|
78
|
+
- 在安装目录里建一个 `.venv`,把主程序的依赖装进去 —— **不污染你的系统 Python**
|
|
79
|
+
- 问几个必填项(AppID / AppSecret / AI 配置 / 端口),生成 `config.json`;
|
|
80
|
+
**留空也能装完**,之后在网页「设置」里改
|
|
81
|
+
- 自动生成网页访问令牌,装完直接打印带令牌的地址
|
|
82
|
+
- 用 `<安装目录>/.venv` 里的 python 跑 `run.py`
|
|
83
|
+
|
|
84
|
+
**没做什么**
|
|
85
|
+
|
|
86
|
+
- **不修改主程序的任何代码**:拉下来就是原来那个完整项目目录,
|
|
87
|
+
它的自动更新、插件、云同步全都照常工作
|
|
88
|
+
- 不接管主程序的配置:主程序启动时会按自己的 schema 补全缺项
|
|
89
|
+
- 程序和数据都在你选的安装目录里,删目录即卸载;
|
|
90
|
+
启动器只在系统配置目录里留一个小文件,记住「上次装在哪」
|
|
91
|
+
(`qqbot uninstall` 会一并清掉,删掉也不影响使用 —— 只是得用 `--dir` 指定目录)
|
|
92
|
+
|
|
93
|
+
## 为什么装进虚拟环境
|
|
94
|
+
|
|
95
|
+
主程序需要 `Werkzeug>=3.1.9`(一个安全修复版本)。直接装进系统 Python 可能和已有包冲突,
|
|
96
|
+
也可能因为版本不对起不来。每个安装目录一个 `.venv`,互不干扰。
|
|
97
|
+
|
|
98
|
+
启动器自己只依赖 `requests`,所以适合用 `pipx` 装(和 NoneBot 的 `nb-cli` 一样):
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
pipx install qqbot-cli
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## 目录结构
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
<安装目录>/
|
|
108
|
+
├── run.py ← 主程序入口
|
|
109
|
+
├── config.json ← 启动器向导生成的,之后由主程序读写
|
|
110
|
+
├── core/ web/ ... ← 主程序代码(随版本更新整体替换)
|
|
111
|
+
├── data/ ← 你的数据(消息库、媒体、日志)—— 更新时保留
|
|
112
|
+
├── plugins/ ← 插件
|
|
113
|
+
├── .venv/ ← 这个安装专用的虚拟环境
|
|
114
|
+
└── .qqbot-install.json ← 启动器的安装记录(版本、sha256)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## 许可证
|
|
118
|
+
|
|
119
|
+
AGPL-3.0(与主程序一致)。
|
|
@@ -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("依赖安装完成")
|
|
@@ -217,6 +278,9 @@ def do_install(install_dir: str = "", force_wizard: bool = False,
|
|
|
217
278
|
"sha256": result.get("sha256") or "",
|
|
218
279
|
"cli_version": __version__,
|
|
219
280
|
"needs_config": True,
|
|
281
|
+
"python": "%d.%d.%d" % sys.version_info[:3],
|
|
282
|
+
"pip": pip_info.get("version") or "",
|
|
283
|
+
"dependencies": versions,
|
|
220
284
|
})
|
|
221
285
|
paths.remember_install_dir(install_dir)
|
|
222
286
|
_info("向导已取消,程序文件已经装好了。")
|
|
@@ -233,6 +297,10 @@ def do_install(install_dir: str = "", force_wizard: bool = False,
|
|
|
233
297
|
"tag": tag,
|
|
234
298
|
"sha256": result.get("sha256") or "",
|
|
235
299
|
"cli_version": __version__,
|
|
300
|
+
# 把运行环境记下来:审计和安全排查时不用再猜装的是什么版本
|
|
301
|
+
"python": "%d.%d.%d" % sys.version_info[:3],
|
|
302
|
+
"pip": pip_info.get("version") or "",
|
|
303
|
+
"dependencies": versions,
|
|
236
304
|
})
|
|
237
305
|
# 记下装到了哪:下次 `qqbot` 不带参数就知道去哪启动
|
|
238
306
|
paths.remember_install_dir(install_dir)
|
|
@@ -433,10 +501,17 @@ def do_uninstall(install_dir: str, export: Optional[bool] = None,
|
|
|
433
501
|
|
|
434
502
|
# ---------------------------------------------------------------- 入口
|
|
435
503
|
def build_parser() -> argparse.ArgumentParser:
|
|
504
|
+
# 完整说明随包一起装着(qqbot_cli/PACKAGING.md),把路径打在帮助末尾,
|
|
505
|
+
# 用户不用回 GitHub 找。
|
|
506
|
+
doc_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
507
|
+
"PACKAGING.md")
|
|
508
|
+
doc_hint = ""
|
|
509
|
+
if os.path.exists(doc_path):
|
|
510
|
+
doc_hint = "\n完整说明:%s" % doc_path
|
|
436
511
|
parser = argparse.ArgumentParser(
|
|
437
512
|
prog="qqbot",
|
|
438
513
|
description="QQBotMerged 启动器:下载程序、建环境、走向导、启动、卸载。",
|
|
439
|
-
epilog="不给子命令时:没装过就走向导,装过了就直接启动。",
|
|
514
|
+
epilog="不给子命令时:没装过就走向导,装过了就直接启动。" + doc_hint,
|
|
440
515
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
441
516
|
parser.add_argument("command", nargs="?", default="auto",
|
|
442
517
|
choices=["auto", "init", "run", "export", "uninstall",
|
|
@@ -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
|
|
48
|
-
raise FetchError("只允许
|
|
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 =
|
|
60
|
-
|
|
61
|
-
|
|
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 =
|
|
120
|
-
|
|
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
|
|
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.
|
|
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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
-
"
|
|
209
|
-
"
|
|
210
|
-
|
|
211
|
-
|
|
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
|
-
|
|
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
|
|
217
|
-
|
|
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
|
-
|
|
150
|
-
|
|
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
|