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/model.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""cfg.toml 配置模型。没有实现的取值在校验时明确拒绝(目前只有 traffic_mode = "transparent")。
|
|
2
|
+
|
|
3
|
+
加载顺序是「迁移 → 字段校验 → 交叉校验」:Schema 版本策略和逐级迁移在
|
|
4
|
+
``norain_core.migrate``,本模块只取结果;迁移产生的 warning 挂在配置对象上,
|
|
5
|
+
由 ``warnings_of`` 统一展示。
|
|
6
|
+
|
|
7
|
+
名单的含义(docs/decisions/0007):
|
|
8
|
+
routing.proxy_domains 白名单:强制走代理,DNS 由服务器侧解析
|
|
9
|
+
routing.direct_domains 黑名单:强制直连,DNS 用国内服务器
|
|
10
|
+
routing.isolation_allowlist 蓝名单:阻断模式下仍允许的连接
|
|
11
|
+
monitor.foreign_targets / domestic_targets 监控测试名单
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import difflib
|
|
17
|
+
import ipaddress
|
|
18
|
+
import os
|
|
19
|
+
import tomllib
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Literal
|
|
22
|
+
from urllib.parse import urlsplit
|
|
23
|
+
|
|
24
|
+
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, ValidationError, field_validator
|
|
25
|
+
|
|
26
|
+
from norain_core.errors import BIZ_CONFIG, EXIT_CONFIG, FieldError, NorainError, config_error
|
|
27
|
+
from norain_core.migrate import (SCHEMA_VERSION, MigrationResult, attach_warnings, migrate,
|
|
28
|
+
migration_warnings)
|
|
29
|
+
from norain_core.redact import REDACTOR
|
|
30
|
+
from norain_core.secrets import check_private_file
|
|
31
|
+
|
|
32
|
+
from . import defaults
|
|
33
|
+
|
|
34
|
+
PROTOCOLS = ("hysteria2", "trojan")
|
|
35
|
+
KNOWN_RULE_SETS = ("geosite-cn", "geoip-cn")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Strict(BaseModel):
|
|
39
|
+
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class App(_Strict):
|
|
43
|
+
mode: Literal["normal", "safe"] = "normal" # safe:不开机自启动,只能手动启动
|
|
44
|
+
auto_start: bool = True # normal 模式下是否注册开机自启动
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Local(_Strict):
|
|
48
|
+
listen: str = "127.0.0.1"
|
|
49
|
+
port: int = Field(2080, ge=1, le=65535)
|
|
50
|
+
probe_port: int = Field(2090, ge=1, le=65530) # 监控用的本地探测入口,占用连续 3 个端口
|
|
51
|
+
|
|
52
|
+
@field_validator("listen")
|
|
53
|
+
@classmethod
|
|
54
|
+
def _ip(cls, v: str) -> str:
|
|
55
|
+
try:
|
|
56
|
+
ipaddress.ip_address(v)
|
|
57
|
+
except ValueError:
|
|
58
|
+
raise ValueError("必须是 IP 地址,例如 127.0.0.1") from None
|
|
59
|
+
return v
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ProtoPort(_Strict):
|
|
63
|
+
port: int = Field(443, ge=1, le=65535)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Multiplex(_Strict):
|
|
67
|
+
"""trojan 的多路复用,**默认关闭**。
|
|
68
|
+
|
|
69
|
+
sing-box 1.7 起客户端 mux 走 sp.mux.sing-box.arpa,服务端必须在**入站**上显式开启
|
|
70
|
+
multiplex 才接受。原来那套服务端(同样是 1.14.4)没有开,2026-11-15 实测:客户端开
|
|
71
|
+
mux 时 trojan 立刻失败(HTTP 000,服务端日志 "global multiplex is deprecated …
|
|
72
|
+
enable multiplex in Inbound fields instead"),关掉立刻通(200)。
|
|
73
|
+
只有自建服务端的入站也开了 multiplex 时才值得打开。
|
|
74
|
+
|
|
75
|
+
hysteria2 不走这里:它是 QUIC 上的原生协议,sing-box 不支持也不需要对它多路复用。
|
|
76
|
+
"""
|
|
77
|
+
enabled: bool = False
|
|
78
|
+
protocol: Literal["smux", "yamux", "h2mux"] = "smux"
|
|
79
|
+
max_streams: int = Field(8, ge=1, le=128)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Trojan(ProtoPort):
|
|
83
|
+
multiplex: Multiplex = Multiplex()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ProxyTls(_Strict):
|
|
87
|
+
server_name: str = "" # 留空时用 proxy.server
|
|
88
|
+
certificate_path: str = "" # 服务端用自签证书时,填这张证书的路径
|
|
89
|
+
insecure: bool = False # 跳过证书校验,不安全,仅调试
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Selection(_Strict):
|
|
93
|
+
"""protocol = "auto" 时的自适应参数(docs/decisions/0009)。"""
|
|
94
|
+
interval_seconds: float = Field(60, ge=5)
|
|
95
|
+
failure_threshold: int = Field(3, ge=1) # 当前协议连续失败这么多次就切换
|
|
96
|
+
latency_ratio: float = Field(1.3, ge=1.0) # 延迟中位数差到这个倍数……
|
|
97
|
+
latency_margin_ms: float = Field(100, ge=0) # ……并且差值超过这么多毫秒才切换
|
|
98
|
+
cooldown_seconds: float = Field(600, ge=0) # 两次切换的最小间隔(当前协议完全不可用时除外)
|
|
99
|
+
prefer: Literal["hysteria2", "trojan"] = "hysteria2"
|
|
100
|
+
test_url: str = "https://www.gstatic.com/generate_204"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Proxy(_Strict):
|
|
104
|
+
protocol: Literal["auto", "hysteria2", "trojan"] = "hysteria2"
|
|
105
|
+
server: str = ""
|
|
106
|
+
credential_ref: str = ""
|
|
107
|
+
password: str = ""
|
|
108
|
+
traffic_mode: Literal["mixed", "system-proxy", "tun", "transparent"] = "mixed"
|
|
109
|
+
hysteria2: ProtoPort = ProtoPort()
|
|
110
|
+
trojan: Trojan = Trojan()
|
|
111
|
+
tls: ProxyTls = ProxyTls()
|
|
112
|
+
selection: Selection = Selection()
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def port(self) -> int:
|
|
116
|
+
return self.port_of(self.protocol if self.protocol != "auto" else self.selection.prefer)
|
|
117
|
+
|
|
118
|
+
def port_of(self, protocol: str) -> int:
|
|
119
|
+
return getattr(self, protocol).port
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Tun(_Strict):
|
|
123
|
+
interface_name: str = "norain0"
|
|
124
|
+
address: list[str] = ["172.19.0.1/30", "fdfe:dcba:9876::1/126"]
|
|
125
|
+
mtu: int = Field(9000, ge=576, le=65535)
|
|
126
|
+
strict_route: bool = True
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Routing(_Strict):
|
|
130
|
+
proxy_domains: list[str] = list(defaults.PROXY_DOMAINS) # 白名单:强制走代理
|
|
131
|
+
direct_domains: list[str] = list(defaults.DIRECT_DOMAINS) # 黑名单:强制直连
|
|
132
|
+
isolation_allowlist: list[str] = list(defaults.ISOLATION_ALLOWLIST) # 蓝名单:阻断模式下仍允许
|
|
133
|
+
rule_set: list[str] = list(KNOWN_RULE_SETS) # 判为「国内 → 直连」的规则集;文件缺失时自动跳过
|
|
134
|
+
default_action: Literal["proxy", "direct"] = "proxy"
|
|
135
|
+
learn: bool = True # 按最初目标的试连流程自动改判并加入名单
|
|
136
|
+
update_interval_hours: float = Field(24, ge=0) # 规则集自更新间隔,0 表示不自动更新
|
|
137
|
+
allow_lan_in_isolation: bool = True
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Dns(_Strict):
|
|
141
|
+
mode: Literal["local", "split", "proxy"] = "split"
|
|
142
|
+
domestic: str = "223.5.5.5" # 国内 DNS(直连)
|
|
143
|
+
proxy: str = "https://1.1.1.1/dns-query" # 经代理服务器访问的国外 DNS
|
|
144
|
+
domestic_doh: str = "https://223.5.5.5/resolve" # 分流判断用的 JSON 查询接口(直连)
|
|
145
|
+
public_doh: str = "https://1.1.1.1/dns-query" # 分流判断用的 JSON 查询接口(经代理)
|
|
146
|
+
strategy: Literal["prefer_ipv4", "prefer_ipv6", "ipv4_only", "ipv6_only"] = "prefer_ipv4"
|
|
147
|
+
cache_ttl_seconds: int = Field(300, ge=0) # 学到的解析结果(hosts 覆盖)的保留时间
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Monitor(_Strict):
|
|
151
|
+
enabled: bool = True
|
|
152
|
+
interval_seconds: float = Field(30, ge=1)
|
|
153
|
+
timeout_seconds: float = Field(5, ge=1, le=60)
|
|
154
|
+
failure_threshold: int = Field(3, ge=1)
|
|
155
|
+
recovery_threshold: int = Field(2, ge=1)
|
|
156
|
+
home_country: str = "CN" # 「国内位置」的国家代码
|
|
157
|
+
domestic_targets: list[str] = ["https://www.baidu.com", "https://www.qq.com", "https://www.taobao.com"]
|
|
158
|
+
foreign_targets: list[str] = ["https://www.google.com/generate_204", "https://www.youtube.com",
|
|
159
|
+
"https://github.com", "https://www.wikipedia.org"]
|
|
160
|
+
trace_v4: str = "https://1.1.1.1/cdn-cgi/trace"
|
|
161
|
+
trace_v6: str = "https://[2606:4700:4700::1111]/cdn-cgi/trace"
|
|
162
|
+
dns_test_domains: list[str] = ["www.google.com", "www.youtube.com"]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Maintain(_Strict):
|
|
166
|
+
scan_interval_seconds: float = Field(5, ge=1, le=300)
|
|
167
|
+
repair_attempts: int = Field(2, ge=1, le=10) # 每个故障最多尝试几轮修复,之后进入阻断
|
|
168
|
+
block_on_failure: bool = True
|
|
169
|
+
watchdog: bool = True # 与看门狗进程互拉保活
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class SupervisorCfg(_Strict):
|
|
173
|
+
check_interval_seconds: float = Field(30, ge=1, le=3600)
|
|
174
|
+
restart_limit: int = Field(3, ge=0, le=100)
|
|
175
|
+
backoff_seconds: float = Field(5, ge=0, le=300)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Logging(_Strict):
|
|
179
|
+
directory: str = ""
|
|
180
|
+
level: Literal["debug", "info", "warn", "error"] = "info"
|
|
181
|
+
max_size_mb: int = Field(20, ge=1, le=1024)
|
|
182
|
+
retain_files: int = Field(5, ge=1, le=100)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class ClientConfig(_Strict):
|
|
186
|
+
_config_warnings: list[str] = PrivateAttr(default_factory=list)
|
|
187
|
+
schema_version: int = Field(SCHEMA_VERSION, alias="schema")
|
|
188
|
+
app: App = App()
|
|
189
|
+
local: Local = Local()
|
|
190
|
+
proxy: Proxy = Proxy()
|
|
191
|
+
tun: Tun = Tun()
|
|
192
|
+
routing: Routing = Routing()
|
|
193
|
+
dns: Dns = Dns()
|
|
194
|
+
monitor: Monitor = Monitor()
|
|
195
|
+
maintain: Maintain = Maintain()
|
|
196
|
+
supervisor: SupervisorCfg = SupervisorCfg()
|
|
197
|
+
logging: Logging = Logging()
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def protocols(self) -> tuple[str, ...]:
|
|
201
|
+
"""本配置会用到的协议。auto 时两套都生成。"""
|
|
202
|
+
return PROTOCOLS if self.proxy.protocol == "auto" else (self.proxy.protocol,)
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def autostart_wanted(self) -> bool:
|
|
206
|
+
return self.app.mode == "normal" and self.app.auto_start
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
_MESSAGES = {
|
|
210
|
+
"missing": "缺少必填字段", "extra_forbidden": "未知字段", "int_parsing": "必须是整数",
|
|
211
|
+
"int_type": "必须是整数", "bool_type": "必须是 true 或 false", "bool_parsing": "必须是 true 或 false",
|
|
212
|
+
"string_type": "必须是字符串", "list_type": "必须是列表", "float_type": "必须是数字",
|
|
213
|
+
"float_parsing": "必须是数字",
|
|
214
|
+
"model_type": "必须是一个表([section])", "model_attributes_type": "必须是一个表([section])",
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _known(model: type[BaseModel], out: set[str]) -> set[str]:
|
|
219
|
+
for name, f in model.model_fields.items():
|
|
220
|
+
out.add(f.alias or name)
|
|
221
|
+
if isinstance(f.annotation, type) and issubclass(f.annotation, BaseModel):
|
|
222
|
+
_known(f.annotation, out)
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
_KNOWN = _known(ClientConfig, set())
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _translate(err: dict) -> FieldError:
|
|
230
|
+
path = ".".join(str(p) for p in err["loc"]) or "(顶层)"
|
|
231
|
+
kind, ctx = err["type"], err.get("ctx", {})
|
|
232
|
+
msg = _MESSAGES.get(kind)
|
|
233
|
+
if kind == "extra_forbidden":
|
|
234
|
+
close = difflib.get_close_matches(str(err["loc"][-1]), _KNOWN, n=1)
|
|
235
|
+
msg += f",是不是想写 {close[0]}?" if close else ""
|
|
236
|
+
elif kind in ("greater_than_equal", "less_than_equal"):
|
|
237
|
+
msg = f"超出范围({'不能小于' if 'ge' in ctx else '不能大于'} {ctx.get('ge', ctx.get('le'))})"
|
|
238
|
+
elif kind == "literal_error":
|
|
239
|
+
msg = f"取值无效,可选:{ctx.get('expected', '')}"
|
|
240
|
+
elif kind == "value_error":
|
|
241
|
+
msg = str(ctx.get("error", err["msg"]))
|
|
242
|
+
return FieldError(path, msg or err["msg"])
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ---- 名单条目 ------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
def split_entries(entries: list[str]) -> dict[str, list[str]]:
|
|
248
|
+
"""把名单条目分成 sing-box 规则字段:
|
|
249
|
+
`example.com` → domain_suffix;`full:example.com` → domain;IP 或 CIDR → ip_cidr。"""
|
|
250
|
+
out: dict[str, list[str]] = {"domain": [], "domain_suffix": [], "ip_cidr": []}
|
|
251
|
+
for raw in entries:
|
|
252
|
+
e = raw.strip().lower()
|
|
253
|
+
if not e:
|
|
254
|
+
continue
|
|
255
|
+
if e.startswith("full:"):
|
|
256
|
+
out["domain"].append(e[5:])
|
|
257
|
+
continue
|
|
258
|
+
try:
|
|
259
|
+
ipaddress.ip_network(e, strict=False)
|
|
260
|
+
out["ip_cidr"].append(e)
|
|
261
|
+
except ValueError:
|
|
262
|
+
out["domain_suffix"].append(e.lstrip("."))
|
|
263
|
+
return {k: v for k, v in out.items() if v}
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _entry_error(e: str) -> str | None:
|
|
267
|
+
s = e.strip()
|
|
268
|
+
body = s[5:] if s.lower().startswith("full:") else s
|
|
269
|
+
if not body:
|
|
270
|
+
return "条目不能为空"
|
|
271
|
+
if any(c.isspace() for c in body) or "://" in body:
|
|
272
|
+
return f"{e!r} 不是域名、IP 或 CIDR(不要带 http:// 和路径)"
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def entry_key(e: str) -> str:
|
|
277
|
+
s = e.strip().lower()
|
|
278
|
+
return s[5:] if s.startswith("full:") else s.lstrip(".")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _cross_checks(cfg: ClientConfig) -> list[FieldError]:
|
|
282
|
+
errs: list[FieldError] = []
|
|
283
|
+
if cfg.proxy.traffic_mode == "transparent":
|
|
284
|
+
errs.append(FieldError("proxy.traffic_mode",
|
|
285
|
+
"transparent 尚未实现;全局接管请用 tun,其余可用 mixed 或 system-proxy"))
|
|
286
|
+
if not cfg.proxy.server.strip():
|
|
287
|
+
errs.append(FieldError("proxy.server", "不能为空(代理服务器的域名或 IP)"))
|
|
288
|
+
if not cfg.proxy.password and not cfg.proxy.credential_ref and not os.environ.get("NORAIN_PASSWORD"):
|
|
289
|
+
errs.append(FieldError("proxy.credential_ref", "不能为空(使用 file:<路径>、env:<变量名> 或 NORAIN_PASSWORD)"))
|
|
290
|
+
if cfg.proxy.password and cfg.proxy.credential_ref:
|
|
291
|
+
errs.append(FieldError("proxy", "password 和 credential_ref 只能设置一个"))
|
|
292
|
+
cert = cfg.proxy.tls.certificate_path
|
|
293
|
+
if cert and not Path(cert).expanduser().is_file():
|
|
294
|
+
errs.append(FieldError("proxy.tls.certificate_path", f"文件不存在:{cert}"))
|
|
295
|
+
|
|
296
|
+
for name in ("proxy_domains", "direct_domains", "isolation_allowlist"):
|
|
297
|
+
for e in getattr(cfg.routing, name):
|
|
298
|
+
msg = _entry_error(e)
|
|
299
|
+
if msg:
|
|
300
|
+
errs.append(FieldError(f"routing.{name}", msg))
|
|
301
|
+
both = {entry_key(e) for e in cfg.routing.proxy_domains} & {entry_key(e) for e in cfg.routing.direct_domains}
|
|
302
|
+
if both: # 同一条目同时在白名单和黑名单:直接报错,不做隐式优先
|
|
303
|
+
errs.append(FieldError("routing", "同时出现在 proxy_domains 和 direct_domains 中:" + "、".join(sorted(both))))
|
|
304
|
+
for rs in cfg.routing.rule_set:
|
|
305
|
+
if rs not in KNOWN_RULE_SETS and not (rs.endswith(".srs") and Path(rs).expanduser().is_file()):
|
|
306
|
+
errs.append(FieldError("routing.rule_set",
|
|
307
|
+
f"{rs!r} 不是内置规则集({'、'.join(KNOWN_RULE_SETS)}),也不是存在的 .srs 文件"))
|
|
308
|
+
|
|
309
|
+
try:
|
|
310
|
+
ipaddress.ip_address(cfg.dns.domestic)
|
|
311
|
+
except ValueError:
|
|
312
|
+
errs.append(FieldError("dns.domestic", "必须是 IP 地址,例如 223.5.5.5"))
|
|
313
|
+
for name in ("proxy", "domestic_doh", "public_doh"):
|
|
314
|
+
value = getattr(cfg.dns, name)
|
|
315
|
+
u = urlsplit(value)
|
|
316
|
+
try:
|
|
317
|
+
u.port # 非法端口(例如 :bad)会让 urlsplit 抛 ValueError
|
|
318
|
+
except ValueError:
|
|
319
|
+
errs.append(FieldError(f"dns.{name}", "端口不是有效的数字"))
|
|
320
|
+
continue
|
|
321
|
+
is_ip = False
|
|
322
|
+
try:
|
|
323
|
+
ipaddress.ip_address(value)
|
|
324
|
+
is_ip = name == "proxy" # dns.proxy 允许直接写 IP(UDP)
|
|
325
|
+
except ValueError:
|
|
326
|
+
pass
|
|
327
|
+
if not is_ip and (u.scheme != "https" or not u.hostname):
|
|
328
|
+
errs.append(FieldError(f"dns.{name}", "必须是 https://… 地址" + ("或 IP 地址" if name == "proxy" else "")))
|
|
329
|
+
for name in ("domestic_targets", "foreign_targets"):
|
|
330
|
+
for t in getattr(cfg.monitor, name):
|
|
331
|
+
if urlsplit(t).scheme not in ("http", "https"):
|
|
332
|
+
errs.append(FieldError(f"monitor.{name}", f"{t!r} 必须是 http(s):// 地址"))
|
|
333
|
+
if cfg.monitor.enabled and not (cfg.monitor.domestic_targets and cfg.monitor.foreign_targets):
|
|
334
|
+
errs.append(FieldError("monitor", "启用监控时 domestic_targets 和 foreign_targets 都不能为空"))
|
|
335
|
+
ports = [cfg.local.port, *range(cfg.local.probe_port, cfg.local.probe_port + 3)]
|
|
336
|
+
if len(set(ports)) != len(ports):
|
|
337
|
+
errs.append(FieldError("local.probe_port", "探测端口(连续 3 个)不能和 local.port 重叠"))
|
|
338
|
+
for a in cfg.tun.address:
|
|
339
|
+
try:
|
|
340
|
+
ipaddress.ip_interface(a)
|
|
341
|
+
except ValueError:
|
|
342
|
+
errs.append(FieldError("tun.address", f"{a!r} 不是带前缀长度的地址,例如 172.19.0.1/30"))
|
|
343
|
+
return errs
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def parse(data: dict, *, source: str = "cfg.toml") -> ClientConfig:
|
|
347
|
+
"""迁移并校验一份已经解析成字典的配置(不检查文件权限)。"""
|
|
348
|
+
migration = migrate(data, current=SCHEMA_VERSION, source=source)
|
|
349
|
+
try:
|
|
350
|
+
cfg = ClientConfig.model_validate(migration.data)
|
|
351
|
+
except ValidationError as e:
|
|
352
|
+
raise config_error([_translate(x) for x in e.errors()]) from None
|
|
353
|
+
attach_warnings(cfg, migration)
|
|
354
|
+
errs = _cross_checks(cfg)
|
|
355
|
+
if errs:
|
|
356
|
+
raise config_error(errs)
|
|
357
|
+
return cfg
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def migrate_doc(data: dict, *, source: str = "cfg.toml") -> MigrationResult:
|
|
361
|
+
"""只做 Schema 迁移、不校验字段:写盘前用它拿到要落盘的数据。
|
|
362
|
+
|
|
363
|
+
命令行改配置时会重写整个文件,顺手把迁移结果写进去,否则「缺少 schema」
|
|
364
|
+
的 warning 每次加载都会再出现一遍。
|
|
365
|
+
"""
|
|
366
|
+
return migrate(data, current=SCHEMA_VERSION, source=source)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def read_raw(path: Path) -> dict:
|
|
370
|
+
try:
|
|
371
|
+
with path.open("rb") as f:
|
|
372
|
+
return tomllib.load(f)
|
|
373
|
+
except FileNotFoundError:
|
|
374
|
+
raise NorainError(f"配置文件不存在:{path}", exit_code=EXIT_CONFIG, business_code=BIZ_CONFIG,
|
|
375
|
+
module="config", hint="运行 norain install,或参考 examples/cfg.toml 创建") from None
|
|
376
|
+
except PermissionError:
|
|
377
|
+
raise NorainError(f"无权读取配置文件:{path}", exit_code=4, business_code=BIZ_CONFIG,
|
|
378
|
+
module="config") from None
|
|
379
|
+
except tomllib.TOMLDecodeError as e:
|
|
380
|
+
raise config_error([FieldError("(TOML 语法)", str(e))]) from None
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def load_config(path: Path) -> ClientConfig:
|
|
384
|
+
cfg = parse(read_raw(path), source=str(path))
|
|
385
|
+
if cfg.proxy.password:
|
|
386
|
+
REDACTOR.register(cfg.proxy.password)
|
|
387
|
+
try:
|
|
388
|
+
check_private_file(path, field="proxy.password")
|
|
389
|
+
except NorainError as e:
|
|
390
|
+
raise config_error([FieldError(fe.path, fe.message + "(配置里直接写了密码)")
|
|
391
|
+
for fe in e.field_errors]) from None
|
|
392
|
+
return cfg
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def warnings_of(cfg: ClientConfig) -> list[str]:
|
|
396
|
+
"""这份配置值得提醒用户的全部事情:迁移 warning 加上取值、运行模式的提示。"""
|
|
397
|
+
out = migration_warnings(cfg)
|
|
398
|
+
if cfg.proxy.tls.insecure:
|
|
399
|
+
out.append("proxy.tls.insecure = true:不校验服务端证书,连接可能被中间人劫持")
|
|
400
|
+
if cfg.local.listen not in ("127.0.0.1", "::1"):
|
|
401
|
+
out.append(f"本地代理监听在 {cfg.local.listen},局域网内其他设备也能使用它,且没有认证")
|
|
402
|
+
if cfg.proxy.traffic_mode != "tun":
|
|
403
|
+
out.append(f"traffic_mode = {cfg.proxy.traffic_mode}:只有使用本地代理的程序才走代理,不是全局接管;"
|
|
404
|
+
"DNS 分流只在 tun 模式下对全部程序生效")
|
|
405
|
+
if not cfg.monitor.enabled:
|
|
406
|
+
out.append("监控已关闭:自维持模块无法发现链路故障,也不会触发阻断")
|
|
407
|
+
if os.name == "nt" and (cfg.proxy.password or cfg.proxy.credential_ref.startswith("file:")):
|
|
408
|
+
out.append("Windows 上不检查密码文件的访问权限,请自行确认其他用户读不到它")
|
|
409
|
+
return out
|