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. 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. 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 ## What it gives you
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` by default – always running, always available to apps - **SOCKS5/HTTP proxy** on `127.0.0.1:1080` when `proxy.enable = true`
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand or autostart at boot - **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 - **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 - **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 - **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 - **Multiple outbounds** with automatic latency-based switching or manual selection
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers - **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 - **`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 - **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 - **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy
@@ -46,8 +47,12 @@ Feature-complete starter config:
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true; enable = true;
singBox.enable = true;
# Or use XRay instead:
# xray.enable = true;
port = 1080; port = 1080;
# Individual proxy example # Individual proxy example
@@ -132,7 +137,7 @@ Usage: proxy-ctl <command> [args]
Commands: Commands:
help show this help message help show this help message
status [--tray] show status of all proxy-suite services 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 tproxy on|off enable/disable TProxy transparent mode
tun on|off enable/disable TUN mode tun on|off enable/disable TUN mode
route-mode default|whitelist|blacklist|all-proxy|all-bypass|status route-mode default|whitelist|blacklist|all-proxy|all-bypass|status
@@ -145,6 +150,6 @@ Commands:
apps list configured per-app routing profiles apps list configured per-app routing profiles
wrap <profile> -- <cmd> run a command via a perAppRouting profile wrap <profile> -- <cmd> run a command via a perAppRouting profile
subscription list show subscriptions, cache age, and proxy count 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 --> <!-- 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 = { inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
+179 -33
View File
@@ -1,5 +1,5 @@
# Build-time sing-box configuration templates. # Build-time proxy backend configuration templates.
# The proxy outbound(s) are injected at service start time, not here. # Proxy outbounds are injected at service start time, not here.
{ {
lib, lib,
pkgs, pkgs,
@@ -10,7 +10,9 @@
let let
derived = import ./derived.nix { inherit lib cfg; }; derived = import ./derived.nix { inherit lib cfg; };
inherit (derived) inherit (derived)
proxyCfg
singBoxCfg singBoxCfg
xrayEnabled
globalTun globalTun
globalTproxy globalTproxy
clashApiEnabled clashApiEnabled
@@ -18,7 +20,7 @@ let
perAppTun = derived.perAppRoutingTun; perAppTun = derived.perAppRoutingTun;
direct = rules.direct; direct = rules.direct;
mkDnsServer = mkSingBoxDnsServer =
tag: upstream: detour: tag: upstream: detour:
{ {
inherit tag; inherit tag;
@@ -28,17 +30,17 @@ let
} }
// lib.optionalAttrs (detour != null) { inherit detour; }; // lib.optionalAttrs (detour != null) { inherit detour; };
mkDnsConfig = mkSingBoxDnsConfig =
{ {
localDetour ? null, localDetour ? null,
}: }:
{ {
servers = [ servers = [
(mkDnsServer "remote" singBoxCfg.dns.remote "proxy") (mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy")
(mkDnsServer "local" singBoxCfg.dns.local localDetour) (mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour)
]; ];
rules = rules =
lib.optional (builtins.elem "google" singBoxCfg.routing.proxy.geosites) { lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ]; rule_set = [ "geosite-google" ];
server = "remote"; server = "remote";
} }
@@ -46,7 +48,7 @@ let
rule_set = map (s: "geosite-${s}") direct.geosites; rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local"; server = "local";
}; };
final = if singBoxCfg.proxyByDefault then "remote" else "local"; final = if proxyCfg.proxyByDefault then "remote" else "local";
}; };
clashApiBlock = lib.optionalAttrs clashApiEnabled { clashApiBlock = lib.optionalAttrs clashApiEnabled {
@@ -57,7 +59,7 @@ let
}; };
}; };
mkConfig = mkSingBoxConfig =
{ {
enableMixed ? false, enableMixed ? false,
enableTProxy ? false, enableTProxy ? false,
@@ -77,10 +79,7 @@ let
{ {
log.level = "warn"; log.level = "warn";
# Keep "local" DNS on the direct path by default, but avoid explicit dns = mkSingBoxDnsConfig {
# detour="direct" because sing-box rejects detouring to an empty
# direct outbound. Global TUN can force local DNS through proxy.
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null; localDetour = if forceLocalDnsViaProxy then "proxy" else null;
}; };
@@ -88,8 +87,8 @@ let
lib.optional enableMixed { lib.optional enableMixed {
type = "mixed"; type = "mixed";
tag = "mixed-in"; tag = "mixed-in";
listen = singBoxCfg.listenAddress; listen = proxyCfg.listenAddress;
listen_port = singBoxCfg.port; listen_port = proxyCfg.port;
} }
++ lib.optional enableTProxy { ++ lib.optional enableTProxy {
type = "tproxy"; type = "tproxy";
@@ -110,14 +109,11 @@ let
stack = "mixed"; stack = "mixed";
} }
// lib.optionalAttrs tunAutoRoute { // 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_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex; iproute2_rule_index = tunAutoRouteRuleIndex;
} }
); );
# proxy outbound(s) are prepended at runtime by the start script
outbounds = [ outbounds = [
( (
{ {
@@ -135,25 +131,155 @@ let
route = { route = {
default_domain_resolver = "local"; default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets; rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = rules.routingRules; rules = rules.singBoxRoutingRules;
final = if singBoxCfg.proxyByDefault then "proxy" else "direct"; final = if proxyCfg.proxyByDefault then "proxy" else "direct";
} }
// lib.optionalAttrs (enableTun && tunAutoRoute) { // 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; auto_detect_interface = true;
}; };
} }
// lib.optionalAttrs enableClashApi clashApiBlock; // 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; enableMixed = true;
enableTProxy = true; enableTProxy = true;
useOutboundRoutingMark = true; useOutboundRoutingMark = true;
}; };
tunTemplate = mkConfig { singBoxTunTemplate = mkSingBoxConfig {
enableTun = true; enableTun = true;
tunInterface = globalTun.interface; tunInterface = globalTun.interface;
tunAddress = globalTun.address; tunAddress = globalTun.address;
@@ -161,15 +287,11 @@ let
tunAutoRoute = true; tunAutoRoute = true;
tunAutoRedirect = true; tunAutoRedirect = true;
tunStrictRoute = 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; forceLocalDnsViaProxy = false;
enableClashApi = false; enableClashApi = false;
}; };
perAppTunTemplate = mkConfig { singBoxPerAppTunTemplate = mkSingBoxConfig {
enableTun = true; enableTun = true;
tunInterface = perAppTun.interface; tunInterface = perAppTun.interface;
tunAddress = perAppTun.address; tunAddress = perAppTun.address;
@@ -178,19 +300,43 @@ let
tunAutoRedirect = false; tunAutoRedirect = false;
tunStrictRoute = false; tunStrictRoute = false;
forceLocalDnsViaProxy = 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; useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false; 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); tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate); tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" ( perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
builtins.toJSON perAppTunTemplate builtins.toJSON perAppTunTemplate
); );
routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" ( routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" (
builtins.toJSON rules.routeModeRules builtins.toJSON routeModeRules
); );
in in
+37 -12
View File
@@ -4,28 +4,47 @@
}: }:
let 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; perAppRoutingCfg = cfg.perAppRouting;
globalTun = singBoxCfg.tun; globalTun = proxyCfg.tun;
globalTproxy = singBoxCfg.tproxy; globalTproxy = proxyCfg.tproxy;
perAppRoutingTun = singBoxCfg.tun.perApp; perAppRoutingTun = proxyCfg.tun.perApp;
perAppRoutingTproxy = singBoxCfg.tproxy.perApp; perAppRoutingTproxy = proxyCfg.tproxy.perApp;
perAppZapretCfg = cfg.zapret.perApp; perAppZapretCfg = cfg.zapret.perApp;
userControlCfg = cfg.userControl; userControlCfg = cfg.userControl;
selectionMode = singBoxCfg.selection; selectionMode = proxyCfg.selection;
builtinTags = [ builtinTags = [
"proxy" "proxy"
"direct" "direct"
"block" "block"
]; ];
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds; outboundTags = map (ob: ob.tag) proxyCfg.outbounds;
subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions; subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions;
hasStaticOutbounds = singBoxCfg.outbounds != [ ]; hasStaticOutbounds = proxyCfg.outbounds != [ ];
hasSubscriptions = singBoxCfg.subscriptions != [ ]; hasSubscriptions = proxyCfg.subscriptions != [ ];
collapseNamedOutbounds = selectionMode == "first"; collapseNamedOutbounds = selectionMode == "first";
clashApiEnabled = selectionMode != "first"; clashApiEnabled = singBoxEnabled && selectionMode != "first";
perAppZapretEnabled = perAppZapretCfg.enable; perAppZapretEnabled = perAppZapretCfg.enable;
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable; userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
@@ -33,13 +52,19 @@ let
map (rule: rule.outbound) ( map (rule: rule.outbound) (
builtins.filter ( builtins.filter (
rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags) rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)
) singBoxCfg.routing.rules ) proxyCfg.routing.rules
) )
); );
in in
{ {
inherit inherit
proxyCfg
singBoxCfg singBoxCfg
xrayCfg
proxyEnabled
singBoxEnabled
xrayEnabled
activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
globalTproxy globalTproxy
+4 -4
View File
@@ -6,10 +6,10 @@
}: }:
let let
singBoxCfg = cfg.singBox; proxyCfg = cfg.proxy;
globalTproxy = singBoxCfg.tproxy; globalTproxy = proxyCfg.tproxy;
perAppTun = singBoxCfg.tun.perApp; perAppTun = proxyCfg.tun.perApp;
perAppTproxy = singBoxCfg.tproxy.perApp; perAppTproxy = proxyCfg.tproxy.perApp;
zapretApp = cfg.zapret.perApp; zapretApp = cfg.zapret.perApp;
tgWsProxyCfg = cfg.tgWsProxy; tgWsProxyCfg = cfg.tgWsProxy;
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy; tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
+1
View File
@@ -3,6 +3,7 @@
{ {
imports = [ imports = [
./other.nix ./other.nix
./legacy-sing-box.nix
./sing-box.nix ./sing-box.nix
./sing-box-outbounds.nix ./sing-box-outbounds.nix
./sing-box-dns.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 in
{ {
options.services.proxy-suite = { 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 = { userControl = {
group = mkOption { group = mkOption {
@@ -141,7 +141,7 @@ in
When enabled and global TUN or TProxy mode is configured, the When enabled and global TUN or TProxy mode is configured, the
tg-ws-proxy systemd service receives a packet mark and an earlier tg-ws-proxy systemd service receives a packet mark and an earlier
policy-routing rule back to the main table. This prevents global TUN 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. which can otherwise break tg-ws-proxy after enabling TUN mode.
''; '';
example = true; example = true;
@@ -20,8 +20,8 @@ in
Current curated defaults: Current curated defaults:
- `proxychains`: route = "proxychains" - `proxychains`: route = "proxychains"
- `tun`: route = "tun" when singBox.tun.perApp.enable = true - `tun`: route = "tun" when proxy.tun.perApp.enable = true
- `tproxy`: route = "tproxy" when singBox.tproxy.perApp.enable = true - `tproxy`: route = "tproxy" when proxy.tproxy.perApp.enable = true
- `zapret`: route = "zapret" when zapret.perApp.enable = true - `zapret`: route = "zapret" when zapret.perApp.enable = true
This makes `proxy-ctl wrap proxychains -- <command>` available This makes `proxy-ctl wrap proxychains -- <command>` available
@@ -51,10 +51,10 @@ in
- "zapret" for per-app-scoped zapret handling through a separate - "zapret" for per-app-scoped zapret handling through a separate
zapret instance without changing the app's network path or exit IP zapret instance without changing the app's network path or exit IP
proxychains-based wrapping depends on singBox.enable = true and the proxychains-based wrapping depends on proxy.enable = true and the
local proxy-suite mixed proxy listener provided by sing-box. The local proxy-suite proxy listener provided by the active backend. The
"tun" route depends on singBox.tun.perApp.enable = true. The "tproxy" "tun" route depends on proxy.tun.perApp.enable = true. The "tproxy"
route depends on singBox.tproxy.perApp.enable = true. The "zapret" route depends on proxy.tproxy.perApp.enable = true. The "zapret"
route depends on zapret.perApp.enable = true. route depends on zapret.perApp.enable = true.
When createDefaultProfiles = true, curated defaults are added on top When createDefaultProfiles = true, curated defaults are added on top
+3 -3
View File
@@ -5,7 +5,7 @@ let
t = import ./types.nix { inherit lib; }; t = import ./types.nix { inherit lib; };
in in
{ {
options.services.proxy-suite.singBox.dns = { options.services.proxy-suite.proxy.dns = {
local = mkOption { local = mkOption {
type = t.dnsUpstreamType; type = t.dnsUpstreamType;
default = { default = {
@@ -15,7 +15,7 @@ in
}; };
description = '' description = ''
DNS upstream used for the built-in "local" resolver role. 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 The module keeps detour policy automatic: in mixed/TProxy mode and
per-app-routing TUN mode, "local" stays on the direct path (without an 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. DNS upstream used for the built-in "remote" resolver role.
This resolver always detours through the proxy and becomes the 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 = { example = {
type = "tls"; type = "tls";
@@ -5,16 +5,18 @@ let
t = import ./types.nix { inherit lib; }; t = import ./types.nix { inherit lib; };
in in
{ {
options.services.proxy-suite.singBox = { options.services.proxy-suite.proxy = {
outbounds = mkOption { outbounds = mkOption {
type = types.listOf t.outboundType; type = types.listOf t.outboundType;
default = [ ]; default = [ ];
description = '' description = ''
List of static proxy outbounds. List of static proxy outbounds.
Set exactly one of urlFile, url, or json per entry. Set exactly one of urlFile, url, singBoxJson, xrayJson, or the
deprecated json field per entry. Backend-specific raw JSON fields are
only valid with their matching backend.
At least one outbound or one subscription is required when At least one outbound or one subscription is required when
singBox.enable = true. proxy.enable = true.
''; '';
example = [ example = [
{ {
@@ -37,12 +39,12 @@ in
(standard v2rayN / Clash subscription format) or plain text of the same. (standard v2rayN / Clash subscription format) or plain text of the same.
On first service start, each subscription is fetched live and cached 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. reuse the cache, so ordinary service restarts do not need network access.
A systemd timer (proxy-suite-subscription-update) refreshes all caches on A systemd timer (proxy-suite-subscription-update) refreshes all caches
the interval set by subscriptionUpdateInterval and restarts the running on the interval set by subscriptionUpdateInterval and restarts the
sing-box services after a successful refresh. running proxy services after a successful refresh.
''; '';
example = [ example = [
{ {
@@ -64,7 +66,7 @@ in
all subscription caches. Accepts any systemd time span string all subscription caches. Accepts any systemd time span string
(e.g. "1h", "6h", "1d", "12h"). (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. once shortly after boot.
''; '';
example = "6h"; example = "6h";
@@ -86,11 +88,13 @@ in
- "selector": create a Clash-compatible selector outbound tagged - "selector": create a Clash-compatible selector outbound tagged
"proxy" and keep all configured outbounds available for manual "proxy" and keep all configured outbounds available for manual
switching via the Clash API. switching via the Clash API.
- "urltest": create an automatic latency-testing outbound tagged - "urltest": create automatic latency testing tagged "proxy" and
"proxy" and keep all configured outbounds available so sing-box keep all configured outbounds available so the active backend can
can periodically probe and switch to a faster one. 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". urlTest.* options are only used with "urltest".
Per-outbound tags are only individually meaningful with "selector" Per-outbound tags are only individually meaningful with "selector"
or "urltest". or "urltest".
@@ -103,7 +107,7 @@ in
type = types.str; type = types.str;
default = "https://www.gstatic.com/generate_204"; default = "https://www.gstatic.com/generate_204";
description = '' 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". Only used when selection = "urltest".
Set this to a URL that is actually blocked in your region (e.g. Set this to a URL that is actually blocked in your region (e.g.
@@ -118,35 +122,12 @@ in
type = types.str; type = types.str;
default = "3m"; default = "3m";
description = '' description = ''
How often sing-box re-tests all outbounds. Accepts a Go duration How often the active backend re-tests all outbounds. Accepts a Go
string (e.g. "1m", "3m", "10m"). duration string (e.g. "1m", "3m", "10m").
Only used when selection = "urltest". Only used when selection = "urltest".
''; '';
example = "1m"; 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; }; t = import ./types.nix { inherit lib; };
in in
{ {
options.services.proxy-suite.singBox.routing = { options.services.proxy-suite.proxy.routing = {
enableRuDirect = mkOption { enableRuDirect = mkOption {
type = types.bool; type = types.bool;
default = true; default = true;
@@ -98,7 +98,7 @@ in
The outbound can be a configured outbound tag (useful with selector/urltest), The outbound can be a configured outbound tag (useful with selector/urltest),
or one of: "proxy" (active proxy), "direct", "block". 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 With selection = "first", non-built-in outbound tags are effectively
routed to the single active "proxy" outbound. routed to the single active "proxy" outbound.
''; '';
@@ -4,8 +4,8 @@ let
inherit (lib) mkOption mkEnableOption types; inherit (lib) mkOption mkEnableOption types;
in in
{ {
options.services.proxy-suite.singBox.tproxy = { options.services.proxy-suite.proxy.tproxy = {
enable = mkEnableOption "global sing-box TProxy mode service"; enable = mkEnableOption "global proxy TProxy mode service";
autostart = mkOption { autostart = mkOption {
type = types.bool; type = types.bool;
@@ -13,7 +13,7 @@ in
description = '' description = ''
Whether to start proxy-suite-tproxy automatically during boot by Whether to start proxy-suite-tproxy automatically during boot by
attaching it to multi-user.target. attaching it to multi-user.target.
Cannot be enabled together with singBox.tun.autostart. Cannot be enabled together with proxy.tun.autostart.
''; '';
example = true; example = true;
}; };
@@ -22,7 +22,7 @@ in
type = types.port; type = types.port;
default = 1081; default = 1081;
description = '' 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 nftables redirection created by proxy-suite-tproxy sends intercepted
TCP/UDP traffic to this port. TCP/UDP traffic to this port.
''; '';
@@ -35,7 +35,7 @@ in
description = '' description = ''
Mark applied to intercepted packets in global TProxy mode. Mark applied to intercepted packets in global TProxy mode.
A matching `ip rule` routes this mark to 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. loopback for local proxy processing.
''; '';
example = 1; example = 1;
@@ -45,7 +45,7 @@ in
type = types.int; type = types.int;
default = 2; default = 2;
description = '' 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 they bypass re-interception and do not loop back into the
transparent proxy path. transparent proxy path.
''; '';
@@ -58,7 +58,7 @@ in
description = '' description = ''
Policy-routing table number used for global TProxy interception flow. Policy-routing table number used for global TProxy interception flow.
The module installs a local default route in this table and binds it The module installs a local default route in this table and binds it
to singBox.tproxy.fwmark. to proxy.tproxy.fwmark.
''; '';
example = 100; example = 100;
}; };
@@ -81,7 +81,7 @@ in
}; };
perApp = { 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 { fwmark = mkOption {
type = types.int; type = types.int;
+4 -4
View File
@@ -36,8 +36,8 @@ let
}; };
in in
{ {
options.services.proxy-suite.singBox.tun = { options.services.proxy-suite.proxy.tun = {
enable = mkEnableOption "global sing-box TUN mode service"; enable = mkEnableOption "global proxy TUN mode service";
autostart = mkOption { autostart = mkOption {
type = types.bool; type = types.bool;
@@ -45,13 +45,13 @@ in
description = '' description = ''
Whether to start proxy-suite-tun automatically during boot by Whether to start proxy-suite-tun automatically during boot by
attaching it to multi-user.target. attaching it to multi-user.target.
Cannot be enabled together with singBox.tproxy.autostart. Cannot be enabled together with proxy.tproxy.autostart.
''; '';
example = true; example = true;
}; };
perApp = { 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 { fwmark = mkOption {
type = types.int; 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, ... }: { lib, pkgs, ... }:
let let
inherit (lib) literalExpression mkOption mkEnableOption types; inherit (lib) literalExpression mkOption mkEnableOption types;
in in
{ {
options.services.proxy-suite.singBox = { options.services.proxy-suite.proxy = {
enable = mkOption { enable = mkOption {
type = types.bool; type = types.bool;
default = true; default = false;
description = '' description = ''
Whether to configure and run sing-box services for proxy-suite. Whether to configure and run the proxy backend services.
When disabled, sing-box services and generated sing-box configs are This is disabled by default; enable it explicitly and choose exactly
skipped even if proxy-suite itself is enabled. one backend with proxy.singBox.enable or proxy.xray.enable.
'';
};
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.
''; '';
}; };
@@ -33,8 +20,8 @@ in
type = types.str; type = types.str;
default = "127.0.0.1"; default = "127.0.0.1";
description = '' description = ''
Address for the SOCKS5/HTTP mixed inbound to bind to. Address for the local SOCKS5/HTTP inbound to bind to.
This affects the always-on proxy-suite-socks service. This affects the proxy-suite-socks service.
Use "0.0.0.0" only if you intentionally want to expose the proxy to Use "0.0.0.0" only if you intentionally want to expose the proxy to
other machines on your network. other machines on your network.
@@ -46,8 +33,9 @@ in
type = types.port; type = types.port;
default = 1080; default = 1080;
description = '' description = ''
Listen port for the always-on SOCKS5/HTTP mixed inbound provided by Listen port for the local SOCKS5/HTTP proxy inbound provided by
proxy-suite-socks. proxy-suite-socks. SingBox exposes SOCKS5 and HTTP on this port.
XRay's Socks inbound also accepts SOCKS and HTTP.
''; '';
example = 1080; example = 1080;
}; };
@@ -102,10 +90,70 @@ in
Whether traffic that does not match any explicit routing rule should Whether traffic that does not match any explicit routing rule should
go through the proxy or go direct. 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. config.
''; '';
example = true; 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 = [ ]; default = [ ];
description = '' description = ''
sing-geosite rule-set names to match in this routing rule. 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 = [ example = [
"netflix" "netflix"
@@ -44,7 +44,7 @@ let
default = [ ]; default = [ ];
description = '' description = ''
sing-geoip rule-set names to match in this routing rule. 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 = [ example = [
"us" "us"
@@ -83,7 +83,8 @@ let
e.g. "my-sub" -> tags like "my-sub-Server-DE". e.g. "my-sub" -> tags like "my-sub-Server-DE".
This value is also used as the subscription cache filename stem under 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"; example = "community-list";
}; };
@@ -125,7 +126,7 @@ let
Outbound tag used in routing rules and multi-outbound selection. Outbound tag used in routing rules and multi-outbound selection.
With selection = "selector" or "urltest", each outbound keeps its own 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 routes through a single active outbound tagged "proxy", so individual
proxy tags are mainly useful for documentation and config structure. proxy tags are mainly useful for documentation and config structure.
''; '';
@@ -158,7 +159,7 @@ let
example = "hy2://password@example.com:443?sni=example.com"; example = "hy2://password@example.com:443?sni=example.com";
}; };
json = mkOption { singBoxJson = mkOption {
type = types.nullOr types.attrs; type = types.nullOr types.attrs;
default = null; default = null;
description = '' description = ''
@@ -166,9 +167,10 @@ let
Embedded directly into the config at build time. The tag field Embedded directly into the config at build time. The tag field
is overridden by the outbound's tag option. 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 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 = { example = {
type = "vless"; 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. # Shorthand for attaching routing rules directly to an outbound definition.
# Traffic matching these patterns is sent to this specific outbound. # Traffic matching these patterns is sent to this specific outbound.
# Only meaningful when selection = "selector" or "urltest" (with "first", # Only meaningful when selection = "selector" or "urltest" (with "first",
@@ -196,7 +229,7 @@ let
]; ];
default = "udp"; default = "udp";
description = '' description = ''
sing-box DNS transport type for this upstream resolver. DNS transport type for this upstream resolver.
''; '';
example = "tls"; example = "tls";
}; };
@@ -280,7 +313,7 @@ let
type = types.bool; type = types.bool;
default = true; default = true;
description = '' 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. 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. only that app's traffic is policy-routed into the app TUN backend.
- "tproxy": launch the command in the dedicated per-app-routing TProxy - "tproxy": launch the command in the dedicated per-app-routing TProxy
slice so only that app's traffic is transparently intercepted by 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 - "zapret": launch the command in the dedicated per-app-routing zapret
slice so only that app's traffic is handled by the separate slice so only that app's traffic is handled by the separate
per-app-scoped zapret instance. per-app-scoped zapret instance.
+8 -8
View File
@@ -39,7 +39,7 @@ in
default = true; default = true;
description = '' description = ''
When zapret.enable = true, mirror zapret's upstream domain hostlists 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 This includes the default zapret domain lists and any custom
hostlistRules entries with enableDirectSync = true. hostlistRules entries with enableDirectSync = true.
@@ -52,7 +52,7 @@ in
default = false; default = false;
description = '' description = ''
When zapret.enable = true, mirror zapret's upstream ipset ranges 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; example = false;
}; };
@@ -62,7 +62,7 @@ in
default = true; default = true;
description = '' description = ''
When zapret.enable = true, mirror user-defined zapret.ipsetAll and 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; example = true;
}; };
@@ -87,7 +87,7 @@ in
description = '' description = ''
Extra domains to include in zapret's interception list. Extra domains to include in zapret's interception list.
When syncDirectRouting = true, these domains are also mirrored into When syncDirectRouting = true, these domains are also mirrored into
sing-box direct routing. proxy direct routing.
''; '';
example = [ "youtube.com" ]; example = [ "youtube.com" ];
}; };
@@ -98,7 +98,7 @@ in
description = '' description = ''
Domains to exclude from zapret interception. Domains to exclude from zapret interception.
When syncDirectRouting = true, these exclusions also remove matching 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" ]; example = [ "music.youtube.com" ];
}; };
@@ -108,7 +108,7 @@ in
default = [ ]; default = [ ];
description = '' description = ''
Extra IPs/CIDRs to add to zapret's ipset. 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. syncDirectRoutingUserIps = true.
''; '';
example = [ "203.0.113.0/24" ]; example = [ "203.0.113.0/24" ];
@@ -119,7 +119,7 @@ in
default = [ ]; default = [ ];
description = '' description = ''
IPs/CIDRs to exclude from zapret's ipset. 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. syncDirectRoutingUserIps = true.
''; '';
example = [ "203.0.113.10/32" ]; example = [ "203.0.113.10/32" ];
@@ -134,7 +134,7 @@ in
upstream preset does not already reference them. upstream preset does not already reference them.
When syncDirectRouting = true, domains from these extra lists are also When syncDirectRouting = true, domains from these extra lists are also
mirrored into sing-box direct routing. mirrored into proxy direct routing.
''; '';
example = false; example = false;
}; };
+117 -6
View File
@@ -8,8 +8,8 @@
let let
derived = import ./derived.nix { inherit lib cfg; }; derived = import ./derived.nix { inherit lib cfg; };
r = cfg.singBox.routing; r = cfg.proxy.routing;
singBoxCfg = derived.singBoxCfg; proxyCfg = derived.proxyCfg;
zapretCfg = cfg.zapret; zapretCfg = cfg.zapret;
tgWsProxyCfg = cfg.tgWsProxy; tgWsProxyCfg = cfg.tgWsProxy;
@@ -116,7 +116,12 @@ let
# to "proxy" instead of the original tag (which won't exist in sing-box). # to "proxy" instead of the original tag (which won't exist in sing-box).
resolveTag = resolveTag =
tag: 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. # Collect per-outbound routing attached directly to outbound definitions.
perOutboundRules = lib.concatMap ( perOutboundRules = lib.concatMap (
@@ -134,7 +139,7 @@ let
geoips geoips
; ;
} }
) singBoxCfg.outbounds; ) proxyCfg.outbounds;
# All custom rules in priority order: per-outbound first, then explicit routing.rules. # All custom rules in priority order: per-outbound first, then explicit routing.rules.
customRules = customRules =
@@ -230,7 +235,7 @@ let
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips)) (mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
]; ];
routingRules = singBoxRoutingRules =
commonRules commonRules
++ lib.concatMap (item: item.entries) customRouteRules ++ lib.concatMap (item: item.entries) customRouteRules
++ proxyPrimaryRules ++ proxyPrimaryRules
@@ -239,7 +244,7 @@ let
++ blockRules ++ blockRules
++ proxyGeoRules; ++ proxyGeoRules;
routeModeRules = { singBoxRouteModeRules = {
common = commonRules; common = commonRules;
custom = customRouteRules; custom = customRouteRules;
proxyPrimary = proxyPrimaryRules; proxyPrimary = proxyPrimaryRules;
@@ -249,12 +254,118 @@ let
proxyGeo = proxyGeoRules; 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 in
{ {
inherit inherit
direct direct
geositeRuleSets geositeRuleSets
geoIPRuleSets geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
xrayRoutingRules
xrayRouteModeRules
routeModeRules routeModeRules
routingRules routingRules
; ;
+96 -72
View File
@@ -27,7 +27,11 @@ let
; ;
inherit (derived) inherit (derived)
proxyCfg
singBoxCfg singBoxCfg
proxyEnabled
singBoxEnabled
xrayEnabled
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
globalTproxy globalTproxy
@@ -39,34 +43,46 @@ let
globalTunAutoRouteTable = 2022; globalTunAutoRouteTable = 2022;
featureAssertions = [ featureAssertions = [
(requireAvailable singBoxCfg.enable ( (requireAvailable proxyCfg.singBox.enable proxyEnabled
singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ] "proxy-suite: proxy.singBox.enable requires proxy.enable = true"
) "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") (requireAvailable proxyCfg.xray.enable proxyEnabled
(uniqueValues singBoxCfg.enable subscriptionTags "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" "proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes"
) )
(mkAssertion ( (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") ) "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}" "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
) )
(requireEnabled globalTun.enable singBoxCfg.enable (mkAssertion (
"proxy-suite: singBox.tun.enable requires singBox.enable = true" !(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 (requireEnabled globalTproxy.enable proxyEnabled
"proxy-suite: singBox.tproxy.enable requires singBox.enable = true" "proxy-suite: proxy.tproxy.enable requires proxy.enable = true"
) )
(requireEnabled globalTun.autostart globalTun.enable (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 (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 (mkAssertion
(!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart)) (!(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 (requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable
"proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true" "proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true"
) )
(requireEnabled perAppRoutingCfg.proxychains.enable singBoxCfg.enable (requireEnabled perAppRoutingCfg.proxychains.enable proxyEnabled
"proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true" "proxy-suite: perAppRouting.proxychains.enable requires proxy.enable = true"
) )
(uniqueValues true effectivePerAppRoutingProfileNames (uniqueValues true effectivePerAppRoutingProfileNames
"proxy-suite: perAppRouting profile names must be unique" "proxy-suite: perAppRouting profile names must be unique"
@@ -86,32 +102,32 @@ let
(requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable (requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable
"proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true" "proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true"
) )
(requireAvailable hasProxychainsProfiles singBoxCfg.enable (requireAvailable hasProxychainsProfiles proxyEnabled
"proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true" "proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true"
) )
(requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable (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 (requireEnabled perAppRoutingTun.enable proxyEnabled
"proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true" "proxy-suite: proxy.tun.perApp.enable requires proxy.enable = true"
) )
(requireAvailable hasTunProfiles perAppRoutingTun.enable (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 (requireAvailable hasTunProfiles proxyEnabled
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true" "proxy-suite: route=tun in perAppRouting.profiles requires proxy.enable = true"
) )
(requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable (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 (requireEnabled perAppRoutingTproxy.enable proxyEnabled
"proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true" "proxy-suite: proxy.tproxy.perApp.enable requires proxy.enable = true"
) )
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable (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 (requireAvailable hasTproxyProfiles proxyEnabled
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true" "proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.enable = true"
) )
(requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable (requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true" "proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true"
@@ -126,115 +142,115 @@ let
condition = globalTun.enable && perAppRoutingTun.enable; condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.interface; left = globalTun.interface;
right = perAppRoutingTun.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; condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.address; left = globalTun.address;
right = perAppRoutingTun.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; condition = globalTun.enable && perAppRoutingTun.enable;
left = perAppRoutingTun.routeTable; left = perAppRoutingTun.routeTable;
right = globalTunAutoRouteTable; 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; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
right = globalTproxy.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; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
right = globalTproxy.proxyMark; 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; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.routeTable; left = perAppRoutingTun.routeTable;
right = globalTproxy.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; condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark; left = perAppRoutingTproxy.fwmark;
right = globalTproxy.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; condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark; left = perAppRoutingTproxy.fwmark;
right = globalTproxy.proxyMark; 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; condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.routeTable; left = perAppRoutingTproxy.routeTable;
right = globalTproxy.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; condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
right = perAppRoutingTproxy.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; condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.routeTable; left = perAppRoutingTun.routeTable;
right = perAppRoutingTproxy.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; condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark; left = perAppZapretCfg.filterMark;
right = globalTproxy.fwmark; 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; condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark; left = perAppZapretCfg.filterMark;
right = globalTproxy.proxyMark; 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; condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
right = perAppZapretCfg.filterMark; 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; condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
left = perAppRoutingTproxy.fwmark; left = perAppRoutingTproxy.fwmark;
right = perAppZapretCfg.filterMark; 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; condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark; left = tgWsProxyCfg.routingMark;
right = globalTproxy.fwmark; 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; condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark; left = tgWsProxyCfg.routingMark;
right = globalTproxy.proxyMark; 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; condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
left = tgWsProxyCfg.routingMark; left = tgWsProxyCfg.routingMark;
right = perAppRoutingTun.fwmark; 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; condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
left = tgWsProxyCfg.routingMark; left = tgWsProxyCfg.routingMark;
right = perAppRoutingTproxy.fwmark; 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; condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
@@ -253,47 +269,47 @@ let
{ {
condition = globalTun.enable; condition = globalTun.enable;
value = globalTun.mtu; 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; condition = perAppRoutingTun.enable;
value = perAppRoutingTun.mtu; 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; condition = globalTproxy.enable;
value = globalTproxy.fwmark; 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; condition = globalTproxy.enable;
value = globalTproxy.proxyMark; 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; condition = globalTproxy.enable;
value = globalTproxy.routeTable; 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; condition = perAppRoutingTun.enable;
value = perAppRoutingTun.fwmark; 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; condition = perAppRoutingTun.enable;
value = perAppRoutingTun.routeTable; 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; condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.fwmark; 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; condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.routeTable; 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; condition = perAppZapretCfg.enable;
@@ -312,19 +328,19 @@ let
} }
]; ];
localProxyAuthCfg = singBoxCfg.auth; localProxyAuthCfg = proxyCfg.auth;
localProxyAuthUsed = localProxyAuthUsed =
localProxyAuthCfg.username != null localProxyAuthCfg.username != null
|| localProxyAuthCfg.password != null || localProxyAuthCfg.password != null
|| localProxyAuthCfg.passwordFile != null; || localProxyAuthCfg.passwordFile != null;
localProxyAuthAssertions = [ localProxyAuthAssertions = [
(mkAssertion ( (mkAssertion (
!singBoxCfg.enable || !localProxyAuthUsed || localProxyAuthCfg.username != null !proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
) "proxy-suite: singBox.auth requires username when password or passwordFile is set") ) "proxy-suite: proxy.auth requires username when password or passwordFile is set")
(exactlyOneOf (singBoxCfg.enable && localProxyAuthUsed) [ (exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
localProxyAuthCfg.password localProxyAuthCfg.password
localProxyAuthCfg.passwordFile 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 = forbiddenValueAssertions =
@@ -343,25 +359,25 @@ let
condition = perAppZapretCfg.enable; condition = perAppZapretCfg.enable;
value = globalTproxy.fwmark; value = globalTproxy.fwmark;
disallowed = perAppZapretDesyncMarks; 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; condition = perAppZapretCfg.enable;
value = globalTproxy.proxyMark; value = globalTproxy.proxyMark;
disallowed = perAppZapretDesyncMarks; 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; condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
value = perAppRoutingTun.fwmark; value = perAppRoutingTun.fwmark;
disallowed = perAppZapretDesyncMarks; 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; condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
value = perAppRoutingTproxy.fwmark; value = perAppRoutingTproxy.fwmark;
disallowed = perAppZapretDesyncMarks; 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; condition = perAppZapretCfg.enable;
@@ -385,19 +401,27 @@ let
]; ];
outboundAssertions = lib.concatMap (ob: [ outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf singBoxCfg.enable [ (exactlyOneOf proxyEnabled [
ob.urlFile ob.urlFile
ob.url ob.url
ob.singBoxJson
ob.xrayJson
ob.json ob.json
] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json") ] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json")
]) singBoxCfg.outbounds; (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: [ subscriptionAssertions = lib.concatMap (sub: [
(exactlyOneOf singBoxCfg.enable [ (exactlyOneOf proxyEnabled [
sub.urlFile sub.urlFile
sub.url sub.url
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url") ] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
]) singBoxCfg.subscriptions; ]) proxyCfg.subscriptions;
in in
featureAssertions featureAssertions
++ perAppRoutingAssertions ++ perAppRoutingAssertions
+22 -1
View File
@@ -19,6 +19,12 @@ let
derived = import ../derived.nix { inherit lib cfg; }; derived = import ../derived.nix { inherit lib cfg; };
inherit (derived) inherit (derived)
singBoxCfg singBoxCfg
proxyCfg
xrayCfg
proxyEnabled
singBoxEnabled
xrayEnabled
activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
globalTproxy globalTproxy
@@ -39,6 +45,7 @@ let
jq = "${pkgs.jq}/bin/jq"; jq = "${pkgs.jq}/bin/jq";
python3 = "${pkgs.python3}/bin/python3"; python3 = "${pkgs.python3}/bin/python3";
singBox = "${singBoxCfg.package}/bin/sing-box"; singBox = "${singBoxCfg.package}/bin/sing-box";
xray = "${xrayCfg.package}/bin/xray";
grepBin = "${pkgs.gnugrep}/bin/grep"; grepBin = "${pkgs.gnugrep}/bin/grep";
awk = "${pkgs.gawk}/bin/awk"; awk = "${pkgs.gawk}/bin/awk";
sleepBin = "${pkgs.coreutils}/bin/sleep"; sleepBin = "${pkgs.coreutils}/bin/sleep";
@@ -60,6 +67,11 @@ let
lib lib
pkgs pkgs
singBoxCfg singBoxCfg
proxyCfg
proxyEnabled
singBoxEnabled
xrayEnabled
activeBackend
perAppRoutingCfg perAppRoutingCfg
userControlCfg userControlCfg
perAppRoutingTun perAppRoutingTun
@@ -71,6 +83,7 @@ let
jq jq
python3 python3
singBox singBox
xray
parserScriptsPythonPath parserScriptsPythonPath
buildOutboundPy buildOutboundPy
fetchSubscriptionPy fetchSubscriptionPy
@@ -84,6 +97,7 @@ let
pkgs pkgs
cfg cfg
singBoxCfg singBoxCfg
proxyCfg
perAppRoutingCfg perAppRoutingCfg
perAppRoutingTun perAppRoutingTun
perAppRoutingTproxy perAppRoutingTproxy
@@ -105,13 +119,14 @@ let
inherit inherit
packages packages
singBoxCfg singBoxCfg
proxyCfg
perAppRoutingCfg perAppRoutingCfg
perAppRoutingTun perAppRoutingTun
perAppRoutingTproxy perAppRoutingTproxy
perAppZapretCfg perAppZapretCfg
selectionMode selectionMode
; ;
inherit (scripts) subscriptionTagsFile; inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
inherit (scripts) routeModeStateFile; inherit (scripts) routeModeStateFile;
inherit (perAppRouting) inherit (perAppRouting)
perAppRoutingProfilesFile perAppRoutingProfilesFile
@@ -124,6 +139,12 @@ in
inherit inherit
derived derived
singBoxCfg singBoxCfg
proxyCfg
xrayCfg
proxyEnabled
singBoxEnabled
xrayEnabled
activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
globalTproxy globalTproxy
+4 -1
View File
@@ -2,12 +2,14 @@
{ {
packages, packages,
singBoxCfg, singBoxCfg,
proxyCfg,
perAppRoutingCfg, perAppRoutingCfg,
perAppRoutingTun, perAppRoutingTun,
perAppRoutingTproxy, perAppRoutingTproxy,
perAppZapretCfg, perAppZapretCfg,
selectionMode, selectionMode,
subscriptionTagsFile, subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingProfilesFile, perAppRoutingProfilesFile,
proxychainsConfigFile, proxychainsConfigFile,
proxychainsQuietArg, proxychainsQuietArg,
@@ -19,12 +21,13 @@
selection = selectionMode; selection = selectionMode;
inherit inherit
subscriptionTagsFile subscriptionTagsFile
subscriptionCacheDir
perAppRoutingProfilesFile perAppRoutingProfilesFile
proxychainsConfigFile proxychainsConfigFile
proxychainsQuietArg proxychainsQuietArg
routeModeStateFile 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"; perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0";
perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0"; perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0";
perAppRoutingTunEnabled = if perAppRoutingTun.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, config,
lib, lib,
@@ -55,6 +55,10 @@ let
inherit (derived) inherit (derived)
singBoxCfg singBoxCfg
proxyCfg
proxyEnabled
xrayEnabled
activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
globalTproxy globalTproxy
@@ -82,12 +86,34 @@ let
}; };
localProxyAuthEnabled = localProxyAuthEnabled =
singBoxCfg.auth.username != null proxyCfg.auth.username != null
&& (singBoxCfg.auth.password != null || singBoxCfg.auth.passwordFile != null); && (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
# Must match the explicit iproute2_* indexes written to the global TUN # Must match the explicit iproute2_* indexes written to the global SingBox TUN
# sing-box template in config.nix. # template in config.nix. XRay uses the same table for manual Linux
# policy routing because XRay's autoSystemRoutingTable is not Linux-ready.
tunAutoRouteTableIndex = 2022; 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" '' tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
set -euo pipefail set -euo pipefail
@@ -115,7 +141,7 @@ let
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
set +e 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 # auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop. # interface after `proxy-ctl tun off` or an unclean service stop.
${nft} delete table inet sing-box 2>/dev/null || true ${nft} delete table inet sing-box 2>/dev/null || true
@@ -130,10 +156,10 @@ let
systemServiceEntries = [ systemServiceEntries = [
{ {
enable = singBoxCfg.enable; enable = proxyEnabled;
name = serviceNames.socks; name = serviceNames.socks;
value = mkRestartingService { 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" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
@@ -143,10 +169,10 @@ let
}; };
} }
{ {
enable = singBoxCfg.enable && globalTproxy.enable; enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy; name = serviceNames.tproxy;
value = mkOneshotService { value = mkOneshotService {
description = "sing-box TProxy – nftables rules and policy routing"; description = "proxy-suite TProxy - nftables rules and policy routing";
after = [ after = [
"network.target" "network.target"
"${serviceNames.socks}.service" "${serviceNames.socks}.service"
@@ -162,26 +188,27 @@ let
}; };
} }
{ {
enable = singBoxCfg.enable && globalTun.enable; enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun; name = serviceNames.tun;
value = mkRestartingService { value = mkRestartingService {
description = "sing-box TUN proxy client"; description = "${if xrayEnabled then "XRay" else "sing-box"} TUN proxy client";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ]; conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript; execStartPre = tunCleanupScript;
execStart = scripts.startTun; execStart = scripts.startTun;
execStartPost = if xrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript; execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun; runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
}; };
} }
{ {
enable = singBoxCfg.enable && perAppRoutingTun.enable; enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun; name = serviceNames.perAppTun;
value = mkRestartingService { value = mkRestartingService {
description = "sing-box per-app-routing TUN backend"; description = "proxy-suite per-app-routing TUN backend";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript; execStartPre = perAppRouting.perAppTunDownScript;
@@ -193,7 +220,7 @@ let
}; };
} }
{ {
enable = singBoxCfg.enable && perAppRoutingTun.enable; enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@"; name = "${serviceNames.perAppTun}-user@";
value = mkUserRuleService { value = mkUserRuleService {
description = "Enable proxy-suite app TUN marking for user %i"; 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; name = serviceNames.perAppTproxy;
value = mkOneshotService { value = mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend"; 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@"; name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService { value = mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i"; 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; name = serviceNames.subscriptionUpdate;
value = mkOneshotService { value = mkOneshotService {
description = "Refresh proxy-suite subscription caches"; description = "Refresh proxy-suite subscription caches";
@@ -252,7 +279,7 @@ let
}; };
} }
{ {
enable = singBoxCfg.enable; enable = proxyEnabled;
name = "proxy-suite-route-mode@"; name = "proxy-suite-route-mode@";
value = mkOneshotService { value = mkOneshotService {
description = "Set proxy-suite route mode to %i"; description = "Set proxy-suite route mode to %i";
@@ -282,14 +309,14 @@ let
timerEntries = [ timerEntries = [
{ {
enable = singBoxCfg.enable && hasSubscriptions; enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate; name = serviceNames.subscriptionUpdate;
value = { value = {
description = "Periodic proxy-suite subscription refresh"; description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ]; wantedBy = [ "timers.target" ];
timerConfig = { timerConfig = {
OnBootSec = "5m"; OnBootSec = "5m";
OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval; OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
}; };
}; };
} }
@@ -299,7 +326,7 @@ in
environment.systemPackages = [ control.proxyCtl ]; environment.systemPackages = [ control.proxyCtl ];
# nftables must be on for transparent routing backends. Global TUN uses # 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 ( networking.nftables.enable = lib.mkIf (
globalTun.enable globalTun.enable
|| globalTproxy.enable || globalTproxy.enable
@@ -4,6 +4,7 @@
pkgs, pkgs,
cfg, cfg,
singBoxCfg, singBoxCfg,
proxyCfg,
perAppRoutingCfg, perAppRoutingCfg,
perAppRoutingTun, perAppRoutingTun,
perAppRoutingTproxy, perAppRoutingTproxy,
@@ -62,7 +63,7 @@ let
profile: !(builtins.elem profile.name perAppRoutingProfileNames) profile: !(builtins.elem profile.name perAppRoutingProfileNames)
) defaultPerAppRoutingProfiles; ) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles; effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = singBoxCfg.auth; localProxyAuth = proxyCfg.auth;
localProxyAuthEnabled = localProxyAuthEnabled =
localProxyAuth.username != null localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null); && (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
@@ -83,7 +84,7 @@ let
tcp_connect_time_out 8000 tcp_connect_time_out 8000
[ProxyList] [ProxyList]
socks5 ${singBoxCfg.listenAddress} ${toString singBoxCfg.port} socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
''; '';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q "; 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, lib,
pkgs, pkgs,
singBoxCfg, singBoxCfg,
proxyCfg,
proxyEnabled,
singBoxEnabled,
xrayEnabled,
activeBackend,
perAppRoutingCfg, perAppRoutingCfg,
userControlCfg, userControlCfg,
perAppRoutingTun, perAppRoutingTun,
@@ -12,6 +17,7 @@
jq, jq,
python3, python3,
singBox, singBox,
xray,
parserScriptsPythonPath, parserScriptsPythonPath,
buildOutboundPy, buildOutboundPy,
fetchSubscriptionPy, fetchSubscriptionPy,
@@ -22,9 +28,12 @@
}: }:
let let
globalTproxy = singBoxCfg.tproxy; globalTproxy = proxyCfg.tproxy;
systemctl = "${pkgs.systemd}/bin/systemctl"; 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 = localProxyAuthEnabled =
localProxyAuth.username != null localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null); && (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
@@ -35,7 +44,7 @@ let
pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password
else else
null; null;
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions"; subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
routeModeStateFile = "/run/proxy-suite/route-mode"; routeModeStateFile = "/run/proxy-suite/route-mode";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
@@ -55,7 +64,7 @@ let
in in
'' ''
printf '%s' "$(cat "${urlSource}")" \ 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 '' subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
@@ -83,23 +92,53 @@ let
} }
''; '';
# Build the shell code block for a single outbound entry. routingMarkJq =
# tag overrides ob.tag (used in "first" mode to force tag = "proxy"). routingMark:
# routingMark is null or an int; added to outbound JSON if set. 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 = mkOutboundBlock =
ob: routingMark: tag: ob: routingMark: tag:
let 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 in
if ob.json != null then if backendRaw != null then
let let
outboundJson = builtins.toJSON ( outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
);
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson; jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
in in
'' ''
# outbound: ${tag} (static json) # outbound: ${tag} (static ${backend} json)
OB_JSON=$(cat "${jsonFile}") OB_JSON=$(cat "${jsonFile}")
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'' ''
@@ -109,23 +148,20 @@ let
if ob.urlFile != null then if ob.urlFile != null then
ob.urlFile ob.urlFile
else 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; pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
in in
'' ''
# outbound: ${tag} # outbound: ${tag}
URL=$(cat "${urlSource}") 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") 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 = mkSubscriptionBlock =
sub: routingMark: sub: routingMark:
let let
cacheFile = mkSubscriptionCacheFile sub; cacheFile = mkSubscriptionCacheFile sub;
markFilter = routingMarkJq routingMark;
in in
'' ''
# subscription: ${sub.tag} # subscription: ${sub.tag}
@@ -143,28 +179,28 @@ let
fi fi
if [ -f "$CACHE_FILE" ]; then if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE") SUB_JSON=$(cat "$CACHE_FILE")
${ ${lib.optionalString (routingMark != null) ''
lib.optionalString (routingMark != null) '' SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON") ''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi 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 = mkOutboundScript =
routingMark: routingMark:
let let
outboundBlocks = outboundBlocks =
if collapseNamedOutbounds && singBoxCfg.outbounds != [ ] then if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
# Only the first static outbound, tagged "proxy" so sing-box routes to it. mkOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy"
mkOutboundBlock (builtins.head singBoxCfg.outbounds) routingMark "proxy"
else else
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds; lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings ( subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark sub: mkSubscriptionBlock sub routingMark
) singBoxCfg.subscriptions; ) proxyCfg.subscriptions;
requireOutboundsBlock = '' requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
@@ -174,10 +210,10 @@ let
''; '';
wrapperBlock = wrapperBlock =
if collapseNamedOutbounds then if xrayEnabled && selectionMode == "urltest" then
# When there are no static outbounds, subscription outbounds keep their xrayUrltestTagFilter
# real tags. Rename the first one to "proxy" so routing rules resolve. else if collapseNamedOutbounds then
lib.optionalString (singBoxCfg.outbounds == [ ] && singBoxCfg.subscriptions != [ ]) '' lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) ''
FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON") FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON")
if [ -n "$FIRST_TAG" ]; then if [ -n "$FIRST_TAG" ]; then
OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \ OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \
@@ -195,13 +231,12 @@ let
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'' ''
else else
# urltest
'' ''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \ WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \ --argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg singBoxCfg.urlTest.url} \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg singBoxCfg.urlTest.interval} \ --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}') '{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
@@ -218,8 +253,8 @@ let
printf '%s\n' 'tcp_connect_time_out 8000' printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]' printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \ printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg singBoxCfg.listenAddress} \ ${lib.escapeShellArg proxyCfg.listenAddress} \
${lib.escapeShellArg (toString singBoxCfg.port)} \ ${lib.escapeShellArg (toString proxyCfg.port)} \
${lib.escapeShellArg localProxyAuth.username} \ ${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD" "$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}" } > "${runtimeProxychainsConfig}"
@@ -227,8 +262,6 @@ let
chmod 640 "${runtimeProxychainsConfig}" chmod 640 "${runtimeProxychainsConfig}"
''; '';
modeBaseline = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist";
restartActiveConfigConsumersBlock = lib.concatMapStrings (svc: '' restartActiveConfigConsumersBlock = lib.concatMapStrings (svc: ''
if ${systemctl} is-active --quiet ${svc}; then if ${systemctl} is-active --quiet ${svc}; then
${systemctl} restart ${svc} ${systemctl} restart ${svc}
@@ -239,6 +272,103 @@ let
"proxy-suite-per-app-tun" "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 = mkStartScript =
{ {
name, name,
@@ -266,68 +396,7 @@ let
${writeProxychainsConfigBlock} ${writeProxychainsConfigBlock}
''} ''}
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then ${routeModeCaseBlock}
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
${mkOutboundScript routingMark} ${mkOutboundScript routingMark}
@@ -341,22 +410,13 @@ let
--arg route_final "$ROUTE_FINAL" \ --arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \ --arg dns_final "$DNS_FINAL" \
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \ --argjson clear_dns_rules "$CLEAR_DNS_RULES" \
'.outbounds = $obs + .outbounds '${mkBackendJqFilter}' \
| 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' \
"${configFile}" > "$RUNTIME_DIR/config.json" "${configFile}" > "$RUNTIME_DIR/config.json"
${lib.optionalString enableLocalProxyAuth '' ${lib.optionalString enableLocalProxyAuth ''
chmod 600 "$RUNTIME_DIR/config.json" chmod 600 "$RUNTIME_DIR/config.json"
''} ''}
exec ${singBox} run -c "$RUNTIME_DIR/config.json" exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
''; '';
startSocks = mkStartScript { startSocks = mkStartScript {
@@ -371,19 +431,16 @@ let
name = "proxy-suite-start-tun"; name = "proxy-suite-start-tun";
runtimeDir = "/run/proxy-suite-tun"; runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile; configFile = tunFile;
routingMark = null; routingMark = if xrayEnabled then globalTproxy.proxyMark else null;
}; };
startPerAppTun = mkStartScript { startPerAppTun = mkStartScript {
name = "proxy-suite-start-per-app-tun"; name = "proxy-suite-start-per-app-tun";
runtimeDir = "/run/proxy-suite-per-app-tun"; runtimeDir = "/run/proxy-suite-per-app-tun";
configFile = perAppTunFile; 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; routingMark = if globalTproxy.enable then globalTproxy.proxyMark else null;
}; };
# Shell code to fetch a single subscription into the cache (used in update service).
mkSubscriptionFetchBlock = mkSubscriptionFetchBlock =
sub: sub:
let let
@@ -409,7 +466,7 @@ let
mkdir -p "$CACHE_DIR" mkdir -p "$CACHE_DIR"
FAILED=0 FAILED=0
${subscriptionCacheHelpersBlock} ${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions} ${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
if [ "$FAILED" -eq 0 ]; then if [ "$FAILED" -eq 0 ]; then
${restartActiveConfigConsumersBlock} ${restartActiveConfigConsumersBlock}
@@ -449,7 +506,7 @@ let
''; '';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( 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 in
{ {
@@ -460,6 +517,7 @@ in
subscriptionUpdateScript subscriptionUpdateScript
hasSubscriptions hasSubscriptions
subscriptionTagsFile subscriptionTagsFile
subscriptionCacheDir
runtimeProxychainsConfig runtimeProxychainsConfig
; ;
} }
+2 -2
View File
@@ -13,8 +13,8 @@ let
transparentBypassEnabled = transparentBypassEnabled =
t.bypassTransparentProxy t.bypassTransparentProxy
&& cfg.singBox.enable && cfg.proxy.enable
&& (cfg.singBox.tun.enable || cfg.singBox.tproxy.enable); && (cfg.proxy.tun.enable || cfg.proxy.tproxy.enable);
bypassRulePriority = 8999; bypassRulePriority = 8999;
dcArgs = lib.concatMapStrings dcArgs = lib.concatMapStrings
+391 -117
View File
@@ -163,12 +163,16 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox.outbounds = [ proxy = {
{ enable = true;
tag = "primary"; singBox.enable = true;
url = "http://proxy.example.com:8080"; outbounds = [
} {
]; tag = "primary";
url = "http://proxy.example.com:8080";
}
];
};
}; };
}; };
mkFixture = proxySuiteConfig: evalProxySuite [ mkFixture = proxySuiteConfig: evalProxySuite [
@@ -206,7 +210,7 @@ let
customSingBoxPackageFixture = evalProxySuite [ customSingBoxPackageFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.package = customSingBoxPackage; services.proxy-suite.proxy.singBox.package = customSingBoxPackage;
} }
]; ];
customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box"; customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box";
@@ -214,10 +218,145 @@ let
customSingBoxPackageFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart 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 [ routeModeFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.routing = { services.proxy-suite.proxy.routing = {
proxy = { proxy = {
domains = [ "proxy.example" ]; domains = [ "proxy.example" ];
geosites = [ "google" ]; geosites = [ "google" ];
@@ -262,7 +401,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tun.enable = true; proxy.tun.enable = true;
tgWsProxy = { tgWsProxy = {
enable = true; enable = true;
secretFile = "/run/secrets/tg-ws-proxy"; secretFile = "/run/secrets/tg-ws-proxy";
@@ -280,7 +419,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tproxy.enable = true; proxy.tproxy.enable = true;
tgWsProxy = { tgWsProxy = {
enable = true; enable = true;
secretFile = "/run/secrets/tg-ws-proxy"; secretFile = "/run/secrets/tg-ws-proxy";
@@ -293,7 +432,7 @@ let
tgRoutingMarkCollision = mkBadFixture [ tgRoutingMarkCollision = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tproxy.enable = true; proxy.tproxy.enable = true;
tgWsProxy = { tgWsProxy = {
enable = true; enable = true;
secretFile = "/run/secrets/tg-ws-proxy"; secretFile = "/run/secrets/tg-ws-proxy";
@@ -306,24 +445,34 @@ let
duplicateTags = forceEval ( duplicateTags = forceEval (
(mkFixture { (mkFixture {
enable = true; enable = true;
singBox.outbounds = [ proxy = {
{ tag = "dup"; url = "http://one.example.com:8080"; } enable = true;
{ tag = "dup"; url = "http://two.example.com:8080"; } 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 }).config.system.build.toplevel.drvPath
); );
reservedTag = forceEval ( reservedTag = forceEval (
(mkFixture { (mkFixture {
enable = true; 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 }).config.system.build.toplevel.drvPath
); );
unknownRoutingTarget = forceEval ( unknownRoutingTarget = forceEval (
(mkFixture { (mkFixture {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
outbounds = [ { tag = "primary"; url = "http://proxy.example.com:8080"; } ]; outbounds = [ { tag = "primary"; url = "http://proxy.example.com:8080"; } ];
routing.rules = [ { outbound = "missing"; domains = [ "example.com" ]; } ]; routing.rules = [ { outbound = "missing"; domains = [ "example.com" ]; } ];
}; };
@@ -336,7 +485,9 @@ let
networking.firewall.enable = true; networking.firewall.enable = true;
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
tproxy.enable = true; tproxy.enable = true;
outbounds = [ outbounds = [
{ {
@@ -352,7 +503,7 @@ let
tproxyManualFixture = evalProxySuite [ tproxyManualFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.tproxy.enable = true; services.proxy-suite.proxy.tproxy.enable = true;
} }
]; ];
tproxyManualServiceConfig = tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig; tproxyManualServiceConfig = tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig;
@@ -362,7 +513,7 @@ let
tproxyAutostartFixture = evalProxySuite [ tproxyAutostartFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.tproxy = { services.proxy-suite.proxy.tproxy = {
enable = true; enable = true;
autostart = true; autostart = true;
}; };
@@ -372,14 +523,14 @@ let
tunManualFixture = evalProxySuite [ tunManualFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.tun.enable = true; services.proxy-suite.proxy.tun.enable = true;
} }
]; ];
tunAutostartFixture = evalProxySuite [ tunAutostartFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.tun = { services.proxy-suite.proxy.tun = {
enable = true; enable = true;
autostart = true; autostart = true;
}; };
@@ -388,19 +539,19 @@ let
conflictingAutostartModes = mkBadFixture [ conflictingAutostartModes = mkBadFixture [
{ {
services.proxy-suite.singBox = { services.proxy-suite.proxy = {
tproxy = { enable = true; autostart = true; }; tproxy = { enable = true; autostart = true; };
tun = { enable = true; autostart = true; }; tun = { enable = true; autostart = true; };
}; };
} }
]; ];
globalTunWithoutSingBox = mkBadFixture [ globalTunWithoutProxy = mkBadFixture [
{ services.proxy-suite.singBox = { enable = false; tun.enable = true; }; } { services.proxy-suite.proxy = { enable = false; tun.enable = true; }; }
]; ];
globalTproxyWithoutSingBox = mkBadFixture [ globalTproxyWithoutProxy = mkBadFixture [
{ services.proxy-suite.singBox = { enable = false; tproxy.enable = true; }; } { services.proxy-suite.proxy = { enable = false; tproxy.enable = true; }; }
]; ];
routingOrFixture = evalProxySuite [ routingOrFixture = evalProxySuite [
@@ -408,7 +559,9 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
outbounds = [ outbounds = [
{ {
tag = "primary"; tag = "primary";
@@ -433,7 +586,7 @@ let
ruDisabledFixture = evalProxySuite [ ruDisabledFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.routing.enableRuDirect = false; services.proxy-suite.proxy.routing.enableRuDirect = false;
} }
]; ];
ruDisabledRules = mkRoutingRules ruDisabledFixture; ruDisabledRules = mkRoutingRules ruDisabledFixture;
@@ -442,7 +595,7 @@ let
ruExplicitFixture = evalProxySuite [ ruExplicitFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.routing = { services.proxy-suite.proxy.routing = {
enableRuDirect = false; enableRuDirect = false;
direct.geosites = [ "category-ru" ]; direct.geosites = [ "category-ru" ];
}; };
@@ -453,7 +606,7 @@ let
dnsLocalOverrideFixture = evalProxySuite [ dnsLocalOverrideFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.dns.local = { services.proxy-suite.proxy.dns.local = {
type = "tcp"; type = "tcp";
address = "9.9.9.9"; address = "9.9.9.9";
port = 5353; port = 5353;
@@ -465,7 +618,7 @@ let
dnsRemoteOverrideFixture = evalProxySuite [ dnsRemoteOverrideFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.dns.remote = { services.proxy-suite.proxy.dns.remote = {
type = "tls"; type = "tls";
address = "1.0.0.1"; address = "1.0.0.1";
port = 853; port = 853;
@@ -672,7 +825,7 @@ let
proxyDirectFixture = evalProxySuite [ proxyDirectFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.proxyByDefault = false; services.proxy-suite.proxy.proxyByDefault = false;
} }
]; ];
proxyDirectConfig = mkTProxyConfig proxyDirectFixture; proxyDirectConfig = mkTProxyConfig proxyDirectFixture;
@@ -703,12 +856,16 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox.subscriptions = [ proxy = {
{ enable = true;
tag = "community"; singBox.enable = true;
url = "https://example.com/sub/token"; subscriptions = [
} {
]; tag = "community";
url = "https://example.com/sub/token";
}
];
};
}; };
} }
]; ];
@@ -736,7 +893,9 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
outbounds = [ outbounds = [
{ {
tag = "own-vps"; tag = "own-vps";
@@ -760,10 +919,14 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox.subscriptions = [ proxy = {
{ tag = "dup"; url = "https://example.com/sub/one"; } enable = true;
{ tag = "dup"; url = "https://example.com/sub/two"; } 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"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; 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"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
subscriptions = [ subscriptions = [
{ {
tag = "community"; tag = "community";
@@ -802,7 +971,9 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
subscriptions = [ subscriptions = [
{ {
tag = "community"; tag = "community";
@@ -825,12 +996,16 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox.subscriptions = [ proxy = {
{ enable = true;
tag = "private"; singBox.enable = true;
urlFile = "/run/secrets/sub-url"; subscriptions = [
} {
]; tag = "private";
urlFile = "/run/secrets/sub-url";
}
];
};
}; };
} }
]; ];
@@ -840,7 +1015,9 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox = { proxy = {
enable = true;
singBox.enable = true;
outbounds = [ outbounds = [
{ {
tag = "test-proxy"; tag = "test-proxy";
@@ -851,8 +1028,8 @@ let
urlTest = { urlTest = {
url = "https://telegram.org"; url = "https://telegram.org";
interval = "1m"; interval = "1m";
tolerance = 100;
}; };
singBox.urlTest.tolerance = 100;
}; };
}; };
} }
@@ -888,7 +1065,7 @@ let
localProxyAuthFixture = evalProxySuite [ localProxyAuthFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.auth = { services.proxy-suite.proxy.auth = {
username = "local-user"; username = "local-user";
password = "local-pass"; password = "local-pass";
}; };
@@ -902,7 +1079,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.auth = { proxy.auth = {
username = "local-user"; username = "local-user";
passwordFile = "/run/secrets/local-proxy-password"; passwordFile = "/run/secrets/local-proxy-password";
}; };
@@ -941,7 +1118,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { proxy = {
tun.perApp.enable = true; tun.perApp.enable = true;
tproxy.perApp.enable = true; tproxy.perApp.enable = true;
}; };
@@ -971,7 +1148,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tun.perApp.enable = true; proxy.tun.perApp.enable = true;
perAppRouting = { perAppRouting = {
enable = true; enable = true;
createDefaultProfiles = true; createDefaultProfiles = true;
@@ -999,7 +1176,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { proxy = {
tproxy.enable = true; tproxy.enable = true;
tun.perApp.enable = true; tun.perApp.enable = true;
}; };
@@ -1029,7 +1206,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tproxy.perApp.enable = true; proxy.tproxy.perApp.enable = true;
perAppRouting = { perAppRouting = {
enable = true; enable = true;
createDefaultProfiles = true; createDefaultProfiles = true;
@@ -1059,46 +1236,46 @@ let
} }
]; ];
perAppRoutingProxychainsWithoutSingBox = mkBadFixture [ perAppRoutingProxychainsWithoutProxy = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.enable = false; proxy.enable = false;
perAppRouting = { enable = true; proxychains.enable = true; }; perAppRouting = { enable = true; proxychains.enable = true; };
}; };
} }
]; ];
perAppRoutingTunBackendWithoutSingBox = mkBadFixture [ perAppRoutingTunBackendWithoutProxy = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { enable = false; tun.perApp.enable = true; }; proxy = { enable = false; tun.perApp.enable = true; };
perAppRouting.enable = true; perAppRouting.enable = true;
}; };
} }
]; ];
perAppRoutingTproxyBackendWithoutSingBox = mkBadFixture [ perAppRoutingTproxyBackendWithoutProxy = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { enable = false; tproxy.perApp.enable = true; }; proxy = { enable = false; tproxy.perApp.enable = true; };
perAppRouting.enable = true; perAppRouting.enable = true;
}; };
} }
]; ];
perAppRoutingTunProfileWithoutSingBox = mkBadFixture [ perAppRoutingTunProfileWithoutProxy = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.enable = false; proxy.enable = false;
perAppRouting = { enable = true; profiles = [ { name = "game"; route = "tun"; } ]; }; perAppRouting = { enable = true; profiles = [ { name = "game"; route = "tun"; } ]; };
}; };
} }
]; ];
perAppRoutingTproxyProfileWithoutSingBox = mkBadFixture [ perAppRoutingTproxyProfileWithoutProxy = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.enable = false; proxy.enable = false;
perAppRouting = { enable = true; profiles = [ { name = "browser"; route = "tproxy"; } ]; }; perAppRouting = { enable = true; profiles = [ { name = "browser"; route = "tproxy"; } ]; };
}; };
} }
@@ -1179,7 +1356,7 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tun.perApp.enable = true; proxy.tun.perApp.enable = true;
perAppRouting = { perAppRouting = {
enable = true; enable = true;
createDefaultProfiles = true; createDefaultProfiles = true;
@@ -1237,7 +1414,7 @@ let
perAppRoutingTunFwmarkCollision = mkBadFixture [ perAppRoutingTunFwmarkCollision = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { proxy = {
tproxy = { enable = true; proxyMark = 16; }; tproxy = { enable = true; proxyMark = 16; };
tun.perApp = { enable = true; fwmark = 16; }; tun.perApp = { enable = true; fwmark = 16; };
}; };
@@ -1249,7 +1426,7 @@ let
perAppRoutingTproxyFwmarkCollision = mkBadFixture [ perAppRoutingTproxyFwmarkCollision = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox.tproxy = { proxyMark = 17; perApp = { enable = true; fwmark = 17; }; }; proxy.tproxy = { proxyMark = 17; perApp = { enable = true; fwmark = 17; }; };
perAppRouting.enable = true; perAppRouting.enable = true;
}; };
} }
@@ -1258,7 +1435,7 @@ let
perAppRoutingTunTproxyFwmarkCollision = mkBadFixture [ perAppRoutingTunTproxyFwmarkCollision = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { proxy = {
tun.perApp = { enable = true; fwmark = 23; }; tun.perApp = { enable = true; fwmark = 23; };
tproxy.perApp = { enable = true; fwmark = 23; }; tproxy.perApp = { enable = true; fwmark = 23; };
}; };
@@ -1270,7 +1447,7 @@ let
perAppRoutingTunTproxyRouteTableCollision = mkBadFixture [ perAppRoutingTunTproxyRouteTableCollision = mkBadFixture [
{ {
services.proxy-suite = { services.proxy-suite = {
singBox = { proxy = {
tun.perApp = { enable = true; routeTable = 123; }; tun.perApp = { enable = true; routeTable = 123; };
tproxy.perApp = { enable = true; routeTable = 123; }; tproxy.perApp = { enable = true; routeTable = 123; };
}; };
@@ -1283,7 +1460,7 @@ let
{ {
services.proxy-suite = { services.proxy-suite = {
zapret = { enable = true; perApp = { enable = true; filterMark = 268435456; }; }; zapret = { enable = true; perApp = { enable = true; filterMark = 268435456; }; };
singBox.tproxy.proxyMark = 268435456; proxy.tproxy.proxyMark = 268435456;
perAppRouting.enable = true; perAppRouting.enable = true;
}; };
} }
@@ -1293,7 +1470,7 @@ let
{ {
services.proxy-suite = { services.proxy-suite = {
zapret = { enable = true; perApp = { enable = true; filterMark = 23; }; }; 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; perAppRouting.enable = true;
}; };
} }
@@ -1305,9 +1482,13 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox.subscriptions = [ proxy = {
{ tag = "bad"; url = "https://example.com/sub/token"; urlFile = "/run/secrets/sub-url"; } 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 [ subscriptionNoSources = mkBadFixtureRaw [
{ {
system.stateVersion = "26.05"; 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 [ localProxyAuthNoPassword = mkBadFixture [
{ services.proxy-suite.singBox.auth.username = "local-user"; } { services.proxy-suite.proxy.auth.username = "local-user"; }
]; ];
localProxyAuthNoUsername = mkBadFixture [ localProxyAuthNoUsername = mkBadFixture [
{ services.proxy-suite.singBox.auth.password = "local-pass"; } { services.proxy-suite.proxy.auth.password = "local-pass"; }
]; ];
localProxyAuthBothPasswordSources = mkBadFixture [ localProxyAuthBothPasswordSources = mkBadFixture [
{ {
services.proxy-suite.singBox.auth = { services.proxy-suite.proxy.auth = {
username = "local-user"; username = "local-user";
password = "local-pass"; password = "local-pass";
passwordFile = "/run/secrets/local-proxy-password"; passwordFile = "/run/secrets/local-proxy-password";
@@ -1337,14 +1525,30 @@ let
} }
]; ];
noProxyBackendDefaultFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite.enable = true;
}
];
noOutboundsNoSubscriptions = mkBadFixtureRaw [ 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 [ blockGeoFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite.singBox.routing.block = { services.proxy-suite.proxy.routing.block = {
geosites = [ "category-ads-all" ]; geosites = [ "category-ads-all" ];
geoips = [ "cn" ]; geoips = [ "cn" ];
}; };
@@ -1364,10 +1568,10 @@ let
validated = builtins.all (x: x) [ 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 true
) )
# -- singBox.auth: default mixed inbound stays unauthenticated -- # -- proxy.auth: default mixed inbound stays unauthenticated --
( (
let let
mixedInbound = builtins.head ( mixedInbound = builtins.head (
@@ -1377,7 +1581,7 @@ let
assert !(mixedInbound ? users); assert !(mixedInbound ? users);
true 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 ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript;
assert pkgs.lib.hasInfix ''--arg user local-user'' 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; assert pkgs.lib.hasInfix ''chmod 600 "$RUNTIME_DIR/config.json"'' localProxyAuthStartScript;
true 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/secrets/local-proxy-password'' localProxyAuthPasswordFileStartScript;
assert pkgs.lib.hasInfix ''/run/proxy-suite-socks/proxychains.conf'' 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; assert pkgs.lib.hasInfix "Proxychains config is not readable" localProxyAuthPasswordFileScript;
true true
) )
# -- singBox.auth: incomplete or conflicting auth config fails -- # -- proxy.auth: incomplete or conflicting auth config fails --
( (
assert localProxyAuthNoPassword.success == false; assert localProxyAuthNoPassword.success == false;
assert localProxyAuthNoUsername.success == false; assert localProxyAuthNoUsername.success == false;
@@ -1448,6 +1652,74 @@ let
assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript; assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript;
true 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; assert duplicateTags.success == false;
true true
@@ -1477,7 +1749,7 @@ let
true 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 == [ ]; assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ];
true true
) )
@@ -1496,7 +1768,7 @@ let
true 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 == [ ]; assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ];
true true
) )
@@ -1533,8 +1805,8 @@ let
true true
) )
( (
assert globalTunWithoutSingBox.success == false; assert globalTunWithoutProxy.success == false;
assert globalTproxyWithoutSingBox.success == false; assert globalTproxyWithoutProxy.success == false;
true true
) )
( (
@@ -1755,7 +2027,7 @@ let
# -- subscription: basic config is accepted -- # -- subscription: basic config is accepted --
( (
assert subscriptionOnlyFixture.config.services.proxy-suite.singBox.subscriptions != [ ]; assert subscriptionOnlyFixture.config.services.proxy-suite.proxy.subscriptions != [ ];
true true
) )
@@ -1842,8 +2114,8 @@ let
# -- subscription/runtime: generated cache paths use the raw validated tag, not shell-escaped quotes -- # -- 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 ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/sing-box/community.json"'' subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix ''/var/lib/proxy-suite/subscriptions/community.json.tmp'' subscriptionOnlyUpdateScript; 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" subscriptionOnlyStartScript);
assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyUpdateScript); assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyUpdateScript);
true true
@@ -1887,7 +2159,7 @@ let
# -- subscription: urlFile form accepted -- # -- subscription: urlFile form accepted --
( (
assert subscriptionUrlFileFixture.config.services.proxy-suite.singBox.subscriptions != [ ]; assert subscriptionUrlFileFixture.config.services.proxy-suite.proxy.subscriptions != [ ];
true true
) )
@@ -2005,8 +2277,8 @@ let
( (
assert pkgs.lib.hasInfix "help)" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "help)" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "show this help message" 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 "enable/disable the proxy backend stack" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "restart active sing-box services" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "restart active global proxy-suite services" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "wrap <profile> -- <cmd>" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "wrap <profile> -- <cmd>" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript;
true true
@@ -2104,7 +2376,7 @@ let
# -- perAppRouting: app TUN applies outbound routing marks when TProxy is enabled -- # -- perAppRouting: app TUN applies outbound routing marks when TProxy is enabled --
( (
let let
expectedMark = perAppRoutingTunWithTproxyFixture.config.services.proxy-suite.singBox.tproxy.proxyMark; expectedMark = perAppRoutingTunWithTproxyFixture.config.services.proxy-suite.proxy.tproxy.proxyMark;
in in
assert builtins.match ".*--routing-mark.*" perAppRoutingTunWithTproxyStartScript != null; assert builtins.match ".*--routing-mark.*" perAppRoutingTunWithTproxyStartScript != null;
assert perAppRoutingTunWithTproxyDirectOutbound.routing_mark == expectedMark; assert perAppRoutingTunWithTproxyDirectOutbound.routing_mark == expectedMark;
@@ -2269,9 +2541,9 @@ let
true true
) )
# -- perAppRouting: proxychains requires singBox.enable -- # -- perAppRouting: proxychains requires proxy.enable --
( (
assert perAppRoutingProxychainsWithoutSingBox.success == false; assert perAppRoutingProxychainsWithoutProxy.success == false;
true true
) )
@@ -2287,29 +2559,29 @@ let
true true
) )
# -- perAppRouting: route=tun requires singBox.tun.perApp.enable -- # -- perAppRouting: route=tun requires proxy.tun.perApp.enable --
( (
assert perAppRoutingTunWithoutEnable.success == false; assert perAppRoutingTunWithoutEnable.success == false;
true true
) )
# -- perAppRouting: app TUN backend requires singBox.enable -- # -- perAppRouting: app TUN backend requires proxy.enable --
( (
assert perAppRoutingTunBackendWithoutSingBox.success == false; assert perAppRoutingTunBackendWithoutProxy.success == false;
assert perAppRoutingTunProfileWithoutSingBox.success == false; assert perAppRoutingTunProfileWithoutProxy.success == false;
true true
) )
# -- perAppRouting: route=tproxy requires singBox.tproxy.perApp.enable -- # -- perAppRouting: route=tproxy requires proxy.tproxy.perApp.enable --
( (
assert perAppRoutingTproxyWithoutEnable.success == false; assert perAppRoutingTproxyWithoutEnable.success == false;
true true
) )
# -- perAppRouting: app TProxy backend requires singBox.enable -- # -- perAppRouting: app TProxy backend requires proxy.enable --
( (
assert perAppRoutingTproxyBackendWithoutSingBox.success == false; assert perAppRoutingTproxyBackendWithoutProxy.success == false;
assert perAppRoutingTproxyProfileWithoutSingBox.success == false; assert perAppRoutingTproxyProfileWithoutProxy.success == false;
true true
) )
@@ -2331,7 +2603,7 @@ let
true 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; assert perAppRoutingTproxyFwmarkCollision.success == false;
true true
@@ -2349,7 +2621,7 @@ let
true 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; assert perAppRoutingZapretFilterMarkCollision.success == false;
true true
@@ -2363,6 +2635,8 @@ let
# -- subscription: no outbounds + no subscriptions fails -- # -- 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; assert noOutboundsNoSubscriptions.success == false;
true true
) )
@@ -2383,11 +2657,11 @@ let
# -- urlTest: defaults are sane -- # -- urlTest: defaults are sane --
( (
let let
cfg = minimal.config.services.proxy-suite.singBox.urlTest; cfg = minimal.config.services.proxy-suite.proxy.urlTest;
in in
assert cfg.url == "https://www.gstatic.com/generate_204"; assert cfg.url == "https://www.gstatic.com/generate_204";
assert cfg.interval == "3m"; assert cfg.interval == "3m";
assert cfg.tolerance == 50; assert minimal.config.services.proxy-suite.proxy.singBox.urlTest.tolerance == 50;
true true
) )
]; ];
+30 -11
View File
@@ -19,22 +19,41 @@ let
]; ];
}; };
filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module"); 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 = sanitizeConfigForDocs =
config: config:
config builtins.removeAttrs config [ "singBox" ]
// { // {
singBox = proxy =
(config.singBox or { }) (config.proxy or { })
// lib.optionalAttrs ((config.singBox or { }) ? package) { // {
package = docPackagePlaceholder; 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 = renderConfigText =
config: config:
lib.replaceStrings [ "\"${docPackagePlaceholder}\"" ] [ "pkgs.sing-box" ] ( lib.replaceStrings
[
"\"${singBoxPackagePlaceholder}\""
"\"${xrayPackagePlaceholder}\""
]
[
"pkgs.sing-box"
"pkgs.xray"
]
(
lib.generators.toPretty { } (sanitizeConfigForDocs config) lib.generators.toPretty { } (sanitizeConfigForDocs config)
); );
mkGeneratedExampleValue = mkGeneratedExampleValue =
option: option:
if (option ? _type) && option._type == "option" then if (option ? _type) && option._type == "option" then
@@ -49,9 +68,9 @@ let
else else
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option); lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option);
defaultConfigText = renderConfigText eval.config.services.proxy-suite; defaultConfigText = renderConfigText eval.config.services.proxy-suite;
exampleConfigText = renderConfigText ( generatedExampleConfig =
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite) lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite);
); exampleConfigText = renderConfigText (builtins.removeAttrs generatedExampleConfig [ "singBox" ]);
repoRoot = toString ../.; repoRoot = toString ../.;
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main"; repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
transformDeclaration = transformDeclaration =
+10 -6
View File
@@ -4,11 +4,15 @@
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
singBox.outbounds = [ proxy = {
{ enable = true;
tag = "primary"; singBox.enable = true;
url = "http://proxy.example.com:8080"; outbounds = [
} {
]; tag = "primary";
url = "http://proxy.example.com:8080";
}
];
};
}; };
} }
+8 -8
View File
@@ -14,7 +14,7 @@ _usage() {
echo "Commands:" echo "Commands:"
echo " help show this help message" echo " help show this help message"
echo " status [--tray] show status of all proxy-suite services" 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 " tproxy on|off enable/disable TProxy transparent mode"
echo " tun on|off enable/disable TUN mode" echo " tun on|off enable/disable TUN mode"
echo " route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" 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 " apps list configured per-app routing profiles"
echo " wrap <profile> -- <cmd> run a command via a perAppRouting profile" echo " wrap <profile> -- <cmd> run a command via a perAppRouting profile"
echo " subscription list show subscriptions, cache age, and proxy count" 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" exit "$status"
} }
@@ -240,11 +240,11 @@ cmd_status() {
cmd_proxy() { cmd_proxy() {
case "${1:-on}" in case "${1:-on}" in
on) 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 systemctl start proxy-suite-socks
;; ;;
off) 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-tproxy
_stop_if_exists proxy-suite-tun _stop_if_exists proxy-suite-tun
systemctl stop proxy-suite-socks systemctl stop proxy-suite-socks
@@ -281,7 +281,7 @@ cmd_route_mode() {
local action local action
if ! _svc_exists proxy-suite-socks; then 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 exit 1
fi fi
@@ -410,13 +410,13 @@ cmd_wrap() {
tun) tun)
_check_no_global_proxy tun _check_no_global_proxy tun
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \ _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" "$@" "proxy-suite-per-app-tun.service" "$@"
;; ;;
tproxy) tproxy)
_check_no_global_proxy tproxy _check_no_global_proxy tproxy
_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \ _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" "$@" "proxy-suite-per-app-tproxy.service" "$@"
;; ;;
zapret) zapret)
@@ -439,7 +439,7 @@ cmd_subscription() {
case "$subcmd" in case "$subcmd" in
list) list)
CACHE_DIR="/var/lib/proxy-suite/subscriptions" CACHE_DIR="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}"
if [ ${#SUB_TAGS[@]} -eq 0 ]; then if [ ${#SUB_TAGS[@]} -eq 0 ]; then
echo "No subscriptions configured." echo "No subscriptions configured."
return return
+2
View File
@@ -7,6 +7,7 @@
clashApi, clashApi,
selection, selection,
subscriptionTagsFile, subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingEnabled, perAppRoutingEnabled,
perAppRoutingProxychainsEnabled, perAppRoutingProxychainsEnabled,
perAppRoutingTunEnabled, perAppRoutingTunEnabled,
@@ -44,6 +45,7 @@ pkgs.symlinkJoin {
--set CLASH_API ${lib.escapeShellArg clashApi} \ --set CLASH_API ${lib.escapeShellArg clashApi} \
--set SELECTION ${lib.escapeShellArg selection} \ --set SELECTION ${lib.escapeShellArg selection} \
--set SUB_TAGS_FILE ${lib.escapeShellArg (toString subscriptionTagsFile)} \ --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_ENABLED ${lib.escapeShellArg perAppRoutingEnabled} \
--set PER_APP_ROUTING_PROXYCHAINS_ENABLED ${lib.escapeShellArg perAppRoutingProxychainsEnabled} \ --set PER_APP_ROUTING_PROXYCHAINS_ENABLED ${lib.escapeShellArg perAppRoutingProxychainsEnabled} \
--set PER_APP_ROUTING_TUN_ENABLED ${lib.escapeShellArg perAppRoutingTunEnabled} \ --set PER_APP_ROUTING_TUN_ENABLED ${lib.escapeShellArg perAppRoutingTunEnabled} \
+4 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 argparse
import json import json
@@ -10,15 +10,16 @@ from proxy_parsing import build_outbound
def main() -> None: def main() -> None:
ap = argparse.ArgumentParser( 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("--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") ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
args = ap.parse_args() args = ap.parse_args()
url = sys.stdin.read().strip() url = sys.stdin.read().strip()
try: 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: except ValueError as exc:
print(f"error: {exc}", file=sys.stderr) print(f"error: {exc}", file=sys.stderr)
sys.exit(1) sys.exit(1)
+4 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 argparse
import json import json
@@ -10,7 +10,7 @@ from proxy_parsing import decode_subscription, fetch_raw, parse_subscription
def main() -> None: def main() -> None:
ap = argparse.ArgumentParser( 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( ap.add_argument(
"--tag-prefix", "--tag-prefix",
@@ -18,6 +18,7 @@ def main() -> None:
dest="tag_prefix", dest="tag_prefix",
help="Prefix for outbound tags, e.g. 'my-sub'.", 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") ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
args = ap.parse_args() args = ap.parse_args()
@@ -33,7 +34,7 @@ def main() -> None:
sys.exit(1) sys.exit(1)
lines = decode_subscription(raw) 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: if not outbounds:
print("error: subscription contained no parseable proxy URIs", file=sys.stderr) 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() 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) scheme = detect_scheme(url)
if scheme not in PARSERS: if scheme not in PARSERS:
raise ValueError(f"unsupported scheme '{scheme}'") 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 routing_mark is not None:
if backend == "xray":
return render_xray_outbound(outbound, routing_mark)
outbound["routing_mark"] = routing_mark outbound["routing_mark"] = routing_mark
elif backend == "xray":
return render_xray_outbound(outbound)
return outbound return outbound
@@ -63,7 +235,7 @@ def make_tag(prefix: str, remark: str, index: int) -> str:
def parse_subscription( 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]: ) -> list[dict]:
outbounds = [] outbounds = []
seen_tags: set[str] = set() seen_tags: set[str] = set()
@@ -84,7 +256,7 @@ def parse_subscription(
tag = f"{base_tag}-{suffix}" tag = f"{base_tag}-{suffix}"
try: try:
outbound = build_outbound(line, tag, routing_mark) outbound = build_outbound(line, tag, routing_mark, backend)
except Exception as exc: except Exception as exc:
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr) print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
continue continue
+20 -4
View File
@@ -16,6 +16,11 @@ SUPPORTED_VLESS_TRANSPORTS = {
"quic", "quic",
} }
SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS | {
"xhttp",
"splithttp",
}
def _qs(query: str) -> dict: def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True)) return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
@@ -79,6 +84,12 @@ def _mk_transport(
return { return {
"type": "quic", "type": "quic",
} }
if normalized in ("xhttp", "splithttp"):
return {
"type": "xhttp",
"host": host_header,
"path": urllib.parse.unquote(path),
}
return None return None
@@ -100,22 +111,25 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
return None, 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") userinfo, host, port, params = _parse_url_parts(url, "vless")
security = params.get("security", "none") security = params.get("security", "none")
transport = params.get("type", "tcp") transport = params.get("type", "tcp")
normalized_transport = transport.lower() normalized_transport = transport.lower()
if "ech" in params: if "ech" in params and backend != "xray":
raise ValueError( raise ValueError(
"unsupported VLESS parameter 'ech': proxy-suite does not translate " "unsupported VLESS parameter 'ech': proxy-suite does not translate "
"share-link ECH blobs into sing-box TLS config" "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( raise ValueError(
f"unsupported VLESS transport '{transport}': proxy-suite only maps " 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 = { ob: dict = {
@@ -138,6 +152,8 @@ def parse_vless(url: str, tag: str) -> dict:
ob["tls"] = _mk_tls( ob["tls"] = _mk_tls(
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn") 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( tr = _mk_transport(
normalized_transport, normalized_transport,
+39
View File
@@ -11,6 +11,10 @@ def run_parser(url: str):
return build_outbound(url, "test-outbound") return build_outbound(url, "test-outbound")
def run_xray_parser(url: str):
return build_outbound(url, "test-outbound", backend="xray")
class BuildOutboundTests(unittest.TestCase): class BuildOutboundTests(unittest.TestCase):
def test_vless_reality(self): def test_vless_reality(self):
ob = run_parser( ob = run_parser(
@@ -50,6 +54,41 @@ class BuildOutboundTests(unittest.TestCase):
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com" "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): def test_vless_ech_fails_loudly(self):
with self.assertRaisesRegex(ValueError, "unsupported VLESS parameter 'ech'"): with self.assertRaisesRegex(ValueError, "unsupported VLESS parameter 'ech'"):
run_parser( run_parser(