norain 0.2.0__py3-none-any.whl

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.
Files changed (53) hide show
  1. norain/__init__.py +3 -0
  2. norain/__main__.py +5 -0
  3. norain/block.py +281 -0
  4. norain/boot.py +142 -0
  5. norain/cli.py +748 -0
  6. norain/control.py +703 -0
  7. norain/defaults.py +42 -0
  8. norain/generate.py +264 -0
  9. norain/install.py +312 -0
  10. norain/maintain.py +313 -0
  11. norain/model.py +409 -0
  12. norain/monitor.py +314 -0
  13. norain/paths.py +124 -0
  14. norain/probe.py +158 -0
  15. norain/proxy.py +136 -0
  16. norain/repair.py +278 -0
  17. norain/routing.py +332 -0
  18. norain/rules.py +214 -0
  19. norain/runner.py +59 -0
  20. norain-0.2.0.dist-info/METADATA +111 -0
  21. norain-0.2.0.dist-info/RECORD +53 -0
  22. norain-0.2.0.dist-info/WHEEL +5 -0
  23. norain-0.2.0.dist-info/entry_points.txt +3 -0
  24. norain-0.2.0.dist-info/licenses/LICENSE +21 -0
  25. norain-0.2.0.dist-info/top_level.txt +3 -0
  26. norain_core/__init__.py +4 -0
  27. norain_core/apply.py +70 -0
  28. norain_core/atomic.py +80 -0
  29. norain_core/cliutil.py +68 -0
  30. norain_core/daemonctl.py +192 -0
  31. norain_core/errors.py +60 -0
  32. norain_core/fetch.py +158 -0
  33. norain_core/log.py +104 -0
  34. norain_core/migrate.py +86 -0
  35. norain_core/osutil.py +332 -0
  36. norain_core/redact.py +60 -0
  37. norain_core/secrets.py +87 -0
  38. norain_core/singbox.py +93 -0
  39. norain_core/state.py +97 -0
  40. norain_core/supervisor.py +352 -0
  41. norain_core/sysproxy.py +112 -0
  42. norain_core/tomlio.py +86 -0
  43. norain_server/__init__.py +3 -0
  44. norain_server/__main__.py +5 -0
  45. norain_server/cert.py +276 -0
  46. norain_server/cli.py +477 -0
  47. norain_server/deploy.py +604 -0
  48. norain_server/firewall.py +226 -0
  49. norain_server/generate.py +112 -0
  50. norain_server/model.py +272 -0
  51. norain_server/paths.py +101 -0
  52. norain_server/runner.py +123 -0
  53. norain_server/service.py +83 -0
norain/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Norain 客户端。模块划分见 HANDOFF.md。"""
2
+
3
+ __version__ = "0.2.0"
norain/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
norain/block.py ADDED
@@ -0,0 +1,281 @@
1
+ """阻断模块:代理无法维持时切断除蓝名单以外的全部出站连接,防止回落直连暴露真实 IP。
2
+
3
+ 行为以最初目标为准(docs/decisions/0011 修订):自维持模块修复失败后自动进入阻断,弹窗提醒并给出
4
+ 可能原因,同时结束其他模块;启动模块运行时自动恢复;也可以用命令行手动解除(解除不代表代理已修好)。
5
+
6
+ 安全措施(只防硬性故障,不改变行为):
7
+ - 规则放在自己的空间里:Windows 用固定前缀 `Norain-Block-` 的规则,Linux 用独立的
8
+ nftables 表 `inet norain_block`。不改系统默认策略,不碰用户的其他规则。
9
+ - 先写状态文件再应用规则,应用失败自动回滚。
10
+ - 解除只读本地状态文件,不需要网络,也不依赖其他模块在运行。状态文件里写有不依赖 Norain 的
11
+ 手工恢复命令。
12
+
13
+ 放行范围:回环、链路本地、DHCP/组播、(可选)局域网、代理服务器、国内 DNS、蓝名单
14
+ (routing.isolation_allowlist)、监控模块的国内检测目标(让监控在阻断期间仍能判断本地网络)。
15
+ 域名在进入阻断时解析成 IP;之后对端换 IP 需要重新进入阻断才会更新。
16
+
17
+ Windows 的实现方式:阻断规则优先于放行规则,所以为「放行范围的补集」建出站阻断规则。
18
+ 这两套命令均未在真实系统上验证。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import ipaddress
24
+ import json
25
+ import socket
26
+ import time
27
+ from urllib.parse import urlsplit
28
+
29
+ from norain_core import osutil
30
+ from norain_core.errors import EXIT_EXTERNAL, NorainError
31
+ from norain_core.log import Logger
32
+ from norain_core.state import read_json, write_json
33
+
34
+ from .model import ClientConfig, split_entries
35
+ from .monitor import GUESS, MEANING
36
+ from .paths import Paths
37
+
38
+ PREFIX = "Norain-Block-"
39
+ NFT_TABLE = "norain_block"
40
+ _CHUNK = 60 # 每条 Windows 规则里的地址段数量上限(控制命令行长度)
41
+
42
+ MANUAL_RESTORE = {
43
+ "nt": "powershell -Command \"Get-NetFirewallRule -DisplayName 'Norain-Block-*' | Remove-NetFirewallRule\"",
44
+ "posix": f"nft delete table inet {NFT_TABLE}",
45
+ }
46
+
47
+ _BASE4 = ["127.0.0.0/8", "169.254.0.0/16", "224.0.0.0/4", "255.255.255.255/32", "0.0.0.0/32"]
48
+ _BASE6 = ["::1/128", "fe80::/10", "ff00::/8", "::/128"]
49
+ _LAN4 = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
50
+ _LAN6 = ["fc00::/7"]
51
+
52
+
53
+ # ---- 放行范围 ------------------------------------------------------------------
54
+
55
+ def _resolve(host: str) -> list[str]:
56
+ try:
57
+ return sorted({ai[4][0].split("%")[0] for ai in socket.getaddrinfo(host, None)})
58
+ except OSError:
59
+ return []
60
+
61
+
62
+ def allowed(cfg: ClientConfig) -> tuple[list, list, dict]:
63
+ """返回 (IPv4 网段, IPv6 网段, 说明)。说明里记录每个域名解析到了什么、哪些没解析出来。"""
64
+ nets: list = [ipaddress.ip_network(n) for n in _BASE4 + _BASE6]
65
+ if cfg.routing.allow_lan_in_isolation:
66
+ nets += [ipaddress.ip_network(n) for n in _LAN4 + _LAN6]
67
+ notes: dict = {"resolved": {}, "unresolved": []}
68
+
69
+ def add_host(host: str) -> None:
70
+ try:
71
+ nets.append(ipaddress.ip_network(host, strict=False))
72
+ return
73
+ except ValueError:
74
+ pass
75
+ ips = _resolve(host)
76
+ if ips:
77
+ notes["resolved"][host] = ips
78
+ nets.extend(ipaddress.ip_network(ip) for ip in ips)
79
+ else:
80
+ notes["unresolved"].append(host)
81
+
82
+ add_host(cfg.proxy.server)
83
+ add_host(cfg.dns.domestic)
84
+ m = split_entries(cfg.routing.isolation_allowlist)
85
+ for e in m.get("ip_cidr", []) + m.get("domain", []) + m.get("domain_suffix", []):
86
+ add_host(e)
87
+ for url in cfg.monitor.domestic_targets: # 绕过监控模块
88
+ host = urlsplit(url).hostname
89
+ if host:
90
+ add_host(host)
91
+ v4 = list(ipaddress.collapse_addresses(n for n in nets if n.version == 4))
92
+ v6 = list(ipaddress.collapse_addresses(n for n in nets if n.version == 6))
93
+ return v4, v6, notes
94
+
95
+
96
+ def complement(nets: list, version: int) -> list[tuple[str, str]]:
97
+ """放行网段的补集,写成 [起始地址, 结束地址] 的列表。"""
98
+ cls = ipaddress.IPv4Address if version == 4 else ipaddress.IPv6Address
99
+ top = int(cls("255.255.255.255" if version == 4 else "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"))
100
+ out, cursor = [], 0
101
+ for n in sorted(nets, key=lambda n: int(n.network_address)):
102
+ lo, hi = int(n.network_address), int(n.broadcast_address)
103
+ if lo > cursor:
104
+ out.append((str(cls(cursor)), str(cls(lo - 1))))
105
+ cursor = max(cursor, hi + 1)
106
+ if cursor <= top:
107
+ out.append((str(cls(cursor)), str(cls(top))))
108
+ return out
109
+
110
+
111
+ # ---- 后端 ----------------------------------------------------------------------
112
+
113
+ class WindowsBackend:
114
+ name = "windows-firewall"
115
+
116
+ def snapshot(self) -> dict:
117
+ proc = osutil.powershell("Get-NetFirewallProfile | Select-Object Name,Enabled | ConvertTo-Json -Compress")
118
+ try:
119
+ rows = json.loads(proc.stdout or "[]")
120
+ except ValueError:
121
+ rows = []
122
+ rows = rows if isinstance(rows, list) else [rows]
123
+ # Enabled 可能序列化成布尔、0/1 或 "True"/"False"
124
+ return {r["Name"]: str(r.get("Enabled")).lower() in ("true", "1") for r in rows if "Name" in r}
125
+
126
+ def apply(self, v4: list, v6: list) -> list[str]:
127
+ names: list[str] = []
128
+ for ver, nets in ((4, v4), (6, v6)):
129
+ ranges = complement(nets, ver)
130
+ for i in range(0, len(ranges), _CHUNK):
131
+ name = f"{PREFIX}v{ver}-{i // _CHUNK}"
132
+ remote = ",".join(a if a == b else f"{a}-{b}" for a, b in ranges[i:i + _CHUNK])
133
+ osutil.run_checked(["netsh", "advfirewall", "firewall", "add", "rule", f"name={name}",
134
+ "dir=out", "action=block", "enable=yes", "profile=any",
135
+ f"remoteip={remote}"], what="添加阻断规则", module="block")
136
+ names.append(name)
137
+ # 防火墙被关掉时规则不生效:记下原状态后打开,解除时还原
138
+ osutil.run_checked(["netsh", "advfirewall", "set", "allprofiles", "state", "on"],
139
+ what="启用 Windows 防火墙", module="block")
140
+ return names
141
+
142
+ def remove(self, state: dict) -> list[str]:
143
+ errors = []
144
+ proc = osutil.powershell(f"Get-NetFirewallRule -DisplayName '{PREFIX}*' -ErrorAction SilentlyContinue "
145
+ "| Remove-NetFirewallRule")
146
+ if proc.returncode != 0:
147
+ # PowerShell 不可用时逐条用 netsh 删除记录在案的规则
148
+ for name in state.get("rules", []):
149
+ p = osutil.run(["netsh", "advfirewall", "firewall", "delete", "rule", f"name={name}"])
150
+ if p.returncode != 0 and "No rules match" not in p.stdout and "没有与" not in p.stdout:
151
+ errors.append(f"删除规则 {name} 失败:{(p.stderr or p.stdout).strip()[:200]}")
152
+ for profile, enabled in (state.get("firewall_profiles") or {}).items():
153
+ if not enabled:
154
+ osutil.run(["netsh", "advfirewall", "set", f"{profile.lower()}profile", "state", "off"])
155
+ return errors
156
+
157
+ def present(self) -> bool:
158
+ proc = osutil.powershell(f"@(Get-NetFirewallRule -DisplayName '{PREFIX}*' -ErrorAction SilentlyContinue).Count")
159
+ return proc.returncode == 0 and proc.stdout.strip() not in ("", "0")
160
+
161
+
162
+ class NftBackend:
163
+ name = "nftables"
164
+
165
+ def snapshot(self) -> dict:
166
+ return {}
167
+
168
+ def apply(self, v4: list, v6: list) -> list[str]:
169
+ def elems(nets) -> str:
170
+ return ", ".join(str(n) for n in nets)
171
+ script = (
172
+ f"table inet {NFT_TABLE} {{}}\n" # 保证下一行的 delete 不会因为表不存在而失败
173
+ f"delete table inet {NFT_TABLE}\n"
174
+ f"table inet {NFT_TABLE} {{\n"
175
+ " chain output {\n"
176
+ " type filter hook output priority -10; policy drop;\n"
177
+ ' oifname "lo" accept\n'
178
+ " udp sport 68 udp dport 67 accept\n"
179
+ + (f" ip daddr {{ {elems(v4)} }} accept\n" if v4 else "")
180
+ + (f" ip6 daddr {{ {elems(v6)} }} accept\n" if v6 else "")
181
+ + " }\n}\n")
182
+ proc = osutil.run(["nft", "-f", "-"], input_text=script, timeout=30)
183
+ if proc.returncode != 0:
184
+ raise NorainError(f"应用 nftables 规则失败:{(proc.stderr or proc.stdout).strip()[:400]}",
185
+ exit_code=EXIT_EXTERNAL, module="block",
186
+ hint="需要 root 权限和 nftables")
187
+ return [f"inet {NFT_TABLE}"]
188
+
189
+ def remove(self, state: dict) -> list[str]:
190
+ proc = osutil.run(["nft", "delete", "table", "inet", NFT_TABLE])
191
+ if proc.returncode != 0 and self.present():
192
+ return [f"删除 nftables 表失败:{(proc.stderr or proc.stdout).strip()[:200]}"]
193
+ return []
194
+
195
+ def present(self) -> bool:
196
+ return osutil.run(["nft", "list", "table", "inet", NFT_TABLE]).returncode == 0
197
+
198
+
199
+ def backend():
200
+ return WindowsBackend() if osutil.IS_WINDOWS else NftBackend()
201
+
202
+
203
+ # ---- 状态 ----------------------------------------------------------------------
204
+
205
+ def state(paths: Paths) -> dict | None:
206
+ return read_json(paths.block_state)
207
+
208
+
209
+ def is_active(paths: Paths) -> bool:
210
+ return bool((state(paths) or {}).get("active"))
211
+
212
+
213
+ def status(paths: Paths) -> dict:
214
+ st = state(paths) or {}
215
+ return {"active": bool(st.get("active")), "engaged_at": st.get("engaged_at"), "code": st.get("code"),
216
+ "reason": st.get("reason"), "guesses": st.get("guesses", []), "backend": st.get("backend"),
217
+ "allowed": st.get("allowed", []), "unresolved": st.get("unresolved", []),
218
+ "restore_command": "norain block off",
219
+ "manual_restore": MANUAL_RESTORE["nt" if osutil.IS_WINDOWS else "posix"]}
220
+
221
+
222
+ def message(code: int, reason: str) -> str:
223
+ guesses = GUESS.get(code, ["代理进程无法启动或反复崩溃", "配置或程序文件损坏"])
224
+ return ("代理无法正常工作,为防止真实 IP 暴露,已切断除蓝名单以外的网络连接。\n\n"
225
+ f"错误码:{code}({MEANING.get(code, '代理无法维持')})\n"
226
+ + (f"依据:{reason}\n" if reason else "")
227
+ + "可能原因:\n" + "".join(f" · {g}\n" for g in guesses)
228
+ + "\n恢复网络:在管理员终端运行 norain block off\n"
229
+ "重新启动代理:norain start(启动时会自动解除阻断)\n"
230
+ "注意:解除阻断不代表代理已修复,解除后流量会直连。")
231
+
232
+
233
+ # ---- 进入与解除 ----------------------------------------------------------------
234
+
235
+ def engage(cfg: ClientConfig, paths: Paths, *, code: int, reason: str, log: Logger | None = None,
236
+ notify: bool = True) -> dict:
237
+ """进入阻断模式。失败时回滚并抛出错误(调用方要知道阻断没有生效)。"""
238
+ osutil.require_admin("进入阻断模式", module="block")
239
+ be = backend()
240
+ v4, v6, notes = allowed(cfg)
241
+ st = {
242
+ "active": True, "engaged_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "code": code, "reason": reason,
243
+ "guesses": GUESS.get(code, []), "backend": be.name, "rules": [],
244
+ "firewall_profiles": be.snapshot(),
245
+ "allowed": [str(n) for n in v4 + v6], "resolved": notes["resolved"], "unresolved": notes["unresolved"],
246
+ "restore_command": "norain block off",
247
+ "manual_restore": MANUAL_RESTORE["nt" if osutil.IS_WINDOWS else "posix"],
248
+ }
249
+ write_json(paths.block_state, st) # 先落盘:即使应用到一半崩溃,解除命令也知道要清理什么
250
+ try:
251
+ st["rules"] = be.apply(v4, v6)
252
+ except NorainError:
253
+ be.remove(st)
254
+ paths.block_state.unlink(missing_ok=True)
255
+ raise
256
+ write_json(paths.block_state, st)
257
+ if log:
258
+ log.error("block.engaged", code=code, reason=reason, backend=be.name, rules=len(st["rules"]),
259
+ unresolved=notes["unresolved"])
260
+ if notify:
261
+ text = message(code, reason)
262
+ if not osutil.popup("Norain 已进入阻断模式", text) and log:
263
+ log.error("block.popup_unavailable", text=text)
264
+ return st
265
+
266
+
267
+ def release(paths: Paths, *, log: Logger | None = None) -> dict:
268
+ """解除阻断,恢复正常的防火墙放行。幂等:没有状态文件时也会清理残留规则。"""
269
+ st = state(paths) or {}
270
+ be = backend()
271
+ if not st and not be.present():
272
+ return {"was_active": False, "errors": []}
273
+ osutil.require_admin("解除阻断", module="block")
274
+ errors = be.remove(st)
275
+ if errors:
276
+ raise NorainError("解除阻断没有完全成功:" + ";".join(errors), exit_code=EXIT_EXTERNAL, module="block",
277
+ hint="手工恢复命令:" + MANUAL_RESTORE["nt" if osutil.IS_WINDOWS else "posix"])
278
+ paths.block_state.unlink(missing_ok=True)
279
+ if log:
280
+ log.info("block.released", was_active=bool(st.get("active")))
281
+ return {"was_active": bool(st.get("active")), "errors": []}
norain/boot.py ADDED
@@ -0,0 +1,142 @@
1
+ """启动模块:开机自启动的注册,以及启动时的「测试检测模式」前半段。
2
+
3
+ 启动顺序(最初目标):
4
+ 1. 检查阻断模块的状态,如果处于阻断模式,先恢复为非阻断模式(pre_start);
5
+ 2. 依次拉起分流模块、代理模块、监控模块;
6
+ 3. 监控通过后激活互拉保活,启动自维持模块。
7
+ 第 2、3 步在内控制模块里执行(control.Controller.run),因为它们需要内控制审批。
8
+
9
+ 正常模式 / 安全模式:app.mode = "normal" 且 app.auto_start = true 时注册开机自启动;
10
+ "safe" 时不自启动,只能用 `norain start` 手动启动。
11
+
12
+ 自启动的实现:
13
+ Windows 登录时运行的计划任务(TUN 和防火墙需要管理员权限,所以用最高权限运行)
14
+ Linux systemd 单元:root 安装时是系统单元,否则是用户单元
15
+ 手动 stop 之后期望状态是 stopped,自启动入口检查到它就直接退出(docs/decisions/0013)。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import shutil
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ from norain_core import osutil
26
+ from norain_core.errors import EXIT_EXTERNAL, NorainError
27
+ from norain_core.log import Logger
28
+
29
+ from . import block
30
+ from .model import ClientConfig
31
+ from .paths import Paths
32
+
33
+ TASK_NAME = "Norain"
34
+ UNIT = "norain.service"
35
+
36
+ _UNIT_TEMPLATE = """\
37
+ # 由 norain 生成(启动模块)。手动 stop 之后期望状态为 stopped,`run --autostart` 会直接退出。
38
+ [Unit]
39
+ Description=Norain client
40
+ After=network-online.target
41
+ Wants=network-online.target
42
+
43
+ [Service]
44
+ Type=simple
45
+ {env}ExecStart={python} -m norain run --autostart
46
+ Restart=on-failure
47
+ RestartSec=5
48
+ # 3=配置无效 5=缺少 sing-box 9=已进入阻断或达到重启上限:再拉起也没用
49
+ RestartPreventExitStatus=3 5 9
50
+ KillMode=mixed
51
+ TimeoutStopSec=30
52
+
53
+ [Install]
54
+ WantedBy={target}
55
+ """
56
+
57
+
58
+ def _env(paths: Paths) -> dict[str, str]:
59
+ return {"NORAIN_HOME": str(paths.home), "NORAIN_CONFIG": str(paths.config),
60
+ "NORAIN_STATE": str(paths.state)}
61
+
62
+
63
+ def _unit_path(system: bool) -> Path:
64
+ if system:
65
+ return Path("/etc/systemd/system") / UNIT
66
+ return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "systemd" / "user" / UNIT
67
+
68
+
69
+ def _systemctl(system: bool, *args: str):
70
+ return osutil.run(["systemctl", *([] if system else ["--user"]), *args], timeout=30)
71
+
72
+
73
+ def register(paths: Paths, cfg: ClientConfig) -> str:
74
+ """注册开机自启动(幂等)。返回说明文字。"""
75
+ if osutil.IS_WINDOWS:
76
+ admin = osutil.is_admin()
77
+ if cfg.proxy.traffic_mode == "tun" and not admin:
78
+ raise NorainError("TUN 模式的开机自启动需要以管理员身份注册", exit_code=4, module="boot",
79
+ hint="在管理员终端里重新运行这条命令")
80
+ cmd = osutil.quote_cmd([osutil.python_exe(windowless=True), "-m", "norain", "boot", "--autostart"])
81
+ osutil.task_create(TASK_NAME, cmd, trigger="ONLOGON", highest=admin)
82
+ return f"计划任务 {TASK_NAME}(登录时运行{',最高权限' if admin else ''})"
83
+ if not shutil.which("systemctl"):
84
+ raise NorainError("没有 systemd,无法注册开机自启动", exit_code=EXIT_EXTERNAL, module="boot",
85
+ hint="可以把 `norain boot --autostart` 加到你的桌面环境的自启动项里")
86
+ system = osutil.is_admin()
87
+ unit = _unit_path(system)
88
+ unit.parent.mkdir(parents=True, exist_ok=True)
89
+ env = "".join(f'Environment="{k}={v}"\n' for k, v in _env(paths).items())
90
+ unit.write_text(_UNIT_TEMPLATE.format(env=env, python=sys.executable,
91
+ target="multi-user.target" if system else "default.target"),
92
+ encoding="utf-8")
93
+ _systemctl(system, "daemon-reload")
94
+ proc = _systemctl(system, "enable", UNIT)
95
+ if proc.returncode != 0:
96
+ raise NorainError(f"启用自启动失败:{(proc.stderr or proc.stdout).strip()[:300]}",
97
+ exit_code=EXIT_EXTERNAL, module="boot")
98
+ return f"systemd {'系统' if system else '用户'}单元 {unit}"
99
+
100
+
101
+ def unregister() -> list[str]:
102
+ done: list[str] = []
103
+ if osutil.IS_WINDOWS:
104
+ if osutil.task_delete(TASK_NAME):
105
+ done.append(f"删除计划任务 {TASK_NAME}")
106
+ return done
107
+ for system in (True, False):
108
+ unit = _unit_path(system)
109
+ if unit.exists():
110
+ _systemctl(system, "disable", UNIT)
111
+ try:
112
+ unit.unlink()
113
+ done.append(f"删除 {unit}")
114
+ except PermissionError:
115
+ raise NorainError(f"没有权限删除 {unit}", exit_code=4, module="boot",
116
+ hint="用 root 重新运行") from None
117
+ _systemctl(system, "daemon-reload")
118
+ return done
119
+
120
+
121
+ def registered() -> bool:
122
+ if osutil.IS_WINDOWS:
123
+ return osutil.task_exists(TASK_NAME)
124
+ return _unit_path(True).exists() or _unit_path(False).exists()
125
+
126
+
127
+ def sync(paths: Paths, cfg: ClientConfig) -> str:
128
+ """让自启动项与配置(正常模式 / 安全模式)一致。"""
129
+ if cfg.autostart_wanted:
130
+ return "已注册开机自启动:" + register(paths, cfg)
131
+ removed = unregister()
132
+ return "安全模式或已关闭自启动:" + (";".join(removed) if removed else "没有自启动项")
133
+
134
+
135
+ def pre_start(paths: Paths, log: Logger | None = None) -> dict:
136
+ """测试检测模式的第一步:处于阻断模式时自动恢复为非阻断模式。"""
137
+ if not block.is_active(paths) and not (paths.block_state.exists()):
138
+ return {"was_blocked": False}
139
+ res = block.release(paths, log=log)
140
+ if log:
141
+ log.info("boot.block_released", was_active=res["was_active"])
142
+ return {"was_blocked": res["was_active"]}