norain 0.2.0.dev0__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.
- norain/__init__.py +3 -0
- norain/__main__.py +5 -0
- norain/block.py +281 -0
- norain/boot.py +142 -0
- norain/cli.py +748 -0
- norain/control.py +703 -0
- norain/defaults.py +42 -0
- norain/generate.py +264 -0
- norain/install.py +312 -0
- norain/maintain.py +313 -0
- norain/model.py +409 -0
- norain/monitor.py +314 -0
- norain/paths.py +124 -0
- norain/probe.py +158 -0
- norain/proxy.py +136 -0
- norain/repair.py +278 -0
- norain/routing.py +332 -0
- norain/rules.py +214 -0
- norain/runner.py +59 -0
- norain-0.2.0.dev0.dist-info/METADATA +99 -0
- norain-0.2.0.dev0.dist-info/RECORD +53 -0
- norain-0.2.0.dev0.dist-info/WHEEL +5 -0
- norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
- norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
- norain-0.2.0.dev0.dist-info/top_level.txt +3 -0
- norain_core/__init__.py +4 -0
- norain_core/apply.py +70 -0
- norain_core/atomic.py +80 -0
- norain_core/cliutil.py +68 -0
- norain_core/daemonctl.py +192 -0
- norain_core/errors.py +60 -0
- norain_core/fetch.py +158 -0
- norain_core/log.py +104 -0
- norain_core/migrate.py +86 -0
- norain_core/osutil.py +332 -0
- norain_core/redact.py +60 -0
- norain_core/secrets.py +87 -0
- norain_core/singbox.py +93 -0
- norain_core/state.py +97 -0
- norain_core/supervisor.py +352 -0
- norain_core/sysproxy.py +112 -0
- norain_core/tomlio.py +86 -0
- norain_server/__init__.py +3 -0
- norain_server/__main__.py +5 -0
- norain_server/cert.py +276 -0
- norain_server/cli.py +477 -0
- norain_server/deploy.py +604 -0
- norain_server/firewall.py +226 -0
- norain_server/generate.py +112 -0
- norain_server/model.py +272 -0
- norain_server/paths.py +101 -0
- norain_server/runner.py +123 -0
- norain_server/service.py +83 -0
norain/defaults.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""安装时写进 cfg.toml 的默认三类名单。
|
|
2
|
+
|
|
3
|
+
来源是本机 2026-11-15 正在运行的那套代理 C:\\Users\\j\\proxy-suite:
|
|
4
|
+
* 白名单 PROXY_DOMAINS sing-box.json 里 route.rules「domain_suffix → proxy」的那一组,
|
|
5
|
+
即原先强制走代理的站点(OpenAI / Claude / Google / GitHub / 维基 等)。
|
|
6
|
+
* 黑名单 DIRECT_DOMAINS 空列表。原配置没有显式直连域名,国内直连由 geosite-cn + geoip-cn
|
|
7
|
+
规则集(routing.rule_set)承担;这里只在需要时补单条。
|
|
8
|
+
* 蓝名单 ISOLATION_ALLOWLIST network-guard.ps1 的 $allowSites:杀开关(阻断)期间仍允许访问的站点。
|
|
9
|
+
|
|
10
|
+
改默认值只改这个文件;examples/cfg.toml 是给人看的完整示例,两处要一致。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
PROXY_DOMAINS = [
|
|
16
|
+
'openai.com', 'chatgpt.com', 'chatgpt.livekit.cloud', 'oaistatic.com', 'oaiusercontent.com',
|
|
17
|
+
'openai.org', 'sora.com', 'openaiapi-site.azureedge.net', 'identrust.com', 'statsig.com',
|
|
18
|
+
'featuregates.org', 'intercom.io', 'browser-intake-datadoghq.com', 'claude.com',
|
|
19
|
+
'claude.ai', 'anthropic.com', 'anthropic.ai', 'claudeusercontent.com', 'cla.st',
|
|
20
|
+
'usefathom.com', 'x.com', 'twitter.com', 'twimg.com', 't.co', 'ads-twitter.com',
|
|
21
|
+
'twitterinc.com', 'gemini.google.com', 'google.com', 'googleapis.com', 'gstatic.com',
|
|
22
|
+
'googleusercontent.com', 'googlevideo.com', 'gvt1.com', 'gvt2.com', 'withgoogle.com',
|
|
23
|
+
'google-analytics.com', 'googletagmanager.com', 'youtube.com', 'youtu.be', 'ytimg.com',
|
|
24
|
+
'youtube-nocookie.com', 'ggpht.com', 'wikipedia.org', 'wikimedia.org', 'wikidata.org',
|
|
25
|
+
'mediawiki.org', 'wikimediafoundation.org', 'wiktionary.org', 'wikisource.org',
|
|
26
|
+
'wikibooks.org', 'wikiquote.org', 'wikinews.org', 'wikivoyage.org', 'wikiversity.org',
|
|
27
|
+
'github.com', 'githubusercontent.com', 'githubassets.com', 'github.io', 'ghcr.io',
|
|
28
|
+
'github-cloud.s3.amazonaws.com', 'npmjs.org', 'npmjs.com', 'pypi.org', 'pythonhosted.org',
|
|
29
|
+
'docker.com', 'docker.io', 'dockerhub.com', 'huggingface.co', 'huggingface.com', 'hf.co',
|
|
30
|
+
'hf.space', 'anthropic.org', 'claude.dev', 'sentry.io', 'statsigcdn.com', 'segment.io',
|
|
31
|
+
'intercomcdn.com', 'challenges.cloudflare.com', 'ippure.com', 'ipinfo.io', 'cf.999831.xyz',
|
|
32
|
+
'myip.ipip.net', 'ipify.org', 'ipwho.is', 'ipapi.co', 'freeipapi.com', 'hiofd.com',
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# 与当前 sing-box.json 一致:没有显式直连域名,国内流量靠规则集。
|
|
36
|
+
DIRECT_DOMAINS: list[str] = []
|
|
37
|
+
|
|
38
|
+
ISOLATION_ALLOWLIST = [
|
|
39
|
+
'deepseek.com', 'api.deepseek.com', 'chat.deepseek.com', 'www.bilibili.com', 'bilibili.com',
|
|
40
|
+
'api.bilibili.com', 'www.zhihu.com', 'zhihu.com', 'api.zhihu.com', 'hdslb.com', 'zhimg.com',
|
|
41
|
+
'bilivideo.com',
|
|
42
|
+
]
|
norain/generate.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""cfg.toml → sing-box JSON:代理模块和分流模块的数据面配置。
|
|
2
|
+
|
|
3
|
+
字段依据 sing-box 1.14 官方文档(不使用 1.14 已弃用的字段:DNS 规则的 strategy、
|
|
4
|
+
independent_cache、TUN 的 stack 等);生成的客户端配置已用真实 sing-box 1.14.4 check 验证。
|
|
5
|
+
|
|
6
|
+
结构:
|
|
7
|
+
入站 mixed-in(本地代理)、tun-in(traffic_mode = tun)、
|
|
8
|
+
probe-direct / probe-<协议>(监控和自适应选协议用的本地探测入口,不受分流规则影响)
|
|
9
|
+
出站 proxy(当前使用的协议)、proxy-alt(auto 时的另一个协议)、direct
|
|
10
|
+
路由 探测入口 → 私有地址直连 → 白名单 → 黑名单 → 学到的名单 → 规则集(国内直连)→ 默认动作
|
|
11
|
+
DNS 白名单和默认动作走代理侧 DNS;黑名单和国内规则集走国内 DNS;代理侧失败不回落国内(防泄漏)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ipaddress
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from urllib.parse import urlsplit
|
|
19
|
+
|
|
20
|
+
from norain_core import apply as core_apply
|
|
21
|
+
from norain_core.secrets import Secret, resolve
|
|
22
|
+
from norain_core.state import read_json
|
|
23
|
+
from norain_core.supervisor import Listener
|
|
24
|
+
|
|
25
|
+
from .model import KNOWN_RULE_SETS, PROTOCOLS, SCHEMA_VERSION, ClientConfig, split_entries
|
|
26
|
+
from .paths import Paths
|
|
27
|
+
|
|
28
|
+
dumps, version_of = core_apply.dumps, core_apply.version_of
|
|
29
|
+
|
|
30
|
+
LOOPBACK = "127.0.0.1"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def resolve_secret(cfg: ClientConfig) -> Secret:
|
|
34
|
+
if cfg.proxy.password:
|
|
35
|
+
return Secret(value=cfg.proxy.password, source="config:proxy.password")
|
|
36
|
+
return resolve(cfg.proxy.credential_ref, field="proxy.credential_ref")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def probe_ports(cfg: ClientConfig) -> dict[str, int]:
|
|
40
|
+
"""本地探测入口的端口。direct:直连;<协议>:强制走该协议的出站。"""
|
|
41
|
+
base = cfg.local.probe_port
|
|
42
|
+
ports = {"direct": base}
|
|
43
|
+
for i, proto in enumerate(PROTOCOLS, start=1):
|
|
44
|
+
if proto in cfg.protocols:
|
|
45
|
+
ports[proto] = base + i
|
|
46
|
+
return ports
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def needs_probes(cfg: ClientConfig) -> bool:
|
|
50
|
+
"""监控、分流学习、自适应选协议都要用本地探测入口。"""
|
|
51
|
+
return cfg.monitor.enabled or cfg.routing.learn or cfg.proxy.protocol == "auto"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def listeners(cfg: ClientConfig) -> list[Listener]:
|
|
55
|
+
out: list[Listener] = [(cfg.local.listen, "tcp", cfg.local.port)]
|
|
56
|
+
if needs_probes(cfg):
|
|
57
|
+
out += [(LOOPBACK, "tcp", port) for port in probe_ports(cfg).values()]
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def active_protocol(cfg: ClientConfig, paths: Paths | None = None) -> str:
|
|
62
|
+
"""当前使用的协议。auto 时取内控制模块上次选中的结果,没有记录时用 prefer。"""
|
|
63
|
+
if cfg.proxy.protocol != "auto":
|
|
64
|
+
return cfg.proxy.protocol
|
|
65
|
+
chosen = (read_json(paths.selection) or {}).get("active") if paths else None
|
|
66
|
+
return chosen if chosen in PROTOCOLS else cfg.proxy.selection.prefer
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def rule_files(cfg: ClientConfig, paths: Paths | None) -> dict[str, Path]:
|
|
70
|
+
"""规则集标签 → 本地 .srs 文件。文件不存在的规则集直接跳过(流量落到默认动作)。"""
|
|
71
|
+
out: dict[str, Path] = {}
|
|
72
|
+
for rs in cfg.routing.rule_set:
|
|
73
|
+
if rs in KNOWN_RULE_SETS:
|
|
74
|
+
f = paths.rules_dir / f"{rs}.srs" if paths else None
|
|
75
|
+
else:
|
|
76
|
+
f = Path(rs).expanduser()
|
|
77
|
+
rs = f.stem
|
|
78
|
+
if f is not None and f.is_file():
|
|
79
|
+
out[rs] = f
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _is_ip(s: str) -> bool:
|
|
84
|
+
try:
|
|
85
|
+
ipaddress.ip_address(s)
|
|
86
|
+
return True
|
|
87
|
+
except ValueError:
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _outbound(cfg: ClientConfig, protocol: str, password: str, tag: str) -> dict:
|
|
92
|
+
p = cfg.proxy
|
|
93
|
+
tls: dict = {"enabled": True, "server_name": p.tls.server_name or p.server}
|
|
94
|
+
if protocol == "hysteria2":
|
|
95
|
+
tls["alpn"] = ["h3"]
|
|
96
|
+
if p.tls.certificate_path:
|
|
97
|
+
tls["certificate_path"] = str(Path(p.tls.certificate_path).expanduser())
|
|
98
|
+
if p.tls.insecure:
|
|
99
|
+
tls["insecure"] = True
|
|
100
|
+
out: dict = {"type": protocol, "tag": tag, "server": p.server, "server_port": p.port_of(protocol),
|
|
101
|
+
"password": password, "tls": tls}
|
|
102
|
+
if protocol == "trojan" and p.trojan.multiplex.enabled: # 服务端入站开了 multiplex 才可用
|
|
103
|
+
m = p.trojan.multiplex
|
|
104
|
+
out["multiplex"] = {"enabled": True, "protocol": m.protocol, "max_streams": m.max_streams}
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _dns_server(tag: str, address: str, *, detour: str | None, resolver: str) -> dict:
|
|
109
|
+
"""把 `https://host/path` 或裸 IP 转成 1.12+ 的 DNS server 写法。"""
|
|
110
|
+
if _is_ip(address):
|
|
111
|
+
srv: dict = {"type": "udp", "tag": tag, "server": address}
|
|
112
|
+
else:
|
|
113
|
+
u = urlsplit(address)
|
|
114
|
+
srv = {"type": "https", "tag": tag, "server": u.hostname}
|
|
115
|
+
if u.port:
|
|
116
|
+
srv["server_port"] = u.port
|
|
117
|
+
if u.path and u.path != "/dns-query":
|
|
118
|
+
srv["path"] = u.path
|
|
119
|
+
if not _is_ip(u.hostname or ""):
|
|
120
|
+
srv["domain_resolver"] = resolver
|
|
121
|
+
if detour:
|
|
122
|
+
srv["detour"] = detour
|
|
123
|
+
return srv
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _domain_match(entries: list[str]) -> dict:
|
|
127
|
+
"""DNS 规则只能按域名匹配,去掉名单里的 IP 条目。"""
|
|
128
|
+
m = split_entries(entries)
|
|
129
|
+
m.pop("ip_cidr", None)
|
|
130
|
+
return m
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _dns(cfg: ClientConfig, learned: dict, geosite_tags: list[str], strategy: str) -> tuple[dict, str]:
|
|
134
|
+
"""返回 (dns 配置, 默认域名解析器的标签)。"""
|
|
135
|
+
if cfg.dns.mode == "local":
|
|
136
|
+
# 只用系统 DNS 解析代理服务器域名和直连目标;走代理的域名交给服务端解析
|
|
137
|
+
return {"servers": [{"type": "local", "tag": "local"}]}, "local"
|
|
138
|
+
|
|
139
|
+
servers = [
|
|
140
|
+
{"type": "local", "tag": "local"},
|
|
141
|
+
{"type": "udp", "tag": "dns-direct", "server": cfg.dns.domestic},
|
|
142
|
+
_dns_server("dns-proxy", cfg.dns.proxy, detour="proxy", resolver="dns-direct"),
|
|
143
|
+
]
|
|
144
|
+
rules: list[dict] = []
|
|
145
|
+
hosts = learned.get("hosts") or {}
|
|
146
|
+
if hosts: # 分流模块更新过的解析结果
|
|
147
|
+
servers.append({"type": "hosts", "tag": "dns-hosts", "predefined": dict(sorted(hosts.items()))})
|
|
148
|
+
rules.append({"domain": sorted(hosts), "action": "route", "server": "dns-hosts"})
|
|
149
|
+
if not _is_ip(cfg.proxy.server): # 代理服务器自己的域名必须直连解析,否则死循环
|
|
150
|
+
rules.append({"domain": [cfg.proxy.server.lower()], "action": "route", "server": "dns-direct"})
|
|
151
|
+
|
|
152
|
+
def add(entries: list[str], server: str) -> None:
|
|
153
|
+
m = _domain_match(entries)
|
|
154
|
+
if m:
|
|
155
|
+
rules.append({**m, "action": "route", "server": server})
|
|
156
|
+
|
|
157
|
+
add(cfg.routing.proxy_domains, "dns-proxy") # 白名单:恒用服务器侧解析
|
|
158
|
+
add(cfg.routing.direct_domains, "dns-direct") # 黑名单:国内 DNS
|
|
159
|
+
add(learned.get("proxy") or [], "dns-proxy")
|
|
160
|
+
add(learned.get("direct") or [], "dns-direct")
|
|
161
|
+
if cfg.dns.mode == "split":
|
|
162
|
+
if geosite_tags:
|
|
163
|
+
rules.append({"rule_set": geosite_tags, "action": "route", "server": "dns-direct"})
|
|
164
|
+
final = "dns-proxy" if cfg.routing.default_action == "proxy" else "dns-direct"
|
|
165
|
+
else: # proxy:除黑名单外全部由服务器侧解析
|
|
166
|
+
final = "dns-proxy"
|
|
167
|
+
return {"servers": servers, "rules": rules, "final": final, "strategy": strategy}, "dns-direct"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def build(cfg: ClientConfig, password: str, *, active: str | None = None, learned: dict | None = None,
|
|
171
|
+
rules: dict[str, Path] | None = None, strategy: str | None = None) -> dict:
|
|
172
|
+
"""生成 sing-box 配置。
|
|
173
|
+
|
|
174
|
+
active 当前协议(auto 时由内控制模块决定)
|
|
175
|
+
learned 分流模块学到的名单:{"proxy": [...], "direct": [...], "hosts": {域名: [IP]}}
|
|
176
|
+
rules 可用的规则集文件:{标签: 路径}
|
|
177
|
+
strategy DNS 的 IPv4/IPv6 策略覆盖(自维持模块处理 604/606 时使用)
|
|
178
|
+
"""
|
|
179
|
+
learned = learned or {}
|
|
180
|
+
rules = rules or {}
|
|
181
|
+
active = active if active in cfg.protocols else active_protocol(cfg)
|
|
182
|
+
tun = cfg.proxy.traffic_mode == "tun"
|
|
183
|
+
|
|
184
|
+
# ---- 出站:当前协议叫 proxy,auto 时另一个叫 proxy-alt ----
|
|
185
|
+
tag_of = {active: "proxy"}
|
|
186
|
+
outbounds = [_outbound(cfg, active, password, "proxy")]
|
|
187
|
+
for proto in cfg.protocols:
|
|
188
|
+
if proto != active:
|
|
189
|
+
tag_of[proto] = "proxy-alt"
|
|
190
|
+
outbounds.append(_outbound(cfg, proto, password, "proxy-alt"))
|
|
191
|
+
outbounds.append({"type": "direct", "tag": "direct"})
|
|
192
|
+
|
|
193
|
+
# ---- 入站 ----
|
|
194
|
+
mixed: dict = {"type": "mixed", "tag": "mixed-in", "listen": cfg.local.listen,
|
|
195
|
+
"listen_port": cfg.local.port}
|
|
196
|
+
if cfg.proxy.traffic_mode == "system-proxy":
|
|
197
|
+
mixed["set_system_proxy"] = True
|
|
198
|
+
inbounds = [mixed]
|
|
199
|
+
if tun:
|
|
200
|
+
inbounds.append({"type": "tun", "tag": "tun-in", "interface_name": cfg.tun.interface_name,
|
|
201
|
+
"address": list(cfg.tun.address), "mtu": cfg.tun.mtu,
|
|
202
|
+
"auto_route": True, "strict_route": cfg.tun.strict_route})
|
|
203
|
+
route_rules: list[dict] = [{"action": "sniff"}]
|
|
204
|
+
if tun:
|
|
205
|
+
route_rules.append({"protocol": "dns", "action": "hijack-dns"})
|
|
206
|
+
if needs_probes(cfg):
|
|
207
|
+
for name, port in probe_ports(cfg).items():
|
|
208
|
+
inbounds.append({"type": "mixed", "tag": f"probe-{name}", "listen": LOOPBACK, "listen_port": port})
|
|
209
|
+
route_rules.append({"inbound": f"probe-{name}", "action": "route",
|
|
210
|
+
"outbound": "direct" if name == "direct" else tag_of[name]})
|
|
211
|
+
|
|
212
|
+
# ---- 路由:内部保留 → 白名单 → 黑名单 → 学到的名单 → 规则集 → 默认动作 ----
|
|
213
|
+
route_rules.append({"ip_is_private": True, "action": "route", "outbound": "direct"})
|
|
214
|
+
|
|
215
|
+
def add(entries: list[str], outbound: str) -> None:
|
|
216
|
+
m = split_entries(entries)
|
|
217
|
+
if m:
|
|
218
|
+
route_rules.append({**m, "action": "route", "outbound": outbound})
|
|
219
|
+
|
|
220
|
+
add(cfg.routing.proxy_domains, "proxy")
|
|
221
|
+
add(cfg.routing.direct_domains, "direct")
|
|
222
|
+
add(learned.get("proxy") or [], "proxy")
|
|
223
|
+
add(learned.get("direct") or [], "direct")
|
|
224
|
+
if rules:
|
|
225
|
+
route_rules.append({"rule_set": sorted(rules), "action": "route", "outbound": "direct"})
|
|
226
|
+
|
|
227
|
+
strategy = strategy or cfg.dns.strategy
|
|
228
|
+
dns, resolver = _dns(cfg, learned, sorted(t for t in rules if t.startswith("geosite")), strategy)
|
|
229
|
+
route: dict = {"rules": route_rules,
|
|
230
|
+
"final": "proxy" if cfg.routing.default_action == "proxy" else "direct",
|
|
231
|
+
"default_domain_resolver": resolver}
|
|
232
|
+
if rules:
|
|
233
|
+
route["rule_set"] = [{"type": "local", "tag": tag, "format": "binary", "path": str(path)}
|
|
234
|
+
for tag, path in sorted(rules.items())]
|
|
235
|
+
if tun:
|
|
236
|
+
route["auto_detect_interface"] = True # 出站绑定物理网卡,避免被自己的 TUN 接管形成环路
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
"log": {"level": cfg.logging.level, "timestamp": True},
|
|
240
|
+
"dns": dns,
|
|
241
|
+
"inbounds": inbounds,
|
|
242
|
+
"outbounds": outbounds,
|
|
243
|
+
"route": route,
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def context(cfg: ClientConfig, paths: Paths | None) -> dict:
|
|
248
|
+
"""从状态目录读出生成器需要的运行时输入。"""
|
|
249
|
+
if paths is None:
|
|
250
|
+
return {}
|
|
251
|
+
from .routing import load_learned
|
|
252
|
+
overrides = read_json(paths.selection) or {}
|
|
253
|
+
return {"active": active_protocol(cfg, paths), "learned": load_learned(paths).for_generator(),
|
|
254
|
+
"rules": rule_files(cfg, paths), "strategy": overrides.get("dns_strategy")}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def render(cfg: ClientConfig, secret: Secret, paths: Paths | None = None) -> bytes:
|
|
258
|
+
return dumps(build(cfg, secret.value, **context(cfg, paths)))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def apply(cfg: ClientConfig, secret: Secret, paths: Paths, binary: Path):
|
|
262
|
+
return core_apply.apply(render(cfg, secret, paths), run_dir=paths.run_dir, current=paths.current_json,
|
|
263
|
+
backups=paths.backups, meta=paths.meta_json, source=paths.config,
|
|
264
|
+
schema=SCHEMA_VERSION, binary=binary)
|
norain/install.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""客户端的安装与卸载(自动部署并加入环境变量)。
|
|
2
|
+
|
|
3
|
+
install:sing-box → 默认配置 → 安装包副本和哈希清单(修复模块用)→ `norain` 启动器和环境变量
|
|
4
|
+
→ 规则集 → 校验配置 → 开机自启动 → 启动。
|
|
5
|
+
uninstall:停止全部进程、解除阻断、删除自启动项、环境变量、PATH、启动器和全部文件。
|
|
6
|
+
它同时是「重载修复」的前半段,也是一条独立的命令。
|
|
7
|
+
|
|
8
|
+
Python 包本身由包管理器安装(pip),卸载命令不删除它。客户端 install 尚未在真实系统上执行过
|
|
9
|
+
(服务端同一套流程已在 Linux 上验证)。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from norain_core import fetch, osutil
|
|
21
|
+
from norain_core.errors import NorainError
|
|
22
|
+
from norain_core.log import Logger, new_op_id
|
|
23
|
+
from norain_core.state import STOPPED, read_json, set_desired, write_json
|
|
24
|
+
|
|
25
|
+
from . import block, boot, defaults, repair, rules
|
|
26
|
+
from .model import load_config
|
|
27
|
+
from .paths import Paths
|
|
28
|
+
|
|
29
|
+
ENV_NAME = "norain"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _env(paths: Paths) -> dict[str, str]:
|
|
33
|
+
# Persist every path that may have been selected through the environment.
|
|
34
|
+
# Omitting NORAIN_STATE makes a custom state directory disappear in the next
|
|
35
|
+
# terminal, so the installed command starts against a different instance.
|
|
36
|
+
return {"NORAIN_HOME": str(paths.home), "NORAIN_CONFIG": str(paths.config),
|
|
37
|
+
"NORAIN_STATE": str(paths.state)}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _toml_list(items: list[str], *, width: int = 96) -> str:
|
|
41
|
+
"""把名单排成多行 TOML 数组,避免生成出来的配置单行过长。"""
|
|
42
|
+
if not items:
|
|
43
|
+
return "[]"
|
|
44
|
+
lines, cur = [], ""
|
|
45
|
+
for item in items:
|
|
46
|
+
token = json.dumps(item, ensure_ascii=False) + ","
|
|
47
|
+
candidate = f"{cur} {token}".strip() if cur else token
|
|
48
|
+
if len(" " + candidate) > width:
|
|
49
|
+
lines.append(cur)
|
|
50
|
+
cur = token
|
|
51
|
+
else:
|
|
52
|
+
cur = candidate
|
|
53
|
+
lines.append(cur)
|
|
54
|
+
return "[" + ("\n ".join(lines)) + "]"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def default_config_text(paths: Paths, *, server: str, credential_ref: str, traffic_mode: str,
|
|
58
|
+
protocol: str) -> str:
|
|
59
|
+
def q(value: str) -> str:
|
|
60
|
+
# Environment variables and paths can contain quotes or backslashes.
|
|
61
|
+
# JSON basic-string escaping is valid TOML basic-string escaping.
|
|
62
|
+
return json.dumps(str(value), ensure_ascii=False)
|
|
63
|
+
|
|
64
|
+
white = _toml_list(defaults.PROXY_DOMAINS)
|
|
65
|
+
black = _toml_list(defaults.DIRECT_DOMAINS)
|
|
66
|
+
blue = _toml_list(defaults.ISOLATION_ALLOWLIST)
|
|
67
|
+
return f"""# 由 norain install 生成。修改后运行 norain config validate 和 norain restart
|
|
68
|
+
# 默认值取自本机 sing-box.json:混合入口 127.0.0.1:1082、国内直连其余走隧道、
|
|
69
|
+
# 白名单是原来那组强制走代理的 domain_suffix(见 src/norain/defaults.py)。
|
|
70
|
+
# 见 docs/decisions/0007。
|
|
71
|
+
schema = 1
|
|
72
|
+
|
|
73
|
+
[app]
|
|
74
|
+
mode = "normal" # normal:开机自启动;safe:只手动启动
|
|
75
|
+
auto_start = true
|
|
76
|
+
|
|
77
|
+
[local]
|
|
78
|
+
listen = "127.0.0.1"
|
|
79
|
+
port = 1082 # 沿用原来的系统代理端口
|
|
80
|
+
probe_port = 1092 # 占用连续 3 个端口,不能和 port 重叠
|
|
81
|
+
|
|
82
|
+
[proxy]
|
|
83
|
+
protocol = {q(protocol)} # auto | hysteria2 | trojan
|
|
84
|
+
server = {q(server)}
|
|
85
|
+
traffic_mode = {q(traffic_mode)} # tun:全局接管(需要管理员权限);system-proxy:只设系统代理;mixed:只有本地代理
|
|
86
|
+
credential_ref = {q(credential_ref)}
|
|
87
|
+
|
|
88
|
+
[proxy.hysteria2]
|
|
89
|
+
port = 443
|
|
90
|
+
|
|
91
|
+
[proxy.trojan]
|
|
92
|
+
port = 443
|
|
93
|
+
|
|
94
|
+
[proxy.tls]
|
|
95
|
+
server_name = "www.bing.com" # 与服务端的伪装域名一致
|
|
96
|
+
insecure = true # 沿用原 sing-box.json 的 tls.insecure: true;配上真证书后改成 false
|
|
97
|
+
|
|
98
|
+
[routing]
|
|
99
|
+
# 白名单:强制走代理。取自原来 sing-box.json 里 domain_suffix → proxy 的那一组
|
|
100
|
+
proxy_domains = {white}
|
|
101
|
+
# 黑名单:强制直连。原配置没有显式条目,国内直连由 routing.rule_set 承担
|
|
102
|
+
direct_domains = {black}
|
|
103
|
+
# 蓝名单:阻断模式下仍允许的连接。取自原来杀开关的 $allowSites
|
|
104
|
+
isolation_allowlist = {blue}
|
|
105
|
+
|
|
106
|
+
[dns]
|
|
107
|
+
mode = "split"
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def install(paths: Paths, *, archive: Path | None = None, sha256: str | None = None,
|
|
112
|
+
singbox_path: Path | None = None, config_src: Path | None = None, server: str = "",
|
|
113
|
+
traffic_mode: str = "system-proxy", protocol: str = "auto", force: bool = False,
|
|
114
|
+
start: bool = True,
|
|
115
|
+
log: Logger | None = None, env=None) -> dict:
|
|
116
|
+
env = os.environ if env is None else env
|
|
117
|
+
steps: list[str] = []
|
|
118
|
+
warnings: list[str] = []
|
|
119
|
+
for d in (paths.home, paths.state, paths.bin_dir, paths.run_dir, paths.log_dir, paths.package_dir):
|
|
120
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
121
|
+
for d in (paths.home, paths.state):
|
|
122
|
+
os.chmod(d, 0o700)
|
|
123
|
+
|
|
124
|
+
# 1. sing-box:校验 SHA-256,再核对版本和构建标签
|
|
125
|
+
info = fetch.install_singbox(paths.bundled_singbox, paths.cache_dir, archive=archive,
|
|
126
|
+
expected_sha256=sha256, existing=singbox_path, need_tags={"with_quic"})
|
|
127
|
+
steps.append(f"sing-box {info.version} → {paths.bundled_singbox}")
|
|
128
|
+
|
|
129
|
+
# 2. 配置:已有的用户配置不覆盖,除非 --force(覆盖前备份)
|
|
130
|
+
if paths.config.exists() and not force:
|
|
131
|
+
steps.append(f"保留已有配置 {paths.config}")
|
|
132
|
+
else:
|
|
133
|
+
if paths.config.exists():
|
|
134
|
+
bak = paths.config.with_name(f"{paths.config.name}.{time.strftime('%Y%m%dT%H%M%S')}.bak")
|
|
135
|
+
shutil.copy2(paths.config, bak)
|
|
136
|
+
steps.append(f"已备份旧配置到 {bak}")
|
|
137
|
+
if config_src is not None:
|
|
138
|
+
shutil.copy2(config_src, paths.config)
|
|
139
|
+
steps.append(f"配置取自 {config_src}")
|
|
140
|
+
else:
|
|
141
|
+
server = server or (env.get("NORAIN_SERVER") or "").strip()
|
|
142
|
+
injected = (env.get("NORAIN_PASSWORD") or "").strip()
|
|
143
|
+
secret_file = paths.home / "password"
|
|
144
|
+
if injected:
|
|
145
|
+
fd = os.open(secret_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
146
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
147
|
+
f.write(injected + "\n")
|
|
148
|
+
steps.append("密码取自 NORAIN_PASSWORD,已写入密码文件")
|
|
149
|
+
ref = f"file:{secret_file.as_posix()}"
|
|
150
|
+
if not secret_file.exists():
|
|
151
|
+
warnings.append(f"还没有密码:把服务端的密码写进 {secret_file}(只写一行)")
|
|
152
|
+
paths.config.write_text(default_config_text(paths, server=server, credential_ref=ref,
|
|
153
|
+
traffic_mode=traffic_mode, protocol=protocol),
|
|
154
|
+
encoding="utf-8")
|
|
155
|
+
steps.append(f"已写入默认配置 {paths.config}")
|
|
156
|
+
os.chmod(paths.config, 0o600)
|
|
157
|
+
|
|
158
|
+
# 3. 安装包副本、初始配置和哈希清单:文件修复、完全配置修复、重载修复都以它们为准
|
|
159
|
+
if force or not paths.orig_config.exists():
|
|
160
|
+
shutil.copy2(paths.config, paths.orig_config)
|
|
161
|
+
repair.save_package(paths)
|
|
162
|
+
steps.append(f"已保存安装包副本和哈希清单:{paths.package_dir}")
|
|
163
|
+
|
|
164
|
+
# 4. norain 命令和环境变量
|
|
165
|
+
osutil.write_launcher(paths.bin_dir, "norain", "norain")
|
|
166
|
+
steps += osutil.persist_env(_env(paths), system=False, name=ENV_NAME, path_dirs=(str(paths.bin_dir),))
|
|
167
|
+
|
|
168
|
+
# 5. 规则集(国内网络直接下载 GitHub 可能失败;代理起来之后内控制模块会经代理自动重试)
|
|
169
|
+
cfg = None
|
|
170
|
+
try:
|
|
171
|
+
cfg = load_config(paths.config)
|
|
172
|
+
except NorainError as e:
|
|
173
|
+
warnings.append("配置还不能用:" + (";".join(f"{f.path} {f.message}" for f in e.field_errors) or e.message))
|
|
174
|
+
if cfg is not None:
|
|
175
|
+
rep = rules.update(cfg, paths, timeout=20)
|
|
176
|
+
if rep["failed"]:
|
|
177
|
+
warnings.append("规则集暂时没有下载成功(代理启动后会自动重试):" + "、".join(rep["failed"]))
|
|
178
|
+
else:
|
|
179
|
+
steps.append("规则集就绪:" + "、".join(rep["updated"] + rep["unchanged"]))
|
|
180
|
+
if rep["unpinned"]:
|
|
181
|
+
warnings.append("规则集没有锁定哈希,只记录了本次下载的哈希:" + "、".join(rep["unpinned"]))
|
|
182
|
+
|
|
183
|
+
# 6. 安装记录
|
|
184
|
+
write_json(paths.install_record, {"installed_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
|
185
|
+
"bin_dir": str(paths.bin_dir), "env": list(_env(paths))})
|
|
186
|
+
|
|
187
|
+
# 7. 开机自启动和首次启动
|
|
188
|
+
started = False
|
|
189
|
+
if cfg is not None:
|
|
190
|
+
try:
|
|
191
|
+
steps.append(boot.sync(paths, cfg))
|
|
192
|
+
except NorainError as e:
|
|
193
|
+
warnings.append(f"开机自启动没有注册:{e.message}" + (f"({e.hint})" if e.hint else ""))
|
|
194
|
+
if start:
|
|
195
|
+
from . import runner
|
|
196
|
+
from norain_core.state import RUNNING
|
|
197
|
+
try:
|
|
198
|
+
runner.prepare(paths, apply=True)
|
|
199
|
+
set_desired(paths.desired, RUNNING, op_id=new_op_id())
|
|
200
|
+
runner.backend(paths).start(timeout=40)
|
|
201
|
+
started = True
|
|
202
|
+
steps.append("已启动")
|
|
203
|
+
except NorainError as e:
|
|
204
|
+
set_desired(paths.desired, STOPPED, op_id=new_op_id())
|
|
205
|
+
warnings.append(f"没有启动成功:{e.message}" + (f"({e.hint})" if e.hint else "")
|
|
206
|
+
+ "。修正后运行 norain start")
|
|
207
|
+
if log:
|
|
208
|
+
log.info("install.done", steps=steps, warnings=warnings)
|
|
209
|
+
return {"steps": steps, "warnings": warnings, "started": started,
|
|
210
|
+
"config": str(paths.config), "state": str(paths.state)}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def clear_system_proxy(paths: Paths) -> str | None:
|
|
214
|
+
"""system-proxy 模式异常退出后系统代理可能残留。
|
|
215
|
+
|
|
216
|
+
优先按启动前的快照原样还原(ProxyServer / ProxyOverride 都回填);没有快照时,
|
|
217
|
+
只在当前值指向本机回环地址时才把 ProxyEnable 关掉。
|
|
218
|
+
"""
|
|
219
|
+
if not osutil.IS_WINDOWS or osutil.system_changes_disabled():
|
|
220
|
+
return None
|
|
221
|
+
from norain_core import sysproxy
|
|
222
|
+
|
|
223
|
+
snapshot = sysproxy.load(paths.sysproxy_state)
|
|
224
|
+
if snapshot and sysproxy.write(snapshot):
|
|
225
|
+
sysproxy.discard(paths.sysproxy_state)
|
|
226
|
+
return f"已按启动前的快照还原系统代理设置(ProxyServer={snapshot.get('ProxyServer')})"
|
|
227
|
+
try:
|
|
228
|
+
import winreg
|
|
229
|
+
key_path = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
|
|
230
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_READ | winreg.KEY_SET_VALUE) as k:
|
|
231
|
+
enabled, _ = winreg.QueryValueEx(k, "ProxyEnable")
|
|
232
|
+
server, _ = winreg.QueryValueEx(k, "ProxyServer")
|
|
233
|
+
if enabled and str(server).startswith(("127.0.0.1:", "localhost:", "[::1]:")):
|
|
234
|
+
winreg.SetValueEx(k, "ProxyEnable", 0, winreg.REG_DWORD, 0)
|
|
235
|
+
return f"已清除残留的系统代理设置({server})"
|
|
236
|
+
except OSError:
|
|
237
|
+
pass
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def stop_everything(paths: Paths) -> tuple[list[str], list[str]]:
|
|
242
|
+
"""停止内控制进程和看门狗。先写期望状态,保证任何保活方都不会再拉起。
|
|
243
|
+
|
|
244
|
+
返回 (已做成的事, 出错的事):卸载必须区分「停下来了」和「停不下来」,
|
|
245
|
+
否则后面的删目录会把还在运行的进程变成孤儿。
|
|
246
|
+
"""
|
|
247
|
+
from . import maintain, runner
|
|
248
|
+
done: list[str] = []
|
|
249
|
+
errors: list[str] = []
|
|
250
|
+
set_desired(paths.desired, STOPPED, op_id=new_op_id())
|
|
251
|
+
try:
|
|
252
|
+
runner.backend(paths).stop()
|
|
253
|
+
done.append("已停止代理")
|
|
254
|
+
except (NorainError, OSError) as e:
|
|
255
|
+
errors.append(f"没有停下代理:{getattr(e, 'message', str(e))}")
|
|
256
|
+
try:
|
|
257
|
+
if maintain.kill_watchdog(paths):
|
|
258
|
+
done.append("已停止看门狗")
|
|
259
|
+
except OSError as e:
|
|
260
|
+
errors.append(f"没有停下看门狗:{e}")
|
|
261
|
+
return done, errors
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def uninstall(paths: Paths, *, log: Logger | None = None) -> dict:
|
|
265
|
+
"""完全卸载:清除注册表 / 计划任务 / 环境变量 / 防火墙规则 / 全部文件。"""
|
|
266
|
+
done: list[str] = []
|
|
267
|
+
errors: list[str] = []
|
|
268
|
+
clean = True
|
|
269
|
+
if paths.state.exists():
|
|
270
|
+
d, e = stop_everything(paths)
|
|
271
|
+
done += d
|
|
272
|
+
errors += e
|
|
273
|
+
clean = clean and not e
|
|
274
|
+
try:
|
|
275
|
+
if block.release(paths)["was_active"]:
|
|
276
|
+
done.append("已解除阻断")
|
|
277
|
+
except (NorainError, OSError) as e:
|
|
278
|
+
errors.append(f"{getattr(e, 'message', str(e))}"
|
|
279
|
+
+ (f"({e.hint})" if isinstance(e, NorainError) and e.hint else ""))
|
|
280
|
+
clean = False
|
|
281
|
+
try:
|
|
282
|
+
done += boot.unregister()
|
|
283
|
+
except (NorainError, OSError) as e:
|
|
284
|
+
errors.append(getattr(e, "message", str(e)))
|
|
285
|
+
clean = False
|
|
286
|
+
msg = clear_system_proxy(paths)
|
|
287
|
+
if msg:
|
|
288
|
+
done.append(msg)
|
|
289
|
+
record = read_json(paths.install_record) or {}
|
|
290
|
+
bin_dir = Path(record.get("bin_dir") or paths.bin_dir)
|
|
291
|
+
try:
|
|
292
|
+
done += osutil.unpersist_env(list(_env(paths)), system=False, name=ENV_NAME, path_dirs=(str(bin_dir),))
|
|
293
|
+
except (NorainError, OSError) as e:
|
|
294
|
+
errors.append(getattr(e, "message", str(e)))
|
|
295
|
+
clean = False
|
|
296
|
+
osutil.remove_launcher(bin_dir, "norain")
|
|
297
|
+
targets = [paths.state, paths.log_dir, paths.home] if clean else []
|
|
298
|
+
if not clean:
|
|
299
|
+
# 保留状态、配置和日志:否则防火墙规则还在或进程仍在运行时,
|
|
300
|
+
# 用户卸载完无法安全恢复。
|
|
301
|
+
errors.append(f"阻断规则或代理进程没有清理干净,保留状态目录 {paths.state};"
|
|
302
|
+
"同时保留配置和日志,处理权限问题后重新运行 norain uninstall")
|
|
303
|
+
for d in targets:
|
|
304
|
+
if d.exists():
|
|
305
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
306
|
+
if d.exists():
|
|
307
|
+
errors.append(f"没有删干净:{d}(可能有文件被占用)")
|
|
308
|
+
else:
|
|
309
|
+
done.append(f"已删除 {d}")
|
|
310
|
+
# 这里不再写日志:日志目录刚被删除,写入会把它重新建出来
|
|
311
|
+
return {"done": done, "errors": errors,
|
|
312
|
+
"note": "Python 包本身没有卸载;需要时运行 pip uninstall norain"}
|