other fixes

This commit is contained in:
FUFSoB committed 2026-05-18 11:03:10 +05:00
1 parent 70c0454446
commit 86e229ff4c
11 files changed
+339 -10

No files matched your search

+83 -2
View File
@@ -115,9 +115,11 @@ Update module option docs there instead of editing this file by hand.
- [url](#services-proxy-suite-singbox-urltest-url)
- tgWsProxy
- [enable](#services-proxy-suite-tgwsproxy-enable)
- [bypassTransparentProxy](#services-proxy-suite-tgwsproxy-bypasstransparentproxy)
- [dcIps](#services-proxy-suite-tgwsproxy-dcips)
- [host](#services-proxy-suite-tgwsproxy-host)
- [port](#services-proxy-suite-tgwsproxy-port)
- [routingMark](#services-proxy-suite-tgwsproxy-routingmark)
- [secret](#services-proxy-suite-tgwsproxy-secret)
- [secretFile](#services-proxy-suite-tgwsproxy-secretfile)
- tray
@@ -266,10 +268,12 @@ services.proxy-suite = {
};
};
tgWsProxy = {
bypassTransparentProxy = true;
dcIps = { };
enable = false;
host = "127.0.0.1";
port = 1443;
routingMark = 4;
secret = null;
secretFile = null;
};
@@ -503,6 +507,7 @@ services.proxy-suite = {
};
};
tgWsProxy = {
bypassTransparentProxy = true;
dcIps = {
"2" = "149.154.167.220";
"203" = "149.154.167.220";
@@ -511,6 +516,7 @@ services.proxy-suite = {
enable = true;
host = "127.0.0.1";
port = 1076;
routingMark = 4;
secret = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
secretFile = "/run/secrets/tg-ws-proxy-secret";
};
@@ -3719,6 +3725,46 @@ false
*Example:*
```nix
true
```
*Declared by:*
- [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix)
<a id="services-proxy-suite-tgwsproxy-bypasstransparentproxy"></a>
## services\.proxy-suite\.tgWsProxy\.bypassTransparentProxy
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 sing-box again,
which can otherwise break tg-ws-proxy after enabling TUN mode\.
*Type:*
boolean
*Default:*
```nix
true
```
*Example:*
```nix
@@ -3839,6 +3885,41 @@ WebSocket proxy\.
<a id="services-proxy-suite-tgwsproxy-routingmark"></a>
## services\.proxy-suite\.tgWsProxy\.routingMark
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\.
*Type:*
signed integer
*Default:*
```nix
4
```
*Example:*
```nix
4
```
*Declared by:*
- [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix)
<a id="services-proxy-suite-tgwsproxy-secret"></a>
## services\.proxy-suite\.tgWsProxy\.secret
@@ -4124,6 +4205,8 @@ true
<a id="services-proxy-suite-zapret-enable"></a>
## services\.proxy-suite\.zapret\.enable
Whether to enable zapret DPI bypass\.
@@ -4155,8 +4238,6 @@ true
<a id="services-proxy-suite-zapret-cidrexemption-enable"></a>
## services\.proxy-suite\.zapret\.cidrExemption\.enable
Whether to enable CIDR exemption from zapret NFQUEUE\.
+6 -1
View File
@@ -11,6 +11,11 @@ let
perAppTun = singBoxCfg.tun.perApp;
perAppTproxy = singBoxCfg.tproxy.perApp;
zapretApp = cfg.zapret.perApp;
tgWsProxyCfg = cfg.tgWsProxy;
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled ''
meta mark ${toString tgWsProxyCfg.routingMark} return
'';
# Shared across all three nftables rule files that do IPv4 routing.
reservedIpBlock = ''
@@ -55,7 +60,7 @@ let
ip daddr $RESERVED_IP return
${tproxyLocalSubnetLines}
meta mark ${toString globalTproxy.proxyMark} return
${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
${tgWsProxyBypassMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
ip protocol udp meta mark set ${toString globalTproxy.fwmark}
}
}
+27
View File
@@ -130,6 +130,33 @@ in
"203" = "149.154.167.220";
};
};
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 sing-box 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;
};
};
};
}
+9 -1
View File
@@ -11,6 +11,7 @@ let
r = cfg.singBox.routing;
singBoxCfg = derived.singBoxCfg;
zapretCfg = cfg.zapret;
tgWsProxyCfg = cfg.tgWsProxy;
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
@@ -203,12 +204,19 @@ let
(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)
@@ -215,6 +215,36 @@ let
right = perAppZapretCfg.filterMark;
message = "proxy-suite: singBox.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark;
right = globalTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tproxy.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark;
right = globalTproxy.proxyMark;
message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tproxy.proxyMark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
left = tgWsProxyCfg.routingMark;
right = perAppRoutingTun.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tun.perApp.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
left = tgWsProxyCfg.routingMark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from singBox.tproxy.perApp.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
left = tgWsProxyCfg.routingMark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: tgWsProxy.routingMark must differ from zapret.perApp.filterMark";
}
];
perAppZapretDesyncMarks = [
@@ -278,6 +308,11 @@ let
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";
}
];
localProxyAuthCfg = singBoxCfg.auth;
@@ -337,6 +372,12 @@ let
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
value = tgWsProxyCfg.routingMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits";
}
];
secretAssertions = [
+34 -3
View File
@@ -58,6 +58,31 @@ let
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag}
'';
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e '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
}
'';
# Build the shell code block for a single outbound entry.
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
# routingMark is null or an int; added to outbound JSON if set.
@@ -106,10 +131,11 @@ let
# 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
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
_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
@@ -233,6 +259,7 @@ let
ROUTE_RULES_JSON='[]'
ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false
${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth ''
umask 077
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
@@ -364,8 +391,11 @@ let
in
''
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
mv "${cacheFile}.tmp" "${cacheFile}"
echo "Updated subscription: ${sub.tag}"
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
@@ -378,6 +408,7 @@ let
CACHE_DIR="${subscriptionCacheDir}"
mkdir -p "$CACHE_DIR"
FAILED=0
${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions}
if [ "$FAILED" -eq 0 ]; then
+32
View File
@@ -9,6 +9,13 @@
let
t = cfg.tgWsProxy;
tgPkg = packages.tg-ws-proxy;
ip = "${pkgs.iproute2}/bin/ip";
transparentBypassEnabled =
t.bypassTransparentProxy
&& cfg.singBox.enable
&& (cfg.singBox.tun.enable || cfg.singBox.tproxy.enable);
bypassRulePriority = 8999;
dcArgs = lib.concatMapStrings
(id: " --dc-ip=${lib.escapeShellArg "${id}:${t.dcIps.${id}}"}")
@@ -24,6 +31,26 @@ let
"--secret=${lib.escapeShellArg t.secret}"
}${dcArgs}
'';
bypassUpScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-up" ''
set -euo pipefail
add_bypass_rule() {
local family="$1"
while ${ip} "$family" rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
${ip} "$family" rule add pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null || true
}
add_bypass_rule -4
add_bypass_rule -6
'';
bypassDownScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-down" ''
set +e
while ${ip} -4 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
'';
in
{
systemd.services.proxy-suite-tg-ws-proxy = {
@@ -35,6 +62,11 @@ in
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
Restart = "on-failure";
RestartSec = 5;
}
// lib.optionalAttrs transparentBypassEnabled {
ExecStartPre = bypassUpScript;
ExecStopPost = bypassDownScript;
SocketMark = toString t.routingMark;
};
};
}
+77
View File
@@ -79,6 +79,16 @@ let
};
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 (
@@ -233,6 +243,51 @@ let
}
];
tgWithGlobalTun = evalProxySuite [
baseModule
{
services.proxy-suite = {
singBox.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 = {
singBox.tproxy.enable = true;
tgWsProxy = {
enable = true;
secretFile = "/run/secrets/tg-ws-proxy";
};
};
}
];
tgWithGlobalTproxyNft = mkTProxyNftRules tgWithGlobalTproxy;
tgRoutingMarkCollision = mkBadFixture [
{
services.proxy-suite = {
singBox.tproxy.enable = true;
tgWsProxy = {
enable = true;
secretFile = "/run/secrets/tg-ws-proxy";
routingMark = 1;
};
};
}
];
duplicateTags = forceEval (
(mkFixture {
enable = true;
@@ -1336,6 +1391,16 @@ let
== [ "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
)
(
assert duplicateTags.success == false;
true
@@ -1735,6 +1800,15 @@ let
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;
@@ -1916,8 +1990,11 @@ let
(
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" "$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
)
+6 -1
View File
@@ -200,6 +200,11 @@ _wrap_slice() {
local user_svc="$slice_base-user@$uid.service"
local status=0
cleanup_slice() {
_cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc"
}
trap cleanup_slice EXIT
systemctl --user start "$anchor_unit" || status=$?
if [ "$status" -eq 0 ]; then
systemctl start "$backend_svc" || status=$?
@@ -212,7 +217,6 @@ _wrap_slice() {
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
fi
_cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc"
exit "$status"
}
@@ -404,6 +408,7 @@ cmd_wrap() {
exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@"
;;
tun)
_check_no_global_proxy tun
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \
"Profile '$profile' uses route=tun, but singBox.tun.perApp.enable is false." \
"proxy-suite-per-app-tun.service" "$@"
+5 -2
View File
@@ -7,7 +7,7 @@ import urllib.parse
def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query))
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
def _split_host_port(hostpart: str) -> tuple[str, str]:
@@ -23,7 +23,7 @@ def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
rest = url[len(f"{scheme}://") :]
rest, _, _ = rest.partition("#")
if "@" in rest:
userinfo, _, rest = rest.partition("@")
userinfo, _, rest = rest.rpartition("@")
else:
userinfo = ""
hostpart, _, query = rest.partition("?")
@@ -119,6 +119,9 @@ def parse_vless(url: str, tag: str) -> dict:
def parse_vmess(url: str, tag: str) -> dict:
b64 = url[len("vmess://") :]
b64, _, _ = b64.partition("#")
b64, _, _ = b64.partition("?")
b64 = urllib.parse.unquote(b64)
pad = "=" * (-len(b64) % 4)
try:
data = json.loads(base64.b64decode(b64 + pad))
+19
View File
@@ -39,6 +39,19 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["transport"]["type"], "ws")
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
def test_vmess_with_external_remark(self):
payload = {
"add": "vmess.example.com",
"port": "443",
"id": "00000000-0000-0000-0000-000000000000",
"aid": "0",
"scy": "auto",
}
encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
ob = run_parser(f"vmess://{encoded}#Subscription Remark")
self.assertEqual(ob["type"], "vmess")
self.assertEqual(ob["server"], "vmess.example.com")
def test_trojan(self):
ob = run_parser("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome")
self.assertEqual(ob["type"], "trojan")
@@ -109,6 +122,12 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["version"], "5")
self.assertEqual(ob["username"], "user")
def test_proxy_userinfo_allows_at_in_password(self):
ob = run_parser("socks5://user:p@ss@example.com:1080")
self.assertEqual(ob["username"], "user")
self.assertEqual(ob["password"], "p@ss")
self.assertEqual(ob["server"], "example.com")
def test_https_proxy(self):
ob = run_parser("https://proxy.example.com:8443")
self.assertEqual(ob["type"], "http")