diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix new file mode 100644 index 0000000..a8709a5 --- /dev/null +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -0,0 +1,195 @@ +# Build-time sing-box backend configuration templates. +# Proxy outbounds are injected at service start time, not here. +{ + lib, + derived, + rules, +}: + +let + constants = derived.constants; + inherit (derived) + proxyCfg + singBoxCfg + hybridEnabled + globalTun + globalTproxy + clashApiEnabled + perAppRoutingTun + ; + inherit (constants) + xrayDnsBridgePorts + ; + direct = rules.direct; + defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex; + defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority; + + mkDnsServer = + tag: upstream: detour: + { + inherit tag; + type = upstream.type; + server = upstream.address; + server_port = upstream.port; + } + // lib.optionalAttrs (detour != null) { inherit detour; }; + + mkDnsConfig = + { + localDetour ? null, + }: + { + servers = [ + (mkDnsServer "remote" proxyCfg.dns.remote "proxy") + (mkDnsServer "local" proxyCfg.dns.local localDetour) + ]; + rules = + lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) { + rule_set = [ "geosite-google" ]; + server = "remote"; + } + ++ lib.optional (direct.geosites != [ ]) { + rule_set = map (s: "geosite-${s}") direct.geosites; + server = "local"; + }; + final = if proxyCfg.proxyByDefault then "remote" else "local"; + }; + + xrayDnsBridgeHijackRule = { + inbound = [ "xray-dns-in" ]; + network = [ + "tcp" + "udp" + ]; + action = "hijack-dns"; + }; + + clashApiBlock = lib.optionalAttrs clashApiEnabled { + experimental.clash_api.external_controller = + "127.0.0.1:${toString singBoxCfg.clashApiPort}"; + }; + + mkConfig = + { + enableMixed ? false, + enableTProxy ? false, + enableTun ? false, + tunInterface ? globalTun.interface, + tunAddress ? globalTun.address, + tunMtu ? globalTun.mtu, + tunAutoRoute ? true, + tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex, + tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority, + tunAutoRedirect ? true, + tunStrictRoute ? true, + forceLocalDnsViaProxy ? false, + useOutboundRoutingMark ? false, + enableClashApi ? clashApiEnabled, + enableXrayDnsBridge ? hybridEnabled, + xrayDnsBridgePort ? xrayDnsBridgePorts.socks, + }: + { + log.level = "warn"; + + dns = mkDnsConfig { + localDetour = if forceLocalDnsViaProxy then "proxy" else null; + }; + + inbounds = + lib.optional enableXrayDnsBridge { + type = "direct"; + tag = "xray-dns-in"; + listen = "127.0.0.1"; + listen_port = xrayDnsBridgePort; + } + ++ lib.optional enableMixed { + type = "mixed"; + tag = "mixed-in"; + listen = proxyCfg.listenAddress; + listen_port = proxyCfg.port; + } + ++ lib.optional enableTProxy { + type = "tproxy"; + tag = "tproxy-in"; + listen = "127.0.0.1"; + listen_port = globalTproxy.port; + } + ++ lib.optional enableTun ( + { + type = "tun"; + tag = "tun-in"; + interface_name = tunInterface; + address = [ tunAddress ]; + mtu = tunMtu; + auto_route = tunAutoRoute; + auto_redirect = tunAutoRedirect; + strict_route = tunStrictRoute; + stack = "mixed"; + } + // lib.optionalAttrs tunAutoRoute { + iproute2_table_index = tunAutoRouteTableIndex; + iproute2_rule_index = tunAutoRouteRuleIndex; + } + ); + + outbounds = [ + ( + { + type = "direct"; + tag = "direct"; + } + // lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; } + ) + { + type = "block"; + tag = "block"; + } + ]; + + route = { + default_domain_resolver = "local"; + rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets; + rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules; + final = if proxyCfg.proxyByDefault then "proxy" else "direct"; + } + // lib.optionalAttrs (enableTun && tunAutoRoute) { + auto_detect_interface = true; + }; + } + // lib.optionalAttrs enableClashApi clashApiBlock; +in +{ + tproxy = mkConfig { + enableMixed = true; + enableTProxy = true; + useOutboundRoutingMark = true; + xrayDnsBridgePort = xrayDnsBridgePorts.socks; + }; + + tun = mkConfig { + enableTun = true; + tunInterface = globalTun.interface; + tunAddress = globalTun.address; + tunMtu = globalTun.mtu; + tunAutoRoute = true; + tunAutoRedirect = true; + tunStrictRoute = true; + forceLocalDnsViaProxy = false; + enableClashApi = false; + xrayDnsBridgePort = xrayDnsBridgePorts.tun; + }; + + perAppTun = mkConfig { + enableTun = true; + tunInterface = perAppRoutingTun.interface; + tunAddress = perAppRoutingTun.address; + tunMtu = perAppRoutingTun.mtu; + tunAutoRoute = false; + tunAutoRedirect = false; + tunStrictRoute = false; + forceLocalDnsViaProxy = false; + useOutboundRoutingMark = globalTproxy.enable; + enableClashApi = false; + xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; + }; +} diff --git a/modules/proxy-suite/config-templates/xray.nix b/modules/proxy-suite/config-templates/xray.nix new file mode 100644 index 0000000..600835b --- /dev/null +++ b/modules/proxy-suite/config-templates/xray.nix @@ -0,0 +1,284 @@ +# Build-time XRay backend configuration templates. +# Proxy outbounds are injected at service start time, not here. +{ + lib, + derived, + rules, +}: + +let + constants = derived.constants; + inherit (derived) + proxyCfg + globalTun + globalTproxy + perAppRoutingTun + ; + inherit (constants) + xrayGlobalTunIPv6Address + xrayPerAppTunIPv6Address + ; + + fakeDnsPools = [ + { + ipPool = "198.18.0.0/15"; + poolSize = 32768; + } + { + ipPool = "fc00::/18"; + poolSize = 32768; + } + ]; + + dnsAddress = + upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address; + + mkDnsServer = tag: upstream: { + address = dnsAddress upstream; + inherit tag; + port = upstream.port; + queryStrategy = "UseIP"; + }; + + mkTunDnsConfig = + { + preferRemote ? proxyCfg.proxyByDefault, + }: + let + primaryTag = if preferRemote then "remote" else "local"; + secondaryTag = if preferRemote then "local" else "remote"; + primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local; + secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote; + in + { + queryStrategy = "UseIP"; + tag = "dns-in"; + servers = [ + { + address = "fakedns"; + tag = "fakedns"; + } + (mkDnsServer primaryTag primaryUpstream) + (mkDnsServer secondaryTag secondaryUpstream) + ]; + }; + + mkSniffing = + { + fakeDnsOnly ? false, + }: + if fakeDnsOnly then + { + enabled = true; + destOverride = [ "fakedns" ]; + metadataOnly = true; + } + else + { + enabled = true; + destOverride = [ + "http" + "tls" + "quic" + ]; + }; + + standardSniffing = mkSniffing { }; + + tunDnsHijackRule = { + type = "field"; + inboundTag = [ "tun-in" ]; + network = "tcp,udp"; + port = 53; + outboundTag = "dns-out"; + ruleTag = "dns-hijack"; + }; + + tunDnsUpstreamRule = { + type = "field"; + inboundTag = [ "dns-in" ]; + network = "tcp,udp"; + outboundTag = "direct"; + ruleTag = "dns-upstream-direct"; + }; + + finalRule = + tag: + { + type = "field"; + network = "tcp,udp"; + ruleTag = "final-default"; + } + // ( + if tag == "proxy" && proxyCfg.selection == "urltest" then + { balancerTag = "proxy"; } + else + { outboundTag = tag; } + ); + + directOutbound = + useOutboundRoutingMark: + { + protocol = "freedom"; + tag = "direct"; + settings = { }; + } + // lib.optionalAttrs useOutboundRoutingMark { + streamSettings.sockopt.mark = globalTproxy.proxyMark; + }; + + mkConfig = + { + enableMixed ? false, + enableTProxy ? false, + enableTun ? false, + tunInterface ? globalTun.interface, + tunAddress ? globalTun.address, + tunIPv6Address ? null, + tunMtu ? globalTun.mtu, + useOutboundRoutingMark ? false, + enableUrlTest ? proxyCfg.selection == "urltest", + domainStrategy ? "IPIfNonMatch", + enableTunFakeDns ? false, + }: + let + tunDnsServers = [ + (if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address) + (if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address) + ]; + tunSniffing = mkSniffing { fakeDnsOnly = enableTunFakeDns; }; + dnsConfig = + if enableTunFakeDns then + mkTunDnsConfig { } + else + { + servers = [ + (mkDnsServer "remote" proxyCfg.dns.remote) + (mkDnsServer "local" proxyCfg.dns.local) + ]; + }; + tunOutbounds = lib.optionals enableTunFakeDns [ + { + protocol = "dns"; + tag = "dns-out"; + settings = { + userLevel = 0; + rules = [ + { + action = "direct"; + qType = "2-27,29-65535"; + } + ]; + }; + } + ]; + routingRules = + lib.optionals enableTunFakeDns [ + tunDnsUpstreamRule + tunDnsHijackRule + ] + ++ rules.xrayRoutingRules + ++ [ (finalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ]; + in + { + log.loglevel = "warning"; + dns = dnsConfig; + inbounds = + lib.optional enableMixed { + tag = "mixed-in"; + protocol = "socks"; + listen = proxyCfg.listenAddress; + port = proxyCfg.port; + settings = { + auth = "noauth"; + udp = true; + ip = proxyCfg.listenAddress; + }; + sniffing = standardSniffing; + } + ++ 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 = standardSniffing; + } + ++ lib.optional enableTun { + tag = "tun-in"; + protocol = "tun"; + settings = { + name = tunInterface; + mtu = tunMtu; + gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ]; + dns = tunDnsServers; + userLevel = 0; + autoOutboundsInterface = "auto"; + }; + sniffing = tunSniffing; + }; + outbounds = tunOutbounds ++ [ + (directOutbound useOutboundRoutingMark) + { + protocol = "blackhole"; + tag = "block"; + settings = { }; + } + ]; + routing = { + domainStrategy = domainStrategy; + domainMatcher = "hybrid"; + rules = routingRules; + } + // 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; + }; + } + // lib.optionalAttrs enableTunFakeDns { fakedns = fakeDnsPools; }; +in +{ + tproxy = mkConfig { + enableMixed = true; + enableTProxy = true; + useOutboundRoutingMark = true; + }; + + tun = mkConfig { + enableTun = true; + tunInterface = globalTun.interface; + tunAddress = globalTun.address; + tunIPv6Address = xrayGlobalTunIPv6Address; + tunMtu = globalTun.mtu; + useOutboundRoutingMark = true; + enableTunFakeDns = true; + }; + + perAppTun = mkConfig { + enableTun = true; + tunInterface = perAppRoutingTun.interface; + tunAddress = perAppRoutingTun.address; + tunIPv6Address = xrayPerAppTunIPv6Address; + tunMtu = perAppRoutingTun.mtu; + useOutboundRoutingMark = true; + enableTunFakeDns = true; + }; +} diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 267cb96..095ffc8 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -9,478 +9,37 @@ let derived = import ./derived.nix { inherit lib cfg; }; - constants = derived.constants; - inherit (derived) - proxyCfg - singBoxCfg - xrayEnabled - hybridEnabled - pureXrayEnabled - globalTun - globalTproxy - clashApiEnabled - ; - inherit (constants) - xrayGlobalTunIPv6Address - xrayPerAppTunIPv6Address - xrayDnsBridgePorts - ; - perAppTun = derived.perAppRoutingTun; - direct = rules.direct; - defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex; - defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority; - xrayFakeDnsPools = [ - { - ipPool = "198.18.0.0/15"; - poolSize = 32768; - } - { - ipPool = "fc00::/18"; - poolSize = 32768; - } - ]; - stripCidr = cidr: builtins.head (lib.splitString "/" cidr); - - mkSingBoxDnsServer = - tag: upstream: detour: - { - inherit tag; - type = upstream.type; - server = upstream.address; - server_port = upstream.port; - } - // lib.optionalAttrs (detour != null) { inherit detour; }; - - mkSingBoxDnsConfig = - { - localDetour ? null, - }: - { - servers = [ - (mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy") - (mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour) - ]; - rules = - lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) { - rule_set = [ "geosite-google" ]; - server = "remote"; - } - ++ lib.optional (direct.geosites != [ ]) { - rule_set = map (s: "geosite-${s}") direct.geosites; - server = "local"; - }; - final = if proxyCfg.proxyByDefault then "remote" else "local"; - }; - - xrayDnsBridgeHijackRule = { - inbound = [ "xray-dns-in" ]; - network = [ - "tcp" - "udp" - ]; - action = "hijack-dns"; + singBoxTemplates = import ./config-templates/sing-box.nix { + inherit + lib + derived + rules + ; + }; + xrayTemplates = import ./config-templates/xray.nix { + inherit + lib + derived + rules + ; }; - clashApiBlock = lib.optionalAttrs clashApiEnabled { - experimental = { - clash_api = { - external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}"; - }; - }; - }; + selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates; + routeModeRules = + if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules; - mkSingBoxConfig = - { - enableMixed ? false, - enableTProxy ? false, - enableTun ? false, - tunInterface ? globalTun.interface, - tunAddress ? globalTun.address, - tunMtu ? globalTun.mtu, - tunAutoRoute ? true, - tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex, - tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority, - tunAutoRedirect ? true, - tunStrictRoute ? true, - forceLocalDnsViaProxy ? false, - useOutboundRoutingMark ? false, - enableClashApi ? clashApiEnabled, - enableXrayDnsBridge ? hybridEnabled, - xrayDnsBridgePort ? xrayDnsBridgePorts.socks, - }: - { - log.level = "warn"; - - dns = mkSingBoxDnsConfig { - localDetour = if forceLocalDnsViaProxy then "proxy" else null; - }; - - inbounds = - lib.optional enableXrayDnsBridge { - type = "direct"; - tag = "xray-dns-in"; - listen = "127.0.0.1"; - listen_port = xrayDnsBridgePort; - } - ++ lib.optional enableMixed { - type = "mixed"; - tag = "mixed-in"; - listen = proxyCfg.listenAddress; - listen_port = proxyCfg.port; - } - ++ lib.optional enableTProxy { - type = "tproxy"; - tag = "tproxy-in"; - listen = "127.0.0.1"; - listen_port = globalTproxy.port; - } - ++ lib.optional enableTun ( - { - type = "tun"; - tag = "tun-in"; - interface_name = tunInterface; - address = [ tunAddress ]; - mtu = tunMtu; - auto_route = tunAutoRoute; - auto_redirect = tunAutoRedirect; - strict_route = tunStrictRoute; - stack = "mixed"; - } - // lib.optionalAttrs tunAutoRoute { - iproute2_table_index = tunAutoRouteTableIndex; - iproute2_rule_index = tunAutoRouteRuleIndex; - } - ); - - outbounds = [ - ( - { - type = "direct"; - tag = "direct"; - } - // lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; } - ) - { - type = "block"; - tag = "block"; - } - ]; - - route = { - default_domain_resolver = "local"; - rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets; - rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules; - final = if proxyCfg.proxyByDefault then "proxy" else "direct"; - } - // lib.optionalAttrs (enableTun && tunAutoRoute) { - auto_detect_interface = true; - }; - } - // lib.optionalAttrs enableClashApi clashApiBlock; - - xrayDnsAddress = - upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address; - - mkXrayDnsServer = tag: upstream: { - address = xrayDnsAddress upstream; - inherit tag; - port = upstream.port; - queryStrategy = "UseIP"; - }; - - mkXraySniffing = - { - fakeDnsOnly ? false, - }: - if fakeDnsOnly then - { - enabled = true; - destOverride = [ "fakedns" ]; - metadataOnly = true; - } - else - { - enabled = true; - destOverride = [ - "http" - "tls" - "quic" - ]; - }; - - xraySniffing = mkXraySniffing { }; - - mkXrayTunDnsConfig = - { - preferRemote ? proxyCfg.proxyByDefault, - }: - let - primaryTag = if preferRemote then "remote" else "local"; - secondaryTag = if preferRemote then "local" else "remote"; - primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local; - secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote; - in - { - queryStrategy = "UseIP"; - tag = "dns-in"; - servers = [ - { - address = "fakedns"; - tag = "fakedns"; - } - (mkXrayDnsServer primaryTag primaryUpstream) - (mkXrayDnsServer secondaryTag secondaryUpstream) - ]; - }; - - xrayTunDnsHijackRule = { - type = "field"; - inboundTag = [ "tun-in" ]; - network = "tcp,udp"; - port = 53; - outboundTag = "dns-out"; - ruleTag = "dns-hijack"; - }; - - xrayTunDnsUpstreamRule = { - type = "field"; - inboundTag = [ "dns-in" ]; - network = "tcp,udp"; - outboundTag = "direct"; - ruleTag = "dns-upstream-direct"; - }; - - xrayFinalRule = - tag: - { - type = "field"; - network = "tcp,udp"; - ruleTag = "final-default"; - } - // ( - 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, - tunIPv6Address ? null, - tunMtu ? globalTun.mtu, - useOutboundRoutingMark ? false, - enableUrlTest ? proxyCfg.selection == "urltest", - domainStrategy ? "IPIfNonMatch", - enableTunFakeDns ? false, - }: - let - tunDnsServers = [ - (if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address) - (if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address) - ]; - xrayTunSniffing = mkXraySniffing { fakeDnsOnly = enableTunFakeDns; }; - xrayDnsConfig = - if enableTunFakeDns then - mkXrayTunDnsConfig { } - else - { - servers = [ - (mkXrayDnsServer "remote" proxyCfg.dns.remote) - (mkXrayDnsServer "local" proxyCfg.dns.local) - ]; - }; - xrayTunOutbounds = lib.optionals enableTunFakeDns [ - { - protocol = "dns"; - tag = "dns-out"; - settings = { - userLevel = 0; - rules = [ - { - action = "direct"; - qType = "2-27,29-65535"; - } - ]; - }; - } - ]; - xrayRoutingRules = - lib.optionals enableTunFakeDns [ - xrayTunDnsUpstreamRule - xrayTunDnsHijackRule - ] - ++ rules.xrayRoutingRules - ++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ]; - in - { - log.loglevel = "warning"; - dns = xrayDnsConfig; - 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 ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ]; - dns = tunDnsServers; - userLevel = 0; - autoOutboundsInterface = "auto"; - }; - sniffing = xrayTunSniffing; - }; - outbounds = xrayTunOutbounds ++ [ - (xrayDirectOutbound useOutboundRoutingMark) - { - protocol = "blackhole"; - tag = "block"; - settings = { }; - } - ]; - routing = { - domainStrategy = domainStrategy; - domainMatcher = "hybrid"; - rules = xrayRoutingRules; - } - // 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; - }; - } - // lib.optionalAttrs enableTunFakeDns { fakedns = xrayFakeDnsPools; }; - - singBoxTproxyTemplate = mkSingBoxConfig { - enableMixed = true; - enableTProxy = true; - useOutboundRoutingMark = true; - xrayDnsBridgePort = xrayDnsBridgePorts.socks; - }; - - singBoxTunTemplate = mkSingBoxConfig { - enableTun = true; - tunInterface = globalTun.interface; - tunAddress = globalTun.address; - tunMtu = globalTun.mtu; - tunAutoRoute = true; - tunAutoRedirect = true; - tunStrictRoute = true; - forceLocalDnsViaProxy = false; - enableClashApi = false; - xrayDnsBridgePort = xrayDnsBridgePorts.tun; - }; - - singBoxPerAppTunTemplate = mkSingBoxConfig { - enableTun = true; - tunInterface = perAppTun.interface; - tunAddress = perAppTun.address; - tunMtu = perAppTun.mtu; - tunAutoRoute = false; - tunAutoRedirect = false; - tunStrictRoute = false; - forceLocalDnsViaProxy = false; - useOutboundRoutingMark = globalTproxy.enable; - enableClashApi = false; - xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; - }; - - xrayTproxyTemplate = mkXrayConfig { - enableMixed = true; - enableTProxy = true; - useOutboundRoutingMark = true; - }; - - xrayTunTemplate = mkXrayConfig { - enableTun = true; - tunInterface = globalTun.interface; - tunAddress = globalTun.address; - tunIPv6Address = xrayGlobalTunIPv6Address; - tunMtu = globalTun.mtu; - useOutboundRoutingMark = true; - enableTunFakeDns = true; - }; - - xrayPerAppTunTemplate = mkXrayConfig { - enableTun = true; - tunInterface = perAppTun.interface; - tunAddress = perAppTun.address; - tunIPv6Address = xrayPerAppTunIPv6Address; - tunMtu = perAppTun.mtu; - useOutboundRoutingMark = true; - enableTunFakeDns = true; - }; - - tproxyTemplate = if pureXrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate; - tunTemplate = if pureXrayEnabled then xrayTunTemplate else singBoxTunTemplate; - perAppTunTemplate = if pureXrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate; - routeModeRules = if pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules; - - tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate); - tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate); + tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" ( + builtins.toJSON selectedTemplates.tproxy + ); + tunFile = pkgs.writeText "proxy-suite-tun-template.json" ( + builtins.toJSON selectedTemplates.tun + ); perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" ( - builtins.toJSON perAppTunTemplate + builtins.toJSON selectedTemplates.perAppTun ); routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" ( builtins.toJSON routeModeRules ); - in { inherit diff --git a/modules/proxy-suite/options/other.nix b/modules/proxy-suite/options/other.nix index 29863f7..782c352 100644 --- a/modules/proxy-suite/options/other.nix +++ b/modules/proxy-suite/options/other.nix @@ -1,13 +1,12 @@ -# Top-level, userControl, tray, and tgWsProxy options. +# Miscellaneous top-level proxy-suite options. { lib, ... }: let inherit (lib) mkOption mkEnableOption types; -in -{ - options.services.proxy-suite = { - enable = mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)"; + tgWsProxyOptions = import ./other/tg-ws-proxy.nix { inherit lib; }; + + userControlOptions = { userControl = { group = mkOption { type = types.strMatching "^[a-z_][a-z0-9_-]*$"; @@ -40,7 +39,9 @@ in ''; }; }; + }; + trayOptions = { tray = { enable = mkEnableOption "system tray indicator for proxy-suite"; @@ -65,210 +66,13 @@ in example = true; }; }; - - tgWsProxy = { - enable = mkEnableOption "Telegram MTProto WebSocket proxy"; - - port = mkOption { - type = types.port; - default = 1443; - description = '' - TCP listen port for tg-ws-proxy. - Telegram clients connect to this endpoint when using the local MTProto - WebSocket proxy. - ''; - example = 1076; - }; - - host = mkOption { - type = types.str; - default = "127.0.0.1"; - description = '' - Bind address for tg-ws-proxy. - Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you - intentionally expose the proxy to other hosts. - ''; - example = "127.0.0.1"; - }; - - secret = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - MTProto proxy secret (hex string). Legacy inline form; this value ends up - in the Nix store. Prefer secretFile for real deployments. - - Set exactly one of secret or secretFile when tgWsProxy.enable = true. - Generate one with: openssl rand -hex 16 - ''; - example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - }; - - secretFile = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - Runtime path to a file containing the MTProto proxy secret. - Intended for use with secret managers so the secret stays out of the Nix store. - - Set exactly one of secretFile or secret when tgWsProxy.enable = true. - ''; - example = "/run/secrets/tg-ws-proxy-secret"; - }; - - dcIps = mkOption { - type = types.attrsOf types.str; - default = { }; - description = '' - Mapping of Telegram DC IDs to relay IPs. - Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by - tg-ws-proxy for MTProto relay selection. - ''; - example = { - "2" = "149.154.167.220"; - "4" = "149.154.167.220"; - "203" = "149.154.167.220"; - }; - }; - - verbose = mkOption { - type = types.bool; - default = false; - description = '' - Whether to enable debug logging in tg-ws-proxy. - ''; - example = true; - }; - - logFile = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - Optional path where tg-ws-proxy writes rotating logs. - When unset, tg-ws-proxy logs to stderr only. - ''; - example = "/var/log/tg-ws-proxy.log"; - }; - - logMaxMb = mkOption { - type = types.numbers.positive; - default = 5.0; - description = '' - Maximum tg-ws-proxy log file size in MiB before rotation. - Only used when tgWsProxy.logFile is set. - ''; - example = 10.0; - }; - - logBackups = mkOption { - type = types.ints.positive; - default = 1; - description = '' - Number of rotated tg-ws-proxy log files to keep. - Only used when tgWsProxy.logFile is set. - ''; - example = 3; - }; - - bufKb = mkOption { - type = types.ints.between 4 2147483647; - default = 256; - description = '' - Socket send and receive buffer size for tg-ws-proxy, in KiB. - ''; - example = 512; - }; - - poolSize = mkOption { - type = types.ints.unsigned; - default = 4; - description = '' - WebSocket connection pool size per Telegram DC. - Set to 0 to disable connection pooling. - ''; - example = 8; - }; - - cfProxyDomains = mkOption { - type = types.listOf types.str; - default = [ ]; - description = '' - User-defined Cloudflare-proxied domains used by tg-ws-proxy for - WebSocket fallback. Each entry is passed as a separate - --cfproxy-domain argument. - ''; - example = [ - "cdn.example.com" - "edge.example.net" - ]; - }; - - cfProxyWorkerDomains = mkOption { - type = types.listOf types.str; - default = [ ]; - description = '' - Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback. - These are tried before other fallback methods. - ''; - example = [ "worker.example.com" ]; - }; - - cfProxyFallback = mkOption { - type = types.bool; - default = true; - description = '' - Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when - direct WebSocket routing is unavailable. - ''; - example = false; - }; - - fakeTlsDomain = mkOption { - type = types.nullOr (types.strMatching ".+"); - default = null; - description = '' - Optional SNI domain used to enable tg-ws-proxy Fake TLS masking. - When set, tg-ws-proxy emits an ee-secret connection link. - ''; - example = "www.example.com"; - }; - - proxyProtocol = mkOption { - type = types.bool; - default = false; - description = '' - Whether tg-ws-proxy should accept a PROXY protocol v1 header from a - fronting reverse proxy such as nginx or HAProxy. - ''; - example = true; - }; - - bypassTransparentProxy = mkOption { - type = types.bool; - default = true; - description = '' - Whether to keep tg-ws-proxy's own relay connections out of proxy-suite - transparent routing backends. - - When enabled and global TUN or TProxy mode is configured, the - tg-ws-proxy systemd service receives a packet mark and an earlier - policy-routing rule back to the main table. This prevents global TUN - from routing the local Telegram MTProto relay through the proxy backend again, - which can otherwise break tg-ws-proxy after enabling TUN mode. - ''; - example = true; - }; - - routingMark = mkOption { - type = types.int; - default = 4; - description = '' - Packet mark used by tgWsProxy.bypassTransparentProxy to bypass - proxy-suite transparent routing. Override this only if it collides - with another local policy-routing mark on your host. - ''; - example = 4; - }; - }; }; +in +{ + options.services.proxy-suite = { + enable = lib.mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)"; + } + // userControlOptions + // trayOptions + // tgWsProxyOptions; } diff --git a/modules/proxy-suite/options/other/tg-ws-proxy.nix b/modules/proxy-suite/options/other/tg-ws-proxy.nix new file mode 100644 index 0000000..5390a6c --- /dev/null +++ b/modules/proxy-suite/options/other/tg-ws-proxy.nix @@ -0,0 +1,212 @@ +# Telegram MTProto WebSocket proxy options. +{ lib }: + +let + inherit (lib) mkOption mkEnableOption types; +in +{ + tgWsProxy = { + enable = mkEnableOption "Telegram MTProto WebSocket proxy"; + + port = mkOption { + type = types.port; + default = 1443; + description = '' + TCP listen port for tg-ws-proxy. + Telegram clients connect to this endpoint when using the local MTProto + WebSocket proxy. + ''; + example = 1076; + }; + + host = mkOption { + type = types.str; + default = "127.0.0.1"; + description = '' + Bind address for tg-ws-proxy. + Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you + intentionally expose the proxy to other hosts. + ''; + example = "127.0.0.1"; + }; + + secret = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + MTProto proxy secret (hex string). Legacy inline form; this value ends up + in the Nix store. Prefer secretFile for real deployments. + + Set exactly one of secret or secretFile when tgWsProxy.enable = true. + Generate one with: openssl rand -hex 16 + ''; + example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + }; + + secretFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a file containing the MTProto proxy secret. + Intended for use with secret managers so the secret stays out of the Nix store. + + Set exactly one of secretFile or secret when tgWsProxy.enable = true. + ''; + example = "/run/secrets/tg-ws-proxy-secret"; + }; + + dcIps = mkOption { + type = types.attrsOf types.str; + default = { }; + description = '' + Mapping of Telegram DC IDs to relay IPs. + Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by + tg-ws-proxy for MTProto relay selection. + ''; + example = { + "2" = "149.154.167.220"; + "4" = "149.154.167.220"; + "203" = "149.154.167.220"; + }; + }; + + verbose = mkOption { + type = types.bool; + default = false; + description = '' + Whether to enable debug logging in tg-ws-proxy. + ''; + example = true; + }; + + logFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Optional path where tg-ws-proxy writes rotating logs. + When unset, tg-ws-proxy logs to stderr only. + ''; + example = "/var/log/tg-ws-proxy.log"; + }; + + logMaxMb = mkOption { + type = types.numbers.positive; + default = 5.0; + description = '' + Maximum tg-ws-proxy log file size in MiB before rotation. + Only used when tgWsProxy.logFile is set. + ''; + example = 10.0; + }; + + logBackups = mkOption { + type = types.ints.positive; + default = 1; + description = '' + Number of rotated tg-ws-proxy log files to keep. + Only used when tgWsProxy.logFile is set. + ''; + example = 3; + }; + + bufKb = mkOption { + type = types.ints.between 4 2147483647; + default = 256; + description = '' + Socket send and receive buffer size for tg-ws-proxy, in KiB. + ''; + example = 512; + }; + + poolSize = mkOption { + type = types.ints.unsigned; + default = 4; + description = '' + WebSocket connection pool size per Telegram DC. + Set to 0 to disable connection pooling. + ''; + example = 8; + }; + + cfProxyDomains = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + User-defined Cloudflare-proxied domains used by tg-ws-proxy for + WebSocket fallback. Each entry is passed as a separate + --cfproxy-domain argument. + ''; + example = [ + "cdn.example.com" + "edge.example.net" + ]; + }; + + cfProxyWorkerDomains = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback. + These are tried before other fallback methods. + ''; + example = [ "worker.example.com" ]; + }; + + cfProxyFallback = mkOption { + type = types.bool; + default = true; + description = '' + Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when + direct WebSocket routing is unavailable. + ''; + example = false; + }; + + fakeTlsDomain = mkOption { + type = types.nullOr (types.strMatching ".+"); + default = null; + description = '' + Optional SNI domain used to enable tg-ws-proxy Fake TLS masking. + When set, tg-ws-proxy emits an ee-secret connection link. + ''; + example = "www.example.com"; + }; + + proxyProtocol = mkOption { + type = types.bool; + default = false; + description = '' + Whether tg-ws-proxy should accept a PROXY protocol v1 header from a + fronting reverse proxy such as nginx or HAProxy. + ''; + example = true; + }; + + bypassTransparentProxy = mkOption { + type = types.bool; + default = true; + description = '' + Whether to keep tg-ws-proxy's own relay connections out of proxy-suite + transparent routing backends. + + When enabled and global TUN or TProxy mode is configured, the + tg-ws-proxy systemd service receives a packet mark and an earlier + policy-routing rule back to the main table. This prevents global TUN + from routing the local Telegram MTProto relay through the proxy backend again, + which can otherwise break tg-ws-proxy after enabling TUN mode. + ''; + example = true; + }; + + routingMark = mkOption { + type = types.int; + default = 4; + description = '' + Packet mark used by tgWsProxy.bypassTransparentProxy to bypass + proxy-suite transparent routing. Override this only if it collides + with another local policy-routing mark on your host. + ''; + example = 4; + }; + }; +} diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index b65c70a..749788a 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -4,7 +4,7 @@ let inherit (lib) mkOption types; - # Shared routing-rule fields (reused in both outboundType.routing and routing.rules entries) + # Reused in both outboundType.routing and routing.rules entries. routingFields = { domains = mkOption { type = types.listOf types.str; @@ -53,7 +53,6 @@ let }; }; - # An explicit routing rule – associates traffic patterns with a named outbound. routingRuleType = types.submodule { options = { outbound = mkOption { @@ -73,167 +72,12 @@ let // routingFields; }; - subscriptionType = types.submodule { - options = { - tag = mkOption { - type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$"; - description = '' - Unique identifier for this subscription. - Used as a prefix for all outbound tags generated from its proxy list, - e.g. "my-sub" -> tags like "my-sub-Server-DE". - - This value is also used as the subscription cache filename stem under - /var/lib/proxy-suite/subscriptions//, so it must be a safe - identifier. - ''; - example = "community-list"; - }; - - url = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - Literal subscription URL. The response must be a base64-encoded - newline-separated list of proxy URIs (standard v2rayN format) or - a plain-text list of the same. - - This value is embedded in the Nix store. Prefer urlFile for private - subscription links or tokens. - ''; - example = "https://example.com/sub/token123"; - }; - - urlFile = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - Runtime path to a file containing the subscription URL. - Intended for use with secret managers (sops-nix, agenix, etc.). - The file is read at service start time and never lands in the Nix store. - - Set exactly one of urlFile or url for each subscription entry. - ''; - example = "/run/secrets/proxy-subscription-url"; - }; - }; + outboundTypes = import ./types/outbounds.nix { + inherit lib; + inherit routingFields; }; - outboundType = types.submodule { - options = { - tag = mkOption { - type = types.str; - description = '' - Outbound tag used in routing rules and multi-outbound selection. - - With selection = "selector" or "urltest", each outbound keeps its own - tag and can be selected directly. With selection = "first", proxy-suite - routes through a single active outbound tagged "proxy", so individual - proxy tags are mainly useful for documentation and config structure. - ''; - example = "vps-de"; - }; - - urlFile = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - Runtime path to a file containing the proxy URL. - Intended for use with secret managers (sops-nix, agenix, etc.). - The file is read at service start time and never lands in the Nix store. - - Set exactly one of urlFile, url, or json for each outbound. - ''; - example = "/run/secrets/my-proxy-url"; - }; - - url = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - Literal proxy URL. Convenient for non-secret configs, but the URL - will end up in the Nix store. - - Set exactly one of urlFile, url, or json for each outbound. - Prefer urlFile for real credentials. - ''; - example = "hy2://password@example.com:443?sni=example.com"; - }; - - backend = mkOption { - type = types.enum [ - "auto" - "sing-box" - "xray" - ]; - default = "auto"; - description = '' - Backend preference for this outbound when both SingBox and XRay are - enabled. "auto" uses SingBox when the URL or JSON can be represented - there and falls back to XRay for XRay-only transports such as XHTTP - or ECH. Ignored by single-backend configurations. - ''; - example = "xray"; - }; - - singBoxJson = mkOption { - type = types.nullOr types.attrs; - default = null; - description = '' - Raw sing-box outbound configuration as a Nix attribute set. - Embedded directly into the config at build time. The tag field - is overridden by the outbound's tag option. - - Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for - each outbound. - Use this when the proxy definition is easier to generate as native Nix - than as a single URL string. Only valid with the SingBox backend. - ''; - example = { - type = "vless"; - server = "example.com"; - server_port = 443; - uuid = "..."; - }; - }; - - xrayJson = mkOption { - type = types.nullOr types.attrs; - default = null; - description = '' - Raw XRay outbound configuration as a Nix attribute set. - Embedded directly into the config at build time. The tag field is - overridden by the outbound's tag option. - - Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for - each outbound. Only valid with the XRay backend. - ''; - example = { - protocol = "vless"; - settings = { - address = "example.com"; - port = 443; - id = "..."; - encryption = "none"; - }; - }; - }; - - json = mkOption { - type = types.nullOr types.attrs; - default = null; - visible = false; - description = '' - Deprecated alias for singBoxJson. Use singBoxJson instead. - ''; - }; - - # Shorthand for attaching routing rules directly to an outbound definition. - # Traffic matching these patterns is sent to this specific outbound. - # Only meaningful when selection = "selector" or "urltest" (with "first", - # all proxy traffic goes to the single "proxy" outbound anyway). - routing = routingFields; - }; - }; + zapretTypes = import ./types/zapret.nix { inherit lib; }; dnsUpstreamType = types.submodule { options = { @@ -269,155 +113,6 @@ let }; }; - zapretPresetType = types.enum [ - "general" - "google" - "instagram" - "soundcloud" - "twitter" - ]; - - zapretDefaultDomainType = types.enum [ - "general" - "google" - "discord" - "youtube" - "instagram" - "soundcloud" - "twitter" - ]; - - zapretDefaultIpType = types.enum [ - "all" - ]; - - zapretHostlistRuleType = types.submodule { - options = { - name = mkOption { - type = types.strMatching "^[a-z0-9][a-z0-9-]*$"; - description = '' - Custom hostlist name. Used to generate hostlists/list-.txt - inside the derived zapret config directory. - ''; - example = "cloudflare"; - }; - - domains = mkOption { - type = types.listOf types.str; - default = [ ]; - description = '' - Domains written into the generated custom zapret hostlist file. - Can be combined with defaultDomains. - ''; - example = [ - "example.com" - "example.de" - ]; - }; - - defaultDomains = mkOption { - type = types.listOf zapretDefaultDomainType; - default = [ ]; - description = '' - Built-in domain groups copied from zapret-discord-youtube hostlists. - These are expanded and combined with domains. - - Each value maps directly to the same-named upstream file: - "general" uses list-general.txt, "google" uses list-google.txt, - and the remaining values use their corresponding list-.txt. - - "discord" is an alias for "general"; "youtube" is an alias for - "google". - - When "general" or "discord" is used together with configName, the - module also clones the selected config's Discord UDP voice rule - (--filter-l7=discord,stun). - - When preset is unset, use one defaultDomains entry per rule so the - module can infer a single rule family. Split groups into separate - rules when they need different strategies. - ''; - example = [ "google" ]; - }; - - ips = mkOption { - type = types.listOf types.str; - default = [ ]; - description = '' - IPs or CIDRs written into the generated custom zapret ipset file. - Can be combined with defaultIps. - ''; - example = [ - "203.0.113.0/24" - "2001:db8::/32" - ]; - }; - - defaultIps = mkOption { - type = types.listOf zapretDefaultIpType; - default = [ ]; - description = '' - Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets. - - "all" uses the upstream ipset-all.txt list. The upstream bundle does - not split this list by service, so site-specific defaults remain in - defaultDomains. - ''; - example = [ "all" ]; - }; - - preset = mkOption { - type = types.nullOr zapretPresetType; - default = null; - description = '' - Clone this built-in NFQWS rule family for this hostlist. When - configName is set, the family is cloned from that zapret config; - otherwise it is cloned from the active global zapret config. - - When unset and defaultDomains is non-empty, rule families are - inferred from defaultDomains. - ''; - example = "google"; - }; - - configName = mkOption { - type = types.nullOr types.str; - default = null; - description = '' - zapret config name to clone NFQWS rules from for this hostlist. - Names use the same matching rules as services.proxy-suite.zapret.configName. - - This is a higher-level alternative to nfqwsArgs and cannot be used - together with nfqwsArgs. - ''; - example = "general(ALT9)"; - }; - - nfqwsArgs = mkOption { - type = types.listOf types.str; - default = [ ]; - description = '' - Additional NFQWS argument fragments for this hostlist. - The module injects --hostlist=... and trailing --new automatically. - - This cannot be used together with configName. - ''; - example = [ - "--filter-tcp=443 --dpi-desync=fake,multisplit" - ]; - }; - - enableDirectSync = mkOption { - type = types.bool; - default = true; - description = '' - Whether this custom hostlist should also be mirrored into proxy - direct domain routing when zapret.syncDirectRouting = true. - ''; - }; - }; - }; - perAppRoutingProfileType = types.submodule { options = { name = mkOption { @@ -459,19 +154,14 @@ let }; }; }; - in { inherit + dnsUpstreamType + perAppRoutingProfileType routingFields routingRuleType - subscriptionType - outboundType - dnsUpstreamType - zapretDefaultDomainType - zapretDefaultIpType - zapretPresetType - zapretHostlistRuleType - perAppRoutingProfileType ; } +// outboundTypes +// zapretTypes diff --git a/modules/proxy-suite/options/types/outbounds.nix b/modules/proxy-suite/options/types/outbounds.nix new file mode 100644 index 0000000..6e0c8f4 --- /dev/null +++ b/modules/proxy-suite/options/types/outbounds.nix @@ -0,0 +1,171 @@ +# Subscription and outbound option type definitions. +{ lib, routingFields }: + +let + inherit (lib) mkOption types; + + subscriptionType = types.submodule { + options = { + tag = mkOption { + type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$"; + description = '' + Unique identifier for this subscription. + Used as a prefix for all outbound tags generated from its proxy list, + e.g. "my-sub" -> tags like "my-sub-Server-DE". + + This value is also used as the subscription cache filename stem under + /var/lib/proxy-suite/subscriptions//, so it must be a safe + identifier. + ''; + example = "community-list"; + }; + + url = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Literal subscription URL. The response must be a base64-encoded + newline-separated list of proxy URIs (standard v2rayN format) or + a plain-text list of the same. + + This value is embedded in the Nix store. Prefer urlFile for private + subscription links or tokens. + ''; + example = "https://example.com/sub/token123"; + }; + + urlFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a file containing the subscription URL. + Intended for use with secret managers (sops-nix, agenix, etc.). + The file is read at service start time and never lands in the Nix store. + + Set exactly one of urlFile or url for each subscription entry. + ''; + example = "/run/secrets/proxy-subscription-url"; + }; + }; + }; + + outboundType = types.submodule { + options = { + tag = mkOption { + type = types.str; + description = '' + Outbound tag used in routing rules and multi-outbound selection. + + With selection = "selector" or "urltest", each outbound keeps its own + tag and can be selected directly. With selection = "first", proxy-suite + routes through a single active outbound tagged "proxy", so individual + proxy tags are mainly useful for documentation and config structure. + ''; + example = "vps-de"; + }; + + urlFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a file containing the proxy URL. + Intended for use with secret managers (sops-nix, agenix, etc.). + The file is read at service start time and never lands in the Nix store. + + Set exactly one of urlFile, url, or json for each outbound. + ''; + example = "/run/secrets/my-proxy-url"; + }; + + url = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Literal proxy URL. Convenient for non-secret configs, but the URL + will end up in the Nix store. + + Set exactly one of urlFile, url, or json for each outbound. + Prefer urlFile for real credentials. + ''; + example = "hy2://password@example.com:443?sni=example.com"; + }; + + backend = mkOption { + type = types.enum [ + "auto" + "sing-box" + "xray" + ]; + default = "auto"; + description = '' + Backend preference for this outbound when both SingBox and XRay are + enabled. "auto" uses SingBox when the URL or JSON can be represented + there and falls back to XRay for XRay-only transports such as XHTTP + or ECH. Ignored by single-backend configurations. + ''; + example = "xray"; + }; + + singBoxJson = mkOption { + type = types.nullOr types.attrs; + default = null; + description = '' + Raw sing-box outbound configuration as a Nix attribute set. + Embedded directly into the config at build time. The tag field + is overridden by the outbound's tag option. + + Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for + each outbound. + Use this when the proxy definition is easier to generate as native Nix + than as a single URL string. Only valid with the SingBox backend. + ''; + example = { + type = "vless"; + server = "example.com"; + server_port = 443; + uuid = "..."; + }; + }; + + xrayJson = mkOption { + type = types.nullOr types.attrs; + default = null; + description = '' + Raw XRay outbound configuration as a Nix attribute set. + Embedded directly into the config at build time. The tag field is + overridden by the outbound's tag option. + + Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for + each outbound. Only valid with the XRay backend. + ''; + example = { + protocol = "vless"; + settings = { + address = "example.com"; + port = 443; + id = "..."; + encryption = "none"; + }; + }; + }; + + json = mkOption { + type = types.nullOr types.attrs; + default = null; + visible = false; + description = '' + Deprecated alias for singBoxJson. Use singBoxJson instead. + ''; + }; + + # Shorthand for attaching routing rules directly to an outbound definition. + # Traffic matching these patterns is sent to this specific outbound. + # Only meaningful when selection = "selector" or "urltest" (with "first", + # all proxy traffic goes to the single "proxy" outbound anyway). + routing = routingFields; + }; + }; +in +{ + inherit subscriptionType outboundType; +} diff --git a/modules/proxy-suite/options/types/zapret.nix b/modules/proxy-suite/options/types/zapret.nix new file mode 100644 index 0000000..5e84a7b --- /dev/null +++ b/modules/proxy-suite/options/types/zapret.nix @@ -0,0 +1,163 @@ +# zapret hostlist and preset option type definitions. +{ lib }: + +let + inherit (lib) mkOption types; + + zapretPresetType = types.enum [ + "general" + "google" + "instagram" + "soundcloud" + "twitter" + ]; + + zapretDefaultDomainType = types.enum [ + "general" + "google" + "discord" + "youtube" + "instagram" + "soundcloud" + "twitter" + ]; + + zapretDefaultIpType = types.enum [ + "all" + ]; + + zapretHostlistRuleType = types.submodule { + options = { + name = mkOption { + type = types.strMatching "^[a-z0-9][a-z0-9-]*$"; + description = '' + Custom hostlist name. Used to generate hostlists/list-.txt + inside the derived zapret config directory. + ''; + example = "cloudflare"; + }; + + domains = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Domains written into the generated custom zapret hostlist file. + Can be combined with defaultDomains. + ''; + example = [ + "example.com" + "example.de" + ]; + }; + + defaultDomains = mkOption { + type = types.listOf zapretDefaultDomainType; + default = [ ]; + description = '' + Built-in domain groups copied from zapret-discord-youtube hostlists. + These are expanded and combined with domains. + + Each value maps directly to the same-named upstream file: + "general" uses list-general.txt, "google" uses list-google.txt, + and the remaining values use their corresponding list-.txt. + + "discord" is an alias for "general"; "youtube" is an alias for + "google". + + When "general" or "discord" is used together with configName, the + module also clones the selected config's Discord UDP voice rule + (--filter-l7=discord,stun). + + When preset is unset, use one defaultDomains entry per rule so the + module can infer a single rule family. Split groups into separate + rules when they need different strategies. + ''; + example = [ "google" ]; + }; + + ips = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + IPs or CIDRs written into the generated custom zapret ipset file. + Can be combined with defaultIps. + ''; + example = [ + "203.0.113.0/24" + "2001:db8::/32" + ]; + }; + + defaultIps = mkOption { + type = types.listOf zapretDefaultIpType; + default = [ ]; + description = '' + Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets. + + "all" uses the upstream ipset-all.txt list. The upstream bundle does + not split this list by service, so site-specific defaults remain in + defaultDomains. + ''; + example = [ "all" ]; + }; + + preset = mkOption { + type = types.nullOr zapretPresetType; + default = null; + description = '' + Clone this built-in NFQWS rule family for this hostlist. When + configName is set, the family is cloned from that zapret config; + otherwise it is cloned from the active global zapret config. + + When unset and defaultDomains is non-empty, rule families are + inferred from defaultDomains. + ''; + example = "google"; + }; + + configName = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + zapret config name to clone NFQWS rules from for this hostlist. + Names use the same matching rules as services.proxy-suite.zapret.configName. + + This is a higher-level alternative to nfqwsArgs and cannot be used + together with nfqwsArgs. + ''; + example = "general(ALT9)"; + }; + + nfqwsArgs = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Additional NFQWS argument fragments for this hostlist. + The module injects --hostlist=... and trailing --new automatically. + + This cannot be used together with configName. + ''; + example = [ + "--filter-tcp=443 --dpi-desync=fake,multisplit" + ]; + }; + + enableDirectSync = mkOption { + type = types.bool; + default = true; + description = '' + Whether this custom hostlist should also be mirrored into proxy + direct domain routing when zapret.syncDirectRouting = true. + ''; + }; + }; + }; +in +{ + inherit + zapretDefaultDomainType + zapretDefaultIpType + zapretPresetType + zapretHostlistRuleType + ; +} diff --git a/modules/proxy-suite/rules-zapret-direct.nix b/modules/proxy-suite/rules-zapret-direct.nix new file mode 100644 index 0000000..86b26f8 --- /dev/null +++ b/modules/proxy-suite/rules-zapret-direct.nix @@ -0,0 +1,112 @@ +{ + lib, + cfg, + zapret, +}: + +let + r = cfg.proxy.routing; + zapretCfg = cfg.zapret; + zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; }; + + trim = lib.strings.trim; + hasPrefix = lib.strings.hasPrefix; + splitString = lib.strings.splitString; + + zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret; + + parseListFile = + path: + lib.unique ( + builtins.filter (line: line != "" && !(hasPrefix "#" line)) ( + map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path))) + ) + ); + + subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items; + + syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting; + syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps; + syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps; + syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps; + + zapretDefaultDomainFiles = [ + "list-general.txt" + "list-google.txt" + ] + ++ lib.optionals zapretCfg.includeExtraUpstreamLists [ + "list-instagram.txt" + "list-soundcloud.txt" + "list-twitter.txt" + ]; + + zapretDefaultDomains = + if syncZapretDirectDomains then + lib.unique ( + lib.concatMap (file: parseListFile "${zapretSrc}/hostlists/${file}") zapretDefaultDomainFiles + ) + else + [ ]; + zapretDefaultIps = + if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ]; + zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ]; + zapretCustomDomains = + if syncZapretDirectDomains then + lib.unique ( + lib.concatMap ( + rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule) + ) zapretCfg.hostlistRules + ) + else + [ ]; + zapretCustomUserIps = + if syncZapretDirectUserIps then + lib.unique ( + lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.hostlistRules + ) + else + [ ]; + zapretCustomDefaultIps = + if syncZapretDirectUpstreamIps then + lib.unique ( + lib.concatMap ( + rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps) + ) zapretCfg.hostlistRules + ) + else + [ ]; + zapretExcludedDomains = + if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ]; + zapretExcludedIps = lib.unique ( + ( + if syncZapretDirectUpstreamIps then + parseListFile "${zapretSrc}/hostlists/ipset-exclude.txt" + else + [ ] + ) + ++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ]) + ); + + zapretDirectDomains = + if syncZapretDirectDomains then + subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) ( + lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude) + ) + else + [ ]; + zapretDirectIps = + if syncZapretDirectAnyIps then + subtractItems ( + lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps) + ) zapretExcludedIps + else + [ ]; +in +{ + direct = { + domains = lib.unique (r.direct.domains ++ zapretDirectDomains); + ips = lib.unique (r.direct.ips ++ zapretDirectIps); + geosites = lib.unique (r.direct.geosites ++ lib.optional r.enableRuDirect "category-ru"); + geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru"); + }; +} diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index a6a3e2e..f8c0a64 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -10,117 +10,16 @@ let derived = import ./derived.nix { inherit lib cfg; }; r = cfg.proxy.routing; proxyCfg = derived.proxyCfg; - zapretCfg = cfg.zapret; tgWsProxyCfg = cfg.tgWsProxy; - zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; }; - - trim = lib.strings.trim; - hasPrefix = lib.strings.hasPrefix; - splitString = lib.strings.splitString; - - zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret; - - parseListFile = - path: - lib.unique ( - builtins.filter (line: line != "" && !(hasPrefix "#" line)) ( - map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path))) - ) - ); - - subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items; - - syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting; - syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps; - syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps; - syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps; - - zapretDefaultDomainFiles = [ - "list-general.txt" - "list-google.txt" - ] - ++ lib.optionals zapretCfg.includeExtraUpstreamLists [ - "list-instagram.txt" - "list-soundcloud.txt" - "list-twitter.txt" - ]; - - zapretDefaultDomains = - if syncZapretDirectDomains then - lib.unique ( - lib.concatMap (file: parseListFile "${zapretSrc}/hostlists/${file}") zapretDefaultDomainFiles - ) - else - [ ]; - zapretDefaultIps = - if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ]; - zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ]; - zapretCustomDomains = - if syncZapretDirectDomains then - lib.unique ( - lib.concatMap ( - rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule) - ) zapretCfg.hostlistRules - ) - else - [ ]; - zapretCustomUserIps = - if syncZapretDirectUserIps then - lib.unique ( - lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.hostlistRules - ) - else - [ ]; - zapretCustomDefaultIps = - if syncZapretDirectUpstreamIps then - lib.unique ( - lib.concatMap ( - rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps) - ) zapretCfg.hostlistRules - ) - else - [ ]; - zapretExcludedDomains = - if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ]; - zapretExcludedIps = lib.unique ( - ( - if syncZapretDirectUpstreamIps then - parseListFile "${zapretSrc}/hostlists/ipset-exclude.txt" - else - [ ] - ) - ++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ]) - ); - - zapretDirectDomains = - if syncZapretDirectDomains then - subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) ( - lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude) - ) - else - [ ]; - zapretDirectIps = - if syncZapretDirectAnyIps then - subtractItems (lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps)) zapretExcludedIps - else - [ ]; - - direct = { - domains = lib.unique (r.direct.domains ++ zapretDirectDomains); - ips = lib.unique (r.direct.ips ++ zapretDirectIps); - geosites = lib.unique (r.direct.geosites ++ lib.optional r.enableRuDirect "category-ru"); - geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru"); + zapretDirect = import ./rules-zapret-direct.nix { + inherit + lib + cfg + zapret + ; }; + inherit (zapretDirect) direct; - mkRule = - field: tag: items: - lib.optional (items != [ ]) { - ${field} = items; - outbound = tag; - }; - mkDomainRule = mkRule "domain_suffix"; - mkIPRule = mkRule "ip_cidr"; - mkRulesetRule = mkRule "rule_set"; customRuleCategory = outbound: if outbound == "direct" then @@ -168,238 +67,36 @@ let customRules = perOutboundRules ++ map (rule: rule // { outbound = resolveTag rule.outbound; }) r.rules; - # Build sing-box routing rule entries from a custom rule record. - mkCustomRuleEntries = - rule: - lib.flatten [ - (mkDomainRule rule.outbound rule.domains) - (mkIPRule rule.outbound rule.ips) - (mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites)) - (mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips)) - ]; - - # All geosite names referenced anywhere (for rule-set file definitions). - allGeositeNames = lib.unique ( - r.proxy.geosites - ++ direct.geosites - ++ r.block.geosites - ++ lib.concatMap (rule: rule.geosites) customRules - ); - - # All geoip names referenced anywhere. - allGeoIPNames = lib.unique ( - r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules - ); - - mkRuleSet = kind: pkg: name: { - tag = "${kind}-${name}"; - type = "local"; - format = "binary"; - path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs"; + singBoxRules = import ./rules/sing-box.nix { + inherit + lib + pkgs + r + direct + tgWsProxyCfg + customRules + customRuleCategory + ; }; + inherit (singBoxRules) + geositeRuleSets + geoIPRuleSets + singBoxRoutingRules + singBoxRouteModeRules + ; - geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames; - geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames; - - commonRules = [ - { - network = [ - "tcp" - "udp" - ]; - port = 53; - action = "hijack-dns"; - } - { action = "sniff"; } - ]; - - customRouteRules = map (rule: { - category = customRuleCategory rule.outbound; - entries = mkCustomRuleEntries rule; - }) customRules; - - proxyPrimaryRules = lib.flatten [ - (mkDomainRule "proxy" r.proxy.domains) - (mkIPRule "proxy" r.proxy.ips) - ]; - - directRules = lib.flatten [ - (mkDomainRule "direct" direct.domains) - (mkIPRule "direct" direct.ips) - (mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites)) - (mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips)) - ]; - - tgWsProxyRelayDirectRules = - lib.optional - (tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { }) - { - ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); - outbound = "direct"; - }; - - safetyDirectRules = [ - { - ip_is_private = true; - outbound = "direct"; - } - ] - ++ tgWsProxyRelayDirectRules; - - blockRules = lib.flatten [ - (mkDomainRule "block" r.block.domains) - (mkIPRule "block" r.block.ips) - (mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites)) - (mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips)) - ]; - - proxyGeoRules = lib.flatten [ - (mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites)) - (mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips)) - ]; - - singBoxRoutingRules = - commonRules - ++ lib.concatMap (item: item.entries) customRouteRules - ++ proxyPrimaryRules - ++ directRules - ++ safetyDirectRules - ++ blockRules - ++ proxyGeoRules; - - singBoxRouteModeRules = { - common = commonRules; - custom = customRouteRules; - proxyPrimary = proxyPrimaryRules; - direct = directRules; - safetyDirect = safetyDirectRules; - block = blockRules; - proxyGeo = proxyGeoRules; - }; - - xrayTarget = - tag: - if tag == "proxy" && derived.selectionMode == "urltest" then - { balancerTag = "proxy"; } - else - { outboundTag = tag; }; - - mkXrayRule = - ruleTag: fields: tag: - ( - { - type = "field"; - inherit ruleTag; - } - // fields - // (xrayTarget tag) - ); - - xrayDomainRules = - ruleTag: tag: domains: - lib.optional (domains != [ ]) ( - mkXrayRule ruleTag { - domain = map (domain: "domain:${domain}") domains; - } tag - ); - - xrayIPRules = - ruleTag: tag: ips: - lib.optional (ips != [ ]) ( - mkXrayRule ruleTag { - ip = ips; - } tag - ); - - xrayGeositeRules = - ruleTag: tag: geosites: - lib.optional (geosites != [ ]) ( - mkXrayRule ruleTag { - domain = map (name: "geosite:${name}") geosites; - } tag - ); - - xrayGeoIPRules = - ruleTag: tag: geoips: - lib.optional (geoips != [ ]) ( - mkXrayRule ruleTag { - ip = map (name: "geoip:${name}") geoips; - } tag - ); - - xrayCustomRuleTag = category: kind: "custom-${category}-${kind}"; - - mkXrayCustomRuleEntries = - rule: - lib.flatten [ - (xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound - rule.domains - ) - (xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips) - (xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound - rule.geosites - ) - (xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound - rule.geoips - ) - ]; - - xrayCustomRouteRules = map (rule: { - category = customRuleCategory rule.outbound; - entries = mkXrayCustomRuleEntries rule; - }) customRules; - - xrayProxyPrimaryRules = lib.flatten [ - (xrayDomainRules "proxy-domain" "proxy" r.proxy.domains) - (xrayIPRules "proxy-ip" "proxy" r.proxy.ips) - ]; - - xrayDirectRules = lib.flatten [ - (xrayDomainRules "direct-domain" "direct" direct.domains) - (xrayIPRules "direct-ip" "direct" direct.ips) - (xrayGeositeRules "direct-geosite" "direct" direct.geosites) - (xrayGeoIPRules "direct-geoip" "direct" direct.geoips) - ]; - - xraySafetyDirectRules = [ - (mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct") - ] - ++ - lib.optional - (tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { }) - ( - mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct" - ); - - xrayBlockRules = lib.flatten [ - (xrayDomainRules "block-domain" "block" r.block.domains) - (xrayIPRules "block-ip" "block" r.block.ips) - (xrayGeositeRules "block-geosite" "block" r.block.geosites) - (xrayGeoIPRules "block-geoip" "block" r.block.geoips) - ]; - - xrayProxyGeoRules = lib.flatten [ - (xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites) - (xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips) - ]; - - xrayRoutingRules = - lib.concatMap (item: item.entries) xrayCustomRouteRules - ++ xrayProxyPrimaryRules - ++ xrayDirectRules - ++ xraySafetyDirectRules - ++ xrayProxyGeoRules - ++ xrayBlockRules; - - xrayRouteModeRules = { - common = [ ]; - custom = xrayCustomRouteRules; - proxyPrimary = xrayProxyPrimaryRules; - direct = xrayDirectRules; - safetyDirect = xraySafetyDirectRules; - block = xrayBlockRules; - proxyGeo = xrayProxyGeoRules; + xrayRules = import ./rules/xray.nix { + inherit + lib + r + direct + tgWsProxyCfg + customRules + customRuleCategory + ; + inherit (derived) selectionMode; }; + inherit (xrayRules) xrayRoutingRules xrayRouteModeRules; routingRules = singBoxRoutingRules; routeModeRules = singBoxRouteModeRules; diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix new file mode 100644 index 0000000..30ceeb9 --- /dev/null +++ b/modules/proxy-suite/rules/sing-box.nix @@ -0,0 +1,136 @@ +# sing-box routing rules and local rule-set definitions. +{ + lib, + pkgs, + r, + direct, + tgWsProxyCfg, + customRules, + customRuleCategory, +}: + +let + mkRule = + field: tag: items: + lib.optional (items != [ ]) { + ${field} = items; + outbound = tag; + }; + mkDomainRule = mkRule "domain_suffix"; + mkIPRule = mkRule "ip_cidr"; + mkRulesetRule = mkRule "rule_set"; + + mkCustomRuleEntries = + rule: + lib.flatten [ + (mkDomainRule rule.outbound rule.domains) + (mkIPRule rule.outbound rule.ips) + (mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites)) + (mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips)) + ]; + + allGeositeNames = lib.unique ( + r.proxy.geosites + ++ direct.geosites + ++ r.block.geosites + ++ lib.concatMap (rule: rule.geosites) customRules + ); + + allGeoIPNames = lib.unique ( + r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules + ); + + mkRuleSet = kind: pkg: name: { + tag = "${kind}-${name}"; + type = "local"; + format = "binary"; + path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs"; + }; + + geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames; + geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames; + + commonRules = [ + { + network = [ + "tcp" + "udp" + ]; + port = 53; + action = "hijack-dns"; + } + { action = "sniff"; } + ]; + + customRouteRules = map (rule: { + category = customRuleCategory rule.outbound; + entries = mkCustomRuleEntries rule; + }) customRules; + + proxyPrimaryRules = lib.flatten [ + (mkDomainRule "proxy" r.proxy.domains) + (mkIPRule "proxy" r.proxy.ips) + ]; + + directRules = lib.flatten [ + (mkDomainRule "direct" direct.domains) + (mkIPRule "direct" direct.ips) + (mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites)) + (mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips)) + ]; + + tgWsProxyRelayDirectRules = + lib.optional + (tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { }) + { + ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); + outbound = "direct"; + }; + + safetyDirectRules = [ + { + ip_is_private = true; + outbound = "direct"; + } + ] + ++ tgWsProxyRelayDirectRules; + + blockRules = lib.flatten [ + (mkDomainRule "block" r.block.domains) + (mkIPRule "block" r.block.ips) + (mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites)) + (mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips)) + ]; + + proxyGeoRules = lib.flatten [ + (mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites)) + (mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips)) + ]; + + singBoxRoutingRules = + commonRules + ++ lib.concatMap (item: item.entries) customRouteRules + ++ proxyPrimaryRules + ++ directRules + ++ safetyDirectRules + ++ blockRules + ++ proxyGeoRules; + + singBoxRouteModeRules = { + common = commonRules; + custom = customRouteRules; + proxyPrimary = proxyPrimaryRules; + direct = directRules; + safetyDirect = safetyDirectRules; + block = blockRules; + proxyGeo = proxyGeoRules; + }; +in +{ + inherit + geositeRuleSets + geoIPRuleSets + singBoxRoutingRules + singBoxRouteModeRules + ; +} diff --git a/modules/proxy-suite/rules/xray.nix b/modules/proxy-suite/rules/xray.nix new file mode 100644 index 0000000..3510597 --- /dev/null +++ b/modules/proxy-suite/rules/xray.nix @@ -0,0 +1,142 @@ +# XRay routing rule definitions. +{ + lib, + r, + direct, + tgWsProxyCfg, + customRules, + customRuleCategory, + selectionMode, +}: + +let + xrayTarget = + tag: + if tag == "proxy" && selectionMode == "urltest" then + { balancerTag = "proxy"; } + else + { outboundTag = tag; }; + + mkXrayRule = + ruleTag: fields: tag: + ( + { + type = "field"; + inherit ruleTag; + } + // fields + // (xrayTarget tag) + ); + + xrayDomainRules = + ruleTag: tag: domains: + lib.optional (domains != [ ]) ( + mkXrayRule ruleTag { + domain = map (domain: "domain:${domain}") domains; + } tag + ); + + xrayIPRules = + ruleTag: tag: ips: + lib.optional (ips != [ ]) ( + mkXrayRule ruleTag { + ip = ips; + } tag + ); + + xrayGeositeRules = + ruleTag: tag: geosites: + lib.optional (geosites != [ ]) ( + mkXrayRule ruleTag { + domain = map (name: "geosite:${name}") geosites; + } tag + ); + + xrayGeoIPRules = + ruleTag: tag: geoips: + lib.optional (geoips != [ ]) ( + mkXrayRule ruleTag { + ip = map (name: "geoip:${name}") geoips; + } tag + ); + + xrayCustomRuleTag = category: kind: "custom-${category}-${kind}"; + + mkXrayCustomRuleEntries = + rule: + lib.flatten [ + (xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound + rule.domains + ) + (xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips) + (xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound + rule.geosites + ) + (xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound + rule.geoips + ) + ]; + + xrayCustomRouteRules = map (rule: { + category = customRuleCategory rule.outbound; + entries = mkXrayCustomRuleEntries rule; + }) customRules; + + xrayProxyPrimaryRules = lib.flatten [ + (xrayDomainRules "proxy-domain" "proxy" r.proxy.domains) + (xrayIPRules "proxy-ip" "proxy" r.proxy.ips) + ]; + + xrayDirectRules = lib.flatten [ + (xrayDomainRules "direct-domain" "direct" direct.domains) + (xrayIPRules "direct-ip" "direct" direct.ips) + (xrayGeositeRules "direct-geosite" "direct" direct.geosites) + (xrayGeoIPRules "direct-geoip" "direct" direct.geoips) + ]; + + xraySafetyDirectRules = [ + (mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct") + ] + ++ + lib.optional + (tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { }) + ( + mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct" + ); + + xrayBlockRules = lib.flatten [ + (xrayDomainRules "block-domain" "block" r.block.domains) + (xrayIPRules "block-ip" "block" r.block.ips) + (xrayGeositeRules "block-geosite" "block" r.block.geosites) + (xrayGeoIPRules "block-geoip" "block" r.block.geoips) + ]; + + xrayProxyGeoRules = lib.flatten [ + (xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites) + (xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips) + ]; + + xrayRoutingRules = + lib.concatMap (item: item.entries) xrayCustomRouteRules + ++ xrayProxyPrimaryRules + ++ xrayDirectRules + ++ xraySafetyDirectRules + ++ xrayProxyGeoRules + ++ xrayBlockRules; + + xrayRouteModeRules = { + common = [ ]; + custom = xrayCustomRouteRules; + proxyPrimary = xrayProxyPrimaryRules; + direct = xrayDirectRules; + safetyDirect = xraySafetyDirectRules; + block = xrayBlockRules; + proxyGeo = xrayProxyGeoRules; + }; +in +{ + inherit + xrayRoutingRules + xrayRouteModeRules + ; +} diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index d34e6bd..3ebb2ba 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -15,21 +15,9 @@ }: let - constants = derived.constants; - assertions = import ./service/assertions-lib.nix { inherit lib; }; - inherit (assertions) - mkAssertion - requireEnabled - requireAvailable - uniqueValues - notEqualWhen - forbiddenValues - exactlyOneOf - ; - inherit (derived) + constants proxyCfg - singBoxCfg proxyEnabled singBoxEnabled xrayEnabled @@ -43,7 +31,27 @@ let perAppZapretCfg ; - globalTunAutoRouteTable = constants.tunAutoRouteTableIndex; + mkAssertion = assertion: message: { inherit assertion message; }; + requireEnabled = + featureEnabled: dependencyEnabled: message: + mkAssertion (!featureEnabled || dependencyEnabled) message; + requireAvailable = + featureUsed: dependencyEnabled: message: + mkAssertion (!featureUsed || dependencyEnabled) message; + uniqueValues = + condition: values: message: + mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message; + exactlyOneOf = + condition: values: message: + mkAssertion ( + !condition || builtins.length (builtins.filter (value: value != null) values) == 1 + ) message; + notEqualWhen = + condition: left: right: message: + mkAssertion (!(condition && left == right)) message; + forbiddenValues = + condition: value: disallowed: message: + mkAssertion (!(condition && builtins.elem value disallowed)) message; featureAssertions = [ (requireAvailable proxyCfg.singBox.enable proxyEnabled @@ -144,6 +152,61 @@ let ) ]; + localProxyAuthCfg = proxyCfg.auth; + localProxyAuthUsed = + localProxyAuthCfg.username != null + || localProxyAuthCfg.password != null + || localProxyAuthCfg.passwordFile != null; + localProxyAuthAssertions = [ + (mkAssertion ( + !proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null + ) "proxy-suite: proxy.auth requires username when password or passwordFile is set") + (exactlyOneOf (proxyEnabled && localProxyAuthUsed) [ + localProxyAuthCfg.password + localProxyAuthCfg.passwordFile + ] "proxy-suite: proxy.auth requires exactly one of password or passwordFile") + ]; + + secretAssertions = [ + (exactlyOneOf tgWsProxyCfg.enable [ + tgWsProxyCfg.secret + tgWsProxyCfg.secretFile + ] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile") + ]; + + outboundAssertions = lib.concatMap (ob: [ + (exactlyOneOf proxyEnabled + [ + ob.urlFile + ob.url + ob.singBoxJson + ob.xrayJson + ob.json + ] + "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json" + ) + (mkAssertion ( + !singBoxEnabled || hybridEnabled || ob.xrayJson == null + ) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true") + (mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null)) + "proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true" + ) + (mkAssertion ( + !(ob.backend == "xray") || xrayEnabled + ) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true") + (mkAssertion ( + !(ob.backend == "sing-box") || singBoxEnabled + ) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true") + ]) proxyCfg.outbounds; + + subscriptionAssertions = lib.concatMap (sub: [ + (exactlyOneOf proxyEnabled [ + sub.urlFile + sub.url + ] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url") + ]) proxyCfg.subscriptions; + + globalTunAutoRouteTable = constants.tunAutoRouteTableIndex; collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [ { condition = globalTun.enable && perAppRoutingTun.enable; @@ -272,7 +335,6 @@ let 67108864 134217728 ]; - positiveNumberAssertions = map (item: mkAssertion (!item.condition || item.value > 0) item.message) [ @@ -338,21 +400,6 @@ let } ]; - localProxyAuthCfg = proxyCfg.auth; - localProxyAuthUsed = - localProxyAuthCfg.username != null - || localProxyAuthCfg.password != null - || localProxyAuthCfg.passwordFile != null; - localProxyAuthAssertions = [ - (mkAssertion ( - !proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null - ) "proxy-suite: proxy.auth requires username when password or passwordFile is set") - (exactlyOneOf (proxyEnabled && localProxyAuthUsed) [ - localProxyAuthCfg.password - localProxyAuthCfg.passwordFile - ] "proxy-suite: proxy.auth requires exactly one of password or passwordFile") - ]; - forbiddenValueAssertions = map (item: forbiddenValues item.condition item.value item.disallowed item.message) [ @@ -402,52 +449,13 @@ let message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits"; } ]; - - secretAssertions = [ - (exactlyOneOf tgWsProxyCfg.enable [ - tgWsProxyCfg.secret - tgWsProxyCfg.secretFile - ] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile") - ]; - - outboundAssertions = lib.concatMap (ob: [ - (exactlyOneOf proxyEnabled - [ - ob.urlFile - ob.url - ob.singBoxJson - ob.xrayJson - ob.json - ] - "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json" - ) - (mkAssertion ( - !singBoxEnabled || hybridEnabled || ob.xrayJson == null - ) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true") - (mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null)) - "proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true" - ) - (mkAssertion ( - !(ob.backend == "xray") || xrayEnabled - ) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true") - (mkAssertion ( - !(ob.backend == "sing-box") || singBoxEnabled - ) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true") - ]) proxyCfg.outbounds; - - subscriptionAssertions = lib.concatMap (sub: [ - (exactlyOneOf proxyEnabled [ - sub.urlFile - sub.url - ] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url") - ]) proxyCfg.subscriptions; in featureAssertions ++ perAppRoutingAssertions -++ collisionAssertions -++ positiveNumberAssertions ++ localProxyAuthAssertions -++ forbiddenValueAssertions ++ secretAssertions ++ outboundAssertions ++ subscriptionAssertions +++ collisionAssertions +++ positiveNumberAssertions +++ forbiddenValueAssertions diff --git a/modules/proxy-suite/service/assertions-lib.nix b/modules/proxy-suite/service/assertions-lib.nix deleted file mode 100644 index b6ebc60..0000000 --- a/modules/proxy-suite/service/assertions-lib.nix +++ /dev/null @@ -1,31 +0,0 @@ -{ lib }: - -rec { - mkAssertion = assertion: message: { inherit assertion message; }; - - requireEnabled = - featureEnabled: dependencyEnabled: message: - mkAssertion (!featureEnabled || dependencyEnabled) message; - - requireAvailable = - featureUsed: dependencyEnabled: message: - mkAssertion (!featureUsed || dependencyEnabled) message; - - uniqueValues = - condition: values: message: - mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message; - - notEqualWhen = - condition: left: right: message: - mkAssertion (!(condition && left == right)) message; - - forbiddenValues = - condition: value: disallowed: message: - mkAssertion (!(condition && builtins.elem value disallowed)) message; - - exactlyOneOf = - condition: values: message: - mkAssertion ( - !condition || builtins.length (builtins.filter (value: value != null) values) == 1 - ) message; -} diff --git a/modules/proxy-suite/service/builders.nix b/modules/proxy-suite/service/builders.nix index 7dbe837..2a108f4 100644 --- a/modules/proxy-suite/service/builders.nix +++ b/modules/proxy-suite/service/builders.nix @@ -35,127 +35,6 @@ rec { ) ); - cidrNetworkFunction = '' - cidr_network() { - local cidr="$1" - local addr="''${cidr%/*}" - local prefix="''${cidr#*/}" - local o1 o2 o3 o4 ip mask net - - IFS=. read -r o1 o2 o3 o4 <<<"$addr" - ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4)) - if [ "$prefix" -eq 0 ]; then - mask=0 - else - mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF)) - fi - net=$((ip & mask)) - - printf '%d.%d.%d.%d/%s' \ - $(((net >> 24) & 255)) \ - $(((net >> 16) & 255)) \ - $(((net >> 8) & 255)) \ - $((net & 255)) \ - "$prefix" - } - ''; - - mkDefaultUplinkIPv4Source = - { - ip, - awk, - errorMessage, - }: - '' - uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} ' - /src/ { - for (i = 1; i <= NF; i++) { - if ($i == "src" && i + 1 <= NF) { - print $(i + 1) - exit - } - } - } - ')" - if [ -z "$uplink_addr" ]; then - echo ${lib.escapeShellArg errorMessage} >&2 - exit 1 - fi - ''; - - mkNftDeleteTable = - { - nft, - family, - table, - }: - '' - ${nft} delete table ${family} ${table} 2>/dev/null || true - ''; - - mkIpRuleDeleteByFwmark = - { - ip, - family ? "", - fwmark, - table, - }: - '' - while ${ip} ${lib.optionalString (family != "") "${family} "}rule del fwmark ${toString fwmark} table ${toString table} 2>/dev/null; do :; done - ''; - - mkIpRuleDeleteByTable = - { - ip, - family, - table, - }: - '' - while ${ip} ${family} rule del table ${toString table} 2>/dev/null; do :; done - ''; - - mkIpRuleDeleteByPriority = - { - ip, - family, - priority, - }: - '' - while ${ip} ${family} rule del pref ${toString priority} 2>/dev/null; do :; done - ''; - - mkIpRouteFlushTable = - { - ip, - family, - table, - }: - '' - ${ip} ${family} route flush table ${toString table} 2>/dev/null || true - ''; - - mkIpLocalDefaultRouteDelete = - { - ip, - table, - }: - '' - ${ip} route del local default dev lo table ${toString table} 2>/dev/null || true - ''; - - mkIpLinkDelete = - { - ip, - interface, - }: - '' - ${ip} link del dev ${lib.escapeShellArg interface} 2>/dev/null || true - ''; - - flushResolvedCaches = '' - ${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true - ''; - mkRestartingService = { description, @@ -263,4 +142,127 @@ rec { execStop = "${pkgs.coreutils}/bin/true"; extraServiceConfig.Slice = sliceName; }; + + cidrNetworkFunction = '' + cidr_network() { + local cidr="$1" + local addr="''${cidr%/*}" + local prefix="''${cidr#*/}" + local o1 o2 o3 o4 ip mask net + + IFS=. read -r o1 o2 o3 o4 <<<"$addr" + ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4)) + if [ "$prefix" -eq 0 ]; then + mask=0 + else + mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF)) + fi + net=$((ip & mask)) + + printf '%d.%d.%d.%d/%s' \ + $(((net >> 24) & 255)) \ + $(((net >> 16) & 255)) \ + $(((net >> 8) & 255)) \ + $((net & 255)) \ + "$prefix" + } + ''; + + mkDefaultUplinkIPv4Source = + { + ip, + awk, + errorMessage, + }: + '' + uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} ' + /src/ { + for (i = 1; i <= NF; i++) { + if ($i == "src" && i + 1 <= NF) { + print $(i + 1) + exit + } + } + } + ')" + if [ -z "$uplink_addr" ]; then + echo ${lib.escapeShellArg errorMessage} >&2 + exit 1 + fi + ''; + + mkNftDeleteTable = + { + nft, + family, + table, + }: + '' + ${nft} delete table ${family} ${table} 2>/dev/null || true + ''; + + mkIpRuleDeleteByFwmark = + { + ip, + family ? "", + fwmark, + table, + }: + '' + while ${ip} ${ + lib.optionalString (family != "") "${family} " + }rule del fwmark ${toString fwmark} table ${toString table} 2>/dev/null; do :; done + ''; + + mkIpRuleDeleteByTable = + { + ip, + family, + table, + }: + '' + while ${ip} ${family} rule del table ${toString table} 2>/dev/null; do :; done + ''; + + mkIpRuleDeleteByPriority = + { + ip, + family, + priority, + }: + '' + while ${ip} ${family} rule del pref ${toString priority} 2>/dev/null; do :; done + ''; + + mkIpRouteFlushTable = + { + ip, + family, + table, + }: + '' + ${ip} ${family} route flush table ${toString table} 2>/dev/null || true + ''; + + mkIpLocalDefaultRouteDelete = + { + ip, + table, + }: + '' + ${ip} route del local default dev lo table ${toString table} 2>/dev/null || true + ''; + + mkIpLinkDelete = + { + ip, + interface, + }: + '' + ${ip} link del dev ${lib.escapeShellArg interface} 2>/dev/null || true + ''; + + flushResolvedCaches = '' + ${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true + ''; } diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 8cdc089..33ae444 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -71,15 +71,12 @@ let pkgs singBoxCfg proxyCfg - proxyEnabled - singBoxEnabled xrayEnabled hybridEnabled pureXrayEnabled activeBackend perAppRoutingCfg userControlCfg - perAppRoutingTun selectionMode collapseNamedOutbounds hasSubscriptions diff --git a/modules/proxy-suite/service/control-scripts.nix b/modules/proxy-suite/service/control-scripts.nix new file mode 100644 index 0000000..8c7d6f9 --- /dev/null +++ b/modules/proxy-suite/service/control-scripts.nix @@ -0,0 +1,78 @@ +# Subscription refresh and route-mode control scripts. +{ + lib, + pkgs, + proxyCfg, + routeModeStateFile, + subscriptionCacheDir, + subscriptionCacheHelpersBlock, + mkSubscriptionFetchBlock, +}: + +let + systemctl = "${pkgs.systemd}/bin/systemctl"; + + restartActiveConfigConsumersBlock = + lib.concatMapStrings + (svc: '' + if ${systemctl} is-active --quiet ${svc}; then + ${systemctl} restart ${svc} + fi + '') + [ + "proxy-suite-socks" + "proxy-suite-tun" + "proxy-suite-per-app-tun" + ]; + + subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" '' + set -euo pipefail + CACHE_DIR="${subscriptionCacheDir}" + mkdir -p "$CACHE_DIR" + FAILED=0 + ${subscriptionCacheHelpersBlock} + ${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions} + + if [ "$FAILED" -eq 0 ]; then + ${restartActiveConfigConsumersBlock} + fi + exit "$FAILED" + ''; + + setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" '' + set -euo pipefail + mode="''${1:-}" + + case "$mode" in + default) + ;; + whitelist) + ;; + blacklist) + ;; + all-proxy) + ;; + all-bypass) + ;; + *) + echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2 + exit 1 + ;; + esac + + mkdir -p "$(dirname "${routeModeStateFile}")" + if [ "$mode" = "default" ]; then + rm -f "${routeModeStateFile}" + else + printf '%s\n' "$mode" > "${routeModeStateFile}" + fi + + ${restartActiveConfigConsumersBlock} + ''; +in +{ + inherit + subscriptionUpdateScript + setRouteModeScript + ; +} diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 74c4306..689f936 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -37,19 +37,7 @@ let }; builders = import ./builders.nix { inherit lib pkgs; }; - inherit (builders) - mkNamedUnits - mkRestartingService - mkOneshotService - mkUserRuleService - mkAnchorService - ; - - defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source { - inherit ip; - awk = "${pkgs.gawk}/bin/awk"; - errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN"; - }; + inherit (builders) mkNamedUnits; inherit (context) derived @@ -60,19 +48,14 @@ let ; inherit (derived) - singBoxCfg proxyCfg proxyEnabled - xrayEnabled hybridEnabled pureXrayEnabled - activeBackend - perAppRoutingCfg globalTun globalTproxy perAppRoutingTun perAppRoutingTproxy - perAppZapretCfg userControlCfg userControlEnabled perAppZapretEnabled @@ -83,323 +66,47 @@ let builtinTags ; constants = derived.constants; - inherit (constants) - tunAutoRouteTableIndex - tunAutoRouteRulePriority - xrayTunPerAppTproxyRulePriority - xrayTunPerAppTunRulePriority - xrayGlobalTunIPv6Address - xrayGlobalTunIPv6RoutePrefix - ; - - serviceNames = { - socks = "proxy-suite-socks"; - tproxy = "proxy-suite-tproxy"; - tun = "proxy-suite-tun"; - perAppTun = "proxy-suite-per-app-tun"; - perAppTproxy = "proxy-suite-per-app-tproxy"; - perAppZapret = "proxy-suite-per-app-zapret"; - subscriptionUpdate = "proxy-suite-subscription-update"; + routingScripts = import ./routing-scripts.nix { + inherit + lib + pkgs + builders + ip + nft + nftablesRulesFile + constants + globalTun + globalTproxy + perAppRoutingTun + perAppRoutingTproxy + ; }; - localProxyAuthEnabled = - proxyCfg.auth.username != null - && (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null); - - xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" '' - set -euo pipefail - - tun_cidr=${lib.escapeShellArg globalTun.address} - tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address} - tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix} - tun_addr="" - tun_route_prefix="" - uplink_addr="" - - ${builders.cidrNetworkFunction} - - 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 - - ${defaultUplinkIPv4Source} - - while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done - while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done - while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done - while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done - while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done - - tun_addr="''${tun_cidr%%/*}" - tun_route_prefix="$(cidr_network "$tun_cidr")" - - ${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface} - ${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface} - ${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex} - ${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex} - ${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex} - ${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex} - ${lib.optionalString perAppRoutingTproxy.enable '' - ${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} - ''} - ${lib.optionalString perAppRoutingTun.enable '' - ${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} - ${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} - ''} - ${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} - ${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} - ''; - - tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" '' - set -euo pipefail - - # Start from a clean policy-routing state. `ip rule add` permits duplicate - # rules on some iproute2 versions, and a stale rule can keep packets routed - # into a dead local table after a failed restart. - ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - fwmark = globalTproxy.fwmark; - table = globalTproxy.routeTable; - }} - ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }} - - ${nft} -f ${nftablesRulesFile} - ${ip} route replace local default dev lo table ${toString globalTproxy.routeTable} - ${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} - ''; - - tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" '' - set +e - - ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - fwmark = globalTproxy.fwmark; - table = globalTproxy.routeTable; - }} - ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }} - ''; - - tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' - set +e - - # SingBox normally removes these on graceful shutdown, but stale - # auto_route/auto_redirect state leaves the host routing through a dead TUN - # interface after `proxy-ctl tun off` or an unclean service stop. - ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }} - ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }} - ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }} - ${builders.mkIpRuleDeleteByPriority { - inherit ip; - family = "-4"; - priority = xrayTunPerAppTproxyRulePriority; - }} - ${builders.mkIpRuleDeleteByPriority { - inherit ip; - family = "-4"; - priority = xrayTunPerAppTunRulePriority; - }} - ${builders.mkIpRuleDeleteByPriority { - inherit ip; - family = "-6"; - priority = xrayTunPerAppTunRulePriority; - }} - ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }} - ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }} - ${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }} - ${builders.flushResolvedCaches} - ''; - - systemServiceEntries = [ - { - enable = proxyEnabled; - name = serviceNames.socks; - value = mkRestartingService { - description = "${ - if pureXrayEnabled then - "XRay" - else if hybridEnabled then - "sing-box + XRay sidecar" - else - "sing-box" - } proxy client (SOCKS + TProxy-ready)"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - wantedBy = [ "multi-user.target" ]; - execStart = scripts.startSocks; - runtimeDirectory = serviceNames.socks; - stateDirectory = "proxy-suite"; - }; - } - { - enable = proxyEnabled && globalTproxy.enable; - name = serviceNames.tproxy; - value = mkOneshotService { - description = "proxy-suite TProxy - nftables rules and policy routing"; - after = [ - "network.target" - "${serviceNames.socks}.service" - ]; - wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ]; - requires = [ "${serviceNames.socks}.service" ]; - conflicts = [ - "${serviceNames.tun}.service" - "${serviceNames.perAppTproxy}.service" - ]; - execStart = tproxyUpScript; - execStop = tproxyDownScript; - }; - } - { - enable = proxyEnabled && globalTun.enable; - name = serviceNames.tun; - value = mkRestartingService { - description = "${ - if pureXrayEnabled then - "XRay" - else if hybridEnabled then - "sing-box + XRay sidecar" - else - "sing-box" - } TUN proxy client"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; - conflicts = [ "${serviceNames.tproxy}.service" ]; - execStartPre = tunCleanupScript; - execStart = scripts.startTun; - execStartPost = if pureXrayEnabled then xrayTunUpScript else null; - execStopPost = tunCleanupScript; - runtimeDirectory = serviceNames.tun; - stateDirectory = "proxy-suite"; - }; - } - { - enable = proxyEnabled && perAppRoutingTun.enable; - name = serviceNames.perAppTun; - value = mkRestartingService { - description = "proxy-suite per-app-routing TUN backend"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - execStartPre = perAppRouting.perAppTunDownScript; - execStart = scripts.startPerAppTun; - execStartPost = perAppRouting.perAppTunUpScript; - execStopPost = perAppRouting.perAppTunDownScript; - runtimeDirectory = serviceNames.perAppTun; - stateDirectory = "proxy-suite"; - }; - } - { - enable = proxyEnabled && perAppRoutingTun.enable; - name = "${serviceNames.perAppTun}-user@"; - value = mkUserRuleService { - description = "Enable proxy-suite app TUN marking for user %i"; - backendService = serviceNames.perAppTun; - execStart = "${perAppRouting.perAppTunUserRuleStart} %i"; - execStop = "${perAppRouting.perAppTunUserRuleStop} %i"; - }; - } - { - enable = proxyEnabled && perAppRoutingTproxy.enable; - name = serviceNames.perAppTproxy; - value = mkOneshotService { - description = "proxy-suite per-app-routing TProxy backend"; - after = [ - "network.target" - "${serviceNames.socks}.service" - ]; - requires = [ "${serviceNames.socks}.service" ]; - conflicts = [ - "${serviceNames.tproxy}.service" - "${serviceNames.tun}.service" - ]; - execStart = perAppRouting.perAppTproxyUpScript; - execStop = perAppRouting.perAppTproxyDownScript; - }; - } - { - enable = proxyEnabled && perAppRoutingTproxy.enable; - name = "${serviceNames.perAppTproxy}-user@"; - value = mkUserRuleService { - description = "Enable proxy-suite app TProxy marking for user %i"; - backendService = serviceNames.perAppTproxy; - execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i"; - execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i"; - }; - } - { - enable = perAppZapretEnabled; - name = "${serviceNames.perAppZapret}-user@"; - value = mkUserRuleService { - description = "Enable proxy-suite app zapret marking for user %i"; - backendService = serviceNames.perAppZapret; - execStart = "${perAppRouting.perAppZapretUserRuleStart} %i"; - execStop = "${perAppRouting.perAppZapretUserRuleStop} %i"; - }; - } - { - enable = proxyEnabled && hasSubscriptions; - name = serviceNames.subscriptionUpdate; - value = mkOneshotService { - description = "Refresh proxy-suite subscription caches"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - execStart = scripts.subscriptionUpdateScript; - stateDirectory = "proxy-suite"; - }; - } - { - enable = proxyEnabled; - name = "proxy-suite-route-mode@"; - value = mkOneshotService { - description = "Set proxy-suite route mode to %i"; - execStart = "${scripts.setRouteModeScript} %i"; - extraServiceConfig.RemainAfterExit = false; - }; - } - ]; - - userServiceEntries = [ - { - enable = perAppRoutingTun.enable; - name = "${serviceNames.perAppTun}-anchor"; - value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice"; - } - { - enable = perAppRoutingTproxy.enable; - name = "${serviceNames.perAppTproxy}-anchor"; - value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice"; - } - { - enable = perAppZapretEnabled; - name = "${serviceNames.perAppZapret}-anchor"; - value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice"; - } - ]; - - timerEntries = [ - { - enable = proxyEnabled && hasSubscriptions; - name = serviceNames.subscriptionUpdate; - value = { - description = "Periodic proxy-suite subscription refresh"; - wantedBy = [ "timers.target" ]; - timerConfig = { - OnBootSec = "5m"; - OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval; - }; - }; - } - ]; + serviceUnits = import ./units.nix { + inherit + lib + builders + proxyCfg + proxyEnabled + hybridEnabled + pureXrayEnabled + globalTun + globalTproxy + perAppRoutingTun + perAppRoutingTproxy + perAppZapretEnabled + hasSubscriptions + scripts + perAppRouting + routingScripts + ; + }; + inherit (serviceUnits) + localProxyAuthEnabled + systemServiceEntries + userServiceEntries + timerEntries + ; in { environment.systemPackages = [ control.proxyCtl ]; diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index fd7d861..3443141 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -27,310 +27,84 @@ let builders = import ./builders.nix { inherit lib pkgs; }; inherit (builders) mkAnchorService; - defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source { - inherit ip awk; - errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN"; - }; perAppTunSliceName = "proxy-suite-per-app-tun.slice"; perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; perAppZapretSliceName = "proxy-suite-per-app-zapret.slice"; - perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles; - defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles ( - [ - { - name = "proxychains"; - route = "proxychains"; - } - ] - ++ lib.optionals perAppRoutingTun.enable [ - { - name = "tun"; - route = "tun"; - } - ] - ++ lib.optionals perAppRoutingTproxy.enable [ - { - name = "tproxy"; - route = "tproxy"; - } - ] - ++ lib.optionals perAppZapretCfg.enable [ - { - name = "zapret"; - route = "zapret"; - } - ] - ); - effectivePerAppRoutingProfiles = - perAppRoutingCfg.profiles - ++ builtins.filter ( - profile: !(builtins.elem profile.name perAppRoutingProfileNames) - ) defaultPerAppRoutingProfiles; - effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles; - localProxyAuth = proxyCfg.auth; - localProxyAuthEnabled = - localProxyAuth.username != null - && (localProxyAuth.password != null || localProxyAuth.passwordFile != null); - - perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" ( - builtins.toJSON effectivePerAppRoutingProfiles - ); - - proxychainsConfigFile = - if localProxyAuthEnabled then - "/run/proxy-suite-socks/proxychains.conf" - else - pkgs.writeText "proxy-suite-proxychains.conf" '' - strict_chain - ${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"} - ${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"} - tcp_read_time_out 15000 - tcp_connect_time_out 8000 - - [ProxyList] - socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port} - ''; - proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q "; - - hasProxychainsProfiles = builtins.any ( - profile: profile.route == "proxychains" - ) effectivePerAppRoutingProfiles; - hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles; - hasTproxyProfiles = builtins.any ( - profile: profile.route == "tproxy" - ) effectivePerAppRoutingProfiles; - hasZapretProfiles = builtins.any ( - profile: profile.route == "zapret" - ) effectivePerAppRoutingProfiles; - inherit (constants) - xrayPerAppTunIPv6Address - xrayPerAppTunIPv6RoutePrefix + profiles = import ./per-app-routing/profiles.nix { + inherit + lib + pkgs + proxyCfg + perAppRoutingCfg + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg + ; + }; + inherit (profiles) + effectivePerAppRoutingProfiles + effectivePerAppRoutingProfileNames + perAppRoutingProfilesFile + proxychainsConfigFile + proxychainsQuietArg + hasProxychainsProfiles + hasTunProfiles + hasTproxyProfiles + hasZapretProfiles ; - perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" '' - set -euo pipefail - for _ in $(${seqBin} 1 50); do - if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then - exit 0 - fi - ${sleepBin} 0.1 - done - echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2 - exit 1 - ''; - - perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" '' - set -euo pipefail - - tun_cidr=${lib.escapeShellArg perAppRoutingTun.address} - tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address} - tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix} - tun_addr="" - tun_route_prefix="" - uplink_addr="" - - ${builders.cidrNetworkFunction} - - ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - family = "-4"; - fwmark = perAppRoutingTun.fwmark; - table = perAppRoutingTun.routeTable; - }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - family = "-6"; - fwmark = perAppRoutingTun.fwmark; - table = perAppRoutingTun.routeTable; - }} - ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }} - ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }} - ${nft} -f ${perAppTunChainFile} - ${perAppTunWaitForInterface} - ${defaultUplinkIPv4Source} - tun_addr="''${tun_cidr%%/*}" - tun_route_prefix="$(cidr_network "$tun_cidr")" - ${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface} - ${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable} - ${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable} - ${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true - ${lib.optionalString pureXrayEnabled '' - ${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface} - ${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} - ${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} - ${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true - ''} - ''; - - perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" '' - set +e - - # Best-effort cleanup for graceful stops and for unclean previous exits. - ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - family = "-4"; - fwmark = perAppRoutingTun.fwmark; - table = perAppRoutingTun.routeTable; - }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - family = "-6"; - fwmark = perAppRoutingTun.fwmark; - table = perAppRoutingTun.routeTable; - }} - ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }} - ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }} - ${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }} - ${builders.flushResolvedCaches} - ''; - - perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" '' - set -euo pipefail - - ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - fwmark = perAppRoutingTproxy.fwmark; - table = perAppRoutingTproxy.routeTable; - }} - ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }} - - ${nft} -f ${perAppTproxyRulesFile} - ${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable} - ${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} - ''; - - perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" '' - set +e - - ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }} - ${builders.mkIpRuleDeleteByFwmark { - inherit ip; - fwmark = perAppRoutingTproxy.fwmark; - table = perAppRoutingTproxy.routeTable; - }} - ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }} - ''; - - # Generate a "start" script that adds a per-user cgroup nftables mark rule. - mkUserRuleStart = - { - name, - nftFamily, - nftTable, - nftChain, - sliceName, - sliceLabel, - markRule, - }: - pkgs.writeShellScript "proxy-suite-${name}-user-start" '' - set -euo pipefail - uid="$1" - rule_comment_prefix="proxy-suite-${name}-user-$uid" - mark_comment="$rule_comment_prefix-mark" - cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service" - if ! [ -d "$cgroup_root" ]; then - echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2 - exit 1 - fi - - cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true) - if [ -z "$cgroup_dir" ]; then - echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2 - exit 1 - fi - cgroup_path=''${cgroup_dir#/sys/fs/cgroup/} - cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }') - - handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ - | ${grepBin} -F "comment \"$rule_comment_prefix" \ - | ${awk} '{ print $NF }' || true) - if [ -n "$handles" ]; then - while IFS= read -r handle; do - [ -n "$handle" ] || continue - ${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true - done <<< "$handles" - fi - - printf '%s\n' \ - "add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \ - | ${nft} -f - - ''; - - # Generate a "stop" script that removes all per-user cgroup nftables mark rules. - mkUserRuleStop = - { - name, - nftFamily, - nftTable, - nftChain, - }: - pkgs.writeShellScript "proxy-suite-${name}-user-stop" '' - set -euo pipefail - uid="$1" - rule_comment_prefix="proxy-suite-${name}-user-$uid" - handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ - | ${grepBin} -F "comment \"$rule_comment_prefix" \ - | ${awk} '{ print $NF }' || true) - if [ -n "$handles" ]; then - while IFS= read -r handle; do - [ -n "$handle" ] || continue - ${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true - done <<< "$handles" - fi - ''; - - perAppTunUserRuleStart = mkUserRuleStart { - name = "per-app-tun"; - nftFamily = "inet"; - nftTable = "proxy_suite_per_app_tun"; - nftChain = "output"; - sliceName = perAppTunSliceName; - sliceLabel = "app TUN"; - markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}"; - }; - perAppTunUserRuleStop = mkUserRuleStop { - name = "per-app-tun"; - nftFamily = "inet"; - nftTable = "proxy_suite_per_app_tun"; - nftChain = "output"; + backendScripts = import ./per-app-routing/backend-scripts.nix { + inherit + lib + pkgs + builders + pureXrayEnabled + perAppRoutingTun + perAppRoutingTproxy + constants + perAppTunChainFile + perAppTproxyRulesFile + ip + nft + awk + seqBin + sleepBin + ; }; + inherit (backendScripts) + perAppTunUpScript + perAppTunDownScript + perAppTproxyUpScript + perAppTproxyDownScript + ; - perAppTproxyUserRuleStart = mkUserRuleStart { - name = "per-app-tproxy"; - nftFamily = "ip"; - nftTable = "proxy_suite_per_app_tproxy"; - nftChain = "output"; - sliceName = perAppTproxySliceName; - sliceLabel = "app TProxy"; - markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}"; - }; - perAppTproxyUserRuleStop = mkUserRuleStop { - name = "per-app-tproxy"; - nftFamily = "ip"; - nftTable = "proxy_suite_per_app_tproxy"; - nftChain = "output"; - }; - - perAppZapretUserRuleStart = mkUserRuleStart { - name = "per-app-zapret"; - nftFamily = "inet"; - nftTable = "proxy_suite_per_app_zapret_mark"; - nftChain = "output"; - sliceName = perAppZapretSliceName; - sliceLabel = "app zapret"; - markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}"; - }; - perAppZapretUserRuleStop = mkUserRuleStop { - name = "per-app-zapret"; - nftFamily = "inet"; - nftTable = "proxy_suite_per_app_zapret_mark"; - nftChain = "output"; + userRules = import ./per-app-routing/user-rules.nix { + inherit + lib + pkgs + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg + perAppTunSliceName + perAppTproxySliceName + perAppZapretSliceName + nft + awk + grepBin + findBin + headBin + ; }; + inherit (userRules) + perAppTunUserRuleStart + perAppTunUserRuleStop + perAppTproxyUserRuleStart + perAppTproxyUserRuleStop + perAppZapretUserRuleStart + perAppZapretUserRuleStop + ; in { diff --git a/modules/proxy-suite/service/per-app-routing/backend-scripts.nix b/modules/proxy-suite/service/per-app-routing/backend-scripts.nix new file mode 100644 index 0000000..aa3936d --- /dev/null +++ b/modules/proxy-suite/service/per-app-routing/backend-scripts.nix @@ -0,0 +1,144 @@ +# Per-app TUN and TProxy backend lifecycle scripts. +{ + lib, + pkgs, + builders, + pureXrayEnabled, + perAppRoutingTun, + perAppRoutingTproxy, + constants, + perAppTunChainFile, + perAppTproxyRulesFile, + ip, + nft, + awk, + seqBin, + sleepBin, +}: + +let + defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source { + inherit ip awk; + errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN"; + }; + + inherit (constants) + xrayPerAppTunIPv6Address + xrayPerAppTunIPv6RoutePrefix + ; + + perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" '' + set -euo pipefail + for _ in $(${seqBin} 1 50); do + if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then + exit 0 + fi + ${sleepBin} 0.1 + done + echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2 + exit 1 + ''; + + perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" '' + set -euo pipefail + + tun_cidr=${lib.escapeShellArg perAppRoutingTun.address} + tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address} + tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix} + tun_addr="" + tun_route_prefix="" + uplink_addr="" + + ${builders.cidrNetworkFunction} + + ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-4"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-6"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }} + ${nft} -f ${perAppTunChainFile} + ${perAppTunWaitForInterface} + ${defaultUplinkIPv4Source} + tun_addr="''${tun_cidr%%/*}" + tun_route_prefix="$(cidr_network "$tun_cidr")" + ${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface} + ${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable} + ${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable} + ${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true + ${lib.optionalString pureXrayEnabled '' + ${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface} + ${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} + ${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} + ${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true + ''} + ''; + + perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" '' + set +e + + # Best-effort cleanup for graceful stops and for unclean previous exits. + ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-4"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-6"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }} + ${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }} + ${builders.flushResolvedCaches} + ''; + + perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" '' + set -euo pipefail + + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = perAppRoutingTproxy.fwmark; + table = perAppRoutingTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }} + + ${nft} -f ${perAppTproxyRulesFile} + ${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable} + ${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} + ''; + + perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" '' + set +e + + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = perAppRoutingTproxy.fwmark; + table = perAppRoutingTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }} + ''; +in +{ + inherit + perAppTunUpScript + perAppTunDownScript + perAppTproxyUpScript + perAppTproxyDownScript + ; +} diff --git a/modules/proxy-suite/service/per-app-routing/profiles.nix b/modules/proxy-suite/service/per-app-routing/profiles.nix new file mode 100644 index 0000000..5ae44a0 --- /dev/null +++ b/modules/proxy-suite/service/per-app-routing/profiles.nix @@ -0,0 +1,95 @@ +# Per-app routing profile expansion and proxychains config. +{ + lib, + pkgs, + proxyCfg, + perAppRoutingCfg, + perAppRoutingTun, + perAppRoutingTproxy, + perAppZapretCfg, +}: + +let + perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles; + defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles ( + [ + { + name = "proxychains"; + route = "proxychains"; + } + ] + ++ lib.optionals perAppRoutingTun.enable [ + { + name = "tun"; + route = "tun"; + } + ] + ++ lib.optionals perAppRoutingTproxy.enable [ + { + name = "tproxy"; + route = "tproxy"; + } + ] + ++ lib.optionals perAppZapretCfg.enable [ + { + name = "zapret"; + route = "zapret"; + } + ] + ); + effectivePerAppRoutingProfiles = + perAppRoutingCfg.profiles + ++ builtins.filter ( + profile: !(builtins.elem profile.name perAppRoutingProfileNames) + ) defaultPerAppRoutingProfiles; + effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles; + + localProxyAuth = proxyCfg.auth; + localProxyAuthEnabled = + localProxyAuth.username != null + && (localProxyAuth.password != null || localProxyAuth.passwordFile != null); + + perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" ( + builtins.toJSON effectivePerAppRoutingProfiles + ); + + proxychainsConfigFile = + if localProxyAuthEnabled then + "/run/proxy-suite-socks/proxychains.conf" + else + pkgs.writeText "proxy-suite-proxychains.conf" '' + strict_chain + ${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"} + ${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"} + tcp_read_time_out 15000 + tcp_connect_time_out 8000 + + [ProxyList] + socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port} + ''; + proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q "; + + hasProxychainsProfiles = builtins.any ( + profile: profile.route == "proxychains" + ) effectivePerAppRoutingProfiles; + hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles; + hasTproxyProfiles = builtins.any ( + profile: profile.route == "tproxy" + ) effectivePerAppRoutingProfiles; + hasZapretProfiles = builtins.any ( + profile: profile.route == "zapret" + ) effectivePerAppRoutingProfiles; +in +{ + inherit + effectivePerAppRoutingProfiles + effectivePerAppRoutingProfileNames + perAppRoutingProfilesFile + proxychainsConfigFile + proxychainsQuietArg + hasProxychainsProfiles + hasTunProfiles + hasTproxyProfiles + hasZapretProfiles + ; +} diff --git a/modules/proxy-suite/service/per-app-routing/user-rules.nix b/modules/proxy-suite/service/per-app-routing/user-rules.nix new file mode 100644 index 0000000..ac41ff8 --- /dev/null +++ b/modules/proxy-suite/service/per-app-routing/user-rules.nix @@ -0,0 +1,142 @@ +# Per-user cgroup nftables mark-rule scripts for per-app routing backends. +{ + lib, + pkgs, + perAppRoutingTun, + perAppRoutingTproxy, + perAppZapretCfg, + perAppTunSliceName, + perAppTproxySliceName, + perAppZapretSliceName, + nft, + awk, + grepBin, + findBin, + headBin, +}: + +let + mkUserRuleStart = + { + name, + nftFamily, + nftTable, + nftChain, + sliceName, + sliceLabel, + markRule, + }: + pkgs.writeShellScript "proxy-suite-${name}-user-start" '' + set -euo pipefail + uid="$1" + rule_comment_prefix="proxy-suite-${name}-user-$uid" + mark_comment="$rule_comment_prefix-mark" + cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service" + if ! [ -d "$cgroup_root" ]; then + echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2 + exit 1 + fi + + cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true) + if [ -z "$cgroup_dir" ]; then + echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2 + exit 1 + fi + cgroup_path=''${cgroup_dir#/sys/fs/cgroup/} + cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }') + + handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ + | ${grepBin} -F "comment \"$rule_comment_prefix" \ + | ${awk} '{ print $NF }' || true) + if [ -n "$handles" ]; then + while IFS= read -r handle; do + [ -n "$handle" ] || continue + ${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true + done <<< "$handles" + fi + + printf '%s\n' \ + "add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \ + | ${nft} -f - + ''; + + mkUserRuleStop = + { + name, + nftFamily, + nftTable, + nftChain, + }: + pkgs.writeShellScript "proxy-suite-${name}-user-stop" '' + set -euo pipefail + uid="$1" + rule_comment_prefix="proxy-suite-${name}-user-$uid" + handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ + | ${grepBin} -F "comment \"$rule_comment_prefix" \ + | ${awk} '{ print $NF }' || true) + if [ -n "$handles" ]; then + while IFS= read -r handle; do + [ -n "$handle" ] || continue + ${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true + done <<< "$handles" + fi + ''; + + perAppTunUserRuleStart = mkUserRuleStart { + name = "per-app-tun"; + nftFamily = "inet"; + nftTable = "proxy_suite_per_app_tun"; + nftChain = "output"; + sliceName = perAppTunSliceName; + sliceLabel = "app TUN"; + markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}"; + }; + perAppTunUserRuleStop = mkUserRuleStop { + name = "per-app-tun"; + nftFamily = "inet"; + nftTable = "proxy_suite_per_app_tun"; + nftChain = "output"; + }; + + perAppTproxyUserRuleStart = mkUserRuleStart { + name = "per-app-tproxy"; + nftFamily = "ip"; + nftTable = "proxy_suite_per_app_tproxy"; + nftChain = "output"; + sliceName = perAppTproxySliceName; + sliceLabel = "app TProxy"; + markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}"; + }; + perAppTproxyUserRuleStop = mkUserRuleStop { + name = "per-app-tproxy"; + nftFamily = "ip"; + nftTable = "proxy_suite_per_app_tproxy"; + nftChain = "output"; + }; + + perAppZapretUserRuleStart = mkUserRuleStart { + name = "per-app-zapret"; + nftFamily = "inet"; + nftTable = "proxy_suite_per_app_zapret_mark"; + nftChain = "output"; + sliceName = perAppZapretSliceName; + sliceLabel = "app zapret"; + markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}"; + }; + perAppZapretUserRuleStop = mkUserRuleStop { + name = "per-app-zapret"; + nftFamily = "inet"; + nftTable = "proxy_suite_per_app_zapret_mark"; + nftChain = "output"; + }; +in +{ + inherit + perAppTunUserRuleStart + perAppTunUserRuleStop + perAppTproxyUserRuleStart + perAppTproxyUserRuleStop + perAppZapretUserRuleStart + perAppZapretUserRuleStop + ; +} diff --git a/modules/proxy-suite/service/routing-scripts.nix b/modules/proxy-suite/service/routing-scripts.nix new file mode 100644 index 0000000..328439b --- /dev/null +++ b/modules/proxy-suite/service/routing-scripts.nix @@ -0,0 +1,144 @@ +{ + lib, + pkgs, + builders, + ip, + nft, + nftablesRulesFile, + constants, + globalTun, + globalTproxy, + perAppRoutingTun, + perAppRoutingTproxy, +}: + +let + inherit (constants) + tunAutoRouteTableIndex + tunAutoRouteRulePriority + xrayTunPerAppTproxyRulePriority + xrayTunPerAppTunRulePriority + xrayGlobalTunIPv6Address + xrayGlobalTunIPv6RoutePrefix + ; + + defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source { + inherit ip; + awk = "${pkgs.gawk}/bin/awk"; + errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN"; + }; +in +{ + xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" '' + set -euo pipefail + + tun_cidr=${lib.escapeShellArg globalTun.address} + tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address} + tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix} + tun_addr="" + tun_route_prefix="" + uplink_addr="" + + ${builders.cidrNetworkFunction} + + 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 + + ${defaultUplinkIPv4Source} + + while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done + while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done + while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done + while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done + while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done + + tun_addr="''${tun_cidr%%/*}" + tun_route_prefix="$(cidr_network "$tun_cidr")" + + ${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface} + ${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface} + ${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex} + ${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex} + ${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex} + ${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex} + ${lib.optionalString perAppRoutingTproxy.enable '' + ${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} + ''} + ${lib.optionalString perAppRoutingTun.enable '' + ${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} + ${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} + ''} + ${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} + ${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} + ''; + + tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" '' + set -euo pipefail + + # Start from a clean policy-routing state. `ip rule add` permits duplicate + # rules on some iproute2 versions, and a stale rule can keep packets routed + # into a dead local table after a failed restart. + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = globalTproxy.fwmark; + table = globalTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }} + + ${nft} -f ${nftablesRulesFile} + ${ip} route replace local default dev lo table ${toString globalTproxy.routeTable} + ${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} + ''; + + tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" '' + set +e + + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = globalTproxy.fwmark; + table = globalTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }} + ''; + + tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' + set +e + + # SingBox normally removes these on graceful shutdown, but stale + # auto_route/auto_redirect state leaves the host routing through a dead TUN + # interface after `proxy-ctl tun off` or an unclean service stop. + ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }} + ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpRuleDeleteByPriority { + inherit ip; + family = "-4"; + priority = xrayTunPerAppTproxyRulePriority; + }} + ${builders.mkIpRuleDeleteByPriority { + inherit ip; + family = "-4"; + priority = xrayTunPerAppTunRulePriority; + }} + ${builders.mkIpRuleDeleteByPriority { + inherit ip; + family = "-6"; + priority = xrayTunPerAppTunRulePriority; + }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }} + ${builders.flushResolvedCaches} + ''; +} diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix new file mode 100644 index 0000000..f6d534d --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -0,0 +1,98 @@ +{ + pureXrayEnabled, + selectionMode, +}: + +if pureXrayEnabled then + '' + def xray_bind_outbound($interface): + if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then + . + else + .streamSettings = (.streamSettings // {}) + | .streamSettings.sockopt = (.streamSettings.sockopt // {}) + | if (.streamSettings.sockopt.interface? // "") == "" then + .streamSettings.sockopt.interface = $interface + else + . + end + end; + def xray_proxy_rule_target($single_tag): + if $single_tag != "" then + {outboundTag:$single_tag} + else + {balancerTag:"proxy"} + end; + def xray_rewrite_proxy_rule($single_tag): + if $single_tag != "" and (.balancerTag? // "") == "proxy" then + .outboundTag = $single_tag | del(.balancerTag) + else + . + end; + def xray_preserved_rules: + [.routing.rules[] + | select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))]; + def xray_final_rule($tag; $single_tag): + if $tag == "proxy" and "${selectionMode}" == "urltest" then + {type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag) + else + {type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag} + end; + def xray_dns_server_order($dns_final): + if $dns_final == "" then + .dns.servers + else + ([.dns.servers[] | select((.tag? // "") == "fakedns")] + + [.dns.servers[] | select((.tag? // "") == $dns_final)] + + [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)]) + end; + def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr): + if $dns_final == "local" then + [$local_addr, $remote_addr] + elif $dns_final == "remote" then + [$remote_addr, $local_addr] + else + [$remote_addr, $local_addr] + end; + .outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface))) + | if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end + | if $auth_enabled then + (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password" + | (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}] + else . end + | if $xray_tun_dns_runtime then + .dns.servers = xray_dns_server_order($dns_final) + | if $dns_final == "" then + . + else + (.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client) + end + else . end + | if $route_enabled then + .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) + else . end + | if $xray_single_proxy_tag == "" then + . + else + .routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag)) + | del(.routing.balancers) + | del(.observatory) + end + '' +else + '' + def sing_box_preserved_rules: + [.route.rules[] + | select(((.action? // "") == "hijack-dns") + and (((.inbound? // []) | index("xray-dns-in")) != null))]; + .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 = (sing_box_preserved_rules + $route_rules) + | .route.final = $route_final + | .dns.final = $dns_final + | if $clear_dns_rules then .dns.rules = [] else . end + else . end + '' diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix new file mode 100644 index 0000000..cff4cfa --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix @@ -0,0 +1,111 @@ +{ + lib, + jq, + hybridEnabled, + xraySidecarRoutingMark, +}: + +routingMark: xraySidecarBasePort: xrayDnsBridgePort: + +lib.optionalString hybridEnabled '' + XRAY_OUTBOUNDS_JSON='[]' + XRAY_INBOUNDS_JSON='[]' + XRAY_ROUTE_RULES_JSON='[]' + XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort} + XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort} + + _proxy_suite_add_sing_box_ob() { + local ob="$1" + OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON") + } + + _proxy_suite_next_xray_sidecar_port() { + local port="$XRAY_SIDECAR_NEXT_PORT" + XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1)) + printf '%s\n' "$port" + } + + _proxy_suite_add_xray_sidecar_ob() { + local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule + port="$(_proxy_suite_next_xray_sidecar_port)" + auth="proxy-suite-xray-$port" + inbound_tag="$tag-inbound" + ob=$(${jq} \ + --arg tag "$tag" \ + --argjson mark ${toString xraySidecarRoutingMark} \ + '.tag = $tag + | .streamSettings = (.streamSettings // {}) + | .streamSettings.sockopt = (.streamSettings.sockopt // {}) + | .streamSettings.sockopt.mark = $mark + | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \ + <<< "$ob") + XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON") + inbound=$(${jq} -n \ + --arg tag "$inbound_tag" \ + --arg auth "$auth" \ + --argjson port "$port" \ + '{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}') + XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON") + route_rule=$(${jq} -n \ + --arg inbound "$inbound_tag" \ + --arg outbound "$tag" \ + '{type:"field",inboundTag:[$inbound],outboundTag:$outbound}') + XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON") + sing_ob=$(${jq} -n \ + --arg tag "$tag" \ + --arg auth "$auth" \ + --argjson port "$port" \ + '{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${ + lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}" + }}') + OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON") + } + + _proxy_suite_write_xray_sidecar_config() { + if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then + return 0 + fi + ${jq} -n \ + --arg loglevel "$XRAY_LOGLEVEL" \ + --arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \ + --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ + --argjson inbounds "$XRAY_INBOUNDS_JSON" \ + --argjson outbounds "$XRAY_OUTBOUNDS_JSON" \ + --argjson route_rules "$XRAY_ROUTE_RULES_JSON" \ + ' + def bind_xray_sidecar($interface): + if $interface == "" then + . + else + .streamSettings = (.streamSettings // {}) + | .streamSettings.sockopt = (.streamSettings.sockopt // {}) + | if (.streamSettings.sockopt.interface? // "") == "" then + .streamSettings.sockopt.interface = $interface + else + . + end + end; + { + log: { + loglevel: (if $loglevel == "" then "warning" else $loglevel end), + access: "none" + }, + dns: { + servers: [ + { + address: "127.0.0.1", + port: $dns_port, + queryStrategy: "UseIP", + skipFallBack: true + } + ] + }, + inbounds: $inbounds, + outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]), + routing: { + domainStrategy: "AsIs", + rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) + } + }' > "$RUNTIME_DIR/xray-sidecar.json" + } +'' diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix new file mode 100644 index 0000000..b9e7532 --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -0,0 +1,230 @@ +# Outbound construction script fragments for backend startup scripts. +{ + lib, + pkgs, + singBoxCfg, + proxyCfg, + pureXrayEnabled, + hybridEnabled, + collapseNamedOutbounds, + selectionMode, + backend, + backendArg, + xraySidecarRoutingMark, + jq, + python3, + parserScriptsPythonPath, + buildOutboundPy, + mkSubscriptionBlock, +}: + +let + rawOutboundJson = + ob: tag: routingMark: + let + backendRaw = + if pureXrayEnabled then + ob.xrayJson + else if ob.singBoxJson != null then + ob.singBoxJson + else + ob.json; + markAttrs = + if routingMark == null then + { } + else if pureXrayEnabled then + { streamSettings.sockopt.mark = routingMark; } + else + { routing_mark = routingMark; }; + taggedRaw = backendRaw // { + inherit tag; + }; + in + if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs; + + mkOutboundBlock = + ob: routingMark: tag: + let + backendRaw = + if pureXrayEnabled then + ob.xrayJson + else if ob.singBoxJson != null then + ob.singBoxJson + else + ob.json; + in + if backendRaw != null then + let + outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark); + jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson; + in + '' + # outbound: ${tag} (static ${backend} json) + OB_JSON=$(cat "${jsonFile}") + OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") + '' + else + let + urlSource = + if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url; + in + '' + # outbound: ${tag} + URL=$(cat "${urlSource}") + 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") + ''; + + singBoxRawOutboundJson = + ob: tag: routingMark: + let + backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json; + markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }; + in + backendRaw // { inherit tag; } // markAttrs; + + xrayRawOutboundJson = + ob: tag: + lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) { + streamSettings.sockopt = { + mark = xraySidecarRoutingMark; + domainStrategy = "UseIP"; + }; + }; + + mkHybridOutboundBlock = + ob: routingMark: tag: + if ob.xrayJson != null then + let + outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag); + jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson; + in + '' + # outbound: ${tag} (hybrid XRay json sidecar) + OB_JSON=$(cat "${jsonFile}") + _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} + '' + else if ob.singBoxJson != null || ob.json != null then + let + outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark); + jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson; + in + '' + # outbound: ${tag} (hybrid SingBox json) + OB_JSON=$(cat "${jsonFile}") + _proxy_suite_add_sing_box_ob "$OB_JSON" + '' + else + let + urlSource = + if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url; + singBoxCommand = '' + printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${ + lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}" + } + ''; + xrayCommand = '' + printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark} + ''; + in + if ob.backend == "xray" then + '' + # outbound: ${tag} (hybrid forced XRay sidecar) + URL=$(cat "${urlSource}") + OB_JSON=$(${xrayCommand}) + _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} + '' + else if ob.backend == "sing-box" then + '' + # outbound: ${tag} (hybrid forced SingBox) + URL=$(cat "${urlSource}") + OB_JSON=$(${singBoxCommand}) + _proxy_suite_add_sing_box_ob "$OB_JSON" + '' + else + '' + # outbound: ${tag} (hybrid auto) + URL=$(cat "${urlSource}") + if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then + _proxy_suite_add_sing_box_ob "$OB_JSON" + else + SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)" + if OB_JSON=$(${xrayCommand}); then + _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} + else + echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2 + if [ -n "$SING_BOX_PARSE_ERROR" ]; then + printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2 + fi + exit 1 + fi + fi + ''; + + mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock; + + requireOutboundsBlock = '' + if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then + echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2 + exit 1 + fi + ''; + + mkOutboundScript = + routingMark: + let + outboundBlocks = + if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then + mkBackendOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy" + else + lib.concatMapStrings (ob: mkBackendOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds; + + subscriptionBlocks = lib.concatMapStrings ( + sub: mkSubscriptionBlock sub routingMark + ) proxyCfg.subscriptions; + + wrapperBlock = + if pureXrayEnabled && selectionMode == "urltest" then + '' + OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON") + if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then + XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")" + fi + '' + else if collapseNamedOutbounds then + lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) '' + FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON") + if [ -n "$FIRST_TAG" ]; then + OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \ + 'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON") + fi + '' + else if selectionMode == "selector" then + '' + TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") + FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") + WRAPPER=$(${jq} -n \ + --argjson tags "$TAGS" \ + --arg default "$FIRST" \ + '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') + OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") + '' + else + '' + TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") + WRAPPER=$(${jq} -n \ + --argjson tags "$TAGS" \ + --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ + --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \ + --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ + '{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}') + OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") + ''; + in + outboundBlocks + subscriptionBlocks + requireOutboundsBlock + wrapperBlock; +in +{ + inherit mkOutboundScript rawOutboundJson; +} diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix new file mode 100644 index 0000000..9330d13 --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -0,0 +1,154 @@ +# Subscription cache and outbound-loading script fragments. +{ + lib, + pkgs, + proxyCfg, + hasSubscriptions, + hybridEnabled, + mainBackend, + backend, + jq, + python3, + parserScriptsPythonPath, + fetchSubscriptionPy, + routingMarkJq, +}: + +let + subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend; + subscriptionBackendArg = "--backend ${subscriptionBackend}"; + subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}"; + + mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json"; + + mkSubscriptionUrlSource = + sub: + if sub.urlFile != null then + sub.urlFile + else + pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url; + + mkSubscriptionFetchCommand = + sub: + let + urlSource = mkSubscriptionUrlSource sub; + in + '' + printf '%s' "$(cat "${urlSource}")" \ + | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag} + ''; + + subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions '' + _proxy_suite_valid_subscription_cache() { + [ -s "$1" ] && ${jq} -e ${ + lib.escapeShellArg ( + if hybridEnabled then + ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' + else + ''type == "array"'' + ) + } "$1" >/dev/null 2>&1 + } + + _proxy_suite_commit_subscription_cache() { + local tmp="$1" target="$2" tag="$3" + if _proxy_suite_valid_subscription_cache "$tmp"; then + mv "$tmp" "$target" + return 0 + fi + rm -f "$tmp" + echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2 + return 1 + } + + _proxy_suite_drop_invalid_subscription_cache() { + local target="$1" tag="$2" + if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then + rm -f "$target" + echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2 + fi + } + ''; + + mkSubscriptionBlock = + sub: routingMark: + let + cacheFile = mkSubscriptionCacheFile sub; + markFilter = routingMarkJq routingMark; + in + '' + # subscription: ${sub.tag} + CACHE_DIR="${subscriptionCacheDir}" + CACHE_FILE="${cacheFile}" + _proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag} + if [ ! -f "$CACHE_FILE" ]; then + mkdir -p "$CACHE_DIR" + if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then + _proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true + else + rm -f "$CACHE_FILE.tmp" + echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2 + fi + fi + ${ + if hybridEnabled then + '' + if [ -f "$CACHE_FILE" ]; then + SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE") + ${ + lib.optionalString (routingMark != null) '' + SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON") + '' + }OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") + while IFS= read -r SUB_XRAY_OB; do + SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")" + _proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG" + done < <(${jq} -c '.xray[]' "$CACHE_FILE") + fi + '' + else + '' + if [ -f "$CACHE_FILE" ]; then + SUB_JSON=$(cat "$CACHE_FILE") + ${ + lib.optionalString (routingMark != null) '' + SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON") + '' + }OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") + fi + '' + } + ''; + + mkSubscriptionFetchBlock = + sub: + let + cacheFile = mkSubscriptionCacheFile sub; + in + '' + if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then + if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then + echo "Updated subscription: ${sub.tag}" + else + FAILED=1 + fi + else + rm -f "${cacheFile}.tmp" + echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2 + FAILED=1 + fi + ''; + + subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( + builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions) + ); +in +{ + inherit + subscriptionCacheDir + subscriptionCacheHelpersBlock + mkSubscriptionBlock + mkSubscriptionFetchBlock + subscriptionTagsFile + ; +} diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 2f8db35..4535e49 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -1,18 +1,15 @@ -# Generates proxy backend startup scripts and subscription management scripts. +# Assembles proxy backend startup and control scripts. { lib, pkgs, singBoxCfg, proxyCfg, - proxyEnabled, - singBoxEnabled, xrayEnabled, hybridEnabled, pureXrayEnabled, activeBackend, perAppRoutingCfg, userControlCfg, - perAppRoutingTun, selectionMode, collapseNamedOutbounds, hasSubscriptions, @@ -32,12 +29,9 @@ let globalTproxy = proxyCfg.tproxy; - systemctl = "${pkgs.systemd}/bin/systemctl"; backend = if activeBackend == null then "sing-box" else activeBackend; mainBackend = if pureXrayEnabled then "xray" else "sing-box"; - subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend; backendArg = "--backend ${mainBackend}"; - subscriptionBackendArg = "--backend ${subscriptionBackend}"; backendBin = if pureXrayEnabled then xray else singBox; localProxyAuth = proxyCfg.auth; localProxyAuthEnabled = @@ -50,66 +44,10 @@ let pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password else null; - subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}"; routeModeStateFile = "/run/proxy-suite/route-mode"; xrayLoglevelFile = "/run/proxy-suite/xray-loglevel"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; xraySidecarRoutingMark = globalTproxy.proxyMark; - inherit (constants) - xrayDnsBridgePorts - xraySidecarBasePorts - ; - - mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json"; - - mkSubscriptionUrlSource = - sub: - if sub.urlFile != null then - sub.urlFile - else - pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url; - - mkSubscriptionFetchCommand = - sub: - let - urlSource = mkSubscriptionUrlSource sub; - in - '' - printf '%s' "$(cat "${urlSource}")" \ - | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag} - ''; - - subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions '' - _proxy_suite_valid_subscription_cache() { - [ -s "$1" ] && ${jq} -e ${ - lib.escapeShellArg ( - if hybridEnabled then - ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' - else - ''type == "array"'' - ) - } "$1" >/dev/null 2>&1 - } - - _proxy_suite_commit_subscription_cache() { - local tmp="$1" target="$2" tag="$3" - if _proxy_suite_valid_subscription_cache "$tmp"; then - mv "$tmp" "$target" - return 0 - fi - rm -f "$tmp" - echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2 - return 1 - } - - _proxy_suite_drop_invalid_subscription_cache() { - local target="$1" tag="$2" - if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then - rm -f "$target" - echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2 - fi - } - ''; routingMarkJq = routingMark: @@ -120,795 +58,119 @@ let else " | .routing_mark = ${toString routingMark}"; - rawOutboundJson = - ob: tag: routingMark: - let - backendRaw = - if pureXrayEnabled then - ob.xrayJson - else if ob.singBoxJson != null then - ob.singBoxJson - else - ob.json; - markAttrs = - if routingMark == null then - { } - else if pureXrayEnabled then - { streamSettings.sockopt.mark = routingMark; } - else - { routing_mark = routingMark; }; - taggedRaw = backendRaw // { - inherit tag; - }; - in - if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs; + subscriptionScripts = import ./script-blocks/subscriptions.nix { + inherit + lib + pkgs + proxyCfg + hasSubscriptions + hybridEnabled + mainBackend + backend + jq + python3 + parserScriptsPythonPath + fetchSubscriptionPy + routingMarkJq + ; + }; + inherit (subscriptionScripts) + subscriptionCacheDir + subscriptionCacheHelpersBlock + mkSubscriptionBlock + mkSubscriptionFetchBlock + subscriptionTagsFile + ; - mkOutboundBlock = - ob: routingMark: tag: - let - backendRaw = - if pureXrayEnabled then - ob.xrayJson - else if ob.singBoxJson != null then - ob.singBoxJson - else - ob.json; - in - if backendRaw != null then - let - outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark); - jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson; - in - '' - # outbound: ${tag} (static ${backend} json) - OB_JSON=$(cat "${jsonFile}") - OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") - '' - else - let - urlSource = - if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url; - in - '' - # outbound: ${tag} - URL=$(cat "${urlSource}") - 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") - ''; + outboundScripts = import ./script-blocks/outbounds.nix { + inherit + lib + pkgs + singBoxCfg + proxyCfg + pureXrayEnabled + hybridEnabled + collapseNamedOutbounds + selectionMode + backend + backendArg + xraySidecarRoutingMark + jq + python3 + parserScriptsPythonPath + buildOutboundPy + mkSubscriptionBlock + ; + }; + inherit (outboundScripts) mkOutboundScript; - singBoxRawOutboundJson = - ob: tag: routingMark: - let - backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json; - markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }; - in - backendRaw // { inherit tag; } // markAttrs; - - xrayRawOutboundJson = - ob: tag: - lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) { - streamSettings.sockopt = { - mark = xraySidecarRoutingMark; - domainStrategy = "UseIP"; - }; - }; - - mkHybridOutboundBlock = - ob: routingMark: tag: - if ob.xrayJson != null then - let - outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag); - jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson; - in - '' - # outbound: ${tag} (hybrid XRay json sidecar) - OB_JSON=$(cat "${jsonFile}") - _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} - '' - else if ob.singBoxJson != null || ob.json != null then - let - outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark); - jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson; - in - '' - # outbound: ${tag} (hybrid SingBox json) - OB_JSON=$(cat "${jsonFile}") - _proxy_suite_add_sing_box_ob "$OB_JSON" - '' - else - let - urlSource = - if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url; - singBoxCommand = '' - printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${ - lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}" - } - ''; - xrayCommand = '' - printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark} - ''; - in - if ob.backend == "xray" then - '' - # outbound: ${tag} (hybrid forced XRay sidecar) - URL=$(cat "${urlSource}") - OB_JSON=$(${xrayCommand}) - _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} - '' - else if ob.backend == "sing-box" then - '' - # outbound: ${tag} (hybrid forced SingBox) - URL=$(cat "${urlSource}") - OB_JSON=$(${singBoxCommand}) - _proxy_suite_add_sing_box_ob "$OB_JSON" - '' - else - '' - # outbound: ${tag} (hybrid auto) - URL=$(cat "${urlSource}") - if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then - _proxy_suite_add_sing_box_ob "$OB_JSON" - else - SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)" - if OB_JSON=$(${xrayCommand}); then - _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} - else - echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2 - if [ -n "$SING_BOX_PARSE_ERROR" ]; then - printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2 - fi - exit 1 - fi - fi - ''; - - mkSubscriptionBlock = - sub: routingMark: - let - cacheFile = mkSubscriptionCacheFile sub; - markFilter = routingMarkJq routingMark; - in - '' - # subscription: ${sub.tag} - CACHE_DIR="${subscriptionCacheDir}" - CACHE_FILE="${cacheFile}" - _proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag} - if [ ! -f "$CACHE_FILE" ]; then - mkdir -p "$CACHE_DIR" - if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then - _proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true - else - rm -f "$CACHE_FILE.tmp" - echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2 - fi - fi - ${ - if hybridEnabled then - '' - if [ -f "$CACHE_FILE" ]; then - SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE") - ${ - lib.optionalString (routingMark != null) '' - SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON") - '' - }OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") - while IFS= read -r SUB_XRAY_OB; do - SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")" - _proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG" - done < <(${jq} -c '.xray[]' "$CACHE_FILE") - fi - '' - else - '' - if [ -f "$CACHE_FILE" ]; then - SUB_JSON=$(cat "$CACHE_FILE") - ${ - lib.optionalString (routingMark != null) '' - SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON") - '' - }OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") - fi - '' - } - ''; - - xrayUrltestTagFilter = '' - OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON") - if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then - XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")" - fi - ''; - - hybridRuntimeHelpersBlock = - routingMark: xraySidecarBasePort: xrayDnsBridgePort: - lib.optionalString hybridEnabled '' - XRAY_OUTBOUNDS_JSON='[]' - XRAY_INBOUNDS_JSON='[]' - XRAY_ROUTE_RULES_JSON='[]' - XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort} - XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort} - - _proxy_suite_add_sing_box_ob() { - local ob="$1" - OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON") - } - - _proxy_suite_next_xray_sidecar_port() { - local port="$XRAY_SIDECAR_NEXT_PORT" - XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1)) - printf '%s\n' "$port" - } - - _proxy_suite_add_xray_sidecar_ob() { - local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule - port="$(_proxy_suite_next_xray_sidecar_port)" - auth="proxy-suite-xray-$port" - inbound_tag="$tag-inbound" - ob=$(${jq} \ - --arg tag "$tag" \ - --argjson mark ${toString xraySidecarRoutingMark} \ - '.tag = $tag - | .streamSettings = (.streamSettings // {}) - | .streamSettings.sockopt = (.streamSettings.sockopt // {}) - | .streamSettings.sockopt.mark = $mark - | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \ - <<< "$ob") - XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON") - inbound=$(${jq} -n \ - --arg tag "$inbound_tag" \ - --arg auth "$auth" \ - --argjson port "$port" \ - '{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}') - XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON") - route_rule=$(${jq} -n \ - --arg inbound "$inbound_tag" \ - --arg outbound "$tag" \ - '{type:"field",inboundTag:[$inbound],outboundTag:$outbound}') - XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON") - sing_ob=$(${jq} -n \ - --arg tag "$tag" \ - --arg auth "$auth" \ - --argjson port "$port" \ - '{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${ - lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}" - }}') - OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON") - } - - _proxy_suite_write_xray_sidecar_config() { - if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then - return 0 - fi - ${jq} -n \ - --arg loglevel "$XRAY_LOGLEVEL" \ - --arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \ - --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ - --argjson inbounds "$XRAY_INBOUNDS_JSON" \ - --argjson outbounds "$XRAY_OUTBOUNDS_JSON" \ - --argjson route_rules "$XRAY_ROUTE_RULES_JSON" \ - ' - def bind_xray_sidecar($interface): - if $interface == "" then - . - else - .streamSettings = (.streamSettings // {}) - | .streamSettings.sockopt = (.streamSettings.sockopt // {}) - | if (.streamSettings.sockopt.interface? // "") == "" then - .streamSettings.sockopt.interface = $interface - else - . - end - end; - { - log: { - loglevel: (if $loglevel == "" then "warning" else $loglevel end), - access: "none" - }, - dns: { - servers: [ - { - address: "127.0.0.1", - port: $dns_port, - queryStrategy: "UseIP", - skipFallBack: true - } - ] - }, - inbounds: $inbounds, - outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]), - routing: { - domainStrategy: "AsIs", - rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) - } - }' > "$RUNTIME_DIR/xray-sidecar.json" - } - ''; - - mkOutboundScript = - routingMark: - let - outboundBlocks = - if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then - (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock) - (builtins.head proxyCfg.outbounds) - routingMark - "proxy" - else - lib.concatMapStrings ( - ob: (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock) ob routingMark ob.tag - ) proxyCfg.outbounds; - - subscriptionBlocks = lib.concatMapStrings ( - sub: mkSubscriptionBlock sub routingMark - ) proxyCfg.subscriptions; - - requireOutboundsBlock = '' - if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then - echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2 - exit 1 - fi - ''; - - wrapperBlock = - if pureXrayEnabled && selectionMode == "urltest" then - xrayUrltestTagFilter - else if collapseNamedOutbounds then - lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) '' - FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON") - if [ -n "$FIRST_TAG" ]; then - OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \ - 'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON") - fi - '' - else if selectionMode == "selector" then - '' - TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") - FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") - WRAPPER=$(${jq} -n \ - --argjson tags "$TAGS" \ - --arg default "$FIRST" \ - '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') - OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") - '' - else - '' - TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") - WRAPPER=$(${jq} -n \ - --argjson tags "$TAGS" \ - --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ - --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \ - --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ - '{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}') - OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") - ''; - in - outboundBlocks + subscriptionBlocks + requireOutboundsBlock + wrapperBlock; - - writeProxychainsConfigBlock = '' - { - printf '%s\n' 'strict_chain' - ${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"} - ${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"} - printf '%s\n' 'tcp_read_time_out 15000' - printf '%s\n' 'tcp_connect_time_out 8000' - printf '\n%s\n' '[ProxyList]' - printf 'socks5 %s %s %s %s\n' \ - ${lib.escapeShellArg proxyCfg.listenAddress} \ - ${lib.escapeShellArg (toString proxyCfg.port)} \ - ${lib.escapeShellArg localProxyAuth.username} \ - "$LOCAL_PROXY_PASSWORD" - } > "${runtimeProxychainsConfig}" - ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}" - chmod 640 "${runtimeProxychainsConfig}" - ''; - - restartActiveConfigConsumersBlock = - lib.concatMapStrings - (svc: '' - if ${systemctl} is-active --quiet ${svc}; then - ${systemctl} restart ${svc} - fi - '') - [ - "proxy-suite-socks" - "proxy-suite-tun" - "proxy-suite-per-app-tun" - ]; - - routeModeBlacklistTail = - if pureXrayEnabled then - '' - + .proxyGeo - + .block - '' - else - '' - + .block - + .proxyGeo - ''; - - 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 - ${routeModeBlacklistTail} - ' "${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 - ${routeModeBlacklistTail} - ' "${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 - ${routeModeBlacklistTail} - ' "${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 pureXrayEnabled then - '' - def xray_bind_outbound($interface): - if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then - . - else - .streamSettings = (.streamSettings // {}) - | .streamSettings.sockopt = (.streamSettings.sockopt // {}) - | if (.streamSettings.sockopt.interface? // "") == "" then - .streamSettings.sockopt.interface = $interface - else - . - end - end; - def xray_proxy_rule_target($single_tag): - if $single_tag != "" then - {outboundTag:$single_tag} - else - {balancerTag:"proxy"} - end; - def xray_rewrite_proxy_rule($single_tag): - if $single_tag != "" and (.balancerTag? // "") == "proxy" then - .outboundTag = $single_tag | del(.balancerTag) - else - . - end; - def xray_preserved_rules: - [.routing.rules[] - | select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))]; - def xray_final_rule($tag; $single_tag): - if $tag == "proxy" and "${selectionMode}" == "urltest" then - {type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag) - else - {type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag} - end; - def xray_dns_server_order($dns_final): - if $dns_final == "" then - .dns.servers - else - ([.dns.servers[] | select((.tag? // "") == "fakedns")] - + [.dns.servers[] | select((.tag? // "") == $dns_final)] - + [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)]) - end; - def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr): - if $dns_final == "local" then - [$local_addr, $remote_addr] - elif $dns_final == "remote" then - [$remote_addr, $local_addr] - else - [$remote_addr, $local_addr] - end; - .outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface))) - | if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end - | if $auth_enabled then - (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password" - | (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}] - else . end - | if $xray_tun_dns_runtime then - .dns.servers = xray_dns_server_order($dns_final) - | if $dns_final == "" then - . - else - (.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client) - end - else . end - | if $route_enabled then - .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) - else . end - | if $xray_single_proxy_tag == "" then - . - else - .routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag)) - | del(.routing.balancers) - | del(.observatory) - end - '' - else - '' - def sing_box_preserved_rules: - [.route.rules[] - | select(((.action? // "") == "hijack-dns") - and (((.inbound? // []) | index("xray-dns-in")) != null))]; - .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 = (sing_box_preserved_rules + $route_rules) - | .route.final = $route_final - | .dns.final = $dns_final - | if $clear_dns_rules then .dns.rules = [] else . end - else . end - ''; - backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" mkBackendJqFilter; - - mkStartScript = - { - name, - runtimeDir, - configFile, - routingMark ? null, - enableLocalProxyAuth ? false, - xrayTunEgressBinding ? false, - xrayTunDnsRuntime ? false, - xraySidecarBasePort ? xraySidecarBasePorts.socks, - xrayDnsBridgePort ? xrayDnsBridgePorts.socks, - }: - pkgs.writeShellScript name '' - set -euo pipefail - RUNTIME_DIR="${runtimeDir}" - ROUTE_MODE_STATE_FILE="${routeModeStateFile}" - BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile} - XRAY_LOGLEVEL="" - XRAY_TUN_BIND_INTERFACE="" - XRAY_SINGLE_PROXY_TAG="" - mkdir -p "$RUNTIME_DIR" - OUTBOUNDS_JSON='[]' - ROUTE_MODE="" - ROUTE_FINAL="" - DNS_FINAL="" - ROUTE_RULES_JSON='[]' - ROUTE_MODE_ACTIVE=false - CLEAR_DNS_RULES=false - ${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort} - ${subscriptionCacheHelpersBlock} - ${lib.optionalString enableLocalProxyAuth '' - umask 077 - LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" - ${writeProxychainsConfigBlock} - ''} - ${lib.optionalString xrayEnabled '' - if [ -r "${xrayLoglevelFile}" ]; then - XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)" - fi - ''} - ${lib.optionalString xrayTunEgressBinding '' - XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk ' - /dev/ { - for (i = 1; i <= NF; i++) { - if ($i == "dev" && i + 1 <= NF) { - print $(i + 1) - exit - } - } - } - ')" - if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then - echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2 - exit 1 - fi - ''} - - ${routeModeCaseBlock} - - ${mkOutboundScript routingMark} - ${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"} - - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \ - --arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \ - --arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \ - --argjson route_enabled "$ROUTE_MODE_ACTIVE" \ - --argjson route_rules "$ROUTE_RULES_JSON" \ - --arg route_final "$ROUTE_FINAL" \ - --arg dns_final "$DNS_FINAL" \ - --argjson clear_dns_rules "$CLEAR_DNS_RULES" \ - --arg xray_loglevel "$XRAY_LOGLEVEL" \ - --arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \ - --arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \ - --argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \ - --arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \ - --arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \ - -f "$BACKEND_JQ_FILTER" \ - "${configFile}" > "$RUNTIME_DIR/config.json" - ${lib.optionalString enableLocalProxyAuth '' - chmod 600 "$RUNTIME_DIR/config.json" - ''} - - ${ - if hybridEnabled then - '' - if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then - XRAY_SIDECAR_PID="" - _proxy_suite_cleanup_xray_sidecar() { - if [ -n "$XRAY_SIDECAR_PID" ]; then - kill "$XRAY_SIDECAR_PID" 2>/dev/null || true - wait "$XRAY_SIDECAR_PID" 2>/dev/null || true - fi - } - trap _proxy_suite_cleanup_xray_sidecar EXIT - trap 'exit 143' INT TERM - - ${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" & - XRAY_SIDECAR_PID="$!" - ${pkgs.coreutils}/bin/sleep 0.2 - if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then - XRAY_SIDECAR_STATUS=1 - wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?" - exit "$XRAY_SIDECAR_STATUS" - fi - - ${singBox} run -c "$RUNTIME_DIR/config.json" & - SING_BOX_PID="$!" - SING_BOX_STATUS=0 - wait "$SING_BOX_PID" || SING_BOX_STATUS="$?" - exit "$SING_BOX_STATUS" - fi - - exec ${singBox} run -c "$RUNTIME_DIR/config.json" - '' - else - '' - exec ${backendBin} run -c "$RUNTIME_DIR/config.json" - '' - } - ''; - - startSocks = mkStartScript { - name = "proxy-suite-start-socks"; - runtimeDir = "/run/proxy-suite-socks"; - configFile = tproxyFile; - routingMark = globalTproxy.proxyMark; - enableLocalProxyAuth = localProxyAuthEnabled; - xraySidecarBasePort = xraySidecarBasePorts.socks; - xrayDnsBridgePort = xrayDnsBridgePorts.socks; + hybridRuntimeHelpersBlock = import ./script-blocks/hybrid-runtime-helpers.nix { + inherit + lib + jq + hybridEnabled + xraySidecarRoutingMark + ; }; - startTun = mkStartScript { - name = "proxy-suite-start-tun"; - runtimeDir = "/run/proxy-suite-tun"; - configFile = tunFile; - routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; - xrayTunEgressBinding = xrayEnabled; - xrayTunDnsRuntime = pureXrayEnabled; - xraySidecarBasePort = xraySidecarBasePorts.tun; - xrayDnsBridgePort = xrayDnsBridgePorts.tun; + backendJqFilter = import ./script-blocks/backend-jq-filter.nix { + inherit + pureXrayEnabled + selectionMode + ; }; + backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" backendJqFilter; - startPerAppTun = mkStartScript { - name = "proxy-suite-start-per-app-tun"; - runtimeDir = "/run/proxy-suite-per-app-tun"; - configFile = perAppTunFile; - routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; - xrayTunEgressBinding = xrayEnabled; - xrayTunDnsRuntime = pureXrayEnabled; - xraySidecarBasePort = xraySidecarBasePorts.perAppTun; - xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; + startScripts = import ./start-scripts.nix { + inherit + lib + pkgs + proxyCfg + perAppRoutingCfg + userControlCfg + globalTproxy + xrayEnabled + hybridEnabled + pureXrayEnabled + constants + jq + singBox + xray + backendBin + routeModeStateFile + routeModeRulesFile + xrayLoglevelFile + runtimeProxychainsConfig + localProxyAuth + localProxyAuthEnabled + localProxyAuthPasswordSource + backendJqFilterFile + hybridRuntimeHelpersBlock + subscriptionCacheHelpersBlock + mkOutboundScript + tproxyFile + tunFile + perAppTunFile + ; }; + inherit (startScripts) startSocks startTun startPerAppTun; - mkSubscriptionFetchBlock = - sub: - let - cacheFile = mkSubscriptionCacheFile sub; - in - '' - if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then - if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then - echo "Updated subscription: ${sub.tag}" - else - FAILED=1 - fi - else - rm -f "${cacheFile}.tmp" - echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2 - FAILED=1 - fi - ''; + controlScripts = import ./control-scripts.nix { + inherit + lib + pkgs + proxyCfg + routeModeStateFile + subscriptionCacheDir + subscriptionCacheHelpersBlock + mkSubscriptionFetchBlock + ; + }; + inherit (controlScripts) + subscriptionUpdateScript + setRouteModeScript + ; - subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" '' - set -euo pipefail - CACHE_DIR="${subscriptionCacheDir}" - mkdir -p "$CACHE_DIR" - FAILED=0 - ${subscriptionCacheHelpersBlock} - ${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions} - - if [ "$FAILED" -eq 0 ]; then - ${restartActiveConfigConsumersBlock} - fi - exit "$FAILED" - ''; - - setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" '' - set -euo pipefail - mode="''${1:-}" - - case "$mode" in - default) - ;; - whitelist) - ;; - blacklist) - ;; - all-proxy) - ;; - all-bypass) - ;; - *) - echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2 - exit 1 - ;; - esac - - mkdir -p "$(dirname "${routeModeStateFile}")" - if [ "$mode" = "default" ]; then - rm -f "${routeModeStateFile}" - else - printf '%s\n' "$mode" > "${routeModeStateFile}" - fi - - ${restartActiveConfigConsumersBlock} - ''; - - subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( - builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions) - ); in { inherit startSocks startTun startPerAppTun; diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix new file mode 100644 index 0000000..7c32a9b --- /dev/null +++ b/modules/proxy-suite/service/start-scripts.nix @@ -0,0 +1,288 @@ +# Backend startup script derivations. +{ + lib, + pkgs, + proxyCfg, + perAppRoutingCfg, + userControlCfg, + globalTproxy, + xrayEnabled, + hybridEnabled, + pureXrayEnabled, + constants, + jq, + singBox, + xray, + backendBin, + routeModeStateFile, + routeModeRulesFile, + xrayLoglevelFile, + runtimeProxychainsConfig, + localProxyAuth, + localProxyAuthEnabled, + localProxyAuthPasswordSource, + backendJqFilterFile, + hybridRuntimeHelpersBlock, + subscriptionCacheHelpersBlock, + mkOutboundScript, + tproxyFile, + tunFile, + perAppTunFile, +}: + +let + inherit (constants) + xrayDnsBridgePorts + xraySidecarBasePorts + ; + + routeModeBlacklistTail = + if pureXrayEnabled then + '' + + .proxyGeo + + .block + '' + else + '' + + .block + + .proxyGeo + ''; + + 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 + ${routeModeBlacklistTail} + ' "${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 + ${routeModeBlacklistTail} + ' "${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 + ${routeModeBlacklistTail} + ' "${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 + ''; + + writeProxychainsConfigBlock = '' + { + printf '%s\n' 'strict_chain' + ${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"} + ${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"} + printf '%s\n' 'tcp_read_time_out 15000' + printf '%s\n' 'tcp_connect_time_out 8000' + printf '\n%s\n' '[ProxyList]' + printf 'socks5 %s %s %s %s\n' \ + ${lib.escapeShellArg proxyCfg.listenAddress} \ + ${lib.escapeShellArg (toString proxyCfg.port)} \ + ${lib.escapeShellArg localProxyAuth.username} \ + "$LOCAL_PROXY_PASSWORD" + } > "${runtimeProxychainsConfig}" + ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}" + chmod 640 "${runtimeProxychainsConfig}" + ''; + + mkStartScript = + { + name, + runtimeDir, + configFile, + routingMark ? null, + enableLocalProxyAuth ? false, + xrayTunEgressBinding ? false, + xrayTunDnsRuntime ? false, + xraySidecarBasePort ? xraySidecarBasePorts.socks, + xrayDnsBridgePort ? xrayDnsBridgePorts.socks, + }: + pkgs.writeShellScript name '' + set -euo pipefail + RUNTIME_DIR="${runtimeDir}" + ROUTE_MODE_STATE_FILE="${routeModeStateFile}" + BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile} + XRAY_LOGLEVEL="" + XRAY_TUN_BIND_INTERFACE="" + XRAY_SINGLE_PROXY_TAG="" + mkdir -p "$RUNTIME_DIR" + OUTBOUNDS_JSON='[]' + ROUTE_MODE="" + ROUTE_FINAL="" + DNS_FINAL="" + ROUTE_RULES_JSON='[]' + ROUTE_MODE_ACTIVE=false + CLEAR_DNS_RULES=false + ${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort} + ${subscriptionCacheHelpersBlock} + ${lib.optionalString enableLocalProxyAuth '' + umask 077 + LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" + ${writeProxychainsConfigBlock} + ''} + ${lib.optionalString xrayEnabled '' + if [ -r "${xrayLoglevelFile}" ]; then + XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)" + fi + ''} + ${lib.optionalString xrayTunEgressBinding '' + XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk ' + /dev/ { + for (i = 1; i <= NF; i++) { + if ($i == "dev" && i + 1 <= NF) { + print $(i + 1) + exit + } + } + } + ')" + if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then + echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2 + exit 1 + fi + ''} + + ${routeModeCaseBlock} + + ${mkOutboundScript routingMark} + ${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"} + + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \ + --arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \ + --arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \ + --argjson route_enabled "$ROUTE_MODE_ACTIVE" \ + --argjson route_rules "$ROUTE_RULES_JSON" \ + --arg route_final "$ROUTE_FINAL" \ + --arg dns_final "$DNS_FINAL" \ + --argjson clear_dns_rules "$CLEAR_DNS_RULES" \ + --arg xray_loglevel "$XRAY_LOGLEVEL" \ + --arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \ + --arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \ + --argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \ + --arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \ + --arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \ + -f "$BACKEND_JQ_FILTER" \ + "${configFile}" > "$RUNTIME_DIR/config.json" + ${lib.optionalString enableLocalProxyAuth '' + chmod 600 "$RUNTIME_DIR/config.json" + ''} + + ${ + if hybridEnabled then + '' + if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then + XRAY_SIDECAR_PID="" + _proxy_suite_cleanup_xray_sidecar() { + if [ -n "$XRAY_SIDECAR_PID" ]; then + kill "$XRAY_SIDECAR_PID" 2>/dev/null || true + wait "$XRAY_SIDECAR_PID" 2>/dev/null || true + fi + } + trap _proxy_suite_cleanup_xray_sidecar EXIT + trap 'exit 143' INT TERM + + ${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" & + XRAY_SIDECAR_PID="$!" + ${pkgs.coreutils}/bin/sleep 0.2 + if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then + XRAY_SIDECAR_STATUS=1 + wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?" + exit "$XRAY_SIDECAR_STATUS" + fi + + ${singBox} run -c "$RUNTIME_DIR/config.json" & + SING_BOX_PID="$!" + SING_BOX_STATUS=0 + wait "$SING_BOX_PID" || SING_BOX_STATUS="$?" + exit "$SING_BOX_STATUS" + fi + + exec ${singBox} run -c "$RUNTIME_DIR/config.json" + '' + else + '' + exec ${backendBin} run -c "$RUNTIME_DIR/config.json" + '' + } + ''; + + startSocks = mkStartScript { + name = "proxy-suite-start-socks"; + runtimeDir = "/run/proxy-suite-socks"; + configFile = tproxyFile; + routingMark = globalTproxy.proxyMark; + enableLocalProxyAuth = localProxyAuthEnabled; + xraySidecarBasePort = xraySidecarBasePorts.socks; + xrayDnsBridgePort = xrayDnsBridgePorts.socks; + }; + + startTun = mkStartScript { + name = "proxy-suite-start-tun"; + runtimeDir = "/run/proxy-suite-tun"; + configFile = tunFile; + routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; + xrayTunEgressBinding = xrayEnabled; + xrayTunDnsRuntime = pureXrayEnabled; + xraySidecarBasePort = xraySidecarBasePorts.tun; + xrayDnsBridgePort = xrayDnsBridgePorts.tun; + }; + + startPerAppTun = mkStartScript { + name = "proxy-suite-start-per-app-tun"; + runtimeDir = "/run/proxy-suite-per-app-tun"; + configFile = perAppTunFile; + routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; + xrayTunEgressBinding = xrayEnabled; + xrayTunDnsRuntime = pureXrayEnabled; + xraySidecarBasePort = xraySidecarBasePorts.perAppTun; + xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; + }; +in +{ + inherit startSocks startTun startPerAppTun; +} diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix new file mode 100644 index 0000000..fc4b514 --- /dev/null +++ b/modules/proxy-suite/service/units.nix @@ -0,0 +1,233 @@ +# Systemd unit definitions for proxy-suite services and timers. +{ + lib, + builders, + proxyCfg, + proxyEnabled, + hybridEnabled, + pureXrayEnabled, + globalTun, + globalTproxy, + perAppRoutingTun, + perAppRoutingTproxy, + perAppZapretEnabled, + hasSubscriptions, + scripts, + perAppRouting, + routingScripts, +}: + +let + inherit (builders) + mkAnchorService + mkRestartingService + mkOneshotService + mkUserRuleService + ; + + inherit (routingScripts) + xrayTunUpScript + tproxyUpScript + tproxyDownScript + tunCleanupScript + ; + + serviceNames = { + socks = "proxy-suite-socks"; + tproxy = "proxy-suite-tproxy"; + tun = "proxy-suite-tun"; + perAppTun = "proxy-suite-per-app-tun"; + perAppTproxy = "proxy-suite-per-app-tproxy"; + perAppZapret = "proxy-suite-per-app-zapret"; + subscriptionUpdate = "proxy-suite-subscription-update"; + }; + + backendDescription = + if pureXrayEnabled then + "XRay" + else if hybridEnabled then + "sing-box + XRay sidecar" + else + "sing-box"; + + localProxyAuthEnabled = + proxyCfg.auth.username != null + && (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null); + + systemServiceEntries = [ + { + enable = proxyEnabled; + name = serviceNames.socks; + value = mkRestartingService { + description = "${backendDescription} proxy client (SOCKS + TProxy-ready)"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + execStart = scripts.startSocks; + runtimeDirectory = serviceNames.socks; + stateDirectory = "proxy-suite"; + }; + } + { + enable = proxyEnabled && globalTproxy.enable; + name = serviceNames.tproxy; + value = mkOneshotService { + description = "proxy-suite TProxy - nftables rules and policy routing"; + after = [ + "network.target" + "${serviceNames.socks}.service" + ]; + wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ]; + requires = [ "${serviceNames.socks}.service" ]; + conflicts = [ + "${serviceNames.tun}.service" + "${serviceNames.perAppTproxy}.service" + ]; + execStart = tproxyUpScript; + execStop = tproxyDownScript; + }; + } + { + enable = proxyEnabled && globalTun.enable; + name = serviceNames.tun; + value = mkRestartingService { + description = "${backendDescription} TUN proxy client"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; + conflicts = [ "${serviceNames.tproxy}.service" ]; + execStartPre = tunCleanupScript; + execStart = scripts.startTun; + execStartPost = if pureXrayEnabled then xrayTunUpScript else null; + execStopPost = tunCleanupScript; + runtimeDirectory = serviceNames.tun; + stateDirectory = "proxy-suite"; + }; + } + { + enable = proxyEnabled && perAppRoutingTun.enable; + name = serviceNames.perAppTun; + value = mkRestartingService { + description = "proxy-suite per-app-routing TUN backend"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + execStartPre = perAppRouting.perAppTunDownScript; + execStart = scripts.startPerAppTun; + execStartPost = perAppRouting.perAppTunUpScript; + execStopPost = perAppRouting.perAppTunDownScript; + runtimeDirectory = serviceNames.perAppTun; + stateDirectory = "proxy-suite"; + }; + } + { + enable = proxyEnabled && perAppRoutingTun.enable; + name = "${serviceNames.perAppTun}-user@"; + value = mkUserRuleService { + description = "Enable proxy-suite app TUN marking for user %i"; + backendService = serviceNames.perAppTun; + execStart = "${perAppRouting.perAppTunUserRuleStart} %i"; + execStop = "${perAppRouting.perAppTunUserRuleStop} %i"; + }; + } + { + enable = proxyEnabled && perAppRoutingTproxy.enable; + name = serviceNames.perAppTproxy; + value = mkOneshotService { + description = "proxy-suite per-app-routing TProxy backend"; + after = [ + "network.target" + "${serviceNames.socks}.service" + ]; + requires = [ "${serviceNames.socks}.service" ]; + conflicts = [ + "${serviceNames.tproxy}.service" + "${serviceNames.tun}.service" + ]; + execStart = perAppRouting.perAppTproxyUpScript; + execStop = perAppRouting.perAppTproxyDownScript; + }; + } + { + enable = proxyEnabled && perAppRoutingTproxy.enable; + name = "${serviceNames.perAppTproxy}-user@"; + value = mkUserRuleService { + description = "Enable proxy-suite app TProxy marking for user %i"; + backendService = serviceNames.perAppTproxy; + execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i"; + execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i"; + }; + } + { + enable = perAppZapretEnabled; + name = "${serviceNames.perAppZapret}-user@"; + value = mkUserRuleService { + description = "Enable proxy-suite app zapret marking for user %i"; + backendService = serviceNames.perAppZapret; + execStart = "${perAppRouting.perAppZapretUserRuleStart} %i"; + execStop = "${perAppRouting.perAppZapretUserRuleStop} %i"; + }; + } + { + enable = proxyEnabled && hasSubscriptions; + name = serviceNames.subscriptionUpdate; + value = mkOneshotService { + description = "Refresh proxy-suite subscription caches"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + execStart = scripts.subscriptionUpdateScript; + stateDirectory = "proxy-suite"; + }; + } + { + enable = proxyEnabled; + name = "proxy-suite-route-mode@"; + value = mkOneshotService { + description = "Set proxy-suite route mode to %i"; + execStart = "${scripts.setRouteModeScript} %i"; + extraServiceConfig.RemainAfterExit = false; + }; + } + ]; + + userServiceEntries = [ + { + enable = perAppRoutingTun.enable; + name = "${serviceNames.perAppTun}-anchor"; + value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice"; + } + { + enable = perAppRoutingTproxy.enable; + name = "${serviceNames.perAppTproxy}-anchor"; + value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice"; + } + { + enable = perAppZapretEnabled; + name = "${serviceNames.perAppZapret}-anchor"; + value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice"; + } + ]; + + timerEntries = [ + { + enable = proxyEnabled && hasSubscriptions; + name = serviceNames.subscriptionUpdate; + value = { + description = "Periodic proxy-suite subscription refresh"; + wantedBy = [ "timers.target" ]; + timerConfig = { + OnBootSec = "5m"; + OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval; + }; + }; + } + ]; +in +{ + inherit + serviceNames + localProxyAuthEnabled + systemServiceEntries + userServiceEntries + timerEntries + ; +} diff --git a/modules/proxy-suite/tg-ws-proxy.nix b/modules/proxy-suite/tg-ws-proxy.nix index 2e7a32b..89f5a79 100644 --- a/modules/proxy-suite/tg-ws-proxy.nix +++ b/modules/proxy-suite/tg-ws-proxy.nix @@ -75,7 +75,7 @@ in wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; serviceConfig = { - ExecStart = "${startScript}"; + ExecStart = startScript; LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}"; Restart = "on-failure"; RestartSec = 5; diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 2485b25..b98cc80 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -1,4 +1,4 @@ -# zapret DPI bypass configuration + optional CIDR exemption from NFQUEUE +# zapret DPI bypass services and optional CIDR exemption from NFQUEUE. { lib, pkgs, @@ -14,311 +14,22 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = zapretCfg.perApp; - zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; }; - - iptables = "${pkgs.iptables}/bin/iptables"; - - runtimeDeps = lib.attrValues { - inherit (pkgs) - iptables - ipset - nftables - coreutils - gawk - curl - wget - bash - kmod - findutils - gnused - gnugrep - procps - util-linux + zapretPackages = import ./zapret/packages.nix { + inherit + lib + pkgs + cfg + zapret ; }; + inherit (zapretPackages) + globalZapretPackage + perAppZapretPackage + globalZapretEnv + perAppZapretEnv + ; - hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules; - effectiveHostlistRules = map ( - rule: - rule - // { - domains = zapretDomainGroups.effectiveRuleDomains rule; - ips = zapretDomainGroups.effectiveRuleIps rule; - presets = zapretDomainGroups.effectiveRulePresets rule; - ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule; - protocols = zapretDomainGroups.effectiveRuleProtocolFamilies rule; - } - ) zapretCfg.hostlistRules; - - baseZapretPackage = - let - upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system}; - in - if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default; - mkOptionalHostlistFile = - fileName: entries: - if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null; - - listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral; - listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude; - ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll; - ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude; - - hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" ( - builtins.toJSON { - includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists; - entries = map (rule: { - inherit (rule) - name - configName - nfqwsArgs - ipsets - presets - protocols - ; - hasDomains = rule.domains != [ ]; - hasIps = rule.ips != [ ]; - }) effectiveHostlistRules; - } - ); - - selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName; - patchConfigScriptSrc = builtins.path { - path = ../../scripts/patch-zapret-config.py; - name = "patch-zapret-config.py"; - }; - patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}"; - - mkGlobalBypassScript = - filterMark: - pkgs.writeText "proxy-suite-zapret-global-bypass.sh" '' - zapret_custom_firewall_nft() { - nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" - nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" - nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" - nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" - } - ''; - - mkDerivedZapretPackage = - { - packageName, - pidDir, - configName ? zapretCfg.configName, - gameFilter ? zapretCfg.gameFilter, - forceDisableFilterMark ? false, - filterMark ? null, - qnum ? null, - modeFilter ? null, - desyncMark ? null, - desyncMarkPostnat ? null, - nftTable ? null, - customScript ? null, - }: - pkgs.runCommand packageName - { - nativeBuildInputs = with pkgs; [ - coreutils - gnused - python3 - ]; - } - '' - set -euo pipefail - - mkdir -p "$out" - cp -a ${baseZapretPackage}/. "$out/" - chmod -R u+w "$out/opt/zapret" "$out/bin" - - find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \ - -e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \ - {} \; - find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \ - -e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \ - {} \; - - requested_config=${lib.escapeShellArg configName} - configs_dir="$out/opt/zapret/configs" - selected_config="$configs_dir/$requested_config" - - config_name_key() { - printf '%s' "$1" | tr -d '[:space:]' - } - - if [ ! -f "$selected_config" ]; then - requested_key=$(config_name_key "$requested_config") - matched_config="" - - for candidate in "$configs_dir"/*; do - [ -f "$candidate" ] || continue - candidate_name="''${candidate##*/}" - - if [ "$(config_name_key "$candidate_name")" = "$requested_key" ]; then - if [ -n "$matched_config" ]; then - echo "proxy-suite: zapret config '$requested_config' is ambiguous after whitespace normalization" >&2 - echo "proxy-suite: matched '$matched_config' and '$candidate'" >&2 - exit 1 - fi - matched_config="$candidate" - fi - done - - if [ -n "$matched_config" ]; then - selected_config="$matched_config" - fi - fi - - if [ -f "$selected_config" ]; then - cp "$selected_config" "$out/opt/zapret/config" - else - echo "proxy-suite: zapret config '$requested_config' not found in curated package" >&2 - ls -la "$out/opt/zapret/configs" >&2 || true - exit 1 - fi - - ${pkgs.gnused}/bin/sed -i \ - -e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \ - "$out/opt/zapret/config" - - ${pkgs.gnused}/bin/sed -i \ - -e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \ - "$out/opt/zapret/init.d/sysv/functions" - - append_list_file() { - local target="$1" - local extra_file="$2" - local tmp="$out/opt/zapret/hostlists/$target.tmp" - cat "$out/opt/zapret/hostlists/$target" > "$tmp" - ${pkgs.gnused}/bin/sed -i -e '$a\' "$tmp" - cat "$extra_file" >> "$tmp" - mv "$tmp" "$out/opt/zapret/hostlists/$target" - } - - set_config_var() { - local key="$1" - local value="$2" - if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then - ${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config" - else - printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config" - fi - } - - ${lib.concatMapStrings - ( - { name, file }: - lib.optionalString (file != null) '' - append_list_file ${name} ${file} - '' - ) - [ - { - name = "list-general-user.txt"; - file = listGeneralFile; - } - { - name = "list-exclude-user.txt"; - file = listExcludeFile; - } - { - name = "ipset-all.txt"; - file = ipsetAllFile; - } - { - name = "ipset-exclude-user.txt"; - file = ipsetExcludeFile; - } - ] - } - - rm -f "$out/opt/zapret/hostlists/.game_filter.enabled" - ${lib.optionalString (gameFilter != "null") '' - echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled" - ''} - - ${lib.concatMapStrings ( - rule: - let - domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" ( - lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n" - ); - ipsetFile = pkgs.writeText "proxy-suite-zapret-ipset-${rule.name}.txt" ( - lib.concatStringsSep "\n" (lib.unique rule.ips) + "\n" - ); - in - lib.optionalString (rule.domains != [ ]) '' - cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt" - '' - + lib.optionalString (rule.ips != [ ]) '' - cp ${ipsetFile} "$out/opt/zapret/hostlists/ipset-${rule.name}.txt" - '' - ) effectiveHostlistRules} - - ${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec} - - ${lib.optionalString forceDisableFilterMark '' - set_config_var FILTER_MARK "" - ''} - ${lib.concatMapStrings - ( - { var, value }: - lib.optionalString (value != null) '' - hex=$(printf '0x%x' ${toString value}) - set_config_var ${var} "$hex" - '' - ) - [ - { - var = "FILTER_MARK"; - value = filterMark; - } - { - var = "DESYNC_MARK"; - value = desyncMark; - } - { - var = "DESYNC_MARK_POSTNAT"; - value = desyncMarkPostnat; - } - ] - } - ${lib.optionalString (qnum != null) '' - set_config_var QNUM ${toString qnum} - ''} - ${lib.optionalString (modeFilter != null) '' - set_config_var MODE_FILTER ${modeFilter} - ''} - ${lib.optionalString (nftTable != null) '' - set_config_var ZAPRET_NFT_TABLE ${nftTable} - ''} - - ${lib.optionalString (customScript != null) '' - mkdir -p "$out/opt/zapret/init.d/sysv/custom.d" - cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh" - chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh" - ''} - ''; - - globalZapretPackage = mkDerivedZapretPackage { - packageName = "proxy-suite-zapret-${selectedConfigName}"; - pidDir = "/run/proxy-suite-zapret"; - gameFilter = zapretCfg.gameFilter; - forceDisableFilterMark = true; - customScript = - if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null; - }; - - perAppZapretPackage = mkDerivedZapretPackage { - packageName = "proxy-suite-per-app-zapret-${selectedConfigName}"; - pidDir = "/run/proxy-suite-per-app-zapret"; - gameFilter = "all"; - filterMark = perAppZapretCfg.filterMark; - qnum = perAppZapretCfg.qnum; - modeFilter = "none"; - desyncMark = 134217728; - desyncMarkPostnat = 67108864; - nftTable = "proxy_suite_per_app_zapret"; - }; + iptables = "${pkgs.iptables}/bin/iptables"; zapretCommonPreStart = package: '' ${package}/opt/zapret/init.d/sysv/zapret stop || true @@ -332,13 +43,6 @@ let fi ''; - mkZapretEnv = package: [ - "ZAPRET_BASE=${package}/opt/zapret" - "PATH=${lib.makeBinPath runtimeDeps}" - ]; - globalZapretEnv = mkZapretEnv globalZapretPackage; - perAppZapretEnv = mkZapretEnv perAppZapretPackage; - perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-up" '' set -euo pipefail ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true @@ -369,53 +73,7 @@ let '') zapretCfg.cidrExemption.cidrs; in { - assertions = [ - { - assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames); - message = "proxy-suite: zapret.hostlistRules names must be unique"; - } - { - assertion = builtins.all ( - rule: zapretDomainGroups.effectiveRuleDomains rule != [ ] || zapretDomainGroups.effectiveRuleIps rule != [ ] - ) zapretCfg.hostlistRules; - message = "proxy-suite: each zapret.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps"; - } - { - assertion = builtins.all ( - rule: - rule.preset != null || rule.defaultDomains != [ ] || rule.ips != [ ] || rule.defaultIps != [ ] || rule.nfqwsArgs != [ ] - ) zapretCfg.hostlistRules; - message = "proxy-suite: each zapret.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source"; - } - { - assertion = builtins.all ( - rule: - zapretDomainGroups.effectiveRuleDomains rule == [ ] - || rule.preset != null - || rule.defaultDomains != [ ] - || rule.nfqwsArgs != [ ] - ) zapretCfg.hostlistRules; - message = "proxy-suite: zapret.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs"; - } - { - assertion = builtins.all ( - rule: rule.preset != null || builtins.length rule.defaultDomains <= 1 - ) zapretCfg.hostlistRules; - message = "proxy-suite: zapret.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset"; - } - { - assertion = builtins.all ( - rule: !(rule.configName != null && rule.nfqwsArgs != [ ]) - ) zapretCfg.hostlistRules; - message = "proxy-suite: zapret.hostlistRules.*.configName cannot be used together with nfqwsArgs"; - } - { - assertion = builtins.all ( - rule: rule.configName == null || rule.preset != null || rule.defaultDomains != [ ] || rule.ips != [ ] || rule.defaultIps != [ ] - ) zapretCfg.hostlistRules; - message = "proxy-suite: zapret.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps"; - } - ]; + assertions = zapretPackages.assertions; environment.systemPackages = lib.mkBefore ( lib.optionals zapretCfg.enable [ globalZapretPackage ] diff --git a/modules/proxy-suite/zapret/package-builder.nix b/modules/proxy-suite/zapret/package-builder.nix new file mode 100644 index 0000000..de0d2e1 --- /dev/null +++ b/modules/proxy-suite/zapret/package-builder.nix @@ -0,0 +1,232 @@ +# Builds derived zapret packages from the curated upstream package. +{ + lib, + pkgs, + zapretCfg, + baseZapretPackage, + effectiveHostlistRules, + listGeneralFile, + listExcludeFile, + ipsetAllFile, + ipsetExcludeFile, + hostlistRuleSpec, + patchConfigScript, +}: + +let + mkGlobalBypassScript = + filterMark: + pkgs.writeText "proxy-suite-zapret-global-bypass.sh" '' + zapret_custom_firewall_nft() { + nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" + nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" + nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" + nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass" + } + ''; + + mkDerivedZapretPackage = + { + packageName, + pidDir, + configName ? zapretCfg.configName, + gameFilter ? zapretCfg.gameFilter, + forceDisableFilterMark ? false, + filterMark ? null, + qnum ? null, + modeFilter ? null, + desyncMark ? null, + desyncMarkPostnat ? null, + nftTable ? null, + customScript ? null, + }: + pkgs.runCommand packageName + { + nativeBuildInputs = with pkgs; [ + coreutils + gnused + python3 + ]; + } + '' + set -euo pipefail + + mkdir -p "$out" + cp -a ${baseZapretPackage}/. "$out/" + chmod -R u+w "$out/opt/zapret" "$out/bin" + + find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \ + -e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \ + {} \; + find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \ + -e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \ + {} \; + + requested_config=${lib.escapeShellArg configName} + configs_dir="$out/opt/zapret/configs" + selected_config="$configs_dir/$requested_config" + + config_name_key() { + printf '%s' "$1" | tr -d '[:space:]' + } + + if [ ! -f "$selected_config" ]; then + requested_key=$(config_name_key "$requested_config") + matched_config="" + + for candidate in "$configs_dir"/*; do + [ -f "$candidate" ] || continue + candidate_name="''${candidate##*/}" + + if [ "$(config_name_key "$candidate_name")" = "$requested_key" ]; then + if [ -n "$matched_config" ]; then + echo "proxy-suite: zapret config '$requested_config' is ambiguous after whitespace normalization" >&2 + echo "proxy-suite: matched '$matched_config' and '$candidate'" >&2 + exit 1 + fi + matched_config="$candidate" + fi + done + + if [ -n "$matched_config" ]; then + selected_config="$matched_config" + fi + fi + + if [ -f "$selected_config" ]; then + cp "$selected_config" "$out/opt/zapret/config" + else + echo "proxy-suite: zapret config '$requested_config' not found in curated package" >&2 + ls -la "$out/opt/zapret/configs" >&2 || true + exit 1 + fi + + ${pkgs.gnused}/bin/sed -i \ + -e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \ + "$out/opt/zapret/config" + + ${pkgs.gnused}/bin/sed -i \ + -e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \ + "$out/opt/zapret/init.d/sysv/functions" + + append_list_file() { + local target="$1" + local extra_file="$2" + local tmp="$out/opt/zapret/hostlists/$target.tmp" + cat "$out/opt/zapret/hostlists/$target" > "$tmp" + ${pkgs.gnused}/bin/sed -i -e '$a\' "$tmp" + cat "$extra_file" >> "$tmp" + mv "$tmp" "$out/opt/zapret/hostlists/$target" + } + + set_config_var() { + local key="$1" + local value="$2" + if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then + ${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config" + else + printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config" + fi + } + + ${lib.concatMapStrings + ( + { name, file }: + lib.optionalString (file != null) '' + append_list_file ${name} ${file} + '' + ) + [ + { + name = "list-general-user.txt"; + file = listGeneralFile; + } + { + name = "list-exclude-user.txt"; + file = listExcludeFile; + } + { + name = "ipset-all.txt"; + file = ipsetAllFile; + } + { + name = "ipset-exclude-user.txt"; + file = ipsetExcludeFile; + } + ] + } + + rm -f "$out/opt/zapret/hostlists/.game_filter.enabled" + ${lib.optionalString (gameFilter != "null") '' + echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled" + ''} + + ${lib.concatMapStrings ( + rule: + let + domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" ( + lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n" + ); + ipsetFile = pkgs.writeText "proxy-suite-zapret-ipset-${rule.name}.txt" ( + lib.concatStringsSep "\n" (lib.unique rule.ips) + "\n" + ); + in + lib.optionalString (rule.domains != [ ]) '' + cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt" + '' + + lib.optionalString (rule.ips != [ ]) '' + cp ${ipsetFile} "$out/opt/zapret/hostlists/ipset-${rule.name}.txt" + '' + ) effectiveHostlistRules} + + ${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec} + + ${lib.optionalString forceDisableFilterMark '' + set_config_var FILTER_MARK "" + ''} + ${lib.concatMapStrings + ( + { var, value }: + lib.optionalString (value != null) '' + hex=$(printf '0x%x' ${toString value}) + set_config_var ${var} "$hex" + '' + ) + [ + { + var = "FILTER_MARK"; + value = filterMark; + } + { + var = "DESYNC_MARK"; + value = desyncMark; + } + { + var = "DESYNC_MARK_POSTNAT"; + value = desyncMarkPostnat; + } + ] + } + ${lib.optionalString (qnum != null) '' + set_config_var QNUM ${toString qnum} + ''} + ${lib.optionalString (modeFilter != null) '' + set_config_var MODE_FILTER ${modeFilter} + ''} + ${lib.optionalString (nftTable != null) '' + set_config_var ZAPRET_NFT_TABLE ${nftTable} + ''} + + ${lib.optionalString (customScript != null) '' + mkdir -p "$out/opt/zapret/init.d/sysv/custom.d" + cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh" + chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh" + ''} + ''; +in +{ + inherit + mkDerivedZapretPackage + mkGlobalBypassScript + ; +} diff --git a/modules/proxy-suite/zapret/packages.nix b/modules/proxy-suite/zapret/packages.nix new file mode 100644 index 0000000..2dd7f75 --- /dev/null +++ b/modules/proxy-suite/zapret/packages.nix @@ -0,0 +1,201 @@ +# Derived zapret packages and validation. +{ + lib, + pkgs, + cfg, + zapret, +}: + +let + zapretCfg = cfg.zapret; + perAppZapretCfg = zapretCfg.perApp; + zapretDomainGroups = import ../zapret-domain-groups.nix { inherit lib zapret; }; + + runtimeDeps = lib.attrValues { + inherit (pkgs) + iptables + ipset + nftables + coreutils + gawk + curl + wget + bash + kmod + findutils + gnused + gnugrep + procps + util-linux + ; + }; + + effectiveHostlistRules = map ( + rule: + rule + // { + domains = zapretDomainGroups.effectiveRuleDomains rule; + ips = zapretDomainGroups.effectiveRuleIps rule; + presets = zapretDomainGroups.effectiveRulePresets rule; + ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule; + protocols = zapretDomainGroups.effectiveRuleProtocolFamilies rule; + } + ) zapretCfg.hostlistRules; + hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules; + + baseZapretPackage = + let + upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system}; + in + if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default; + + mkOptionalHostlistFile = + fileName: entries: + if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null; + + listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral; + listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude; + ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll; + ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude; + + hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" ( + builtins.toJSON { + includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists; + entries = map (rule: { + inherit (rule) + name + configName + nfqwsArgs + ipsets + presets + protocols + ; + hasDomains = rule.domains != [ ]; + hasIps = rule.ips != [ ]; + }) effectiveHostlistRules; + } + ); + + selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName; + patchConfigScriptSrc = builtins.path { + path = ../../../scripts/patch-zapret-config.py; + name = "patch-zapret-config.py"; + }; + patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}"; + + packageBuilder = import ./package-builder.nix { + inherit + lib + pkgs + zapretCfg + baseZapretPackage + effectiveHostlistRules + listGeneralFile + listExcludeFile + ipsetAllFile + ipsetExcludeFile + hostlistRuleSpec + patchConfigScript + ; + }; + inherit (packageBuilder) + mkDerivedZapretPackage + mkGlobalBypassScript + ; + + globalZapretPackage = mkDerivedZapretPackage { + packageName = "proxy-suite-zapret-${selectedConfigName}"; + pidDir = "/run/proxy-suite-zapret"; + gameFilter = zapretCfg.gameFilter; + forceDisableFilterMark = true; + customScript = + if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null; + }; + + perAppZapretPackage = mkDerivedZapretPackage { + packageName = "proxy-suite-per-app-zapret-${selectedConfigName}"; + pidDir = "/run/proxy-suite-per-app-zapret"; + gameFilter = "all"; + filterMark = perAppZapretCfg.filterMark; + qnum = perAppZapretCfg.qnum; + modeFilter = "none"; + desyncMark = 134217728; + desyncMarkPostnat = 67108864; + nftTable = "proxy_suite_per_app_zapret"; + }; + + mkZapretEnv = package: [ + "ZAPRET_BASE=${package}/opt/zapret" + "PATH=${lib.makeBinPath runtimeDeps}" + ]; + + assertions = [ + { + assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames); + message = "proxy-suite: zapret.hostlistRules names must be unique"; + } + { + assertion = builtins.all ( + rule: + zapretDomainGroups.effectiveRuleDomains rule != [ ] + || zapretDomainGroups.effectiveRuleIps rule != [ ] + ) zapretCfg.hostlistRules; + message = "proxy-suite: each zapret.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps"; + } + { + assertion = builtins.all ( + rule: + rule.preset != null + || rule.defaultDomains != [ ] + || rule.ips != [ ] + || rule.defaultIps != [ ] + || rule.nfqwsArgs != [ ] + ) zapretCfg.hostlistRules; + message = "proxy-suite: each zapret.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source"; + } + { + assertion = builtins.all ( + rule: + zapretDomainGroups.effectiveRuleDomains rule == [ ] + || rule.preset != null + || rule.defaultDomains != [ ] + || rule.nfqwsArgs != [ ] + ) zapretCfg.hostlistRules; + message = "proxy-suite: zapret.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs"; + } + { + assertion = builtins.all ( + rule: rule.preset != null || builtins.length rule.defaultDomains <= 1 + ) zapretCfg.hostlistRules; + message = "proxy-suite: zapret.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset"; + } + { + assertion = builtins.all ( + rule: !(rule.configName != null && rule.nfqwsArgs != [ ]) + ) zapretCfg.hostlistRules; + message = "proxy-suite: zapret.hostlistRules.*.configName cannot be used together with nfqwsArgs"; + } + { + assertion = builtins.all ( + rule: + rule.configName == null + || rule.preset != null + || rule.defaultDomains != [ ] + || rule.ips != [ ] + || rule.defaultIps != [ ] + ) zapretCfg.hostlistRules; + message = "proxy-suite: zapret.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps"; + } + ]; +in +{ + inherit + globalZapretPackage + perAppZapretPackage + ; + + globalZapretEnv = mkZapretEnv globalZapretPackage; + perAppZapretEnv = mkZapretEnv perAppZapretPackage; + + inherit assertions; +} diff --git a/nix/checks.nix b/nix/checks.nix index 9e1fa4c..f903b5a 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -9,3670 +9,34 @@ let pkgs = import nixpkgs { inherit system; }; - parserChecks = import ./checks/parsers.nix { inherit pkgs; }; suitePkgs = import ../pkgs/default.nix { inherit pkgs; }; - readmeDocSource = builtins.readFile ../nix/readme-doc.nix; - trayModuleSource = builtins.readFile ../modules/proxy-suite/tray.nix; - tgWsProxyModuleSource = builtins.readFile ../modules/proxy-suite/tg-ws-proxy.nix; - controlModuleSource = builtins.readFile ../modules/proxy-suite/service/control.nix; + parserChecks = import ./checks/parsers.nix { inherit pkgs; }; + checkLib = import ./checks/lib.nix { + inherit + pkgs + system + nixpkgs + proxySuiteModule + zapret + ; + }; repoChecks = import ./checks/repo.nix { inherit pkgs - rg generatedOptionsDoc generatedReadmeDoc - readmeDocSource - trayModuleSource - tgWsProxyModuleSource - controlModuleSource ; + inherit (checkLib) rg; + readmeDocSource = builtins.readFile ../nix/readme-doc.nix; + trayModuleSource = builtins.readFile ../modules/proxy-suite/tray.nix; + tgWsProxyModuleSource = builtins.readFile ../modules/proxy-suite/tg-ws-proxy.nix; + controlModuleSource = builtins.readFile ../modules/proxy-suite/service/control.nix; }; - evalProxySuite = - modules: - import "${nixpkgs}/nixos/lib/eval-config.nix" { - inherit system; - modules = [ proxySuiteModule ] ++ modules; - }; - forceEval = value: builtins.tryEval (builtins.deepSeq value true); - rg = "${pkgs.ripgrep}/bin/rg"; - mkRouting = - fixture: - let - cfg = fixture.config.services.proxy-suite; - in - import ../modules/proxy-suite/rules.nix { - lib = pkgs.lib; - inherit pkgs cfg zapret; - }; - mkRoutingRules = fixture: (mkRouting fixture).routingRules; - mkRouteModeRules = fixture: (mkRouting fixture).routeModeRules; - mkTProxyConfig = - fixture: - let - cfg = fixture.config.services.proxy-suite; - rules = mkRouting fixture; - configs = import ../modules/proxy-suite/config.nix { - lib = pkgs.lib; - inherit pkgs cfg rules; - }; - in - builtins.fromJSON (builtins.unsafeDiscardStringContext (builtins.readFile configs.tproxyFile)); - mkTunConfig = - fixture: - let - cfg = fixture.config.services.proxy-suite; - rules = mkRouting fixture; - configs = import ../modules/proxy-suite/config.nix { - lib = pkgs.lib; - inherit pkgs cfg rules; - }; - in - builtins.fromJSON (builtins.unsafeDiscardStringContext (builtins.readFile configs.tunFile)); - mkPerAppTunConfig = - fixture: - let - cfg = fixture.config.services.proxy-suite; - rules = mkRouting fixture; - configs = import ../modules/proxy-suite/config.nix { - lib = pkgs.lib; - inherit pkgs cfg rules; - }; - in - builtins.fromJSON (builtins.unsafeDiscardStringContext (builtins.readFile configs.perAppTunFile)); - mkTProxyNftRules = - fixture: - let - cfg = fixture.config.services.proxy-suite; - nftr = import ../modules/proxy-suite/nftables.nix { - lib = pkgs.lib; - inherit pkgs cfg; - }; - in - builtins.readFile nftr.nftablesRulesFile; - hasDirectDomain = - rules: domain: - builtins.any ( - rule: (rule ? domain_suffix) && rule.outbound == "direct" && builtins.elem domain rule.domain_suffix - ) rules; - hasDirectIP = - rules: cidr: - builtins.any ( - rule: (rule ? ip_cidr) && rule.outbound == "direct" && builtins.elem cidr rule.ip_cidr - ) rules; - hasRuleSet = - rules: outbound: ruleSet: - builtins.any ( - rule: (rule ? rule_set) && rule.outbound == outbound && builtins.elem ruleSet rule.rule_set - ) rules; - dnsHasRuleSet = - dnsRules: ruleSet: - builtins.any (rule: (rule ? rule_set) && builtins.elem ruleSet rule.rule_set) dnsRules; - dnsServerByTag = - dnsConfig: tag: builtins.head (builtins.filter (server: server.tag == tag) dnsConfig.dns.servers); - mkZapretBaseFor = - fixture: serviceName: - let - env = fixture.config.systemd.services.${serviceName}.serviceConfig.Environment; - zapretBaseEnv = builtins.head ( - builtins.filter (value: pkgs.lib.hasPrefix "ZAPRET_BASE=" value) env - ); - in - pkgs.lib.removePrefix "ZAPRET_BASE=" zapretBaseEnv; - mkZapretBase = fixture: mkZapretBaseFor fixture "zapret-discord-youtube"; - packagePathMatches = - packages: pattern: - builtins.any ( - pkg: builtins.match pattern (builtins.unsafeDiscardStringContext (toString pkg)) != null - ) packages; - packageByPattern = - packages: pattern: - builtins.head ( - builtins.filter ( - pkg: builtins.match pattern (builtins.unsafeDiscardStringContext (toString pkg)) != null - ) packages - ); - lineByPrefix = - text: prefix: - builtins.head ( - builtins.filter (line: pkgs.lib.hasPrefix prefix line) (pkgs.lib.splitString "\n" text) - ); - lineContaining = - text: infix: - builtins.head ( - builtins.filter (line: pkgs.lib.hasInfix infix line) (pkgs.lib.splitString "\n" text) - ); - staticOutboundJsonFromScript = - script: - let - line = lineContaining script "OB_JSON=$(cat \""; - parts = pkgs.lib.splitString "\"" line; - in - builtins.fromJSON (builtins.readFile (builtins.elemAt parts 1)); - normalizeExec = value: if builtins.isList value then builtins.head value else value; - readExecScripts = - value: - let - execs = if builtins.isList value then value else [ value ]; - in - pkgs.lib.concatStringsSep "\n" (map builtins.readFile execs); - quotedValueByPrefix = - text: prefix: pkgs.lib.removeSuffix "\"" (pkgs.lib.removePrefix prefix (lineByPrefix text prefix)); - shellValueByPrefix = - text: prefix: - let - value = pkgs.lib.removePrefix prefix (lineByPrefix text prefix); - in - if pkgs.lib.hasPrefix "'" value && pkgs.lib.hasSuffix "'" value then - pkgs.lib.removeSuffix "'" (pkgs.lib.removePrefix "'" value) - else if pkgs.lib.hasPrefix "\"" value && pkgs.lib.hasSuffix "\"" value then - pkgs.lib.removeSuffix "\"" (pkgs.lib.removePrefix "\"" value) - else - value; - - baseModule = { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }; - }; - mkFixture = - proxySuiteConfig: - evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = proxySuiteConfig; - } - ]; - # Fixture that must fail validation; uses baseModule as the base. - mkBadFixture = - modules: - forceEval ((evalProxySuite ([ baseModule ] ++ modules)).config.system.build.toplevel.drvPath); - # Same but without baseModule (for fixtures that need custom base config). - mkBadFixtureRaw = - modules: forceEval ((evalProxySuite modules).config.system.build.toplevel.drvPath); - # Extract the proxy-ctl package and derived script/profile values from a fixture. - mkProxyCtlDerived = - fixture: - let - proxyCtl = packageByPattern fixture.config.environment.systemPackages ".*/[^/]*proxy-ctl(-[0-9.]+)?$"; - wrapper = builtins.readFile "${proxyCtl}/bin/proxy-ctl"; - in - { - inherit proxyCtl wrapper; - script = wrapper + "\n" + builtins.readFile "${proxyCtl}/bin/.proxy-ctl-wrapped"; - profiles = builtins.fromJSON ( - builtins.readFile (shellValueByPrefix wrapper "export PER_APP_ROUTING_PROFILES_FILE=") - ); - }; - - minimal = evalProxySuite [ baseModule ]; - checkConstants = (import ../modules/proxy-suite/derived.nix { - lib = pkgs.lib; - cfg = minimal.config.services.proxy-suite; - }).constants; - _minimalProxyCtl = mkProxyCtlDerived minimal; - minimalProxyCtlWrapper = _minimalProxyCtl.wrapper; - minimalProxyCtlScript = _minimalProxyCtl.script; - minimalSocksService = minimal.config.systemd.services."proxy-suite-socks"; - customSingBoxPackage = pkgs.writeShellScriptBin "sing-box" '' - exit 0 - ''; - customSingBoxPackageFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.singBox.package = customSingBoxPackage; - } - ]; - customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box"; - customSingBoxPackageStartScript = builtins.readFile ( - 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; - tproxy.perApp.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 - ); - xrayTunStartScript = builtins.readFile ( - xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart - ); - xrayTunUpScript = builtins.readFile ( - xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStartPost - ); - xrayPerAppTunStartScript = builtins.readFile ( - xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart - ); - xrayPerAppTunUpScript = builtins.readFile ( - xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStartPost - ); - xrayPerAppTunCleanupScript = builtins.readFile ( - xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStopPost - ); - xrayStartBackendJqFilterFile = shellValueByPrefix xrayStartScript "BACKEND_JQ_FILTER="; - xrayTunBackendJqFilterFile = shellValueByPrefix xrayTunStartScript "BACKEND_JQ_FILTER="; - xrayPerAppTunBackendJqFilterFile = shellValueByPrefix xrayPerAppTunStartScript "BACKEND_JQ_FILTER="; - xrayBackendJqFilter = builtins.readFile xrayTunBackendJqFilterFile; - xrayDnsLocalClient = xrayFixture.config.services.proxy-suite.proxy.dns.local.address; - xrayDnsRemoteClient = xrayFixture.config.services.proxy-suite.proxy.dns.remote.address; - xrayTunConfigJson = pkgs.writeText "proxy-suite-xray-tun-check.json" ( - builtins.toJSON xrayTunConfig - ); - xrayPerAppTunConfigJson = pkgs.writeText "proxy-suite-xray-per-app-tun-check.json" ( - builtins.toJSON xrayPerAppTunConfig - ); - xrayJqFilterRuntimeCheck = - pkgs.runCommand "proxy-suite-xray-jq-filter-runtime-check" { nativeBuildInputs = [ pkgs.jq ]; } - '' - OBS='[{"protocol":"freedom","tag":"proxy-suite-ob-primary"}]' - - check_runtime() { - local name="$1" - local input="$2" - local output="$TMPDIR/$name.json" - - jq \ - --argjson obs "$OBS" \ - --argjson auth_enabled false \ - --arg user "" \ - --arg password "" \ - --argjson route_enabled true \ - --argjson route_rules '[]' \ - --arg route_final "proxy" \ - --arg dns_final "remote" \ - --argjson clear_dns_rules false \ - --arg xray_loglevel "" \ - --arg xray_bind_interface "eth0" \ - --arg xray_single_proxy_tag "proxy-suite-ob-primary" \ - --argjson xray_tun_dns_runtime true \ - --arg xray_dns_local_client ${pkgs.lib.escapeShellArg xrayDnsLocalClient} \ - --arg xray_dns_remote_client ${pkgs.lib.escapeShellArg xrayDnsRemoteClient} \ - -f ${pkgs.lib.escapeShellArg xrayTunBackendJqFilterFile} \ - "$input" > "$output" - - jq -e \ - --arg remote ${pkgs.lib.escapeShellArg xrayDnsRemoteClient} \ - --arg local ${pkgs.lib.escapeShellArg xrayDnsLocalClient} \ - ' - type == "object" - and (.dns.servers | length) >= 3 - and .dns.servers[0].tag == "fakedns" - and ([.routing.rules[] | select((.ruleTag? // "") == "dns-hijack")] | length) == 1 - and ([.routing.rules[] | select((.ruleTag? // "") == "dns-upstream-direct")] | length) == 1 - and ([.outbounds[] | select(.tag == "proxy-suite-ob-primary" and (.streamSettings.sockopt.interface? // "") == "eth0")] | length) == 1 - and ([.outbounds[] | select(.tag == "dns-out" and ((.streamSettings.sockopt.interface? // "") == ""))] | length) == 1 - and ([.inbounds[] | select(.tag == "tun-in") | .settings.dns] | length) == 1 - and ([.inbounds[] | select(.tag == "tun-in") | .settings.dns][0] == [$remote, $local]) - and ((.routing | has("balancers")) | not) - and ((has("observatory")) | not) - ' "$output" >/dev/null - } - - check_runtime global ${pkgs.lib.escapeShellArg xrayTunConfigJson} - check_runtime per-app ${pkgs.lib.escapeShellArg xrayPerAppTunConfigJson} - touch "$out" - ''; - 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 - ); - xrayRawStreamFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - xray.enable = true; - outbounds = [ - { - tag = "raw-stream"; - xrayJson = { - protocol = "vless"; - settings = { - address = "example.com"; - port = 443; - id = "00000000-0000-0000-0000-000000000000"; - encryption = "none"; - }; - streamSettings = { - network = "ws"; - security = "tls"; - tlsSettings.serverName = "cdn.example.com"; - wsSettings.path = "/ws"; - sockopt.tcpFastOpen = true; - }; - }; - } - ]; - }; - }; - } - ]; - xrayRawStreamStartScript = builtins.readFile ( - xrayRawStreamFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - xrayRawStreamOutbound = staticOutboundJsonFromScript xrayRawStreamStartScript; - xrayDnsTcpFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - xray.enable = true; - dns.local = { - type = "tcp"; - address = "9.9.9.9"; - port = 5353; - }; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }; - } - ]; - xrayDnsTcpConfig = mkTProxyConfig xrayDnsTcpFixture; - xrayDnsTlsUnavailable = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - xray.enable = true; - dns.remote = { - type = "tls"; - address = "1.1.1.1"; - port = 853; - }; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }; - } - ]; - hybridModule = { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - xray.enable = true; - selection = "selector"; - outbounds = [ - { - tag = "primary"; - url = "vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"; - } - { - tag = "xray-only"; - url = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"; - } - ]; - tproxy.enable = true; - tun.enable = true; - tun.perApp.enable = true; - }; - }; - }; - hybridFixture = evalProxySuite [ hybridModule ]; - hybridTproxyConfig = mkTProxyConfig hybridFixture; - hybridTunConfig = mkTunConfig hybridFixture; - hybridStartScript = builtins.readFile ( - hybridFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - hybridTunStartScript = builtins.readFile ( - hybridFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart - ); - hybridPerAppTunStartScript = builtins.readFile ( - hybridFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart - ); - hybridBackendJqFilterFile = shellValueByPrefix hybridStartScript "BACKEND_JQ_FILTER="; - hybridBackendJqFilter = builtins.readFile hybridBackendJqFilterFile; - hybridXrayRawFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - xray.enable = true; - outbounds = [ - { - tag = "raw-xray"; - xrayJson = { - protocol = "freedom"; - settings = { }; - }; - } - ]; - }; - }; - } - ]; - hybridXrayRawStartScript = builtins.readFile ( - hybridXrayRawFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - hybridSubscriptionFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - xray.enable = true; - subscriptions = [ - { - tag = "community"; - url = "https://example.com/hybrid-sub"; - } - ]; - selection = "selector"; - }; - }; - } - ]; - hybridSubscriptionStartScript = builtins.readFile ( - hybridSubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - hybridSubscriptionUpdateScript = builtins.readFile ( - hybridSubscriptionFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart - ); - proxyEnabledNoBackend = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }; - } - ]; - xraySelectorUnavailable = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - xray.enable = true; - selection = "selector"; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }; - } - ]; - xraySingBoxJsonUnavailable = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - xray.enable = true; - outbounds = [ - { - tag = "raw"; - singBoxJson = { - type = "direct"; - }; - } - ]; - }; - }; - } - ]; - singBoxXrayJsonUnavailable = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "raw"; - xrayJson = { - protocol = "freedom"; - settings = { }; - }; - } - ]; - }; - }; - } - ]; - - routeModeFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.routing = { - proxy = { - domains = [ "proxy.example" ]; - geosites = [ "google" ]; - }; - direct.domains = [ "direct.example" ]; - block.domains = [ "block.example" ]; - rules = [ - { - outbound = "direct"; - domains = [ "custom-direct.example" ]; - } - { - outbound = "primary"; - domains = [ "custom-proxy.example" ]; - } - { - outbound = "block"; - domains = [ "custom-block.example" ]; - } - ]; - }; - } - ]; - routeModeStartScript = builtins.readFile ( - routeModeFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - routeModeBackendJqFilterFile = shellValueByPrefix routeModeStartScript "BACKEND_JQ_FILTER="; - routeModeBackendJqFilter = builtins.readFile routeModeBackendJqFilterFile; - routeModeRules = mkRouteModeRules routeModeFixture; - - tgSecretFile = evalProxySuite [ - baseModule - { - services.proxy-suite.tgWsProxy = { - enable = true; - host = "127.0.0.1"; - secretFile = "/run/secrets/tg-ws-proxy"; - }; - } - ]; - tgSecretFileService = tgSecretFile.config.systemd.services."proxy-suite-tg-ws-proxy"; - - tgAllOptions = evalProxySuite [ - baseModule - { - services.proxy-suite.tgWsProxy = { - enable = true; - port = 2443; - host = "0.0.0.0"; - secretFile = "/run/secrets/tg-ws-proxy"; - verbose = true; - logFile = "/var/log/tg-ws-proxy.log"; - logMaxMb = 2.5; - logBackups = 3; - bufKb = 512; - poolSize = 8; - cfProxyDomains = [ - "cdn.example.com" - "edge.example.net" - ]; - cfProxyWorkerDomains = [ "worker.example.com" ]; - cfProxyFallback = false; - fakeTlsDomain = "mask.example.com"; - proxyProtocol = true; - }; - } - ]; - tgAllOptionsStartScript = builtins.readFile ( - tgAllOptions.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig.ExecStart - ); - - tgWithGlobalTun = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy.tun.enable = true; - tgWsProxy = { - enable = true; - secretFile = "/run/secrets/tg-ws-proxy"; - dcIps."2" = "149.154.167.220"; - }; - }; - } - ]; - tgWithGlobalTunServiceConfig = - tgWithGlobalTun.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig; - tgWithGlobalTunBypassUp = builtins.readFile tgWithGlobalTunServiceConfig.ExecStartPre; - tgWithGlobalTunBypassDown = builtins.readFile tgWithGlobalTunServiceConfig.ExecStopPost; - tgWithGlobalTunRules = mkRoutingRules tgWithGlobalTun; - - tgWithGlobalTproxy = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy.tproxy.enable = true; - tgWsProxy = { - enable = true; - secretFile = "/run/secrets/tg-ws-proxy"; - }; - }; - } - ]; - tgWithGlobalTproxyNft = mkTProxyNftRules tgWithGlobalTproxy; - - tgRoutingMarkCollision = mkBadFixture [ - { - services.proxy-suite = { - proxy.tproxy.enable = true; - tgWsProxy = { - enable = true; - secretFile = "/run/secrets/tg-ws-proxy"; - routingMark = 1; - }; - }; - } - ]; - - tgInvalidBufKb = mkBadFixture [ - { - services.proxy-suite.tgWsProxy = { - enable = true; - secretFile = "/run/secrets/tg-ws-proxy"; - bufKb = 3; - }; - } - ]; - - tgInvalidPoolSize = mkBadFixture [ - { - services.proxy-suite.tgWsProxy = { - enable = true; - secretFile = "/run/secrets/tg-ws-proxy"; - poolSize = -1; - }; - } - ]; - - tgInvalidLogBackups = mkBadFixture [ - { - services.proxy-suite.tgWsProxy = { - enable = true; - secretFile = "/run/secrets/tg-ws-proxy"; - logBackups = 0; - }; - } - ]; - - duplicateTags = forceEval ( - (mkFixture { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "dup"; - url = "http://one.example.com:8080"; - } - { - tag = "dup"; - url = "http://two.example.com:8080"; - } - ]; - }; - }).config.system.build.toplevel.drvPath - ); - - reservedTag = forceEval ( - (mkFixture { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "proxy"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }).config.system.build.toplevel.drvPath - ); - - unknownRoutingTarget = forceEval ( - (mkFixture { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - routing.rules = [ - { - outbound = "missing"; - domains = [ "example.com" ]; - } - ]; - }; - }).config.system.build.toplevel.drvPath - ); - - tproxyWithFirewall = evalProxySuite [ - { - system.stateVersion = "26.05"; - networking.firewall.enable = true; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - tproxy.enable = true; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - }; - } - ]; - - tproxyManualFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.tproxy.enable = true; - } - ]; - tproxyManualServiceConfig = - tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig; - tproxyManualStartScript = builtins.readFile tproxyManualServiceConfig.ExecStart; - tproxyManualStopScript = builtins.readFile tproxyManualServiceConfig.ExecStop; - - tproxyAutostartFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.tproxy = { - enable = true; - autostart = true; - }; - } - ]; - - tunManualFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.tun.enable = true; - } - ]; - - tunAutostartFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.tun = { - enable = true; - autostart = true; - }; - } - ]; - - conflictingAutostartModes = mkBadFixture [ - { - services.proxy-suite.proxy = { - tproxy = { - enable = true; - autostart = true; - }; - tun = { - enable = true; - autostart = true; - }; - }; - } - ]; - - globalTunWithoutProxy = mkBadFixture [ - { - services.proxy-suite.proxy = { - enable = false; - tun.enable = true; - }; - } - ]; - - globalTproxyWithoutProxy = mkBadFixture [ - { - services.proxy-suite.proxy = { - enable = false; - tproxy.enable = true; - }; - } - ]; - - routingOrFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - routing.rules = [ - { - outbound = "primary"; - domains = [ "example.com" ]; - geoips = [ "us" ]; - } - ]; - }; - }; - } - ]; - - ruDefaultRules = mkRoutingRules minimal; - ruDefaultConfig = mkTProxyConfig minimal; - - ruDisabledFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.routing.enableRuDirect = false; - } - ]; - ruDisabledRules = mkRoutingRules ruDisabledFixture; - ruDisabledConfig = mkTProxyConfig ruDisabledFixture; - - ruExplicitFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.routing = { - enableRuDirect = false; - direct.geosites = [ "category-ru" ]; - }; - } - ]; - ruExplicitConfig = mkTProxyConfig ruExplicitFixture; - - dnsLocalOverrideFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.dns.local = { - type = "tcp"; - address = "9.9.9.9"; - port = 5353; - }; - } - ]; - dnsLocalOverrideConfig = mkTProxyConfig dnsLocalOverrideFixture; - - dnsRemoteOverrideFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.dns.remote = { - type = "tls"; - address = "1.0.0.1"; - port = 853; - }; - } - ]; - dnsRemoteOverrideConfig = mkTProxyConfig dnsRemoteOverrideFixture; - tunDefaultConfig = mkTunConfig tunManualFixture; - tunServiceConfig = tunManualFixture.config.systemd.services."proxy-suite-tun".serviceConfig; - tunCleanupScript = builtins.readFile tunServiceConfig.ExecStopPost; - - zapretSyncFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret.enable = true; - } - ]; - zapretSyncService = zapretSyncFixture.config.systemd.services."zapret-discord-youtube"; - zapretSyncRules = mkRoutingRules zapretSyncFixture; - zapretSyncBase = mkZapretBase zapretSyncFixture; - - zapretSpacedConfigAliasFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - configName = "general(ALT12)"; - }; - } - ]; - zapretSpacedConfigAliasBase = mkZapretBase zapretSpacedConfigAliasFixture; - - zapretUnspacedConfigAliasFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - configName = "general (ALT)"; - }; - } - ]; - zapretUnspacedConfigAliasBase = mkZapretBase zapretUnspacedConfigAliasFixture; - - zapretSyncNoExtraListsFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - includeExtraUpstreamLists = false; - }; - } - ]; - zapretSyncNoExtraListsBase = mkZapretBase zapretSyncNoExtraListsFixture; - zapretSyncNoExtraListsRules = mkRoutingRules zapretSyncNoExtraListsFixture; - - zapretSyncExtraListsFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - includeExtraUpstreamLists = true; - }; - } - ]; - zapretSyncExtraListsBase = mkZapretBase zapretSyncExtraListsFixture; - zapretSyncExtraListsRules = mkRoutingRules zapretSyncExtraListsFixture; - - zapretSyncIpsFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - syncDirectRoutingUpstreamIps = true; - }; - } - ]; - zapretSyncIpsRules = mkRoutingRules zapretSyncIpsFixture; - - zapretSyncUserIpsDisabledFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - syncDirectRoutingUserIps = false; - ipsetAll = [ "203.0.113.0/24" ]; - }; - } - ]; - zapretSyncUserIpsDisabledRules = mkRoutingRules zapretSyncUserIpsDisabledFixture; - - zapretSyncDisabledFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - syncDirectRouting = false; - }; - } - ]; - zapretSyncDisabledRules = mkRoutingRules zapretSyncDisabledFixture; - - zapretSyncDomainsOnlyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - syncDirectRouting = true; - syncDirectRoutingUpstreamIps = false; - }; - } - ]; - zapretSyncDomainsOnlyRules = mkRoutingRules zapretSyncDomainsOnlyFixture; - - zapretExtrasFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - listGeneral = [ "pixiv.net" ]; - }; - } - ]; - zapretExtrasRules = mkRoutingRules zapretExtrasFixture; - - zapretIpExtrasFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - ipsetAll = [ "203.0.113.0/24" ]; - }; - } - ]; - zapretIpExtrasRules = mkRoutingRules zapretIpExtrasFixture; - - zapretExcludesFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - listExclude = [ "discord.com" ]; - }; - } - ]; - zapretExcludesRules = mkRoutingRules zapretExcludesFixture; - - zapretIpExcludesFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - ipsetExclude = [ "1.1.1.0/24" ]; - ipsetAll = [ "1.1.1.0/24" ]; - }; - } - ]; - zapretIpExcludesRules = mkRoutingRules zapretIpExcludesFixture; - - zapretHostlistRulesFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.zapret = { - enable = true; - hostlistRules = [ - { - name = "googlevideo"; - domains = [ - "googlevideo.com" - "ggpht.com" - ]; - preset = "google"; - } - { - name = "example"; - domains = [ - "example.com" - "example.de" - ]; - nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake,multisplit" ]; - } - { - name = "twitter-no-direct"; - domains = [ "x.example" ]; - nfqwsArgs = [ "--filter-udp=443 --dpi-desync=fake --dpi-desync-repeats=6" ]; - enableDirectSync = false; - } - { - name = "google-general"; - defaultDomains = [ "google" ]; - configName = "general"; - } - { - name = "general-alt12"; - defaultDomains = [ "general" ]; - configName = "general (ALT12)"; - } - { - name = "youtube-alias"; - defaultDomains = [ "youtube" ]; - configName = "general"; - enableDirectSync = false; - } - { - name = "discord-alias"; - defaultDomains = [ "discord" ]; - configName = "general (ALT12)"; - enableDirectSync = false; - } - { - name = "upstream-ips"; - defaultIps = [ "all" ]; - configName = "general"; - enableDirectSync = false; - } - { - name = "explicit-ips"; - ips = [ "203.0.113.0/24" ]; - configName = "general"; - } - ]; - }; - } - ]; - zapretHostlistRules = mkRoutingRules zapretHostlistRulesFixture; - zapretHostlistBase = mkZapretBase zapretHostlistRulesFixture; - - duplicateZapretHostlistNames = mkBadFixture [ - { - services.proxy-suite.zapret = { - enable = true; - hostlistRules = [ - { - name = "dup"; - domains = [ "one.example" ]; - nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; - } - { - name = "dup"; - domains = [ "two.example" ]; - nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; - } - ]; - }; - } - ]; - - emptyZapretHostlistDomains = mkBadFixture [ - { - services.proxy-suite.zapret = { - enable = true; - hostlistRules = [ - { - name = "empty"; - domains = [ ]; - nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; - } - ]; - }; - } - ]; - - missingZapretHostlistAction = mkBadFixture [ - { - services.proxy-suite.zapret = { - enable = true; - hostlistRules = [ - { - name = "missing"; - domains = [ "missing.example" ]; - } - ]; - }; - } - ]; - - conflictingZapretHostlistConfigAndArgs = mkBadFixture [ - { - services.proxy-suite.zapret = { - enable = true; - hostlistRules = [ - { - name = "conflict"; - defaultDomains = [ "google" ]; - configName = "general"; - nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; - } - ]; - }; - } - ]; - - configNameZapretHostlistWithoutFamily = mkBadFixture [ - { - services.proxy-suite.zapret = { - enable = true; - hostlistRules = [ - { - name = "missing-family"; - domains = [ "example.com" ]; - configName = "general"; - } - ]; - }; - } - ]; - - proxyDirectFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.proxyByDefault = false; - } - ]; - proxyDirectConfig = mkTProxyConfig proxyDirectFixture; - - trayAutostartFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.tray.enable = true; - } - ]; - - trayManualFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.tray = { - enable = true; - autostart = false; - }; - } - ]; - - # --------------------------------------------------------------------------- - # Subscription fixtures - # --------------------------------------------------------------------------- - - subscriptionOnlyFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "community"; - url = "https://example.com/sub/token"; - } - ]; - }; - }; - } - ]; - subscriptionOnlyProxyCtl = packageByPattern subscriptionOnlyFixture.config.environment.systemPackages ".*/[^/]*proxy-ctl(-[0-9.]+)?$"; - subscriptionOnlyWrapper = builtins.readFile "${subscriptionOnlyProxyCtl}/bin/proxy-ctl"; - subscriptionOnlyScript = - subscriptionOnlyWrapper - + "\n" - + builtins.readFile "${subscriptionOnlyProxyCtl}/bin/.proxy-ctl-wrapped"; - subscriptionOnlyTags = builtins.fromJSON ( - builtins.readFile (shellValueByPrefix subscriptionOnlyWrapper "export SUB_TAGS_FILE=") - ); - subscriptionOnlyStartScript = - builtins.readFile - subscriptionOnlyFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; - subscriptionOnlyUpdateScript = - builtins.readFile - subscriptionOnlyFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart; - - subscriptionWithStaticFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "own-vps"; - url = "http://proxy.example.com:8080"; - } - ]; - subscriptions = [ - { - tag = "backup"; - url = "https://example.com/sub/token"; - } - ]; - selection = "urltest"; - subscriptionUpdateInterval = "6h"; - }; - }; - } - ]; - duplicateSubscriptionTags = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "dup"; - url = "https://example.com/sub/one"; - } - { - tag = "dup"; - url = "https://example.com/sub/two"; - } - ]; - }; - }; - } - ]; - - unsafeSubscriptionTag = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "bad/tag"; - url = "https://example.com/sub/token"; - } - ]; - }; - }; - } - ]; - - # selection=first with subscriptions only – start script must rename first - # subscription outbound to "proxy" so routing rules resolve at runtime. - subscriptionFirstSelectionFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "community"; - url = "https://example.com/sub/token"; - } - ]; - selection = "first"; - }; - }; - } - ]; - subscriptionPerAppTunFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "community"; - url = "https://example.com/sub/token"; - } - ]; - tun.perApp.enable = true; - }; - perAppRouting.enable = true; - }; - } - ]; - subscriptionPerAppTunUpdateScript = builtins.readFile ( - subscriptionPerAppTunFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart - ); - - subscriptionUrlFileFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "private"; - urlFile = "/run/secrets/sub-url"; - } - ]; - }; - }; - } - ]; - - urlTestCustomFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - outbounds = [ - { - tag = "test-proxy"; - url = "http://proxy.example.com:8080"; - } - ]; - selection = "urltest"; - urlTest = { - url = "https://telegram.org"; - interval = "1m"; - }; - singBox.urlTest.tolerance = 100; - }; - }; - } - ]; - - perAppRoutingProxychainsFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.perAppRouting = { - enable = true; - proxychains.enable = true; - profiles = [ - { - name = "steam-browser"; - route = "proxychains"; - } - { - name = "native-direct"; - route = "direct"; - } - ]; - }; - } - ]; - _perAppRoutingProxychains = mkProxyCtlDerived perAppRoutingProxychainsFixture; - perAppRoutingProxychainsProxyCtl = _perAppRoutingProxychains.proxyCtl; - perAppRoutingProxychainsWrapper = _perAppRoutingProxychains.wrapper; - perAppRoutingProxychainsScript = _perAppRoutingProxychains.script; - perAppRoutingProxychainsProfiles = _perAppRoutingProxychains.profiles; - perAppRoutingProxychainsConfig = builtins.readFile ( - shellValueByPrefix perAppRoutingProxychainsWrapper "export PROXYCHAINS_CONFIG=" - ); - - localProxyAuthFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.auth = { - username = "local-user"; - password = "local-pass"; - }; - } - ]; - localProxyAuthStartScript = builtins.readFile ( - localProxyAuthFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - localProxyAuthBackendJqFilterFile = shellValueByPrefix localProxyAuthStartScript "BACKEND_JQ_FILTER="; - localProxyAuthBackendJqFilter = builtins.readFile localProxyAuthBackendJqFilterFile; - - localProxyAuthPasswordFileFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy.auth = { - username = "local-user"; - passwordFile = "/run/secrets/local-proxy-password"; - }; - perAppRouting = { - enable = true; - proxychains.enable = true; - profiles = [ - { - name = "steam-browser"; - route = "proxychains"; - } - ]; - }; - }; - } - ]; - _localProxyAuthPasswordFile = mkProxyCtlDerived localProxyAuthPasswordFileFixture; - localProxyAuthPasswordFileWrapper = _localProxyAuthPasswordFile.wrapper; - localProxyAuthPasswordFileScript = _localProxyAuthPasswordFile.script; - localProxyAuthPasswordFileStartScript = builtins.readFile ( - localProxyAuthPasswordFileFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - - perAppRoutingDefaultProfilesFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.perAppRouting = { - enable = true; - createDefaultProfiles = true; - proxychains.enable = true; - }; - } - ]; - _perAppRoutingDefaultProfiles = mkProxyCtlDerived perAppRoutingDefaultProfilesFixture; - perAppRoutingDefaultProfilesProxyCtl = _perAppRoutingDefaultProfiles.proxyCtl; - perAppRoutingDefaultProfilesWrapper = _perAppRoutingDefaultProfiles.wrapper; - perAppRoutingDefaultProfilesScript = _perAppRoutingDefaultProfiles.script; - perAppRoutingDefaultProfiles = _perAppRoutingDefaultProfiles.profiles; - - perAppRoutingNoDefaultProfilesFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy = { - tun.perApp.enable = true; - tproxy.perApp.enable = true; - }; - zapret = { - enable = true; - perApp.enable = true; - }; - perAppRouting = { - enable = true; - createDefaultProfiles = false; - proxychains.enable = true; - }; - }; - } - ]; - _perAppRoutingNoDefaultProfiles = mkProxyCtlDerived perAppRoutingNoDefaultProfilesFixture; - perAppRoutingNoDefaultProfilesProxyCtl = _perAppRoutingNoDefaultProfiles.proxyCtl; - perAppRoutingNoDefaultProfilesWrapper = _perAppRoutingNoDefaultProfiles.wrapper; - perAppRoutingNoDefaultProfilesScript = _perAppRoutingNoDefaultProfiles.script; - perAppRoutingNoDefaultProfiles = _perAppRoutingNoDefaultProfiles.profiles; - - perAppRoutingDefaultProfilesWithoutProxychainsEnable = mkBadFixture [ - { - services.proxy-suite.perAppRouting = { - enable = true; - createDefaultProfiles = true; - }; - } - ]; - - perAppRoutingTunFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy.tun.perApp.enable = true; - perAppRouting = { - enable = true; - createDefaultProfiles = true; - }; - }; - } - ]; - _perAppRoutingTun = mkProxyCtlDerived perAppRoutingTunFixture; - perAppRoutingTunProxyCtl = _perAppRoutingTun.proxyCtl; - perAppRoutingTunWrapper = _perAppRoutingTun.wrapper; - perAppRoutingTunScript = _perAppRoutingTun.script; - perAppRoutingTunProfiles = _perAppRoutingTun.profiles; - perAppRoutingTunServiceConfig = - perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig; - perAppRoutingTunStartScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStart; - perAppRoutingTunUpScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStartPost; - perAppRoutingTunCleanupScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStopPost; - perAppRoutingTunConfig = mkPerAppTunConfig perAppRoutingTunFixture; - perAppRoutingTunDirectOutbound = builtins.head ( - builtins.filter (item: item.tag == "direct") perAppRoutingTunConfig.outbounds - ); - perAppRoutingTunUserStartExec = - perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun-user@".serviceConfig.ExecStart; - perAppRoutingTunUserStartScript = builtins.readFile ( - builtins.head (pkgs.lib.splitString " " perAppRoutingTunUserStartExec) - ); - - perAppRoutingTunWithTproxyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy = { - tproxy.enable = true; - tun.perApp.enable = true; - }; - perAppRouting = { - enable = true; - createDefaultProfiles = true; - }; - }; - } - ]; - perAppRoutingTunWithTproxyStartScript = - builtins.readFile - perAppRoutingTunWithTproxyFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart; - perAppRoutingTunWithTproxyConfig = mkPerAppTunConfig perAppRoutingTunWithTproxyFixture; - perAppRoutingTunWithTproxyDirectOutbound = builtins.head ( - builtins.filter (item: item.tag == "direct") perAppRoutingTunWithTproxyConfig.outbounds - ); - - perAppRoutingTunWithoutEnable = mkBadFixture [ - { - services.proxy-suite.perAppRouting = { - enable = true; - profiles = [ - { - name = "game"; - route = "tun"; - } - ]; - }; - } - ]; - - perAppRoutingTproxyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy.tproxy.perApp.enable = true; - perAppRouting = { - enable = true; - createDefaultProfiles = true; - }; - }; - } - ]; - _perAppRoutingTproxy = mkProxyCtlDerived perAppRoutingTproxyFixture; - perAppRoutingTproxyProxyCtl = _perAppRoutingTproxy.proxyCtl; - perAppRoutingTproxyWrapper = _perAppRoutingTproxy.wrapper; - perAppRoutingTproxyScript = _perAppRoutingTproxy.script; - perAppRoutingTproxyProfiles = _perAppRoutingTproxy.profiles; - perAppRoutingTproxyServiceConfig = - perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig; - perAppRoutingTproxyStartScript = builtins.readFile perAppRoutingTproxyServiceConfig.ExecStart; - perAppRoutingTproxyStopScript = builtins.readFile perAppRoutingTproxyServiceConfig.ExecStop; - perAppRoutingTproxyUserStartExec = - perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".serviceConfig.ExecStart; - perAppRoutingTproxyUserStartScript = builtins.readFile ( - builtins.head (pkgs.lib.splitString " " perAppRoutingTproxyUserStartExec) - ); - - perAppRoutingTproxyWithoutEnable = mkBadFixture [ - { - services.proxy-suite.perAppRouting = { - enable = true; - profiles = [ - { - name = "browser"; - route = "tproxy"; - } - ]; - }; - } - ]; - - perAppRoutingProxychainsWithoutProxy = mkBadFixture [ - { - services.proxy-suite = { - proxy.enable = false; - perAppRouting = { - enable = true; - proxychains.enable = true; - }; - }; - } - ]; - - perAppRoutingTunBackendWithoutProxy = mkBadFixture [ - { - services.proxy-suite = { - proxy = { - enable = false; - tun.perApp.enable = true; - }; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingTproxyBackendWithoutProxy = mkBadFixture [ - { - services.proxy-suite = { - proxy = { - enable = false; - tproxy.perApp.enable = true; - }; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingTunProfileWithoutProxy = mkBadFixture [ - { - services.proxy-suite = { - proxy.enable = false; - perAppRouting = { - enable = true; - profiles = [ - { - name = "game"; - route = "tun"; - } - ]; - }; - }; - } - ]; - - perAppRoutingTproxyProfileWithoutProxy = mkBadFixture [ - { - services.proxy-suite = { - proxy.enable = false; - perAppRouting = { - enable = true; - profiles = [ - { - name = "browser"; - route = "tproxy"; - } - ]; - }; - }; - } - ]; - - perAppRoutingZapretFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - zapret = { - enable = true; - perApp.enable = true; - }; - perAppRouting = { - enable = true; - createDefaultProfiles = true; - proxychains.enable = true; - }; - }; - } - ]; - _perAppRoutingZapret = mkProxyCtlDerived perAppRoutingZapretFixture; - perAppRoutingZapretProxyCtl = _perAppRoutingZapret.proxyCtl; - perAppRoutingZapretWrapper = _perAppRoutingZapret.wrapper; - perAppRoutingZapretScript = _perAppRoutingZapret.script; - perAppRoutingZapretProfiles = _perAppRoutingZapret.profiles; - perAppRoutingZapretStartScript = - readExecScripts - perAppRoutingZapretFixture.config.systemd.services."proxy-suite-per-app-zapret".serviceConfig.ExecStartPre; - perAppRoutingZapretUserStartExec = - perAppRoutingZapretFixture.config.systemd.services."proxy-suite-per-app-zapret-user@".serviceConfig.ExecStart; - perAppRoutingZapretUserStartScript = builtins.readFile ( - builtins.head (pkgs.lib.splitString " " perAppRoutingZapretUserStartExec) - ); - perAppRoutingZapretService = - perAppRoutingZapretFixture.config.systemd.services."proxy-suite-per-app-zapret"; - perAppRoutingZapretBase = mkZapretBase perAppRoutingZapretFixture; - perAppRoutingZapretConfig = builtins.readFile "${perAppRoutingZapretBase}/config"; - perAppRoutingPerAppZapretBase = mkZapretBaseFor perAppRoutingZapretFixture "proxy-suite-per-app-zapret"; - perAppRoutingPerAppZapretConfig = builtins.readFile "${perAppRoutingPerAppZapretBase}/config"; - perAppRoutingZapretGlobalCustomScript = builtins.readFile "${perAppRoutingZapretBase}/init.d/sysv/custom.d/50-proxy-suite-custom.sh"; - - perAppRoutingZapretWithoutGlobalFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - zapret = { - enable = false; - perApp.enable = true; - }; - perAppRouting = { - enable = true; - createDefaultProfiles = true; - proxychains.enable = true; - }; - }; - } - ]; - _perAppRoutingZapretWithoutGlobal = mkProxyCtlDerived perAppRoutingZapretWithoutGlobalFixture; - perAppRoutingZapretWithoutGlobalProfiles = _perAppRoutingZapretWithoutGlobal.profiles; - perAppRoutingZapretWithoutGlobalPerAppBase = mkZapretBaseFor perAppRoutingZapretWithoutGlobalFixture "proxy-suite-per-app-zapret"; - perAppRoutingZapretWithoutGlobalPerAppConfig = builtins.readFile "${perAppRoutingZapretWithoutGlobalPerAppBase}/config"; - - perAppRoutingTunPolkitConfig = perAppRoutingTunFixture.config.security.polkit.extraConfig; - - userControlGlobalOnlyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.userControl = { - global.enable = true; - perApp.enable = false; - }; - } - ]; - userControlGlobalOnlyPolkitConfig = userControlGlobalOnlyFixture.config.security.polkit.extraConfig; - - userControlPerAppOnlyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - proxy.tun.perApp.enable = true; - perAppRouting = { - enable = true; - createDefaultProfiles = true; - }; - userControl = { - global.enable = false; - perApp.enable = true; - }; - }; - } - ]; - userControlPerAppOnlyPolkitConfig = userControlPerAppOnlyFixture.config.security.polkit.extraConfig; - - userControlDisabledFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.userControl = { - global.enable = false; - perApp.enable = false; - }; - } - ]; - - perAppRoutingZapretWithoutEnable = mkBadFixture [ - { - services.proxy-suite = { - zapret.enable = true; - perAppRouting = { - enable = true; - profiles = [ - { - name = "yt"; - route = "zapret"; - } - ]; - }; - }; - } - ]; - - duplicatePerAppRoutingProfiles = mkBadFixture [ - { - services.proxy-suite.perAppRouting = { - enable = true; - profiles = [ - { name = "dup"; } - { name = "dup"; } - ]; - }; - } - ]; - - perAppRoutingProfilesWithoutEnable = mkBadFixture [ - { services.proxy-suite.perAppRouting.profiles = [ { name = "oops"; } ]; } - ]; - - perAppRoutingProxychainsWithoutEnable = mkBadFixture [ - { - services.proxy-suite.perAppRouting = { - enable = true; - profiles = [ - { - name = "steam-browser"; - route = "proxychains"; - } - ]; - }; - } - ]; - - perAppRoutingTunFwmarkCollision = mkBadFixture [ - { - services.proxy-suite = { - proxy = { - tproxy = { - enable = true; - proxyMark = 16; - }; - tun.perApp = { - enable = true; - fwmark = 16; - }; - }; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingTproxyFwmarkCollision = mkBadFixture [ - { - services.proxy-suite = { - proxy.tproxy = { - proxyMark = 17; - perApp = { - enable = true; - fwmark = 17; - }; - }; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingTunTproxyFwmarkCollision = mkBadFixture [ - { - services.proxy-suite = { - proxy = { - tun.perApp = { - enable = true; - fwmark = 23; - }; - tproxy.perApp = { - enable = true; - fwmark = 23; - }; - }; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingTunTproxyRouteTableCollision = mkBadFixture [ - { - services.proxy-suite = { - proxy = { - tun.perApp = { - enable = true; - routeTable = 123; - }; - tproxy.perApp = { - enable = true; - routeTable = 123; - }; - }; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingZapretFilterMarkCollision = mkBadFixture [ - { - services.proxy-suite = { - zapret = { - enable = true; - perApp = { - enable = true; - filterMark = 268435456; - }; - }; - proxy.tproxy.proxyMark = 268435456; - perAppRouting.enable = true; - }; - } - ]; - - perAppRoutingTproxyZapretMarkCollision = mkBadFixture [ - { - services.proxy-suite = { - zapret = { - enable = true; - perApp = { - enable = true; - filterMark = 23; - }; - }; - proxy.tproxy.perApp = { - enable = true; - fwmark = 23; - }; - perAppRouting.enable = true; - }; - } - ]; - - # Validation failures - subscriptionBothSources = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ - { - tag = "bad"; - url = "https://example.com/sub/token"; - urlFile = "/run/secrets/sub-url"; - } - ]; - }; - }; - } - ]; - - subscriptionNoSources = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - subscriptions = [ { tag = "bad"; } ]; - }; - }; - } - ]; - - localProxyAuthNoPassword = mkBadFixture [ - { services.proxy-suite.proxy.auth.username = "local-user"; } - ]; - - localProxyAuthNoUsername = mkBadFixture [ - { services.proxy-suite.proxy.auth.password = "local-pass"; } - ]; - - localProxyAuthBothPasswordSources = mkBadFixture [ - { - services.proxy-suite.proxy.auth = { - username = "local-user"; - password = "local-pass"; - passwordFile = "/run/secrets/local-proxy-password"; - }; - } - ]; - - noProxyBackendDefaultFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite.enable = true; - } - ]; - - noOutboundsNoSubscriptions = mkBadFixtureRaw [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - singBox.enable = true; - }; - }; - } - ]; - - blockGeoFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.proxy.routing.block = { - geosites = [ "category-ads-all" ]; - geoips = [ "cn" ]; - }; - } - ]; - blockGeoRules = mkRoutingRules blockGeoFixture; - - routingOrRules = mkRoutingRules routingOrFixture; - - routingOrDomainRules = builtins.filter ( - rule: (rule ? domain_suffix) && rule.domain_suffix == [ "example.com" ] - ) routingOrRules; - - routingOrGeoIPRules = builtins.filter ( - rule: (rule ? rule_set) && rule.rule_set == [ "geoip-us" ] - ) routingOrRules; - - validated = builtins.all (x: x) [ - ( - assert minimal.config.services.proxy-suite.proxy.listenAddress == "127.0.0.1"; - true - ) - # -- proxy.auth: default mixed inbound stays unauthenticated -- - ( - let - mixedInbound = builtins.head ( - builtins.filter (inbound: inbound.tag == "mixed-in") ruDefaultConfig.inbounds - ); - in - assert !(mixedInbound ? users); - true - ) - # -- proxy.auth: authenticated mixed inbound is injected at runtime -- - ( - assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript; - assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" localProxyAuthStartScript; - assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' localProxyAuthStartScript; - assert pkgs.lib.hasInfix "--arg user local-user" localProxyAuthStartScript; - assert pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript; - assert pkgs.lib.hasInfix ''select(.type == "mixed" and .tag == "mixed-in") | .users'' - localProxyAuthBackendJqFilter; - assert pkgs.lib.hasInfix ''chmod 600 "$RUNTIME_DIR/config.json"'' localProxyAuthStartScript; - true - ) - # -- proxy.auth: passwordFile is read from runtime path and proxychains uses runtime config -- - ( - assert pkgs.lib.hasInfix "/run/secrets/local-proxy-password" localProxyAuthPasswordFileStartScript; - assert pkgs.lib.hasInfix "/run/proxy-suite-socks/proxychains.conf" - localProxyAuthPasswordFileStartScript; - assert pkgs.lib.hasInfix "printf 'socks5 %s %s %s %s\\n'" localProxyAuthPasswordFileStartScript; - assert pkgs.lib.hasInfix ''chgrp proxy-suite "/run/proxy-suite-socks/proxychains.conf"'' - localProxyAuthPasswordFileStartScript; - assert pkgs.lib.hasInfix ''chmod 640 "/run/proxy-suite-socks/proxychains.conf"'' - localProxyAuthPasswordFileStartScript; - assert builtins.hasAttr "proxy-suite" localProxyAuthPasswordFileFixture.config.users.groups; - assert - shellValueByPrefix localProxyAuthPasswordFileWrapper "export PROXYCHAINS_CONFIG=" - == "/run/proxy-suite-socks/proxychains.conf"; - assert pkgs.lib.hasInfix "Proxychains config is not readable" localProxyAuthPasswordFileScript; - true - ) - # -- proxy.auth: incomplete or conflicting auth config fails -- - ( - assert localProxyAuthNoPassword.success == false; - assert localProxyAuthNoUsername.success == false; - assert localProxyAuthBothPasswordSources.success == false; - true - ) - ( - assert tgSecretFile.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; - true - ) - ( - assert minimal.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; - true - ) - ( - assert minimal.config.services.proxy-suite.tgWsProxy.dcIps == { }; - true - ) - # -- tg-ws-proxy: upstream runtime flags are exposed as typed module options -- - ( - assert pkgs.lib.hasInfix "--port=2443" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--host=0.0.0.0" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--secret-file=\"$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret\"" - tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--verbose" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--log-file=/var/log/tg-ws-proxy.log" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--log-max-mb=2.500000" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--log-backups=3" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--buf-kb=512" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--pool-size=8" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--cfproxy-domain=cdn.example.com" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--cfproxy-domain=edge.example.net" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--cfproxy-worker-domain=worker.example.com" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--no-cfproxy" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--fake-tls-domain=mask.example.com" tgAllOptionsStartScript; - assert pkgs.lib.hasInfix "--proxy-protocol" tgAllOptionsStartScript; - assert tgInvalidBufKb.success == false; - assert tgInvalidPoolSize.success == false; - assert tgInvalidLogBackups.success == false; - true - ) - ( - assert - tgSecretFile.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig.LoadCredential - == [ "tg_ws_proxy_secret:/run/secrets/tg-ws-proxy" ]; - true - ) - # -- tg-ws-proxy: global TUN/TProxy bypass mark keeps relay traffic out of transparent capture -- - ( - assert tgWithGlobalTunServiceConfig.SocketMark == "4"; - assert pkgs.lib.hasInfix "rule add pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassUp; - assert pkgs.lib.hasInfix "rule del pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassDown; - assert hasDirectIP tgWithGlobalTunRules "149.154.167.220"; - assert pkgs.lib.hasInfix "meta mark 4 return" tgWithGlobalTproxyNft; - assert tgRoutingMarkCollision.success == false; - true - ) - # -- boot ordering: network-sensitive global services wait for network-online -- - ( - assert builtins.elem "network-online.target" minimalSocksService.after; - assert builtins.elem "network-online.target" minimalSocksService.wants; - assert builtins.elem "network-online.target" tgSecretFileService.after; - assert builtins.elem "network-online.target" tgSecretFileService.wants; - assert builtins.elem "network-online.target" zapretSyncService.after; - assert builtins.elem "network-online.target" zapretSyncService.wants; - true - ) - # -- sing-box package override propagates into generated service scripts -- - ( - assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript; - true - ) - # -- hybrid backend: sing-box frontend with XRay loopback sidecar -- - ( - let - dnsBridgeInbound = builtins.head ( - builtins.filter (inbound: inbound.tag == "xray-dns-in") hybridTproxyConfig.inbounds - ); - mixedInbound = builtins.head ( - builtins.filter (inbound: inbound.tag == "mixed-in") hybridTproxyConfig.inbounds - ); - tproxyInbound = builtins.head ( - builtins.filter (inbound: inbound.tag == "tproxy-in") hybridTproxyConfig.inbounds - ); - tunDnsBridgeInbound = builtins.head ( - builtins.filter (inbound: inbound.tag == "xray-dns-in") hybridTunConfig.inbounds - ); - dnsBridgeRouteRule = builtins.head ( - builtins.filter ( - rule: - (rule.action or "") == "hijack-dns" && (rule ? inbound) && builtins.elem "xray-dns-in" rule.inbound - ) hybridTproxyConfig.route.rules - ); - in - assert hybridFixture.config.services.proxy-suite.proxy.singBox.enable; - assert hybridFixture.config.services.proxy-suite.proxy.xray.enable; - assert hybridTproxyConfig ? route; - assert !(hybridTproxyConfig ? routing); - assert dnsBridgeInbound.type == "direct"; - assert dnsBridgeInbound.listen == "127.0.0.1"; - assert dnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.socks; - assert mixedInbound.type == "mixed"; - assert tproxyInbound.type == "tproxy"; - assert tunDnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.tun; - assert - dnsBridgeRouteRule.network == [ - "tcp" - "udp" - ]; - assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript; - assert pkgs.lib.hasInfix "/bin/xray run -c" hybridStartScript; - assert pkgs.lib.hasInfix "xray-sidecar.json" hybridStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}" - hybridStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}" - hybridStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}" - hybridTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}" - hybridTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.perAppTun}" - hybridPerAppTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}" - hybridPerAppTunStartScript; - assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript; - assert pkgs.lib.hasInfix "--backend xray" hybridStartScript; - assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript; - assert pkgs.lib.hasInfix "hybrid XRay json sidecar" hybridXrayRawStartScript; - assert pkgs.lib.hasInfix ''{type:"socks",tag:$tag,server:"127.0.0.1"'' hybridXrayRawStartScript; - assert pkgs.lib.hasInfix "udp:true" hybridXrayRawStartScript; - assert pkgs.lib.hasInfix "routing_mark:2" hybridXrayRawStartScript; - assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter; - assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter; - assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionStartScript; - assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionUpdateScript; - assert pkgs.lib.hasInfix - ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' - hybridSubscriptionStartScript; - assert pkgs.lib.hasInfix ".singBox" hybridSubscriptionStartScript; - assert pkgs.lib.hasInfix ".xray[]" hybridSubscriptionStartScript; - assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridSubscriptionStartScript; - 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 specificRule.ruleTag == "custom-proxy-domain"; - 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 - ); - tunDirectOutbound = builtins.head ( - builtins.filter (outbound: outbound.tag == "direct") xrayTunConfig.outbounds - ); - perAppTunDirectOutbound = builtins.head ( - builtins.filter (outbound: outbound.tag == "direct") xrayPerAppTunConfig.outbounds - ); - tunDnsOutbound = builtins.head ( - builtins.filter (outbound: outbound.tag == "dns-out") xrayTunConfig.outbounds - ); - tunHasFinalRuleTag = builtins.any ( - rule: (rule ? ruleTag) && rule.ruleTag == "final-default" - ) xrayTunConfig.routing.rules; - tunHasDirectGeositeRule = builtins.any ( - rule: (rule ? ruleTag) && rule.ruleTag == "direct-geosite" - ) xrayTunConfig.routing.rules; - tunHasDnsHijackRule = builtins.any ( - rule: (rule ? ruleTag) && rule.ruleTag == "dns-hijack" - ) xrayTunConfig.routing.rules; - tunHasDnsUpstreamRule = builtins.any ( - rule: (rule ? ruleTag) && rule.ruleTag == "dns-upstream-direct" - ) xrayTunConfig.routing.rules; - in - assert tunInbound.protocol == "tun"; - assert tunInbound.settings.name == "singtun0"; - assert - tunInbound.settings.gateway == [ - "172.19.0.1/30" - checkConstants.xrayGlobalTunIPv6Address - ]; - assert builtins.length tunInbound.settings.dns == 2; - assert tunInbound.settings.autoOutboundsInterface == "auto"; - assert tunInbound.sniffing.destOverride == [ "fakedns" ]; - assert tunInbound.sniffing.metadataOnly == true; - assert xrayTunConfig.routing.domainStrategy == "IPIfNonMatch"; - assert tunHasFinalRuleTag; - assert tunHasDirectGeositeRule; - assert tunHasDnsHijackRule; - assert tunHasDnsUpstreamRule; - assert xrayTunConfig.dns.queryStrategy == "UseIP"; - assert xrayTunConfig.dns.tag == "dns-in"; - assert (builtins.head xrayTunConfig.dns.servers).address == "fakedns"; - assert (builtins.head xrayTunConfig.dns.servers).tag == "fakedns"; - assert (builtins.elemAt xrayTunConfig.dns.servers 1).tag == "remote"; - assert (builtins.elemAt xrayTunConfig.dns.servers 2).tag == "local"; - assert builtins.length xrayTunConfig.fakedns == 2; - assert tunDnsOutbound.protocol == "dns"; - assert - tunDnsOutbound.settings.rules == [ - { - action = "direct"; - qType = "2-27,29-65535"; - } - ]; - assert tunDirectOutbound.streamSettings.sockopt.mark == 2; - assert xrayStartBackendJqFilterFile == xrayTunBackendJqFilterFile; - assert xrayTunBackendJqFilterFile == xrayPerAppTunBackendJqFilterFile; - assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" xrayStartScript; - assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' xrayStartScript; - assert pkgs.lib.hasInfix - ''select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts'' - xrayBackendJqFilter; - assert - !(pkgs.lib.hasInfix ''select(.protocol == "socks" and .tag == "mixed-in") | .settings.users'' xrayBackendJqFilter); - assert pkgs.lib.hasInfix "xray-loglevel" xrayTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SINGLE_PROXY_TAG=" xrayTunStartScript; - assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1" xrayTunStartScript; - assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1 mark 2" xrayTunStartScript; - assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" xrayTunStartScript; - assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' xrayTunStartScript; - assert pkgs.lib.hasInfix "xray_tun_dns_runtime" xrayTunStartScript; - assert pkgs.lib.hasInfix "xray_preserved_rules" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "dns-upstream-direct" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "xray_tun_dns_addresses" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "dns-hijack" xrayBackendJqFilter; - assert pkgs.lib.hasInfix ".streamSettings.sockopt.interface = $interface" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "del(.observatory)" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "xray_rewrite_proxy_rule" xrayBackendJqFilter; - assert pkgs.lib.hasInfix ".protocol == \"dns\"" xrayBackendJqFilter; - assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayTunUpScript; - assert pkgs.lib.hasInfix checkConstants.xrayGlobalTunIPv6Address xrayTunUpScript; - assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayTunUpScript; - assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev singtun0'' xrayTunUpScript; - assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev singtun0'' xrayTunUpScript; - assert pkgs.lib.hasInfix - ''route replace "$tun_route_prefix" dev singtun0 src "$tun_addr" table ${toString checkConstants.tunAutoRouteTableIndex}'' - xrayTunUpScript; - assert pkgs.lib.hasInfix ''route replace default dev singtun0 src "$uplink_addr" table ${toString checkConstants.tunAutoRouteTableIndex}'' - xrayTunUpScript; - assert pkgs.lib.hasInfix ''-6 route replace "$tun6_route_prefix" dev singtun0 table ${toString checkConstants.tunAutoRouteTableIndex}'' - xrayTunUpScript; - assert pkgs.lib.hasInfix "-6 route replace default dev singtun0 table ${toString checkConstants.tunAutoRouteTableIndex}" - xrayTunUpScript; - assert pkgs.lib.hasInfix - "rule add pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority} fwmark 17 table 102" - xrayTunUpScript; - assert pkgs.lib.hasInfix - "rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101" - xrayTunUpScript; - assert pkgs.lib.hasInfix - "rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}" - xrayTunUpScript; - assert pkgs.lib.hasInfix - "-6 rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101" - xrayTunUpScript; - assert pkgs.lib.hasInfix - "-6 rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}" - xrayTunUpScript; - assert perAppTunInbound.settings.name == "psperapptun0"; - assert - perAppTunInbound.settings.gateway == [ - "172.20.0.1/30" - checkConstants.xrayPerAppTunIPv6Address - ]; - assert builtins.length perAppTunInbound.settings.dns == 2; - assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ]; - assert perAppTunInbound.sniffing.metadataOnly == true; - assert xrayPerAppTunConfig.routing.domainStrategy == "IPIfNonMatch"; - assert (builtins.head xrayPerAppTunConfig.dns.servers).address == "fakedns"; - assert xrayPerAppTunConfig.dns.tag == "dns-in"; - assert builtins.length xrayPerAppTunConfig.fakedns == 2; - assert perAppTunDirectOutbound.streamSettings.sockopt.mark == 2; - assert pkgs.lib.hasInfix "XRAY_SINGLE_PROXY_TAG=" xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1" xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1 mark 2" xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix "--routing-mark 2" xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix "xray_tun_dns_runtime" xrayPerAppTunStartScript; - assert pkgs.lib.hasInfix ".streamSettings.sockopt.interface = $interface" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayBackendJqFilter; - assert pkgs.lib.hasInfix "del(.observatory)" xrayBackendJqFilter; - assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix checkConstants.xrayPerAppTunIPv6Address xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev psperapptun0'' xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix - ''route replace "$tun_route_prefix" dev psperapptun0 src "$tun_addr" table 101'' - xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix ''route replace default dev psperapptun0 src "$uplink_addr" table 101'' - xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix ''-6 route replace "$tun6_route_prefix" dev psperapptun0 table 101'' - xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix "-6 route replace default dev psperapptun0 table 101" - xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix "-6 rule add fwmark 16 table 101" xrayPerAppTunUpScript; - assert pkgs.lib.hasInfix "-4 route flush table 101" xrayPerAppTunCleanupScript; - assert pkgs.lib.hasInfix "-6 route flush table 101" xrayPerAppTunCleanupScript; - assert pkgs.lib.hasInfix "resolvectl flush-caches" xrayPerAppTunCleanupScript; - 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 - ) - # -- xray backend: raw stream settings and DNS encoding are preserved -- - ( - let - localDns = dnsServerByTag xrayDnsTcpConfig "local"; - in - assert xrayRawStreamOutbound.tag == "proxy"; - assert xrayRawStreamOutbound.streamSettings.network == "ws"; - assert xrayRawStreamOutbound.streamSettings.security == "tls"; - assert xrayRawStreamOutbound.streamSettings.tlsSettings.serverName == "cdn.example.com"; - assert xrayRawStreamOutbound.streamSettings.wsSettings.path == "/ws"; - assert xrayRawStreamOutbound.streamSettings.sockopt.tcpFastOpen == true; - assert xrayRawStreamOutbound.streamSettings.sockopt.mark == 2; - assert localDns.address == "tcp://9.9.9.9"; - assert localDns.port == 5353; - assert localDns.queryStrategy == "UseIP"; - assert xrayDnsTlsUnavailable.success == false; - true - ) - # -- backend selection and backend-specific raw JSON options are enforced -- - ( - assert proxyEnabledNoBackend.success == false; - assert xraySelectorUnavailable.success == false; - assert xraySingBoxJsonUnavailable.success == false; - assert singBoxXrayJsonUnavailable.success == false; - true - ) - ( - assert duplicateTags.success == false; - true - ) - ( - assert reservedTag.success == false; - true - ) - ( - assert unknownRoutingTarget.success == false; - true - ) - ( - assert duplicateZapretHostlistNames.success == false; - true - ) - ( - assert emptyZapretHostlistDomains.success == false; - true - ) - ( - assert missingZapretHostlistAction.success == false; - true - ) - ( - assert conflictingZapretHostlistConfigAndArgs.success == false; - true - ) - ( - assert configNameZapretHostlistWithoutFamily.success == false; - true - ) - ( - assert tproxyWithFirewall.config.networking.firewall.enable; - true - ) - ( - assert tproxyManualFixture.config.services.proxy-suite.proxy.tproxy.autostart == false; - assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ]; - true - ) - ( - assert - tproxyAutostartFixture.config.systemd.services."proxy-suite-tproxy".wantedBy - == [ "multi-user.target" ]; - true - ) - ( - assert pkgs.lib.hasInfix "set -euo pipefail" tproxyManualStartScript; - assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStartScript; - assert pkgs.lib.hasInfix "route replace local default dev lo table 100" tproxyManualStartScript; - assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript; - assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript; - true - ) - ( - assert tunManualFixture.config.services.proxy-suite.proxy.tun.autostart == false; - assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ]; - true - ) - ( - let - inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds); - in - assert inbound.iproute2_table_index == checkConstants.tunAutoRouteTableIndex; - assert inbound.iproute2_rule_index == checkConstants.tunAutoRouteRulePriority; - assert tunDefaultConfig.route.auto_detect_interface == true; - true - ) - ( - assert tunManualFixture.config.networking.nftables.enable; - true - ) - ( - assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost; - assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript; - assert pkgs.lib.hasInfix "rule del table ${toString checkConstants.tunAutoRouteTableIndex}" - tunCleanupScript; - assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority}" - tunCleanupScript; - assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTunRulePriority}" - tunCleanupScript; - assert pkgs.lib.hasInfix "route flush table ${toString checkConstants.tunAutoRouteTableIndex}" - tunCleanupScript; - assert pkgs.lib.hasInfix "link del dev" tunCleanupScript; - assert pkgs.lib.hasInfix "singtun0" tunCleanupScript; - true - ) - ( - assert - tunAutostartFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ "multi-user.target" ]; - true - ) - ( - assert conflictingAutostartModes.success == false; - true - ) - ( - assert globalTunWithoutProxy.success == false; - assert globalTproxyWithoutProxy.success == false; - true - ) - ( - assert builtins.length routingOrDomainRules == 1; - true - ) - ( - assert builtins.length routingOrGeoIPRules == 1; - true - ) - ( - assert (builtins.head routingOrDomainRules).outbound == "proxy"; - true - ) - ( - assert (builtins.head routingOrGeoIPRules).outbound == "proxy"; - true - ) - ( - let - localDns = dnsServerByTag ruDefaultConfig "local"; - remoteDns = dnsServerByTag ruDefaultConfig "remote"; - in - assert localDns.type == "udp"; - assert localDns.server == "1.1.1.1"; - assert localDns.server_port == 53; - assert !(localDns ? detour); - assert remoteDns.type == "udp"; - assert remoteDns.server == "1.1.1.1"; - assert remoteDns.server_port == 53; - assert remoteDns.detour == "proxy"; - true - ) - ( - assert hasRuleSet ruDefaultRules "direct" "geosite-category-ru"; - true - ) - ( - assert hasRuleSet ruDefaultRules "direct" "geoip-ru"; - true - ) - ( - assert dnsHasRuleSet ruDefaultConfig.dns.rules "geosite-category-ru"; - true - ) - ( - assert !(hasRuleSet ruDisabledRules "direct" "geosite-category-ru"); - true - ) - ( - assert !(hasRuleSet ruDisabledRules "direct" "geoip-ru"); - true - ) - ( - assert !(dnsHasRuleSet ruDisabledConfig.dns.rules "geosite-category-ru"); - true - ) - ( - assert dnsHasRuleSet ruExplicitConfig.dns.rules "geosite-category-ru"; - true - ) - ( - let - localDns = dnsServerByTag dnsLocalOverrideConfig "local"; - in - assert localDns.type == "tcp"; - assert localDns.server == "9.9.9.9"; - assert localDns.server_port == 5353; - assert !(localDns ? detour); - true - ) - ( - let - remoteDns = dnsServerByTag dnsRemoteOverrideConfig "remote"; - in - assert remoteDns.type == "tls"; - assert remoteDns.server == "1.0.0.1"; - assert remoteDns.server_port == 853; - assert remoteDns.detour == "proxy"; - true - ) - ( - let - localDns = dnsServerByTag tunDefaultConfig "local"; - in - assert !(localDns ? detour); - true - ) - ( - assert hasDirectDomain zapretSyncRules "discord.com"; - true - ) - ( - assert hasDirectDomain zapretSyncRules "youtube.com"; - true - ) - ( - assert hasDirectDomain zapretSyncRules "cloudflare-ech.com"; - true - ) - ( - assert !(hasDirectDomain zapretSyncRules "twitter.com"); - true - ) - ( - assert !(hasDirectIP zapretSyncRules "1.1.1.0/24"); - true - ) - ( - assert hasDirectDomain zapretSyncDomainsOnlyRules "cloudflare-ech.com"; - true - ) - ( - assert !(hasDirectIP zapretSyncDomainsOnlyRules "1.1.1.0/24"); - true - ) - ( - assert hasDirectIP zapretSyncIpsRules "1.1.1.0/24"; - true - ) - ( - assert !(hasDirectDomain zapretSyncNoExtraListsRules "twitter.com"); - true - ) - ( - assert hasDirectDomain zapretSyncExtraListsRules "twitter.com"; - true - ) - ( - assert !(hasDirectIP zapretSyncUserIpsDisabledRules "203.0.113.0/24"); - true - ) - ( - assert !(hasDirectDomain zapretSyncDisabledRules "discord.com"); - true - ) - ( - assert !(hasDirectIP zapretSyncDisabledRules "1.1.1.0/24"); - true - ) - ( - assert hasDirectDomain zapretExtrasRules "pixiv.net"; - true - ) - ( - assert hasDirectIP zapretIpExtrasRules "203.0.113.0/24"; - true - ) - ( - assert !(hasDirectDomain zapretExcludesRules "discord.com"); - true - ) - ( - assert !(hasDirectIP zapretIpExcludesRules "1.1.1.0/24"); - true - ) - ( - assert hasDirectDomain zapretHostlistRules "googlevideo.com"; - true - ) - ( - assert hasDirectDomain zapretHostlistRules "example.com"; - true - ) - ( - assert !(hasDirectDomain zapretHostlistRules "x.example"); - true - ) - ( - assert hasDirectDomain zapretHostlistRules "youtube.com"; - assert hasDirectDomain zapretHostlistRules "discord.com"; - assert hasDirectDomain zapretHostlistRules "cloudflare-ech.com"; - true - ) - ( - assert hasDirectIP zapretHostlistRules "203.0.113.0/24"; - assert !(hasDirectIP zapretHostlistRules "1.1.1.0/24"); - true - ) - ( - assert hasRuleSet blockGeoRules "block" "geosite-category-ads-all"; - true - ) - ( - assert hasRuleSet blockGeoRules "block" "geoip-cn"; - true - ) - ( - assert proxyDirectConfig.dns.final == "local"; - true - ) - ( - assert ruDefaultConfig.dns.final == "remote"; - true - ) - ( - assert ruDefaultConfig.route.default_domain_resolver == "local"; - assert tunDefaultConfig.route.default_domain_resolver == "local"; - assert perAppRoutingTunConfig.route.default_domain_resolver == "local"; - true - ) - ( - assert packagePathMatches trayAutostartFixture.config.environment.systemPackages - ".*/[^/]*proxy-suite-tray(-[0-9.]+)?$"; - true - ) - ( - assert packagePathMatches trayAutostartFixture.config.environment.systemPackages - ".*/[^/]*proxy-suite-tray\\.desktop$"; - true - ) - ( - assert - builtins.match ".*/share/xdg/autostart/proxy-suite-tray\\.desktop$" ( - builtins.unsafeDiscardStringContext - trayAutostartFixture.config.environment.etc."xdg/autostart/proxy-suite-tray.desktop".source - ) != null; - true - ) - ( - assert !(trayManualFixture.config.environment.etc ? "xdg/autostart/proxy-suite-tray.desktop"); - true - ) - ( - assert packagePathMatches trayManualFixture.config.environment.systemPackages - ".*/[^/]*proxy-suite-tray\\.desktop$"; - true - ) - - # -- subscription: basic config is accepted -- - ( - assert subscriptionOnlyFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; - true - ) - - # -- subscription: wrapper exposes tags through a JSON file, not shell word splitting -- - ( - assert subscriptionOnlyTags == [ "community" ]; - assert pkgs.lib.hasInfix "export SUB_TAGS_FILE=" subscriptionOnlyScript; - assert !(pkgs.lib.hasInfix "SUB_TAGS_RAW" subscriptionOnlyScript); - true - ) - - # -- subscription: update service is created when subscriptions are configured -- - ( - assert subscriptionOnlyFixture.config.systemd.services ? "proxy-suite-subscription-update"; - true - ) - - # -- subscription: update timer is created when subscriptions are configured -- - ( - assert subscriptionOnlyFixture.config.systemd.timers ? "proxy-suite-subscription-update"; - true - ) - - # -- subscription: StateDirectory set on socks service -- - ( - assert - subscriptionOnlyFixture.config.systemd.services."proxy-suite-socks".serviceConfig.StateDirectory - == "proxy-suite"; - true - ) - - # -- subscription: custom update interval flows through to timer -- - ( - assert - subscriptionWithStaticFixture.config.systemd.timers."proxy-suite-subscription-update".timerConfig.OnUnitActiveSec - == "6h"; - true - ) - - # -- subscription: duplicate tags fail because they are cache keys and tag prefixes -- - ( - assert duplicateSubscriptionTags.success == false; - true - ) - - # -- subscription: tag must be a filesystem-safe identifier -- - ( - assert unsafeSubscriptionTag.success == false; - true - ) - - # -- subscription: selection=first renames first subscription outbound to "proxy" -- - ( - let - startScript = - subscriptionFirstSelectionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; - scriptText = builtins.readFile startScript; - in - assert builtins.match ".*proxy.*" scriptText != null; - true - ) - - # -- runtime parser: socks start script sets PYTHONPATH for static URL parser imports -- - ( - let - startScript = - subscriptionWithStaticFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; - scriptText = builtins.readFile startScript; - in - assert builtins.match ".*PYTHONPATH=.*build-outbound\\.py.*" scriptText != null; - true - ) - - # -- subscription/runtime parser: update script sets PYTHONPATH for parser module imports -- - ( - let - updateScript = - subscriptionOnlyFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart; - scriptText = builtins.readFile updateScript; - in - assert builtins.match ".*PYTHONPATH=.*fetch-subscription\\.py.*" scriptText != null; - true - ) - - # -- 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/sing-box/community.json"'' - subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix "/var/lib/proxy-suite/subscriptions/sing-box/community.json.tmp" - subscriptionOnlyUpdateScript; - assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyStartScript); - assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyUpdateScript); - true - ) - - # -- subscription/runtime: invalid cache files are ignored and refreshed -- - ( - assert pkgs.lib.hasInfix "_proxy_suite_valid_subscription_cache()" subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix "_proxy_suite_drop_invalid_subscription_cache" subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix "removed invalid subscription cache" subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix "produced an invalid cache" subscriptionOnlyUpdateScript; - true - ) - - # -- subscription/runtime: refresh only restarts sing-box units that are active -- - ( - assert pkgs.lib.hasInfix "is-active --quiet proxy-suite-socks" subscriptionOnlyUpdateScript; - assert pkgs.lib.hasInfix "restart proxy-suite-socks" subscriptionOnlyUpdateScript; - assert pkgs.lib.hasInfix "is-active --quiet proxy-suite-tun" subscriptionOnlyUpdateScript; - assert !(pkgs.lib.hasInfix "SOCKS_WAS_ACTIVE" subscriptionOnlyUpdateScript); - true - ) - - # -- subscription/runtime: refresh also handles the per-app TUN sing-box service when present -- - ( - assert pkgs.lib.hasInfix "is-active --quiet proxy-suite-per-app-tun" - subscriptionPerAppTunUpdateScript; - assert pkgs.lib.hasInfix "restart proxy-suite-per-app-tun" subscriptionPerAppTunUpdateScript; - assert !(pkgs.lib.hasInfix "PER_APP_TUN_WAS_ACTIVE" subscriptionPerAppTunUpdateScript); - true - ) - - # -- subscription: no update service/timer without subscriptions -- - ( - assert !(minimal.config.systemd.services ? "proxy-suite-subscription-update"); - true - ) - ( - assert !(minimal.config.systemd.timers ? "proxy-suite-subscription-update"); - true - ) - - # -- subscription: urlFile form accepted -- - ( - assert subscriptionUrlFileFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; - true - ) - - # -- runtime route mode: proxy-ctl wrapper exports the volatile state file and baseline default -- - ( - assert - shellValueByPrefix minimalProxyCtlWrapper "export ROUTE_MODE_STATE_FILE=" - == "/run/proxy-suite/route-mode"; - assert shellValueByPrefix minimalProxyCtlWrapper "export DEFAULT_ROUTE_MODE=" == "blacklist"; - true - ) - - # -- runtime route mode: proxy-ctl help/status script exposes default + four explicit modes -- - ( - assert pkgs.lib.hasInfix "route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" - minimalProxyCtlScript; - assert pkgs.lib.hasInfix ''printf 'route_mode=%s\n' "$(_route_mode_current)"'' - minimalProxyCtlScript; - assert pkgs.lib.hasInfix ''printf 'default_route_mode=%s\n' "$(_route_mode_default)"'' - minimalProxyCtlScript; - assert pkgs.lib.hasInfix ''systemctl start "proxy-suite-route-mode@''${action}.service"'' - minimalProxyCtlScript; - true - ) - - # -- runtime route mode: socks start script includes all override branches and uses volatile state -- - ( - assert pkgs.lib.hasInfix ''ROUTE_MODE_STATE_FILE="/run/proxy-suite/route-mode"'' - routeModeStartScript; - assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" routeModeStartScript; - assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' routeModeStartScript; - assert pkgs.lib.hasInfix "all-proxy)" routeModeStartScript; - assert pkgs.lib.hasInfix "all-bypass)" routeModeStartScript; - assert pkgs.lib.hasInfix ".route.rules = (sing_box_preserved_rules + $route_rules)" - routeModeBackendJqFilter; - assert pkgs.lib.hasInfix ".dns.rules = []" routeModeBackendJqFilter; - true - ) - - # -- runtime route mode: grouped routing metadata preserves custom rule categories and order -- - ( - assert builtins.length routeModeRules.custom == 3; - assert (builtins.elemAt routeModeRules.custom 0).category == "direct"; - assert (builtins.elemAt routeModeRules.custom 1).category == "proxy"; - assert (builtins.elemAt routeModeRules.custom 2).category == "block"; - true - ) - - # -- runtime route mode: setter unit is present and writes into /run -- - ( - let - setterSvc = routeModeFixture.config.systemd.services."proxy-suite-route-mode@"; - setterScript = builtins.readFile ( - builtins.head (pkgs.lib.splitString " " setterSvc.serviceConfig.ExecStart) - ); - in - assert !(setterSvc.serviceConfig ? RuntimeDirectory); - assert pkgs.lib.hasInfix "/run/proxy-suite/route-mode" setterScript; - assert pkgs.lib.hasInfix "default)" setterScript; - assert pkgs.lib.hasInfix "all-proxy)" setterScript; - assert pkgs.lib.hasInfix "all-bypass)" setterScript; - true - ) - - # -- subscription: both url + urlFile fails -- - ( - assert subscriptionBothSources.success == false; - true - ) - - # -- subscription: neither url nor urlFile fails -- - ( - assert subscriptionNoSources.success == false; - true - ) - - # -- perAppRouting: proxychains/direct profile config is accepted -- - ( - assert perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.enable; - true - ) - ( - assert - builtins.length perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.profiles - == 2; - true - ) - ( - assert builtins.length perAppRoutingProxychainsProfiles == 2; - true - ) - - # -- perAppRouting: createDefaultProfiles injects curated proxychains profile -- - ( - assert builtins.length perAppRoutingDefaultProfiles == 1; - assert (builtins.head perAppRoutingDefaultProfiles).name == "proxychains"; - assert (builtins.head perAppRoutingDefaultProfiles).route == "proxychains"; - true - ) - - # -- perAppRouting: createDefaultProfiles = false injects no curated profiles -- - ( - assert builtins.length perAppRoutingNoDefaultProfiles == 0; - true - ) - - # -- perAppRouting: createDefaultProfiles injects curated tun profile when backend is enabled -- - ( - assert builtins.length perAppRoutingTunProfiles == 2; - assert builtins.any ( - profile: profile.name == "tun" && profile.route == "tun" - ) perAppRoutingTunProfiles; - true - ) - - # -- perAppRouting: createDefaultProfiles injects curated tproxy profile when backend is enabled -- - ( - assert builtins.length perAppRoutingTproxyProfiles == 2; - assert builtins.any ( - profile: profile.name == "tproxy" && profile.route == "tproxy" - ) perAppRoutingTproxyProfiles; - true - ) - - # -- perAppRouting: createDefaultProfiles injects curated zapret profile when backend is enabled -- - ( - assert builtins.length perAppRoutingZapretProfiles == 2; - assert builtins.any ( - profile: profile.name == "zapret" && profile.route == "zapret" - ) perAppRoutingZapretProfiles; - true - ) - - # -- perAppRouting: proxy-ctl script embeds wrap/apps commands -- - ( - assert pkgs.lib.hasInfix "help)" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "show this help message" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "enable/disable the proxy backend stack" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "restart active global proxy-suite services" - perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "wrap -- " perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript; - true - ) - - # -- perAppRouting: proxychains config is quiet and points at local SOCKS listener -- - ( - assert pkgs.lib.hasInfix "quiet_mode" perAppRoutingProxychainsConfig; - assert pkgs.lib.hasInfix "proxy_dns" perAppRoutingProxychainsConfig; - assert pkgs.lib.hasInfix "socks5 127.0.0.1 1080" perAppRoutingProxychainsConfig; - true - ) - - # -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds -- - ( - assert pkgs.lib.hasInfix "if _svc_exists proxy-suite-socks; then" minimalProxyCtlScript; - assert pkgs.lib.hasInfix "_svc_exists \"$svc\" && _svc_active \"$svc\"" minimalProxyCtlScript; - assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript; - true - ) - - # -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 -- - ( - assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG='-q'" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix - "exec proxychains4 $PROXYCHAINS_QUIET_ARG -f \"$PROXYCHAINS_CONFIG\" \"$@\"" - perAppRoutingProxychainsScript; - true - ) - - # -- perAppRouting: generated proxy-ctl script dispatches tun profiles through systemd slices -- - ( - assert pkgs.lib.hasInfix "PER_APP_ROUTING_TUN_ENABLED" perAppRoutingTunScript; - assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" - perAppRoutingTunScript; - assert pkgs.lib.hasInfix "_check_no_global_proxy tun" perAppRoutingTunScript; - assert pkgs.lib.hasInfix - ''_wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED"'' - perAppRoutingTunScript; - assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" perAppRoutingTunScript; - assert pkgs.lib.hasInfix "cleanup_slice()" perAppRoutingTunScript; - assert pkgs.lib.hasInfix "trap cleanup_slice EXIT" perAppRoutingTunScript; - true - ) - - # -- perAppRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices -- - ( - assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript; - assert pkgs.lib.hasInfix - ''_wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED"'' - perAppRoutingTproxyScript; - assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript; - true - ) - - # -- perAppRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices -- - ( - assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript; - assert pkgs.lib.hasInfix - ''_wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED"'' - perAppRoutingZapretScript; - assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript; - true - ) - - # -- perAppRouting: user mark script installs fwmark + conntrack mark rules -- - ( - assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTunUserStartScript; - assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTunUserStartScript; - true - ) - - # -- perAppRouting: app TUN config is separate and does not auto-route globally -- - ( - let - inbound = builtins.head ( - builtins.filter (item: item.tag == "tun-in") perAppRoutingTunConfig.inbounds - ); - in - assert inbound.interface_name == "psperapptun0"; - assert inbound.address == [ "172.20.0.1/30" ]; - assert inbound.auto_route == false; - assert inbound.auto_redirect == false; - assert inbound.strict_route == false; - assert !(inbound ? iproute2_table_index); - assert !(inbound ? iproute2_rule_index); - true - ) - - # -- perAppRouting: app TUN local DNS keeps direct path without explicit detour -- - ( - let - localDns = dnsServerByTag perAppRoutingTunConfig "local"; - in - assert !(localDns ? detour); - true - ) - - # -- perAppRouting: app TUN does not set outbound routing marks when TProxy is disabled -- - ( - assert builtins.match ".*--routing-mark.*" perAppRoutingTunStartScript == null; - assert !(perAppRoutingTunDirectOutbound ? routing_mark); - true - ) - - # -- perAppRouting: app TUN applies outbound routing marks when TProxy is enabled -- - ( - let - expectedMark = perAppRoutingTunWithTproxyFixture.config.services.proxy-suite.proxy.tproxy.proxyMark; - in - assert builtins.match ".*--routing-mark.*" perAppRoutingTunWithTproxyStartScript != null; - assert perAppRoutingTunWithTproxyDirectOutbound.routing_mark == expectedMark; - true - ) - - # -- perAppRouting: app TUN service and helper units are created -- - ( - assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun"; - assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@"; - assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor"; - assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost; - assert !(pkgs.lib.hasInfix "-6 addr replace" perAppRoutingTunUpScript); - assert !(pkgs.lib.hasInfix "-6 route replace" perAppRoutingTunUpScript); - assert !(pkgs.lib.hasInfix "-6 rule add" perAppRoutingTunUpScript); - assert pkgs.lib.hasInfix "link del dev" perAppRoutingTunCleanupScript; - assert pkgs.lib.hasInfix "psperapptun0" perAppRoutingTunCleanupScript; - assert pkgs.lib.hasInfix "rule del fwmark 16 table 101" perAppRoutingTunCleanupScript; - true - ) - - # -- perAppRouting: app TProxy service and helper units are created -- - ( - assert perAppRoutingTproxyFixture.config.systemd.services ? "proxy-suite-per-app-tproxy"; - assert perAppRoutingTproxyFixture.config.systemd.services ? "proxy-suite-per-app-tproxy-user@"; - assert - perAppRoutingTproxyFixture.config.systemd.user.services ? "proxy-suite-per-app-tproxy-anchor"; - true - ) - - # -- perAppRouting: app zapret service and helper units are created -- - ( - assert perAppRoutingZapretFixture.config.systemd.services ? "proxy-suite-per-app-zapret"; - assert perAppRoutingZapretFixture.config.systemd.services ? "proxy-suite-per-app-zapret-user@"; - assert - perAppRoutingZapretFixture.config.systemd.user.services ? "proxy-suite-per-app-zapret-anchor"; - assert builtins.elem "network-online.target" perAppRoutingZapretService.after; - assert builtins.elem "network-online.target" perAppRoutingZapretService.wants; - true - ) - - # -- perAppRouting: app zapret can run without the global zapret service -- - ( - assert - perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-per-app-zapret"; - assert - perAppRoutingZapretWithoutGlobalFixture.config.systemd.services - ? "proxy-suite-per-app-zapret-user@"; - assert - perAppRoutingZapretWithoutGlobalFixture.config.systemd.user.services - ? "proxy-suite-per-app-zapret-anchor"; - assert - !(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "zapret-discord-youtube"); - assert builtins.length perAppRoutingZapretWithoutGlobalProfiles == 2; - assert builtins.any ( - profile: profile.name == "zapret" && profile.route == "zapret" - ) perAppRoutingZapretWithoutGlobalProfiles; - assert pkgs.lib.hasInfix "proxy-suite-per-app-zapret" perAppRoutingZapretWithoutGlobalPerAppBase; - assert !(pkgs.lib.hasInfix "proxy-suite-zapret" perAppRoutingZapretWithoutGlobalPerAppBase); - true - ) - - # -- perAppRouting: app TUN enables nftables and user control group -- - ( - assert perAppRoutingTunFixture.config.networking.nftables.enable; - assert perAppRoutingTunFixture.config.users.groups ? "proxy-suite"; - assert builtins.elem "network-online.target" - tunManualFixture.config.systemd.services."proxy-suite-tun".after; - assert builtins.elem "network-online.target" - tunManualFixture.config.systemd.services."proxy-suite-tun".wants; - true - ) - - # -- userControl: default polkit rule covers both per-app and global proxy-ctl managed units -- - ( - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") === 0" - perAppRoutingTunPolkitConfig; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" perAppRoutingTunPolkitConfig; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" - perAppRoutingTunPolkitConfig; - assert pkgs.lib.hasInfix "unit === \"zapret-discord-youtube.service\"" perAppRoutingTunPolkitConfig; - true - ) - - # -- userControl: global-only rule excludes per-app units -- - ( - assert userControlGlobalOnlyFixture.config.users.groups ? "proxy-suite"; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlGlobalOnlyPolkitConfig; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" - userControlGlobalOnlyPolkitConfig; - assert - builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) === 0.*" userControlGlobalOnlyPolkitConfig - == null; - assert pkgs.lib.hasInfix "unit === \"zapret-discord-youtube.service\"" - userControlGlobalOnlyPolkitConfig; - true - ) - - # -- userControl: per-app-only rule covers per-app-scoped helpers only -- - ( - assert userControlPerAppOnlyFixture.config.users.groups ? "proxy-suite"; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") === 0" - userControlPerAppOnlyPolkitConfig; - assert - builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) !== 0.*" userControlPerAppOnlyPolkitConfig - == null; - assert - builtins.match ".*unit === \"zapret-discord-youtube\\.service\".*" userControlPerAppOnlyPolkitConfig - == null; - true - ) - - # -- userControl: disabling both scopes removes group and polkit wiring -- - ( - assert !(userControlDisabledFixture.config.users.groups ? "proxy-suite"); - assert !userControlDisabledFixture.config.security.polkit.enable; - assert - builtins.match ".*subject\\.isInGroup\\(\"proxy-suite\"\\).*" userControlDisabledFixture.config.security.polkit.extraConfig - == null; - assert - builtins.match ".*org\\.freedesktop\\.systemd1\\.manage-units.*" userControlDisabledFixture.config.security.polkit.extraConfig - == null; - true - ) - - # -- perAppRouting: app TProxy helper installs socket cgroup mark rules -- - ( - assert pkgs.lib.hasInfix "socket cgroupv2" perAppRoutingTproxyUserStartScript; - assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTproxyUserStartScript; - assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTproxyUserStartScript; - true - ) - - # -- perAppRouting: app TProxy startup installs nftables and loopback policy route -- - ( - assert pkgs.lib.hasInfix "proxy_suite_per_app_tproxy" perAppRoutingTproxyStartScript; - assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStartScript; - assert pkgs.lib.hasInfix "route replace local default dev lo table 102" - perAppRoutingTproxyStartScript; - assert pkgs.lib.hasInfix "rule add fwmark 17 table 102" perAppRoutingTproxyStartScript; - assert pkgs.lib.hasInfix "set +e" perAppRoutingTproxyStopScript; - assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStopScript; - true - ) - - # -- perAppRouting: app zapret helper installs socket cgroup bitwise mark rules -- - ( - assert pkgs.lib.hasInfix "socket cgroupv2" perAppRoutingZapretUserStartScript; - assert pkgs.lib.hasInfix "meta mark set meta mark or 268435456" perAppRoutingZapretUserStartScript; - assert pkgs.lib.hasInfix "ct mark set ct mark or 268435456" perAppRoutingZapretUserStartScript; - true - ) - - # -- perAppRouting: app zapret startup installs nftables backend -- - ( - assert pkgs.lib.hasInfix "proxy_suite_per_app_zapret_mark" perAppRoutingZapretStartScript; - true - ) - - # -- perAppRouting: global zapret config keeps FILTER_MARK disabled -- - ( - assert pkgs.lib.hasInfix "FILTER_MARK=" perAppRoutingZapretConfig; - assert builtins.match ".*FILTER_MARK=0x10000000.*" perAppRoutingZapretConfig == null; - true - ) - - # -- perAppRouting: app zapret config is a separate instance with its own filter/qnum/marks -- - ( - assert pkgs.lib.hasInfix "FILTER_MARK=0x10000000" perAppRoutingPerAppZapretConfig; - assert pkgs.lib.hasInfix "MODE_FILTER=none" perAppRoutingPerAppZapretConfig; - assert pkgs.lib.hasInfix "QNUM=201" perAppRoutingPerAppZapretConfig; - assert pkgs.lib.hasInfix "DESYNC_MARK=0x8000000" perAppRoutingPerAppZapretConfig; - assert pkgs.lib.hasInfix "DESYNC_MARK_POSTNAT=0x4000000" perAppRoutingPerAppZapretConfig; - assert pkgs.lib.hasInfix "ZAPRET_NFT_TABLE=proxy_suite_per_app_zapret" - perAppRoutingPerAppZapretConfig; - true - ) - ( - assert pkgs.lib.hasInfix "FILTER_MARK=0x10000000" perAppRoutingZapretWithoutGlobalPerAppConfig; - assert pkgs.lib.hasInfix "QNUM=201" perAppRoutingZapretWithoutGlobalPerAppConfig; - true - ) - - # -- perAppRouting: global zapret installs a bypass hook for app-marked traffic -- - ( - assert pkgs.lib.hasInfix "proxy-suite per-app-zapret bypass" perAppRoutingZapretGlobalCustomScript; - assert pkgs.lib.hasInfix "mark and 268435456 != 0 return" perAppRoutingZapretGlobalCustomScript; - true - ) - - # -- perAppRouting: route=proxychains requires proxychains.enable -- - ( - assert perAppRoutingProxychainsWithoutEnable.success == false; - true - ) - - # -- perAppRouting: proxychains requires proxy.enable -- - ( - assert perAppRoutingProxychainsWithoutProxy.success == false; - true - ) - - # -- perAppRouting: profiles require perAppRouting.enable -- - ( - assert perAppRoutingProfilesWithoutEnable.success == false; - true - ) - - # -- perAppRouting: default proxychains profile still requires proxychains.enable -- - ( - assert perAppRoutingDefaultProfilesWithoutProxychainsEnable.success == false; - true - ) - - # -- perAppRouting: route=tun requires proxy.tun.perApp.enable -- - ( - assert perAppRoutingTunWithoutEnable.success == false; - true - ) - - # -- perAppRouting: app TUN backend requires proxy.enable -- - ( - assert perAppRoutingTunBackendWithoutProxy.success == false; - assert perAppRoutingTunProfileWithoutProxy.success == false; - true - ) - - # -- perAppRouting: route=tproxy requires proxy.tproxy.perApp.enable -- - ( - assert perAppRoutingTproxyWithoutEnable.success == false; - true - ) - - # -- perAppRouting: app TProxy backend requires proxy.enable -- - ( - assert perAppRoutingTproxyBackendWithoutProxy.success == false; - assert perAppRoutingTproxyProfileWithoutProxy.success == false; - true - ) - - # -- perAppRouting: route=zapret requires zapret.perApp.enable -- - ( - assert perAppRoutingZapretWithoutEnable.success == false; - true - ) - - # -- perAppRouting: profile names must be unique -- - ( - assert duplicatePerAppRoutingProfiles.success == false; - true - ) - - # -- perAppRouting: with TProxy enabled, app TUN fwmark must differ from proxyMark -- - ( - assert perAppRoutingTunFwmarkCollision.success == false; - true - ) - - # -- perAppRouting: app TProxy fwmark must differ from proxy.tproxy.proxyMark -- - ( - assert perAppRoutingTproxyFwmarkCollision.success == false; - true - ) - - # -- perAppRouting: app TUN and app TProxy fwmarks must differ -- - ( - assert perAppRoutingTunTproxyFwmarkCollision.success == false; - true - ) - - # -- perAppRouting: app TUN and app TProxy route tables must differ -- - ( - assert perAppRoutingTunTproxyRouteTableCollision.success == false; - true - ) - - # -- perAppRouting: app zapret filter mark must differ from proxy.tproxy.proxyMark -- - ( - assert perAppRoutingZapretFilterMarkCollision.success == false; - true - ) - - # -- perAppRouting: app TProxy and app zapret marks must differ -- - ( - assert perAppRoutingTproxyZapretMarkCollision.success == false; - true - ) - - # -- subscription: no outbounds + no subscriptions fails -- - ( - assert noProxyBackendDefaultFixture.config.services.proxy-suite.proxy.enable == false; - assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks"); - assert noOutboundsNoSubscriptions.success == false; - true - ) - - # -- urlTest: custom url/interval/tolerance propagate to start script -- - ( - let - startScript = - urlTestCustomFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; - scriptText = builtins.readFile startScript; - in - assert builtins.match ".*telegram\\.org.*" scriptText != null; - assert builtins.match ".*1m.*" scriptText != null; - assert builtins.match ".*100.*" scriptText != null; - true - ) - - # -- urlTest: defaults are sane -- - ( - let - cfg = minimal.config.services.proxy-suite.proxy.urlTest; - in - assert cfg.url == "https://www.gstatic.com/generate_204"; - assert cfg.interval == "3m"; - assert minimal.config.services.proxy-suite.proxy.singBox.urlTest.tolerance == 50; - true - ) - ]; + moduleSuiteChecks = import ./checks/module-suite.nix { inherit pkgs checkLib; }; in -{ - proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); +moduleSuiteChecks +// { proxy-suite-tray-build = suitePkgs.proxy-suite-tray; - xray-jq-filter-runtime = xrayJqFilterRuntimeCheck; - - zapret-hostlist-rules = pkgs.runCommand "proxy-suite-zapret-hostlist-rules-check" { } '' - grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-twitter.txt"' "${zapretSyncExtraListsBase}/config" - grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-instagram.txt"' "${zapretSyncExtraListsBase}/config" - grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-soundcloud.txt"' "${zapretSyncExtraListsBase}/config" - ! grep -F -- '--hostlist="${zapretSyncBase}/hostlists/list-twitter.txt"' "${zapretSyncBase}/config" - ! grep -F -- '--hostlist="${zapretSyncBase}/hostlists/list-instagram.txt"' "${zapretSyncBase}/config" - ! grep -F -- '--hostlist="${zapretSyncBase}/hostlists/list-soundcloud.txt"' "${zapretSyncBase}/config" - test -f "${zapretSpacedConfigAliasBase}/config" - test -f "${zapretUnspacedConfigAliasBase}/config" - ! grep -F -- '--hostlist="${zapretSyncNoExtraListsBase}/hostlists/list-twitter.txt"' "${zapretSyncNoExtraListsBase}/config" - ! grep -F -- '--hostlist="${zapretSyncNoExtraListsBase}/hostlists/list-instagram.txt"' "${zapretSyncNoExtraListsBase}/config" - ! grep -F -- '--hostlist="${zapretSyncNoExtraListsBase}/hostlists/list-soundcloud.txt"' "${zapretSyncNoExtraListsBase}/config" - grep -F 'googlevideo.com' "${zapretHostlistBase}/hostlists/list-googlevideo.txt" - grep -F 'example.de' "${zapretHostlistBase}/hostlists/list-example.txt" - grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-googlevideo.txt"' "${zapretHostlistBase}/config" - grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-example.txt"' "${zapretHostlistBase}/config" - grep -F -- '--filter-tcp=443 --dpi-desync=fake,multisplit --hostlist="${zapretHostlistBase}/hostlists/list-example.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude-user.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude-user.txt" --new' "${zapretHostlistBase}/config" - grep -F 'youtube.com' "${zapretHostlistBase}/hostlists/list-google-general.txt" - grep -F 'googlevideo.com' "${zapretHostlistBase}/hostlists/list-google-general.txt" - grep -F 'discord.com' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" - grep -F 'discord.gg' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" - grep -F 'cloudflare-ech.com' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" - grep -F 'cloudfront.net' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" - grep -F '7tv.app' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" - cmp "${zapretHostlistBase}/hostlists/list-google-general.txt" "${zapretHostlistBase}/hostlists/list-youtube-alias.txt" - cmp "${zapretHostlistBase}/hostlists/list-general-alt12.txt" "${zapretHostlistBase}/hostlists/list-discord-alias.txt" - grep -F '1.1.1.0/24' "${zapretHostlistBase}/hostlists/ipset-upstream-ips.txt" - grep -F '203.0.113.0/24' "${zapretHostlistBase}/hostlists/ipset-explicit-ips.txt" - grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-google-general.txt"' "${zapretHostlistBase}/config" - grep -F -- '--dpi-desync=multisplit --dpi-desync-split-seqovl=681' "${zapretHostlistBase}/config" - grep -F -- '--ipset="${zapretHostlistBase}/hostlists/ipset-upstream-ips.txt"' "${zapretHostlistBase}/config" - grep -F -- '--ipset="${zapretHostlistBase}/hostlists/ipset-explicit-ips.txt"' "${zapretHostlistBase}/config" - google_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-google-general.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) - default_google_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-google.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) - general_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-general-alt12.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) - default_general_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-general.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) - discord_voice_rule_line=$(grep -nF -- '--filter-l7=discord,stun' "${zapretHostlistBase}/config" | grep -F -- '--dpi-desync-repeats=3' | head -n1 | cut -d: -f1) - default_voice_rule_line=$(grep -nF -- '--filter-l7=discord,stun' "${zapretHostlistBase}/config" | grep -F -- '--dpi-desync-repeats=6' | head -n1 | cut -d: -f1) - test "$google_rule_line" -lt "$default_google_rule_line" - test "$general_rule_line" -lt "$default_general_rule_line" - test "$discord_voice_rule_line" -lt "$default_voice_rule_line" - touch "$out" - ''; } // parserChecks // repoChecks diff --git a/nix/checks/core-proxy.nix b/nix/checks/core-proxy.nix new file mode 100644 index 0000000..10d9ab1 --- /dev/null +++ b/nix/checks/core-proxy.nix @@ -0,0 +1,82 @@ +{ + pkgs, + evalProxySuite, + baseModule, + minimal, + mkRoutingRules, + mkTProxyConfig, + hasRuleSet, + dnsHasRuleSet, + dnsServerByTag, + mkBadFixtureRaw, + mkFailingAssertions, +}: + +let + fixtures = import ./core-proxy/fixtures.nix { + inherit + pkgs + evalProxySuite + baseModule + minimal + mkRoutingRules + mkTProxyConfig + mkBadFixtureRaw + mkFailingAssertions + ; + }; + inherit (fixtures) + customSingBoxPackageBin + customSingBoxPackageStartScript + ruDefaultRules + ruDefaultConfig + ruDisabledRules + ruDisabledConfig + ruExplicitConfig + dnsLocalOverrideConfig + dnsRemoteOverrideConfig + proxyDirectConfig + urlTestCustomStartScript + noProxyBackendDefaultFixture + invalidCoreProxyAssertions + blockGeoRules + routingOrDomainRules + routingOrGeoIPRules + ; + + routingDnsChecks = import ./core-proxy/routing-dns.nix { + inherit + hasRuleSet + dnsHasRuleSet + dnsServerByTag + ruDefaultRules + ruDefaultConfig + ruDisabledRules + ruDisabledConfig + ruExplicitConfig + dnsLocalOverrideConfig + dnsRemoteOverrideConfig + blockGeoRules + routingOrDomainRules + routingOrGeoIPRules + ; + }; + serviceDefaultChecks = import ./core-proxy/service-defaults.nix { + inherit + pkgs + minimal + customSingBoxPackageBin + customSingBoxPackageStartScript + proxyDirectConfig + ruDefaultConfig + urlTestCustomStartScript + noProxyBackendDefaultFixture + invalidCoreProxyAssertions + ; + }; +in +{ + inherit ruDefaultConfig; + + assertions = routingDnsChecks.assertions ++ serviceDefaultChecks.assertions; +} diff --git a/nix/checks/core-proxy/fixtures.nix b/nix/checks/core-proxy/fixtures.nix new file mode 100644 index 0000000..2e9afef --- /dev/null +++ b/nix/checks/core-proxy/fixtures.nix @@ -0,0 +1,196 @@ +{ + pkgs, + evalProxySuite, + baseModule, + minimal, + mkRoutingRules, + mkTProxyConfig, + mkBadFixtureRaw, + mkFailingAssertions, +}: + +let + generated = import ../read-generated.nix; + + customSingBoxPackage = pkgs.writeShellScriptBin "sing-box" '' + exit 0 + ''; + customSingBoxPackageFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.singBox.package = customSingBoxPackage; + } + ]; + customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box"; + customSingBoxPackageStartScript = generated.readDerivation ( + customSingBoxPackageFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + routingOrFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + routing.rules = [ + { + outbound = "primary"; + domains = [ "example.com" ]; + geoips = [ "us" ]; + } + ]; + }; + }; + } + ]; + + ruDefaultRules = mkRoutingRules minimal; + ruDefaultConfig = mkTProxyConfig minimal; + + ruDisabledFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.routing.enableRuDirect = false; + } + ]; + ruDisabledRules = mkRoutingRules ruDisabledFixture; + ruDisabledConfig = mkTProxyConfig ruDisabledFixture; + + ruExplicitConfig = mkTProxyConfig (evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.routing = { + enableRuDirect = false; + direct.geosites = [ "category-ru" ]; + }; + } + ]); + + dnsLocalOverrideConfig = mkTProxyConfig (evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.dns.local = { + type = "tcp"; + address = "9.9.9.9"; + port = 5353; + }; + } + ]); + + dnsRemoteOverrideConfig = mkTProxyConfig (evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.dns.remote = { + type = "tls"; + address = "1.0.0.1"; + port = 853; + }; + } + ]); + + proxyDirectConfig = mkTProxyConfig (evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.proxyByDefault = false; + } + ]); + + urlTestCustomFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "test-proxy"; + url = "http://proxy.example.com:8080"; + } + ]; + selection = "urltest"; + urlTest = { + url = "https://telegram.org"; + interval = "1m"; + }; + singBox.urlTest.tolerance = 100; + }; + }; + } + ]; + urlTestCustomStartScript = generated.readDerivation ( + urlTestCustomFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + noProxyBackendDefaultFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite.enable = true; + } + ]; + + invalidCoreProxyAssertions = mkFailingAssertions mkBadFixtureRaw [ + [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + }; + }; + } + ] + ]; + + blockGeoRules = mkRoutingRules (evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.routing.block = { + geosites = [ "category-ads-all" ]; + geoips = [ "cn" ]; + }; + } + ]); + + routingOrRules = mkRoutingRules routingOrFixture; + + routingOrDomainRules = builtins.filter ( + rule: (rule ? domain_suffix) && rule.domain_suffix == [ "example.com" ] + ) routingOrRules; + + routingOrGeoIPRules = builtins.filter ( + rule: (rule ? rule_set) && rule.rule_set == [ "geoip-us" ] + ) routingOrRules; +in +{ + inherit + customSingBoxPackageBin + customSingBoxPackageStartScript + ruDefaultRules + ruDefaultConfig + ruDisabledRules + ruDisabledConfig + ruExplicitConfig + dnsLocalOverrideConfig + dnsRemoteOverrideConfig + proxyDirectConfig + urlTestCustomFixture + urlTestCustomStartScript + noProxyBackendDefaultFixture + invalidCoreProxyAssertions + blockGeoRules + routingOrDomainRules + routingOrGeoIPRules + ; +} diff --git a/nix/checks/core-proxy/routing-dns.nix b/nix/checks/core-proxy/routing-dns.nix new file mode 100644 index 0000000..3c093b6 --- /dev/null +++ b/nix/checks/core-proxy/routing-dns.nix @@ -0,0 +1,114 @@ +{ + hasRuleSet, + dnsHasRuleSet, + dnsServerByTag, + ruDefaultRules, + ruDefaultConfig, + ruDisabledRules, + ruDisabledConfig, + ruExplicitConfig, + dnsLocalOverrideConfig, + dnsRemoteOverrideConfig, + blockGeoRules, + routingOrDomainRules, + routingOrGeoIPRules, +}: + +{ + assertions = [ + # -- routing rule entries with domains and geoips preserve both matchers -- + ( + assert builtins.length routingOrDomainRules == 1; + true + ) + ( + assert builtins.length routingOrGeoIPRules == 1; + true + ) + ( + assert (builtins.head routingOrDomainRules).outbound == "proxy"; + true + ) + ( + assert (builtins.head routingOrGeoIPRules).outbound == "proxy"; + true + ) + + # -- default RU direct route and DNS rules are generated -- + ( + let + localDns = dnsServerByTag ruDefaultConfig "local"; + remoteDns = dnsServerByTag ruDefaultConfig "remote"; + in + assert localDns.type == "udp"; + assert localDns.server == "1.1.1.1"; + assert localDns.server_port == 53; + assert !(localDns ? detour); + assert remoteDns.type == "udp"; + assert remoteDns.server == "1.1.1.1"; + assert remoteDns.server_port == 53; + assert remoteDns.detour == "proxy"; + true + ) + ( + assert hasRuleSet ruDefaultRules "direct" "geosite-category-ru"; + true + ) + ( + assert hasRuleSet ruDefaultRules "direct" "geoip-ru"; + true + ) + ( + assert dnsHasRuleSet ruDefaultConfig.dns.rules "geosite-category-ru"; + true + ) + ( + assert !(hasRuleSet ruDisabledRules "direct" "geosite-category-ru"); + true + ) + ( + assert !(hasRuleSet ruDisabledRules "direct" "geoip-ru"); + true + ) + ( + assert !(dnsHasRuleSet ruDisabledConfig.dns.rules "geosite-category-ru"); + true + ) + ( + assert dnsHasRuleSet ruExplicitConfig.dns.rules "geosite-category-ru"; + true + ) + + # -- DNS overrides map to sing-box server entries -- + ( + let + localDns = dnsServerByTag dnsLocalOverrideConfig "local"; + in + assert localDns.type == "tcp"; + assert localDns.server == "9.9.9.9"; + assert localDns.server_port == 5353; + assert !(localDns ? detour); + true + ) + ( + let + remoteDns = dnsServerByTag dnsRemoteOverrideConfig "remote"; + in + assert remoteDns.type == "tls"; + assert remoteDns.server == "1.0.0.1"; + assert remoteDns.server_port == 853; + assert remoteDns.detour == "proxy"; + true + ) + + # -- block route geosite and geoip sets are emitted -- + ( + assert hasRuleSet blockGeoRules "block" "geosite-category-ads-all"; + true + ) + ( + assert hasRuleSet blockGeoRules "block" "geoip-cn"; + true + ) + ]; +} diff --git a/nix/checks/core-proxy/service-defaults.nix b/nix/checks/core-proxy/service-defaults.nix new file mode 100644 index 0000000..85986fe --- /dev/null +++ b/nix/checks/core-proxy/service-defaults.nix @@ -0,0 +1,58 @@ +{ + pkgs, + minimal, + customSingBoxPackageBin, + customSingBoxPackageStartScript, + proxyDirectConfig, + ruDefaultConfig, + urlTestCustomStartScript, + noProxyBackendDefaultFixture, + invalidCoreProxyAssertions, +}: + +{ + assertions = [ + # -- sing-box package override propagates into generated service scripts -- + ( + assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript; + true + ) + + # -- proxy defaults and urltest settings are applied -- + ( + assert proxyDirectConfig.dns.final == "local"; + true + ) + ( + assert ruDefaultConfig.dns.final == "remote"; + true + ) + ( + assert ruDefaultConfig.route.default_domain_resolver == "local"; + true + ) + ( + assert builtins.match ".*telegram\\.org.*" urlTestCustomStartScript != null; + assert builtins.match ".*1m.*" urlTestCustomStartScript != null; + assert builtins.match ".*100.*" urlTestCustomStartScript != null; + true + ) + ( + let + cfg = minimal.config.services.proxy-suite.proxy.urlTest; + in + assert cfg.url == "https://www.gstatic.com/generate_204"; + assert cfg.interval == "3m"; + assert minimal.config.services.proxy-suite.proxy.singBox.urlTest.tolerance == 50; + true + ) + + # -- proxy backend defaults and required inputs are enforced -- + ( + assert noProxyBackendDefaultFixture.config.services.proxy-suite.proxy.enable == false; + assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks"); + true + ) + ] + ++ invalidCoreProxyAssertions; +} diff --git a/nix/checks/global-proxy-modes.nix b/nix/checks/global-proxy-modes.nix new file mode 100644 index 0000000..4eef149 --- /dev/null +++ b/nix/checks/global-proxy-modes.nix @@ -0,0 +1,120 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkBadFixture, + mkFailingAssertions, + mkTunConfig, + dnsServerByTag, + checkConstants, +}: + +let + fixtures = import ./global-proxy-modes/fixtures.nix { + inherit + evalProxySuite + baseModule + mkBadFixture + mkFailingAssertions + mkTunConfig + ; + }; + + inherit (fixtures) + invalidGlobalProxyModeAssertions + tproxyAutostartFixture + tproxyManualFixture + tproxyManualStartScript + tproxyManualStopScript + tproxyWithFirewall + tunAutostartFixture + tunCleanupScript + tunDefaultConfig + tunManualFixture + tunServiceConfig + ; +in +{ + assertions = [ + ( + assert tproxyWithFirewall.config.networking.firewall.enable; + true + ) + ( + assert tproxyManualFixture.config.services.proxy-suite.proxy.tproxy.autostart == false; + assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ]; + true + ) + ( + assert + tproxyAutostartFixture.config.systemd.services."proxy-suite-tproxy".wantedBy + == [ "multi-user.target" ]; + true + ) + ( + assert pkgs.lib.hasInfix "set -euo pipefail" tproxyManualStartScript; + assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStartScript; + assert pkgs.lib.hasInfix "route replace local default dev lo table 100" tproxyManualStartScript; + assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript; + assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript; + true + ) + ( + assert tunManualFixture.config.services.proxy-suite.proxy.tun.autostart == false; + assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ]; + true + ) + ( + let + inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds); + in + assert inbound.iproute2_table_index == checkConstants.tunAutoRouteTableIndex; + assert inbound.iproute2_rule_index == checkConstants.tunAutoRouteRulePriority; + assert tunDefaultConfig.route.auto_detect_interface == true; + true + ) + ( + assert tunManualFixture.config.networking.nftables.enable; + true + ) + ( + assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost; + assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript; + assert pkgs.lib.hasInfix "rule del table ${toString checkConstants.tunAutoRouteTableIndex}" + tunCleanupScript; + assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority}" + tunCleanupScript; + assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTunRulePriority}" + tunCleanupScript; + assert pkgs.lib.hasInfix "route flush table ${toString checkConstants.tunAutoRouteTableIndex}" + tunCleanupScript; + assert pkgs.lib.hasInfix "link del dev" tunCleanupScript; + assert pkgs.lib.hasInfix "singtun0" tunCleanupScript; + true + ) + ( + assert + tunAutostartFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ "multi-user.target" ]; + true + ) + ( + let + localDns = dnsServerByTag tunDefaultConfig "local"; + in + assert !(localDns ? detour); + true + ) + ( + assert tunDefaultConfig.route.default_domain_resolver == "local"; + true + ) + ( + assert builtins.elem "network-online.target" + tunManualFixture.config.systemd.services."proxy-suite-tun".after; + assert builtins.elem "network-online.target" + tunManualFixture.config.systemd.services."proxy-suite-tun".wants; + true + ) + ] + ++ invalidGlobalProxyModeAssertions; +} diff --git a/nix/checks/global-proxy-modes/fixtures.nix b/nix/checks/global-proxy-modes/fixtures.nix new file mode 100644 index 0000000..e056ca3 --- /dev/null +++ b/nix/checks/global-proxy-modes/fixtures.nix @@ -0,0 +1,125 @@ +{ + evalProxySuite, + baseModule, + mkBadFixture, + mkFailingAssertions, + mkTunConfig, +}: + +let + generated = import ../read-generated.nix; + + tproxyWithFirewall = evalProxySuite [ + { + system.stateVersion = "26.05"; + networking.firewall.enable = true; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + tproxy.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + }; + } + ]; + + tproxyManualFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.tproxy.enable = true; + } + ]; + tproxyManualServiceConfig = + tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig; + tproxyManualStartScript = generated.readDerivation tproxyManualServiceConfig.ExecStart; + tproxyManualStopScript = generated.readDerivation tproxyManualServiceConfig.ExecStop; + + tproxyAutostartFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.tproxy = { + enable = true; + autostart = true; + }; + } + ]; + + tunManualFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.tun.enable = true; + } + ]; + + tunAutostartFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.tun = { + enable = true; + autostart = true; + }; + } + ]; + + invalidGlobalProxyModeAssertions = mkFailingAssertions mkBadFixture [ + # TUN and TProxy cannot both autostart globally. + [ + { + services.proxy-suite.proxy = { + tproxy = { + enable = true; + autostart = true; + }; + tun = { + enable = true; + autostart = true; + }; + }; + } + ] + + # Transparent proxy backends require proxy.enable. + [ + { + services.proxy-suite.proxy = { + enable = false; + tun.enable = true; + }; + } + ] + [ + { + services.proxy-suite.proxy = { + enable = false; + tproxy.enable = true; + }; + } + ] + ]; + + tunDefaultConfig = mkTunConfig tunManualFixture; + tunServiceConfig = tunManualFixture.config.systemd.services."proxy-suite-tun".serviceConfig; + tunCleanupScript = generated.readDerivation tunServiceConfig.ExecStopPost; +in +{ + inherit + invalidGlobalProxyModeAssertions + tproxyAutostartFixture + tproxyManualFixture + tproxyManualStartScript + tproxyManualStopScript + tproxyWithFirewall + tunAutostartFixture + tunCleanupScript + tunDefaultConfig + tunManualFixture + tunServiceConfig + ; +} diff --git a/nix/checks/hybrid-backend.nix b/nix/checks/hybrid-backend.nix new file mode 100644 index 0000000..3a7d9bb --- /dev/null +++ b/nix/checks/hybrid-backend.nix @@ -0,0 +1,111 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkTunConfig, + shellValueByPrefix, + checkConstants, +}: + +let + fixtures = import ./hybrid-backend/fixtures.nix { + inherit + evalProxySuite + mkTProxyConfig + mkTunConfig + shellValueByPrefix + ; + }; + + inherit (fixtures) + hybridBackendJqFilter + hybridFixture + hybridPerAppTunStartScript + hybridStartScript + hybridSubscriptionStartScript + hybridSubscriptionUpdateScript + hybridTproxyConfig + hybridTunConfig + hybridTunStartScript + hybridXrayRawStartScript + ; +in +{ + assertions = [ + # -- hybrid backend: sing-box frontend with XRay loopback sidecar -- + ( + let + dnsBridgeInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "xray-dns-in") hybridTproxyConfig.inbounds + ); + mixedInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "mixed-in") hybridTproxyConfig.inbounds + ); + tproxyInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "tproxy-in") hybridTproxyConfig.inbounds + ); + tunDnsBridgeInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "xray-dns-in") hybridTunConfig.inbounds + ); + dnsBridgeRouteRule = builtins.head ( + builtins.filter ( + rule: + (rule.action or "") == "hijack-dns" && (rule ? inbound) && builtins.elem "xray-dns-in" rule.inbound + ) hybridTproxyConfig.route.rules + ); + in + assert hybridFixture.config.services.proxy-suite.proxy.singBox.enable; + assert hybridFixture.config.services.proxy-suite.proxy.xray.enable; + assert hybridTproxyConfig ? route; + assert !(hybridTproxyConfig ? routing); + assert dnsBridgeInbound.type == "direct"; + assert dnsBridgeInbound.listen == "127.0.0.1"; + assert dnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.socks; + assert mixedInbound.type == "mixed"; + assert tproxyInbound.type == "tproxy"; + assert tunDnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.tun; + assert + dnsBridgeRouteRule.network == [ + "tcp" + "udp" + ]; + assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript; + assert pkgs.lib.hasInfix "/bin/xray run -c" hybridStartScript; + assert pkgs.lib.hasInfix "xray-sidecar.json" hybridStartScript; + assert pkgs.lib.hasInfix + "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}" + hybridStartScript; + assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}" + hybridStartScript; + assert pkgs.lib.hasInfix + "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}" + hybridTunStartScript; + assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}" + hybridTunStartScript; + assert pkgs.lib.hasInfix + "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.perAppTun}" + hybridPerAppTunStartScript; + assert pkgs.lib.hasInfix + "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}" + hybridPerAppTunStartScript; + assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript; + assert pkgs.lib.hasInfix "--backend xray" hybridStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript; + assert pkgs.lib.hasInfix "hybrid XRay json sidecar" hybridXrayRawStartScript; + assert pkgs.lib.hasInfix ''{type:"socks",tag:$tag,server:"127.0.0.1"'' hybridXrayRawStartScript; + assert pkgs.lib.hasInfix "udp:true" hybridXrayRawStartScript; + assert pkgs.lib.hasInfix "routing_mark:2" hybridXrayRawStartScript; + assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter; + assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter; + assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionStartScript; + assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionUpdateScript; + assert pkgs.lib.hasInfix + ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' + hybridSubscriptionStartScript; + assert pkgs.lib.hasInfix ".singBox" hybridSubscriptionStartScript; + assert pkgs.lib.hasInfix ".xray[]" hybridSubscriptionStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridSubscriptionStartScript; + true + ) + ]; +} diff --git a/nix/checks/hybrid-backend/fixtures.nix b/nix/checks/hybrid-backend/fixtures.nix new file mode 100644 index 0000000..d95ecb0 --- /dev/null +++ b/nix/checks/hybrid-backend/fixtures.nix @@ -0,0 +1,121 @@ +{ + evalProxySuite, + mkTProxyConfig, + mkTunConfig, + shellValueByPrefix, +}: + +let + generated = import ../read-generated.nix; + + hybridModule = { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + xray.enable = true; + selection = "selector"; + outbounds = [ + { + tag = "primary"; + url = "vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"; + } + { + tag = "xray-only"; + url = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"; + } + ]; + tproxy.enable = true; + tun.enable = true; + tun.perApp.enable = true; + }; + }; + }; + hybridFixture = evalProxySuite [ hybridModule ]; + hybridTproxyConfig = mkTProxyConfig hybridFixture; + hybridTunConfig = mkTunConfig hybridFixture; + hybridStartScript = generated.readDerivation ( + hybridFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + hybridTunStartScript = generated.readDerivation ( + hybridFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart + ); + hybridPerAppTunStartScript = generated.readDerivation ( + hybridFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart + ); + hybridBackendJqFilter = + import ../../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix + { + pureXrayEnabled = false; + selectionMode = hybridFixture.config.services.proxy-suite.proxy.selection; + }; + + hybridXrayRawFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + xray.enable = true; + outbounds = [ + { + tag = "raw-xray"; + xrayJson = { + protocol = "freedom"; + settings = { }; + }; + } + ]; + }; + }; + } + ]; + hybridXrayRawStartScript = generated.readDerivation ( + hybridXrayRawFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + hybridSubscriptionFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + xray.enable = true; + subscriptions = [ + { + tag = "community"; + url = "https://example.com/hybrid-sub"; + } + ]; + selection = "selector"; + }; + }; + } + ]; + hybridSubscriptionStartScript = generated.readDerivation ( + hybridSubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + hybridSubscriptionUpdateScript = generated.readDerivation ( + hybridSubscriptionFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart + ); +in +{ + inherit + hybridBackendJqFilter + hybridFixture + hybridPerAppTunStartScript + hybridStartScript + hybridSubscriptionStartScript + hybridSubscriptionUpdateScript + hybridTproxyConfig + hybridTunConfig + hybridTunStartScript + hybridXrayRawStartScript + ; +} diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix new file mode 100644 index 0000000..b6cc777 --- /dev/null +++ b/nix/checks/lib.nix @@ -0,0 +1,252 @@ +{ + pkgs, + system, + nixpkgs, + proxySuiteModule, + zapret, +}: + +let + generated = import ./read-generated.nix; + + evalProxySuite = + modules: + import "${nixpkgs}/nixos/lib/eval-config.nix" { + inherit system; + modules = [ proxySuiteModule ] ++ modules; + }; + forceEval = value: builtins.tryEval (builtins.deepSeq value true); + rg = "${pkgs.ripgrep}/bin/rg"; + mkRouting = + fixture: + let + cfg = fixture.config.services.proxy-suite; + in + import ../../modules/proxy-suite/rules.nix { + lib = pkgs.lib; + inherit pkgs cfg zapret; + }; + mkRoutingRules = fixture: (mkRouting fixture).routingRules; + mkRouteModeRules = fixture: (mkRouting fixture).routeModeRules; + mkProxyConfig = + fixture: configAttr: + let + cfg = fixture.config.services.proxy-suite; + rules = mkRouting fixture; + configs = import ../../modules/proxy-suite/config.nix { + lib = pkgs.lib; + inherit pkgs cfg rules; + }; + in + builtins.fromJSON ( + builtins.unsafeDiscardStringContext (generated.readDerivation configs.${configAttr}) + ); + mkTProxyConfig = fixture: mkProxyConfig fixture "tproxyFile"; + mkTunConfig = fixture: mkProxyConfig fixture "tunFile"; + mkPerAppTunConfig = fixture: mkProxyConfig fixture "perAppTunFile"; + mkTProxyNftRules = + fixture: + let + cfg = fixture.config.services.proxy-suite; + nftr = import ../../modules/proxy-suite/nftables.nix { + lib = pkgs.lib; + inherit pkgs cfg; + }; + in + generated.readDerivation nftr.nftablesRulesFile; + mkPerAppZapretNftRules = + fixture: + let + cfg = fixture.config.services.proxy-suite; + nftr = import ../../modules/proxy-suite/nftables.nix { + lib = pkgs.lib; + inherit pkgs cfg; + }; + in + generated.readDerivation nftr.perAppZapretRulesFile; + mkPerAppUserRules = + fixture: + let + cfg = fixture.config.services.proxy-suite; + derived = import ../../modules/proxy-suite/derived.nix { + lib = pkgs.lib; + inherit cfg; + }; + nftr = import ../../modules/proxy-suite/nftables.nix { + lib = pkgs.lib; + inherit pkgs cfg; + }; + in + import ../../modules/proxy-suite/service/per-app-routing/user-rules.nix { + lib = pkgs.lib; + inherit pkgs; + inherit (derived) + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg + ; + perAppTunSliceName = "proxy-suite-per-app-tun.slice"; + perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; + perAppZapretSliceName = "proxy-suite-per-app-zapret.slice"; + inherit (nftr) nft; + awk = "${pkgs.gawk}/bin/awk"; + grepBin = "${pkgs.gnugrep}/bin/grep"; + findBin = "${pkgs.findutils}/bin/find"; + headBin = "${pkgs.coreutils}/bin/head"; + }; + hasDirectDomain = + rules: domain: + builtins.any ( + rule: (rule ? domain_suffix) && rule.outbound == "direct" && builtins.elem domain rule.domain_suffix + ) rules; + hasDirectIP = + rules: cidr: + builtins.any ( + rule: (rule ? ip_cidr) && rule.outbound == "direct" && builtins.elem cidr rule.ip_cidr + ) rules; + hasRuleSet = + rules: outbound: ruleSet: + builtins.any ( + rule: (rule ? rule_set) && rule.outbound == outbound && builtins.elem ruleSet rule.rule_set + ) rules; + dnsHasRuleSet = + dnsRules: ruleSet: + builtins.any (rule: (rule ? rule_set) && builtins.elem ruleSet rule.rule_set) dnsRules; + dnsServerByTag = + dnsConfig: tag: builtins.head (builtins.filter (server: server.tag == tag) dnsConfig.dns.servers); + mkZapretBaseFor = + fixture: serviceName: + let + env = fixture.config.systemd.services.${serviceName}.serviceConfig.Environment; + zapretBaseEnv = builtins.head ( + builtins.filter (value: pkgs.lib.hasPrefix "ZAPRET_BASE=" value) env + ); + in + pkgs.lib.removePrefix "ZAPRET_BASE=" zapretBaseEnv; + mkZapretBase = fixture: mkZapretBaseFor fixture "zapret-discord-youtube"; + packagePathMatches = + packages: pattern: + builtins.any ( + pkg: builtins.match pattern (builtins.unsafeDiscardStringContext (toString pkg)) != null + ) packages; + packageByPattern = + packages: pattern: + builtins.head ( + builtins.filter ( + pkg: builtins.match pattern (builtins.unsafeDiscardStringContext (toString pkg)) != null + ) packages + ); + lineByPrefix = + text: prefix: + builtins.head ( + builtins.filter (line: pkgs.lib.hasPrefix prefix line) (pkgs.lib.splitString "\n" text) + ); + lineContaining = + text: infix: + builtins.head ( + builtins.filter (line: pkgs.lib.hasInfix infix line) (pkgs.lib.splitString "\n" text) + ); + shellValueByPrefix = + text: prefix: + let + value = pkgs.lib.removePrefix prefix (lineByPrefix text prefix); + in + if pkgs.lib.hasPrefix "'" value && pkgs.lib.hasSuffix "'" value then + pkgs.lib.removeSuffix "'" (pkgs.lib.removePrefix "'" value) + else if pkgs.lib.hasPrefix "\"" value && pkgs.lib.hasSuffix "\"" value then + pkgs.lib.removeSuffix "\"" (pkgs.lib.removePrefix "\"" value) + else + value; + + baseModule = { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + }; + }; + mkFixture = + proxySuiteConfig: + evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = proxySuiteConfig; + } + ]; + mkBadFixture = + modules: + forceEval ((evalProxySuite ([ baseModule ] ++ modules)).config.system.build.toplevel.drvPath); + mkBadFixtureRaw = + modules: forceEval ((evalProxySuite modules).config.system.build.toplevel.drvPath); + mkBadProxySuiteFixture = + proxySuiteConfig: forceEval ((mkFixture proxySuiteConfig).config.system.build.toplevel.drvPath); + mkFailingAssertions = + evaluate: cases: + map ( + case: + assert (evaluate case).success == false; + true + ) cases; + mkProxyCtlDerived = + fixture: + let + proxyCtl = packageByPattern fixture.config.environment.systemPackages ".*/[^/]*proxy-ctl(-[0-9.]+)?$"; + metadata = proxyCtl.proxySuiteCheck; + wrapper = pkgs.lib.concatStringsSep "\n" ( + pkgs.lib.mapAttrsToList ( + name: value: "export ${name}=${pkgs.lib.escapeShellArg value}" + ) metadata.wrapperEnv + ); + in + { + inherit proxyCtl wrapper; + script = wrapper + "\n" + metadata.script; + profiles = builtins.fromJSON (generated.readDerivation metadata.perAppRoutingProfilesFile); + subscriptionTags = builtins.fromJSON (generated.readDerivation metadata.subscriptionTagsFile); + inherit (metadata) proxychainsConfigFile; + }; +in +{ + inherit + rg + evalProxySuite + forceEval + mkRouting + mkRoutingRules + mkRouteModeRules + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + mkTProxyNftRules + mkPerAppZapretNftRules + mkPerAppUserRules + hasDirectDomain + hasDirectIP + hasRuleSet + dnsHasRuleSet + dnsServerByTag + mkZapretBaseFor + mkZapretBase + packagePathMatches + packageByPattern + lineByPrefix + lineContaining + shellValueByPrefix + baseModule + mkFixture + mkBadFixture + mkBadFixtureRaw + mkBadProxySuiteFixture + mkFailingAssertions + mkProxyCtlDerived + ; +} diff --git a/nix/checks/local-proxy-auth.nix b/nix/checks/local-proxy-auth.nix new file mode 100644 index 0000000..612a196 --- /dev/null +++ b/nix/checks/local-proxy-auth.nix @@ -0,0 +1,129 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + shellValueByPrefix, + mkBadFixture, + mkFailingAssertions, + ruDefaultConfig, +}: + +let + generated = import ./read-generated.nix; + + localProxyAuthFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.auth = { + username = "local-user"; + password = "local-pass"; + }; + } + ]; + localProxyAuthStartScript = generated.readDerivation ( + localProxyAuthFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + localProxyAuthBackendJqFilter = + import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix + { + pureXrayEnabled = false; + selectionMode = localProxyAuthFixture.config.services.proxy-suite.proxy.selection; + }; + + localProxyAuthPasswordFileFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.auth = { + username = "local-user"; + passwordFile = "/run/secrets/local-proxy-password"; + }; + perAppRouting = { + enable = true; + proxychains.enable = true; + profiles = [ + { + name = "steam-browser"; + route = "proxychains"; + } + ]; + }; + }; + } + ]; + _localProxyAuthPasswordFile = mkProxyCtlDerived localProxyAuthPasswordFileFixture; + localProxyAuthPasswordFileWrapper = _localProxyAuthPasswordFile.wrapper; + localProxyAuthPasswordFileScript = _localProxyAuthPasswordFile.script; + localProxyAuthPasswordFileStartScript = generated.readDerivation ( + localProxyAuthPasswordFileFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + invalidLocalProxyAuthAssertions = mkFailingAssertions mkBadFixture [ + # Auth requires both username and a password source. + [ + { services.proxy-suite.proxy.auth.username = "local-user"; } + ] + [ + { services.proxy-suite.proxy.auth.password = "local-pass"; } + ] + + # Inline password and passwordFile are mutually exclusive. + [ + { + services.proxy-suite.proxy.auth = { + username = "local-user"; + password = "local-pass"; + passwordFile = "/run/secrets/local-proxy-password"; + }; + } + ] + ]; +in +{ + assertions = [ + # Default mixed inbound stays unauthenticated. + ( + let + mixedInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "mixed-in") ruDefaultConfig.inbounds + ); + in + assert !(mixedInbound ? users); + true + ) + + # Authenticated mixed inbound is injected at runtime. + ( + assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript; + assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" localProxyAuthStartScript; + assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' localProxyAuthStartScript; + assert pkgs.lib.hasInfix "--arg user local-user" localProxyAuthStartScript; + assert pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript; + assert pkgs.lib.hasInfix ''select(.type == "mixed" and .tag == "mixed-in") | .users'' + localProxyAuthBackendJqFilter; + assert pkgs.lib.hasInfix ''chmod 600 "$RUNTIME_DIR/config.json"'' localProxyAuthStartScript; + true + ) + + # passwordFile is read from runtime path and proxychains uses runtime config. + ( + assert pkgs.lib.hasInfix "/run/secrets/local-proxy-password" localProxyAuthPasswordFileStartScript; + assert pkgs.lib.hasInfix "/run/proxy-suite-socks/proxychains.conf" + localProxyAuthPasswordFileStartScript; + assert pkgs.lib.hasInfix "printf 'socks5 %s %s %s %s\\n'" localProxyAuthPasswordFileStartScript; + assert pkgs.lib.hasInfix ''chgrp proxy-suite "/run/proxy-suite-socks/proxychains.conf"'' + localProxyAuthPasswordFileStartScript; + assert pkgs.lib.hasInfix ''chmod 640 "/run/proxy-suite-socks/proxychains.conf"'' + localProxyAuthPasswordFileStartScript; + assert builtins.hasAttr "proxy-suite" localProxyAuthPasswordFileFixture.config.users.groups; + assert + shellValueByPrefix localProxyAuthPasswordFileWrapper "export PROXYCHAINS_CONFIG=" + == "/run/proxy-suite-socks/proxychains.conf"; + assert pkgs.lib.hasInfix "Proxychains config is not readable" localProxyAuthPasswordFileScript; + true + ) + + ] + ++ invalidLocalProxyAuthAssertions; +} diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix new file mode 100644 index 0000000..3f0b157 --- /dev/null +++ b/nix/checks/module-suite.nix @@ -0,0 +1,212 @@ +{ + pkgs, + checkLib, +}: + +let + inherit (checkLib) + evalProxySuite + mkRoutingRules + mkRouteModeRules + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + mkTProxyNftRules + mkPerAppZapretNftRules + mkPerAppUserRules + hasDirectDomain + hasDirectIP + hasRuleSet + dnsHasRuleSet + dnsServerByTag + mkZapretBaseFor + mkZapretBase + packagePathMatches + packageByPattern + shellValueByPrefix + baseModule + mkBadFixture + mkBadFixtureRaw + mkBadProxySuiteFixture + mkFailingAssertions + mkProxyCtlDerived + ; + + minimal = evalProxySuite [ baseModule ]; + checkConstants = + (import ../../modules/proxy-suite/derived.nix { + lib = pkgs.lib; + cfg = minimal.config.services.proxy-suite; + }).constants; + _minimalProxyCtl = mkProxyCtlDerived minimal; + minimalProxyCtlWrapper = _minimalProxyCtl.wrapper; + minimalProxyCtlScript = _minimalProxyCtl.script; + minimalSocksService = minimal.config.systemd.services."proxy-suite-socks"; + + coreProxyChecks = import ./core-proxy.nix { + inherit + pkgs + evalProxySuite + baseModule + minimal + mkRoutingRules + mkTProxyConfig + hasRuleSet + dnsHasRuleSet + dnsServerByTag + mkBadFixtureRaw + mkFailingAssertions + ; + }; + inherit (coreProxyChecks) ruDefaultConfig; + + routeModeChecks = import ./route-mode.nix { + inherit + pkgs + evalProxySuite + baseModule + mkRouteModeRules + shellValueByPrefix + minimalProxyCtlWrapper + minimalProxyCtlScript + ; + }; + + subscriptionChecks = import ./subscriptions.nix { + inherit + pkgs + evalProxySuite + mkBadFixtureRaw + mkFailingAssertions + mkProxyCtlDerived + minimal + ; + }; + + trayChecks = import ./tray.nix { + inherit + evalProxySuite + baseModule + packagePathMatches + ; + }; + + localProxyAuthChecks = import ./local-proxy-auth.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + shellValueByPrefix + mkBadFixture + mkFailingAssertions + ruDefaultConfig + ; + }; + + perAppRoutingChecks = import ./per-app-routing.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + mkPerAppUserRules + mkPerAppZapretNftRules + mkPerAppTunConfig + dnsServerByTag + mkZapretBase + mkZapretBaseFor + mkBadFixture + mkFailingAssertions + minimalProxyCtlScript + ; + }; + + outboundValidationChecks = import ./outbound-validation.nix { + inherit mkBadProxySuiteFixture mkFailingAssertions; + }; + + globalProxyModeChecks = import ./global-proxy-modes.nix { + inherit + pkgs + evalProxySuite + baseModule + mkBadFixture + mkFailingAssertions + mkTunConfig + dnsServerByTag + checkConstants + ; + }; + + zapretChecks = import ./zapret.nix { + inherit + pkgs + evalProxySuite + baseModule + mkRoutingRules + mkZapretBase + mkBadFixture + mkFailingAssertions + hasDirectDomain + hasDirectIP + ; + }; + + tgWsProxyChecks = import ./tg-ws-proxy.nix { + inherit + pkgs + evalProxySuite + baseModule + mkRoutingRules + mkTProxyNftRules + mkBadFixture + mkFailingAssertions + hasDirectIP + minimal + minimalSocksService + ; + zapretSyncService = zapretChecks.syncService; + }; + + xrayBackendChecks = import ./xray-backends.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + shellValueByPrefix + mkBadProxySuiteFixture + mkFailingAssertions + dnsServerByTag + checkConstants + ; + }; + + validated = builtins.all (x: x) ( + [ + ( + assert minimal.config.services.proxy-suite.proxy.listenAddress == "127.0.0.1"; + true + ) + ] + ++ coreProxyChecks.assertions + ++ localProxyAuthChecks.assertions + ++ tgWsProxyChecks.assertions + ++ xrayBackendChecks.assertions + ++ outboundValidationChecks.assertions + ++ zapretChecks.assertions + ++ globalProxyModeChecks.assertions + ++ trayChecks.assertions + ++ subscriptionChecks.assertions + ++ routeModeChecks.assertions + ++ perAppRoutingChecks.assertions + ); +in +{ + proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); + xray-jq-filter-runtime = xrayBackendChecks.runtime; + per-app-zapret-runtime = perAppRoutingChecks.runtime; + zapret-hostlist-rules = zapretChecks.rules; +} diff --git a/nix/checks/outbound-validation.nix b/nix/checks/outbound-validation.nix new file mode 100644 index 0000000..abee3bb --- /dev/null +++ b/nix/checks/outbound-validation.nix @@ -0,0 +1,63 @@ +{ + mkBadProxySuiteFixture, + mkFailingAssertions, +}: + +{ + assertions = mkFailingAssertions mkBadProxySuiteFixture [ + # Outbound tags must be unique. + { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "dup"; + url = "http://one.example.com:8080"; + } + { + tag = "dup"; + url = "http://two.example.com:8080"; + } + ]; + }; + } + + # Built-in outbound names are reserved. + { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "proxy"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + } + + # Explicit routing rules must target an existing outbound. + { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + routing.rules = [ + { + outbound = "missing"; + domains = [ "example.com" ]; + } + ]; + }; + } + ]; +} diff --git a/nix/checks/per-app-routing-proxychains.nix b/nix/checks/per-app-routing-proxychains.nix new file mode 100644 index 0000000..9d784a8 --- /dev/null +++ b/nix/checks/per-app-routing-proxychains.nix @@ -0,0 +1,140 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + minimalProxyCtlScript, +}: + +let + generated = import ./read-generated.nix; + + perAppRoutingProxychainsFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.perAppRouting = { + enable = true; + proxychains.enable = true; + profiles = [ + { + name = "steam-browser"; + route = "proxychains"; + } + { + name = "native-direct"; + route = "direct"; + } + ]; + }; + } + ]; + perAppRoutingProxychains = mkProxyCtlDerived perAppRoutingProxychainsFixture; + perAppRoutingProxychainsWrapper = perAppRoutingProxychains.wrapper; + perAppRoutingProxychainsScript = perAppRoutingProxychains.script; + perAppRoutingProxychainsProfiles = perAppRoutingProxychains.profiles; + perAppRoutingProxychainsConfig = generated.readDerivation perAppRoutingProxychains.proxychainsConfigFile; + + perAppRoutingDefaultProfilesFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.perAppRouting = { + enable = true; + createDefaultProfiles = true; + proxychains.enable = true; + }; + } + ]; + perAppRoutingDefaultProfiles = (mkProxyCtlDerived perAppRoutingDefaultProfilesFixture).profiles; + + perAppRoutingNoDefaultProfilesFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy = { + tun.perApp.enable = true; + tproxy.perApp.enable = true; + }; + zapret = { + enable = true; + perApp.enable = true; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = false; + proxychains.enable = true; + }; + }; + } + ]; + perAppRoutingNoDefaultProfiles = (mkProxyCtlDerived perAppRoutingNoDefaultProfilesFixture).profiles; +in +{ + assertions = [ + # -- perAppRouting: proxychains/direct profile config is accepted -- + ( + assert perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.enable; + true + ) + ( + assert + builtins.length perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.profiles + == 2; + true + ) + ( + assert builtins.length perAppRoutingProxychainsProfiles == 2; + true + ) + + # -- perAppRouting: createDefaultProfiles injects curated proxychains profile -- + ( + assert builtins.length perAppRoutingDefaultProfiles == 1; + assert (builtins.head perAppRoutingDefaultProfiles).name == "proxychains"; + assert (builtins.head perAppRoutingDefaultProfiles).route == "proxychains"; + true + ) + + # -- perAppRouting: createDefaultProfiles = false injects no curated profiles -- + ( + assert builtins.length perAppRoutingNoDefaultProfiles == 0; + true + ) + + # -- perAppRouting: proxy-ctl script embeds wrap/apps commands -- + ( + assert pkgs.lib.hasInfix "help)" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "show this help message" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "enable/disable the proxy backend stack" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "restart active global proxy-suite services" + perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "wrap -- " perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript; + true + ) + + # -- perAppRouting: proxychains config is quiet and points at local SOCKS listener -- + ( + assert pkgs.lib.hasInfix "quiet_mode" perAppRoutingProxychainsConfig; + assert pkgs.lib.hasInfix "proxy_dns" perAppRoutingProxychainsConfig; + assert pkgs.lib.hasInfix "socks5 127.0.0.1 1080" perAppRoutingProxychainsConfig; + true + ) + + # -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds -- + ( + assert pkgs.lib.hasInfix "if _svc_exists proxy-suite-socks; then" minimalProxyCtlScript; + assert pkgs.lib.hasInfix "_svc_exists \"$svc\" && _svc_active \"$svc\"" minimalProxyCtlScript; + assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript; + true + ) + + # -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 -- + ( + assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG=-q" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix + "exec proxychains4 $PROXYCHAINS_QUIET_ARG -f \"$PROXYCHAINS_CONFIG\" \"$@\"" + perAppRoutingProxychainsScript; + true + ) + ]; +} diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix new file mode 100644 index 0000000..7d1f7b0 --- /dev/null +++ b/nix/checks/per-app-routing-tproxy.nix @@ -0,0 +1,85 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + mkPerAppUserRules, +}: + +let + generated = import ./read-generated.nix; + + perAppRoutingTproxyFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tproxy.perApp.enable = true; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + }; + } + ]; + perAppRoutingTproxy = mkProxyCtlDerived perAppRoutingTproxyFixture; + perAppRoutingTproxyScript = perAppRoutingTproxy.script; + perAppRoutingTproxyProfiles = perAppRoutingTproxy.profiles; + perAppRoutingTproxyServiceConfig = + perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig; + perAppRoutingTproxyStartScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStart; + perAppRoutingTproxyStopScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStop; + perAppRoutingTproxyUserStartScript = generated.readDerivation ( + (mkPerAppUserRules perAppRoutingTproxyFixture).perAppTproxyUserRuleStart + ); +in +{ + assertions = [ + # -- perAppRouting: createDefaultProfiles injects curated tproxy profile when backend is enabled -- + ( + assert builtins.length perAppRoutingTproxyProfiles == 2; + assert builtins.any ( + profile: profile.name == "tproxy" && profile.route == "tproxy" + ) perAppRoutingTproxyProfiles; + true + ) + + # -- perAppRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices -- + ( + assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript; + assert pkgs.lib.hasInfix + ''_wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED"'' + perAppRoutingTproxyScript; + assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript; + true + ) + + # -- perAppRouting: app TProxy service and helper units are created -- + ( + assert perAppRoutingTproxyFixture.config.systemd.services ? "proxy-suite-per-app-tproxy"; + assert perAppRoutingTproxyFixture.config.systemd.services ? "proxy-suite-per-app-tproxy-user@"; + assert + perAppRoutingTproxyFixture.config.systemd.user.services ? "proxy-suite-per-app-tproxy-anchor"; + true + ) + + # -- perAppRouting: app TProxy helper installs socket cgroup mark rules -- + ( + assert pkgs.lib.hasInfix "socket cgroupv2" perAppRoutingTproxyUserStartScript; + assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTproxyUserStartScript; + assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTproxyUserStartScript; + true + ) + + # -- perAppRouting: app TProxy startup installs nftables and loopback policy route -- + ( + assert pkgs.lib.hasInfix "proxy_suite_per_app_tproxy" perAppRoutingTproxyStartScript; + assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStartScript; + assert pkgs.lib.hasInfix "route replace local default dev lo table 102" + perAppRoutingTproxyStartScript; + assert pkgs.lib.hasInfix "rule add fwmark 17 table 102" perAppRoutingTproxyStartScript; + assert pkgs.lib.hasInfix "set +e" perAppRoutingTproxyStopScript; + assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStopScript; + true + ) + ]; +} diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix new file mode 100644 index 0000000..29ba2d8 --- /dev/null +++ b/nix/checks/per-app-routing-tun.nix @@ -0,0 +1,169 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + mkPerAppUserRules, + mkPerAppTunConfig, + dnsServerByTag, +}: + +let + generated = import ./read-generated.nix; + + perAppRoutingTunFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tun.perApp.enable = true; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + }; + } + ]; + perAppRoutingTun = mkProxyCtlDerived perAppRoutingTunFixture; + perAppRoutingTunScript = perAppRoutingTun.script; + perAppRoutingTunProfiles = perAppRoutingTun.profiles; + perAppRoutingTunServiceConfig = + perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig; + perAppRoutingTunStartScript = generated.readDerivation perAppRoutingTunServiceConfig.ExecStart; + perAppRoutingTunUpScript = generated.readDerivation perAppRoutingTunServiceConfig.ExecStartPost; + perAppRoutingTunCleanupScript = generated.readDerivation perAppRoutingTunServiceConfig.ExecStopPost; + perAppRoutingTunConfig = mkPerAppTunConfig perAppRoutingTunFixture; + perAppRoutingTunDirectOutbound = builtins.head ( + builtins.filter (item: item.tag == "direct") perAppRoutingTunConfig.outbounds + ); + perAppRoutingTunUserStartScript = generated.readDerivation ( + (mkPerAppUserRules perAppRoutingTunFixture).perAppTunUserRuleStart + ); + + perAppRoutingTunWithTproxyFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy = { + tproxy.enable = true; + tun.perApp.enable = true; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + }; + } + ]; + perAppRoutingTunWithTproxyStartScript = + generated.readDerivation + perAppRoutingTunWithTproxyFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart; + perAppRoutingTunWithTproxyConfig = mkPerAppTunConfig perAppRoutingTunWithTproxyFixture; + perAppRoutingTunWithTproxyDirectOutbound = builtins.head ( + builtins.filter (item: item.tag == "direct") perAppRoutingTunWithTproxyConfig.outbounds + ); +in +{ + assertions = [ + # -- perAppRouting: createDefaultProfiles injects curated tun profile when backend is enabled -- + ( + assert builtins.length perAppRoutingTunProfiles == 2; + assert builtins.any ( + profile: profile.name == "tun" && profile.route == "tun" + ) perAppRoutingTunProfiles; + true + ) + + # -- perAppRouting: generated proxy-ctl script dispatches tun profiles through systemd slices -- + ( + assert pkgs.lib.hasInfix "PER_APP_ROUTING_TUN_ENABLED" perAppRoutingTunScript; + assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" + perAppRoutingTunScript; + assert pkgs.lib.hasInfix "_check_no_global_proxy tun" perAppRoutingTunScript; + assert pkgs.lib.hasInfix + ''_wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED"'' + perAppRoutingTunScript; + assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" perAppRoutingTunScript; + assert pkgs.lib.hasInfix "cleanup_slice()" perAppRoutingTunScript; + assert pkgs.lib.hasInfix "trap cleanup_slice EXIT" perAppRoutingTunScript; + true + ) + + # -- perAppRouting: user mark script installs fwmark + conntrack mark rules -- + ( + assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTunUserStartScript; + assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTunUserStartScript; + true + ) + + # -- perAppRouting: app TUN config is separate and does not auto-route globally -- + ( + let + inbound = builtins.head ( + builtins.filter (item: item.tag == "tun-in") perAppRoutingTunConfig.inbounds + ); + in + assert inbound.interface_name == "psperapptun0"; + assert inbound.address == [ "172.20.0.1/30" ]; + assert inbound.auto_route == false; + assert inbound.auto_redirect == false; + assert inbound.strict_route == false; + assert !(inbound ? iproute2_table_index); + assert !(inbound ? iproute2_rule_index); + true + ) + + # -- perAppRouting: app TUN local DNS keeps direct path without explicit detour -- + ( + let + localDns = dnsServerByTag perAppRoutingTunConfig "local"; + in + assert !(localDns ? detour); + true + ) + + # -- perAppRouting: app TUN uses local domain resolver and avoids global auto-routing -- + ( + assert perAppRoutingTunConfig.route.default_domain_resolver == "local"; + true + ) + + # -- perAppRouting: app TUN does not set outbound routing marks when TProxy is disabled -- + ( + assert builtins.match ".*--routing-mark.*" perAppRoutingTunStartScript == null; + assert !(perAppRoutingTunDirectOutbound ? routing_mark); + true + ) + + # -- perAppRouting: app TUN applies outbound routing marks when TProxy is enabled -- + ( + let + expectedMark = perAppRoutingTunWithTproxyFixture.config.services.proxy-suite.proxy.tproxy.proxyMark; + in + assert builtins.match ".*--routing-mark.*" perAppRoutingTunWithTproxyStartScript != null; + assert perAppRoutingTunWithTproxyDirectOutbound.routing_mark == expectedMark; + true + ) + + # -- perAppRouting: app TUN service and helper units are created -- + ( + assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun"; + assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@"; + assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor"; + assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost; + assert !(pkgs.lib.hasInfix "-6 addr replace" perAppRoutingTunUpScript); + assert !(pkgs.lib.hasInfix "-6 route replace" perAppRoutingTunUpScript); + assert !(pkgs.lib.hasInfix "-6 rule add" perAppRoutingTunUpScript); + assert pkgs.lib.hasInfix "link del dev" perAppRoutingTunCleanupScript; + assert pkgs.lib.hasInfix "psperapptun0" perAppRoutingTunCleanupScript; + assert pkgs.lib.hasInfix "rule del fwmark 16 table 101" perAppRoutingTunCleanupScript; + true + ) + + # -- perAppRouting: app TUN enables nftables and user control group -- + ( + assert perAppRoutingTunFixture.config.networking.nftables.enable; + assert perAppRoutingTunFixture.config.users.groups ? "proxy-suite"; + true + ) + ]; +} diff --git a/nix/checks/per-app-routing-validation-profiles.nix b/nix/checks/per-app-routing-validation-profiles.nix new file mode 100644 index 0000000..55386b1 --- /dev/null +++ b/nix/checks/per-app-routing-validation-profiles.nix @@ -0,0 +1,170 @@ +{ + mkBadFixture, + mkFailingAssertions, +}: + +{ + assertions = mkFailingAssertions mkBadFixture [ + # route=proxychains requires proxychains.enable. + [ + { + services.proxy-suite.perAppRouting = { + enable = true; + profiles = [ + { + name = "steam-browser"; + route = "proxychains"; + } + ]; + }; + } + ] + + # proxychains requires proxy.enable. + [ + { + services.proxy-suite = { + proxy.enable = false; + perAppRouting = { + enable = true; + proxychains.enable = true; + }; + }; + } + ] + + # profiles require perAppRouting.enable. + [ + { services.proxy-suite.perAppRouting.profiles = [ { name = "oops"; } ]; } + ] + + # default proxychains profile still requires proxychains.enable. + [ + { + services.proxy-suite.perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + } + ] + + # route=tun requires proxy.tun.perApp.enable. + [ + { + services.proxy-suite.perAppRouting = { + enable = true; + profiles = [ + { + name = "game"; + route = "tun"; + } + ]; + }; + } + ] + + # app TUN backend requires proxy.enable. + [ + { + services.proxy-suite = { + proxy = { + enable = false; + tun.perApp.enable = true; + }; + perAppRouting.enable = true; + }; + } + ] + [ + { + services.proxy-suite = { + proxy.enable = false; + perAppRouting = { + enable = true; + profiles = [ + { + name = "game"; + route = "tun"; + } + ]; + }; + }; + } + ] + + # route=tproxy requires proxy.tproxy.perApp.enable. + [ + { + services.proxy-suite.perAppRouting = { + enable = true; + profiles = [ + { + name = "browser"; + route = "tproxy"; + } + ]; + }; + } + ] + + # app TProxy backend requires proxy.enable. + [ + { + services.proxy-suite = { + proxy = { + enable = false; + tproxy.perApp.enable = true; + }; + perAppRouting.enable = true; + }; + } + ] + [ + { + services.proxy-suite = { + proxy.enable = false; + perAppRouting = { + enable = true; + profiles = [ + { + name = "browser"; + route = "tproxy"; + } + ]; + }; + }; + } + ] + + # route=zapret requires zapret.perApp.enable. + [ + { + services.proxy-suite = { + zapret.enable = true; + perAppRouting = { + enable = true; + profiles = [ + { + name = "yt"; + route = "zapret"; + } + ]; + }; + }; + } + ] + + # profile names must be unique. + [ + { + services.proxy-suite.perAppRouting = { + enable = true; + profiles = [ + { name = "dup"; } + { name = "dup"; } + ]; + }; + } + ] + ]; +} diff --git a/nix/checks/per-app-routing-validation-resources.nix b/nix/checks/per-app-routing-validation-resources.nix new file mode 100644 index 0000000..54f095a --- /dev/null +++ b/nix/checks/per-app-routing-validation-resources.nix @@ -0,0 +1,102 @@ +{ + mkBadFixture, + mkFailingAssertions, +}: + +{ + assertions = mkFailingAssertions mkBadFixture [ + # app TUN fwmark must not collide with global TProxy proxyMark. + [ + { + services.proxy-suite = { + proxy.tproxy.proxyMark = 7; + proxy.tun.perApp = { + enable = true; + fwmark = 7; + }; + perAppRouting.enable = true; + }; + } + ] + + # app TProxy fwmark must not collide with global TProxy proxyMark. + [ + { + services.proxy-suite = { + proxy.tproxy = { + proxyMark = 8; + perApp = { + enable = true; + fwmark = 8; + }; + }; + perAppRouting.enable = true; + }; + } + ] + + # app TUN and TProxy backends must use distinct marks and route tables. + [ + { + services.proxy-suite = { + proxy.tun.perApp = { + enable = true; + fwmark = 11; + }; + proxy.tproxy.perApp = { + enable = true; + fwmark = 11; + }; + perAppRouting.enable = true; + }; + } + ] + [ + { + services.proxy-suite = { + proxy.tun.perApp = { + enable = true; + routeTable = 100; + }; + proxy.tproxy.perApp = { + enable = true; + routeTable = 100; + }; + perAppRouting.enable = true; + }; + } + ] + + # per-app zapret marks must not collide with TUN/TProxy marks. + [ + { + services.proxy-suite = { + proxy.tun.perApp = { + enable = true; + fwmark = 12; + }; + zapret.perApp = { + enable = true; + filterMark = 12; + }; + perAppRouting.enable = true; + }; + } + ] + [ + { + services.proxy-suite = { + proxy.tproxy.perApp = { + enable = true; + fwmark = 13; + }; + zapret.perApp = { + enable = true; + filterMark = 13; + }; + perAppRouting.enable = true; + }; + } + ] + ]; +} diff --git a/nix/checks/per-app-routing-validation.nix b/nix/checks/per-app-routing-validation.nix new file mode 100644 index 0000000..bb4f88c --- /dev/null +++ b/nix/checks/per-app-routing-validation.nix @@ -0,0 +1,16 @@ +{ + mkBadFixture, + mkFailingAssertions, +}: + +let + profileChecks = import ./per-app-routing-validation-profiles.nix { + inherit mkBadFixture mkFailingAssertions; + }; + resourceChecks = import ./per-app-routing-validation-resources.nix { + inherit mkBadFixture mkFailingAssertions; + }; +in +{ + assertions = profileChecks.assertions ++ resourceChecks.assertions; +} diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix new file mode 100644 index 0000000..1fecfb3 --- /dev/null +++ b/nix/checks/per-app-routing-zapret.nix @@ -0,0 +1,158 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + mkPerAppUserRules, + mkPerAppZapretNftRules, + mkZapretBase, + mkZapretBaseFor, +}: + +let + generated = import ./read-generated.nix; + + perAppRoutingZapretFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + zapret = { + enable = true; + perApp.enable = true; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + proxychains.enable = true; + }; + }; + } + ]; + perAppRoutingZapret = mkProxyCtlDerived perAppRoutingZapretFixture; + perAppRoutingZapretScript = perAppRoutingZapret.script; + perAppRoutingZapretProfiles = perAppRoutingZapret.profiles; + perAppRoutingZapretStartScript = mkPerAppZapretNftRules perAppRoutingZapretFixture; + perAppRoutingZapretUserStartScript = generated.readDerivation ( + (mkPerAppUserRules perAppRoutingZapretFixture).perAppZapretUserRuleStart + ); + perAppRoutingZapretService = + perAppRoutingZapretFixture.config.systemd.services."proxy-suite-per-app-zapret"; + perAppRoutingZapretBase = mkZapretBase perAppRoutingZapretFixture; + perAppRoutingPerAppZapretBase = mkZapretBaseFor perAppRoutingZapretFixture "proxy-suite-per-app-zapret"; + + perAppRoutingZapretWithoutGlobalFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + zapret = { + enable = false; + perApp.enable = true; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + proxychains.enable = true; + }; + }; + } + ]; + perAppRoutingZapretWithoutGlobal = mkProxyCtlDerived perAppRoutingZapretWithoutGlobalFixture; + perAppRoutingZapretWithoutGlobalProfiles = perAppRoutingZapretWithoutGlobal.profiles; + perAppRoutingZapretWithoutGlobalPerAppBase = mkZapretBaseFor perAppRoutingZapretWithoutGlobalFixture "proxy-suite-per-app-zapret"; + + runtime = pkgs.runCommand "proxy-suite-per-app-zapret-runtime-check" { } '' + global_config=${perAppRoutingZapretBase}/config + per_app_config=${perAppRoutingPerAppZapretBase}/config + per_app_only_config=${perAppRoutingZapretWithoutGlobalPerAppBase}/config + custom_script=${perAppRoutingZapretBase}/init.d/sysv/custom.d/50-proxy-suite-custom.sh + + grep -F 'FILTER_MARK=' "$global_config" + ! grep -F 'FILTER_MARK=0x10000000' "$global_config" + + grep -F 'FILTER_MARK=0x10000000' "$per_app_config" + grep -F 'MODE_FILTER=none' "$per_app_config" + grep -F 'QNUM=201' "$per_app_config" + grep -F 'DESYNC_MARK=0x8000000' "$per_app_config" + grep -F 'DESYNC_MARK_POSTNAT=0x4000000' "$per_app_config" + grep -F 'ZAPRET_NFT_TABLE=proxy_suite_per_app_zapret' "$per_app_config" + + grep -F 'FILTER_MARK=0x10000000' "$per_app_only_config" + grep -F 'QNUM=201' "$per_app_only_config" + + grep -F 'proxy-suite per-app-zapret bypass' "$custom_script" + grep -F 'mark and 268435456 != 0 return' "$custom_script" + + touch "$out" + ''; +in +{ + assertions = [ + # -- perAppRouting: createDefaultProfiles injects curated zapret profile when backend is enabled -- + ( + assert builtins.length perAppRoutingZapretProfiles == 2; + assert builtins.any ( + profile: profile.name == "zapret" && profile.route == "zapret" + ) perAppRoutingZapretProfiles; + true + ) + + # -- perAppRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices -- + ( + assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript; + assert pkgs.lib.hasInfix + ''_wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED"'' + perAppRoutingZapretScript; + assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript; + true + ) + + # -- perAppRouting: app zapret service and helper units are created -- + ( + assert perAppRoutingZapretFixture.config.systemd.services ? "proxy-suite-per-app-zapret"; + assert perAppRoutingZapretFixture.config.systemd.services ? "proxy-suite-per-app-zapret-user@"; + assert + perAppRoutingZapretFixture.config.systemd.user.services ? "proxy-suite-per-app-zapret-anchor"; + assert builtins.elem "network-online.target" perAppRoutingZapretService.after; + assert builtins.elem "network-online.target" perAppRoutingZapretService.wants; + true + ) + + # -- perAppRouting: app zapret can run without the global zapret service -- + ( + assert + perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-per-app-zapret"; + assert + perAppRoutingZapretWithoutGlobalFixture.config.systemd.services + ? "proxy-suite-per-app-zapret-user@"; + assert + perAppRoutingZapretWithoutGlobalFixture.config.systemd.user.services + ? "proxy-suite-per-app-zapret-anchor"; + assert + !(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "zapret-discord-youtube"); + assert builtins.length perAppRoutingZapretWithoutGlobalProfiles == 2; + assert builtins.any ( + profile: profile.name == "zapret" && profile.route == "zapret" + ) perAppRoutingZapretWithoutGlobalProfiles; + assert pkgs.lib.hasInfix "proxy-suite-per-app-zapret" perAppRoutingZapretWithoutGlobalPerAppBase; + assert !(pkgs.lib.hasInfix "proxy-suite-zapret" perAppRoutingZapretWithoutGlobalPerAppBase); + true + ) + + # -- perAppRouting: app zapret helper installs socket cgroup bitwise mark rules -- + ( + assert pkgs.lib.hasInfix "socket cgroupv2" perAppRoutingZapretUserStartScript; + assert pkgs.lib.hasInfix "meta mark set meta mark or 268435456" perAppRoutingZapretUserStartScript; + assert pkgs.lib.hasInfix "ct mark set ct mark or 268435456" perAppRoutingZapretUserStartScript; + true + ) + + # -- perAppRouting: app zapret startup installs nftables backend -- + ( + assert pkgs.lib.hasInfix "proxy_suite_per_app_zapret_mark" perAppRoutingZapretStartScript; + true + ) + + ]; + + inherit runtime; +} diff --git a/nix/checks/per-app-routing.nix b/nix/checks/per-app-routing.nix new file mode 100644 index 0000000..ef8eddf --- /dev/null +++ b/nix/checks/per-app-routing.nix @@ -0,0 +1,80 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + mkPerAppUserRules, + mkPerAppZapretNftRules, + mkPerAppTunConfig, + dnsServerByTag, + mkZapretBase, + mkZapretBaseFor, + mkBadFixture, + mkFailingAssertions, + minimalProxyCtlScript, +}: + +let + tunChecks = import ./per-app-routing-tun.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + mkPerAppUserRules + mkPerAppTunConfig + dnsServerByTag + ; + }; + tproxyChecks = import ./per-app-routing-tproxy.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + mkPerAppUserRules + ; + }; + zapretChecks = import ./per-app-routing-zapret.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + mkPerAppUserRules + mkPerAppZapretNftRules + mkZapretBase + mkZapretBaseFor + ; + }; + validationChecks = import ./per-app-routing-validation.nix { + inherit mkBadFixture mkFailingAssertions; + }; + userControlChecks = import ./user-control.nix { + inherit + pkgs + evalProxySuite + baseModule + ; + }; + proxychainsChecks = import ./per-app-routing-proxychains.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + minimalProxyCtlScript + ; + }; +in +{ + assertions = + tunChecks.assertions + ++ tproxyChecks.assertions + ++ zapretChecks.assertions + ++ proxychainsChecks.assertions + ++ userControlChecks.assertions + ++ validationChecks.assertions; + + runtime = zapretChecks.runtime; +} diff --git a/nix/checks/read-generated.nix b/nix/checks/read-generated.nix new file mode 100644 index 0000000..d6eace1 --- /dev/null +++ b/nix/checks/read-generated.nix @@ -0,0 +1,9 @@ +# Inspect writeText/writeShellScript output without import-from-derivation. +{ + readDerivation = + derivation: + if derivation ? drvAttrs && derivation.drvAttrs ? text then + derivation.drvAttrs.text + else + throw "proxy-suite checks: expected a writeText/writeShellScript derivation"; +} diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix new file mode 100644 index 0000000..1a39b31 --- /dev/null +++ b/nix/checks/route-mode.nix @@ -0,0 +1,123 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkRouteModeRules, + shellValueByPrefix, + minimalProxyCtlWrapper, + minimalProxyCtlScript, +}: + +let + generated = import ./read-generated.nix; + + routeModeFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.routing = { + proxy = { + domains = [ "proxy.example" ]; + geosites = [ "google" ]; + }; + direct.domains = [ "direct.example" ]; + block.domains = [ "block.example" ]; + rules = [ + { + outbound = "direct"; + domains = [ "custom-direct.example" ]; + } + { + outbound = "primary"; + domains = [ "custom-proxy.example" ]; + } + { + outbound = "block"; + domains = [ "custom-block.example" ]; + } + ]; + }; + } + ]; + routeModeStartScript = generated.readDerivation ( + routeModeFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + routeModeBackendJqFilter = + import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix + { + pureXrayEnabled = false; + selectionMode = routeModeFixture.config.services.proxy-suite.proxy.selection; + }; + routeModeSetterScript = generated.readDerivation ( + (import ../../modules/proxy-suite/service/control-scripts.nix { + inherit pkgs; + lib = pkgs.lib; + proxyCfg = routeModeFixture.config.services.proxy-suite.proxy; + routeModeStateFile = "/run/proxy-suite/route-mode"; + subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/sing-box"; + subscriptionCacheHelpersBlock = ""; + mkSubscriptionFetchBlock = _: ""; + }).setRouteModeScript + ); + routeModeRules = mkRouteModeRules routeModeFixture; +in +{ + assertions = [ + # proxy-ctl wrapper exports the volatile state file and baseline default. + ( + assert + shellValueByPrefix minimalProxyCtlWrapper "export ROUTE_MODE_STATE_FILE=" + == "/run/proxy-suite/route-mode"; + assert shellValueByPrefix minimalProxyCtlWrapper "export DEFAULT_ROUTE_MODE=" == "blacklist"; + true + ) + + # proxy-ctl help/status exposes default plus the explicit route modes. + ( + assert pkgs.lib.hasInfix "route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" + minimalProxyCtlScript; + assert pkgs.lib.hasInfix ''printf 'route_mode=%s\n' "$(_route_mode_current)"'' + minimalProxyCtlScript; + assert pkgs.lib.hasInfix ''printf 'default_route_mode=%s\n' "$(_route_mode_default)"'' + minimalProxyCtlScript; + assert pkgs.lib.hasInfix ''systemctl start "proxy-suite-route-mode@''${action}.service"'' + minimalProxyCtlScript; + true + ) + + # The socks start script includes every override branch and uses volatile state. + ( + assert pkgs.lib.hasInfix ''ROUTE_MODE_STATE_FILE="/run/proxy-suite/route-mode"'' + routeModeStartScript; + assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" routeModeStartScript; + assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' routeModeStartScript; + assert pkgs.lib.hasInfix "all-proxy)" routeModeStartScript; + assert pkgs.lib.hasInfix "all-bypass)" routeModeStartScript; + assert pkgs.lib.hasInfix ".route.rules = (sing_box_preserved_rules + $route_rules)" + routeModeBackendJqFilter; + assert pkgs.lib.hasInfix ".dns.rules = []" routeModeBackendJqFilter; + true + ) + + # Grouped routing metadata preserves custom rule categories and order. + ( + assert builtins.length routeModeRules.custom == 3; + assert (builtins.elemAt routeModeRules.custom 0).category == "direct"; + assert (builtins.elemAt routeModeRules.custom 1).category == "proxy"; + assert (builtins.elemAt routeModeRules.custom 2).category == "block"; + true + ) + + # Setter unit is present and writes into /run. + ( + let + setterSvc = routeModeFixture.config.systemd.services."proxy-suite-route-mode@"; + in + assert !(setterSvc.serviceConfig ? RuntimeDirectory); + assert pkgs.lib.hasInfix "/run/proxy-suite/route-mode" routeModeSetterScript; + assert pkgs.lib.hasInfix "default)" routeModeSetterScript; + assert pkgs.lib.hasInfix "all-proxy)" routeModeSetterScript; + assert pkgs.lib.hasInfix "all-bypass)" routeModeSetterScript; + true + ) + ]; +} diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix new file mode 100644 index 0000000..6ea2444 --- /dev/null +++ b/nix/checks/subscriptions-runtime.nix @@ -0,0 +1,134 @@ +{ + pkgs, + evalProxySuite, + mkProxyCtlDerived, + minimal, +}: + +let + fixtures = import ./subscriptions-runtime/fixtures.nix { + inherit + evalProxySuite + mkProxyCtlDerived + ; + }; + inherit (fixtures) + subscriptionOnlyFixture + subscriptionOnlyScript + subscriptionOnlyTags + subscriptionOnlyStartScript + subscriptionOnlyUpdateScript + subscriptionWithStaticFixture + subscriptionWithStaticStartScript + subscriptionFirstSelectionFixture + subscriptionFirstSelectionStartScript + subscriptionPerAppTunUpdateScript + ; +in +{ + assertions = [ + # Basic config is accepted. + ( + assert subscriptionOnlyFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; + true + ) + + # Wrapper exposes tags through a JSON file, not shell word splitting. + ( + assert subscriptionOnlyTags == [ "community" ]; + assert pkgs.lib.hasInfix "export SUB_TAGS_FILE=" subscriptionOnlyScript; + assert !(pkgs.lib.hasInfix "SUB_TAGS_RAW" subscriptionOnlyScript); + true + ) + + # Update service and timer are created when subscriptions are configured. + ( + assert subscriptionOnlyFixture.config.systemd.services ? "proxy-suite-subscription-update"; + true + ) + ( + assert subscriptionOnlyFixture.config.systemd.timers ? "proxy-suite-subscription-update"; + true + ) + + # StateDirectory is set on the socks service. + ( + assert + subscriptionOnlyFixture.config.systemd.services."proxy-suite-socks".serviceConfig.StateDirectory + == "proxy-suite"; + true + ) + + # Custom update interval flows through to the timer. + ( + assert + subscriptionWithStaticFixture.config.systemd.timers."proxy-suite-subscription-update".timerConfig.OnUnitActiveSec + == "6h"; + true + ) + + # selection=first renames the first subscription outbound to "proxy". + ( + assert builtins.match ".*proxy.*" subscriptionFirstSelectionStartScript != null; + true + ) + + # Runtime parser imports are available in socks and update scripts. + ( + assert + builtins.match ".*PYTHONPATH=.*build-outbound\\.py.*" subscriptionWithStaticStartScript != null; + true + ) + ( + assert + builtins.match ".*PYTHONPATH=.*fetch-subscription\\.py.*" subscriptionOnlyUpdateScript != null; + true + ) + + # Generated cache paths use the raw validated tag, not shell-escaped quotes. + ( + assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/sing-box/community.json"'' + subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "/var/lib/proxy-suite/subscriptions/sing-box/community.json.tmp" + subscriptionOnlyUpdateScript; + assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyStartScript); + assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyUpdateScript); + true + ) + + # Invalid cache files are ignored and refreshed. + ( + assert pkgs.lib.hasInfix "_proxy_suite_valid_subscription_cache()" subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_drop_invalid_subscription_cache" subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "removed invalid subscription cache" subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "produced an invalid cache" subscriptionOnlyUpdateScript; + true + ) + + # Refresh restarts only active sing-box units, including per-app TUN when present. + ( + assert pkgs.lib.hasInfix "is-active --quiet proxy-suite-socks" subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix "restart proxy-suite-socks" subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix "is-active --quiet proxy-suite-tun" subscriptionOnlyUpdateScript; + assert !(pkgs.lib.hasInfix "SOCKS_WAS_ACTIVE" subscriptionOnlyUpdateScript); + true + ) + ( + assert pkgs.lib.hasInfix "is-active --quiet proxy-suite-per-app-tun" + subscriptionPerAppTunUpdateScript; + assert pkgs.lib.hasInfix "restart proxy-suite-per-app-tun" subscriptionPerAppTunUpdateScript; + assert !(pkgs.lib.hasInfix "PER_APP_TUN_WAS_ACTIVE" subscriptionPerAppTunUpdateScript); + true + ) + + # No update service or timer exists without subscriptions. + ( + assert !(minimal.config.systemd.services ? "proxy-suite-subscription-update"); + true + ) + ( + assert !(minimal.config.systemd.timers ? "proxy-suite-subscription-update"); + true + ) + ]; +} diff --git a/nix/checks/subscriptions-runtime/fixtures.nix b/nix/checks/subscriptions-runtime/fixtures.nix new file mode 100644 index 0000000..906b574 --- /dev/null +++ b/nix/checks/subscriptions-runtime/fixtures.nix @@ -0,0 +1,127 @@ +{ + evalProxySuite, + mkProxyCtlDerived, +}: + +let + generated = import ../read-generated.nix; + + subscriptionOnlyFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { + tag = "community"; + url = "https://example.com/sub/token"; + } + ]; + }; + }; + } + ]; + subscriptionOnlyProxyCtl = mkProxyCtlDerived subscriptionOnlyFixture; + subscriptionOnlyScript = subscriptionOnlyProxyCtl.script; + subscriptionOnlyTags = subscriptionOnlyProxyCtl.subscriptionTags; + subscriptionOnlyStartScript = + generated.readDerivation + subscriptionOnlyFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; + subscriptionOnlyUpdateScript = + generated.readDerivation + subscriptionOnlyFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart; + + subscriptionWithStaticFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "own-vps"; + url = "http://proxy.example.com:8080"; + } + ]; + subscriptions = [ + { + tag = "backup"; + url = "https://example.com/sub/token"; + } + ]; + selection = "urltest"; + subscriptionUpdateInterval = "6h"; + }; + }; + } + ]; + subscriptionWithStaticStartScript = generated.readDerivation ( + subscriptionWithStaticFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + subscriptionFirstSelectionFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { + tag = "community"; + url = "https://example.com/sub/token"; + } + ]; + selection = "first"; + }; + }; + } + ]; + subscriptionFirstSelectionStartScript = generated.readDerivation ( + subscriptionFirstSelectionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + subscriptionPerAppTunFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + subscriptions = [ + { + tag = "community"; + url = "https://example.com/sub/token"; + } + ]; + tun.perApp.enable = true; + }; + perAppRouting.enable = true; + }; + } + ]; + subscriptionPerAppTunUpdateScript = generated.readDerivation ( + subscriptionPerAppTunFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart + ); +in +{ + inherit + subscriptionOnlyFixture + subscriptionOnlyScript + subscriptionOnlyTags + subscriptionOnlyStartScript + subscriptionOnlyUpdateScript + subscriptionWithStaticFixture + subscriptionWithStaticStartScript + subscriptionFirstSelectionFixture + subscriptionFirstSelectionStartScript + subscriptionPerAppTunUpdateScript + ; +} diff --git a/nix/checks/subscriptions-validation.nix b/nix/checks/subscriptions-validation.nix new file mode 100644 index 0000000..284d341 --- /dev/null +++ b/nix/checks/subscriptions-validation.nix @@ -0,0 +1,81 @@ +{ + evalProxySuite, + mkBadFixtureRaw, + mkFailingAssertions, +}: + +let + proxyWithSubscriptions = + subscriptions: + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + inherit subscriptions; + }; + }; + }; + + subscriptionUrlFileFixture = evalProxySuite [ + (proxyWithSubscriptions [ + { + tag = "private"; + urlFile = "/run/secrets/sub-url"; + } + ]) + ]; +in +{ + assertions = + (mkFailingAssertions mkBadFixtureRaw [ + # Tags are cache keys and tag prefixes, so duplicates are invalid. + [ + (proxyWithSubscriptions [ + { + tag = "dup"; + url = "https://example.com/sub/one"; + } + { + tag = "dup"; + url = "https://example.com/sub/two"; + } + ]) + ] + + # Tags must be safe for generated names. + [ + (proxyWithSubscriptions [ + { + tag = "bad/tag"; + url = "https://example.com/sub/token"; + } + ]) + ] + + # A subscription source must be either url or urlFile, not both. + [ + (proxyWithSubscriptions [ + { + tag = "bad"; + url = "https://example.com/sub/token"; + urlFile = "/run/secrets/sub-url"; + } + ]) + ] + + # A subscription with no source is invalid. + [ + (proxyWithSubscriptions [ { tag = "bad"; } ]) + ] + ]) + ++ [ + # urlFile form is accepted. + ( + assert subscriptionUrlFileFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; + true + ) + ]; +} diff --git a/nix/checks/subscriptions.nix b/nix/checks/subscriptions.nix new file mode 100644 index 0000000..7f24ef4 --- /dev/null +++ b/nix/checks/subscriptions.nix @@ -0,0 +1,29 @@ +{ + pkgs, + evalProxySuite, + mkBadFixtureRaw, + mkFailingAssertions, + mkProxyCtlDerived, + minimal, +}: + +let + runtimeChecks = import ./subscriptions-runtime.nix { + inherit + pkgs + evalProxySuite + mkProxyCtlDerived + minimal + ; + }; + validationChecks = import ./subscriptions-validation.nix { + inherit + evalProxySuite + mkBadFixtureRaw + mkFailingAssertions + ; + }; +in +{ + assertions = runtimeChecks.assertions ++ validationChecks.assertions; +} diff --git a/nix/checks/tg-ws-proxy.nix b/nix/checks/tg-ws-proxy.nix new file mode 100644 index 0000000..029a429 --- /dev/null +++ b/nix/checks/tg-ws-proxy.nix @@ -0,0 +1,103 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkRoutingRules, + mkTProxyNftRules, + mkBadFixture, + mkFailingAssertions, + hasDirectIP, + minimal, + minimalSocksService, + zapretSyncService, +}: + +let + fixtures = import ./tg-ws-proxy/fixtures.nix { + inherit + evalProxySuite + baseModule + mkRoutingRules + mkTProxyNftRules + mkBadFixture + mkFailingAssertions + ; + }; + inherit (fixtures) + tgSecretFile + tgSecretFileService + tgAllOptionsStartScript + tgWithGlobalTunServiceConfig + tgWithGlobalTunBypassUp + tgWithGlobalTunBypassDown + tgWithGlobalTunRules + tgWithGlobalTproxyNft + invalidTgWsProxyAssertions + ; +in +{ + assertions = [ + ( + assert tgSecretFile.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; + true + ) + ( + assert minimal.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; + true + ) + ( + assert minimal.config.services.proxy-suite.tgWsProxy.dcIps == { }; + true + ) + + # Upstream runtime flags are exposed as typed module options. + ( + assert pkgs.lib.hasInfix "--port=2443" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--host=0.0.0.0" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--secret-file=\"$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret\"" + tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--verbose" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--log-file=/var/log/tg-ws-proxy.log" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--log-max-mb=2.500000" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--log-backups=3" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--buf-kb=512" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--pool-size=8" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--cfproxy-domain=cdn.example.com" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--cfproxy-domain=edge.example.net" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--cfproxy-worker-domain=worker.example.com" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--no-cfproxy" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--fake-tls-domain=mask.example.com" tgAllOptionsStartScript; + assert pkgs.lib.hasInfix "--proxy-protocol" tgAllOptionsStartScript; + true + ) + + ( + assert + tgSecretFile.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig.LoadCredential + == [ "tg_ws_proxy_secret:/run/secrets/tg-ws-proxy" ]; + true + ) + + # Global TUN/TProxy bypass mark keeps relay traffic out of transparent capture. + ( + assert tgWithGlobalTunServiceConfig.SocketMark == "4"; + assert pkgs.lib.hasInfix "rule add pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassUp; + assert pkgs.lib.hasInfix "rule del pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassDown; + assert hasDirectIP tgWithGlobalTunRules "149.154.167.220"; + assert pkgs.lib.hasInfix "meta mark 4 return" tgWithGlobalTproxyNft; + true + ) + + # Network-sensitive global services wait for network-online. + ( + assert builtins.elem "network-online.target" minimalSocksService.after; + assert builtins.elem "network-online.target" minimalSocksService.wants; + assert builtins.elem "network-online.target" tgSecretFileService.after; + assert builtins.elem "network-online.target" tgSecretFileService.wants; + assert builtins.elem "network-online.target" zapretSyncService.after; + assert builtins.elem "network-online.target" zapretSyncService.wants; + true + ) + ] + ++ invalidTgWsProxyAssertions; +} diff --git a/nix/checks/tg-ws-proxy/fixtures.nix b/nix/checks/tg-ws-proxy/fixtures.nix new file mode 100644 index 0000000..e8eef99 --- /dev/null +++ b/nix/checks/tg-ws-proxy/fixtures.nix @@ -0,0 +1,141 @@ +{ + evalProxySuite, + baseModule, + mkRoutingRules, + mkTProxyNftRules, + mkBadFixture, + mkFailingAssertions, +}: + +let + generated = import ../read-generated.nix; + + tgSecretFile = evalProxySuite [ + baseModule + { + services.proxy-suite.tgWsProxy = { + enable = true; + host = "127.0.0.1"; + secretFile = "/run/secrets/tg-ws-proxy"; + }; + } + ]; + tgSecretFileService = tgSecretFile.config.systemd.services."proxy-suite-tg-ws-proxy"; + + tgAllOptions = evalProxySuite [ + baseModule + { + services.proxy-suite.tgWsProxy = { + enable = true; + port = 2443; + host = "0.0.0.0"; + secretFile = "/run/secrets/tg-ws-proxy"; + verbose = true; + logFile = "/var/log/tg-ws-proxy.log"; + logMaxMb = 2.5; + logBackups = 3; + bufKb = 512; + poolSize = 8; + cfProxyDomains = [ + "cdn.example.com" + "edge.example.net" + ]; + cfProxyWorkerDomains = [ "worker.example.com" ]; + cfProxyFallback = false; + fakeTlsDomain = "mask.example.com"; + proxyProtocol = true; + }; + } + ]; + tgAllOptionsStartScript = generated.readDerivation ( + tgAllOptions.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig.ExecStart + ); + + tgWithGlobalTun = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tun.enable = true; + tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg-ws-proxy"; + dcIps."2" = "149.154.167.220"; + }; + }; + } + ]; + tgWithGlobalTunServiceConfig = + tgWithGlobalTun.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig; + tgWithGlobalTunBypassUp = generated.readDerivation tgWithGlobalTunServiceConfig.ExecStartPre; + tgWithGlobalTunBypassDown = generated.readDerivation tgWithGlobalTunServiceConfig.ExecStopPost; + tgWithGlobalTunRules = mkRoutingRules tgWithGlobalTun; + + tgWithGlobalTproxy = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tproxy.enable = true; + tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg-ws-proxy"; + }; + }; + } + ]; + tgWithGlobalTproxyNft = mkTProxyNftRules tgWithGlobalTproxy; + + invalidTgWsProxyAssertions = mkFailingAssertions mkBadFixture [ + [ + { + services.proxy-suite = { + proxy.tproxy.enable = true; + tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg-ws-proxy"; + routingMark = 1; + }; + }; + } + ] + [ + { + services.proxy-suite.tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg-ws-proxy"; + bufKb = 3; + }; + } + ] + [ + { + services.proxy-suite.tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg-ws-proxy"; + poolSize = -1; + }; + } + ] + [ + { + services.proxy-suite.tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg-ws-proxy"; + logBackups = 0; + }; + } + ] + ]; +in +{ + inherit + tgSecretFile + tgSecretFileService + tgAllOptionsStartScript + tgWithGlobalTunServiceConfig + tgWithGlobalTunBypassUp + tgWithGlobalTunBypassDown + tgWithGlobalTunRules + tgWithGlobalTproxyNft + invalidTgWsProxyAssertions + ; +} diff --git a/nix/checks/tray.nix b/nix/checks/tray.nix new file mode 100644 index 0000000..46012fc --- /dev/null +++ b/nix/checks/tray.nix @@ -0,0 +1,55 @@ +{ + evalProxySuite, + baseModule, + packagePathMatches, +}: + +let + trayAutostartFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.tray.enable = true; + } + ]; + + trayManualFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.tray = { + enable = true; + autostart = false; + }; + } + ]; +in +{ + assertions = [ + ( + assert packagePathMatches trayAutostartFixture.config.environment.systemPackages + ".*/[^/]*proxy-suite-tray(-[0-9.]+)?$"; + true + ) + ( + assert packagePathMatches trayAutostartFixture.config.environment.systemPackages + ".*/[^/]*proxy-suite-tray\\.desktop$"; + true + ) + ( + assert + builtins.match ".*/share/xdg/autostart/proxy-suite-tray\\.desktop$" ( + builtins.unsafeDiscardStringContext + trayAutostartFixture.config.environment.etc."xdg/autostart/proxy-suite-tray.desktop".source + ) != null; + true + ) + ( + assert !(trayManualFixture.config.environment.etc ? "xdg/autostart/proxy-suite-tray.desktop"); + true + ) + ( + assert packagePathMatches trayManualFixture.config.environment.systemPackages + ".*/[^/]*proxy-suite-tray\\.desktop$"; + true + ) + ]; +} diff --git a/nix/checks/user-control.nix b/nix/checks/user-control.nix new file mode 100644 index 0000000..1166b3e --- /dev/null +++ b/nix/checks/user-control.nix @@ -0,0 +1,116 @@ +{ + pkgs, + evalProxySuite, + baseModule, +}: + +let + userControlDefaultFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tun.perApp.enable = true; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + }; + } + ]; + userControlDefaultPolkitConfig = userControlDefaultFixture.config.security.polkit.extraConfig; + + userControlGlobalOnlyFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.userControl = { + global.enable = true; + perApp.enable = false; + }; + } + ]; + userControlGlobalOnlyPolkitConfig = userControlGlobalOnlyFixture.config.security.polkit.extraConfig; + + userControlPerAppOnlyFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tun.perApp.enable = true; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + }; + userControl = { + global.enable = false; + perApp.enable = true; + }; + }; + } + ]; + userControlPerAppOnlyPolkitConfig = userControlPerAppOnlyFixture.config.security.polkit.extraConfig; + + userControlDisabledFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.userControl = { + global.enable = false; + perApp.enable = false; + }; + } + ]; +in +{ + assertions = [ + # -- userControl: default polkit rule covers both per-app and global proxy-ctl managed units -- + ( + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") === 0" + userControlDefaultPolkitConfig; + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlDefaultPolkitConfig; + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" + userControlDefaultPolkitConfig; + assert pkgs.lib.hasInfix "unit === \"zapret-discord-youtube.service\"" + userControlDefaultPolkitConfig; + true + ) + + # -- userControl: global-only rule excludes per-app units -- + ( + assert userControlGlobalOnlyFixture.config.users.groups ? "proxy-suite"; + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlGlobalOnlyPolkitConfig; + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" + userControlGlobalOnlyPolkitConfig; + assert + builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) === 0.*" userControlGlobalOnlyPolkitConfig + == null; + assert pkgs.lib.hasInfix "unit === \"zapret-discord-youtube.service\"" + userControlGlobalOnlyPolkitConfig; + true + ) + + # -- userControl: per-app-only rule covers per-app-scoped helpers only -- + ( + assert userControlPerAppOnlyFixture.config.users.groups ? "proxy-suite"; + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") === 0" + userControlPerAppOnlyPolkitConfig; + assert + builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) !== 0.*" userControlPerAppOnlyPolkitConfig + == null; + assert + builtins.match ".*unit === \"zapret-discord-youtube\\.service\".*" userControlPerAppOnlyPolkitConfig + == null; + true + ) + + # -- userControl: disabling both scopes removes group and polkit wiring -- + ( + assert !(userControlDisabledFixture.config.users.groups ? "proxy-suite"); + assert !userControlDisabledFixture.config.security.polkit.enable; + assert + builtins.match ".*subject\\.isInGroup\\(\"proxy-suite\"\\).*" userControlDisabledFixture.config.security.polkit.extraConfig + == null; + assert + builtins.match ".*org\\.freedesktop\\.systemd1\\.manage-units.*" userControlDisabledFixture.config.security.polkit.extraConfig + == null; + true + ) + ]; +} diff --git a/nix/checks/xray-backend-features.nix b/nix/checks/xray-backend-features.nix new file mode 100644 index 0000000..6cf1802 --- /dev/null +++ b/nix/checks/xray-backend-features.nix @@ -0,0 +1,55 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkBadProxySuiteFixture, + mkFailingAssertions, + dnsServerByTag, +}: + +let + fixtures = import ./xray-backend-features/fixtures.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkBadProxySuiteFixture + mkFailingAssertions + ; + }; + inherit (fixtures) + xraySubscriptionStartScript + xrayRawStreamOutbound + xrayDnsTcpConfig + invalidXrayFeatureAssertions + ; +in +{ + assertions = [ + ( + assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/xray/xray-sub.json"'' + xraySubscriptionStartScript; + assert pkgs.lib.hasInfix "--backend xray" xraySubscriptionStartScript; + true + ) + + # -- xray backend: raw stream settings and DNS encoding are preserved -- + ( + let + localDns = dnsServerByTag xrayDnsTcpConfig "local"; + in + assert xrayRawStreamOutbound.tag == "proxy"; + assert xrayRawStreamOutbound.streamSettings.network == "ws"; + assert xrayRawStreamOutbound.streamSettings.security == "tls"; + assert xrayRawStreamOutbound.streamSettings.tlsSettings.serverName == "cdn.example.com"; + assert xrayRawStreamOutbound.streamSettings.wsSettings.path == "/ws"; + assert xrayRawStreamOutbound.streamSettings.sockopt.tcpFastOpen == true; + assert xrayRawStreamOutbound.streamSettings.sockopt.mark == 2; + assert localDns.address == "tcp://9.9.9.9"; + assert localDns.port == 5353; + assert localDns.queryStrategy == "UseIP"; + true + ) + ] + ++ invalidXrayFeatureAssertions; +} diff --git a/nix/checks/xray-backend-features/fixtures.nix b/nix/checks/xray-backend-features/fixtures.nix new file mode 100644 index 0000000..b937f41 --- /dev/null +++ b/nix/checks/xray-backend-features/fixtures.nix @@ -0,0 +1,200 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkBadProxySuiteFixture, + mkFailingAssertions, +}: + +let + generated = import ../read-generated.nix; + rawOutboundJson = + (import ../../../modules/proxy-suite/service/script-blocks/outbounds.nix { + lib = pkgs.lib; + inherit pkgs; + pureXrayEnabled = true; + singBoxCfg = null; + proxyCfg = null; + hybridEnabled = null; + collapseNamedOutbounds = null; + selectionMode = null; + backend = null; + backendArg = null; + xraySidecarRoutingMark = null; + jq = null; + python3 = null; + parserScriptsPythonPath = null; + buildOutboundPy = null; + mkSubscriptionBlock = null; + }).rawOutboundJson; + + xrayRawStreamDefinition = { + tag = "raw-stream"; + xrayJson = { + protocol = "vless"; + settings = { + address = "example.com"; + port = 443; + id = "00000000-0000-0000-0000-000000000000"; + encryption = "none"; + }; + streamSettings = { + network = "ws"; + security = "tls"; + tlsSettings.serverName = "cdn.example.com"; + wsSettings.path = "/ws"; + sockopt.tcpFastOpen = true; + }; + }; + }; + + 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 = generated.readDerivation ( + xraySubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + xrayRawStreamFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + outbounds = [ xrayRawStreamDefinition ]; + }; + }; + } + ]; + xrayRawStreamOutbound = + rawOutboundJson (builtins.head xrayRawStreamFixture.config.services.proxy-suite.proxy.outbounds) + "proxy" + 2; + + xrayDnsTcpConfig = mkTProxyConfig (evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + dns.local = { + type = "tcp"; + address = "9.9.9.9"; + port = 5353; + }; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + }; + } + ]); + + invalidXrayFeatureAssertions = mkFailingAssertions mkBadProxySuiteFixture [ + { + enable = true; + proxy = { + enable = true; + xray.enable = true; + dns.remote = { + type = "tls"; + address = "1.1.1.1"; + port = 853; + }; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + } + { + enable = true; + proxy = { + enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + } + { + enable = true; + proxy = { + enable = true; + xray.enable = true; + selection = "selector"; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + } + { + enable = true; + proxy = { + enable = true; + xray.enable = true; + outbounds = [ + { + tag = "raw"; + singBoxJson = { + type = "direct"; + }; + } + ]; + }; + } + { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "raw"; + xrayJson = { + protocol = "freedom"; + settings = { }; + }; + } + ]; + }; + } + ]; +in +{ + inherit + xraySubscriptionStartScript + xrayRawStreamOutbound + xrayDnsTcpConfig + invalidXrayFeatureAssertions + ; +} diff --git a/nix/checks/xray-backend-runtime.nix b/nix/checks/xray-backend-runtime.nix new file mode 100644 index 0000000..7ab8334 --- /dev/null +++ b/nix/checks/xray-backend-runtime.nix @@ -0,0 +1,127 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkTunConfig, + mkPerAppTunConfig, + shellValueByPrefix, + checkConstants, +}: + +let + fixtures = import ./xray-backend-runtime/fixtures.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + shellValueByPrefix + ; + }; + + inherit (fixtures) + xrayBackendJqFilter + xrayBackendJqFilterFile + xrayDnsLocalClient + xrayDnsRemoteClient + xrayFixture + xrayPerAppTunBackendJqFilterFile + xrayPerAppTunCleanupScript + xrayPerAppTunConfig + xrayPerAppTunConfigJson + xrayPerAppTunStartScript + xrayPerAppTunUpScript + xrayStartBackendJqFilterFile + xrayStartScript + xrayTproxyConfig + xrayTunBackendJqFilterFile + xrayTunConfig + xrayTunConfigJson + xrayTunStartScript + xrayTunUpScript + ; + xrayJqFilterRuntimeCheck = + pkgs.runCommand "proxy-suite-xray-jq-filter-runtime-check" { nativeBuildInputs = [ pkgs.jq ]; } + '' + OBS='[{"protocol":"freedom","tag":"proxy-suite-ob-primary"}]' + + check_runtime() { + local name="$1" + local input="$2" + local output="$TMPDIR/$name.json" + + jq \ + --argjson obs "$OBS" \ + --argjson auth_enabled false \ + --arg user "" \ + --arg password "" \ + --argjson route_enabled true \ + --argjson route_rules '[]' \ + --arg route_final "proxy" \ + --arg dns_final "remote" \ + --argjson clear_dns_rules false \ + --arg xray_loglevel "" \ + --arg xray_bind_interface "eth0" \ + --arg xray_single_proxy_tag "proxy-suite-ob-primary" \ + --argjson xray_tun_dns_runtime true \ + --arg xray_dns_local_client ${pkgs.lib.escapeShellArg xrayDnsLocalClient} \ + --arg xray_dns_remote_client ${pkgs.lib.escapeShellArg xrayDnsRemoteClient} \ + -f ${pkgs.lib.escapeShellArg xrayBackendJqFilterFile} \ + "$input" > "$output" + + jq -e \ + --arg remote ${pkgs.lib.escapeShellArg xrayDnsRemoteClient} \ + --arg local ${pkgs.lib.escapeShellArg xrayDnsLocalClient} \ + ' + type == "object" + and (.dns.servers | length) >= 3 + and .dns.servers[0].tag == "fakedns" + and ([.routing.rules[] | select((.ruleTag? // "") == "dns-hijack")] | length) == 1 + and ([.routing.rules[] | select((.ruleTag? // "") == "dns-upstream-direct")] | length) == 1 + and ([.outbounds[] | select(.tag == "proxy-suite-ob-primary" and (.streamSettings.sockopt.interface? // "") == "eth0")] | length) == 1 + and ([.outbounds[] | select(.tag == "dns-out" and ((.streamSettings.sockopt.interface? // "") == ""))] | length) == 1 + and ([.inbounds[] | select(.tag == "tun-in") | .settings.dns] | length) == 1 + and ([.inbounds[] | select(.tag == "tun-in") | .settings.dns][0] == [$remote, $local]) + and ((.routing | has("balancers")) | not) + and ((has("observatory")) | not) + ' "$output" >/dev/null + } + + check_runtime global ${pkgs.lib.escapeShellArg xrayTunConfigJson} + check_runtime per-app ${pkgs.lib.escapeShellArg xrayPerAppTunConfigJson} + touch "$out" + ''; + + serviceShapeChecks = import ./xray-backend-runtime/service-shape.nix { + inherit + pkgs + xrayFixture + xrayTproxyConfig + xrayStartScript + ; + }; + tunChecks = import ./xray-backend-runtime/tun.nix { + inherit + pkgs + checkConstants + xrayTunConfig + xrayPerAppTunConfig + xrayStartBackendJqFilterFile + xrayTunBackendJqFilterFile + xrayPerAppTunBackendJqFilterFile + xrayStartScript + xrayTunStartScript + xrayTunUpScript + xrayPerAppTunStartScript + xrayPerAppTunUpScript + xrayPerAppTunCleanupScript + xrayBackendJqFilter + ; + }; +in +{ + runtime = xrayJqFilterRuntimeCheck; + + assertions = serviceShapeChecks.assertions ++ tunChecks.assertions; +} diff --git a/nix/checks/xray-backend-runtime/fixtures.nix b/nix/checks/xray-backend-runtime/fixtures.nix new file mode 100644 index 0000000..71a2d9f --- /dev/null +++ b/nix/checks/xray-backend-runtime/fixtures.nix @@ -0,0 +1,119 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkTunConfig, + mkPerAppTunConfig, + shellValueByPrefix, +}: + +let + generated = import ../read-generated.nix; + + 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; + tproxy.perApp.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 = generated.readDerivation ( + xrayFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + xrayTunStartScript = generated.readDerivation ( + xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart + ); + xrayTunUpScript = generated.readDerivation ( + xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStartPost + ); + xrayPerAppTunStartScript = generated.readDerivation ( + xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart + ); + xrayPerAppTunUpScript = generated.readDerivation ( + xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStartPost + ); + xrayPerAppTunCleanupScript = generated.readDerivation ( + xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStopPost + ); + xrayStartBackendJqFilterFile = builtins.unsafeDiscardStringContext ( + shellValueByPrefix xrayStartScript "BACKEND_JQ_FILTER=" + ); + xrayTunBackendJqFilterFile = builtins.unsafeDiscardStringContext ( + shellValueByPrefix xrayTunStartScript "BACKEND_JQ_FILTER=" + ); + xrayPerAppTunBackendJqFilterFile = builtins.unsafeDiscardStringContext ( + shellValueByPrefix xrayPerAppTunStartScript "BACKEND_JQ_FILTER=" + ); + xrayBackendJqFilter = + import ../../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix + { + pureXrayEnabled = true; + selectionMode = xrayFixture.config.services.proxy-suite.proxy.selection; + }; + xrayBackendJqFilterFile = pkgs.writeText "proxy-suite-xray-backend-filter-check.jq" xrayBackendJqFilter; + xrayDnsLocalClient = xrayFixture.config.services.proxy-suite.proxy.dns.local.address; + xrayDnsRemoteClient = xrayFixture.config.services.proxy-suite.proxy.dns.remote.address; + xrayTunConfigJson = pkgs.writeText "proxy-suite-xray-tun-check.json" ( + builtins.toJSON xrayTunConfig + ); + xrayPerAppTunConfigJson = pkgs.writeText "proxy-suite-xray-per-app-tun-check.json" ( + builtins.toJSON xrayPerAppTunConfig + ); +in +{ + inherit + xrayBackendJqFilter + xrayBackendJqFilterFile + xrayDnsLocalClient + xrayDnsRemoteClient + xrayFixture + xrayPerAppTunBackendJqFilterFile + xrayPerAppTunCleanupScript + xrayPerAppTunConfig + xrayPerAppTunConfigJson + xrayPerAppTunStartScript + xrayPerAppTunUpScript + xrayStartBackendJqFilterFile + xrayStartScript + xrayTproxyConfig + xrayTunBackendJqFilterFile + xrayTunConfig + xrayTunConfigJson + xrayTunStartScript + xrayTunUpScript + ; +} diff --git a/nix/checks/xray-backend-runtime/service-shape.nix b/nix/checks/xray-backend-runtime/service-shape.nix new file mode 100644 index 0000000..588c23d --- /dev/null +++ b/nix/checks/xray-backend-runtime/service-shape.nix @@ -0,0 +1,49 @@ +{ + pkgs, + xrayFixture, + xrayTproxyConfig, + xrayStartScript, +}: + +{ + assertions = [ + # -- 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 specificRule.ruleTag == "custom-proxy-domain"; + 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 + ) + ]; +} diff --git a/nix/checks/xray-backend-runtime/tun.nix b/nix/checks/xray-backend-runtime/tun.nix new file mode 100644 index 0000000..4104c43 --- /dev/null +++ b/nix/checks/xray-backend-runtime/tun.nix @@ -0,0 +1,54 @@ +{ + pkgs, + checkConstants, + xrayTunConfig, + xrayPerAppTunConfig, + xrayStartBackendJqFilterFile, + xrayTunBackendJqFilterFile, + xrayPerAppTunBackendJqFilterFile, + xrayStartScript, + xrayTunStartScript, + xrayTunUpScript, + xrayPerAppTunStartScript, + xrayPerAppTunUpScript, + xrayPerAppTunCleanupScript, + xrayBackendJqFilter, +}: + +let + backendFilterChecks = import ./tun/backend-filter.nix { + inherit + pkgs + xrayStartBackendJqFilterFile + xrayTunBackendJqFilterFile + xrayPerAppTunBackendJqFilterFile + xrayStartScript + xrayBackendJqFilter + ; + }; + + globalTunChecks = import ./tun/global.nix { + inherit + pkgs + checkConstants + xrayTunConfig + xrayTunStartScript + xrayTunUpScript + ; + }; + + perAppTunChecks = import ./tun/per-app.nix { + inherit + pkgs + checkConstants + xrayPerAppTunConfig + xrayPerAppTunStartScript + xrayPerAppTunUpScript + xrayPerAppTunCleanupScript + ; + }; +in +{ + assertions = + backendFilterChecks.assertions ++ globalTunChecks.assertions ++ perAppTunChecks.assertions; +} diff --git a/nix/checks/xray-backend-runtime/tun/backend-filter.nix b/nix/checks/xray-backend-runtime/tun/backend-filter.nix new file mode 100644 index 0000000..16c4753 --- /dev/null +++ b/nix/checks/xray-backend-runtime/tun/backend-filter.nix @@ -0,0 +1,35 @@ +{ + pkgs, + xrayStartBackendJqFilterFile, + xrayTunBackendJqFilterFile, + xrayPerAppTunBackendJqFilterFile, + xrayStartScript, + xrayBackendJqFilter, +}: + +{ + assertions = [ + # -- xray backend: shared backend jq filter -- + ( + assert xrayStartBackendJqFilterFile == xrayTunBackendJqFilterFile; + assert xrayTunBackendJqFilterFile == xrayPerAppTunBackendJqFilterFile; + assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" xrayStartScript; + assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' xrayStartScript; + assert pkgs.lib.hasInfix + ''select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts'' + xrayBackendJqFilter; + assert + !(pkgs.lib.hasInfix ''select(.protocol == "socks" and .tag == "mixed-in") | .settings.users'' xrayBackendJqFilter); + assert pkgs.lib.hasInfix "xray_preserved_rules" xrayBackendJqFilter; + assert pkgs.lib.hasInfix "dns-upstream-direct" xrayBackendJqFilter; + assert pkgs.lib.hasInfix "xray_tun_dns_addresses" xrayBackendJqFilter; + assert pkgs.lib.hasInfix "dns-hijack" xrayBackendJqFilter; + assert pkgs.lib.hasInfix ".streamSettings.sockopt.interface = $interface" xrayBackendJqFilter; + assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayBackendJqFilter; + assert pkgs.lib.hasInfix "del(.observatory)" xrayBackendJqFilter; + assert pkgs.lib.hasInfix "xray_rewrite_proxy_rule" xrayBackendJqFilter; + assert pkgs.lib.hasInfix ".protocol == \"dns\"" xrayBackendJqFilter; + true + ) + ]; +} diff --git a/nix/checks/xray-backend-runtime/tun/global.nix b/nix/checks/xray-backend-runtime/tun/global.nix new file mode 100644 index 0000000..ff45dcb --- /dev/null +++ b/nix/checks/xray-backend-runtime/tun/global.nix @@ -0,0 +1,110 @@ +{ + pkgs, + checkConstants, + xrayTunConfig, + xrayTunStartScript, + xrayTunUpScript, +}: + +{ + assertions = [ + # -- xray backend: global TUN runtime config/scripts -- + ( + let + tunInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "tun-in") xrayTunConfig.inbounds + ); + tunDirectOutbound = builtins.head ( + builtins.filter (outbound: outbound.tag == "direct") xrayTunConfig.outbounds + ); + tunDnsOutbound = builtins.head ( + builtins.filter (outbound: outbound.tag == "dns-out") xrayTunConfig.outbounds + ); + tunHasFinalRuleTag = builtins.any ( + rule: (rule ? ruleTag) && rule.ruleTag == "final-default" + ) xrayTunConfig.routing.rules; + tunHasDirectGeositeRule = builtins.any ( + rule: (rule ? ruleTag) && rule.ruleTag == "direct-geosite" + ) xrayTunConfig.routing.rules; + tunHasDnsHijackRule = builtins.any ( + rule: (rule ? ruleTag) && rule.ruleTag == "dns-hijack" + ) xrayTunConfig.routing.rules; + tunHasDnsUpstreamRule = builtins.any ( + rule: (rule ? ruleTag) && rule.ruleTag == "dns-upstream-direct" + ) xrayTunConfig.routing.rules; + in + assert tunInbound.protocol == "tun"; + assert tunInbound.settings.name == "singtun0"; + assert + tunInbound.settings.gateway == [ + "172.19.0.1/30" + checkConstants.xrayGlobalTunIPv6Address + ]; + assert builtins.length tunInbound.settings.dns == 2; + assert tunInbound.settings.autoOutboundsInterface == "auto"; + assert tunInbound.sniffing.destOverride == [ "fakedns" ]; + assert tunInbound.sniffing.metadataOnly == true; + assert xrayTunConfig.routing.domainStrategy == "IPIfNonMatch"; + assert tunHasFinalRuleTag; + assert tunHasDirectGeositeRule; + assert tunHasDnsHijackRule; + assert tunHasDnsUpstreamRule; + assert xrayTunConfig.dns.queryStrategy == "UseIP"; + assert xrayTunConfig.dns.tag == "dns-in"; + assert (builtins.head xrayTunConfig.dns.servers).address == "fakedns"; + assert (builtins.head xrayTunConfig.dns.servers).tag == "fakedns"; + assert (builtins.elemAt xrayTunConfig.dns.servers 1).tag == "remote"; + assert (builtins.elemAt xrayTunConfig.dns.servers 2).tag == "local"; + assert builtins.length xrayTunConfig.fakedns == 2; + assert tunDnsOutbound.protocol == "dns"; + assert + tunDnsOutbound.settings.rules == [ + { + action = "direct"; + qType = "2-27,29-65535"; + } + ]; + assert tunDirectOutbound.streamSettings.sockopt.mark == 2; + assert pkgs.lib.hasInfix "xray-loglevel" xrayTunStartScript; + assert pkgs.lib.hasInfix "XRAY_SINGLE_PROXY_TAG=" xrayTunStartScript; + assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1" xrayTunStartScript; + assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1 mark 2" xrayTunStartScript; + assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" xrayTunStartScript; + assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' xrayTunStartScript; + assert pkgs.lib.hasInfix "xray_tun_dns_runtime" xrayTunStartScript; + assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayTunUpScript; + assert pkgs.lib.hasInfix checkConstants.xrayGlobalTunIPv6Address xrayTunUpScript; + assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayTunUpScript; + assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev singtun0'' xrayTunUpScript; + assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev singtun0'' xrayTunUpScript; + assert pkgs.lib.hasInfix + ''route replace "$tun_route_prefix" dev singtun0 src "$tun_addr" table ${toString checkConstants.tunAutoRouteTableIndex}'' + xrayTunUpScript; + assert pkgs.lib.hasInfix + ''route replace default dev singtun0 src "$uplink_addr" table ${toString checkConstants.tunAutoRouteTableIndex}'' + xrayTunUpScript; + assert pkgs.lib.hasInfix + ''-6 route replace "$tun6_route_prefix" dev singtun0 table ${toString checkConstants.tunAutoRouteTableIndex}'' + xrayTunUpScript; + assert pkgs.lib.hasInfix + "-6 route replace default dev singtun0 table ${toString checkConstants.tunAutoRouteTableIndex}" + xrayTunUpScript; + assert pkgs.lib.hasInfix + "rule add pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority} fwmark 17 table 102" + xrayTunUpScript; + assert pkgs.lib.hasInfix + "rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101" + xrayTunUpScript; + assert pkgs.lib.hasInfix + "rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}" + xrayTunUpScript; + assert pkgs.lib.hasInfix + "-6 rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101" + xrayTunUpScript; + assert pkgs.lib.hasInfix + "-6 rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}" + xrayTunUpScript; + true + ) + ]; +} diff --git a/nix/checks/xray-backend-runtime/tun/per-app.nix b/nix/checks/xray-backend-runtime/tun/per-app.nix new file mode 100644 index 0000000..8ec0dde --- /dev/null +++ b/nix/checks/xray-backend-runtime/tun/per-app.nix @@ -0,0 +1,64 @@ +{ + pkgs, + checkConstants, + xrayPerAppTunConfig, + xrayPerAppTunStartScript, + xrayPerAppTunUpScript, + xrayPerAppTunCleanupScript, +}: + +{ + assertions = [ + # -- xray backend: per-app TUN runtime config/scripts -- + ( + let + perAppTunInbound = builtins.head ( + builtins.filter (inbound: inbound.tag == "tun-in") xrayPerAppTunConfig.inbounds + ); + perAppTunDirectOutbound = builtins.head ( + builtins.filter (outbound: outbound.tag == "direct") xrayPerAppTunConfig.outbounds + ); + in + assert perAppTunInbound.settings.name == "psperapptun0"; + assert + perAppTunInbound.settings.gateway == [ + "172.20.0.1/30" + checkConstants.xrayPerAppTunIPv6Address + ]; + assert builtins.length perAppTunInbound.settings.dns == 2; + assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ]; + assert perAppTunInbound.sniffing.metadataOnly == true; + assert xrayPerAppTunConfig.routing.domainStrategy == "IPIfNonMatch"; + assert (builtins.head xrayPerAppTunConfig.dns.servers).address == "fakedns"; + assert xrayPerAppTunConfig.dns.tag == "dns-in"; + assert builtins.length xrayPerAppTunConfig.fakedns == 2; + assert perAppTunDirectOutbound.streamSettings.sockopt.mark == 2; + assert pkgs.lib.hasInfix "XRAY_SINGLE_PROXY_TAG=" xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1" xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1 mark 2" xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix "--routing-mark 2" xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix "xray_tun_dns_runtime" xrayPerAppTunStartScript; + assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix checkConstants.xrayPerAppTunIPv6Address xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev psperapptun0'' xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix + ''route replace "$tun_route_prefix" dev psperapptun0 src "$tun_addr" table 101'' + xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix ''route replace default dev psperapptun0 src "$uplink_addr" table 101'' + xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix ''-6 route replace "$tun6_route_prefix" dev psperapptun0 table 101'' + xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix "-6 route replace default dev psperapptun0 table 101" + xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix "-6 rule add fwmark 16 table 101" xrayPerAppTunUpScript; + assert pkgs.lib.hasInfix "-4 route flush table 101" xrayPerAppTunCleanupScript; + assert pkgs.lib.hasInfix "-6 route flush table 101" xrayPerAppTunCleanupScript; + assert pkgs.lib.hasInfix "resolvectl flush-caches" xrayPerAppTunCleanupScript; + true + ) + ]; +} diff --git a/nix/checks/xray-backend.nix b/nix/checks/xray-backend.nix new file mode 100644 index 0000000..e96002e --- /dev/null +++ b/nix/checks/xray-backend.nix @@ -0,0 +1,40 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkTunConfig, + mkPerAppTunConfig, + shellValueByPrefix, + mkBadProxySuiteFixture, + mkFailingAssertions, + dnsServerByTag, + checkConstants, +}: + +let + runtimeChecks = import ./xray-backend-runtime.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + shellValueByPrefix + checkConstants + ; + }; + featureChecks = import ./xray-backend-features.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkBadProxySuiteFixture + mkFailingAssertions + dnsServerByTag + ; + }; +in +{ + runtime = runtimeChecks.runtime; + assertions = runtimeChecks.assertions ++ featureChecks.assertions; +} diff --git a/nix/checks/xray-backends.nix b/nix/checks/xray-backends.nix new file mode 100644 index 0000000..2241a11 --- /dev/null +++ b/nix/checks/xray-backends.nix @@ -0,0 +1,43 @@ +{ + pkgs, + evalProxySuite, + mkTProxyConfig, + mkTunConfig, + mkPerAppTunConfig, + shellValueByPrefix, + mkBadProxySuiteFixture, + mkFailingAssertions, + dnsServerByTag, + checkConstants, +}: + +let + xrayChecks = import ./xray-backend.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + shellValueByPrefix + mkBadProxySuiteFixture + mkFailingAssertions + dnsServerByTag + checkConstants + ; + }; + hybridChecks = import ./hybrid-backend.nix { + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkTunConfig + shellValueByPrefix + checkConstants + ; + }; +in +{ + runtime = xrayChecks.runtime; + assertions = hybridChecks.assertions ++ xrayChecks.assertions; +} diff --git a/nix/checks/zapret-hostlist-routing.nix b/nix/checks/zapret-hostlist-routing.nix new file mode 100644 index 0000000..b7d9691 --- /dev/null +++ b/nix/checks/zapret-hostlist-routing.nix @@ -0,0 +1,70 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkRoutingRules, + mkZapretBase, + mkBadFixture, + mkFailingAssertions, + hasDirectDomain, + hasDirectIP, + zapretSyncBase, + zapretSyncExtraListsBase, + zapretSyncNoExtraListsBase, + zapretSpacedConfigAliasBase, + zapretUnspacedConfigAliasBase, +}: + +let + fixtures = import ./zapret-hostlist-routing/fixtures.nix { + inherit + evalProxySuite + baseModule + mkRoutingRules + mkZapretBase + mkBadFixture + mkFailingAssertions + ; + }; + inherit (fixtures) + zapretHostlistRules + zapretHostlistBase + invalidHostlistAssertions + ; + + zapretHostlistChecks = import ./zapret-hostlist.nix { + inherit + pkgs + zapretSyncBase + zapretSyncExtraListsBase + zapretSyncNoExtraListsBase + zapretSpacedConfigAliasBase + zapretUnspacedConfigAliasBase + zapretHostlistBase + ; + }; +in +{ + inherit (zapretHostlistChecks) rules; + + assertions = [ + ( + assert hasDirectDomain zapretHostlistRules "googlevideo.com"; + assert hasDirectDomain zapretHostlistRules "example.com"; + assert !(hasDirectDomain zapretHostlistRules "x.example"); + true + ) + ( + assert hasDirectDomain zapretHostlistRules "youtube.com"; + assert hasDirectDomain zapretHostlistRules "discord.com"; + assert hasDirectDomain zapretHostlistRules "cloudflare-ech.com"; + true + ) + ( + assert hasDirectIP zapretHostlistRules "203.0.113.0/24"; + assert !(hasDirectIP zapretHostlistRules "1.1.1.0/24"); + true + ) + ] + ++ invalidHostlistAssertions; +} diff --git a/nix/checks/zapret-hostlist-routing/fixtures.nix b/nix/checks/zapret-hostlist-routing/fixtures.nix new file mode 100644 index 0000000..67f78d6 --- /dev/null +++ b/nix/checks/zapret-hostlist-routing/fixtures.nix @@ -0,0 +1,163 @@ +{ + evalProxySuite, + baseModule, + mkRoutingRules, + mkZapretBase, + mkBadFixture, + mkFailingAssertions, +}: + +let + zapretHostlistRulesFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.zapret = { + enable = true; + hostlistRules = [ + { + name = "googlevideo"; + domains = [ + "googlevideo.com" + "ggpht.com" + ]; + preset = "google"; + } + { + name = "example"; + domains = [ + "example.com" + "example.de" + ]; + nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake,multisplit" ]; + } + { + name = "twitter-no-direct"; + domains = [ "x.example" ]; + nfqwsArgs = [ "--filter-udp=443 --dpi-desync=fake --dpi-desync-repeats=6" ]; + enableDirectSync = false; + } + { + name = "google-general"; + defaultDomains = [ "google" ]; + configName = "general"; + } + { + name = "general-alt12"; + defaultDomains = [ "general" ]; + configName = "general (ALT12)"; + } + { + name = "youtube-alias"; + defaultDomains = [ "youtube" ]; + configName = "general"; + enableDirectSync = false; + } + { + name = "discord-alias"; + defaultDomains = [ "discord" ]; + configName = "general (ALT12)"; + enableDirectSync = false; + } + { + name = "upstream-ips"; + defaultIps = [ "all" ]; + configName = "general"; + enableDirectSync = false; + } + { + name = "explicit-ips"; + ips = [ "203.0.113.0/24" ]; + configName = "general"; + } + ]; + }; + } + ]; + zapretHostlistRules = mkRoutingRules zapretHostlistRulesFixture; + zapretHostlistBase = mkZapretBase zapretHostlistRulesFixture; + + invalidHostlistAssertions = mkFailingAssertions mkBadFixture [ + [ + { + services.proxy-suite.zapret = { + enable = true; + hostlistRules = [ + { + name = "dup"; + domains = [ "one.example" ]; + nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; + } + { + name = "dup"; + domains = [ "two.example" ]; + nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; + } + ]; + }; + } + ] + [ + { + services.proxy-suite.zapret = { + enable = true; + hostlistRules = [ + { + name = "empty"; + domains = [ ]; + nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; + } + ]; + }; + } + ] + [ + { + services.proxy-suite.zapret = { + enable = true; + hostlistRules = [ + { + name = "missing"; + domains = [ "missing.example" ]; + } + ]; + }; + } + ] + [ + { + services.proxy-suite.zapret = { + enable = true; + hostlistRules = [ + { + name = "conflict"; + defaultDomains = [ "google" ]; + configName = "general"; + nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ]; + } + ]; + }; + } + ] + [ + { + services.proxy-suite.zapret = { + enable = true; + hostlistRules = [ + { + name = "missing-family"; + domains = [ "example.com" ]; + configName = "general"; + } + ]; + }; + } + ] + ]; +in +{ + inherit + zapretHostlistRules + zapretHostlistBase + invalidHostlistAssertions + ; +} diff --git a/nix/checks/zapret-hostlist.nix b/nix/checks/zapret-hostlist.nix new file mode 100644 index 0000000..b56c7e0 --- /dev/null +++ b/nix/checks/zapret-hostlist.nix @@ -0,0 +1,55 @@ +{ + pkgs, + zapretSyncBase, + zapretSyncExtraListsBase, + zapretSyncNoExtraListsBase, + zapretSpacedConfigAliasBase, + zapretUnspacedConfigAliasBase, + zapretHostlistBase, +}: + +{ + rules = pkgs.runCommand "proxy-suite-zapret-hostlist-rules-check" { } '' + grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-twitter.txt"' "${zapretSyncExtraListsBase}/config" + grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-instagram.txt"' "${zapretSyncExtraListsBase}/config" + grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-soundcloud.txt"' "${zapretSyncExtraListsBase}/config" + ! grep -F -- '--hostlist="${zapretSyncBase}/hostlists/list-twitter.txt"' "${zapretSyncBase}/config" + ! grep -F -- '--hostlist="${zapretSyncBase}/hostlists/list-instagram.txt"' "${zapretSyncBase}/config" + ! grep -F -- '--hostlist="${zapretSyncBase}/hostlists/list-soundcloud.txt"' "${zapretSyncBase}/config" + test -f "${zapretSpacedConfigAliasBase}/config" + test -f "${zapretUnspacedConfigAliasBase}/config" + ! grep -F -- '--hostlist="${zapretSyncNoExtraListsBase}/hostlists/list-twitter.txt"' "${zapretSyncNoExtraListsBase}/config" + ! grep -F -- '--hostlist="${zapretSyncNoExtraListsBase}/hostlists/list-instagram.txt"' "${zapretSyncNoExtraListsBase}/config" + ! grep -F -- '--hostlist="${zapretSyncNoExtraListsBase}/hostlists/list-soundcloud.txt"' "${zapretSyncNoExtraListsBase}/config" + grep -F 'googlevideo.com' "${zapretHostlistBase}/hostlists/list-googlevideo.txt" + grep -F 'example.de' "${zapretHostlistBase}/hostlists/list-example.txt" + grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-googlevideo.txt"' "${zapretHostlistBase}/config" + grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-example.txt"' "${zapretHostlistBase}/config" + grep -F -- '--filter-tcp=443 --dpi-desync=fake,multisplit --hostlist="${zapretHostlistBase}/hostlists/list-example.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude-user.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude-user.txt" --new' "${zapretHostlistBase}/config" + grep -F 'youtube.com' "${zapretHostlistBase}/hostlists/list-google-general.txt" + grep -F 'googlevideo.com' "${zapretHostlistBase}/hostlists/list-google-general.txt" + grep -F 'discord.com' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" + grep -F 'discord.gg' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" + grep -F 'cloudflare-ech.com' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" + grep -F 'cloudfront.net' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" + grep -F '7tv.app' "${zapretHostlistBase}/hostlists/list-general-alt12.txt" + cmp "${zapretHostlistBase}/hostlists/list-google-general.txt" "${zapretHostlistBase}/hostlists/list-youtube-alias.txt" + cmp "${zapretHostlistBase}/hostlists/list-general-alt12.txt" "${zapretHostlistBase}/hostlists/list-discord-alias.txt" + grep -F '1.1.1.0/24' "${zapretHostlistBase}/hostlists/ipset-upstream-ips.txt" + grep -F '203.0.113.0/24' "${zapretHostlistBase}/hostlists/ipset-explicit-ips.txt" + grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-google-general.txt"' "${zapretHostlistBase}/config" + grep -F -- '--dpi-desync=multisplit --dpi-desync-split-seqovl=681' "${zapretHostlistBase}/config" + grep -F -- '--ipset="${zapretHostlistBase}/hostlists/ipset-upstream-ips.txt"' "${zapretHostlistBase}/config" + grep -F -- '--ipset="${zapretHostlistBase}/hostlists/ipset-explicit-ips.txt"' "${zapretHostlistBase}/config" + google_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-google-general.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) + default_google_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-google.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) + general_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-general-alt12.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) + default_general_rule_line=$(grep -nF -- '--hostlist="${zapretHostlistBase}/hostlists/list-general.txt"' "${zapretHostlistBase}/config" | head -n1 | cut -d: -f1) + discord_voice_rule_line=$(grep -nF -- '--filter-l7=discord,stun' "${zapretHostlistBase}/config" | grep -F -- '--dpi-desync-repeats=3' | head -n1 | cut -d: -f1) + default_voice_rule_line=$(grep -nF -- '--filter-l7=discord,stun' "${zapretHostlistBase}/config" | grep -F -- '--dpi-desync-repeats=6' | head -n1 | cut -d: -f1) + test "$google_rule_line" -lt "$default_google_rule_line" + test "$general_rule_line" -lt "$default_general_rule_line" + test "$discord_voice_rule_line" -lt "$default_voice_rule_line" + touch "$out" + ''; +} diff --git a/nix/checks/zapret.nix b/nix/checks/zapret.nix new file mode 100644 index 0000000..61273eb --- /dev/null +++ b/nix/checks/zapret.nix @@ -0,0 +1,106 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkRoutingRules, + mkZapretBase, + mkBadFixture, + mkFailingAssertions, + hasDirectDomain, + hasDirectIP, +}: + +let + fixtures = import ./zapret/fixtures.nix { + inherit + evalProxySuite + baseModule + mkRoutingRules + mkZapretBase + ; + }; + inherit (fixtures) + zapretSyncService + zapretSyncRules + zapretSyncBase + zapretSpacedConfigAliasBase + zapretUnspacedConfigAliasBase + zapretSyncNoExtraListsBase + zapretSyncNoExtraListsRules + zapretSyncExtraListsBase + zapretSyncExtraListsRules + zapretSyncIpsRules + zapretSyncUserIpsDisabledRules + zapretSyncDisabledRules + zapretSyncDomainsOnlyRules + zapretExtrasRules + zapretIpExtrasRules + zapretExcludesRules + zapretIpExcludesRules + ; + + zapretHostlistRoutingChecks = import ./zapret-hostlist-routing.nix { + inherit + pkgs + evalProxySuite + baseModule + mkRoutingRules + mkZapretBase + mkBadFixture + mkFailingAssertions + hasDirectDomain + hasDirectIP + zapretSyncBase + zapretSyncExtraListsBase + zapretSyncNoExtraListsBase + zapretSpacedConfigAliasBase + zapretUnspacedConfigAliasBase + ; + }; +in +{ + inherit (zapretHostlistRoutingChecks) rules; + syncService = zapretSyncService; + + assertions = [ + ( + assert hasDirectDomain zapretSyncRules "discord.com"; + assert hasDirectDomain zapretSyncRules "youtube.com"; + assert hasDirectDomain zapretSyncRules "cloudflare-ech.com"; + assert !(hasDirectDomain zapretSyncRules "twitter.com"); + assert !(hasDirectIP zapretSyncRules "1.1.1.0/24"); + true + ) + ( + assert hasDirectDomain zapretSyncDomainsOnlyRules "cloudflare-ech.com"; + assert !(hasDirectIP zapretSyncDomainsOnlyRules "1.1.1.0/24"); + true + ) + ( + assert hasDirectIP zapretSyncIpsRules "1.1.1.0/24"; + assert !(hasDirectIP zapretSyncUserIpsDisabledRules "203.0.113.0/24"); + true + ) + ( + assert !(hasDirectDomain zapretSyncNoExtraListsRules "twitter.com"); + assert hasDirectDomain zapretSyncExtraListsRules "twitter.com"; + true + ) + ( + assert !(hasDirectDomain zapretSyncDisabledRules "discord.com"); + assert !(hasDirectIP zapretSyncDisabledRules "1.1.1.0/24"); + true + ) + ( + assert hasDirectDomain zapretExtrasRules "pixiv.net"; + assert hasDirectIP zapretIpExtrasRules "203.0.113.0/24"; + true + ) + ( + assert !(hasDirectDomain zapretExcludesRules "discord.com"); + assert !(hasDirectIP zapretIpExcludesRules "1.1.1.0/24"); + true + ) + ] + ++ zapretHostlistRoutingChecks.assertions; +} diff --git a/nix/checks/zapret/fixtures.nix b/nix/checks/zapret/fixtures.nix new file mode 100644 index 0000000..fd4aae9 --- /dev/null +++ b/nix/checks/zapret/fixtures.nix @@ -0,0 +1,101 @@ +{ + evalProxySuite, + baseModule, + mkRoutingRules, + mkZapretBase, +}: + +let + evalZapret = + zapretConfig: + evalProxySuite [ + baseModule + { + services.proxy-suite.zapret = { + enable = true; + } + // zapretConfig; + } + ]; + + zapretSyncFixture = evalZapret { }; + zapretSyncService = zapretSyncFixture.config.systemd.services."zapret-discord-youtube"; + zapretSyncRules = mkRoutingRules zapretSyncFixture; + zapretSyncBase = mkZapretBase zapretSyncFixture; + + zapretSpacedConfigAliasBase = mkZapretBase (evalZapret { + configName = "general(ALT12)"; + }); + + zapretUnspacedConfigAliasBase = mkZapretBase (evalZapret { + configName = "general (ALT)"; + }); + + zapretSyncNoExtraListsFixture = evalZapret { + includeExtraUpstreamLists = false; + }; + zapretSyncNoExtraListsBase = mkZapretBase zapretSyncNoExtraListsFixture; + zapretSyncNoExtraListsRules = mkRoutingRules zapretSyncNoExtraListsFixture; + + zapretSyncExtraListsFixture = evalZapret { + includeExtraUpstreamLists = true; + }; + zapretSyncExtraListsBase = mkZapretBase zapretSyncExtraListsFixture; + zapretSyncExtraListsRules = mkRoutingRules zapretSyncExtraListsFixture; + + zapretSyncIpsRules = mkRoutingRules (evalZapret { + syncDirectRoutingUpstreamIps = true; + }); + + zapretSyncUserIpsDisabledRules = mkRoutingRules (evalZapret { + syncDirectRoutingUserIps = false; + ipsetAll = [ "203.0.113.0/24" ]; + }); + + zapretSyncDisabledRules = mkRoutingRules (evalZapret { + syncDirectRouting = false; + }); + + zapretSyncDomainsOnlyRules = mkRoutingRules (evalZapret { + syncDirectRouting = true; + syncDirectRoutingUpstreamIps = false; + }); + + zapretExtrasRules = mkRoutingRules (evalZapret { + listGeneral = [ "pixiv.net" ]; + }); + + zapretIpExtrasRules = mkRoutingRules (evalZapret { + ipsetAll = [ "203.0.113.0/24" ]; + }); + + zapretExcludesRules = mkRoutingRules (evalZapret { + listExclude = [ "discord.com" ]; + }); + + zapretIpExcludesRules = mkRoutingRules (evalZapret { + ipsetExclude = [ "1.1.1.0/24" ]; + ipsetAll = [ "1.1.1.0/24" ]; + }); +in +{ + inherit + zapretSyncService + zapretSyncRules + zapretSyncBase + zapretSpacedConfigAliasBase + zapretUnspacedConfigAliasBase + zapretSyncNoExtraListsBase + zapretSyncNoExtraListsRules + zapretSyncExtraListsBase + zapretSyncExtraListsRules + zapretSyncIpsRules + zapretSyncUserIpsDisabledRules + zapretSyncDisabledRules + zapretSyncDomainsOnlyRules + zapretExtrasRules + zapretIpExtrasRules + zapretExcludesRules + zapretIpExcludesRules + ; +} diff --git a/nix/options-doc.nix b/nix/options-doc.nix index a086a5c..7700ed8 100644 --- a/nix/options-doc.nix +++ b/nix/options-doc.nix @@ -25,20 +25,18 @@ let config: builtins.removeAttrs config [ "singBox" ] // { - proxy = - (config.proxy or { }) - // { - singBox = - ((config.proxy or { }).singBox or { }) - // lib.optionalAttrs (((config.proxy or { }).singBox or { }) ? package) { - package = singBoxPackagePlaceholder; - }; - xray = - ((config.proxy or { }).xray or { }) - // lib.optionalAttrs (((config.proxy or { }).xray or { }) ? package) { - package = xrayPackagePlaceholder; - }; - }; + proxy = (config.proxy or { }) // { + singBox = + ((config.proxy or { }).singBox or { }) + // lib.optionalAttrs (((config.proxy or { }).singBox or { }) ? package) { + package = singBoxPackagePlaceholder; + }; + xray = + ((config.proxy or { }).xray or { }) + // lib.optionalAttrs (((config.proxy or { }).xray or { }) ? package) { + package = xrayPackagePlaceholder; + }; + }; }; renderConfigText = config: @@ -51,9 +49,7 @@ let "pkgs.sing-box" "pkgs.xray" ] - ( - lib.generators.toPretty { } (sanitizeConfigForDocs config) - ); + (lib.generators.toPretty { } (sanitizeConfigForDocs config)); mkGeneratedExampleValue = option: if (option ? _type) && option._type == "option" then @@ -68,8 +64,9 @@ let else lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option); defaultConfigText = renderConfigText eval.config.services.proxy-suite; - generatedExampleConfig = - lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite); + generatedExampleConfig = lib.mapAttrs (_: mkGeneratedExampleValue) ( + filterGeneratedOptions eval.options.services.proxy-suite + ); exampleConfigText = renderConfigText (builtins.removeAttrs generatedExampleConfig [ "singBox" ]); repoRoot = toString ../.; repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main"; @@ -98,189 +95,11 @@ let transformOptions = opt: opt // { declarations = map transformDeclaration opt.declarations; }; }; in -pkgs.runCommand "proxy-suite-options.md" { } '' - preamble="$TMPDIR/preamble.md" - sections="$TMPDIR/sections.md" - sections_with_anchors="$TMPDIR/sections-with-anchors.md" - section_index="$TMPDIR/sections-index.tsv" - toc="$TMPDIR/toc.md" - - cat >"$preamble" <<'EOF' - # proxy-suite options - - This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options/default.nix`](/modules/proxy-suite/options/default.nix). - Update module option docs there instead of editing this file by hand. - - ## Table of contents - - EOF - - cat >"$sections" <<'EOF' - ## Complete default config - - ```nix - services.proxy-suite = ${defaultConfigText}; - ``` - - ## Complete example config - - This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options. - - ```nix - services.proxy-suite = ${exampleConfigText}; - ``` - - EOF - - cat ${optionDocs.optionsCommonMark} >>"$sections" - - : >"$section_index" - : >"$sections_with_anchors" - awk -v section_index="$section_index" -v out="$sections_with_anchors" ' - function slugify(text, slug) { - slug = text - gsub(/\\/, "", slug) - slug = tolower(slug) - gsub(/[^a-z0-9]+/, "-", slug) - sub(/^-+/, "", slug) - sub(/-+$/, "", slug) - return slug - } - - /^## / { - title = substr($0, 4) - base = slugify(title) - count = seen[base] - seen[base]++ - slug = count == 0 ? base : base "-" count - - print title "\t" slug >> section_index - print "" >> out - } - - { - print >> out - } - ' "$sections" - - : >"$toc" - awk -F '\t' -v toc="$toc" ' - function addChild(parent, child, key) { - key = parent SUBSEP child - if (!(key in seenChild)) { - seenChild[key] = 1 - childCount[parent]++ - childOrder[parent, childCount[parent]] = child - } - } - - function indent(depth, i, prefix) { - prefix = "" - for (i = 0; i < depth; i++) { - prefix = prefix " " - } - return prefix - } - - function displayLabel(label) { - if (label == "*") { - return "item" - } - return label - } - - function printNode(path, label, depth, i, child, childPath, text) { - text = displayLabel(label) - if (path in slugByPath) { - text = "[" text "](#" slugByPath[path] ")" - } - - print indent(depth) "- " text >> toc - - for (i = 1; i <= childCount[path]; i++) { - child = childOrder[path, i] - childPath = path "." child - printNode(childPath, child, depth + 1) - } - } - - { - title = $1 - slug = $2 - normalized = title - gsub(/\\/, "", normalized) - - if (normalized ~ /^Complete /) { - sampleCount++ - sampleTitle[sampleCount] = title - sampleSlug[sampleCount] = slug - next - } - - if (index(normalized, "services.proxy-suite") == 1) { - optionRootSeen = 1 - slugByPath[normalized] = slug - - count = split(normalized, parts, /\./) - if (count < 3) { - next - } - - parent = "services.proxy-suite" - for (i = 3; i <= count; i++) { - child = parts[i] - addChild(parent, child) - parent = parent "." child - } - next - } - - otherCount++ - otherTitle[otherCount] = title - otherSlug[otherCount] = slug - } - - END { - if (sampleCount > 0) { - print "- Config samples" >> toc - for (i = 1; i <= sampleCount; i++) { - print " - [" sampleTitle[i] "](#" sampleSlug[i] ")" >> toc - } - } - - if (optionRootSeen) { - print "- services.proxy-suite" >> toc - for (i = 1; i <= childCount["services.proxy-suite"]; i++) { - child = childOrder["services.proxy-suite", i] - printNode("services.proxy-suite." child, child, 1) - } - } - - for (i = 1; i <= otherCount; i++) { - print "- [" otherTitle[i] "](#" otherSlug[i] ")" >> toc - } - } - ' "$section_index" - - raw="$TMPDIR/options.md.raw" - - cat "$preamble" >"$raw" - cat "$toc" >>"$raw" - printf '\n' >>"$raw" - cat "$sections_with_anchors" >>"$raw" - - awk ' - NF { - for (i = 0; i < blanks; i++) { - print "" - } - blanks = 0 - print - next - } - - { - blanks++ - } - ' "$raw" >"$out" -'' +import ./options-doc/render-options-markdown.nix { + inherit + pkgs + optionDocs + defaultConfigText + exampleConfigText + ; +} diff --git a/nix/options-doc/render-options-markdown.nix b/nix/options-doc/render-options-markdown.nix new file mode 100644 index 0000000..f42a9bc --- /dev/null +++ b/nix/options-doc/render-options-markdown.nix @@ -0,0 +1,193 @@ +{ + pkgs, + optionDocs, + defaultConfigText, + exampleConfigText, +}: + +pkgs.runCommand "proxy-suite-options.md" { } '' + preamble="$TMPDIR/preamble.md" + sections="$TMPDIR/sections.md" + sections_with_anchors="$TMPDIR/sections-with-anchors.md" + section_index="$TMPDIR/sections-index.tsv" + toc="$TMPDIR/toc.md" + + cat >"$preamble" <<'EOF' + # proxy-suite options + + This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options/default.nix`](/modules/proxy-suite/options/default.nix). + Update module option docs there instead of editing this file by hand. + + ## Table of contents + + EOF + + cat >"$sections" <<'EOF' + ## Complete default config + + ```nix + services.proxy-suite = ${defaultConfigText}; + ``` + + ## Complete example config + + This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options. + + ```nix + services.proxy-suite = ${exampleConfigText}; + ``` + + EOF + + cat ${optionDocs.optionsCommonMark} >>"$sections" + + : >"$section_index" + : >"$sections_with_anchors" + awk -v section_index="$section_index" -v out="$sections_with_anchors" ' + function slugify(text, slug) { + slug = text + gsub(/\\/, "", slug) + slug = tolower(slug) + gsub(/[^a-z0-9]+/, "-", slug) + sub(/^-+/, "", slug) + sub(/-+$/, "", slug) + return slug + } + + /^## / { + title = substr($0, 4) + base = slugify(title) + count = seen[base] + seen[base]++ + slug = count == 0 ? base : base "-" count + + print title "\t" slug >> section_index + print "" >> out + } + + { + print >> out + } + ' "$sections" + + : >"$toc" + awk -F '\t' -v toc="$toc" ' + function addChild(parent, child, key) { + key = parent SUBSEP child + if (!(key in seenChild)) { + seenChild[key] = 1 + childCount[parent]++ + childOrder[parent, childCount[parent]] = child + } + } + + function indent(depth, i, prefix) { + prefix = "" + for (i = 0; i < depth; i++) { + prefix = prefix " " + } + return prefix + } + + function displayLabel(label) { + if (label == "*") { + return "item" + } + return label + } + + function printNode(path, label, depth, i, child, childPath, text) { + text = displayLabel(label) + if (path in slugByPath) { + text = "[" text "](#" slugByPath[path] ")" + } + + print indent(depth) "- " text >> toc + + for (i = 1; i <= childCount[path]; i++) { + child = childOrder[path, i] + childPath = path "." child + printNode(childPath, child, depth + 1) + } + } + + { + title = $1 + slug = $2 + normalized = title + gsub(/\\/, "", normalized) + + if (normalized ~ /^Complete /) { + sampleCount++ + sampleTitle[sampleCount] = title + sampleSlug[sampleCount] = slug + next + } + + if (index(normalized, "services.proxy-suite") == 1) { + optionRootSeen = 1 + slugByPath[normalized] = slug + + count = split(normalized, parts, /\./) + if (count < 3) { + next + } + + parent = "services.proxy-suite" + for (i = 3; i <= count; i++) { + child = parts[i] + addChild(parent, child) + parent = parent "." child + } + next + } + + otherCount++ + otherTitle[otherCount] = title + otherSlug[otherCount] = slug + } + + END { + if (sampleCount > 0) { + print "- Config samples" >> toc + for (i = 1; i <= sampleCount; i++) { + print " - [" sampleTitle[i] "](#" sampleSlug[i] ")" >> toc + } + } + + if (optionRootSeen) { + print "- services.proxy-suite" >> toc + for (i = 1; i <= childCount["services.proxy-suite"]; i++) { + child = childOrder["services.proxy-suite", i] + printNode("services.proxy-suite." child, child, 1) + } + } + + for (i = 1; i <= otherCount; i++) { + print "- [" otherTitle[i] "](#" otherSlug[i] ")" >> toc + } + } + ' "$section_index" + + raw="$TMPDIR/options.md.raw" + + cat "$preamble" >"$raw" + cat "$toc" >>"$raw" + printf '\n' >>"$raw" + cat "$sections_with_anchors" >>"$raw" + + awk ' + NF { + for (i = 0; i < blanks; i++) { + print "" + } + blanks = 0 + print + next + } + + { + blanks++ + } + ' "$raw" >"$out" +'' diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 53fd974..35afba8 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -24,11 +24,36 @@ let unwrapped = pkgs.writeShellScriptBin "proxy-ctl" ( builtins.readFile ./proxy-ctl-lib.sh + "\n" + builtins.readFile ./proxy-ctl.sh ); + wrapperEnv = { + CLASH_API = clashApi; + SELECTION = selection; + SUB_TAGS_FILE = toString subscriptionTagsFile; + SUB_CACHE_DIR = subscriptionCacheDir; + PER_APP_ROUTING_ENABLED = perAppRoutingEnabled; + PER_APP_ROUTING_PROXYCHAINS_ENABLED = perAppRoutingProxychainsEnabled; + PER_APP_ROUTING_TUN_ENABLED = perAppRoutingTunEnabled; + PER_APP_ROUTING_TPROXY_ENABLED = perAppRoutingTproxyEnabled; + PER_APP_ROUTING_ZAPRET_ENABLED = perAppRoutingZapretEnabled; + PER_APP_ROUTING_PROFILES_FILE = toString perAppRoutingProfilesFile; + PROXYCHAINS_CONFIG = toString proxychainsConfigFile; + PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg; + ROUTE_MODE_STATE_FILE = routeModeStateFile; + DEFAULT_ROUTE_MODE = defaultRouteMode; + }; in pkgs.symlinkJoin { name = "proxy-ctl"; paths = [ unwrapped ]; nativeBuildInputs = [ pkgs.makeWrapper ]; + passthru.proxySuiteCheck = { + inherit + wrapperEnv + subscriptionTagsFile + perAppRoutingProfilesFile + proxychainsConfigFile + ; + script = unwrapped.drvAttrs.text; + }; postBuild = '' wrapProgram "$out/bin/proxy-ctl" \ --prefix PATH : "${