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

+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