fix: attempt to mitigate client<-server dropped packages

This commit is contained in:
FUFSoB committed 2026-06-18 20:15:05 +05:00
1 parent ce86e5669b
commit 5b5598d12e
14 files changed
+1271 -452

No files matched your search

+44 -5
View File
@@ -39,6 +39,7 @@ Update module option docs there instead of editing this file by hand.
- [listenAddress](#services-proxy-suite-proxy-listenaddress) - [listenAddress](#services-proxy-suite-proxy-listenaddress)
- [outbounds](#services-proxy-suite-proxy-outbounds) - [outbounds](#services-proxy-suite-proxy-outbounds)
- item - item
- [backend](#services-proxy-suite-proxy-outbounds-backend)
- routing - routing
- [domains](#services-proxy-suite-proxy-outbounds-routing-domains) - [domains](#services-proxy-suite-proxy-outbounds-routing-domains)
- [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips) - [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips)
@@ -978,8 +979,10 @@ true
Whether to configure and run the proxy backend services\. Whether to configure and run the proxy backend services\.
This is disabled by default; enable it explicitly and choose exactly This is disabled by default; enable it explicitly and choose at least
one backend with proxy\.singBox\.enable or proxy\.xray\.enable\. one backend with proxy\.singBox\.enable or proxy\.xray\.enable\. Enabling
both runs sing-box as the frontend and XRay as a sidecar for outbounds
that require XRay\.
@@ -1470,6 +1473,42 @@ list of (submodule)
<a id="services-proxy-suite-proxy-outbounds-backend"></a>
## services\.proxy-suite\.proxy\.outbounds\.\*\.backend
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\.
*Type:*
one of “auto”, “sing-box”, “xray”
*Default:*
```nix
"auto"
```
*Example:*
```nix
"xray"
```
*Declared by:*
- [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix)
<a id="services-proxy-suite-proxy-outbounds-routing-domains"></a> <a id="services-proxy-suite-proxy-outbounds-routing-domains"></a>
## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.domains ## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.domains
@@ -4217,8 +4256,6 @@ null
<a id="services-proxy-suite-tray-enable"></a> <a id="services-proxy-suite-tray-enable"></a>
## services\.proxy-suite\.tray\.enable ## services\.proxy-suite\.tray\.enable
Whether to enable system tray indicator for proxy-suite\. Whether to enable system tray indicator for proxy-suite\.
@@ -4284,6 +4321,8 @@ true
<a id="services-proxy-suite-tray-pollinterval"></a> <a id="services-proxy-suite-tray-pollinterval"></a>
## services\.proxy-suite\.tray\.pollInterval ## services\.proxy-suite\.tray\.pollInterval
Tray status refresh interval in seconds\. Tray status refresh interval in seconds\.
Lower values make UI state changes appear faster, while higher values Lower values make UI state changes appear faster, while higher values
reduce background polling overhead\. reduce background polling overhead\.
@@ -4453,6 +4492,7 @@ true
- [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix)
<a id="services-proxy-suite-zapret-cidrexemption-enable"></a> <a id="services-proxy-suite-zapret-cidrexemption-enable"></a>
## services\.proxy-suite\.zapret\.cidrExemption\.enable ## services\.proxy-suite\.zapret\.cidrExemption\.enable
@@ -5199,4 +5239,3 @@ true
*Declared by:* *Declared by:*
- [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix)
+37 -22
View File
@@ -13,6 +13,8 @@ let
proxyCfg proxyCfg
singBoxCfg singBoxCfg
xrayEnabled xrayEnabled
hybridEnabled
pureXrayEnabled
globalTun globalTun
globalTproxy globalTproxy
clashApiEnabled clashApiEnabled
@@ -88,6 +90,8 @@ let
forceLocalDnsViaProxy ? false, forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false, useOutboundRoutingMark ? false,
enableClashApi ? clashApiEnabled, enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? 18533,
}: }:
{ {
log.level = "warn"; log.level = "warn";
@@ -97,7 +101,13 @@ let
}; };
inbounds = inbounds =
lib.optional enableMixed { lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed"; type = "mixed";
tag = "mixed-in"; tag = "mixed-in";
listen = proxyCfg.listenAddress; listen = proxyCfg.listenAddress;
@@ -154,20 +164,14 @@ let
// lib.optionalAttrs enableClashApi clashApiBlock; // lib.optionalAttrs enableClashApi clashApiBlock;
xrayDnsAddress = xrayDnsAddress =
upstream: upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
if upstream.type == "tcp" then
"tcp://${upstream.address}"
else
upstream.address;
mkXrayDnsServer = mkXrayDnsServer = tag: upstream: {
tag: upstream: address = xrayDnsAddress upstream;
{ inherit tag;
address = xrayDnsAddress upstream; port = upstream.port;
inherit tag; queryStrategy = "UseIP";
port = upstream.port; };
queryStrategy = "UseIP";
};
mkXraySniffing = mkXraySniffing =
{ {
@@ -245,8 +249,9 @@ let
{ outboundTag = tag; } { outboundTag = tag; }
); );
xrayRouteRules = xrayRouteRules = rules.xrayRoutingRules ++ [
rules.xrayRoutingRules ++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ]; (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct"))
];
xrayDirectOutbound = xrayDirectOutbound =
useOutboundRoutingMark: useOutboundRoutingMark:
@@ -371,7 +376,9 @@ let
{ {
tag = "proxy"; tag = "proxy";
selector = [ "proxy-suite-ob-" ]; selector = [ "proxy-suite-ob-" ];
strategy = { type = "leastPing"; }; strategy = {
type = "leastPing";
};
} }
]; ];
}; };
@@ -389,6 +396,7 @@ let
enableMixed = true; enableMixed = true;
enableTProxy = true; enableTProxy = true;
useOutboundRoutingMark = true; useOutboundRoutingMark = true;
xrayDnsBridgePort = 18533;
}; };
singBoxTunTemplate = mkSingBoxConfig { singBoxTunTemplate = mkSingBoxConfig {
@@ -401,6 +409,7 @@ let
tunStrictRoute = true; tunStrictRoute = true;
forceLocalDnsViaProxy = false; forceLocalDnsViaProxy = false;
enableClashApi = false; enableClashApi = false;
xrayDnsBridgePort = 18534;
}; };
singBoxPerAppTunTemplate = mkSingBoxConfig { singBoxPerAppTunTemplate = mkSingBoxConfig {
@@ -414,6 +423,7 @@ let
forceLocalDnsViaProxy = false; forceLocalDnsViaProxy = false;
useOutboundRoutingMark = globalTproxy.enable; useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false; enableClashApi = false;
xrayDnsBridgePort = 18535;
}; };
xrayTproxyTemplate = mkXrayConfig { xrayTproxyTemplate = mkXrayConfig {
@@ -442,10 +452,10 @@ let
enableTunFakeDns = true; enableTunFakeDns = true;
}; };
tproxyTemplate = if xrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate; tproxyTemplate = if pureXrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate;
tunTemplate = if xrayEnabled then xrayTunTemplate else singBoxTunTemplate; tunTemplate = if pureXrayEnabled then xrayTunTemplate else singBoxTunTemplate;
perAppTunTemplate = if xrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate; perAppTunTemplate = if pureXrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate;
routeModeRules = if xrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules; routeModeRules = if pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate); tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate); tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
@@ -458,5 +468,10 @@ let
in in
{ {
inherit tproxyFile tunFile perAppTunFile routeModeRulesFile; inherit
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
;
} }
+18 -10
View File
@@ -5,22 +5,27 @@
let let
proxyCfg = cfg.proxy; proxyCfg = cfg.proxy;
singBoxCfg = singBoxCfg = proxyCfg // {
proxyCfg enable = proxyCfg.enable && proxyCfg.singBox.enable;
// { package = proxyCfg.singBox.package;
enable = proxyCfg.enable && proxyCfg.singBox.enable; clashApiPort = proxyCfg.singBox.clashApiPort;
package = proxyCfg.singBox.package; urlTest = proxyCfg.urlTest // {
clashApiPort = proxyCfg.singBox.clashApiPort; tolerance = proxyCfg.singBox.urlTest.tolerance;
urlTest = proxyCfg.urlTest // { tolerance = proxyCfg.singBox.urlTest.tolerance; };
}; };
};
xrayCfg = proxyCfg.xray; xrayCfg = proxyCfg.xray;
proxyEnabled = proxyCfg.enable; proxyEnabled = proxyCfg.enable;
singBoxEnabled = proxyCfg.enable && proxyCfg.singBox.enable; singBoxEnabled = proxyCfg.enable && proxyCfg.singBox.enable;
xrayEnabled = proxyCfg.enable && proxyCfg.xray.enable; xrayEnabled = proxyCfg.enable && proxyCfg.xray.enable;
hybridEnabled = singBoxEnabled && xrayEnabled;
pureSingBoxEnabled = singBoxEnabled && !xrayEnabled;
pureXrayEnabled = xrayEnabled && !singBoxEnabled;
activeBackend = activeBackend =
if xrayEnabled then if hybridEnabled then
"hybrid"
else if pureXrayEnabled then
"xray" "xray"
else if singBoxEnabled then else if pureSingBoxEnabled then
"sing-box" "sing-box"
else else
null; null;
@@ -44,7 +49,7 @@ let
hasStaticOutbounds = proxyCfg.outbounds != [ ]; hasStaticOutbounds = proxyCfg.outbounds != [ ];
hasSubscriptions = proxyCfg.subscriptions != [ ]; hasSubscriptions = proxyCfg.subscriptions != [ ];
collapseNamedOutbounds = selectionMode == "first"; collapseNamedOutbounds = selectionMode == "first";
clashApiEnabled = singBoxEnabled && selectionMode != "first"; clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
perAppZapretEnabled = perAppZapretCfg.enable; perAppZapretEnabled = perAppZapretCfg.enable;
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable; userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
@@ -64,6 +69,9 @@ in
proxyEnabled proxyEnabled
singBoxEnabled singBoxEnabled
xrayEnabled xrayEnabled
hybridEnabled
pureSingBoxEnabled
pureXrayEnabled
activeBackend activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
+10 -3
View File
@@ -2,7 +2,12 @@
{ lib, pkgs, ... }: { lib, pkgs, ... }:
let let
inherit (lib) literalExpression mkOption mkEnableOption types; inherit (lib)
literalExpression
mkOption
mkEnableOption
types
;
in in
{ {
options.services.proxy-suite.proxy = { options.services.proxy-suite.proxy = {
@@ -11,8 +16,10 @@ in
default = false; default = false;
description = '' description = ''
Whether to configure and run the proxy backend services. Whether to configure and run the proxy backend services.
This is disabled by default; enable it explicitly and choose exactly This is disabled by default; enable it explicitly and choose at least
one backend with proxy.singBox.enable or proxy.xray.enable. one backend with proxy.singBox.enable or proxy.xray.enable. Enabling
both runs sing-box as the frontend and XRay as a sidecar for outbounds
that require XRay.
''; '';
}; };
+16
View File
@@ -159,6 +159,22 @@ let
example = "hy2://password@example.com:443?sni=example.com"; 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 { singBoxJson = mkOption {
type = types.nullOr types.attrs; type = types.nullOr types.attrs;
default = null; default = null;
+66 -44
View File
@@ -118,7 +118,11 @@ let
tag: tag:
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then
"proxy" "proxy"
else if derived.xrayEnabled && derived.selectionMode == "urltest" && !builtins.elem tag derived.builtinTags then else if
derived.pureXrayEnabled
&& derived.selectionMode == "urltest"
&& !builtins.elem tag derived.builtinTags
then
"proxy-suite-ob-${tag}" "proxy-suite-ob-${tag}"
else else
tag; tag;
@@ -190,12 +194,10 @@ let
{ action = "sniff"; } { action = "sniff"; }
]; ];
customRouteRules = map ( customRouteRules = map (rule: {
rule: { category = customRuleCategory rule.outbound;
category = customRuleCategory rule.outbound; entries = mkCustomRuleEntries rule;
entries = mkCustomRuleEntries rule; }) customRules;
}
) customRules;
proxyPrimaryRules = lib.flatten [ proxyPrimaryRules = lib.flatten [
(mkDomainRule "proxy" r.proxy.domains) (mkDomainRule "proxy" r.proxy.domains)
@@ -209,19 +211,21 @@ let
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips)) (mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
]; ];
tgWsProxyRelayDirectRules = lib.optional ( tgWsProxyRelayDirectRules =
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { } lib.optional
) { (tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); {
outbound = "direct"; ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
}; outbound = "direct";
};
safetyDirectRules = [ safetyDirectRules = [
{ {
ip_is_private = true; ip_is_private = true;
outbound = "direct"; outbound = "direct";
} }
] ++ tgWsProxyRelayDirectRules; ]
++ tgWsProxyRelayDirectRules;
blockRules = lib.flatten [ blockRules = lib.flatten [
(mkDomainRule "block" r.block.domains) (mkDomainRule "block" r.block.domains)
@@ -263,54 +267,68 @@ let
mkXrayRule = mkXrayRule =
ruleTag: fields: tag: ruleTag: fields: tag:
({ (
type = "field"; {
inherit ruleTag; type = "field";
} inherit ruleTag;
// fields }
// (xrayTarget tag)); // fields
// (xrayTarget tag)
);
xrayDomainRules = xrayDomainRules =
ruleTag: tag: domains: ruleTag: tag: domains:
lib.optional (domains != [ ]) (mkXrayRule ruleTag { lib.optional (domains != [ ]) (
domain = map (domain: "domain:${domain}") domains; mkXrayRule ruleTag {
} tag); domain = map (domain: "domain:${domain}") domains;
} tag
);
xrayIPRules = xrayIPRules =
ruleTag: tag: ips: ruleTag: tag: ips:
lib.optional (ips != [ ]) (mkXrayRule ruleTag { lib.optional (ips != [ ]) (
ip = ips; mkXrayRule ruleTag {
} tag); ip = ips;
} tag
);
xrayGeositeRules = xrayGeositeRules =
ruleTag: tag: geosites: ruleTag: tag: geosites:
lib.optional (geosites != [ ]) (mkXrayRule ruleTag { lib.optional (geosites != [ ]) (
domain = map (name: "geosite:${name}") geosites; mkXrayRule ruleTag {
} tag); domain = map (name: "geosite:${name}") geosites;
} tag
);
xrayGeoIPRules = xrayGeoIPRules =
ruleTag: tag: geoips: ruleTag: tag: geoips:
lib.optional (geoips != [ ]) (mkXrayRule ruleTag { lib.optional (geoips != [ ]) (
ip = map (name: "geoip:${name}") geoips; mkXrayRule ruleTag {
} tag); ip = map (name: "geoip:${name}") geoips;
} tag
);
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}"; xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
mkXrayCustomRuleEntries = mkXrayCustomRuleEntries =
rule: rule:
lib.flatten [ lib.flatten [
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound rule.domains) (xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
rule.domains
)
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips) (xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound rule.geosites) (xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound rule.geoips) rule.geosites
)
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
rule.geoips
)
]; ];
xrayCustomRouteRules = map ( xrayCustomRouteRules = map (rule: {
rule: { category = customRuleCategory rule.outbound;
category = customRuleCategory rule.outbound; entries = mkXrayCustomRuleEntries rule;
entries = mkXrayCustomRuleEntries rule; }) customRules;
}
) customRules;
xrayProxyPrimaryRules = lib.flatten [ xrayProxyPrimaryRules = lib.flatten [
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains) (xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
@@ -326,9 +344,13 @@ let
xraySafetyDirectRules = [ xraySafetyDirectRules = [
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct") (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"); lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
(
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
);
xrayBlockRules = lib.flatten [ xrayBlockRules = lib.flatten [
(xrayDomainRules "block-domain" "block" r.block.domains) (xrayDomainRules "block-domain" "block" r.block.domains)
+95 -80
View File
@@ -32,6 +32,8 @@ let
proxyEnabled proxyEnabled
singBoxEnabled singBoxEnabled
xrayEnabled xrayEnabled
hybridEnabled
pureXrayEnabled
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
globalTproxy globalTproxy
@@ -49,9 +51,9 @@ let
(requireAvailable proxyCfg.xray.enable proxyEnabled (requireAvailable proxyCfg.xray.enable proxyEnabled
"proxy-suite: proxy.xray.enable requires proxy.enable = true" "proxy-suite: proxy.xray.enable requires proxy.enable = true"
) )
(mkAssertion ( (mkAssertion (!proxyEnabled || proxyCfg.singBox.enable || proxyCfg.xray.enable)
!proxyEnabled || (proxyCfg.singBox.enable != proxyCfg.xray.enable) "proxy-suite: at least one of proxy.singBox.enable or proxy.xray.enable must be true when proxy.enable = true"
) "proxy-suite: exactly one of proxy.singBox.enable or proxy.xray.enable must be true when proxy.enable = true") )
(requireAvailable proxyEnabled ( (requireAvailable proxyEnabled (
proxyCfg.outbounds != [ ] || proxyCfg.subscriptions != [ ] proxyCfg.outbounds != [ ] || proxyCfg.subscriptions != [ ]
) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true") ) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true")
@@ -66,11 +68,12 @@ let
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}" "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
) )
(mkAssertion ( (mkAssertion (
!(xrayEnabled && proxyCfg.selection == "selector") !(pureXrayEnabled && proxyCfg.selection == "selector")
) "proxy-suite: proxy.selection = \"selector\" is only available with proxy.singBox.enable = true") ) "proxy-suite: proxy.selection = \"selector\" is only available with proxy.singBox.enable = true")
(mkAssertion ( (mkAssertion
!(xrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")) (!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
) "proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.xray.enable = true; use udp/tcp DNS for XRay") "proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.xray.enable = true; use udp/tcp DNS for XRay"
)
(requireEnabled globalTun.enable proxyEnabled (requireEnabled globalTun.enable proxyEnabled
"proxy-suite: proxy.tun.enable requires proxy.enable = true" "proxy-suite: proxy.tun.enable requires proxy.enable = true"
) )
@@ -250,7 +253,8 @@ let
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark"; message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark";
} }
{ {
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable; condition =
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
left = tgWsProxyCfg.routingMark; left = tgWsProxyCfg.routingMark;
right = perAppRoutingTproxy.fwmark; right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark"; message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark";
@@ -268,68 +272,70 @@ let
134217728 134217728
]; ];
positiveNumberAssertions = map (item: mkAssertion (!item.condition || item.value > 0) item.message) [ positiveNumberAssertions =
{ map (item: mkAssertion (!item.condition || item.value > 0) item.message)
condition = globalTun.enable; [
value = globalTun.mtu; {
message = "proxy-suite: proxy.tun.mtu must be greater than zero"; condition = globalTun.enable;
} value = globalTun.mtu;
{ message = "proxy-suite: proxy.tun.mtu must be greater than zero";
condition = perAppRoutingTun.enable; }
value = perAppRoutingTun.mtu; {
message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero"; condition = perAppRoutingTun.enable;
} value = perAppRoutingTun.mtu;
{ message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero";
condition = globalTproxy.enable; }
value = globalTproxy.fwmark; {
message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero"; condition = globalTproxy.enable;
} value = globalTproxy.fwmark;
{ message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero";
condition = globalTproxy.enable; }
value = globalTproxy.proxyMark; {
message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero"; condition = globalTproxy.enable;
} value = globalTproxy.proxyMark;
{ message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero";
condition = globalTproxy.enable; }
value = globalTproxy.routeTable; {
message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero"; condition = globalTproxy.enable;
} value = globalTproxy.routeTable;
{ message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero";
condition = perAppRoutingTun.enable; }
value = perAppRoutingTun.fwmark; {
message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero"; condition = perAppRoutingTun.enable;
} value = perAppRoutingTun.fwmark;
{ message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero";
condition = perAppRoutingTun.enable; }
value = perAppRoutingTun.routeTable; {
message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero"; condition = perAppRoutingTun.enable;
} value = perAppRoutingTun.routeTable;
{ message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero";
condition = perAppRoutingTproxy.enable; }
value = perAppRoutingTproxy.fwmark; {
message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero"; condition = perAppRoutingTproxy.enable;
} value = perAppRoutingTproxy.fwmark;
{ message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero";
condition = perAppRoutingTproxy.enable; }
value = perAppRoutingTproxy.routeTable; {
message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero"; condition = perAppRoutingTproxy.enable;
} value = perAppRoutingTproxy.routeTable;
{ message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero";
condition = perAppZapretCfg.enable; }
value = perAppZapretCfg.filterMark; {
message = "proxy-suite: zapret.perApp.filterMark must be greater than zero"; condition = perAppZapretCfg.enable;
} value = perAppZapretCfg.filterMark;
{ message = "proxy-suite: zapret.perApp.filterMark must be greater than zero";
condition = perAppZapretCfg.enable; }
value = perAppZapretCfg.qnum; {
message = "proxy-suite: zapret.perApp.qnum must be greater than zero"; condition = perAppZapretCfg.enable;
} value = perAppZapretCfg.qnum;
{ message = "proxy-suite: zapret.perApp.qnum must be greater than zero";
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy; }
value = tgWsProxyCfg.routingMark; {
message = "proxy-suite: tgWsProxy.routingMark must be greater than zero"; condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
} value = tgWsProxyCfg.routingMark;
]; message = "proxy-suite: tgWsProxy.routingMark must be greater than zero";
}
];
localProxyAuthCfg = proxyCfg.auth; localProxyAuthCfg = proxyCfg.auth;
localProxyAuthUsed = localProxyAuthUsed =
@@ -404,19 +410,28 @@ let
]; ];
outboundAssertions = lib.concatMap (ob: [ outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf proxyEnabled [ (exactlyOneOf proxyEnabled
ob.urlFile [
ob.url ob.urlFile
ob.singBoxJson ob.url
ob.xrayJson ob.singBoxJson
ob.json ob.xrayJson
] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json") ob.json
(mkAssertion (!singBoxEnabled || ob.xrayJson == null) ]
"proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true" "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
) )
(mkAssertion (!xrayEnabled || (ob.singBoxJson == null && ob.json == null)) (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" "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; ]) proxyCfg.outbounds;
subscriptionAssertions = lib.concatMap (sub: [ subscriptionAssertions = lib.concatMap (sub: [
+12 -1
View File
@@ -24,6 +24,8 @@ let
proxyEnabled proxyEnabled
singBoxEnabled singBoxEnabled
xrayEnabled xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
@@ -71,6 +73,8 @@ let
proxyEnabled proxyEnabled
singBoxEnabled singBoxEnabled
xrayEnabled xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend activeBackend
perAppRoutingCfg perAppRoutingCfg
userControlCfg userControlCfg
@@ -88,7 +92,12 @@ let
buildOutboundPy buildOutboundPy
fetchSubscriptionPy fetchSubscriptionPy
; ;
inherit tproxyFile tunFile perAppTunFile routeModeRulesFile; inherit
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
;
}; };
perAppRouting = import ./per-app-routing.nix { perAppRouting = import ./per-app-routing.nix {
@@ -144,6 +153,8 @@ in
proxyEnabled proxyEnabled
singBoxEnabled singBoxEnabled
xrayEnabled xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
+19 -3
View File
@@ -58,6 +58,8 @@ let
proxyCfg proxyCfg
proxyEnabled proxyEnabled
xrayEnabled xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend activeBackend
perAppRoutingCfg perAppRoutingCfg
globalTun globalTun
@@ -236,7 +238,14 @@ let
enable = proxyEnabled; enable = proxyEnabled;
name = serviceNames.socks; name = serviceNames.socks;
value = mkRestartingService { value = mkRestartingService {
description = "${if xrayEnabled then "XRay" else "sing-box"} proxy client (SOCKS + TProxy-ready)"; 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" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
@@ -268,14 +277,21 @@ let
enable = proxyEnabled && globalTun.enable; enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun; name = serviceNames.tun;
value = mkRestartingService { value = mkRestartingService {
description = "${if xrayEnabled then "XRay" else "sing-box"} TUN proxy client"; description = "${
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box"
} TUN proxy client";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ]; conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript; execStartPre = tunCleanupScript;
execStart = scripts.startTun; execStart = scripts.startTun;
execStartPost = if xrayEnabled then xrayTunUpScript else null; execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript; execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun; runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
+286 -37
View File
@@ -7,6 +7,8 @@
proxyEnabled, proxyEnabled,
singBoxEnabled, singBoxEnabled,
xrayEnabled, xrayEnabled,
hybridEnabled,
pureXrayEnabled,
activeBackend, activeBackend,
perAppRoutingCfg, perAppRoutingCfg,
userControlCfg, userControlCfg,
@@ -31,8 +33,9 @@ let
globalTproxy = proxyCfg.tproxy; globalTproxy = proxyCfg.tproxy;
systemctl = "${pkgs.systemd}/bin/systemctl"; systemctl = "${pkgs.systemd}/bin/systemctl";
backend = if activeBackend == null then "sing-box" else activeBackend; backend = if activeBackend == null then "sing-box" else activeBackend;
backendArg = "--backend ${backend}"; mainBackend = if pureXrayEnabled then "xray" else "sing-box";
backendBin = if xrayEnabled then xray else singBox; backendArg = "--backend ${mainBackend}";
backendBin = if pureXrayEnabled then xray else singBox;
localProxyAuth = proxyCfg.auth; localProxyAuth = proxyCfg.auth;
localProxyAuthEnabled = localProxyAuthEnabled =
localProxyAuth.username != null localProxyAuth.username != null
@@ -48,6 +51,7 @@ let
routeModeStateFile = "/run/proxy-suite/route-mode"; routeModeStateFile = "/run/proxy-suite/route-mode";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel"; xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json"; mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
@@ -97,7 +101,7 @@ let
routingMark: routingMark:
if routingMark == null then if routingMark == null then
"" ""
else if xrayEnabled then else if pureXrayEnabled then
" | .streamSettings.sockopt.mark = ${toString routingMark}" " | .streamSettings.sockopt.mark = ${toString routingMark}"
else else
" | .routing_mark = ${toString routingMark}"; " | .routing_mark = ${toString routingMark}";
@@ -106,7 +110,7 @@ let
ob: tag: routingMark: ob: tag: routingMark:
let let
backendRaw = backendRaw =
if xrayEnabled then if pureXrayEnabled then
ob.xrayJson ob.xrayJson
else if ob.singBoxJson != null then else if ob.singBoxJson != null then
ob.singBoxJson ob.singBoxJson
@@ -115,22 +119,21 @@ let
markAttrs = markAttrs =
if routingMark == null then if routingMark == null then
{ } { }
else if xrayEnabled then else if pureXrayEnabled then
{ streamSettings.sockopt.mark = routingMark; } { streamSettings.sockopt.mark = routingMark; }
else else
{ routing_mark = routingMark; }; { routing_mark = routingMark; };
taggedRaw = backendRaw // { inherit tag; }; taggedRaw = backendRaw // {
inherit tag;
};
in in
if xrayEnabled then if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
lib.recursiveUpdate taggedRaw markAttrs
else
taggedRaw // markAttrs;
mkOutboundBlock = mkOutboundBlock =
ob: routingMark: tag: ob: routingMark: tag:
let let
backendRaw = backendRaw =
if xrayEnabled then if pureXrayEnabled then
ob.xrayJson ob.xrayJson
else if ob.singBoxJson != null then else if ob.singBoxJson != null then
ob.singBoxJson ob.singBoxJson
@@ -150,18 +153,103 @@ let
else else
let let
urlSource = urlSource =
if ob.urlFile != null then if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
ob.urlFile
else
pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
in in
'' ''
# outbound: ${tag} # outbound: ${tag}
URL=$(cat "${urlSource}") URL=$(cat "${urlSource}")
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"}) OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
''; '';
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 = mkSubscriptionBlock =
sub: routingMark: sub: routingMark:
let let
@@ -184,9 +272,11 @@ let
fi fi
if [ -f "$CACHE_FILE" ]; then if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE") SUB_JSON=$(cat "$CACHE_FILE")
${lib.optionalString (routingMark != null) '' ${
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON") lib.optionalString (routingMark != null) ''
''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi fi
''; '';
@@ -197,14 +287,124 @@ let
fi 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:false,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 = mkOutboundScript =
routingMark: routingMark:
let let
outboundBlocks = outboundBlocks =
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
mkOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy" (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock)
(builtins.head proxyCfg.outbounds)
routingMark
"proxy"
else else
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds; lib.concatMapStrings (
ob: (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock) ob routingMark ob.tag
) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings ( subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark sub: mkSubscriptionBlock sub routingMark
@@ -218,7 +418,7 @@ let
''; '';
wrapperBlock = wrapperBlock =
if xrayEnabled && selectionMode == "urltest" then if pureXrayEnabled && selectionMode == "urltest" then
xrayUrltestTagFilter xrayUrltestTagFilter
else if collapseNamedOutbounds then else if collapseNamedOutbounds then
lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) '' lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) ''
@@ -270,18 +470,21 @@ let
chmod 640 "${runtimeProxychainsConfig}" chmod 640 "${runtimeProxychainsConfig}"
''; '';
restartActiveConfigConsumersBlock = lib.concatMapStrings (svc: '' restartActiveConfigConsumersBlock =
if ${systemctl} is-active --quiet ${svc}; then lib.concatMapStrings
${systemctl} restart ${svc} (svc: ''
fi if ${systemctl} is-active --quiet ${svc}; then
'') [ ${systemctl} restart ${svc}
"proxy-suite-socks" fi
"proxy-suite-tun" '')
"proxy-suite-per-app-tun" [
]; "proxy-suite-socks"
"proxy-suite-tun"
"proxy-suite-per-app-tun"
];
routeModeBlacklistTail = routeModeBlacklistTail =
if xrayEnabled then if pureXrayEnabled then
'' ''
+ .proxyGeo + .proxyGeo
+ .block + .block
@@ -355,7 +558,7 @@ let
''; '';
mkBackendJqFilter = mkBackendJqFilter =
if xrayEnabled then if pureXrayEnabled then
'' ''
def xray_bind_outbound($interface): def xray_bind_outbound($interface):
if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then
@@ -455,6 +658,8 @@ let
enableLocalProxyAuth ? false, enableLocalProxyAuth ? false,
xrayTunEgressBinding ? false, xrayTunEgressBinding ? false,
xrayTunDnsRuntime ? false, xrayTunDnsRuntime ? false,
xraySidecarBasePort ? 33080,
xrayDnsBridgePort ? 18533,
}: }:
pkgs.writeShellScript name '' pkgs.writeShellScript name ''
set -euo pipefail set -euo pipefail
@@ -472,6 +677,7 @@ let
ROUTE_RULES_JSON='[]' ROUTE_RULES_JSON='[]'
ROUTE_MODE_ACTIVE=false ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false CLEAR_DNS_RULES=false
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
${subscriptionCacheHelpersBlock} ${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth '' ${lib.optionalString enableLocalProxyAuth ''
umask 077 umask 077
@@ -503,6 +709,7 @@ let
${routeModeCaseBlock} ${routeModeCaseBlock}
${mkOutboundScript routingMark} ${mkOutboundScript routingMark}
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
${jq} \ ${jq} \
--argjson obs "$OUTBOUNDS_JSON" \ --argjson obs "$OUTBOUNDS_JSON" \
@@ -526,7 +733,43 @@ let
chmod 600 "$RUNTIME_DIR/config.json" chmod 600 "$RUNTIME_DIR/config.json"
''} ''}
exec ${backendBin} run -c "$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 { startSocks = mkStartScript {
@@ -535,15 +778,19 @@ let
configFile = tproxyFile; configFile = tproxyFile;
routingMark = globalTproxy.proxyMark; routingMark = globalTproxy.proxyMark;
enableLocalProxyAuth = localProxyAuthEnabled; enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = 33080;
xrayDnsBridgePort = 18533;
}; };
startTun = mkStartScript { startTun = mkStartScript {
name = "proxy-suite-start-tun"; name = "proxy-suite-start-tun";
runtimeDir = "/run/proxy-suite-tun"; runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile; configFile = tunFile;
routingMark = if xrayEnabled then globalTproxy.proxyMark else null; routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled; xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = xrayEnabled; xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = 33180;
xrayDnsBridgePort = 18534;
}; };
startPerAppTun = mkStartScript { startPerAppTun = mkStartScript {
@@ -552,7 +799,9 @@ let
configFile = perAppTunFile; configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled; xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = xrayEnabled; xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = 33280;
xrayDnsBridgePort = 18535;
}; };
mkSubscriptionFetchBlock = mkSubscriptionFetchBlock =
+649 -245
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -67,7 +67,7 @@ def _xray_tls(tls: dict | None) -> tuple[str, dict]:
def _xray_transport(transport: dict | None) -> tuple[str, dict]: def _xray_transport(transport: dict | None) -> tuple[str, dict]:
if not transport: if not transport:
return "tcp", {} return "raw", {}
t = transport["type"] t = transport["type"]
if t == "ws": if t == "ws":
@@ -107,6 +107,7 @@ def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict:
stream = {"network": network, "security": security} stream = {"network": network, "security": security}
stream.update(sec) stream.update(sec)
stream.update(net) stream.update(net)
stream.setdefault("sockopt", {})["domainStrategy"] = "UseIP"
if routing_mark is not None: if routing_mark is not None:
stream.setdefault("sockopt", {})["mark"] = routing_mark stream.setdefault("sockopt", {})["mark"] = routing_mark
return stream return stream
+1 -1
View File
@@ -169,7 +169,7 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
"public_key": params["pbk"], "public_key": params["pbk"],
"short_id": params.get("sid", ""), "short_id": params.get("sid", ""),
} }
if params.get("spx"): if backend == "xray" and params.get("spx"):
ob["tls"]["reality"]["spider_x"] = params["spx"] ob["tls"]["reality"]["spider_x"] = params["spx"]
elif security == "tls": elif security == "tls":
ob["tls"] = _mk_tls( ob["tls"] = _mk_tls(
+16
View File
@@ -34,8 +34,24 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["tls"]["server_name"], "last.fm") self.assertEqual(ob["tls"]["server_name"], "last.fm")
self.assertEqual(ob["tls"]["utls"]["fingerprint"], "qq") self.assertEqual(ob["tls"]["utls"]["fingerprint"], "qq")
self.assertEqual(ob["tls"]["reality"]["short_id"], "8a54") self.assertEqual(ob["tls"]["reality"]["short_id"], "8a54")
self.assertNotIn("spider_x", ob["tls"]["reality"])
self.assertNotIn("transport", ob) self.assertNotIn("transport", ob)
def test_xray_vless_reality_germany_main_shape(self):
ob = run_xray_parser(
"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"
)
self.assertEqual(ob["protocol"], "vless")
self.assertEqual(ob["settings"]["address"], "example.com")
self.assertEqual(ob["settings"]["flow"], "xtls-rprx-vision")
self.assertEqual(ob["streamSettings"]["network"], "raw")
self.assertEqual(ob["streamSettings"]["sockopt"]["domainStrategy"], "UseIP")
self.assertEqual(ob["streamSettings"]["realitySettings"]["serverName"], "last.fm")
self.assertEqual(ob["streamSettings"]["realitySettings"]["fingerprint"], "qq")
self.assertEqual(
ob["streamSettings"]["realitySettings"]["spiderX"], "/-/en/gp/bestsellers"
)
def test_vless_httpupgrade_transport(self): def test_vless_httpupgrade_transport(self):
ob = run_parser( ob = run_parser(
"vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade" "vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade"