From 39ce4d6be2c4ef26e1baa24e1db1b02bbbb39798 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Sun, 7 Jun 2026 18:15:37 +0500 Subject: [PATCH] feat(wip): xray proxy backend --- README.md | 19 +- docs/options.md | 1089 ++++++++++------- flake.nix | 2 +- modules/proxy-suite/config.nix | 212 +++- modules/proxy-suite/derived.nix | 49 +- modules/proxy-suite/nftables.nix | 8 +- modules/proxy-suite/options/default.nix | 1 + .../proxy-suite/options/legacy-sing-box.nix | 72 ++ modules/proxy-suite/options/other.nix | 4 +- .../proxy-suite/options/per-app-routing.nix | 12 +- modules/proxy-suite/options/sing-box-dns.nix | 6 +- .../options/sing-box-outbounds.nix | 57 +- .../proxy-suite/options/sing-box-routing.nix | 4 +- .../proxy-suite/options/sing-box-tproxy.nix | 16 +- modules/proxy-suite/options/sing-box-tun.nix | 8 +- modules/proxy-suite/options/sing-box.nix | 96 +- modules/proxy-suite/options/types.nix | 53 +- modules/proxy-suite/options/zapret.nix | 16 +- modules/proxy-suite/rules.nix | 123 +- modules/proxy-suite/service-assertions.nix | 168 +-- modules/proxy-suite/service/context.nix | 23 +- modules/proxy-suite/service/control.nix | 5 +- modules/proxy-suite/service/default.nix | 71 +- .../proxy-suite/service/per-app-routing.nix | 5 +- modules/proxy-suite/service/scripts.nix | 298 +++-- modules/proxy-suite/tg-ws-proxy.nix | 4 +- nix/checks.nix | 508 ++++++-- nix/options-doc.nix | 41 +- nix/readme-doc-fixture.nix | 16 +- pkgs/proxy-ctl-lib.sh | 16 +- pkgs/proxy-ctl.nix | 2 + scripts/build-outbound.py | 7 +- scripts/fetch-subscription.py | 7 +- scripts/proxy_parsing.py | 180 ++- scripts/proxy_url_parsers.py | 24 +- scripts/test-build-outbound.py | 39 + 36 files changed, 2265 insertions(+), 996 deletions(-) create mode 100644 modules/proxy-suite/options/legacy-sing-box.nix diff --git a/README.md b/README.md index 3f70dd1..66254c2 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Declarative proxy stack for NixOS. -Bundles [sing-box](https://github.com/SagerNet/sing-box), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense. +Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense. The goal is to replace GUI clients like v2rayN and throne – you configure your proxies in Nix, rebuild, and they just work as systemd services. @@ -10,14 +10,15 @@ The goal is to replace GUI clients like v2rayN and throne – you configure your ## What it gives you -- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` by default – always running, always available to apps -- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand or autostart at boot +- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` when `proxy.enable = true` +- **Backend choice** – use SingBox or XRay through the same `services.proxy-suite.proxy` option tree +- **Transparent proxy (TProxy)** – redirect all system traffic through the active backend without configuring each app; start/stop on demand or autostart at boot - **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart - **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap -- `, without enabling global TProxy or TUN - **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer - **Multiple outbounds** with automatic latency-based switching or manual selection - **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers -- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, TUIC v5, socks5, socks4, http/https proxy +- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, socks5, socks4, http/https proxy; SingBox also supports TUIC v5, while XRay supports XHTTP/ECH share links - **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs - **DPI bypass** via zapret – handles YouTube, Discord, and other sites defined by the project - **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy @@ -46,8 +47,12 @@ Feature-complete starter config: services.proxy-suite = { enable = true; - singBox = { + proxy = { enable = true; + singBox.enable = true; + # Or use XRay instead: + # xray.enable = true; + port = 1080; # Individual proxy example @@ -132,7 +137,7 @@ Usage: proxy-ctl [args] Commands: help show this help message status [--tray] show status of all proxy-suite services - proxy on|off enable/disable the sing-box proxy stack + proxy on|off enable/disable the proxy backend stack tproxy on|off enable/disable TProxy transparent mode tun on|off enable/disable TUN mode route-mode default|whitelist|blacklist|all-proxy|all-bypass|status @@ -145,6 +150,6 @@ Commands: apps list configured per-app routing profiles wrap -- run a command via a perAppRouting profile subscription list show subscriptions, cache age, and proxy count - subscription update force-refresh all subscription caches and restart active sing-box services + subscription update force-refresh all subscription caches and restart active proxy services ``` diff --git a/docs/options.md b/docs/options.md index 70e7d76..6fe1492 100644 --- a/docs/options.md +++ b/docs/options.md @@ -21,99 +21,106 @@ Update module option docs there instead of editing this file by hand. - [enable](#services-proxy-suite-perapprouting-proxychains-enable) - [proxyDns](#services-proxy-suite-perapprouting-proxychains-proxydns) - [quiet](#services-proxy-suite-perapprouting-proxychains-quiet) - - singBox - - [enable](#services-proxy-suite-singbox-enable) - - [package](#services-proxy-suite-singbox-package) + - proxy + - [enable](#services-proxy-suite-proxy-enable) - auth - - [password](#services-proxy-suite-singbox-auth-password) - - [passwordFile](#services-proxy-suite-singbox-auth-passwordfile) - - [username](#services-proxy-suite-singbox-auth-username) - - [clashApiPort](#services-proxy-suite-singbox-clashapiport) + - [password](#services-proxy-suite-proxy-auth-password) + - [passwordFile](#services-proxy-suite-proxy-auth-passwordfile) + - [username](#services-proxy-suite-proxy-auth-username) - dns - - [local](#services-proxy-suite-singbox-dns-local) - - [address](#services-proxy-suite-singbox-dns-local-address) - - [port](#services-proxy-suite-singbox-dns-local-port) - - [type](#services-proxy-suite-singbox-dns-local-type) - - [remote](#services-proxy-suite-singbox-dns-remote) - - [address](#services-proxy-suite-singbox-dns-remote-address) - - [port](#services-proxy-suite-singbox-dns-remote-port) - - [type](#services-proxy-suite-singbox-dns-remote-type) - - [listenAddress](#services-proxy-suite-singbox-listenaddress) - - [outbounds](#services-proxy-suite-singbox-outbounds) + - [local](#services-proxy-suite-proxy-dns-local) + - [address](#services-proxy-suite-proxy-dns-local-address) + - [port](#services-proxy-suite-proxy-dns-local-port) + - [type](#services-proxy-suite-proxy-dns-local-type) + - [remote](#services-proxy-suite-proxy-dns-remote) + - [address](#services-proxy-suite-proxy-dns-remote-address) + - [port](#services-proxy-suite-proxy-dns-remote-port) + - [type](#services-proxy-suite-proxy-dns-remote-type) + - [listenAddress](#services-proxy-suite-proxy-listenaddress) + - [outbounds](#services-proxy-suite-proxy-outbounds) - item - - [json](#services-proxy-suite-singbox-outbounds-json) - routing - - [domains](#services-proxy-suite-singbox-outbounds-routing-domains) - - [geoips](#services-proxy-suite-singbox-outbounds-routing-geoips) - - [geosites](#services-proxy-suite-singbox-outbounds-routing-geosites) - - [ips](#services-proxy-suite-singbox-outbounds-routing-ips) - - [tag](#services-proxy-suite-singbox-outbounds-tag) - - [url](#services-proxy-suite-singbox-outbounds-url) - - [urlFile](#services-proxy-suite-singbox-outbounds-urlfile) - - [port](#services-proxy-suite-singbox-port) - - [proxyByDefault](#services-proxy-suite-singbox-proxybydefault) + - [domains](#services-proxy-suite-proxy-outbounds-routing-domains) + - [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips) + - [geosites](#services-proxy-suite-proxy-outbounds-routing-geosites) + - [ips](#services-proxy-suite-proxy-outbounds-routing-ips) + - [singBoxJson](#services-proxy-suite-proxy-outbounds-singboxjson) + - [tag](#services-proxy-suite-proxy-outbounds-tag) + - [url](#services-proxy-suite-proxy-outbounds-url) + - [urlFile](#services-proxy-suite-proxy-outbounds-urlfile) + - [xrayJson](#services-proxy-suite-proxy-outbounds-xrayjson) + - [port](#services-proxy-suite-proxy-port) + - [proxyByDefault](#services-proxy-suite-proxy-proxybydefault) - routing - - [enableRuDirect](#services-proxy-suite-singbox-routing-enablerudirect) + - [enableRuDirect](#services-proxy-suite-proxy-routing-enablerudirect) - block - - [domains](#services-proxy-suite-singbox-routing-block-domains) - - [geoips](#services-proxy-suite-singbox-routing-block-geoips) - - [geosites](#services-proxy-suite-singbox-routing-block-geosites) - - [ips](#services-proxy-suite-singbox-routing-block-ips) + - [domains](#services-proxy-suite-proxy-routing-block-domains) + - [geoips](#services-proxy-suite-proxy-routing-block-geoips) + - [geosites](#services-proxy-suite-proxy-routing-block-geosites) + - [ips](#services-proxy-suite-proxy-routing-block-ips) - direct - - [domains](#services-proxy-suite-singbox-routing-direct-domains) - - [geoips](#services-proxy-suite-singbox-routing-direct-geoips) - - [geosites](#services-proxy-suite-singbox-routing-direct-geosites) - - [ips](#services-proxy-suite-singbox-routing-direct-ips) + - [domains](#services-proxy-suite-proxy-routing-direct-domains) + - [geoips](#services-proxy-suite-proxy-routing-direct-geoips) + - [geosites](#services-proxy-suite-proxy-routing-direct-geosites) + - [ips](#services-proxy-suite-proxy-routing-direct-ips) - proxy - - [domains](#services-proxy-suite-singbox-routing-proxy-domains) - - [geoips](#services-proxy-suite-singbox-routing-proxy-geoips) - - [geosites](#services-proxy-suite-singbox-routing-proxy-geosites) - - [ips](#services-proxy-suite-singbox-routing-proxy-ips) - - [rules](#services-proxy-suite-singbox-routing-rules) + - [domains](#services-proxy-suite-proxy-routing-proxy-domains) + - [geoips](#services-proxy-suite-proxy-routing-proxy-geoips) + - [geosites](#services-proxy-suite-proxy-routing-proxy-geosites) + - [ips](#services-proxy-suite-proxy-routing-proxy-ips) + - [rules](#services-proxy-suite-proxy-routing-rules) - item - - [domains](#services-proxy-suite-singbox-routing-rules-domains) - - [geoips](#services-proxy-suite-singbox-routing-rules-geoips) - - [geosites](#services-proxy-suite-singbox-routing-rules-geosites) - - [ips](#services-proxy-suite-singbox-routing-rules-ips) - - [outbound](#services-proxy-suite-singbox-routing-rules-outbound) - - [selection](#services-proxy-suite-singbox-selection) - - [subscriptionUpdateInterval](#services-proxy-suite-singbox-subscriptionupdateinterval) - - [subscriptions](#services-proxy-suite-singbox-subscriptions) + - [domains](#services-proxy-suite-proxy-routing-rules-domains) + - [geoips](#services-proxy-suite-proxy-routing-rules-geoips) + - [geosites](#services-proxy-suite-proxy-routing-rules-geosites) + - [ips](#services-proxy-suite-proxy-routing-rules-ips) + - [outbound](#services-proxy-suite-proxy-routing-rules-outbound) + - [selection](#services-proxy-suite-proxy-selection) + - singBox + - [enable](#services-proxy-suite-proxy-singbox-enable) + - [package](#services-proxy-suite-proxy-singbox-package) + - [clashApiPort](#services-proxy-suite-proxy-singbox-clashapiport) + - urlTest + - [tolerance](#services-proxy-suite-proxy-singbox-urltest-tolerance) + - [subscriptionUpdateInterval](#services-proxy-suite-proxy-subscriptionupdateinterval) + - [subscriptions](#services-proxy-suite-proxy-subscriptions) - item - - [tag](#services-proxy-suite-singbox-subscriptions-tag) - - [url](#services-proxy-suite-singbox-subscriptions-url) - - [urlFile](#services-proxy-suite-singbox-subscriptions-urlfile) + - [tag](#services-proxy-suite-proxy-subscriptions-tag) + - [url](#services-proxy-suite-proxy-subscriptions-url) + - [urlFile](#services-proxy-suite-proxy-subscriptions-urlfile) - tproxy - - [enable](#services-proxy-suite-singbox-tproxy-enable) - - [autostart](#services-proxy-suite-singbox-tproxy-autostart) - - [fwmark](#services-proxy-suite-singbox-tproxy-fwmark) - - [localSubnets](#services-proxy-suite-singbox-tproxy-localsubnets) + - [enable](#services-proxy-suite-proxy-tproxy-enable) + - [autostart](#services-proxy-suite-proxy-tproxy-autostart) + - [fwmark](#services-proxy-suite-proxy-tproxy-fwmark) + - [localSubnets](#services-proxy-suite-proxy-tproxy-localsubnets) - perApp - - [enable](#services-proxy-suite-singbox-tproxy-perapp-enable) - - [fwmark](#services-proxy-suite-singbox-tproxy-perapp-fwmark) - - [localSubnets](#services-proxy-suite-singbox-tproxy-perapp-localsubnets) - - [routeTable](#services-proxy-suite-singbox-tproxy-perapp-routetable) - - [port](#services-proxy-suite-singbox-tproxy-port) - - [proxyMark](#services-proxy-suite-singbox-tproxy-proxymark) - - [routeTable](#services-proxy-suite-singbox-tproxy-routetable) + - [enable](#services-proxy-suite-proxy-tproxy-perapp-enable) + - [fwmark](#services-proxy-suite-proxy-tproxy-perapp-fwmark) + - [localSubnets](#services-proxy-suite-proxy-tproxy-perapp-localsubnets) + - [routeTable](#services-proxy-suite-proxy-tproxy-perapp-routetable) + - [port](#services-proxy-suite-proxy-tproxy-port) + - [proxyMark](#services-proxy-suite-proxy-tproxy-proxymark) + - [routeTable](#services-proxy-suite-proxy-tproxy-routetable) - tun - - [enable](#services-proxy-suite-singbox-tun-enable) - - [address](#services-proxy-suite-singbox-tun-address) - - [autostart](#services-proxy-suite-singbox-tun-autostart) - - [interface](#services-proxy-suite-singbox-tun-interface) - - [mtu](#services-proxy-suite-singbox-tun-mtu) + - [enable](#services-proxy-suite-proxy-tun-enable) + - [address](#services-proxy-suite-proxy-tun-address) + - [autostart](#services-proxy-suite-proxy-tun-autostart) + - [interface](#services-proxy-suite-proxy-tun-interface) + - [mtu](#services-proxy-suite-proxy-tun-mtu) - perApp - - [enable](#services-proxy-suite-singbox-tun-perapp-enable) - - [address](#services-proxy-suite-singbox-tun-perapp-address) - - [fwmark](#services-proxy-suite-singbox-tun-perapp-fwmark) - - [interface](#services-proxy-suite-singbox-tun-perapp-interface) - - [localSubnets](#services-proxy-suite-singbox-tun-perapp-localsubnets) - - [mtu](#services-proxy-suite-singbox-tun-perapp-mtu) - - [routeTable](#services-proxy-suite-singbox-tun-perapp-routetable) + - [enable](#services-proxy-suite-proxy-tun-perapp-enable) + - [address](#services-proxy-suite-proxy-tun-perapp-address) + - [fwmark](#services-proxy-suite-proxy-tun-perapp-fwmark) + - [interface](#services-proxy-suite-proxy-tun-perapp-interface) + - [localSubnets](#services-proxy-suite-proxy-tun-perapp-localsubnets) + - [mtu](#services-proxy-suite-proxy-tun-perapp-mtu) + - [routeTable](#services-proxy-suite-proxy-tun-perapp-routetable) - urlTest - - [interval](#services-proxy-suite-singbox-urltest-interval) - - [tolerance](#services-proxy-suite-singbox-urltest-tolerance) - - [url](#services-proxy-suite-singbox-urltest-url) + - [interval](#services-proxy-suite-proxy-urltest-interval) + - [url](#services-proxy-suite-proxy-urltest-url) + - xray + - [enable](#services-proxy-suite-proxy-xray-enable) + - [package](#services-proxy-suite-proxy-xray-package) - tgWsProxy - [enable](#services-proxy-suite-tgwsproxy-enable) - [bypassTransparentProxy](#services-proxy-suite-tgwsproxy-bypasstransparentproxy) @@ -176,13 +183,12 @@ services.proxy-suite = { quiet = true; }; }; - singBox = { + proxy = { auth = { password = null; passwordFile = null; username = null; }; - clashApiPort = 9090; dns = { local = { address = "1.1.1.1"; @@ -195,10 +201,9 @@ services.proxy-suite = { type = "udp"; }; }; - enable = true; + enable = false; listenAddress = "127.0.0.1"; outbounds = [ ]; - package = pkgs.sing-box; port = 1080; proxyByDefault = true; routing = { @@ -224,6 +229,14 @@ services.proxy-suite = { rules = [ ]; }; selection = "first"; + singBox = { + clashApiPort = 9090; + enable = false; + package = pkgs.sing-box; + urlTest = { + tolerance = 50; + }; + }; subscriptionUpdateInterval = "1d"; subscriptions = [ ]; tproxy = { @@ -265,9 +278,12 @@ services.proxy-suite = { }; urlTest = { interval = "3m"; - tolerance = 50; url = "https://www.gstatic.com/generate_204"; }; + xray = { + enable = false; + package = pkgs.xray; + }; }; tgWsProxy = { bypassTransparentProxy = true; @@ -346,13 +362,12 @@ services.proxy-suite = { quiet = true; }; }; - singBox = { + proxy = { auth = { password = "change-me"; passwordFile = "/run/secrets/proxy-suite-local-proxy-password"; username = "proxy-user"; }; - clashApiPort = 9090; dns = { local = { address = "9.9.9.9"; @@ -365,7 +380,7 @@ services.proxy-suite = { type = "tls"; }; }; - enable = true; + enable = false; listenAddress = "127.0.0.1"; outbounds = [ { @@ -377,7 +392,6 @@ services.proxy-suite = { url = "hy2://password@example.com:443?sni=example.com"; } ]; - package = pkgs.sing-box; port = 1080; proxyByDefault = true; routing = { @@ -452,6 +466,14 @@ services.proxy-suite = { ]; }; selection = "urltest"; + singBox = { + clashApiPort = 9090; + enable = true; + package = pkgs.sing-box; + urlTest = { + tolerance = 100; + }; + }; subscriptionUpdateInterval = "6h"; subscriptions = [ { @@ -505,9 +527,15 @@ services.proxy-suite = { }; urlTest = { interval = "1m"; - tolerance = 100; url = "https://telegram.org"; }; + xray = { + enable = true; + package = pkgs.xray; + }; + }; + singBox = { + _freeformOptions = { }; }; tgWsProxy = { bypassTransparentProxy = true; @@ -597,7 +625,7 @@ services.proxy-suite = { ## services\.proxy-suite\.enable -Whether to enable proxy suite (sing-box + zapret + tg-ws-proxy)\. +Whether to enable proxy suite (proxy backend + zapret + tg-ws-proxy)\. @@ -671,8 +699,8 @@ user-defined profile with the same name already exists\. Current curated defaults: - ` proxychains `: route = “proxychains” - - ` tun `: route = “tun” when singBox\.tun\.perApp\.enable = true - - ` tproxy `: route = “tproxy” when singBox\.tproxy\.perApp\.enable = true + - ` tun `: route = “tun” when proxy\.tun\.perApp\.enable = true + - ` tproxy `: route = “tproxy” when proxy\.tproxy\.perApp\.enable = true - ` zapret `: route = “zapret” when zapret\.perApp\.enable = true This makes ` proxy-ctl wrap proxychains -- ` available @@ -727,10 +755,10 @@ This initial implementation supports: - “zapret” for per-app-scoped zapret handling through a separate zapret instance without changing the app’s network path or exit IP -proxychains-based wrapping depends on singBox\.enable = true and the -local proxy-suite mixed proxy listener provided by sing-box\. The -“tun” route depends on singBox\.tun\.perApp\.enable = true\. The “tproxy” -route depends on singBox\.tproxy\.perApp\.enable = true\. The “zapret” +proxychains-based wrapping depends on proxy\.enable = true and the +local proxy-suite proxy listener provided by the active backend\. The +“tun” route depends on proxy\.tun\.perApp\.enable = true\. The “tproxy” +route depends on proxy\.tproxy\.perApp\.enable = true\. The “zapret” route depends on zapret\.perApp\.enable = true\. When createDefaultProfiles = true, curated defaults are added on top @@ -812,7 +840,7 @@ Per-app route backend used by proxy-ctl wrap\. only that app’s traffic is policy-routed into the app TUN backend\. - “tproxy”: launch the command in the dedicated per-app-routing TProxy slice so only that app’s traffic is transparently intercepted by - the local sing-box TProxy inbound\. + the local proxy TProxy inbound\. - “zapret”: launch the command in the dedicated per-app-routing zapret slice so only that app’s traffic is handled by the separate per-app-scoped zapret instance\. @@ -947,14 +975,14 @@ true - -## services\.proxy-suite\.singBox\.enable + +## services\.proxy-suite\.proxy\.enable -Whether to configure and run sing-box services for proxy-suite\. -When disabled, sing-box services and generated sing-box configs are -skipped even if proxy-suite itself is enabled\. +Whether to configure and run the proxy backend services\. +This is disabled by default; enable it explicitly and choose exactly +one backend with proxy\.singBox\.enable or proxy\.xray\.enable\. @@ -966,7 +994,7 @@ boolean *Default:* ```nix -true +false ``` *Declared by:* @@ -974,44 +1002,8 @@ true - -## services\.proxy-suite\.singBox\.package - - - -sing-box package used by proxy-suite systemd services\. - -Override this to pin or test a specific sing-box build when upstream -protocol behavior changes\. - - - -*Type:* -package - - - -*Default:* - -```nix -pkgs.sing-box -``` - - - -*Example:* - -```nix -pkgs.sing-box -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.singBox\.auth\.password + +## services\.proxy-suite\.proxy\.auth\.password @@ -1046,8 +1038,8 @@ null - -## services\.proxy-suite\.singBox\.auth\.passwordFile + +## services\.proxy-suite\.proxy\.auth\.passwordFile @@ -1086,8 +1078,8 @@ null - -## services\.proxy-suite\.singBox\.auth\.username + +## services\.proxy-suite\.proxy\.auth\.username @@ -1123,48 +1115,13 @@ null - -## services\.proxy-suite\.singBox\.clashApiPort - - - -Port for the Clash-compatible REST API exposed by sing-box\. -Only used when selection is “selector” or “urltest”\. Ignored in -“first” mode because there is no selector-style outbound to control\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -9090 -``` - - - -*Example:* - -```nix -9090 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.singBox\.dns\.local + +## services\.proxy-suite\.proxy\.dns\.local DNS upstream used for the built-in “local” resolver role\. -This resolver is also used as sing-box route\.default_domain_resolver\. +This resolver is also used as the backend’s default domain resolver\. The module keeps detour policy automatic: in mixed/TProxy mode and per-app-routing TUN mode, “local” stays on the direct path (without an @@ -1205,8 +1162,8 @@ submodule - -## services\.proxy-suite\.singBox\.dns\.local\.address + +## services\.proxy-suite\.proxy\.dns\.local\.address @@ -1230,8 +1187,8 @@ string matching the pattern \.+ - -## services\.proxy-suite\.singBox\.dns\.local\.port + +## services\.proxy-suite\.proxy\.dns\.local\.port @@ -1263,12 +1220,12 @@ Destination port for this DNS upstream\. - -## services\.proxy-suite\.singBox\.dns\.local\.type + +## services\.proxy-suite\.proxy\.dns\.local\.type -sing-box DNS transport type for this upstream resolver\. +DNS transport type for this upstream resolver\. @@ -1296,15 +1253,15 @@ one of “udp”, “tcp”, “tls” - -## services\.proxy-suite\.singBox\.dns\.remote + +## services\.proxy-suite\.proxy\.dns\.remote DNS upstream used for the built-in “remote” resolver role\. This resolver always detours through the proxy and becomes the -generated dns\.final target when singBox\.proxyByDefault = true\. +generated dns\.final target when proxy\.proxyByDefault = true\. @@ -1340,8 +1297,8 @@ submodule - -## services\.proxy-suite\.singBox\.dns\.remote\.address + +## services\.proxy-suite\.proxy\.dns\.remote\.address @@ -1365,8 +1322,8 @@ string matching the pattern \.+ - -## services\.proxy-suite\.singBox\.dns\.remote\.port + +## services\.proxy-suite\.proxy\.dns\.remote\.port @@ -1398,12 +1355,12 @@ Destination port for this DNS upstream\. - -## services\.proxy-suite\.singBox\.dns\.remote\.type + +## services\.proxy-suite\.proxy\.dns\.remote\.type -sing-box DNS transport type for this upstream resolver\. +DNS transport type for this upstream resolver\. @@ -1431,13 +1388,13 @@ one of “udp”, “tcp”, “tls” - -## services\.proxy-suite\.singBox\.listenAddress + +## services\.proxy-suite\.proxy\.listenAddress -Address for the SOCKS5/HTTP mixed inbound to bind to\. -This affects the always-on proxy-suite-socks service\. +Address for the local SOCKS5/HTTP inbound to bind to\. +This affects the proxy-suite-socks service\. Use “0\.0\.0\.0” only if you intentionally want to expose the proxy to other machines on your network\. @@ -1468,16 +1425,18 @@ string - -## services\.proxy-suite\.singBox\.outbounds + +## services\.proxy-suite\.proxy\.outbounds List of static proxy outbounds\. -Set exactly one of urlFile, url, or json per entry\. +Set exactly one of urlFile, url, singBoxJson, xrayJson, or the +deprecated json field per entry\. Backend-specific raw JSON fields are +only valid with their matching backend\. At least one outbound or one subscription is required when -singBox\.enable = true\. +proxy\.enable = true\. @@ -1514,52 +1473,8 @@ list of (submodule) - -## services\.proxy-suite\.singBox\.outbounds\.\*\.json - - - -Raw sing-box outbound configuration as a Nix attribute set\. -Embedded directly into the config at build time\. The tag field -is overridden by the outbound’s tag option\. - -Set exactly one of urlFile, url, or json for each outbound\. -Use this when the proxy definition is easier to generate as native Nix -than as a single URL string\. - - - -*Type:* -null or (attribute set) - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -{ - server = "example.com"; - server_port = 443; - type = "vless"; - uuid = "..."; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.singBox\.outbounds\.\*\.routing\.domains + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.domains @@ -1595,13 +1510,13 @@ list of string - -## services\.proxy-suite\.singBox\.outbounds\.\*\.routing\.geoips + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.geoips sing-geoip rule-set names to match in this routing rule\. -Each name becomes a sing-box geoip rule-set reference\. +Each name becomes a backend geoip rule-set reference\. @@ -1632,13 +1547,13 @@ list of string - -## services\.proxy-suite\.singBox\.outbounds\.\*\.routing\.geosites + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.geosites sing-geosite rule-set names to match in this routing rule\. -Each name becomes a sing-box geosite rule-set reference\. +Each name becomes a backend geosite rule-set reference\. @@ -1669,8 +1584,8 @@ list of string - -## services\.proxy-suite\.singBox\.outbounds\.\*\.routing\.ips + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.ips @@ -1705,15 +1620,60 @@ list of string - -## services\.proxy-suite\.singBox\.outbounds\.\*\.tag + +## services\.proxy-suite\.proxy\.outbounds\.\*\.singBoxJson + + + +Raw sing-box outbound configuration as a Nix attribute set\. +Embedded directly into the config at build time\. The tag field +is overridden by the outbound’s tag option\. + +Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for +each outbound\. +Use this when the proxy definition is easier to generate as native Nix +than as a single URL string\. Only valid with the SingBox backend\. + + + +*Type:* +null or (attribute set) + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +{ + server = "example.com"; + server_port = 443; + type = "vless"; + uuid = "..."; +} +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) + + + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.tag Outbound tag used in routing rules and multi-outbound selection\. With selection = “selector” or “urltest”, each outbound keeps its own -tag and can be selected directly\. With selection = “first”, sing-box +tag and can be selected directly\. With selection = “first”, proxy-suite routes through a single active outbound tagged “proxy”, so individual proxy tags are mainly useful for documentation and config structure\. @@ -1735,8 +1695,8 @@ string - -## services\.proxy-suite\.singBox\.outbounds\.\*\.url + +## services\.proxy-suite\.proxy\.outbounds\.\*\.url @@ -1772,8 +1732,8 @@ null - -## services\.proxy-suite\.singBox\.outbounds\.\*\.urlFile + +## services\.proxy-suite\.proxy\.outbounds\.\*\.urlFile @@ -1809,13 +1769,60 @@ null - -## services\.proxy-suite\.singBox\.port + +## services\.proxy-suite\.proxy\.outbounds\.\*\.xrayJson -Listen port for the always-on SOCKS5/HTTP mixed inbound provided by -proxy-suite-socks\. +Raw XRay outbound configuration as a Nix attribute set\. +Embedded directly into the config at build time\. The tag field is +overridden by the outbound’s tag option\. + +Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for +each outbound\. Only valid with the XRay backend\. + + + +*Type:* +null or (attribute set) + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +{ + protocol = "vless"; + settings = { + address = "example.com"; + encryption = "none"; + id = "..."; + port = 443; + }; +} +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) + + + + +## services\.proxy-suite\.proxy\.port + + + +Listen port for the local SOCKS5/HTTP proxy inbound provided by +proxy-suite-socks\. SingBox exposes SOCKS5 and HTTP on this port\. +XRay’s Socks inbound also accepts SOCKS and HTTP\. @@ -1843,15 +1850,15 @@ proxy-suite-socks\. - -## services\.proxy-suite\.singBox\.proxyByDefault + +## services\.proxy-suite\.proxy\.proxyByDefault Whether traffic that does not match any explicit routing rule should go through the proxy or go direct\. -This affects sing-box route\.final and dns\.final in the generated +This affects the generated backend route final and DNS final in the config\. @@ -1880,8 +1887,8 @@ true - -## services\.proxy-suite\.singBox\.routing\.enableRuDirect + +## services\.proxy-suite\.proxy\.routing\.enableRuDirect @@ -1916,8 +1923,8 @@ true - -## services\.proxy-suite\.singBox\.routing\.block\.domains + +## services\.proxy-suite\.proxy\.routing\.block\.domains @@ -1951,8 +1958,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.block\.geoips + +## services\.proxy-suite\.proxy\.routing\.block\.geoips @@ -1986,8 +1993,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.block\.geosites + +## services\.proxy-suite\.proxy\.routing\.block\.geosites @@ -2021,8 +2028,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.block\.ips + +## services\.proxy-suite\.proxy\.routing\.block\.ips @@ -2056,8 +2063,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.direct\.domains + +## services\.proxy-suite\.proxy\.routing\.direct\.domains @@ -2093,8 +2100,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.direct\.geoips + +## services\.proxy-suite\.proxy\.routing\.direct\.geoips @@ -2129,8 +2136,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.direct\.geosites + +## services\.proxy-suite\.proxy\.routing\.direct\.geosites @@ -2165,8 +2172,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.direct\.ips + +## services\.proxy-suite\.proxy\.routing\.direct\.ips @@ -2202,8 +2209,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.proxy\.domains + +## services\.proxy-suite\.proxy\.routing\.proxy\.domains @@ -2239,13 +2246,13 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.proxy\.geoips + +## services\.proxy-suite\.proxy\.routing\.proxy\.geoips sing-geoip rule-set names to match in this routing rule\. -Each name becomes a sing-box geoip rule-set reference\. +Each name becomes a backend geoip rule-set reference\. @@ -2276,13 +2283,13 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.proxy\.geosites + +## services\.proxy-suite\.proxy\.routing\.proxy\.geosites sing-geosite rule-set names to match in this routing rule\. -Each name becomes a sing-box geosite rule-set reference\. +Each name becomes a backend geosite rule-set reference\. @@ -2313,8 +2320,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.proxy\.ips + +## services\.proxy-suite\.proxy\.routing\.proxy\.ips @@ -2349,8 +2356,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.rules + +## services\.proxy-suite\.proxy\.routing\.rules @@ -2360,7 +2367,7 @@ Each rule routes matching traffic to a specific outbound tag\. The outbound can be a configured outbound tag (useful with selector/urltest), or one of: “proxy” (active proxy), “direct”, “block”\. -Order is preserved\. The first matching rule wins in sing-box\. +Order is preserved\. The first matching rule wins in the active backend\. With selection = “first”, non-built-in outbound tags are effectively routed to the single active “proxy” outbound\. @@ -2412,8 +2419,8 @@ list of (submodule) - -## services\.proxy-suite\.singBox\.routing\.rules\.\*\.domains + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.domains @@ -2449,13 +2456,13 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.rules\.\*\.geoips + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.geoips sing-geoip rule-set names to match in this routing rule\. -Each name becomes a sing-box geoip rule-set reference\. +Each name becomes a backend geoip rule-set reference\. @@ -2486,13 +2493,13 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.rules\.\*\.geosites + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.geosites sing-geosite rule-set names to match in this routing rule\. -Each name becomes a sing-box geosite rule-set reference\. +Each name becomes a backend geosite rule-set reference\. @@ -2523,8 +2530,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.rules\.\*\.ips + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.ips @@ -2559,8 +2566,8 @@ list of string - -## services\.proxy-suite\.singBox\.routing\.rules\.\*\.outbound + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.outbound @@ -2590,8 +2597,8 @@ string - -## services\.proxy-suite\.singBox\.selection + +## services\.proxy-suite\.proxy\.selection @@ -2603,11 +2610,13 @@ How to pick between multiple proxy outbounds: - “selector”: create a Clash-compatible selector outbound tagged “proxy” and keep all configured outbounds available for manual switching via the Clash API\. - - “urltest”: create an automatic latency-testing outbound tagged - “proxy” and keep all configured outbounds available so sing-box - can periodically probe and switch to a faster one\. + - “urltest”: create automatic latency testing tagged “proxy” and + keep all configured outbounds available so the active backend can + periodically probe and switch to a faster one\. -clashApiPort is only used with “selector” or “urltest”\. +proxy\.singBox\.clashApiPort is only used with “selector” or “urltest” +on the SingBox backend\. “selector” is SingBox-only\. “urltest” maps to +SingBox urltest or XRay observatory/balancer depending on backend\. urlTest\.\* options are only used with “urltest”\. Per-outbound tags are only individually meaningful with “selector” or “urltest”\. @@ -2638,8 +2647,151 @@ one of “first”, “selector”, “urltest” - -## services\.proxy-suite\.singBox\.subscriptionUpdateInterval + +## services\.proxy-suite\.proxy\.singBox\.enable + + + +Whether to enable SingBox proxy backend\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + + + +*Example:* + +```nix +true +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) + + + + +## services\.proxy-suite\.proxy\.singBox\.package + + + +sing-box package used by proxy-suite systemd services\. + +Override this to pin or test a specific sing-box build when upstream +protocol behavior changes\. + + + +*Type:* +package + + + +*Default:* + +```nix +pkgs.sing-box +``` + + + +*Example:* + +```nix +pkgs.sing-box +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) + + + + +## services\.proxy-suite\.proxy\.singBox\.clashApiPort + + + +Port for the Clash-compatible REST API exposed by sing-box\. +Only used when proxy\.selection is “selector” or “urltest”\. Ignored +in “first” mode because there is no selector-style outbound to +control\. + + + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + + + +*Default:* + +```nix +9090 +``` + + + +*Example:* + +```nix +9090 +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) + + + + +## services\.proxy-suite\.proxy\.singBox\.urlTest\.tolerance + + + +Latency tolerance in milliseconds for sing-box urltest\. The current +proxy is only replaced when a competing one is faster by more than +this value\. + +Only used when proxy\.selection = “urltest” and the SingBox backend +is active\. + + + +*Type:* +signed integer + + + +*Default:* + +```nix +50 +``` + + + +*Example:* + +```nix +100 +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) + + + + +## services\.proxy-suite\.proxy\.subscriptionUpdateInterval @@ -2647,7 +2799,7 @@ How often the proxy-suite-subscription-update timer fires and refreshes all subscription caches\. Accepts any systemd time span string (e\.g\. “1h”, “6h”, “1d”, “12h”)\. -Only used when singBox\.subscriptions is non-empty\. The timer also runs +Only used when proxy\.subscriptions is non-empty\. The timer also runs once shortly after boot\. @@ -2676,8 +2828,8 @@ string - -## services\.proxy-suite\.singBox\.subscriptions + +## services\.proxy-suite\.proxy\.subscriptions @@ -2686,12 +2838,12 @@ Each URL must return a base64-encoded newline-separated list of proxy URIs (standard v2rayN / Clash subscription format) or plain text of the same\. On first service start, each subscription is fetched live and cached -under /var/lib/proxy-suite/subscriptions/\\.json\. Later restarts +under /var/lib/proxy-suite/subscriptions/\/\\.json\. Later restarts reuse the cache, so ordinary service restarts do not need network access\. -A systemd timer (proxy-suite-subscription-update) refreshes all caches on -the interval set by subscriptionUpdateInterval and restarts the running -sing-box services after a successful refresh\. +A systemd timer (proxy-suite-subscription-update) refreshes all caches +on the interval set by subscriptionUpdateInterval and restarts the +running proxy services after a successful refresh\. @@ -2728,8 +2880,8 @@ list of (submodule) - -## services\.proxy-suite\.singBox\.subscriptions\.\*\.tag + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.tag @@ -2738,7 +2890,8 @@ Used as a prefix for all outbound tags generated from its proxy list, e\.g\. “my-sub” -> tags like “my-sub-Server-DE”\. This value is also used as the subscription cache filename stem under -/var/lib/proxy-suite/subscriptions/, so it must be a safe identifier\. +/var/lib/proxy-suite/subscriptions/\/, so it must be a safe +identifier\. @@ -2758,8 +2911,8 @@ string matching the pattern ^\[A-Za-z0-9]\[A-Za-z0-9\._-]\*$ - -## services\.proxy-suite\.singBox\.subscriptions\.\*\.url + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.url @@ -2796,8 +2949,8 @@ null - -## services\.proxy-suite\.singBox\.subscriptions\.\*\.urlFile + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.urlFile @@ -2833,12 +2986,12 @@ null - -## services\.proxy-suite\.singBox\.tproxy\.enable + +## services\.proxy-suite\.proxy\.tproxy\.enable -Whether to enable global sing-box TProxy mode service\. +Whether to enable global proxy TProxy mode service\. @@ -2866,14 +3019,14 @@ true - -## services\.proxy-suite\.singBox\.tproxy\.autostart + +## services\.proxy-suite\.proxy\.tproxy\.autostart Whether to start proxy-suite-tproxy automatically during boot by attaching it to multi-user\.target\. -Cannot be enabled together with singBox\.tun\.autostart\. +Cannot be enabled together with proxy\.tun\.autostart\. @@ -2901,14 +3054,14 @@ true - -## services\.proxy-suite\.singBox\.tproxy\.fwmark + +## services\.proxy-suite\.proxy\.tproxy\.fwmark Mark applied to intercepted packets in global TProxy mode\. A matching ` ip rule ` routes this mark to -singBox\.tproxy\.routeTable, which points traffic to +proxy\.tproxy\.routeTable, which points traffic to loopback for local proxy processing\. @@ -2937,8 +3090,8 @@ signed integer - -## services\.proxy-suite\.singBox\.tproxy\.localSubnets + +## services\.proxy-suite\.proxy\.tproxy\.localSubnets @@ -2980,12 +3133,12 @@ list of string - -## services\.proxy-suite\.singBox\.tproxy\.perApp\.enable + +## services\.proxy-suite\.proxy\.tproxy\.perApp\.enable -Whether to enable per-app-scoped sing-box TProxy backend for perAppRouting profiles\. +Whether to enable per-app-scoped proxy TProxy backend for perAppRouting profiles\. @@ -3013,8 +3166,8 @@ true - -## services\.proxy-suite\.singBox\.tproxy\.perApp\.fwmark + +## services\.proxy-suite\.proxy\.tproxy\.perApp\.fwmark @@ -3047,8 +3200,8 @@ signed integer - -## services\.proxy-suite\.singBox\.tproxy\.perApp\.localSubnets + +## services\.proxy-suite\.proxy\.tproxy\.perApp\.localSubnets @@ -3086,8 +3239,8 @@ list of string - -## services\.proxy-suite\.singBox\.tproxy\.perApp\.routeTable + +## services\.proxy-suite\.proxy\.tproxy\.perApp\.routeTable @@ -3119,12 +3272,12 @@ signed integer - -## services\.proxy-suite\.singBox\.tproxy\.port + +## services\.proxy-suite\.proxy\.tproxy\.port -Local listen port for sing-box’s TProxy inbound\. +Local listen port for the proxy backend’s TProxy inbound\. nftables redirection created by proxy-suite-tproxy sends intercepted TCP/UDP traffic to this port\. @@ -3154,12 +3307,12 @@ TCP/UDP traffic to this port\. - -## services\.proxy-suite\.singBox\.tproxy\.proxyMark + +## services\.proxy-suite\.proxy\.tproxy\.proxyMark -Mark applied to sing-box egress packets in global TProxy mode so +Mark applied to backend egress packets in global TProxy mode so they bypass re-interception and do not loop back into the transparent proxy path\. @@ -3189,14 +3342,14 @@ signed integer - -## services\.proxy-suite\.singBox\.tproxy\.routeTable + +## services\.proxy-suite\.proxy\.tproxy\.routeTable Policy-routing table number used for global TProxy interception flow\. The module installs a local default route in this table and binds it -to singBox\.tproxy\.fwmark\. +to proxy\.tproxy\.fwmark\. @@ -3224,12 +3377,12 @@ signed integer - -## services\.proxy-suite\.singBox\.tun\.enable + +## services\.proxy-suite\.proxy\.tun\.enable -Whether to enable global sing-box TUN mode service\. +Whether to enable global proxy TUN mode service\. @@ -3257,8 +3410,8 @@ true - -## services\.proxy-suite\.singBox\.tun\.address + +## services\.proxy-suite\.proxy\.tun\.address @@ -3290,14 +3443,14 @@ string - -## services\.proxy-suite\.singBox\.tun\.autostart + +## services\.proxy-suite\.proxy\.tun\.autostart Whether to start proxy-suite-tun automatically during boot by attaching it to multi-user\.target\. -Cannot be enabled together with singBox\.tproxy\.autostart\. +Cannot be enabled together with proxy\.tproxy\.autostart\. @@ -3325,8 +3478,8 @@ true - -## services\.proxy-suite\.singBox\.tun\.interface + +## services\.proxy-suite\.proxy\.tun\.interface @@ -3358,8 +3511,8 @@ string - -## services\.proxy-suite\.singBox\.tun\.mtu + +## services\.proxy-suite\.proxy\.tun\.mtu @@ -3391,12 +3544,12 @@ signed integer - -## services\.proxy-suite\.singBox\.tun\.perApp\.enable + +## services\.proxy-suite\.proxy\.tun\.perApp\.enable -Whether to enable per-app-scoped sing-box TUN backend for perAppRouting profiles\. +Whether to enable per-app-scoped proxy TUN backend for perAppRouting profiles\. @@ -3424,8 +3577,8 @@ true - -## services\.proxy-suite\.singBox\.tun\.perApp\.address + +## services\.proxy-suite\.proxy\.tun\.perApp\.address @@ -3458,8 +3611,8 @@ string - -## services\.proxy-suite\.singBox\.tun\.perApp\.fwmark + +## services\.proxy-suite\.proxy\.tun\.perApp\.fwmark @@ -3492,8 +3645,8 @@ signed integer - -## services\.proxy-suite\.singBox\.tun\.perApp\.interface + +## services\.proxy-suite\.proxy\.tun\.perApp\.interface @@ -3526,8 +3679,8 @@ string - -## services\.proxy-suite\.singBox\.tun\.perApp\.localSubnets + +## services\.proxy-suite\.proxy\.tun\.perApp\.localSubnets @@ -3565,8 +3718,8 @@ list of string - -## services\.proxy-suite\.singBox\.tun\.perApp\.mtu + +## services\.proxy-suite\.proxy\.tun\.perApp\.mtu @@ -3598,8 +3751,8 @@ signed integer - -## services\.proxy-suite\.singBox\.tun\.perApp\.routeTable + +## services\.proxy-suite\.proxy\.tun\.perApp\.routeTable @@ -3631,13 +3784,13 @@ signed integer - -## services\.proxy-suite\.singBox\.urlTest\.interval + +## services\.proxy-suite\.proxy\.urlTest\.interval -How often sing-box re-tests all outbounds\. Accepts a Go duration -string (e\.g\. “1m”, “3m”, “10m”)\. +How often the active backend re-tests all outbounds\. Accepts a Go +duration string (e\.g\. “1m”, “3m”, “10m”)\. Only used when selection = “urltest”\. @@ -3666,48 +3819,12 @@ string - -## services\.proxy-suite\.singBox\.urlTest\.tolerance + +## services\.proxy-suite\.proxy\.urlTest\.url -Latency tolerance in milliseconds\. The current proxy is only replaced -when a competing one is faster by more than this value\. - -Only used when selection = “urltest”\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -50 -``` - - - -*Example:* - -```nix -100 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.singBox\.urlTest\.url - - - -URL that sing-box fetches through each proxy to measure latency\. +URL that the active backend fetches through each proxy to measure latency\. Only used when selection = “urltest”\. Set this to a URL that is actually blocked in your region (e\.g\. @@ -3741,6 +3858,75 @@ string + +## services\.proxy-suite\.proxy\.xray\.enable + + + +Whether to enable XRay proxy backend\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + + + +*Example:* + +```nix +true +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) + + + + +## services\.proxy-suite\.proxy\.xray\.package + + + +XRay package used by proxy-suite systemd services\. + +Override this to pin or test a specific XRay build when upstream +protocol behavior changes\. + + + +*Type:* +package + + + +*Default:* + +```nix +pkgs.xray +``` + + + +*Example:* + +```nix +pkgs.xray +``` + +*Declared by:* + - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) + + + ## services\.proxy-suite\.tgWsProxy\.enable @@ -3785,7 +3971,7 @@ transparent routing backends\. When enabled and global TUN or TProxy mode is configured, the tg-ws-proxy systemd service receives a packet mark and an earlier policy-routing rule back to the main table\. This prevents global TUN -from routing the local Telegram MTProto relay through sing-box again, +from routing the local Telegram MTProto relay through the proxy backend again, which can otherwise break tg-ws-proxy after enabling TUN mode\. @@ -4101,8 +4287,6 @@ true ## services\.proxy-suite\.tray\.pollInterval - - Tray status refresh interval in seconds\. Lower values make UI state changes appear faster, while higher values reduce background polling overhead\. @@ -4309,6 +4493,8 @@ true ## services\.proxy-suite\.zapret\.cidrExemption\.cidrs + + Subnets to exempt from zapret’s NFQUEUE mangle rules\. Useful when a VM (libvirt, etc\.) is behind NAT and zapret would corrupt its traffic through the host’s nftables\. @@ -4471,7 +4657,7 @@ list of (submodule) -Whether this custom hostlist should also be mirrored into sing-box +Whether this custom hostlist should also be mirrored into proxy direct domain routing when zapret\.syncDirectRouting = true\. @@ -4637,7 +4823,7 @@ and list-twitter\.txt in the generated zapret config when the selected upstream preset does not already reference them\. When syncDirectRouting = true, domains from these extra lists are also -mirrored into sing-box direct routing\. +mirrored into proxy direct routing\. @@ -4671,7 +4857,7 @@ false Extra IPs/CIDRs to add to zapret’s ipset\. -Mirrored into sing-box direct IP routing when +Mirrored into proxy direct IP routing when syncDirectRoutingUserIps = true\. @@ -4708,7 +4894,7 @@ list of string IPs/CIDRs to exclude from zapret’s ipset\. -Also excluded from zapret-derived sing-box direct IP routing when +Also excluded from zapret-derived proxy direct IP routing when syncDirectRoutingUserIps = true\. @@ -4746,7 +4932,7 @@ list of string Domains to exclude from zapret interception\. When syncDirectRouting = true, these exclusions also remove matching -domains from the zapret-derived sing-box direct-routing set\. +domains from the zapret-derived proxy direct-routing set\. @@ -4783,7 +4969,7 @@ list of string Extra domains to include in zapret’s interception list\. When syncDirectRouting = true, these domains are also mirrored into -sing-box direct routing\. +proxy direct routing\. @@ -4921,7 +5107,7 @@ signed integer When zapret\.enable = true, mirror zapret’s upstream domain hostlists -into sing-box direct domain routing\. +into proxy direct domain routing\. This includes the default zapret domain lists and any custom hostlistRules entries with enableDirectSync = true\. @@ -4958,7 +5144,7 @@ true When zapret\.enable = true, mirror zapret’s upstream ipset ranges -(such as ipset-all\.txt minus exclusions) into sing-box direct IP routing\. +(such as ipset-all\.txt minus exclusions) into proxy direct IP routing\. @@ -4992,7 +5178,7 @@ false When zapret\.enable = true, mirror user-defined zapret\.ipsetAll and -zapret\.ipsetExclude entries into sing-box direct IP routing\. +zapret\.ipsetExclude entries into proxy direct IP routing\. @@ -5018,4 +5204,3 @@ true *Declared by:* - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - diff --git a/flake.nix b/flake.nix index 63139bd..e2c5a49 100644 --- a/flake.nix +++ b/flake.nix @@ -1,5 +1,5 @@ { - description = "NixOS proxy suite – sing-box, zapret, tg-ws-proxy"; + description = "NixOS proxy suite - SingBox, XRay, zapret, tg-ws-proxy"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index f41009b..fc22d78 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -1,5 +1,5 @@ -# Build-time sing-box configuration templates. -# The proxy outbound(s) are injected at service start time, not here. +# Build-time proxy backend configuration templates. +# Proxy outbounds are injected at service start time, not here. { lib, pkgs, @@ -10,7 +10,9 @@ let derived = import ./derived.nix { inherit lib cfg; }; inherit (derived) + proxyCfg singBoxCfg + xrayEnabled globalTun globalTproxy clashApiEnabled @@ -18,7 +20,7 @@ let perAppTun = derived.perAppRoutingTun; direct = rules.direct; - mkDnsServer = + mkSingBoxDnsServer = tag: upstream: detour: { inherit tag; @@ -28,17 +30,17 @@ let } // lib.optionalAttrs (detour != null) { inherit detour; }; - mkDnsConfig = + mkSingBoxDnsConfig = { localDetour ? null, }: { servers = [ - (mkDnsServer "remote" singBoxCfg.dns.remote "proxy") - (mkDnsServer "local" singBoxCfg.dns.local localDetour) + (mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy") + (mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour) ]; rules = - lib.optional (builtins.elem "google" singBoxCfg.routing.proxy.geosites) { + lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) { rule_set = [ "geosite-google" ]; server = "remote"; } @@ -46,7 +48,7 @@ let rule_set = map (s: "geosite-${s}") direct.geosites; server = "local"; }; - final = if singBoxCfg.proxyByDefault then "remote" else "local"; + final = if proxyCfg.proxyByDefault then "remote" else "local"; }; clashApiBlock = lib.optionalAttrs clashApiEnabled { @@ -57,7 +59,7 @@ let }; }; - mkConfig = + mkSingBoxConfig = { enableMixed ? false, enableTProxy ? false, @@ -77,10 +79,7 @@ let { log.level = "warn"; - # Keep "local" DNS on the direct path by default, but avoid explicit - # detour="direct" because sing-box rejects detouring to an empty - # direct outbound. Global TUN can force local DNS through proxy. - dns = mkDnsConfig { + dns = mkSingBoxDnsConfig { localDetour = if forceLocalDnsViaProxy then "proxy" else null; }; @@ -88,8 +87,8 @@ let lib.optional enableMixed { type = "mixed"; tag = "mixed-in"; - listen = singBoxCfg.listenAddress; - listen_port = singBoxCfg.port; + listen = proxyCfg.listenAddress; + listen_port = proxyCfg.port; } ++ lib.optional enableTProxy { type = "tproxy"; @@ -110,14 +109,11 @@ let stack = "mixed"; } // lib.optionalAttrs tunAutoRoute { - # Keep sing-box auto_route indexes explicit so service cleanup can - # reliably remove stale policy-routing state after unclean stops. iproute2_table_index = tunAutoRouteTableIndex; iproute2_rule_index = tunAutoRouteRuleIndex; } ); - # proxy outbound(s) are prepended at runtime by the start script outbounds = [ ( { @@ -135,25 +131,155 @@ let route = { default_domain_resolver = "local"; rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets; - rules = rules.routingRules; - final = if singBoxCfg.proxyByDefault then "proxy" else "direct"; + rules = rules.singBoxRoutingRules; + final = if proxyCfg.proxyByDefault then "proxy" else "direct"; } // lib.optionalAttrs (enableTun && tunAutoRoute) { - # sing-box recommends this with auto_route to keep its own outbound - # connections pinned to the host's default NIC instead of looping back - # into the TUN interface. auto_detect_interface = true; }; } // lib.optionalAttrs enableClashApi clashApiBlock; - tproxyTemplate = mkConfig { + xrayDnsAddress = + upstream: + let + base = + if upstream.type == "tls" then + "tls://${upstream.address}" + else + upstream.address; + in + if upstream.port == 53 && upstream.type != "tls" then + base + else + "${base}:${toString upstream.port}"; + + xraySniffing = { + enabled = true; + destOverride = [ + "http" + "tls" + "quic" + ]; + }; + + xrayFinalRule = + tag: + { type = "field"; network = "tcp,udp"; } + // ( + if tag == "proxy" && proxyCfg.selection == "urltest" then + { balancerTag = "proxy"; } + else + { outboundTag = tag; } + ); + + xrayRouteRules = + rules.xrayRoutingRules ++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ]; + + xrayDirectOutbound = + useOutboundRoutingMark: + { + protocol = "freedom"; + tag = "direct"; + settings = { }; + } + // lib.optionalAttrs useOutboundRoutingMark { + streamSettings.sockopt.mark = globalTproxy.proxyMark; + }; + + mkXrayConfig = + { + enableMixed ? false, + enableTProxy ? false, + enableTun ? false, + tunInterface ? globalTun.interface, + tunAddress ? globalTun.address, + tunMtu ? globalTun.mtu, + useOutboundRoutingMark ? false, + enableUrlTest ? proxyCfg.selection == "urltest", + }: + { + log.loglevel = "warning"; + dns.servers = [ + (xrayDnsAddress proxyCfg.dns.remote) + (xrayDnsAddress proxyCfg.dns.local) + ]; + inbounds = + lib.optional enableMixed { + tag = "mixed-in"; + protocol = "socks"; + listen = proxyCfg.listenAddress; + port = proxyCfg.port; + settings = { + auth = "noauth"; + udp = true; + ip = proxyCfg.listenAddress; + }; + sniffing = xraySniffing; + } + ++ lib.optional enableTProxy { + tag = "tproxy-in"; + protocol = "tunnel"; + listen = "127.0.0.1"; + port = globalTproxy.port; + settings = { + allowedNetwork = "tcp,udp"; + followRedirect = true; + }; + streamSettings.sockopt.tproxy = "tproxy"; + sniffing = xraySniffing; + } + ++ lib.optional enableTun { + tag = "tun-in"; + protocol = "tun"; + settings = { + name = tunInterface; + mtu = tunMtu; + gateway = [ tunAddress ]; + dns = [ proxyCfg.dns.local.address ]; + userLevel = 0; + autoOutboundsInterface = "auto"; + }; + sniffing = xraySniffing; + }; + outbounds = [ + (xrayDirectOutbound useOutboundRoutingMark) + { + protocol = "blackhole"; + tag = "block"; + settings = { }; + } + ]; + routing = { + domainStrategy = "IPIfNonMatch"; + domainMatcher = "hybrid"; + rules = xrayRouteRules; + } + // lib.optionalAttrs enableUrlTest { + balancers = [ + { + tag = "proxy"; + selector = [ "proxy-suite-ob-" ]; + strategy = { type = "leastPing"; }; + } + ]; + }; + } + // lib.optionalAttrs enableUrlTest { + observatory = { + subjectSelector = [ "proxy-suite-ob-" ]; + probeUrl = proxyCfg.urlTest.url; + probeInterval = proxyCfg.urlTest.interval; + }; + }; + + singBoxTproxyTemplate = mkSingBoxConfig { enableMixed = true; enableTProxy = true; useOutboundRoutingMark = true; }; - tunTemplate = mkConfig { + singBoxTunTemplate = mkSingBoxConfig { enableTun = true; tunInterface = globalTun.interface; tunAddress = globalTun.address; @@ -161,15 +287,11 @@ let tunAutoRoute = true; tunAutoRedirect = true; tunStrictRoute = true; - # Keep the bootstrap resolver on the direct path. Sending the "local" DNS - # transport through outbound tag "proxy" causes a resolver loop in global - # TUN mode because outbound hostname resolution and urltest probe lookups - # recurse back into the same proxy path. forceLocalDnsViaProxy = false; enableClashApi = false; }; - perAppTunTemplate = mkConfig { + singBoxPerAppTunTemplate = mkSingBoxConfig { enableTun = true; tunInterface = perAppTun.interface; tunAddress = perAppTun.address; @@ -178,19 +300,43 @@ let tunAutoRedirect = false; tunStrictRoute = false; forceLocalDnsViaProxy = false; - # App TUN can be used alongside TProxy; mark direct egress so TProxy output - # rules do not re-intercept sing-box's own packets. useOutboundRoutingMark = globalTproxy.enable; enableClashApi = false; }; + xrayTproxyTemplate = mkXrayConfig { + enableMixed = true; + enableTProxy = true; + useOutboundRoutingMark = true; + }; + + xrayTunTemplate = mkXrayConfig { + enableTun = true; + tunInterface = globalTun.interface; + tunAddress = globalTun.address; + tunMtu = globalTun.mtu; + }; + + xrayPerAppTunTemplate = mkXrayConfig { + enableTun = true; + tunInterface = perAppTun.interface; + tunAddress = perAppTun.address; + tunMtu = perAppTun.mtu; + useOutboundRoutingMark = globalTproxy.enable; + }; + + tproxyTemplate = if xrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate; + tunTemplate = if xrayEnabled then xrayTunTemplate else singBoxTunTemplate; + perAppTunTemplate = if xrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate; + routeModeRules = if xrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules; + tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate); tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate); perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" ( builtins.toJSON perAppTunTemplate ); routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" ( - builtins.toJSON rules.routeModeRules + builtins.toJSON routeModeRules ); in diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 78ef999..5cea743 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -4,28 +4,47 @@ }: let - singBoxCfg = cfg.singBox; + proxyCfg = cfg.proxy; + singBoxCfg = + proxyCfg + // { + enable = proxyCfg.enable && proxyCfg.singBox.enable; + package = proxyCfg.singBox.package; + clashApiPort = proxyCfg.singBox.clashApiPort; + urlTest = proxyCfg.urlTest // { tolerance = proxyCfg.singBox.urlTest.tolerance; }; + }; + xrayCfg = proxyCfg.xray; + proxyEnabled = proxyCfg.enable; + singBoxEnabled = proxyCfg.enable && proxyCfg.singBox.enable; + xrayEnabled = proxyCfg.enable && proxyCfg.xray.enable; + activeBackend = + if xrayEnabled then + "xray" + else if singBoxEnabled then + "sing-box" + else + null; perAppRoutingCfg = cfg.perAppRouting; - globalTun = singBoxCfg.tun; - globalTproxy = singBoxCfg.tproxy; - perAppRoutingTun = singBoxCfg.tun.perApp; - perAppRoutingTproxy = singBoxCfg.tproxy.perApp; + globalTun = proxyCfg.tun; + globalTproxy = proxyCfg.tproxy; + perAppRoutingTun = proxyCfg.tun.perApp; + perAppRoutingTproxy = proxyCfg.tproxy.perApp; perAppZapretCfg = cfg.zapret.perApp; userControlCfg = cfg.userControl; - selectionMode = singBoxCfg.selection; + selectionMode = proxyCfg.selection; builtinTags = [ "proxy" "direct" "block" ]; - outboundTags = map (ob: ob.tag) singBoxCfg.outbounds; - subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions; + outboundTags = map (ob: ob.tag) proxyCfg.outbounds; + subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions; - hasStaticOutbounds = singBoxCfg.outbounds != [ ]; - hasSubscriptions = singBoxCfg.subscriptions != [ ]; + hasStaticOutbounds = proxyCfg.outbounds != [ ]; + hasSubscriptions = proxyCfg.subscriptions != [ ]; collapseNamedOutbounds = selectionMode == "first"; - clashApiEnabled = selectionMode != "first"; + clashApiEnabled = singBoxEnabled && selectionMode != "first"; perAppZapretEnabled = perAppZapretCfg.enable; userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable; @@ -33,13 +52,19 @@ let map (rule: rule.outbound) ( builtins.filter ( rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags) - ) singBoxCfg.routing.rules + ) proxyCfg.routing.rules ) ); in { inherit + proxyCfg singBoxCfg + xrayCfg + proxyEnabled + singBoxEnabled + xrayEnabled + activeBackend perAppRoutingCfg globalTun globalTproxy diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index c7a8af7..54ed93f 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -6,10 +6,10 @@ }: let - singBoxCfg = cfg.singBox; - globalTproxy = singBoxCfg.tproxy; - perAppTun = singBoxCfg.tun.perApp; - perAppTproxy = singBoxCfg.tproxy.perApp; + proxyCfg = cfg.proxy; + globalTproxy = proxyCfg.tproxy; + perAppTun = proxyCfg.tun.perApp; + perAppTproxy = proxyCfg.tproxy.perApp; zapretApp = cfg.zapret.perApp; tgWsProxyCfg = cfg.tgWsProxy; tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy; diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index f8b7b9b..5a045ff 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -3,6 +3,7 @@ { imports = [ ./other.nix + ./legacy-sing-box.nix ./sing-box.nix ./sing-box-outbounds.nix ./sing-box-dns.nix diff --git a/modules/proxy-suite/options/legacy-sing-box.nix b/modules/proxy-suite/options/legacy-sing-box.nix new file mode 100644 index 0000000..bbe67e2 --- /dev/null +++ b/modules/proxy-suite/options/legacy-sing-box.nix @@ -0,0 +1,72 @@ +{ lib, config, ... }: + +let + inherit (lib) mkIf mkOption types; + cfg = config.services.proxy-suite; + legacy = cfg.singBox or { }; + legacyUsed = legacy != { }; + + has = name: builtins.hasAttr name legacy; + hasNested = path: lib.hasAttrByPath path legacy; + getNested = path: lib.getAttrFromPath path legacy; + setIf = condition: value: lib.optionalAttrs condition value; +in +{ + options.services.proxy-suite.singBox = mkOption { + type = types.submodule { + freeformType = types.anything; + }; + default = { }; + visible = false; + description = '' + Deprecated compatibility tree for the old services.proxy-suite.singBox + options. Use services.proxy-suite.proxy instead. + ''; + }; + + config = mkIf legacyUsed { + warnings = [ + '' + services.proxy-suite.singBox is deprecated. Move shared options to + services.proxy-suite.proxy and SingBox-specific options to + services.proxy-suite.proxy.singBox. + '' + ]; + + services.proxy-suite.proxy = lib.mkMerge [ + (setIf (!has "enable") { + enable = lib.mkDefault true; + singBox.enable = lib.mkDefault true; + }) + (setIf (has "enable") { + enable = lib.mkDefault legacy.enable; + singBox.enable = lib.mkDefault legacy.enable; + }) + (setIf (has "listenAddress") { listenAddress = lib.mkDefault legacy.listenAddress; }) + (setIf (has "port") { port = lib.mkDefault legacy.port; }) + (setIf (has "auth") { auth = lib.mkDefault legacy.auth; }) + (setIf (has "proxyByDefault") { proxyByDefault = lib.mkDefault legacy.proxyByDefault; }) + (setIf (has "outbounds") { outbounds = lib.mkDefault legacy.outbounds; }) + (setIf (has "subscriptions") { subscriptions = lib.mkDefault legacy.subscriptions; }) + (setIf (has "subscriptionUpdateInterval") { + subscriptionUpdateInterval = lib.mkDefault legacy.subscriptionUpdateInterval; + }) + (setIf (has "selection") { selection = lib.mkDefault legacy.selection; }) + (setIf (has "dns") { dns = lib.mkDefault legacy.dns; }) + (setIf (has "routing") { routing = lib.mkDefault legacy.routing; }) + (setIf (has "tun") { tun = lib.mkDefault legacy.tun; }) + (setIf (has "tproxy") { tproxy = lib.mkDefault legacy.tproxy; }) + (setIf (hasNested [ "urlTest" "url" ]) { + urlTest.url = lib.mkDefault (getNested [ "urlTest" "url" ]); + }) + (setIf (hasNested [ "urlTest" "interval" ]) { + urlTest.interval = lib.mkDefault (getNested [ "urlTest" "interval" ]); + }) + (setIf (hasNested [ "urlTest" "tolerance" ]) { + singBox.urlTest.tolerance = lib.mkDefault (getNested [ "urlTest" "tolerance" ]); + }) + (setIf (has "package") { singBox.package = lib.mkDefault legacy.package; }) + (setIf (has "clashApiPort") { singBox.clashApiPort = lib.mkDefault legacy.clashApiPort; }) + ]; + }; +} diff --git a/modules/proxy-suite/options/other.nix b/modules/proxy-suite/options/other.nix index f27d256..4e261d6 100644 --- a/modules/proxy-suite/options/other.nix +++ b/modules/proxy-suite/options/other.nix @@ -6,7 +6,7 @@ let in { options.services.proxy-suite = { - enable = mkEnableOption "proxy suite (sing-box + zapret + tg-ws-proxy)"; + enable = mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)"; userControl = { group = mkOption { @@ -141,7 +141,7 @@ in When enabled and global TUN or TProxy mode is configured, the tg-ws-proxy systemd service receives a packet mark and an earlier policy-routing rule back to the main table. This prevents global TUN - from routing the local Telegram MTProto relay through sing-box again, + from routing the local Telegram MTProto relay through the proxy backend again, which can otherwise break tg-ws-proxy after enabling TUN mode. ''; example = true; diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index 03061ce..ae41b27 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -20,8 +20,8 @@ in Current curated defaults: - `proxychains`: route = "proxychains" - - `tun`: route = "tun" when singBox.tun.perApp.enable = true - - `tproxy`: route = "tproxy" when singBox.tproxy.perApp.enable = true + - `tun`: route = "tun" when proxy.tun.perApp.enable = true + - `tproxy`: route = "tproxy" when proxy.tproxy.perApp.enable = true - `zapret`: route = "zapret" when zapret.perApp.enable = true This makes `proxy-ctl wrap proxychains -- ` available @@ -51,10 +51,10 @@ in - "zapret" for per-app-scoped zapret handling through a separate zapret instance without changing the app's network path or exit IP - proxychains-based wrapping depends on singBox.enable = true and the - local proxy-suite mixed proxy listener provided by sing-box. The - "tun" route depends on singBox.tun.perApp.enable = true. The "tproxy" - route depends on singBox.tproxy.perApp.enable = true. The "zapret" + proxychains-based wrapping depends on proxy.enable = true and the + local proxy-suite proxy listener provided by the active backend. The + "tun" route depends on proxy.tun.perApp.enable = true. The "tproxy" + route depends on proxy.tproxy.perApp.enable = true. The "zapret" route depends on zapret.perApp.enable = true. When createDefaultProfiles = true, curated defaults are added on top diff --git a/modules/proxy-suite/options/sing-box-dns.nix b/modules/proxy-suite/options/sing-box-dns.nix index d952085..0818b5c 100644 --- a/modules/proxy-suite/options/sing-box-dns.nix +++ b/modules/proxy-suite/options/sing-box-dns.nix @@ -5,7 +5,7 @@ let t = import ./types.nix { inherit lib; }; in { - options.services.proxy-suite.singBox.dns = { + options.services.proxy-suite.proxy.dns = { local = mkOption { type = t.dnsUpstreamType; default = { @@ -15,7 +15,7 @@ in }; description = '' DNS upstream used for the built-in "local" resolver role. - This resolver is also used as sing-box route.default_domain_resolver. + This resolver is also used as the backend's default domain resolver. The module keeps detour policy automatic: in mixed/TProxy mode and per-app-routing TUN mode, "local" stays on the direct path (without an @@ -40,7 +40,7 @@ in DNS upstream used for the built-in "remote" resolver role. This resolver always detours through the proxy and becomes the - generated dns.final target when singBox.proxyByDefault = true. + generated dns.final target when proxy.proxyByDefault = true. ''; example = { type = "tls"; diff --git a/modules/proxy-suite/options/sing-box-outbounds.nix b/modules/proxy-suite/options/sing-box-outbounds.nix index 4815046..9c77608 100644 --- a/modules/proxy-suite/options/sing-box-outbounds.nix +++ b/modules/proxy-suite/options/sing-box-outbounds.nix @@ -5,16 +5,18 @@ let t = import ./types.nix { inherit lib; }; in { - options.services.proxy-suite.singBox = { + options.services.proxy-suite.proxy = { outbounds = mkOption { type = types.listOf t.outboundType; default = [ ]; description = '' List of static proxy outbounds. - Set exactly one of urlFile, url, or json per entry. + Set exactly one of urlFile, url, singBoxJson, xrayJson, or the + deprecated json field per entry. Backend-specific raw JSON fields are + only valid with their matching backend. At least one outbound or one subscription is required when - singBox.enable = true. + proxy.enable = true. ''; example = [ { @@ -37,12 +39,12 @@ in (standard v2rayN / Clash subscription format) or plain text of the same. On first service start, each subscription is fetched live and cached - under /var/lib/proxy-suite/subscriptions/.json. Later restarts + under /var/lib/proxy-suite/subscriptions//.json. Later restarts reuse the cache, so ordinary service restarts do not need network access. - A systemd timer (proxy-suite-subscription-update) refreshes all caches on - the interval set by subscriptionUpdateInterval and restarts the running - sing-box services after a successful refresh. + A systemd timer (proxy-suite-subscription-update) refreshes all caches + on the interval set by subscriptionUpdateInterval and restarts the + running proxy services after a successful refresh. ''; example = [ { @@ -64,7 +66,7 @@ in all subscription caches. Accepts any systemd time span string (e.g. "1h", "6h", "1d", "12h"). - Only used when singBox.subscriptions is non-empty. The timer also runs + Only used when proxy.subscriptions is non-empty. The timer also runs once shortly after boot. ''; example = "6h"; @@ -86,11 +88,13 @@ in - "selector": create a Clash-compatible selector outbound tagged "proxy" and keep all configured outbounds available for manual switching via the Clash API. - - "urltest": create an automatic latency-testing outbound tagged - "proxy" and keep all configured outbounds available so sing-box - can periodically probe and switch to a faster one. + - "urltest": create automatic latency testing tagged "proxy" and + keep all configured outbounds available so the active backend can + periodically probe and switch to a faster one. - clashApiPort is only used with "selector" or "urltest". + proxy.singBox.clashApiPort is only used with "selector" or "urltest" + on the SingBox backend. "selector" is SingBox-only. "urltest" maps to + SingBox urltest or XRay observatory/balancer depending on backend. urlTest.* options are only used with "urltest". Per-outbound tags are only individually meaningful with "selector" or "urltest". @@ -103,7 +107,7 @@ in type = types.str; default = "https://www.gstatic.com/generate_204"; description = '' - URL that sing-box fetches through each proxy to measure latency. + URL that the active backend fetches through each proxy to measure latency. Only used when selection = "urltest". Set this to a URL that is actually blocked in your region (e.g. @@ -118,35 +122,12 @@ in type = types.str; default = "3m"; description = '' - How often sing-box re-tests all outbounds. Accepts a Go duration - string (e.g. "1m", "3m", "10m"). + How often the active backend re-tests all outbounds. Accepts a Go + duration string (e.g. "1m", "3m", "10m"). Only used when selection = "urltest". ''; example = "1m"; }; - - tolerance = mkOption { - type = types.int; - default = 50; - description = '' - Latency tolerance in milliseconds. The current proxy is only replaced - when a competing one is faster by more than this value. - - Only used when selection = "urltest". - ''; - example = 100; - }; - }; - - clashApiPort = mkOption { - type = types.port; - default = 9090; - description = '' - Port for the Clash-compatible REST API exposed by sing-box. - Only used when selection is "selector" or "urltest". Ignored in - "first" mode because there is no selector-style outbound to control. - ''; - example = 9090; }; }; } diff --git a/modules/proxy-suite/options/sing-box-routing.nix b/modules/proxy-suite/options/sing-box-routing.nix index 4b74817..a8cfbc1 100644 --- a/modules/proxy-suite/options/sing-box-routing.nix +++ b/modules/proxy-suite/options/sing-box-routing.nix @@ -5,7 +5,7 @@ let t = import ./types.nix { inherit lib; }; in { - options.services.proxy-suite.singBox.routing = { + options.services.proxy-suite.proxy.routing = { enableRuDirect = mkOption { type = types.bool; default = true; @@ -98,7 +98,7 @@ in The outbound can be a configured outbound tag (useful with selector/urltest), or one of: "proxy" (active proxy), "direct", "block". - Order is preserved. The first matching rule wins in sing-box. + Order is preserved. The first matching rule wins in the active backend. With selection = "first", non-built-in outbound tags are effectively routed to the single active "proxy" outbound. ''; diff --git a/modules/proxy-suite/options/sing-box-tproxy.nix b/modules/proxy-suite/options/sing-box-tproxy.nix index 02db000..710dc4d 100644 --- a/modules/proxy-suite/options/sing-box-tproxy.nix +++ b/modules/proxy-suite/options/sing-box-tproxy.nix @@ -4,8 +4,8 @@ let inherit (lib) mkOption mkEnableOption types; in { - options.services.proxy-suite.singBox.tproxy = { - enable = mkEnableOption "global sing-box TProxy mode service"; + options.services.proxy-suite.proxy.tproxy = { + enable = mkEnableOption "global proxy TProxy mode service"; autostart = mkOption { type = types.bool; @@ -13,7 +13,7 @@ in description = '' Whether to start proxy-suite-tproxy automatically during boot by attaching it to multi-user.target. - Cannot be enabled together with singBox.tun.autostart. + Cannot be enabled together with proxy.tun.autostart. ''; example = true; }; @@ -22,7 +22,7 @@ in type = types.port; default = 1081; description = '' - Local listen port for sing-box's TProxy inbound. + Local listen port for the proxy backend's TProxy inbound. nftables redirection created by proxy-suite-tproxy sends intercepted TCP/UDP traffic to this port. ''; @@ -35,7 +35,7 @@ in description = '' Mark applied to intercepted packets in global TProxy mode. A matching `ip rule` routes this mark to - singBox.tproxy.routeTable, which points traffic to + proxy.tproxy.routeTable, which points traffic to loopback for local proxy processing. ''; example = 1; @@ -45,7 +45,7 @@ in type = types.int; default = 2; description = '' - Mark applied to sing-box egress packets in global TProxy mode so + Mark applied to backend egress packets in global TProxy mode so they bypass re-interception and do not loop back into the transparent proxy path. ''; @@ -58,7 +58,7 @@ in description = '' Policy-routing table number used for global TProxy interception flow. The module installs a local default route in this table and binds it - to singBox.tproxy.fwmark. + to proxy.tproxy.fwmark. ''; example = 100; }; @@ -81,7 +81,7 @@ in }; perApp = { - enable = mkEnableOption "per-app-scoped sing-box TProxy backend for perAppRouting profiles"; + enable = mkEnableOption "per-app-scoped proxy TProxy backend for perAppRouting profiles"; fwmark = mkOption { type = types.int; diff --git a/modules/proxy-suite/options/sing-box-tun.nix b/modules/proxy-suite/options/sing-box-tun.nix index a11569b..bb0e8b9 100644 --- a/modules/proxy-suite/options/sing-box-tun.nix +++ b/modules/proxy-suite/options/sing-box-tun.nix @@ -36,8 +36,8 @@ let }; in { - options.services.proxy-suite.singBox.tun = { - enable = mkEnableOption "global sing-box TUN mode service"; + options.services.proxy-suite.proxy.tun = { + enable = mkEnableOption "global proxy TUN mode service"; autostart = mkOption { type = types.bool; @@ -45,13 +45,13 @@ in description = '' Whether to start proxy-suite-tun automatically during boot by attaching it to multi-user.target. - Cannot be enabled together with singBox.tproxy.autostart. + Cannot be enabled together with proxy.tproxy.autostart. ''; example = true; }; perApp = { - enable = mkEnableOption "per-app-scoped sing-box TUN backend for perAppRouting profiles"; + enable = mkEnableOption "per-app-scoped proxy TUN backend for perAppRouting profiles"; fwmark = mkOption { type = types.int; diff --git a/modules/proxy-suite/options/sing-box.nix b/modules/proxy-suite/options/sing-box.nix index ad525b6..4cea891 100644 --- a/modules/proxy-suite/options/sing-box.nix +++ b/modules/proxy-suite/options/sing-box.nix @@ -1,31 +1,18 @@ -# Core sing-box options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix. +# Core proxy options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix. { lib, pkgs, ... }: let inherit (lib) literalExpression mkOption mkEnableOption types; in { - options.services.proxy-suite.singBox = { + options.services.proxy-suite.proxy = { enable = mkOption { type = types.bool; - default = true; + default = false; description = '' - Whether to configure and run sing-box services for proxy-suite. - When disabled, sing-box services and generated sing-box configs are - skipped even if proxy-suite itself is enabled. - ''; - }; - - package = mkOption { - type = types.package; - default = pkgs.sing-box; - defaultText = literalExpression "pkgs.sing-box"; - example = literalExpression "pkgs.sing-box"; - description = '' - sing-box package used by proxy-suite systemd services. - - Override this to pin or test a specific sing-box build when upstream - protocol behavior changes. + Whether to configure and run the proxy backend services. + This is disabled by default; enable it explicitly and choose exactly + one backend with proxy.singBox.enable or proxy.xray.enable. ''; }; @@ -33,8 +20,8 @@ in type = types.str; default = "127.0.0.1"; description = '' - Address for the SOCKS5/HTTP mixed inbound to bind to. - This affects the always-on proxy-suite-socks service. + Address for the local SOCKS5/HTTP inbound to bind to. + This affects the proxy-suite-socks service. Use "0.0.0.0" only if you intentionally want to expose the proxy to other machines on your network. @@ -46,8 +33,9 @@ in type = types.port; default = 1080; description = '' - Listen port for the always-on SOCKS5/HTTP mixed inbound provided by - proxy-suite-socks. + Listen port for the local SOCKS5/HTTP proxy inbound provided by + proxy-suite-socks. SingBox exposes SOCKS5 and HTTP on this port. + XRay's Socks inbound also accepts SOCKS and HTTP. ''; example = 1080; }; @@ -102,10 +90,70 @@ in Whether traffic that does not match any explicit routing rule should go through the proxy or go direct. - This affects sing-box route.final and dns.final in the generated + This affects the generated backend route final and DNS final in the config. ''; example = true; }; + + singBox = { + enable = mkEnableOption "SingBox proxy backend"; + + package = mkOption { + type = types.package; + default = pkgs.sing-box; + defaultText = literalExpression "pkgs.sing-box"; + example = literalExpression "pkgs.sing-box"; + description = '' + sing-box package used by proxy-suite systemd services. + + Override this to pin or test a specific sing-box build when upstream + protocol behavior changes. + ''; + }; + + clashApiPort = mkOption { + type = types.port; + default = 9090; + description = '' + Port for the Clash-compatible REST API exposed by sing-box. + Only used when proxy.selection is "selector" or "urltest". Ignored + in "first" mode because there is no selector-style outbound to + control. + ''; + example = 9090; + }; + + urlTest.tolerance = mkOption { + type = types.int; + default = 50; + description = '' + Latency tolerance in milliseconds for sing-box urltest. The current + proxy is only replaced when a competing one is faster by more than + this value. + + Only used when proxy.selection = "urltest" and the SingBox backend + is active. + ''; + example = 100; + }; + }; + + xray = { + enable = mkEnableOption "XRay proxy backend"; + + package = mkOption { + type = types.package; + default = pkgs.xray; + defaultText = literalExpression "pkgs.xray"; + example = literalExpression "pkgs.xray"; + description = '' + XRay package used by proxy-suite systemd services. + + Override this to pin or test a specific XRay build when upstream + protocol behavior changes. + ''; + }; + }; }; } diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index bba3ff4..dac31c1 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -32,7 +32,7 @@ let default = [ ]; description = '' sing-geosite rule-set names to match in this routing rule. - Each name becomes a sing-box geosite rule-set reference. + Each name becomes a backend geosite rule-set reference. ''; example = [ "netflix" @@ -44,7 +44,7 @@ let default = [ ]; description = '' sing-geoip rule-set names to match in this routing rule. - Each name becomes a sing-box geoip rule-set reference. + Each name becomes a backend geoip rule-set reference. ''; example = [ "us" @@ -83,7 +83,8 @@ let e.g. "my-sub" -> tags like "my-sub-Server-DE". This value is also used as the subscription cache filename stem under - /var/lib/proxy-suite/subscriptions/, so it must be a safe identifier. + /var/lib/proxy-suite/subscriptions//, so it must be a safe + identifier. ''; example = "community-list"; }; @@ -125,7 +126,7 @@ let Outbound tag used in routing rules and multi-outbound selection. With selection = "selector" or "urltest", each outbound keeps its own - tag and can be selected directly. With selection = "first", sing-box + tag and can be selected directly. With selection = "first", proxy-suite routes through a single active outbound tagged "proxy", so individual proxy tags are mainly useful for documentation and config structure. ''; @@ -158,7 +159,7 @@ let example = "hy2://password@example.com:443?sni=example.com"; }; - json = mkOption { + singBoxJson = mkOption { type = types.nullOr types.attrs; default = null; description = '' @@ -166,9 +167,10 @@ let Embedded directly into the config at build time. The tag field is overridden by the outbound's tag option. - Set exactly one of urlFile, url, or json for each outbound. + Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for + each outbound. Use this when the proxy definition is easier to generate as native Nix - than as a single URL string. + than as a single URL string. Only valid with the SingBox backend. ''; example = { type = "vless"; @@ -178,6 +180,37 @@ let }; }; + xrayJson = mkOption { + type = types.nullOr types.attrs; + default = null; + description = '' + Raw XRay outbound configuration as a Nix attribute set. + Embedded directly into the config at build time. The tag field is + overridden by the outbound's tag option. + + Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for + each outbound. Only valid with the XRay backend. + ''; + example = { + protocol = "vless"; + settings = { + address = "example.com"; + port = 443; + id = "..."; + encryption = "none"; + }; + }; + }; + + json = mkOption { + type = types.nullOr types.attrs; + default = null; + visible = false; + description = '' + Deprecated alias for singBoxJson. Use singBoxJson instead. + ''; + }; + # Shorthand for attaching routing rules directly to an outbound definition. # Traffic matching these patterns is sent to this specific outbound. # Only meaningful when selection = "selector" or "urltest" (with "first", @@ -196,7 +229,7 @@ let ]; default = "udp"; description = '' - sing-box DNS transport type for this upstream resolver. + DNS transport type for this upstream resolver. ''; example = "tls"; }; @@ -280,7 +313,7 @@ let type = types.bool; default = true; description = '' - Whether this custom hostlist should also be mirrored into sing-box + Whether this custom hostlist should also be mirrored into proxy direct domain routing when zapret.syncDirectRouting = true. ''; }; @@ -317,7 +350,7 @@ let only that app's traffic is policy-routed into the app TUN backend. - "tproxy": launch the command in the dedicated per-app-routing TProxy slice so only that app's traffic is transparently intercepted by - the local sing-box TProxy inbound. + the local proxy TProxy inbound. - "zapret": launch the command in the dedicated per-app-routing zapret slice so only that app's traffic is handled by the separate per-app-scoped zapret instance. diff --git a/modules/proxy-suite/options/zapret.nix b/modules/proxy-suite/options/zapret.nix index 16ca7e5..7a56f6e 100644 --- a/modules/proxy-suite/options/zapret.nix +++ b/modules/proxy-suite/options/zapret.nix @@ -39,7 +39,7 @@ in default = true; description = '' When zapret.enable = true, mirror zapret's upstream domain hostlists - into sing-box direct domain routing. + into proxy direct domain routing. This includes the default zapret domain lists and any custom hostlistRules entries with enableDirectSync = true. @@ -52,7 +52,7 @@ in default = false; description = '' When zapret.enable = true, mirror zapret's upstream ipset ranges - (such as ipset-all.txt minus exclusions) into sing-box direct IP routing. + (such as ipset-all.txt minus exclusions) into proxy direct IP routing. ''; example = false; }; @@ -62,7 +62,7 @@ in default = true; description = '' When zapret.enable = true, mirror user-defined zapret.ipsetAll and - zapret.ipsetExclude entries into sing-box direct IP routing. + zapret.ipsetExclude entries into proxy direct IP routing. ''; example = true; }; @@ -87,7 +87,7 @@ in description = '' Extra domains to include in zapret's interception list. When syncDirectRouting = true, these domains are also mirrored into - sing-box direct routing. + proxy direct routing. ''; example = [ "youtube.com" ]; }; @@ -98,7 +98,7 @@ in description = '' Domains to exclude from zapret interception. When syncDirectRouting = true, these exclusions also remove matching - domains from the zapret-derived sing-box direct-routing set. + domains from the zapret-derived proxy direct-routing set. ''; example = [ "music.youtube.com" ]; }; @@ -108,7 +108,7 @@ in default = [ ]; description = '' Extra IPs/CIDRs to add to zapret's ipset. - Mirrored into sing-box direct IP routing when + Mirrored into proxy direct IP routing when syncDirectRoutingUserIps = true. ''; example = [ "203.0.113.0/24" ]; @@ -119,7 +119,7 @@ in default = [ ]; description = '' IPs/CIDRs to exclude from zapret's ipset. - Also excluded from zapret-derived sing-box direct IP routing when + Also excluded from zapret-derived proxy direct IP routing when syncDirectRoutingUserIps = true. ''; example = [ "203.0.113.10/32" ]; @@ -134,7 +134,7 @@ in upstream preset does not already reference them. When syncDirectRouting = true, domains from these extra lists are also - mirrored into sing-box direct routing. + mirrored into proxy direct routing. ''; example = false; }; diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index 966fe92..7f1de1d 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -8,8 +8,8 @@ let derived = import ./derived.nix { inherit lib cfg; }; - r = cfg.singBox.routing; - singBoxCfg = derived.singBoxCfg; + r = cfg.proxy.routing; + proxyCfg = derived.proxyCfg; zapretCfg = cfg.zapret; tgWsProxyCfg = cfg.tgWsProxy; @@ -116,7 +116,12 @@ let # to "proxy" instead of the original tag (which won't exist in sing-box). resolveTag = tag: - if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then "proxy" else tag; + if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then + "proxy" + else if derived.xrayEnabled && derived.selectionMode == "urltest" && !builtins.elem tag derived.builtinTags then + "proxy-suite-ob-${tag}" + else + tag; # Collect per-outbound routing attached directly to outbound definitions. perOutboundRules = lib.concatMap ( @@ -134,7 +139,7 @@ let geoips ; } - ) singBoxCfg.outbounds; + ) proxyCfg.outbounds; # All custom rules in priority order: per-outbound first, then explicit routing.rules. customRules = @@ -230,7 +235,7 @@ let (mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips)) ]; - routingRules = + singBoxRoutingRules = commonRules ++ lib.concatMap (item: item.entries) customRouteRules ++ proxyPrimaryRules @@ -239,7 +244,7 @@ let ++ blockRules ++ proxyGeoRules; - routeModeRules = { + singBoxRouteModeRules = { common = commonRules; custom = customRouteRules; proxyPrimary = proxyPrimaryRules; @@ -249,12 +254,118 @@ let proxyGeo = proxyGeoRules; }; + xrayTarget = + tag: + if tag == "proxy" && derived.selectionMode == "urltest" then + { balancerTag = "proxy"; } + else + { outboundTag = tag; }; + + mkXrayRule = + fields: tag: + ({ type = "field"; } // fields // (xrayTarget tag)); + + xrayDomainRules = + tag: domains: + lib.optional (domains != [ ]) (mkXrayRule { + domain = map (domain: "domain:${domain}") domains; + } tag); + + xrayIPRules = + tag: ips: + lib.optional (ips != [ ]) (mkXrayRule { + ip = ips; + } tag); + + xrayGeositeRules = + tag: geosites: + lib.optional (geosites != [ ]) (mkXrayRule { + domain = map (name: "geosite:${name}") geosites; + } tag); + + xrayGeoIPRules = + tag: geoips: + lib.optional (geoips != [ ]) (mkXrayRule { + ip = map (name: "geoip:${name}") geoips; + } tag); + + mkXrayCustomRuleEntries = + rule: + lib.flatten [ + (xrayDomainRules rule.outbound rule.domains) + (xrayIPRules rule.outbound rule.ips) + (xrayGeositeRules rule.outbound rule.geosites) + (xrayGeoIPRules rule.outbound rule.geoips) + ]; + + xrayCustomRouteRules = map ( + rule: { + category = customRuleCategory rule.outbound; + entries = mkXrayCustomRuleEntries rule; + } + ) customRules; + + xrayProxyPrimaryRules = lib.flatten [ + (xrayDomainRules "proxy" r.proxy.domains) + (xrayIPRules "proxy" r.proxy.ips) + ]; + + xrayDirectRules = lib.flatten [ + (xrayDomainRules "direct" direct.domains) + (xrayIPRules "direct" direct.ips) + (xrayGeositeRules "direct" direct.geosites) + (xrayGeoIPRules "direct" direct.geoips) + ]; + + xraySafetyDirectRules = [ + (mkXrayRule { ip = [ "geoip:private" ]; } "direct") + ] ++ lib.optional ( + tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { } + ) (mkXrayRule { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"); + + xrayBlockRules = lib.flatten [ + (xrayDomainRules "block" r.block.domains) + (xrayIPRules "block" r.block.ips) + (xrayGeositeRules "block" r.block.geosites) + (xrayGeoIPRules "block" r.block.geoips) + ]; + + xrayProxyGeoRules = lib.flatten [ + (xrayGeositeRules "proxy" r.proxy.geosites) + (xrayGeoIPRules "proxy" r.proxy.geoips) + ]; + + xrayRoutingRules = + lib.concatMap (item: item.entries) xrayCustomRouteRules + ++ xrayProxyPrimaryRules + ++ xrayDirectRules + ++ xraySafetyDirectRules + ++ xrayBlockRules + ++ xrayProxyGeoRules; + + xrayRouteModeRules = { + common = [ ]; + custom = xrayCustomRouteRules; + proxyPrimary = xrayProxyPrimaryRules; + direct = xrayDirectRules; + safetyDirect = xraySafetyDirectRules; + block = xrayBlockRules; + proxyGeo = xrayProxyGeoRules; + }; + + routingRules = singBoxRoutingRules; + routeModeRules = singBoxRouteModeRules; + in { inherit direct geositeRuleSets geoIPRuleSets + singBoxRoutingRules + singBoxRouteModeRules + xrayRoutingRules + xrayRouteModeRules routeModeRules routingRules ; diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 41e64e4..533f554 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -27,7 +27,11 @@ let ; inherit (derived) + proxyCfg singBoxCfg + proxyEnabled + singBoxEnabled + xrayEnabled perAppRoutingCfg globalTun globalTproxy @@ -39,34 +43,46 @@ let globalTunAutoRouteTable = 2022; featureAssertions = [ - (requireAvailable singBoxCfg.enable ( - singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ] - ) "proxy-suite: at least one outbound or subscription is required when singBox.enable = true") - (uniqueValues singBoxCfg.enable outboundTags "proxy-suite: outbound tags must be unique") - (uniqueValues singBoxCfg.enable subscriptionTags + (requireAvailable proxyCfg.singBox.enable proxyEnabled + "proxy-suite: proxy.singBox.enable requires proxy.enable = true" + ) + (requireAvailable proxyCfg.xray.enable proxyEnabled + "proxy-suite: proxy.xray.enable requires proxy.enable = true" + ) + (mkAssertion ( + !proxyEnabled || (proxyCfg.singBox.enable != proxyCfg.xray.enable) + ) "proxy-suite: exactly one of proxy.singBox.enable or proxy.xray.enable must be true when proxy.enable = true") + (requireAvailable proxyEnabled ( + proxyCfg.outbounds != [ ] || proxyCfg.subscriptions != [ ] + ) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true") + (uniqueValues proxyEnabled outboundTags "proxy-suite: outbound tags must be unique") + (uniqueValues proxyEnabled subscriptionTags "proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes" ) (mkAssertion ( - !singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags + !proxyEnabled || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags ) "proxy-suite: outbound tags must not use reserved names: proxy, direct, block") - (mkAssertion (!singBoxCfg.enable || invalidRoutingTargets == [ ]) + (mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ]) "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}" ) - (requireEnabled globalTun.enable singBoxCfg.enable - "proxy-suite: singBox.tun.enable requires singBox.enable = true" + (mkAssertion ( + !(xrayEnabled && proxyCfg.selection == "selector") + ) "proxy-suite: proxy.selection = \"selector\" is only available with proxy.singBox.enable = true") + (requireEnabled globalTun.enable proxyEnabled + "proxy-suite: proxy.tun.enable requires proxy.enable = true" ) - (requireEnabled globalTproxy.enable singBoxCfg.enable - "proxy-suite: singBox.tproxy.enable requires singBox.enable = true" + (requireEnabled globalTproxy.enable proxyEnabled + "proxy-suite: proxy.tproxy.enable requires proxy.enable = true" ) (requireEnabled globalTun.autostart globalTun.enable - "proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true" + "proxy-suite: proxy.tun.autostart requires proxy.tun.enable = true" ) (requireEnabled globalTproxy.autostart globalTproxy.enable - "proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true" + "proxy-suite: proxy.tproxy.autostart requires proxy.tproxy.enable = true" ) (mkAssertion (!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart)) - "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time" + "proxy-suite: proxy.tproxy.autostart and proxy.tun.autostart cannot both be enabled at the same time" ) ]; @@ -77,8 +93,8 @@ let (requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable "proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true" ) - (requireEnabled perAppRoutingCfg.proxychains.enable singBoxCfg.enable - "proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true" + (requireEnabled perAppRoutingCfg.proxychains.enable proxyEnabled + "proxy-suite: perAppRouting.proxychains.enable requires proxy.enable = true" ) (uniqueValues true effectivePerAppRoutingProfileNames "proxy-suite: perAppRouting profile names must be unique" @@ -86,32 +102,32 @@ let (requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable "proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true" ) - (requireAvailable hasProxychainsProfiles singBoxCfg.enable - "proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true" + (requireAvailable hasProxychainsProfiles proxyEnabled + "proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true" ) (requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable - "proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true" + "proxy-suite: proxy.tun.perApp.enable requires perAppRouting.enable = true" ) - (requireEnabled perAppRoutingTun.enable singBoxCfg.enable - "proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true" + (requireEnabled perAppRoutingTun.enable proxyEnabled + "proxy-suite: proxy.tun.perApp.enable requires proxy.enable = true" ) (requireAvailable hasTunProfiles perAppRoutingTun.enable - "proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true" + "proxy-suite: route=tun in perAppRouting.profiles requires proxy.tun.perApp.enable = true" ) - (requireAvailable hasTunProfiles singBoxCfg.enable - "proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true" + (requireAvailable hasTunProfiles proxyEnabled + "proxy-suite: route=tun in perAppRouting.profiles requires proxy.enable = true" ) (requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable - "proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true" + "proxy-suite: proxy.tproxy.perApp.enable requires perAppRouting.enable = true" ) - (requireEnabled perAppRoutingTproxy.enable singBoxCfg.enable - "proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true" + (requireEnabled perAppRoutingTproxy.enable proxyEnabled + "proxy-suite: proxy.tproxy.perApp.enable requires proxy.enable = true" ) (requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable - "proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true" + "proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.tproxy.perApp.enable = true" ) - (requireAvailable hasTproxyProfiles singBoxCfg.enable - "proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true" + (requireAvailable hasTproxyProfiles proxyEnabled + "proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.enable = true" ) (requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable "proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true" @@ -126,115 +142,115 @@ let condition = globalTun.enable && perAppRoutingTun.enable; left = globalTun.interface; right = perAppRoutingTun.interface; - message = "proxy-suite: singBox.tun.interface and singBox.tun.perApp.interface must differ"; + message = "proxy-suite: proxy.tun.interface and proxy.tun.perApp.interface must differ"; } { condition = globalTun.enable && perAppRoutingTun.enable; left = globalTun.address; right = perAppRoutingTun.address; - message = "proxy-suite: singBox.tun.address and singBox.tun.perApp.address must differ"; + message = "proxy-suite: proxy.tun.address and proxy.tun.perApp.address must differ"; } { condition = globalTun.enable && perAppRoutingTun.enable; left = perAppRoutingTun.routeTable; right = globalTunAutoRouteTable; - message = "proxy-suite: singBox.tun.perApp.routeTable must differ from the global TUN auto-route table 2022"; + message = "proxy-suite: proxy.tun.perApp.routeTable must differ from the global TUN auto-route table 2022"; } { condition = perAppRoutingTun.enable && globalTproxy.enable; left = perAppRoutingTun.fwmark; right = globalTproxy.fwmark; - message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled"; + message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled"; } { condition = perAppRoutingTun.enable && globalTproxy.enable; left = perAppRoutingTun.fwmark; right = globalTproxy.proxyMark; - message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled"; + message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled"; } { condition = perAppRoutingTun.enable && globalTproxy.enable; left = perAppRoutingTun.routeTable; right = globalTproxy.routeTable; - message = "proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled"; + message = "proxy-suite: proxy.tun.perApp.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled"; } { condition = perAppRoutingTproxy.enable; left = perAppRoutingTproxy.fwmark; right = globalTproxy.fwmark; - message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.fwmark"; + message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.fwmark"; } { condition = perAppRoutingTproxy.enable; left = perAppRoutingTproxy.fwmark; right = globalTproxy.proxyMark; - message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.proxyMark"; + message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.proxyMark"; } { condition = perAppRoutingTproxy.enable; left = perAppRoutingTproxy.routeTable; right = globalTproxy.routeTable; - message = "proxy-suite: singBox.tproxy.perApp.routeTable must differ from singBox.tproxy.routeTable"; + message = "proxy-suite: proxy.tproxy.perApp.routeTable must differ from proxy.tproxy.routeTable"; } { condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable; left = perAppRoutingTun.fwmark; right = perAppRoutingTproxy.fwmark; - message = "proxy-suite: singBox.tun.perApp.fwmark and singBox.tproxy.perApp.fwmark must differ"; + message = "proxy-suite: proxy.tun.perApp.fwmark and proxy.tproxy.perApp.fwmark must differ"; } { condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable; left = perAppRoutingTun.routeTable; right = perAppRoutingTproxy.routeTable; - message = "proxy-suite: singBox.tun.perApp.routeTable and singBox.tproxy.perApp.routeTable must differ"; + message = "proxy-suite: proxy.tun.perApp.routeTable and proxy.tproxy.perApp.routeTable must differ"; } { condition = perAppZapretCfg.enable; left = perAppZapretCfg.filterMark; right = globalTproxy.fwmark; - message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.fwmark"; + message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.fwmark"; } { condition = perAppZapretCfg.enable; left = perAppZapretCfg.filterMark; right = globalTproxy.proxyMark; - message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.proxyMark"; + message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.proxyMark"; } { condition = perAppRoutingTun.enable && perAppZapretCfg.enable; left = perAppRoutingTun.fwmark; right = perAppZapretCfg.filterMark; - message = "proxy-suite: singBox.tun.perApp.fwmark and zapret.perApp.filterMark must differ"; + message = "proxy-suite: proxy.tun.perApp.fwmark and zapret.perApp.filterMark must differ"; } { condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable; left = perAppRoutingTproxy.fwmark; right = perAppZapretCfg.filterMark; - message = "proxy-suite: singBox.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ"; + message = "proxy-suite: proxy.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ"; } { condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable; left = tgWsProxyCfg.routingMark; right = globalTproxy.fwmark; - message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tproxy.fwmark"; + message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.fwmark"; } { condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable; left = tgWsProxyCfg.routingMark; right = globalTproxy.proxyMark; - message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tproxy.proxyMark"; + message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.proxyMark"; } { condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable; left = tgWsProxyCfg.routingMark; right = perAppRoutingTun.fwmark; - message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tun.perApp.fwmark"; + message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark"; } { condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable; left = tgWsProxyCfg.routingMark; right = perAppRoutingTproxy.fwmark; - message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tproxy.perApp.fwmark"; + message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark"; } { condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable; @@ -253,47 +269,47 @@ let { condition = globalTun.enable; value = globalTun.mtu; - message = "proxy-suite: singBox.tun.mtu must be greater than zero"; + message = "proxy-suite: proxy.tun.mtu must be greater than zero"; } { condition = perAppRoutingTun.enable; value = perAppRoutingTun.mtu; - message = "proxy-suite: singBox.tun.perApp.mtu must be greater than zero"; + message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero"; } { condition = globalTproxy.enable; value = globalTproxy.fwmark; - message = "proxy-suite: singBox.tproxy.fwmark must be greater than zero"; + message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero"; } { condition = globalTproxy.enable; value = globalTproxy.proxyMark; - message = "proxy-suite: singBox.tproxy.proxyMark must be greater than zero"; + message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero"; } { condition = globalTproxy.enable; value = globalTproxy.routeTable; - message = "proxy-suite: singBox.tproxy.routeTable must be greater than zero"; + message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero"; } { condition = perAppRoutingTun.enable; value = perAppRoutingTun.fwmark; - message = "proxy-suite: singBox.tun.perApp.fwmark must be greater than zero"; + message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero"; } { condition = perAppRoutingTun.enable; value = perAppRoutingTun.routeTable; - message = "proxy-suite: singBox.tun.perApp.routeTable must be greater than zero"; + message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero"; } { condition = perAppRoutingTproxy.enable; value = perAppRoutingTproxy.fwmark; - message = "proxy-suite: singBox.tproxy.perApp.fwmark must be greater than zero"; + message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero"; } { condition = perAppRoutingTproxy.enable; value = perAppRoutingTproxy.routeTable; - message = "proxy-suite: singBox.tproxy.perApp.routeTable must be greater than zero"; + message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero"; } { condition = perAppZapretCfg.enable; @@ -312,19 +328,19 @@ let } ]; - localProxyAuthCfg = singBoxCfg.auth; + localProxyAuthCfg = proxyCfg.auth; localProxyAuthUsed = localProxyAuthCfg.username != null || localProxyAuthCfg.password != null || localProxyAuthCfg.passwordFile != null; localProxyAuthAssertions = [ (mkAssertion ( - !singBoxCfg.enable || !localProxyAuthUsed || localProxyAuthCfg.username != null - ) "proxy-suite: singBox.auth requires username when password or passwordFile is set") - (exactlyOneOf (singBoxCfg.enable && localProxyAuthUsed) [ + !proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null + ) "proxy-suite: proxy.auth requires username when password or passwordFile is set") + (exactlyOneOf (proxyEnabled && localProxyAuthUsed) [ localProxyAuthCfg.password localProxyAuthCfg.passwordFile - ] "proxy-suite: singBox.auth requires exactly one of password or passwordFile") + ] "proxy-suite: proxy.auth requires exactly one of password or passwordFile") ]; forbiddenValueAssertions = @@ -343,25 +359,25 @@ let condition = perAppZapretCfg.enable; value = globalTproxy.fwmark; disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits"; + message = "proxy-suite: proxy.tproxy.fwmark must not use per-app-zapret internal desync mark bits"; } { condition = perAppZapretCfg.enable; value = globalTproxy.proxyMark; disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits"; + message = "proxy-suite: proxy.tproxy.proxyMark must not use per-app-zapret internal desync mark bits"; } { condition = perAppRoutingTun.enable && perAppZapretCfg.enable; value = perAppRoutingTun.fwmark; disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits"; + message = "proxy-suite: proxy.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits"; } { condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable; value = perAppRoutingTproxy.fwmark; disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits"; + message = "proxy-suite: proxy.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits"; } { condition = perAppZapretCfg.enable; @@ -385,19 +401,27 @@ let ]; outboundAssertions = lib.concatMap (ob: [ - (exactlyOneOf singBoxCfg.enable [ + (exactlyOneOf proxyEnabled [ ob.urlFile ob.url + ob.singBoxJson + ob.xrayJson ob.json - ] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json") - ]) singBoxCfg.outbounds; + ] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json") + (mkAssertion (!singBoxEnabled || ob.xrayJson == null) + "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true" + ) + (mkAssertion (!xrayEnabled || (ob.singBoxJson == null && ob.json == null)) + "proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true" + ) + ]) proxyCfg.outbounds; subscriptionAssertions = lib.concatMap (sub: [ - (exactlyOneOf singBoxCfg.enable [ + (exactlyOneOf proxyEnabled [ sub.urlFile sub.url ] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url") - ]) singBoxCfg.subscriptions; + ]) proxyCfg.subscriptions; in featureAssertions ++ perAppRoutingAssertions diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 8f2f55a..cd9f0ec 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -19,6 +19,12 @@ let derived = import ../derived.nix { inherit lib cfg; }; inherit (derived) singBoxCfg + proxyCfg + xrayCfg + proxyEnabled + singBoxEnabled + xrayEnabled + activeBackend perAppRoutingCfg globalTun globalTproxy @@ -39,6 +45,7 @@ let jq = "${pkgs.jq}/bin/jq"; python3 = "${pkgs.python3}/bin/python3"; singBox = "${singBoxCfg.package}/bin/sing-box"; + xray = "${xrayCfg.package}/bin/xray"; grepBin = "${pkgs.gnugrep}/bin/grep"; awk = "${pkgs.gawk}/bin/awk"; sleepBin = "${pkgs.coreutils}/bin/sleep"; @@ -60,6 +67,11 @@ let lib pkgs singBoxCfg + proxyCfg + proxyEnabled + singBoxEnabled + xrayEnabled + activeBackend perAppRoutingCfg userControlCfg perAppRoutingTun @@ -71,6 +83,7 @@ let jq python3 singBox + xray parserScriptsPythonPath buildOutboundPy fetchSubscriptionPy @@ -84,6 +97,7 @@ let pkgs cfg singBoxCfg + proxyCfg perAppRoutingCfg perAppRoutingTun perAppRoutingTproxy @@ -105,13 +119,14 @@ let inherit packages singBoxCfg + proxyCfg perAppRoutingCfg perAppRoutingTun perAppRoutingTproxy perAppZapretCfg selectionMode ; - inherit (scripts) subscriptionTagsFile; + inherit (scripts) subscriptionTagsFile subscriptionCacheDir; inherit (scripts) routeModeStateFile; inherit (perAppRouting) perAppRoutingProfilesFile @@ -124,6 +139,12 @@ in inherit derived singBoxCfg + proxyCfg + xrayCfg + proxyEnabled + singBoxEnabled + xrayEnabled + activeBackend perAppRoutingCfg globalTun globalTproxy diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index b1f64a8..570f2ef 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -2,12 +2,14 @@ { packages, singBoxCfg, + proxyCfg, perAppRoutingCfg, perAppRoutingTun, perAppRoutingTproxy, perAppZapretCfg, selectionMode, subscriptionTagsFile, + subscriptionCacheDir, perAppRoutingProfilesFile, proxychainsConfigFile, proxychainsQuietArg, @@ -19,12 +21,13 @@ selection = selectionMode; inherit subscriptionTagsFile + subscriptionCacheDir perAppRoutingProfilesFile proxychainsConfigFile proxychainsQuietArg routeModeStateFile ; - defaultRouteMode = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist"; + defaultRouteMode = if proxyCfg.proxyByDefault then "blacklist" else "whitelist"; perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0"; perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0"; perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0"; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 9ba6d15..ad185ba 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -1,4 +1,4 @@ -# Assembles all sing-box systemd services from the sub-modules. +# Assembles proxy-suite systemd services from the sub-modules. { config, lib, @@ -55,6 +55,10 @@ let inherit (derived) singBoxCfg + proxyCfg + proxyEnabled + xrayEnabled + activeBackend perAppRoutingCfg globalTun globalTproxy @@ -82,12 +86,34 @@ let }; localProxyAuthEnabled = - singBoxCfg.auth.username != null - && (singBoxCfg.auth.password != null || singBoxCfg.auth.passwordFile != null); + proxyCfg.auth.username != null + && (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null); - # Must match the explicit iproute2_* indexes written to the global TUN - # sing-box template in config.nix. + # Must match the explicit iproute2_* indexes written to the global SingBox TUN + # template in config.nix. XRay uses the same table for manual Linux + # policy routing because XRay's autoSystemRoutingTable is not Linux-ready. tunAutoRouteTableIndex = 2022; + tunAutoRouteRulePriority = 9000; + + xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" '' + set -euo pipefail + + for _ in $(${pkgs.coreutils}/bin/seq 1 50); do + if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then + break + fi + ${pkgs.coreutils}/bin/sleep 0.1 + done + + if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then + echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2 + exit 1 + fi + + while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done + ${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex} + ${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} + ''; tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" '' set -euo pipefail @@ -115,7 +141,7 @@ let tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' set +e - # sing-box normally removes these on graceful shutdown, but stale + # SingBox normally removes these on graceful shutdown, but stale # auto_route/auto_redirect state leaves the host routing through a dead TUN # interface after `proxy-ctl tun off` or an unclean service stop. ${nft} delete table inet sing-box 2>/dev/null || true @@ -130,10 +156,10 @@ let systemServiceEntries = [ { - enable = singBoxCfg.enable; + enable = proxyEnabled; name = serviceNames.socks; value = mkRestartingService { - description = "sing-box proxy client (SOCKS + TProxy-ready)"; + description = "${if xrayEnabled then "XRay" else "sing-box"} proxy client (SOCKS + TProxy-ready)"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; @@ -143,10 +169,10 @@ let }; } { - enable = singBoxCfg.enable && globalTproxy.enable; + enable = proxyEnabled && globalTproxy.enable; name = serviceNames.tproxy; value = mkOneshotService { - description = "sing-box TProxy – nftables rules and policy routing"; + description = "proxy-suite TProxy - nftables rules and policy routing"; after = [ "network.target" "${serviceNames.socks}.service" @@ -162,26 +188,27 @@ let }; } { - enable = singBoxCfg.enable && globalTun.enable; + enable = proxyEnabled && globalTun.enable; name = serviceNames.tun; value = mkRestartingService { - description = "sing-box TUN proxy client"; + description = "${if xrayEnabled then "XRay" else "sing-box"} TUN proxy client"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; conflicts = [ "${serviceNames.tproxy}.service" ]; execStartPre = tunCleanupScript; execStart = scripts.startTun; + execStartPost = if xrayEnabled then xrayTunUpScript else null; execStopPost = tunCleanupScript; runtimeDirectory = serviceNames.tun; stateDirectory = "proxy-suite"; }; } { - enable = singBoxCfg.enable && perAppRoutingTun.enable; + enable = proxyEnabled && perAppRoutingTun.enable; name = serviceNames.perAppTun; value = mkRestartingService { - description = "sing-box per-app-routing TUN backend"; + description = "proxy-suite per-app-routing TUN backend"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; execStartPre = perAppRouting.perAppTunDownScript; @@ -193,7 +220,7 @@ let }; } { - enable = singBoxCfg.enable && perAppRoutingTun.enable; + enable = proxyEnabled && perAppRoutingTun.enable; name = "${serviceNames.perAppTun}-user@"; value = mkUserRuleService { description = "Enable proxy-suite app TUN marking for user %i"; @@ -203,7 +230,7 @@ let }; } { - enable = singBoxCfg.enable && perAppRoutingTproxy.enable; + enable = proxyEnabled && perAppRoutingTproxy.enable; name = serviceNames.perAppTproxy; value = mkOneshotService { description = "proxy-suite per-app-routing TProxy backend"; @@ -221,7 +248,7 @@ let }; } { - enable = singBoxCfg.enable && perAppRoutingTproxy.enable; + enable = proxyEnabled && perAppRoutingTproxy.enable; name = "${serviceNames.perAppTproxy}-user@"; value = mkUserRuleService { description = "Enable proxy-suite app TProxy marking for user %i"; @@ -241,7 +268,7 @@ let }; } { - enable = singBoxCfg.enable && hasSubscriptions; + enable = proxyEnabled && hasSubscriptions; name = serviceNames.subscriptionUpdate; value = mkOneshotService { description = "Refresh proxy-suite subscription caches"; @@ -252,7 +279,7 @@ let }; } { - enable = singBoxCfg.enable; + enable = proxyEnabled; name = "proxy-suite-route-mode@"; value = mkOneshotService { description = "Set proxy-suite route mode to %i"; @@ -282,14 +309,14 @@ let timerEntries = [ { - enable = singBoxCfg.enable && hasSubscriptions; + enable = proxyEnabled && hasSubscriptions; name = serviceNames.subscriptionUpdate; value = { description = "Periodic proxy-suite subscription refresh"; wantedBy = [ "timers.target" ]; timerConfig = { OnBootSec = "5m"; - OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval; + OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval; }; }; } @@ -299,7 +326,7 @@ in environment.systemPackages = [ control.proxyCtl ]; # nftables must be on for transparent routing backends. Global TUN uses - # sing-box auto_redirect, which programs an `inet sing-box` nftables table. + # SingBox auto_redirect programs an `inet sing-box` nftables table. networking.nftables.enable = lib.mkIf ( globalTun.enable || globalTproxy.enable diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index c78b928..6eacd7a 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -4,6 +4,7 @@ pkgs, cfg, singBoxCfg, + proxyCfg, perAppRoutingCfg, perAppRoutingTun, perAppRoutingTproxy, @@ -62,7 +63,7 @@ let profile: !(builtins.elem profile.name perAppRoutingProfileNames) ) defaultPerAppRoutingProfiles; effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles; - localProxyAuth = singBoxCfg.auth; + localProxyAuth = proxyCfg.auth; localProxyAuthEnabled = localProxyAuth.username != null && (localProxyAuth.password != null || localProxyAuth.passwordFile != null); @@ -83,7 +84,7 @@ let tcp_connect_time_out 8000 [ProxyList] - socks5 ${singBoxCfg.listenAddress} ${toString singBoxCfg.port} + socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port} ''; proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q "; diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 08e7718..edb9754 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -1,8 +1,13 @@ -# Generates the sing-box startup scripts and subscription management scripts. +# Generates proxy backend startup scripts and subscription management scripts. { lib, pkgs, singBoxCfg, + proxyCfg, + proxyEnabled, + singBoxEnabled, + xrayEnabled, + activeBackend, perAppRoutingCfg, userControlCfg, perAppRoutingTun, @@ -12,6 +17,7 @@ jq, python3, singBox, + xray, parserScriptsPythonPath, buildOutboundPy, fetchSubscriptionPy, @@ -22,9 +28,12 @@ }: let - globalTproxy = singBoxCfg.tproxy; + globalTproxy = proxyCfg.tproxy; systemctl = "${pkgs.systemd}/bin/systemctl"; - localProxyAuth = singBoxCfg.auth; + backend = if activeBackend == null then "sing-box" else activeBackend; + backendArg = "--backend ${backend}"; + backendBin = if xrayEnabled then xray else singBox; + localProxyAuth = proxyCfg.auth; localProxyAuthEnabled = localProxyAuth.username != null && (localProxyAuth.password != null || localProxyAuth.passwordFile != null); @@ -35,7 +44,7 @@ let pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password else null; - subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions"; + subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}"; routeModeStateFile = "/run/proxy-suite/route-mode"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; @@ -55,7 +64,7 @@ let in '' printf '%s' "$(cat "${urlSource}")" \ - | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} + | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${backendArg} --tag-prefix ${lib.escapeShellArg sub.tag} ''; subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions '' @@ -83,23 +92,53 @@ let } ''; - # Build the shell code block for a single outbound entry. - # tag overrides ob.tag (used in "first" mode to force tag = "proxy"). - # routingMark is null or an int; added to outbound JSON if set. + routingMarkJq = + routingMark: + if routingMark == null then + "" + else if xrayEnabled then + " | .streamSettings.sockopt.mark = ${toString routingMark}" + else + " | .routing_mark = ${toString routingMark}"; + + rawOutboundJson = + ob: tag: routingMark: + let + backendRaw = + if xrayEnabled then + ob.xrayJson + else if ob.singBoxJson != null then + ob.singBoxJson + else + ob.json; + markAttrs = + if routingMark == null then + { } + else if xrayEnabled then + { streamSettings.sockopt.mark = routingMark; } + else + { routing_mark = routingMark; }; + in + backendRaw // { inherit tag; } // markAttrs; + mkOutboundBlock = ob: routingMark: tag: let - markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"; + backendRaw = + if xrayEnabled then + ob.xrayJson + else if ob.singBoxJson != null then + ob.singBoxJson + else + ob.json; in - if ob.json != null then + if backendRaw != null then let - outboundJson = builtins.toJSON ( - ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; } - ); + outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark); jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson; in '' - # outbound: ${tag} (static json) + # outbound: ${tag} (static ${backend} json) OB_JSON=$(cat "${jsonFile}") OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") '' @@ -109,23 +148,20 @@ let if ob.urlFile != null then ob.urlFile else - # Literal URL – write to nix store so the script can cat it. - # Less secret than urlFile, but convenient for non-sensitive configs. pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url; in '' # outbound: ${tag} URL=$(cat "${urlSource}") - OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --tag ${lib.escapeShellArg tag}${markArg}) + OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"}) OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") ''; - # Build the shell code block for a single subscription entry. - # Fetches subscription into the cache on first run; subsequent starts use the cache. mkSubscriptionBlock = sub: routingMark: let cacheFile = mkSubscriptionCacheFile sub; + markFilter = routingMarkJq routingMark; in '' # subscription: ${sub.tag} @@ -143,28 +179,28 @@ let fi if [ -f "$CACHE_FILE" ]; then SUB_JSON=$(cat "$CACHE_FILE") - ${ - lib.optionalString (routingMark != null) '' - SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON") - '' - }OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") + ${lib.optionalString (routingMark != null) '' + SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON") + ''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") fi ''; - # Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper. + xrayUrltestTagFilter = '' + OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON") + ''; + mkOutboundScript = routingMark: let outboundBlocks = - if collapseNamedOutbounds && singBoxCfg.outbounds != [ ] then - # Only the first static outbound, tagged "proxy" so sing-box routes to it. - mkOutboundBlock (builtins.head singBoxCfg.outbounds) routingMark "proxy" + if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then + mkOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy" else - lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds; + lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds; subscriptionBlocks = lib.concatMapStrings ( sub: mkSubscriptionBlock sub routingMark - ) singBoxCfg.subscriptions; + ) proxyCfg.subscriptions; requireOutboundsBlock = '' if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then @@ -174,10 +210,10 @@ let ''; wrapperBlock = - if collapseNamedOutbounds then - # When there are no static outbounds, subscription outbounds keep their - # real tags. Rename the first one to "proxy" so routing rules resolve. - lib.optionalString (singBoxCfg.outbounds == [ ] && singBoxCfg.subscriptions != [ ]) '' + if xrayEnabled && selectionMode == "urltest" then + xrayUrltestTagFilter + else if collapseNamedOutbounds then + lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) '' FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON") if [ -n "$FIRST_TAG" ]; then OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \ @@ -195,13 +231,12 @@ let OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") '' else - # urltest '' TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") WRAPPER=$(${jq} -n \ --argjson tags "$TAGS" \ - --arg url ${lib.escapeShellArg singBoxCfg.urlTest.url} \ - --arg interval ${lib.escapeShellArg singBoxCfg.urlTest.interval} \ + --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ + --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \ --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ '{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}') OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") @@ -218,8 +253,8 @@ let printf '%s\n' 'tcp_connect_time_out 8000' printf '\n%s\n' '[ProxyList]' printf 'socks5 %s %s %s %s\n' \ - ${lib.escapeShellArg singBoxCfg.listenAddress} \ - ${lib.escapeShellArg (toString singBoxCfg.port)} \ + ${lib.escapeShellArg proxyCfg.listenAddress} \ + ${lib.escapeShellArg (toString proxyCfg.port)} \ ${lib.escapeShellArg localProxyAuth.username} \ "$LOCAL_PROXY_PASSWORD" } > "${runtimeProxychainsConfig}" @@ -227,8 +262,6 @@ let chmod 640 "${runtimeProxychainsConfig}" ''; - modeBaseline = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist"; - restartActiveConfigConsumersBlock = lib.concatMapStrings (svc: '' if ${systemctl} is-active --quiet ${svc}; then ${systemctl} restart ${svc} @@ -239,6 +272,103 @@ let "proxy-suite-per-app-tun" ]; + routeModeCaseBlock = '' + if [ -r "$ROUTE_MODE_STATE_FILE" ]; then + ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)" + fi + case "$ROUTE_MODE" in + blacklist) + ROUTE_FINAL="proxy" + DNS_FINAL="remote" + ROUTE_MODE_ACTIVE=true + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(.entries) | add // []) + + .proxyPrimary + + .direct + + .safetyDirect + + .block + + .proxyGeo + ' "${routeModeRulesFile}") + ;; + whitelist) + ROUTE_FINAL="direct" + DNS_FINAL="local" + ROUTE_MODE_ACTIVE=true + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(.entries) | add // []) + + .proxyPrimary + + .direct + + .safetyDirect + + .block + + .proxyGeo + ' "${routeModeRulesFile}") + ;; + all-proxy) + ROUTE_FINAL="proxy" + DNS_FINAL="remote" + ROUTE_MODE_ACTIVE=true + CLEAR_DNS_RULES=true + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) + + .proxyPrimary + + .safetyDirect + + .block + + .proxyGeo + ' "${routeModeRulesFile}") + ;; + all-bypass) + ROUTE_FINAL="direct" + DNS_FINAL="local" + ROUTE_MODE_ACTIVE=true + CLEAR_DNS_RULES=true + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(select(.category == "block") | .entries) | add // []) + + .safetyDirect + + .block + ' "${routeModeRulesFile}") + ;; + *) + ROUTE_MODE="" + ;; + esac + ''; + + mkBackendJqFilter = + if xrayEnabled then + '' + def xray_final_rule($tag): + if $tag == "proxy" and "${selectionMode}" == "urltest" then + {type:"field",network:"tcp,udp",balancerTag:"proxy"} + else + {type:"field",network:"tcp,udp",outboundTag:$tag} + end; + .outbounds = $obs + .outbounds + | if $auth_enabled then + (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password" + | (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.users) = [{user:$user,pass:$password}] + else . end + | if $route_enabled then + .routing.rules = ($route_rules + [xray_final_rule($route_final)]) + else . end + '' + else + '' + .outbounds = $obs + .outbounds + | if $auth_enabled then + (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] + else . end + | if $route_enabled then + .route.rules = $route_rules + | .route.final = $route_final + | .dns.final = $dns_final + | if $clear_dns_rules then .dns.rules = [] else . end + else . end + ''; + mkStartScript = { name, @@ -266,68 +396,7 @@ let ${writeProxychainsConfigBlock} ''} - if [ -r "$ROUTE_MODE_STATE_FILE" ]; then - ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)" - fi - case "$ROUTE_MODE" in - blacklist) - ROUTE_FINAL="proxy" - DNS_FINAL="remote" - ROUTE_MODE_ACTIVE=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(.entries) | add // []) - + .proxyPrimary - + .direct - + .safetyDirect - + .block - + .proxyGeo - ' "${routeModeRulesFile}") - ;; - whitelist) - ROUTE_FINAL="direct" - DNS_FINAL="local" - ROUTE_MODE_ACTIVE=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(.entries) | add // []) - + .proxyPrimary - + .direct - + .safetyDirect - + .block - + .proxyGeo - ' "${routeModeRulesFile}") - ;; - all-proxy) - ROUTE_FINAL="proxy" - DNS_FINAL="remote" - ROUTE_MODE_ACTIVE=true - CLEAR_DNS_RULES=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) - + .proxyPrimary - + .safetyDirect - + .block - + .proxyGeo - ' "${routeModeRulesFile}") - ;; - all-bypass) - ROUTE_FINAL="direct" - DNS_FINAL="local" - ROUTE_MODE_ACTIVE=true - CLEAR_DNS_RULES=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(select(.category == "block") | .entries) | add // []) - + .safetyDirect - + .block - ' "${routeModeRulesFile}") - ;; - *) - ROUTE_MODE="" - ;; - esac + ${routeModeCaseBlock} ${mkOutboundScript routingMark} @@ -341,22 +410,13 @@ let --arg route_final "$ROUTE_FINAL" \ --arg dns_final "$DNS_FINAL" \ --argjson clear_dns_rules "$CLEAR_DNS_RULES" \ - '.outbounds = $obs + .outbounds - | if $auth_enabled then - (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] - else . end - | if $route_enabled then - .route.rules = $route_rules - | .route.final = $route_final - | .dns.final = $dns_final - | if $clear_dns_rules then .dns.rules = [] else . end - else . end' \ + '${mkBackendJqFilter}' \ "${configFile}" > "$RUNTIME_DIR/config.json" ${lib.optionalString enableLocalProxyAuth '' chmod 600 "$RUNTIME_DIR/config.json" ''} - exec ${singBox} run -c "$RUNTIME_DIR/config.json" + exec ${backendBin} run -c "$RUNTIME_DIR/config.json" ''; startSocks = mkStartScript { @@ -371,19 +431,16 @@ let name = "proxy-suite-start-tun"; runtimeDir = "/run/proxy-suite-tun"; configFile = tunFile; - routingMark = null; + routingMark = if xrayEnabled then globalTproxy.proxyMark else null; }; startPerAppTun = mkStartScript { name = "proxy-suite-start-per-app-tun"; runtimeDir = "/run/proxy-suite-per-app-tun"; configFile = perAppTunFile; - # Only needed when TProxy mode is enabled; otherwise avoid tagging app TUN - # proxy outbounds with a host-global mark. routingMark = if globalTproxy.enable then globalTproxy.proxyMark else null; }; - # Shell code to fetch a single subscription into the cache (used in update service). mkSubscriptionFetchBlock = sub: let @@ -409,7 +466,7 @@ let mkdir -p "$CACHE_DIR" FAILED=0 ${subscriptionCacheHelpersBlock} - ${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions} + ${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions} if [ "$FAILED" -eq 0 ]; then ${restartActiveConfigConsumersBlock} @@ -449,7 +506,7 @@ let ''; subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( - builtins.toJSON (map (sub: sub.tag) singBoxCfg.subscriptions) + builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions) ); in { @@ -460,6 +517,7 @@ in subscriptionUpdateScript hasSubscriptions subscriptionTagsFile + subscriptionCacheDir runtimeProxychainsConfig ; } diff --git a/modules/proxy-suite/tg-ws-proxy.nix b/modules/proxy-suite/tg-ws-proxy.nix index 5569156..106d48e 100644 --- a/modules/proxy-suite/tg-ws-proxy.nix +++ b/modules/proxy-suite/tg-ws-proxy.nix @@ -13,8 +13,8 @@ let transparentBypassEnabled = t.bypassTransparentProxy - && cfg.singBox.enable - && (cfg.singBox.tun.enable || cfg.singBox.tproxy.enable); + && cfg.proxy.enable + && (cfg.proxy.tun.enable || cfg.proxy.tproxy.enable); bypassRulePriority = 8999; dcArgs = lib.concatMapStrings diff --git a/nix/checks.nix b/nix/checks.nix index b9070f1..70d7227 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -163,12 +163,16 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox.outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; }; }; mkFixture = proxySuiteConfig: evalProxySuite [ @@ -206,7 +210,7 @@ let customSingBoxPackageFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.package = customSingBoxPackage; + services.proxy-suite.proxy.singBox.package = customSingBoxPackage; } ]; customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box"; @@ -214,10 +218,145 @@ let customSingBoxPackageFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); + xrayModule = { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + selection = "urltest"; + outbounds = [ + { + tag = "primary"; + url = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"; + routing.domains = [ "specific.example" ]; + } + ]; + routing = { + proxy.domains = [ "proxy.example" ]; + direct = { + domains = [ "direct.example" ]; + geosites = [ "category-ru" ]; + }; + block.domains = [ "block.example" ]; + }; + tproxy.enable = true; + tun = { + enable = true; + perApp.enable = true; + }; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + }; + }; + xrayFixture = evalProxySuite [ xrayModule ]; + xrayTproxyConfig = mkTProxyConfig xrayFixture; + xrayTunConfig = mkTunConfig xrayFixture; + xrayPerAppTunConfig = mkPerAppTunConfig xrayFixture; + xrayStartScript = builtins.readFile ( + xrayFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + xraySubscriptionFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + subscriptions = [ { tag = "xray-sub"; url = "https://example.com/xray-sub"; } ]; + }; + }; + } + ]; + xraySubscriptionStartScript = builtins.readFile ( + xraySubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + xrayBothBackends = mkBadFixtureRaw [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + xray.enable = true; + outbounds = [ { tag = "primary"; url = "http://proxy.example.com:8080"; } ]; + }; + }; + } + ]; + proxyEnabledNoBackend = mkBadFixtureRaw [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "primary"; url = "http://proxy.example.com:8080"; } ]; + }; + }; + } + ]; + xraySelectorUnavailable = mkBadFixtureRaw [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + selection = "selector"; + outbounds = [ { tag = "primary"; url = "http://proxy.example.com:8080"; } ]; + }; + }; + } + ]; + xraySingBoxJsonUnavailable = mkBadFixtureRaw [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + outbounds = [ + { + tag = "raw"; + singBoxJson = { type = "direct"; }; + } + ]; + }; + }; + } + ]; + singBoxXrayJsonUnavailable = mkBadFixtureRaw [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "raw"; + xrayJson = { protocol = "freedom"; settings = { }; }; + } + ]; + }; + }; + } + ]; + routeModeFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.routing = { + services.proxy-suite.proxy.routing = { proxy = { domains = [ "proxy.example" ]; geosites = [ "google" ]; @@ -262,7 +401,7 @@ let baseModule { services.proxy-suite = { - singBox.tun.enable = true; + proxy.tun.enable = true; tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; @@ -280,7 +419,7 @@ let baseModule { services.proxy-suite = { - singBox.tproxy.enable = true; + proxy.tproxy.enable = true; tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; @@ -293,7 +432,7 @@ let tgRoutingMarkCollision = mkBadFixture [ { services.proxy-suite = { - singBox.tproxy.enable = true; + proxy.tproxy.enable = true; tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; @@ -306,24 +445,34 @@ let duplicateTags = forceEval ( (mkFixture { enable = true; - singBox.outbounds = [ - { tag = "dup"; url = "http://one.example.com:8080"; } - { tag = "dup"; url = "http://two.example.com:8080"; } - ]; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { tag = "dup"; url = "http://one.example.com:8080"; } + { tag = "dup"; url = "http://two.example.com:8080"; } + ]; + }; }).config.system.build.toplevel.drvPath ); reservedTag = forceEval ( (mkFixture { enable = true; - singBox.outbounds = [ { tag = "proxy"; url = "http://proxy.example.com:8080"; } ]; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ { tag = "proxy"; url = "http://proxy.example.com:8080"; } ]; + }; }).config.system.build.toplevel.drvPath ); unknownRoutingTarget = forceEval ( (mkFixture { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; outbounds = [ { tag = "primary"; url = "http://proxy.example.com:8080"; } ]; routing.rules = [ { outbound = "missing"; domains = [ "example.com" ]; } ]; }; @@ -336,7 +485,9 @@ let networking.firewall.enable = true; services.proxy-suite = { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; tproxy.enable = true; outbounds = [ { @@ -352,7 +503,7 @@ let tproxyManualFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.tproxy.enable = true; + services.proxy-suite.proxy.tproxy.enable = true; } ]; tproxyManualServiceConfig = tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig; @@ -362,7 +513,7 @@ let tproxyAutostartFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.tproxy = { + services.proxy-suite.proxy.tproxy = { enable = true; autostart = true; }; @@ -372,14 +523,14 @@ let tunManualFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.tun.enable = true; + services.proxy-suite.proxy.tun.enable = true; } ]; tunAutostartFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.tun = { + services.proxy-suite.proxy.tun = { enable = true; autostart = true; }; @@ -388,19 +539,19 @@ let conflictingAutostartModes = mkBadFixture [ { - services.proxy-suite.singBox = { + services.proxy-suite.proxy = { tproxy = { enable = true; autostart = true; }; tun = { enable = true; autostart = true; }; }; } ]; - globalTunWithoutSingBox = mkBadFixture [ - { services.proxy-suite.singBox = { enable = false; tun.enable = true; }; } + globalTunWithoutProxy = mkBadFixture [ + { services.proxy-suite.proxy = { enable = false; tun.enable = true; }; } ]; - globalTproxyWithoutSingBox = mkBadFixture [ - { services.proxy-suite.singBox = { enable = false; tproxy.enable = true; }; } + globalTproxyWithoutProxy = mkBadFixture [ + { services.proxy-suite.proxy = { enable = false; tproxy.enable = true; }; } ]; routingOrFixture = evalProxySuite [ @@ -408,7 +559,9 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; outbounds = [ { tag = "primary"; @@ -433,7 +586,7 @@ let ruDisabledFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.routing.enableRuDirect = false; + services.proxy-suite.proxy.routing.enableRuDirect = false; } ]; ruDisabledRules = mkRoutingRules ruDisabledFixture; @@ -442,7 +595,7 @@ let ruExplicitFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.routing = { + services.proxy-suite.proxy.routing = { enableRuDirect = false; direct.geosites = [ "category-ru" ]; }; @@ -453,7 +606,7 @@ let dnsLocalOverrideFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.dns.local = { + services.proxy-suite.proxy.dns.local = { type = "tcp"; address = "9.9.9.9"; port = 5353; @@ -465,7 +618,7 @@ let dnsRemoteOverrideFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.dns.remote = { + services.proxy-suite.proxy.dns.remote = { type = "tls"; address = "1.0.0.1"; port = 853; @@ -672,7 +825,7 @@ let proxyDirectFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.proxyByDefault = false; + services.proxy-suite.proxy.proxyByDefault = false; } ]; proxyDirectConfig = mkTProxyConfig proxyDirectFixture; @@ -703,12 +856,16 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox.subscriptions = [ - { - tag = "community"; - url = "https://example.com/sub/token"; - } - ]; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { + tag = "community"; + url = "https://example.com/sub/token"; + } + ]; + }; }; } ]; @@ -736,7 +893,9 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; outbounds = [ { tag = "own-vps"; @@ -760,10 +919,14 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox.subscriptions = [ - { tag = "dup"; url = "https://example.com/sub/one"; } - { tag = "dup"; url = "https://example.com/sub/two"; } - ]; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { tag = "dup"; url = "https://example.com/sub/one"; } + { tag = "dup"; url = "https://example.com/sub/two"; } + ]; + }; }; } ]; @@ -773,7 +936,11 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox.subscriptions = [ { tag = "bad/tag"; url = "https://example.com/sub/token"; } ]; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ { tag = "bad/tag"; url = "https://example.com/sub/token"; } ]; + }; }; } ]; @@ -785,7 +952,9 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; subscriptions = [ { tag = "community"; @@ -802,7 +971,9 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; subscriptions = [ { tag = "community"; @@ -825,12 +996,16 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox.subscriptions = [ - { - tag = "private"; - urlFile = "/run/secrets/sub-url"; - } - ]; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { + tag = "private"; + urlFile = "/run/secrets/sub-url"; + } + ]; + }; }; } ]; @@ -840,7 +1015,9 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox = { + proxy = { + enable = true; + singBox.enable = true; outbounds = [ { tag = "test-proxy"; @@ -851,8 +1028,8 @@ let urlTest = { url = "https://telegram.org"; interval = "1m"; - tolerance = 100; }; + singBox.urlTest.tolerance = 100; }; }; } @@ -888,7 +1065,7 @@ let localProxyAuthFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.auth = { + services.proxy-suite.proxy.auth = { username = "local-user"; password = "local-pass"; }; @@ -902,7 +1079,7 @@ let baseModule { services.proxy-suite = { - singBox.auth = { + proxy.auth = { username = "local-user"; passwordFile = "/run/secrets/local-proxy-password"; }; @@ -941,7 +1118,7 @@ let baseModule { services.proxy-suite = { - singBox = { + proxy = { tun.perApp.enable = true; tproxy.perApp.enable = true; }; @@ -971,7 +1148,7 @@ let baseModule { services.proxy-suite = { - singBox.tun.perApp.enable = true; + proxy.tun.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; @@ -999,7 +1176,7 @@ let baseModule { services.proxy-suite = { - singBox = { + proxy = { tproxy.enable = true; tun.perApp.enable = true; }; @@ -1029,7 +1206,7 @@ let baseModule { services.proxy-suite = { - singBox.tproxy.perApp.enable = true; + proxy.tproxy.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; @@ -1059,46 +1236,46 @@ let } ]; - perAppRoutingProxychainsWithoutSingBox = mkBadFixture [ + perAppRoutingProxychainsWithoutProxy = mkBadFixture [ { services.proxy-suite = { - singBox.enable = false; + proxy.enable = false; perAppRouting = { enable = true; proxychains.enable = true; }; }; } ]; - perAppRoutingTunBackendWithoutSingBox = mkBadFixture [ + perAppRoutingTunBackendWithoutProxy = mkBadFixture [ { services.proxy-suite = { - singBox = { enable = false; tun.perApp.enable = true; }; + proxy = { enable = false; tun.perApp.enable = true; }; perAppRouting.enable = true; }; } ]; - perAppRoutingTproxyBackendWithoutSingBox = mkBadFixture [ + perAppRoutingTproxyBackendWithoutProxy = mkBadFixture [ { services.proxy-suite = { - singBox = { enable = false; tproxy.perApp.enable = true; }; + proxy = { enable = false; tproxy.perApp.enable = true; }; perAppRouting.enable = true; }; } ]; - perAppRoutingTunProfileWithoutSingBox = mkBadFixture [ + perAppRoutingTunProfileWithoutProxy = mkBadFixture [ { services.proxy-suite = { - singBox.enable = false; + proxy.enable = false; perAppRouting = { enable = true; profiles = [ { name = "game"; route = "tun"; } ]; }; }; } ]; - perAppRoutingTproxyProfileWithoutSingBox = mkBadFixture [ + perAppRoutingTproxyProfileWithoutProxy = mkBadFixture [ { services.proxy-suite = { - singBox.enable = false; + proxy.enable = false; perAppRouting = { enable = true; profiles = [ { name = "browser"; route = "tproxy"; } ]; }; }; } @@ -1179,7 +1356,7 @@ let baseModule { services.proxy-suite = { - singBox.tun.perApp.enable = true; + proxy.tun.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; @@ -1237,7 +1414,7 @@ let perAppRoutingTunFwmarkCollision = mkBadFixture [ { services.proxy-suite = { - singBox = { + proxy = { tproxy = { enable = true; proxyMark = 16; }; tun.perApp = { enable = true; fwmark = 16; }; }; @@ -1249,7 +1426,7 @@ let perAppRoutingTproxyFwmarkCollision = mkBadFixture [ { services.proxy-suite = { - singBox.tproxy = { proxyMark = 17; perApp = { enable = true; fwmark = 17; }; }; + proxy.tproxy = { proxyMark = 17; perApp = { enable = true; fwmark = 17; }; }; perAppRouting.enable = true; }; } @@ -1258,7 +1435,7 @@ let perAppRoutingTunTproxyFwmarkCollision = mkBadFixture [ { services.proxy-suite = { - singBox = { + proxy = { tun.perApp = { enable = true; fwmark = 23; }; tproxy.perApp = { enable = true; fwmark = 23; }; }; @@ -1270,7 +1447,7 @@ let perAppRoutingTunTproxyRouteTableCollision = mkBadFixture [ { services.proxy-suite = { - singBox = { + proxy = { tun.perApp = { enable = true; routeTable = 123; }; tproxy.perApp = { enable = true; routeTable = 123; }; }; @@ -1283,7 +1460,7 @@ let { services.proxy-suite = { zapret = { enable = true; perApp = { enable = true; filterMark = 268435456; }; }; - singBox.tproxy.proxyMark = 268435456; + proxy.tproxy.proxyMark = 268435456; perAppRouting.enable = true; }; } @@ -1293,7 +1470,7 @@ let { services.proxy-suite = { zapret = { enable = true; perApp = { enable = true; filterMark = 23; }; }; - singBox.tproxy.perApp = { enable = true; fwmark = 23; }; + proxy.tproxy.perApp = { enable = true; fwmark = 23; }; perAppRouting.enable = true; }; } @@ -1305,9 +1482,13 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - singBox.subscriptions = [ - { tag = "bad"; url = "https://example.com/sub/token"; urlFile = "/run/secrets/sub-url"; } - ]; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { tag = "bad"; url = "https://example.com/sub/token"; urlFile = "/run/secrets/sub-url"; } + ]; + }; }; } ]; @@ -1315,21 +1496,28 @@ let subscriptionNoSources = mkBadFixtureRaw [ { system.stateVersion = "26.05"; - services.proxy-suite = { enable = true; singBox.subscriptions = [ { tag = "bad"; } ]; }; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ { tag = "bad"; } ]; + }; + }; } ]; localProxyAuthNoPassword = mkBadFixture [ - { services.proxy-suite.singBox.auth.username = "local-user"; } + { services.proxy-suite.proxy.auth.username = "local-user"; } ]; localProxyAuthNoUsername = mkBadFixture [ - { services.proxy-suite.singBox.auth.password = "local-pass"; } + { services.proxy-suite.proxy.auth.password = "local-pass"; } ]; localProxyAuthBothPasswordSources = mkBadFixture [ { - services.proxy-suite.singBox.auth = { + services.proxy-suite.proxy.auth = { username = "local-user"; password = "local-pass"; passwordFile = "/run/secrets/local-proxy-password"; @@ -1337,14 +1525,30 @@ let } ]; + noProxyBackendDefaultFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite.enable = true; + } + ]; + noOutboundsNoSubscriptions = mkBadFixtureRaw [ - { system.stateVersion = "26.05"; services.proxy-suite.enable = true; } + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + }; + }; + } ]; blockGeoFixture = evalProxySuite [ baseModule { - services.proxy-suite.singBox.routing.block = { + services.proxy-suite.proxy.routing.block = { geosites = [ "category-ads-all" ]; geoips = [ "cn" ]; }; @@ -1364,10 +1568,10 @@ let validated = builtins.all (x: x) [ ( - assert minimal.config.services.proxy-suite.singBox.listenAddress == "127.0.0.1"; + assert minimal.config.services.proxy-suite.proxy.listenAddress == "127.0.0.1"; true ) - # -- singBox.auth: default mixed inbound stays unauthenticated -- + # -- proxy.auth: default mixed inbound stays unauthenticated -- ( let mixedInbound = builtins.head ( @@ -1377,7 +1581,7 @@ let assert !(mixedInbound ? users); true ) - # -- singBox.auth: authenticated mixed inbound is injected at runtime -- + # -- proxy.auth: authenticated mixed inbound is injected at runtime -- ( assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript; assert pkgs.lib.hasInfix ''--arg user local-user'' localProxyAuthStartScript; @@ -1386,7 +1590,7 @@ let assert pkgs.lib.hasInfix ''chmod 600 "$RUNTIME_DIR/config.json"'' localProxyAuthStartScript; true ) - # -- singBox.auth: passwordFile is read from runtime path and proxychains uses runtime config -- + # -- proxy.auth: passwordFile is read from runtime path and proxychains uses runtime config -- ( assert pkgs.lib.hasInfix ''/run/secrets/local-proxy-password'' localProxyAuthPasswordFileStartScript; assert pkgs.lib.hasInfix ''/run/proxy-suite-socks/proxychains.conf'' localProxyAuthPasswordFileStartScript; @@ -1398,7 +1602,7 @@ let assert pkgs.lib.hasInfix "Proxychains config is not readable" localProxyAuthPasswordFileScript; true ) - # -- singBox.auth: incomplete or conflicting auth config fails -- + # -- proxy.auth: incomplete or conflicting auth config fails -- ( assert localProxyAuthNoPassword.success == false; assert localProxyAuthNoUsername.success == false; @@ -1448,6 +1652,74 @@ let assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript; true ) + # -- xray backend: same service surface, XRay config shape, and urltest balancer -- + ( + let + socksInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "mixed-in") xrayTproxyConfig.inbounds + ); + tproxyInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "tproxy-in") xrayTproxyConfig.inbounds + ); + specificRule = builtins.head ( + builtins.filter ( + rule: (rule ? domain) && builtins.elem "domain:specific.example" rule.domain + ) xrayTproxyConfig.routing.rules + ); + balancer = builtins.head xrayTproxyConfig.routing.balancers; + in + assert xrayFixture.config.services.proxy-suite.proxy.xray.enable; + assert xrayFixture.config.systemd.services ? "proxy-suite-socks"; + assert xrayFixture.config.systemd.services ? "proxy-suite-tproxy"; + assert xrayFixture.config.systemd.services ? "proxy-suite-tun"; + assert xrayFixture.config.systemd.services ? "proxy-suite-per-app-tun"; + assert pkgs.lib.hasInfix "/bin/xray run -c" xrayStartScript; + assert pkgs.lib.hasInfix "--backend xray" xrayStartScript; + assert socksInbound.protocol == "socks"; + assert socksInbound.settings.auth == "noauth"; + assert socksInbound.settings.udp == true; + assert tproxyInbound.protocol == "tunnel"; + assert tproxyInbound.settings.followRedirect == true; + assert tproxyInbound.streamSettings.sockopt.tproxy == "tproxy"; + assert specificRule.outboundTag == "proxy-suite-ob-primary"; + assert balancer.tag == "proxy"; + assert balancer.selector == [ "proxy-suite-ob-" ]; + assert balancer.strategy.type == "leastPing"; + assert xrayTproxyConfig.observatory.subjectSelector == [ "proxy-suite-ob-" ]; + assert xrayTproxyConfig.observatory.probeUrl == "https://www.gstatic.com/generate_204"; + true + ) + ( + let + tunInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "tun-in") xrayTunConfig.inbounds + ); + perAppTunInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "tun-in") xrayPerAppTunConfig.inbounds + ); + in + assert tunInbound.protocol == "tun"; + assert tunInbound.settings.name == "singtun0"; + assert tunInbound.settings.gateway == [ "172.19.0.1/30" ]; + assert tunInbound.settings.autoOutboundsInterface == "auto"; + assert perAppTunInbound.settings.name == "psperapptun0"; + assert perAppTunInbound.settings.gateway == [ "172.20.0.1/30" ]; + true + ) + ( + assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/xray/xray-sub.json"'' xraySubscriptionStartScript; + assert pkgs.lib.hasInfix "--backend xray" xraySubscriptionStartScript; + true + ) + # -- backend selection and backend-specific raw JSON options are enforced -- + ( + assert xrayBothBackends.success == false; + assert proxyEnabledNoBackend.success == false; + assert xraySelectorUnavailable.success == false; + assert xraySingBoxJsonUnavailable.success == false; + assert singBoxXrayJsonUnavailable.success == false; + true + ) ( assert duplicateTags.success == false; true @@ -1477,7 +1749,7 @@ let true ) ( - assert tproxyManualFixture.config.services.proxy-suite.singBox.tproxy.autostart == false; + assert tproxyManualFixture.config.services.proxy-suite.proxy.tproxy.autostart == false; assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ]; true ) @@ -1496,7 +1768,7 @@ let true ) ( - assert tunManualFixture.config.services.proxy-suite.singBox.tun.autostart == false; + assert tunManualFixture.config.services.proxy-suite.proxy.tun.autostart == false; assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ]; true ) @@ -1533,8 +1805,8 @@ let true ) ( - assert globalTunWithoutSingBox.success == false; - assert globalTproxyWithoutSingBox.success == false; + assert globalTunWithoutProxy.success == false; + assert globalTproxyWithoutProxy.success == false; true ) ( @@ -1755,7 +2027,7 @@ let # -- subscription: basic config is accepted -- ( - assert subscriptionOnlyFixture.config.services.proxy-suite.singBox.subscriptions != [ ]; + assert subscriptionOnlyFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; true ) @@ -1842,8 +2114,8 @@ let # -- subscription/runtime: generated cache paths use the raw validated tag, not shell-escaped quotes -- ( - assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/community.json"'' subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix ''/var/lib/proxy-suite/subscriptions/community.json.tmp'' subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/sing-box/community.json"'' subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix ''/var/lib/proxy-suite/subscriptions/sing-box/community.json.tmp'' subscriptionOnlyUpdateScript; assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyStartScript); assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyUpdateScript); true @@ -1887,7 +2159,7 @@ let # -- subscription: urlFile form accepted -- ( - assert subscriptionUrlFileFixture.config.services.proxy-suite.singBox.subscriptions != [ ]; + assert subscriptionUrlFileFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; true ) @@ -2005,8 +2277,8 @@ let ( assert pkgs.lib.hasInfix "help)" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "show this help message" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "enable/disable the sing-box proxy stack" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "restart active sing-box services" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "enable/disable the proxy backend stack" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "restart active global proxy-suite services" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "wrap -- " perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript; true @@ -2104,7 +2376,7 @@ let # -- perAppRouting: app TUN applies outbound routing marks when TProxy is enabled -- ( let - expectedMark = perAppRoutingTunWithTproxyFixture.config.services.proxy-suite.singBox.tproxy.proxyMark; + expectedMark = perAppRoutingTunWithTproxyFixture.config.services.proxy-suite.proxy.tproxy.proxyMark; in assert builtins.match ".*--routing-mark.*" perAppRoutingTunWithTproxyStartScript != null; assert perAppRoutingTunWithTproxyDirectOutbound.routing_mark == expectedMark; @@ -2269,9 +2541,9 @@ let true ) - # -- perAppRouting: proxychains requires singBox.enable -- + # -- perAppRouting: proxychains requires proxy.enable -- ( - assert perAppRoutingProxychainsWithoutSingBox.success == false; + assert perAppRoutingProxychainsWithoutProxy.success == false; true ) @@ -2287,29 +2559,29 @@ let true ) - # -- perAppRouting: route=tun requires singBox.tun.perApp.enable -- + # -- perAppRouting: route=tun requires proxy.tun.perApp.enable -- ( assert perAppRoutingTunWithoutEnable.success == false; true ) - # -- perAppRouting: app TUN backend requires singBox.enable -- + # -- perAppRouting: app TUN backend requires proxy.enable -- ( - assert perAppRoutingTunBackendWithoutSingBox.success == false; - assert perAppRoutingTunProfileWithoutSingBox.success == false; + assert perAppRoutingTunBackendWithoutProxy.success == false; + assert perAppRoutingTunProfileWithoutProxy.success == false; true ) - # -- perAppRouting: route=tproxy requires singBox.tproxy.perApp.enable -- + # -- perAppRouting: route=tproxy requires proxy.tproxy.perApp.enable -- ( assert perAppRoutingTproxyWithoutEnable.success == false; true ) - # -- perAppRouting: app TProxy backend requires singBox.enable -- + # -- perAppRouting: app TProxy backend requires proxy.enable -- ( - assert perAppRoutingTproxyBackendWithoutSingBox.success == false; - assert perAppRoutingTproxyProfileWithoutSingBox.success == false; + assert perAppRoutingTproxyBackendWithoutProxy.success == false; + assert perAppRoutingTproxyProfileWithoutProxy.success == false; true ) @@ -2331,7 +2603,7 @@ let true ) - # -- perAppRouting: app TProxy fwmark must differ from sing-box proxyMark -- + # -- perAppRouting: app TProxy fwmark must differ from proxy.tproxy.proxyMark -- ( assert perAppRoutingTproxyFwmarkCollision.success == false; true @@ -2349,7 +2621,7 @@ let true ) - # -- perAppRouting: app zapret filter mark must differ from sing-box proxyMark -- + # -- perAppRouting: app zapret filter mark must differ from proxy.tproxy.proxyMark -- ( assert perAppRoutingZapretFilterMarkCollision.success == false; true @@ -2363,6 +2635,8 @@ let # -- subscription: no outbounds + no subscriptions fails -- ( + assert noProxyBackendDefaultFixture.config.services.proxy-suite.proxy.enable == false; + assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks"); assert noOutboundsNoSubscriptions.success == false; true ) @@ -2383,11 +2657,11 @@ let # -- urlTest: defaults are sane -- ( let - cfg = minimal.config.services.proxy-suite.singBox.urlTest; + cfg = minimal.config.services.proxy-suite.proxy.urlTest; in assert cfg.url == "https://www.gstatic.com/generate_204"; assert cfg.interval == "3m"; - assert cfg.tolerance == 50; + assert minimal.config.services.proxy-suite.proxy.singBox.urlTest.tolerance == 50; true ) ]; diff --git a/nix/options-doc.nix b/nix/options-doc.nix index c50a01d..a6887c0 100644 --- a/nix/options-doc.nix +++ b/nix/options-doc.nix @@ -19,22 +19,41 @@ let ]; }; filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module"); - docPackagePlaceholder = "__proxy_suite_doc_pkg_sing_box__"; + singBoxPackagePlaceholder = "__proxy_suite_doc_pkg_sing_box__"; + xrayPackagePlaceholder = "__proxy_suite_doc_pkg_xray__"; sanitizeConfigForDocs = config: - config + builtins.removeAttrs config [ "singBox" ] // { - singBox = - (config.singBox or { }) - // lib.optionalAttrs ((config.singBox or { }) ? package) { - package = docPackagePlaceholder; + proxy = + (config.proxy or { }) + // { + singBox = + ((config.proxy or { }).singBox or { }) + // lib.optionalAttrs (((config.proxy or { }).singBox or { }) ? package) { + package = singBoxPackagePlaceholder; + }; + xray = + ((config.proxy or { }).xray or { }) + // lib.optionalAttrs (((config.proxy or { }).xray or { }) ? package) { + package = xrayPackagePlaceholder; + }; }; }; renderConfigText = config: - lib.replaceStrings [ "\"${docPackagePlaceholder}\"" ] [ "pkgs.sing-box" ] ( + lib.replaceStrings + [ + "\"${singBoxPackagePlaceholder}\"" + "\"${xrayPackagePlaceholder}\"" + ] + [ + "pkgs.sing-box" + "pkgs.xray" + ] + ( lib.generators.toPretty { } (sanitizeConfigForDocs config) - ); + ); mkGeneratedExampleValue = option: if (option ? _type) && option._type == "option" then @@ -49,9 +68,9 @@ let else lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option); defaultConfigText = renderConfigText eval.config.services.proxy-suite; - exampleConfigText = renderConfigText ( - lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite) - ); + generatedExampleConfig = + lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite); + exampleConfigText = renderConfigText (builtins.removeAttrs generatedExampleConfig [ "singBox" ]); repoRoot = toString ../.; repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main"; transformDeclaration = diff --git a/nix/readme-doc-fixture.nix b/nix/readme-doc-fixture.nix index f47ef6a..df815e8 100644 --- a/nix/readme-doc-fixture.nix +++ b/nix/readme-doc-fixture.nix @@ -4,11 +4,15 @@ services.proxy-suite = { enable = true; - singBox.outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; }; } diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index ff82bfe..c632467 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -14,7 +14,7 @@ _usage() { echo "Commands:" echo " help show this help message" echo " status [--tray] show status of all proxy-suite services" - echo " proxy on|off enable/disable the sing-box proxy stack" + echo " proxy on|off enable/disable the proxy backend stack" echo " tproxy on|off enable/disable TProxy transparent mode" echo " tun on|off enable/disable TUN mode" echo " route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" @@ -27,7 +27,7 @@ _usage() { echo " apps list configured per-app routing profiles" echo " wrap -- run a command via a perAppRouting profile" echo " subscription list show subscriptions, cache age, and proxy count" - echo " subscription update force-refresh all subscription caches and restart active sing-box services" + echo " subscription update force-refresh all subscription caches and restart active proxy services" exit "$status" } @@ -240,11 +240,11 @@ cmd_status() { cmd_proxy() { case "${1:-on}" in on) - _require_service proxy-suite-socks "SOCKS proxy service is not available because singBox is not enabled." + _require_service proxy-suite-socks "SOCKS proxy service is not available because proxy.enable is not enabled." systemctl start proxy-suite-socks ;; off) - _require_service proxy-suite-socks "SOCKS proxy service is not available because singBox is not enabled." + _require_service proxy-suite-socks "SOCKS proxy service is not available because proxy.enable is not enabled." _stop_if_exists proxy-suite-tproxy _stop_if_exists proxy-suite-tun systemctl stop proxy-suite-socks @@ -281,7 +281,7 @@ cmd_route_mode() { local action if ! _svc_exists proxy-suite-socks; then - echo "Route mode is unavailable because sing-box services are not enabled." + echo "Route mode is unavailable because proxy services are not enabled." exit 1 fi @@ -410,13 +410,13 @@ cmd_wrap() { tun) _check_no_global_proxy tun _wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \ - "Profile '$profile' uses route=tun, but singBox.tun.perApp.enable is false." \ + "Profile '$profile' uses route=tun, but proxy.tun.perApp.enable is false." \ "proxy-suite-per-app-tun.service" "$@" ;; tproxy) _check_no_global_proxy tproxy _wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \ - "Profile '$profile' uses route=tproxy, but singBox.tproxy.perApp.enable is false." \ + "Profile '$profile' uses route=tproxy, but proxy.tproxy.perApp.enable is false." \ "proxy-suite-per-app-tproxy.service" "$@" ;; zapret) @@ -439,7 +439,7 @@ cmd_subscription() { case "$subcmd" in list) - CACHE_DIR="/var/lib/proxy-suite/subscriptions" + CACHE_DIR="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}" if [ ${#SUB_TAGS[@]} -eq 0 ]; then echo "No subscriptions configured." return diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index cc84712..53fd974 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -7,6 +7,7 @@ clashApi, selection, subscriptionTagsFile, + subscriptionCacheDir, perAppRoutingEnabled, perAppRoutingProxychainsEnabled, perAppRoutingTunEnabled, @@ -44,6 +45,7 @@ pkgs.symlinkJoin { --set CLASH_API ${lib.escapeShellArg clashApi} \ --set SELECTION ${lib.escapeShellArg selection} \ --set SUB_TAGS_FILE ${lib.escapeShellArg (toString subscriptionTagsFile)} \ + --set SUB_CACHE_DIR ${lib.escapeShellArg subscriptionCacheDir} \ --set PER_APP_ROUTING_ENABLED ${lib.escapeShellArg perAppRoutingEnabled} \ --set PER_APP_ROUTING_PROXYCHAINS_ENABLED ${lib.escapeShellArg perAppRoutingProxychainsEnabled} \ --set PER_APP_ROUTING_TUN_ENABLED ${lib.escapeShellArg perAppRoutingTunEnabled} \ diff --git a/scripts/build-outbound.py b/scripts/build-outbound.py index 755ebed..f1c8bcd 100644 --- a/scripts/build-outbound.py +++ b/scripts/build-outbound.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Read a proxy URL from stdin and emit a sing-box outbound JSON object.""" +"""Read a proxy URL from stdin and emit a backend outbound JSON object.""" import argparse import json @@ -10,15 +10,16 @@ from proxy_parsing import build_outbound def main() -> None: ap = argparse.ArgumentParser( - description="Convert a proxy URL from stdin into a sing-box outbound JSON object." + description="Convert a proxy URL from stdin into a backend outbound JSON object." ) ap.add_argument("--tag", required=True) + ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box") ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark") args = ap.parse_args() url = sys.stdin.read().strip() try: - outbound = build_outbound(url, args.tag, args.routing_mark) + outbound = build_outbound(url, args.tag, args.routing_mark, args.backend) except ValueError as exc: print(f"error: {exc}", file=sys.stderr) sys.exit(1) diff --git a/scripts/fetch-subscription.py b/scripts/fetch-subscription.py index b9dbc73..ad628d6 100644 --- a/scripts/fetch-subscription.py +++ b/scripts/fetch-subscription.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Read a subscription URL from stdin and emit a JSON array of outbounds.""" +"""Read a subscription URL from stdin and emit a JSON array of backend outbounds.""" import argparse import json @@ -10,7 +10,7 @@ from proxy_parsing import decode_subscription, fetch_raw, parse_subscription def main() -> None: ap = argparse.ArgumentParser( - description="Fetch a proxy subscription URL from stdin and emit a sing-box outbound JSON array." + description="Fetch a proxy subscription URL from stdin and emit a backend outbound JSON array." ) ap.add_argument( "--tag-prefix", @@ -18,6 +18,7 @@ def main() -> None: dest="tag_prefix", help="Prefix for outbound tags, e.g. 'my-sub'.", ) + ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box") ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark") args = ap.parse_args() @@ -33,7 +34,7 @@ def main() -> None: sys.exit(1) lines = decode_subscription(raw) - outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark) + outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend) if not outbounds: print("error: subscription contained no parseable proxy URIs", file=sys.stderr) diff --git a/scripts/proxy_parsing.py b/scripts/proxy_parsing.py index 1c0ad76..3efa772 100644 --- a/scripts/proxy_parsing.py +++ b/scripts/proxy_parsing.py @@ -13,14 +13,186 @@ def detect_scheme(url: str) -> str: return url.split("://", 1)[0].lower() -def build_outbound(url: str, tag: str, routing_mark: int | None = None) -> dict: +def _parse_url(url: str, tag: str, backend: str) -> dict: scheme = detect_scheme(url) if scheme not in PARSERS: raise ValueError(f"unsupported scheme '{scheme}'") - outbound = PARSERS[scheme](url, tag) + parser = PARSERS[scheme] + try: + return parser(url, tag, backend) + except TypeError: + return parser(url, tag) + + +def _xray_sockopt(routing_mark: int | None) -> dict: + if routing_mark is None: + return {} + return {"streamSettings": {"sockopt": {"mark": routing_mark}}} + + +def _xray_tls(tls: dict | None) -> tuple[str, dict]: + if not tls or not tls.get("enabled"): + return "none", {} + + if tls.get("reality", {}).get("enabled"): + reality = tls["reality"] + settings = { + "serverName": tls.get("server_name", ""), + "publicKey": reality["public_key"], + "shortId": reality.get("short_id", ""), + } + utls = tls.get("utls", {}) + if utls.get("enabled") and utls.get("fingerprint"): + settings["fingerprint"] = utls["fingerprint"] + return "reality", {"realitySettings": settings} + + settings = {"serverName": tls.get("server_name", "")} + if tls.get("alpn"): + settings["alpn"] = tls["alpn"] + if tls.get("insecure"): + settings["allowInsecure"] = True + if tls.get("ech_config_list"): + settings["echConfigList"] = tls["ech_config_list"] + utls = tls.get("utls", {}) + if utls.get("enabled") and utls.get("fingerprint"): + settings["fingerprint"] = utls["fingerprint"] + return "tls", {"tlsSettings": settings} + + +def _xray_transport(transport: dict | None) -> tuple[str, dict]: + if not transport: + return "tcp", {} + + t = transport["type"] + if t == "ws": + return "ws", {"wsSettings": {"path": transport.get("path", "/"), "headers": transport.get("headers", {})}} + if t == "grpc": + return "grpc", {"grpcSettings": {"serviceName": transport.get("service_name", "")}} + if t == "http": + return "http", {"httpSettings": {"host": transport.get("host", []), "path": transport.get("path", "/")}} + if t == "httpupgrade": + return "httpupgrade", { + "httpupgradeSettings": { + "host": transport.get("host", ""), + "path": transport.get("path", "/"), + } + } + if t == "quic": + return "quic", {} + if t == "xhttp": + return "xhttp", { + "xhttpSettings": { + "host": transport.get("host", ""), + "path": transport.get("path", "/"), + } + } + return t, {} + + +def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict: + typ = ob["type"] + tag = ob["tag"] + + def stream_settings() -> dict: + security, sec = _xray_tls(ob.get("tls")) + network, net = _xray_transport(ob.get("transport")) + stream = {"network": network, "security": security} + stream.update(sec) + stream.update(net) + if routing_mark is not None: + stream.setdefault("sockopt", {})["mark"] = routing_mark + return stream + + if typ == "vless": + settings = { + "address": ob["server"], + "port": ob["server_port"], + "id": ob["uuid"], + "encryption": "none", + } + if ob.get("flow"): + settings["flow"] = ob["flow"] + return {"protocol": "vless", "tag": tag, "settings": settings, "streamSettings": stream_settings()} + + if typ == "vmess": + settings = { + "address": ob["server"], + "port": ob["server_port"], + "id": ob["uuid"], + "security": ob.get("security", "auto"), + "alterId": ob.get("alter_id", 0), + } + return {"protocol": "vmess", "tag": tag, "settings": settings, "streamSettings": stream_settings()} + + if typ == "trojan": + settings = { + "address": ob["server"], + "port": ob["server_port"], + "password": ob["password"], + } + return {"protocol": "trojan", "tag": tag, "settings": settings, "streamSettings": stream_settings()} + + if typ == "shadowsocks": + settings = { + "address": ob["server"], + "port": ob["server_port"], + "method": ob["method"], + "password": ob["password"], + } + return {"protocol": "shadowsocks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)} + + if typ == "hysteria2": + stream = stream_settings() + stream["network"] = "hysteria" + stream["security"] = "tls" + settings = { + "version": 2, + "address": ob["server"], + "port": ob["server_port"], + } + if ob.get("password"): + settings["password"] = ob["password"] + return {"protocol": "hysteria", "tag": tag, "settings": settings, "streamSettings": stream} + + if typ == "socks": + settings = {"address": ob["server"], "port": ob["server_port"]} + if ob.get("username"): + settings["user"] = ob["username"] + settings["pass"] = ob.get("password", "") + return {"protocol": "socks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)} + + if typ == "http": + settings = {"address": ob["server"], "port": ob["server_port"]} + if ob.get("username"): + settings["user"] = ob["username"] + settings["pass"] = ob.get("password", "") + outbound = {"protocol": "http", "tag": tag, "settings": settings} + if ob.get("tls"): + security, sec = _xray_tls(ob.get("tls")) + outbound["streamSettings"] = {"security": security, **sec} + if routing_mark is not None: + outbound["streamSettings"].setdefault("sockopt", {})["mark"] = routing_mark + elif routing_mark is not None: + outbound.update(_xray_sockopt(routing_mark)) + return outbound + + raise ValueError(f"unsupported XRay outbound type '{typ}'") + + +def build_outbound( + url: str, tag: str, routing_mark: int | None = None, backend: str = "sing-box" +) -> dict: + if backend not in {"sing-box", "xray"}: + raise ValueError(f"unsupported backend '{backend}'") + + outbound = _parse_url(url, tag, backend) if routing_mark is not None: + if backend == "xray": + return render_xray_outbound(outbound, routing_mark) outbound["routing_mark"] = routing_mark + elif backend == "xray": + return render_xray_outbound(outbound) return outbound @@ -63,7 +235,7 @@ def make_tag(prefix: str, remark: str, index: int) -> str: def parse_subscription( - lines: list[str], tag_prefix: str, routing_mark: int | None + lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box" ) -> list[dict]: outbounds = [] seen_tags: set[str] = set() @@ -84,7 +256,7 @@ def parse_subscription( tag = f"{base_tag}-{suffix}" try: - outbound = build_outbound(line, tag, routing_mark) + outbound = build_outbound(line, tag, routing_mark, backend) except Exception as exc: print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr) continue diff --git a/scripts/proxy_url_parsers.py b/scripts/proxy_url_parsers.py index cc07384..5311889 100644 --- a/scripts/proxy_url_parsers.py +++ b/scripts/proxy_url_parsers.py @@ -16,6 +16,11 @@ SUPPORTED_VLESS_TRANSPORTS = { "quic", } +SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS | { + "xhttp", + "splithttp", +} + def _qs(query: str) -> dict: return dict(urllib.parse.parse_qsl(query, keep_blank_values=True)) @@ -79,6 +84,12 @@ def _mk_transport( return { "type": "quic", } + if normalized in ("xhttp", "splithttp"): + return { + "type": "xhttp", + "host": host_header, + "path": urllib.parse.unquote(path), + } return None @@ -100,22 +111,25 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]": return None, None -def parse_vless(url: str, tag: str) -> dict: +def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict: userinfo, host, port, params = _parse_url_parts(url, "vless") security = params.get("security", "none") transport = params.get("type", "tcp") normalized_transport = transport.lower() - if "ech" in params: + if "ech" in params and backend != "xray": raise ValueError( "unsupported VLESS parameter 'ech': proxy-suite does not translate " "share-link ECH blobs into sing-box TLS config" ) - if normalized_transport not in SUPPORTED_VLESS_TRANSPORTS: + supported_transports = ( + SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS + ) + if normalized_transport not in supported_transports: raise ValueError( f"unsupported VLESS transport '{transport}': proxy-suite only maps " - "sing-box-documented transports; use raw JSON or another client/core" + f"{backend}-documented transports; use raw JSON or another client/core" ) ob: dict = { @@ -138,6 +152,8 @@ def parse_vless(url: str, tag: str) -> dict: ob["tls"] = _mk_tls( params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn") ) + if backend == "xray" and "ech" in params: + ob["tls"]["ech_config_list"] = urllib.parse.unquote(params["ech"]) tr = _mk_transport( normalized_transport, diff --git a/scripts/test-build-outbound.py b/scripts/test-build-outbound.py index 2bf0ab1..5a9ef07 100644 --- a/scripts/test-build-outbound.py +++ b/scripts/test-build-outbound.py @@ -11,6 +11,10 @@ def run_parser(url: str): return build_outbound(url, "test-outbound") +def run_xray_parser(url: str): + return build_outbound(url, "test-outbound", backend="xray") + + class BuildOutboundTests(unittest.TestCase): def test_vless_reality(self): ob = run_parser( @@ -50,6 +54,41 @@ class BuildOutboundTests(unittest.TestCase): "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com" ) + def test_xray_vless_xhttp(self): + ob = run_xray_parser( + "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx" + ) + self.assertEqual(ob["protocol"], "vless") + self.assertEqual(ob["settings"]["address"], "example.com") + self.assertEqual(ob["settings"]["id"], "uuid") + self.assertEqual(ob["streamSettings"]["network"], "xhttp") + self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x") + + def test_xray_vless_ech(self): + ob = run_xray_parser( + "vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1" + ) + self.assertEqual(ob["streamSettings"]["tlsSettings"]["echConfigList"], "udp://1.1.1.1") + + def test_xray_socks_uses_current_flat_settings_shape(self): + ob = run_xray_parser("socks5://user:pass@example.com:1080") + self.assertEqual(ob["protocol"], "socks") + self.assertEqual(ob["settings"]["address"], "example.com") + self.assertEqual(ob["settings"]["user"], "user") + self.assertNotIn("servers", ob["settings"]) + + def test_xray_shadowsocks_uses_current_flat_settings_shape(self): + credentials = ( + base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd") + .decode() + .rstrip("=") + ) + ob = run_xray_parser(f"ss://{credentials}@ss.example.com:8388") + self.assertEqual(ob["protocol"], "shadowsocks") + self.assertEqual(ob["settings"]["address"], "ss.example.com") + self.assertEqual(ob["settings"]["method"], "chacha20-ietf-poly1305") + self.assertNotIn("servers", ob["settings"]) + def test_vless_ech_fails_loudly(self): with self.assertRaisesRegex(ValueError, "unsupported VLESS parameter 'ech'"): run_parser(