norain 0.2.0__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.
Files changed (72) hide show
  1. norain-0.2.0/LICENSE +21 -0
  2. norain-0.2.0/PKG-INFO +111 -0
  3. norain-0.2.0/README.md +79 -0
  4. norain-0.2.0/pyproject.toml +48 -0
  5. norain-0.2.0/setup.cfg +4 -0
  6. norain-0.2.0/src/norain/__init__.py +3 -0
  7. norain-0.2.0/src/norain/__main__.py +5 -0
  8. norain-0.2.0/src/norain/block.py +281 -0
  9. norain-0.2.0/src/norain/boot.py +142 -0
  10. norain-0.2.0/src/norain/cli.py +748 -0
  11. norain-0.2.0/src/norain/control.py +703 -0
  12. norain-0.2.0/src/norain/defaults.py +42 -0
  13. norain-0.2.0/src/norain/generate.py +264 -0
  14. norain-0.2.0/src/norain/install.py +312 -0
  15. norain-0.2.0/src/norain/maintain.py +313 -0
  16. norain-0.2.0/src/norain/model.py +409 -0
  17. norain-0.2.0/src/norain/monitor.py +314 -0
  18. norain-0.2.0/src/norain/paths.py +124 -0
  19. norain-0.2.0/src/norain/probe.py +158 -0
  20. norain-0.2.0/src/norain/proxy.py +136 -0
  21. norain-0.2.0/src/norain/repair.py +278 -0
  22. norain-0.2.0/src/norain/routing.py +332 -0
  23. norain-0.2.0/src/norain/rules.py +214 -0
  24. norain-0.2.0/src/norain/runner.py +59 -0
  25. norain-0.2.0/src/norain.egg-info/PKG-INFO +111 -0
  26. norain-0.2.0/src/norain.egg-info/SOURCES.txt +70 -0
  27. norain-0.2.0/src/norain.egg-info/dependency_links.txt +1 -0
  28. norain-0.2.0/src/norain.egg-info/entry_points.txt +3 -0
  29. norain-0.2.0/src/norain.egg-info/requires.txt +6 -0
  30. norain-0.2.0/src/norain.egg-info/top_level.txt +3 -0
  31. norain-0.2.0/src/norain_core/__init__.py +4 -0
  32. norain-0.2.0/src/norain_core/apply.py +70 -0
  33. norain-0.2.0/src/norain_core/atomic.py +80 -0
  34. norain-0.2.0/src/norain_core/cliutil.py +68 -0
  35. norain-0.2.0/src/norain_core/daemonctl.py +192 -0
  36. norain-0.2.0/src/norain_core/errors.py +60 -0
  37. norain-0.2.0/src/norain_core/fetch.py +158 -0
  38. norain-0.2.0/src/norain_core/log.py +104 -0
  39. norain-0.2.0/src/norain_core/migrate.py +86 -0
  40. norain-0.2.0/src/norain_core/osutil.py +332 -0
  41. norain-0.2.0/src/norain_core/redact.py +60 -0
  42. norain-0.2.0/src/norain_core/secrets.py +87 -0
  43. norain-0.2.0/src/norain_core/singbox.py +93 -0
  44. norain-0.2.0/src/norain_core/state.py +97 -0
  45. norain-0.2.0/src/norain_core/supervisor.py +352 -0
  46. norain-0.2.0/src/norain_core/sysproxy.py +112 -0
  47. norain-0.2.0/src/norain_core/tomlio.py +86 -0
  48. norain-0.2.0/src/norain_server/__init__.py +3 -0
  49. norain-0.2.0/src/norain_server/__main__.py +5 -0
  50. norain-0.2.0/src/norain_server/cert.py +276 -0
  51. norain-0.2.0/src/norain_server/cli.py +477 -0
  52. norain-0.2.0/src/norain_server/deploy.py +604 -0
  53. norain-0.2.0/src/norain_server/firewall.py +226 -0
  54. norain-0.2.0/src/norain_server/generate.py +112 -0
  55. norain-0.2.0/src/norain_server/model.py +272 -0
  56. norain-0.2.0/src/norain_server/paths.py +101 -0
  57. norain-0.2.0/src/norain_server/runner.py +123 -0
  58. norain-0.2.0/src/norain_server/service.py +83 -0
  59. norain-0.2.0/tests/test_cert_acme.py +53 -0
  60. norain-0.2.0/tests/test_cli_entry.py +55 -0
  61. norain-0.2.0/tests/test_client.py +237 -0
  62. norain-0.2.0/tests/test_config_and_generate.py +220 -0
  63. norain-0.2.0/tests/test_core.py +83 -0
  64. norain-0.2.0/tests/test_deploy_prereqs.py +58 -0
  65. norain-0.2.0/tests/test_efficiency.py +314 -0
  66. norain-0.2.0/tests/test_lifecycle.py +153 -0
  67. norain-0.2.0/tests/test_migrate.py +73 -0
  68. norain-0.2.0/tests/test_modules.py +103 -0
  69. norain-0.2.0/tests/test_regressions.py +187 -0
  70. norain-0.2.0/tests/test_singbox_lock.py +34 -0
  71. norain-0.2.0/tests/test_sysproxy_geo.py +152 -0
  72. norain-0.2.0/tests/test_version.py +14 -0
norain-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jcy0chenyuan0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
norain-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: norain
3
+ Version: 0.2.0
4
+ Summary: Norain:基于 sing-box 的 Hysteria2/Trojan 客户端与服务端控制层
5
+ Author-email: jcy0chenyuan0 <jboxi@qq.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/jcy0chenyuan0/norain
8
+ Project-URL: Repository, https://github.com/jcy0chenyuan0/norain
9
+ Project-URL: Issues, https://github.com/jcy0chenyuan0/norain/issues
10
+ Keywords: sing-box,hysteria2,trojan,proxy,vpn
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Internet :: Proxy Servers
22
+ Classifier: Topic :: System :: Networking
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: pydantic>=2.5
27
+ Requires-Dist: cryptography>=42
28
+ Requires-Dist: psutil>=5.9
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # Norain
34
+
35
+ [![PyPI](https://img.shields.io/pypi/v/norain.svg)](https://pypi.org/project/norain/)
36
+ [![Python](https://img.shields.io/pypi/pyversions/norain.svg)](https://pypi.org/project/norain/)
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
38
+
39
+ 基于 sing-box 的 Hysteria2 / Trojan 代理:客户端 `norain` 和服务端 `norain-server`,Python 做控制层,
40
+ sing-box 做数据面,兼容 Windows 和 Linux。
41
+
42
+ ## 安装
43
+
44
+ ```bash
45
+ pip install norain
46
+ ```
47
+
48
+ 同一个包提供两个命令:`norain`(客户端)和 `norain-server`(服务端)。
49
+
50
+ **当前状态:0.2.0 首个正式版。两端模块代码齐备;测试套件在 Windows 上 95 项通过(3 项仅 POSIX 跳过)。
51
+ 已在真实环境验证过的部分**:生成配置通过真实 `sing-box 1.14.4 check`、本地端到端隧道、TUN 路由接管与还原、
52
+ Windows 防火墙阻断与解除、nftables 阻断、系统代理写入与还原、服务端 install/reload/fix/update/uninstall、
53
+ systemd 开机自启(真实重启)、真实 ACME 签发。**仍未验证**:客户端与 Linux 的安装流程、TUN 的实际流量、
54
+ 监控错误码、自维持互拉、分流学习闭环。逐项见 [docs/pending.md](docs/pending.md)。
55
+
56
+ 优先级:以最初目标 [docs/reference/original-goals.md](docs/reference/original-goals.md) 为准,除非有硬性 bug。
57
+
58
+ ## 客户端(九个模块)
59
+
60
+ 代理、分流、监控、自维持、阻断、修复、启动、内控制、外控制。
61
+
62
+ ```bash
63
+ norain install --server example.com # 部署:sing-box、配置、norain 命令、环境变量、开机自启动
64
+ norain start | stop | restart | status
65
+ norain config protocol auto # 自适应 / hysteria2 / trojan
66
+ norain config mode safe # 安全模式:不开机自启动
67
+ norain list white add example.com # 白名单 / black 黑名单 / blue 蓝名单 / monitor 监控名单
68
+ norain module monitor restart # 启动 / 结束 / 重启单个模块
69
+ norain repair file|builtin|full|reload # 四种修复
70
+ norain block status|off # 阻断模式;off = 手动解除
71
+ norain once monitor # 一次性执行某个模块的某个功能
72
+ norain status -t # -t:显示每个模块的运行情况和返回结果
73
+ norain uninstall
74
+ ```
75
+
76
+ ## 服务端
77
+
78
+ 干净机器上可以直接用引导脚本(系统依赖 → 虚拟环境 → 安装包 → `norain-server install`):
79
+
80
+ ```bash
81
+ sudo ./scripts/bootstrap-server.sh
82
+ ```
83
+
84
+ 已经装好 Python 与 venv 时,照常手动安装:
85
+
86
+ ```bash
87
+ NORAIN_DOMAIN=example.com NORAIN_PASSWORD=… norain-server install
88
+ norain-server start | stop | restart | reload | status
89
+ norain-server config validate|show|edit
90
+ norain-server cert check | cert self-signed --domain <域名>
91
+ norain-server firewall open|close|status
92
+ norain-server fix
93
+ norain-server update | uninstall [--purge]
94
+ ```
95
+
96
+ ## 文档
97
+
98
+ - 交接说明和未验证项目:[HANDOFF.md](HANDOFF.md)
99
+ - 实现状态清单:[docs/pending.md](docs/pending.md)
100
+ - 决策记录:[docs/decisions/](docs/decisions/README.md)
101
+ - 配置示例:[examples/server.toml](examples/server.toml)、[examples/cfg.toml](examples/cfg.toml)
102
+ - sing-box 锁定版本:[third_party/singbox.lock.toml](third_party/singbox.lock.toml)(1.14.4)
103
+
104
+ ## 开发
105
+
106
+ 需要 Python ≥ 3.11,以及 pydantic、cryptography、psutil。
107
+
108
+ ```bash
109
+ pip install -e ".[dev]"
110
+ python3 -m pytest -q
111
+ ```
norain-0.2.0/README.md ADDED
@@ -0,0 +1,79 @@
1
+ # Norain
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/norain.svg)](https://pypi.org/project/norain/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/norain.svg)](https://pypi.org/project/norain/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
+
7
+ 基于 sing-box 的 Hysteria2 / Trojan 代理:客户端 `norain` 和服务端 `norain-server`,Python 做控制层,
8
+ sing-box 做数据面,兼容 Windows 和 Linux。
9
+
10
+ ## 安装
11
+
12
+ ```bash
13
+ pip install norain
14
+ ```
15
+
16
+ 同一个包提供两个命令:`norain`(客户端)和 `norain-server`(服务端)。
17
+
18
+ **当前状态:0.2.0 首个正式版。两端模块代码齐备;测试套件在 Windows 上 95 项通过(3 项仅 POSIX 跳过)。
19
+ 已在真实环境验证过的部分**:生成配置通过真实 `sing-box 1.14.4 check`、本地端到端隧道、TUN 路由接管与还原、
20
+ Windows 防火墙阻断与解除、nftables 阻断、系统代理写入与还原、服务端 install/reload/fix/update/uninstall、
21
+ systemd 开机自启(真实重启)、真实 ACME 签发。**仍未验证**:客户端与 Linux 的安装流程、TUN 的实际流量、
22
+ 监控错误码、自维持互拉、分流学习闭环。逐项见 [docs/pending.md](docs/pending.md)。
23
+
24
+ 优先级:以最初目标 [docs/reference/original-goals.md](docs/reference/original-goals.md) 为准,除非有硬性 bug。
25
+
26
+ ## 客户端(九个模块)
27
+
28
+ 代理、分流、监控、自维持、阻断、修复、启动、内控制、外控制。
29
+
30
+ ```bash
31
+ norain install --server example.com # 部署:sing-box、配置、norain 命令、环境变量、开机自启动
32
+ norain start | stop | restart | status
33
+ norain config protocol auto # 自适应 / hysteria2 / trojan
34
+ norain config mode safe # 安全模式:不开机自启动
35
+ norain list white add example.com # 白名单 / black 黑名单 / blue 蓝名单 / monitor 监控名单
36
+ norain module monitor restart # 启动 / 结束 / 重启单个模块
37
+ norain repair file|builtin|full|reload # 四种修复
38
+ norain block status|off # 阻断模式;off = 手动解除
39
+ norain once monitor # 一次性执行某个模块的某个功能
40
+ norain status -t # -t:显示每个模块的运行情况和返回结果
41
+ norain uninstall
42
+ ```
43
+
44
+ ## 服务端
45
+
46
+ 干净机器上可以直接用引导脚本(系统依赖 → 虚拟环境 → 安装包 → `norain-server install`):
47
+
48
+ ```bash
49
+ sudo ./scripts/bootstrap-server.sh
50
+ ```
51
+
52
+ 已经装好 Python 与 venv 时,照常手动安装:
53
+
54
+ ```bash
55
+ NORAIN_DOMAIN=example.com NORAIN_PASSWORD=… norain-server install
56
+ norain-server start | stop | restart | reload | status
57
+ norain-server config validate|show|edit
58
+ norain-server cert check | cert self-signed --domain <域名>
59
+ norain-server firewall open|close|status
60
+ norain-server fix
61
+ norain-server update | uninstall [--purge]
62
+ ```
63
+
64
+ ## 文档
65
+
66
+ - 交接说明和未验证项目:[HANDOFF.md](HANDOFF.md)
67
+ - 实现状态清单:[docs/pending.md](docs/pending.md)
68
+ - 决策记录:[docs/decisions/](docs/decisions/README.md)
69
+ - 配置示例:[examples/server.toml](examples/server.toml)、[examples/cfg.toml](examples/cfg.toml)
70
+ - sing-box 锁定版本:[third_party/singbox.lock.toml](third_party/singbox.lock.toml)(1.14.4)
71
+
72
+ ## 开发
73
+
74
+ 需要 Python ≥ 3.11,以及 pydantic、cryptography、psutil。
75
+
76
+ ```bash
77
+ pip install -e ".[dev]"
78
+ python3 -m pytest -q
79
+ ```
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "norain"
7
+ version = "0.2.0"
8
+ description = "Norain:基于 sing-box 的 Hysteria2/Trojan 客户端与服务端控制层"
9
+ requires-python = ">=3.11"
10
+ readme = "README.md"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "jcy0chenyuan0", email = "jboxi@qq.com" }]
13
+ keywords = ["sing-box", "hysteria2", "trojan", "proxy", "vpn"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: End Users/Desktop",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: Microsoft :: Windows",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ "Topic :: Internet :: Proxy Servers",
26
+ "Topic :: System :: Networking",
27
+ ]
28
+ # 见 docs/decisions/0003-python-build-cli.md
29
+ dependencies = ["pydantic>=2.5", "cryptography>=42", "psutil>=5.9"]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/jcy0chenyuan0/norain"
33
+ Repository = "https://github.com/jcy0chenyuan0/norain"
34
+ Issues = "https://github.com/jcy0chenyuan0/norain/issues"
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest>=8"]
38
+
39
+ [project.scripts]
40
+ norain = "norain.cli:main"
41
+ norain-server = "norain_server.cli:main"
42
+
43
+ [tool.setuptools.packages.find]
44
+ where = ["src"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
48
+ pythonpath = ["src", "tests"]
norain-0.2.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Norain 客户端。模块划分见 HANDOFF.md。"""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -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": []}