feat(wip): xray proxy backend

This commit is contained in:
FUFSoB committed 2026-06-07 18:15:37 +05:00
1 parent 377d974a18
commit 39ce4d6be2
36 files changed
+2265 -996

No files matched your search

+12 -7
View File
@@ -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 <profile> -- <command>`, 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 <command> [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 <profile> -- <cmd> 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
```
<!-- proxy-ctl-help:end -->
+637 -452
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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";
+179 -33
View File
@@ -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
+37 -12
View File
@@ -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
+4 -4
View File
@@ -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;
+1
View File
@@ -3,6 +3,7 @@
{
imports = [
./other.nix
./legacy-sing-box.nix
./sing-box.nix
./sing-box-outbounds.nix
./sing-box-dns.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; })
];
};
}
+2 -2
View File
@@ -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;
@@ -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 -- <command>` 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
+3 -3
View File
@@ -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";
@@ -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/<tag>.json. Later restarts
under /var/lib/proxy-suite/subscriptions/<backend>/<tag>.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;
};
};
}
@@ -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.
'';
@@ -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;
+4 -4
View File
@@ -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;
+72 -24
View File
@@ -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.
'';
};
};
};
}
+43 -10
View File
@@ -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/<backend>/, 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.
+8 -8
View File
@@ -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;
};
+117 -6
View File
@@ -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
;
+96 -72
View File
@@ -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
+22 -1
View File
@@ -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
+4 -1
View File
@@ -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";
+49 -22
View File
@@ -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
@@ -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 ";
+178 -120
View File
@@ -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
;
}
+2 -2
View File
@@ -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
+391 -117
View File
@@ -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 <profile> -- <cmd>" 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
)
];
+30 -11
View File
@@ -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 =
+10 -6
View File
@@ -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";
}
];
};
};
}
+8 -8
View File
@@ -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 <profile> -- <cmd> 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
+2
View File
@@ -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} \
+4 -3
View File
@@ -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)
+4 -3
View File
@@ -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)
+176 -4
View File
@@ -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
+20 -4
View File
@@ -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,
+39
View File
@@ -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(