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.
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.dev0.dist-info/METADATA +99 -0
  21. norain-0.2.0.dev0.dist-info/RECORD +53 -0
  22. norain-0.2.0.dev0.dist-info/WHEEL +5 -0
  23. norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
  24. norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
  25. norain-0.2.0.dev0.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
@@ -0,0 +1,226 @@
1
+ """防火墙模块:放行或关闭服务端协议端口。
2
+
3
+ 原则(最初目标):只放行配置中启用的端口;不开放无关端口;关闭协议或卸载时移除对应规则;
4
+ 操作失败必须给出具体原因。Norain 只移除自己创建的规则——创建过的规则记在
5
+ `<state>/firewall.json` 里,用户原有的同端口规则不会被动到。
6
+
7
+ 后端:Linux 优先 ufw,其次 firewalld,都没有时提示手动放行;Windows 用 netsh advfirewall。
8
+ ufw 后端已实测(install 放行端口、uninstall 撤回规则);firewalld 与 netsh 未实测。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import shutil
14
+ import time
15
+ from dataclasses import dataclass
16
+
17
+ from norain_core import osutil
18
+ from norain_core.errors import EXIT_EXTERNAL, NorainError
19
+ from norain_core.state import read_json, write_json
20
+
21
+ from .model import ServerConfig
22
+ from .paths import Paths
23
+ from .runner import firewall_ports
24
+
25
+ PREFIX = "norain-server"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Rule:
30
+ proto: str # tcp | udp
31
+ port: int
32
+ label: str # hysteria2 | trojan | acme
33
+
34
+ @property
35
+ def key(self) -> str:
36
+ return f"{self.port}/{self.proto}"
37
+
38
+ @property
39
+ def name(self) -> str:
40
+ return f"{PREFIX}-{self.label}-{self.proto}-{self.port}"
41
+
42
+
43
+ class UfwBackend:
44
+ name = "ufw"
45
+
46
+ def is_open(self, r: Rule) -> bool:
47
+ out = osutil.run(["ufw", "status"]).stdout
48
+ return any(line.split()[:1] == [r.key] and "ALLOW" in line for line in out.splitlines())
49
+
50
+ def active(self) -> bool:
51
+ return "Status: active" in osutil.run(["ufw", "status"]).stdout
52
+
53
+ def open(self, r: Rule) -> None:
54
+ osutil.run_checked(["ufw", "allow", r.key, "comment", r.name], what=f"放行 {r.key}", module="firewall")
55
+
56
+ def close(self, r: Rule) -> None:
57
+ osutil.run_checked(["ufw", "delete", "allow", r.key], what=f"关闭 {r.key}", module="firewall")
58
+
59
+ def manual(self, r: Rule, action: str) -> str:
60
+ return f"ufw allow {r.key}" if action == "open" else f"ufw delete allow {r.key}"
61
+
62
+
63
+ class FirewalldBackend:
64
+ name = "firewalld"
65
+
66
+ def is_open(self, r: Rule) -> bool:
67
+ return osutil.run(["firewall-cmd", "--permanent", f"--query-port={r.key}"]).returncode == 0
68
+
69
+ def active(self) -> bool:
70
+ return osutil.run(["firewall-cmd", "--state"]).returncode == 0
71
+
72
+ def _apply(self, flag: str, r: Rule, what: str) -> None:
73
+ osutil.run_checked(["firewall-cmd", "--permanent", f"{flag}={r.key}"], what=what, module="firewall")
74
+ osutil.run_checked(["firewall-cmd", "--reload"], what="重载 firewalld", module="firewall")
75
+
76
+ def open(self, r: Rule) -> None:
77
+ self._apply("--add-port", r, f"放行 {r.key}")
78
+
79
+ def close(self, r: Rule) -> None:
80
+ self._apply("--remove-port", r, f"关闭 {r.key}")
81
+
82
+ def manual(self, r: Rule, action: str) -> str:
83
+ flag = "--add-port" if action == "open" else "--remove-port"
84
+ return f"firewall-cmd --permanent {flag}={r.key} && firewall-cmd --reload"
85
+
86
+
87
+ class NetshBackend:
88
+ name = "netsh"
89
+
90
+ def is_open(self, r: Rule) -> bool:
91
+ return osutil.run(["netsh", "advfirewall", "firewall", "show", "rule", f"name={r.name}"]).returncode == 0
92
+
93
+ def active(self) -> bool:
94
+ return True
95
+
96
+ def open(self, r: Rule) -> None:
97
+ osutil.run_checked(["netsh", "advfirewall", "firewall", "add", "rule", f"name={r.name}", "dir=in",
98
+ "action=allow", f"protocol={r.proto.upper()}", f"localport={r.port}"],
99
+ what=f"放行 {r.key}", module="firewall")
100
+
101
+ def close(self, r: Rule) -> None:
102
+ osutil.run_checked(["netsh", "advfirewall", "firewall", "delete", "rule", f"name={r.name}"],
103
+ what=f"关闭 {r.key}", module="firewall")
104
+
105
+ def manual(self, r: Rule, action: str) -> str:
106
+ if action == "open":
107
+ return (f'netsh advfirewall firewall add rule name="{r.name}" dir=in action=allow '
108
+ f"protocol={r.proto.upper()} localport={r.port}")
109
+ return f'netsh advfirewall firewall delete rule name="{r.name}"'
110
+
111
+
112
+ def detect():
113
+ if osutil.IS_WINDOWS:
114
+ return NetshBackend()
115
+ if shutil.which("ufw"):
116
+ return UfwBackend()
117
+ if shutil.which("firewall-cmd"):
118
+ return FirewalldBackend()
119
+ return None
120
+
121
+
122
+ def wanted(cfg: ServerConfig) -> list[Rule]:
123
+ return [Rule(proto, port, label) for proto, port, label in firewall_ports(cfg)]
124
+
125
+
126
+ def _recorded(paths: Paths) -> list[Rule]:
127
+ data = read_json(paths.firewall_state) or {}
128
+ return [Rule(r["proto"], int(r["port"]), r.get("label", "port")) for r in data.get("rules", [])]
129
+
130
+
131
+ def _save(paths: Paths, backend_name: str | None, rules: list[Rule]) -> None:
132
+ if not rules:
133
+ paths.firewall_state.unlink(missing_ok=True)
134
+ return
135
+ write_json(paths.firewall_state, {
136
+ "backend": backend_name, "updated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
137
+ "rules": [{"proto": r.proto, "port": r.port, "label": r.label} for r in rules]})
138
+
139
+
140
+ def _manual_only(rules: list[Rule], action: str) -> dict:
141
+ cmds = [f"iptables -{'I' if action == 'open' else 'D'} INPUT -p {r.proto} --dport {r.port} -j ACCEPT"
142
+ for r in rules]
143
+ return {"backend": None, "applied": False, "ports": [r.key for r in rules], "manual_commands": cmds,
144
+ "note": "没有找到 ufw 或 firewalld,请手动放行(云服务器还要检查安全组)"}
145
+
146
+
147
+ def open_ports(cfg: ServerConfig, paths: Paths) -> dict:
148
+ """放行配置中启用的端口,并移除 Norain 以前放行、现在已不需要的端口。"""
149
+ want = wanted(cfg)
150
+ backend = detect()
151
+ if backend is None:
152
+ return _manual_only(want, "open")
153
+ osutil.require_admin("修改防火墙", module="firewall")
154
+ recorded = _recorded(paths)
155
+ opened, kept, closed, errors = [], [], [], []
156
+ mine = list(recorded)
157
+ for r in want:
158
+ if r in recorded or backend.is_open(r):
159
+ kept.append(r.key) # 已经放行(可能是用户自己的规则,不记到 Norain 名下)
160
+ continue
161
+ try:
162
+ backend.open(r)
163
+ opened.append(r.key)
164
+ mine.append(r)
165
+ except NorainError as e:
166
+ errors.append(e.message)
167
+ for r in recorded:
168
+ if r not in want: # 协议已关闭或端口已更换
169
+ try:
170
+ backend.close(r)
171
+ closed.append(r.key)
172
+ mine.remove(r)
173
+ except NorainError as e:
174
+ errors.append(e.message)
175
+ _save(paths, backend.name, mine)
176
+ result = {"backend": backend.name, "applied": True, "ports": [r.key for r in want],
177
+ "opened": opened, "already_open": kept, "closed_stale": closed}
178
+ if not backend.active():
179
+ result["note"] = f"{backend.name} 当前没有启用,规则已写入但不生效"
180
+ if errors:
181
+ raise NorainError("防火墙操作失败:" + ";".join(errors), exit_code=EXIT_EXTERNAL, module="firewall",
182
+ hint="已成功的部分保留,修正后可重新运行 firewall open")
183
+ return result
184
+
185
+
186
+ def close_ports(paths: Paths, cfg: ServerConfig | None = None) -> dict:
187
+ """移除 Norain 创建的全部规则。不依赖配置文件可读(卸载时配置可能已损坏)。"""
188
+ recorded = _recorded(paths)
189
+ backend = detect()
190
+ if backend is None:
191
+ return _manual_only(recorded or (wanted(cfg) if cfg else []), "close")
192
+ if not recorded:
193
+ return {"backend": backend.name, "applied": True, "closed": [],
194
+ "note": "没有 Norain 创建的规则;用户自己添加的规则不会被移除"}
195
+ osutil.require_admin("修改防火墙", module="firewall")
196
+ closed, errors, left = [], [], []
197
+ for r in recorded:
198
+ try:
199
+ if backend.is_open(r):
200
+ backend.close(r)
201
+ closed.append(r.key)
202
+ except NorainError as e:
203
+ errors.append(e.message)
204
+ left.append(r)
205
+ _save(paths, backend.name, left)
206
+ if errors:
207
+ raise NorainError("防火墙操作失败:" + ";".join(errors), exit_code=EXIT_EXTERNAL, module="firewall")
208
+ return {"backend": backend.name, "applied": True, "closed": closed}
209
+
210
+
211
+ def status(cfg: ServerConfig, paths: Paths) -> dict:
212
+ want = wanted(cfg)
213
+ backend = detect()
214
+ recorded = {r.key for r in _recorded(paths)}
215
+ rows = []
216
+ for r in want:
217
+ state = None
218
+ if backend is not None:
219
+ try:
220
+ state = backend.is_open(r)
221
+ except Exception: # noqa: BLE001 查询失败时如实标为未知
222
+ state = None
223
+ rows.append({"port": r.key, "purpose": r.label, "open": state, "managed_by_norain": r.key in recorded})
224
+ return {"backend": backend.name if backend else None,
225
+ "active": backend.active() if backend else None, "ports": rows,
226
+ "manual_commands": [] if backend else _manual_only(want, "open")["manual_commands"]}
@@ -0,0 +1,112 @@
1
+ """server.toml → sing-box JSON,以及「生成 → check → 备份 → 原子替换」流程。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from norain_core import apply as core_apply
8
+ from norain_core.secrets import Secret, resolve
9
+
10
+ from .model import SCHEMA_VERSION, ServerConfig
11
+ from .paths import Paths
12
+
13
+ USER_NAME = "norain"
14
+ ACME_TAG = "norain-acme"
15
+
16
+
17
+ def resolve_secret(cfg: ServerConfig) -> Secret:
18
+ if cfg.auth.password:
19
+ return Secret(value=cfg.auth.password, source="config:auth.password")
20
+ return resolve(cfg.auth.credential_ref)
21
+
22
+
23
+ def cert_paths(cfg: ServerConfig, paths: Paths) -> tuple[Path, Path]:
24
+ """manual / self-signed 的证书和私钥路径。acme 模式没有固定文件,返回值不会被使用。"""
25
+ if cfg.tls.mode == "acme":
26
+ return paths.acme_dir / "acme.crt", paths.acme_dir / "acme.key"
27
+ if cfg.tls.mode == "self-signed" and not (cfg.tls.certificate and cfg.tls.private_key):
28
+ return paths.tls_dir / "self-signed.crt", paths.tls_dir / "self-signed.key"
29
+ return Path(cfg.tls.certificate).expanduser(), Path(cfg.tls.private_key).expanduser()
30
+
31
+
32
+ def acme_provider(cfg: ServerConfig, acme_dir: Path) -> dict:
33
+ """sing-box 1.14 的顶层 certificate_providers 条目(不使用已弃用的 TLS 内联 acme)。
34
+
35
+ 挑战方式:默认 HTTP-01(需要 80/tcp 可从公网访问)。TLS-ALPN-01 需要 443/tcp 上的 TLS
36
+ 监听,只有 Trojan 正好监听 443/tcp 时才保留,其余情况显式关闭。
37
+ """
38
+ tj = cfg.protocols.trojan
39
+ prov: dict = {"type": "acme", "tag": ACME_TAG, "domain": [cfg.server.domain],
40
+ "data_directory": str(acme_dir),
41
+ "disable_tls_alpn_challenge": not (tj.enabled and tj.port == 443)}
42
+ if cfg.tls.email:
43
+ prov["email"] = cfg.tls.email
44
+ if cfg.tls.acme_provider:
45
+ prov["provider"] = cfg.tls.acme_provider
46
+ return prov
47
+
48
+
49
+ def build(cfg: ServerConfig, password: str, cert: Path, key: Path, *,
50
+ acme_dir: Path | None = None) -> dict:
51
+ """生成 sing-box 1.14 配置。已用真实 sing-box 1.14.4 check 验证 5 种组合。"""
52
+ acme = cfg.tls.mode == "acme"
53
+
54
+ def tls(**extra) -> dict:
55
+ if acme:
56
+ return {"enabled": True, "server_name": cfg.server.domain,
57
+ "certificate_provider": ACME_TAG, **extra}
58
+ return {"enabled": True, "server_name": cfg.server.domain,
59
+ "certificate_path": str(cert), "key_path": str(key), **extra}
60
+
61
+ users = [{"name": USER_NAME, "password": password}]
62
+ inbounds = []
63
+ if cfg.protocols.hysteria2.enabled:
64
+ inbounds.append({
65
+ "type": "hysteria2", "tag": "hy2-in",
66
+ "listen": cfg.server.listen, "listen_port": cfg.protocols.hysteria2.port,
67
+ "users": users, "tls": tls(alpn=["h3"]),
68
+ })
69
+ if cfg.protocols.trojan.enabled:
70
+ inbound = {
71
+ "type": "trojan", "tag": "trojan-in",
72
+ "listen": cfg.server.listen, "listen_port": cfg.protocols.trojan.port,
73
+ "users": users, "tls": tls(),
74
+ }
75
+ fb = cfg.protocols.trojan.fallback
76
+ if fb:
77
+ inbound["fallback"] = {"server": fb.host, "server_port": fb.port}
78
+ inbounds.append(inbound)
79
+ outbounds: list[dict] = [{"type": "direct", "tag": "direct"}]
80
+ route_rules: list[dict] = []
81
+ warp = cfg.routing.warp
82
+ if warp is not None and warp.domains:
83
+ # 与原来的服务端一致:这些域名从本机 WARP 出去,其余直连
84
+ host, _, port = warp.address.rpartition(":")
85
+ outbounds.insert(0, {"type": "socks", "tag": "warp", "server": host, "server_port": int(port)})
86
+ route_rules.append({"domain_suffix": [d.strip().lower() for d in warp.domains],
87
+ "outbound": "warp"})
88
+ doc: dict = {
89
+ "log": {"level": cfg.logging.level, "timestamp": True},
90
+ "inbounds": inbounds,
91
+ "outbounds": outbounds,
92
+ "route": {"final": "direct", **({"rules": route_rules} if route_rules else {})},
93
+ }
94
+ if acme:
95
+ doc["certificate_providers"] = [acme_provider(cfg, acme_dir or Path("acme"))]
96
+ return doc
97
+
98
+
99
+ dumps, version_of, ApplyResult = core_apply.dumps, core_apply.version_of, core_apply.ApplyResult
100
+
101
+
102
+ def render(cfg: ServerConfig, secret: Secret, paths: Paths) -> bytes:
103
+ cert, key = cert_paths(cfg, paths)
104
+ return dumps(build(cfg, secret.value, cert, key, acme_dir=paths.acme_dir))
105
+
106
+
107
+ def apply(cfg: ServerConfig, secret: Secret, paths: Paths, binary: Path) -> ApplyResult:
108
+ """生成候选配置并用 sing-box check 校验,通过后才替换当前配置。"""
109
+ return core_apply.apply(render(cfg, secret, paths), run_dir=paths.run_dir,
110
+ current=paths.current_json, backups=paths.backups,
111
+ meta=paths.meta_json, source=paths.config, schema=SCHEMA_VERSION,
112
+ binary=binary)
norain_server/model.py ADDED
@@ -0,0 +1,272 @@
1
+ """server.toml 配置模型和字段级校验。映射规则见 docs/decisions/0004。
2
+
3
+ 加载顺序是「迁移 → 环境变量覆盖 → 字段校验 → 交叉校验」:Schema 版本策略和
4
+ 逐级迁移在 ``norain_core.migrate``,本模块只取结果;迁移产生的 warning 挂在
5
+ 配置对象上,由 ``migration_warnings`` 读取(服务端没有额外的取值提醒)。"""
6
+
7
+ from __future__ import annotations
8
+
9
+ import difflib
10
+ import ipaddress
11
+ import os
12
+ import tomllib
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, ValidationError, field_validator
17
+
18
+ from norain_core.errors import BIZ_CONFIG, EXIT_CONFIG, FieldError, NorainError, config_error
19
+ from norain_core.migrate import SCHEMA_VERSION, attach_warnings, migrate
20
+ from norain_core.redact import REDACTOR
21
+ from norain_core.secrets import check_private_file
22
+
23
+ Port = Field(ge=1, le=65535)
24
+
25
+
26
+ class _Strict(BaseModel):
27
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
28
+
29
+
30
+ class Server(_Strict):
31
+ domain: str = ""
32
+ listen: str = "::"
33
+
34
+ @field_validator("listen")
35
+ @classmethod
36
+ def _listen_is_ip(cls, v: str) -> str:
37
+ try:
38
+ ipaddress.ip_address(v)
39
+ except ValueError:
40
+ raise ValueError("必须是 IP 地址,例如 :: 或 0.0.0.0") from None
41
+ return v
42
+
43
+
44
+ class Hysteria2(_Strict):
45
+ enabled: bool = True
46
+ port: int = Field(443, ge=1, le=65535)
47
+
48
+
49
+ class Fallback(_Strict):
50
+ host: str = "127.0.0.1"
51
+ port: int = Port
52
+
53
+
54
+ class Trojan(_Strict):
55
+ enabled: bool = False
56
+ port: int = Field(443, ge=1, le=65535)
57
+ fallback: Fallback | None = None
58
+
59
+
60
+ class Protocols(_Strict):
61
+ hysteria2: Hysteria2 = Hysteria2()
62
+ trojan: Trojan = Trojan()
63
+
64
+
65
+ class Auth(_Strict):
66
+ credential_ref: str = ""
67
+ password: str = ""
68
+
69
+
70
+ class Tls(_Strict):
71
+ mode: Literal["acme", "manual", "self-signed"] = "manual"
72
+ certificate: str = ""
73
+ private_key: str = ""
74
+ email: str = "" # acme:注册邮箱,可留空
75
+ acme_provider: str = "" # acme:留空为 letsencrypt,可写 zerossl 或 https://… 目录地址
76
+
77
+
78
+ class Service(_Strict):
79
+ check_interval_seconds: float = Field(30, ge=1, le=3600)
80
+ restart_limit: int = Field(3, ge=0, le=100)
81
+ restart_backoff_seconds: float = Field(2, ge=0, le=300)
82
+
83
+
84
+ class Logging(_Strict):
85
+ directory: str = ""
86
+ level: Literal["debug", "info", "warn", "error"] = "info"
87
+ max_size_mb: int = Field(20, ge=1, le=1024)
88
+ retain_files: int = Field(5, ge=1, le=100)
89
+
90
+
91
+ WARP_DOMAINS = ["claude.ai", "claude.com", "anthropic.com", "anthropic.ai",
92
+ "claudeusercontent.com", "cla.st"]
93
+
94
+
95
+ class Warp(_Strict):
96
+ """把指定域名从本机 WARP(Cloudflare Zero Trust Client 的 socks5)出去。
97
+
98
+ 原来的服务端就是这么干的(claude/anthropic 走 WARP,其余直连);不配就不产生路由规则。
99
+ """
100
+ address: str = "127.0.0.1:40000"
101
+ domains: list[str] = Field(default_factory=lambda: list(WARP_DOMAINS))
102
+
103
+
104
+ class Routing(_Strict):
105
+ warp: Warp | None = None
106
+
107
+
108
+ class ServerConfig(_Strict):
109
+ _config_warnings: list[str] = PrivateAttr(default_factory=list)
110
+ schema_version: int = Field(SCHEMA_VERSION, alias="schema")
111
+ server: Server = Server()
112
+ protocols: Protocols = Protocols()
113
+ auth: Auth = Auth()
114
+ tls: Tls = Tls()
115
+ routing: Routing = Routing()
116
+ service: Service = Service()
117
+ logging: Logging = Logging()
118
+
119
+
120
+ _ENV_OVERRIDES = {
121
+ "NORAIN_DOMAIN": ("server", "domain", str),
122
+ "NORAIN_HY2_PORT": ("protocols", "hysteria2", "port", int),
123
+ "NORAIN_TROJAN_PORT": ("protocols", "trojan", "port", int),
124
+ "NORAIN_CERT_MODE": ("tls", "mode", str),
125
+ "NORAIN_ACME_EMAIL": ("tls", "email", str),
126
+ # 密码本身不写进模型,改成 credential_ref,避免 status / 日志把环境变量
127
+ # 内容当成配置里的明文密码,同时保证环境变量优先于 TOML 中的旧来源。
128
+ "NORAIN_PASSWORD": ("auth", "credential_ref", str),
129
+ }
130
+
131
+ _TYPE_MESSAGES = {
132
+ "missing": "缺少必填字段",
133
+ "extra_forbidden": "未知字段",
134
+ "int_parsing": "必须是整数",
135
+ "int_type": "必须是整数",
136
+ "bool_type": "必须是 true 或 false",
137
+ "bool_parsing": "必须是 true 或 false",
138
+ "string_type": "必须是字符串",
139
+ "model_type": "必须是一个表([section])",
140
+ "model_attributes_type": "必须是一个表([section])",
141
+ }
142
+
143
+
144
+ def _known_names(model: type[BaseModel], out: set[str]) -> set[str]:
145
+ for name, f in model.model_fields.items():
146
+ out.add(f.alias or name)
147
+ for sub in (f.annotation, *getattr(f.annotation, "__args__", ())):
148
+ if isinstance(sub, type) and issubclass(sub, BaseModel):
149
+ _known_names(sub, out)
150
+ return out
151
+
152
+
153
+ _KNOWN = _known_names(ServerConfig, set())
154
+
155
+
156
+ def _translate(err: dict) -> FieldError:
157
+ path = ".".join(str(p) for p in err["loc"]) or "(顶层)"
158
+ kind = err["type"]
159
+ msg = _TYPE_MESSAGES.get(kind)
160
+ if kind == "extra_forbidden":
161
+ close = difflib.get_close_matches(str(err["loc"][-1]), _KNOWN, n=1)
162
+ if close:
163
+ msg += f",是不是想写 {close[0]}?"
164
+ elif kind in ("greater_than_equal", "less_than_equal"):
165
+ ctx = err.get("ctx", {})
166
+ bound = ctx.get("ge", ctx.get("le"))
167
+ msg = f"超出范围({'不能小于' if 'ge' in ctx else '不能大于'} {bound})"
168
+ elif kind == "literal_error":
169
+ msg = f"取值无效,可选:{err.get('ctx', {}).get('expected', '')}"
170
+ elif kind == "value_error":
171
+ msg = str(err.get("ctx", {}).get("error", err["msg"]))
172
+ return FieldError(path, msg or err["msg"])
173
+
174
+
175
+ def _apply_env(data: dict, env, errors: list[FieldError]) -> list[str]:
176
+ applied = []
177
+ for var, (*keys, leaf, cast) in _ENV_OVERRIDES.items():
178
+ raw = env.get(var)
179
+ if raw is None or raw == "":
180
+ continue
181
+ try:
182
+ value = (f"env:{var}" if var == "NORAIN_PASSWORD" else cast(raw))
183
+ except ValueError:
184
+ errors.append(FieldError(f"环境变量 {var}", "必须是整数"))
185
+ continue
186
+ node = data
187
+ for k in keys:
188
+ nxt = node.setdefault(k, {})
189
+ if not isinstance(nxt, dict):
190
+ break
191
+ node = nxt
192
+ else:
193
+ if var == "NORAIN_PASSWORD":
194
+ # 环境变量优先于 TOML,不能让旧的 auth.password 与新的来源
195
+ # 同时存在,也不能保留一个会被 credential_ref 覆盖的旧文件引用。
196
+ node.pop("password", None)
197
+ node[leaf] = value
198
+ applied.append(var)
199
+ return applied
200
+
201
+
202
+ def _cross_checks(cfg: ServerConfig) -> list[FieldError]:
203
+ errs: list[FieldError] = []
204
+ p = cfg.protocols
205
+ if not (p.hysteria2.enabled or p.trojan.enabled):
206
+ errs.append(FieldError("protocols", "至少要启用 hysteria2 或 trojan 中的一个"))
207
+ if not cfg.server.domain.strip():
208
+ errs.append(FieldError("server.domain", "不能为空(证书的域名或 IP)"))
209
+ if cfg.auth.password and cfg.auth.credential_ref:
210
+ errs.append(FieldError("auth", "password 和 credential_ref 只能设置一个"))
211
+ if cfg.tls.mode == "acme":
212
+ # 最初目标:没有域名时不允许使用 acme
213
+ domain = cfg.server.domain.strip().strip(".")
214
+ try:
215
+ ipaddress.ip_address(domain)
216
+ errs.append(FieldError("tls.mode", "acme 模式需要域名,server.domain 不能是 IP 地址"))
217
+ except ValueError:
218
+ if domain and "." not in domain:
219
+ errs.append(FieldError("tls.mode", "acme 模式需要可公开解析的域名"))
220
+ if cfg.tls.certificate or cfg.tls.private_key:
221
+ errs.append(FieldError("tls", "acme 模式下不要填写 certificate / private_key"))
222
+ if p.trojan.enabled and p.trojan.port == 80:
223
+ errs.append(FieldError("protocols.trojan.port",
224
+ "acme 的 HTTP-01 挑战要占用 80/tcp,Trojan 不能用 80 端口"))
225
+ if cfg.tls.mode == "manual":
226
+ for name in ("certificate", "private_key"):
227
+ if not getattr(cfg.tls, name):
228
+ errs.append(FieldError(f"tls.{name}", "manual 模式下必须填写路径"))
229
+ warp = cfg.routing.warp
230
+ if warp is not None:
231
+ host, _, port = warp.address.rpartition(":")
232
+ if not host or not port.isdigit() or not 0 < int(port) < 65536:
233
+ errs.append(FieldError("routing.warp.address", "必须是 host:port 形式,例如 127.0.0.1:40000"))
234
+ if not warp.domains:
235
+ errs.append(FieldError("routing.warp.domains", "至少写一个要走 WARP 的域名"))
236
+ return errs
237
+
238
+
239
+ def load_config(path: Path, env=None) -> ServerConfig:
240
+ env = os.environ if env is None else env
241
+ try:
242
+ with path.open("rb") as f:
243
+ data = tomllib.load(f)
244
+ except FileNotFoundError:
245
+ raise NorainError(f"配置文件不存在:{path}", exit_code=EXIT_CONFIG, business_code=BIZ_CONFIG,
246
+ module="config", hint="参考 examples/server.toml 创建") from None
247
+ except PermissionError:
248
+ raise NorainError(f"无权读取配置文件:{path}", exit_code=4, business_code=BIZ_CONFIG,
249
+ module="config") from None
250
+ except tomllib.TOMLDecodeError as e:
251
+ raise config_error([FieldError("(TOML 语法)", str(e))]) from None
252
+
253
+ migration = migrate(data, current=SCHEMA_VERSION, source=str(path))
254
+ errors: list[FieldError] = []
255
+ _apply_env(migration.data, env, errors)
256
+ try:
257
+ cfg = ServerConfig.model_validate(migration.data)
258
+ except ValidationError as e:
259
+ raise config_error(errors + [_translate(x) for x in e.errors()]) from None
260
+ attach_warnings(cfg, migration)
261
+ if not cfg.auth.password and not cfg.auth.credential_ref and not env.get("NORAIN_PASSWORD"):
262
+ errors.append(FieldError("auth.credential_ref", "不能为空(使用 file:<路径>、env:<变量名> 或 NORAIN_PASSWORD)"))
263
+ errors += _cross_checks(cfg)
264
+ if cfg.auth.password:
265
+ REDACTOR.register(cfg.auth.password)
266
+ try:
267
+ check_private_file(path, field="auth.password")
268
+ except NorainError as e:
269
+ errors += [FieldError(fe.path, fe.message + "(配置里直接写了密码)") for fe in e.field_errors]
270
+ if errors:
271
+ raise config_error(errors)
272
+ return cfg