fix: various fixes

This commit is contained in:
FUFSoB committed 2026-06-20 17:11:35 +05:00
1 parent 5b5598d12e
commit 1f5e050cb2
8 files changed
+204 -24

No files matched your search

+10 -1
View File
@@ -66,6 +66,15 @@ let
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 = {
@@ -154,7 +163,7 @@ let
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = rules.singBoxRoutingRules;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
+1
View File
@@ -107,6 +107,7 @@ let
cfg
singBoxCfg
proxyCfg
pureXrayEnabled
perAppRoutingCfg
perAppRoutingTun
perAppRoutingTproxy
@@ -5,6 +5,7 @@
cfg,
singBoxCfg,
proxyCfg,
pureXrayEnabled,
perAppRoutingCfg,
perAppRoutingTun,
perAppRoutingTproxy,
@@ -170,13 +171,15 @@ let
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -6 addr replace "$tun6_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} -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} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} -6 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" ''
+48 -11
View File
@@ -34,7 +34,13 @@ let
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 =
@@ -69,12 +75,19 @@ let
in
''
printf '%s' "$(cat "${urlSource}")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${backendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --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
[ -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() {
@@ -270,14 +283,34 @@ let
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
fi
fi
if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
${
if hybridEnabled then
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi
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 = ''
@@ -326,7 +359,7 @@ let
--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}]}}')
'{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" \
@@ -636,12 +669,16 @@ let
''
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 = $route_rules
.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
+56 -1
View File
@@ -497,6 +497,8 @@ let
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";
@@ -522,6 +524,32 @@ let
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";
@@ -1489,6 +1517,7 @@ let
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 (
@@ -2101,6 +2130,14 @@ let
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;
@@ -2112,6 +2149,10 @@ let
assert mixedInbound.type == "mixed";
assert tproxyInbound.type == "tproxy";
assert tunDnsBridgeInbound.listen_port == 18534;
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;
@@ -2126,7 +2167,17 @@ let
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 --
@@ -2828,7 +2879,8 @@ let
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 = $route_rules" routeModeBackendJqFilter;
assert pkgs.lib.hasInfix ".route.rules = (sing_box_preserved_rules + $route_rules)"
routeModeBackendJqFilter;
assert pkgs.lib.hasInfix ".dns.rules = []" routeModeBackendJqFilter;
true
)
@@ -3054,6 +3106,9 @@ let
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;
+9 -4
View File
@@ -5,7 +5,7 @@ import argparse
import json
import sys
from proxy_parsing import decode_subscription, fetch_raw, parse_subscription
from proxy_parsing import decode_subscription, fetch_raw, parse_hybrid_subscription, parse_subscription
def main() -> None:
@@ -18,7 +18,7 @@ def main() -> None:
dest="tag_prefix",
help="Prefix for outbound tags, e.g. 'my-sub'.",
)
ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box")
ap.add_argument("--backend", choices=["sing-box", "xray", "hybrid"], default="sing-box")
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
args = ap.parse_args()
@@ -34,9 +34,14 @@ def main() -> None:
sys.exit(1)
lines = decode_subscription(raw)
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
if args.backend == "hybrid":
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark)
has_outbounds = bool(outbounds["singBox"] or outbounds["xray"])
else:
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
has_outbounds = bool(outbounds)
if not outbounds:
if not has_outbounds:
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
sys.exit(1)
+45
View File
@@ -281,3 +281,48 @@ def parse_subscription(
outbounds.append(outbound)
return outbounds
def parse_hybrid_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None = None
) -> dict[str, list[dict]]:
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
seen_tags: set[str] = set()
for index, line in enumerate(lines):
scheme = detect_scheme(line)
if scheme not in PARSERS:
continue
remark = line.split("#", 1)[1] if "#" in line else ""
base_tag = make_tag(tag_prefix, remark, index)
tag = base_tag
if tag in seen_tags:
suffix = 2
while f"{base_tag}-{suffix}" in seen_tags:
suffix += 1
tag = f"{base_tag}-{suffix}"
try:
outbound = build_outbound(line, tag, routing_mark, "sing-box")
outbounds["singBox"].append(outbound)
seen_tags.add(tag)
continue
except Exception as sing_box_exc:
sing_box_error = sing_box_exc
try:
outbound = build_outbound(line, tag, routing_mark, "xray")
except Exception as xray_exc:
print(
f"warning: skipping entry {index} ({scheme}): "
f"sing-box: {sing_box_error}; xray: {xray_exc}",
file=sys.stderr,
)
continue
outbounds["xray"].append(outbound)
seen_tags.add(tag)
return outbounds
+28 -3
View File
@@ -2,9 +2,11 @@
import base64
import unittest
from proxy_parsing import decode_subscription, parse_subscription
from proxy_parsing import decode_subscription, parse_hybrid_subscription, parse_subscription
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
VLESS_XHTTP_URI = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
VLESS_ECH_URI = "vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
SS_URI = "ss://{}@ss.example.com:8388".format(
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
)
@@ -18,10 +20,16 @@ def _make_b64_payload(*uris: str) -> bytes:
def run_fetcher(
server_data: bytes, tag_prefix: str = "test", *, routing_mark: int | None = None
server_data: bytes,
tag_prefix: str = "test",
*,
routing_mark: int | None = None,
backend: str = "sing-box",
):
lines = decode_subscription(server_data)
return parse_subscription(lines, tag_prefix, routing_mark)
if backend == "hybrid":
return parse_hybrid_subscription(lines, tag_prefix, routing_mark)
return parse_subscription(lines, tag_prefix, routing_mark, backend)
class FetchSubscriptionTests(unittest.TestCase):
@@ -112,6 +120,23 @@ class FetchSubscriptionTests(unittest.TestCase):
obs = run_fetcher(payload)
self.assertEqual(len(obs), 2)
def test_hybrid_subscription_preserves_xray_only_entries(self):
payload = _make_b64_payload(VLESS_URI, VLESS_XHTTP_URI, VLESS_ECH_URI)
obs = run_fetcher(payload, backend="hybrid")
self.assertEqual(len(obs["singBox"]), 1)
self.assertEqual(len(obs["xray"]), 2)
self.assertEqual(obs["singBox"][0]["type"], "vless")
self.assertEqual(obs["xray"][0]["streamSettings"]["network"], "xhttp")
self.assertEqual(
obs["xray"][1]["streamSettings"]["tlsSettings"]["echConfigList"],
"udp://1.1.1.1",
)
def test_hybrid_subscription_all_invalid_returns_empty_backend_lists(self):
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
obs = run_fetcher(payload, backend="hybrid")
self.assertEqual(obs, {"singBox": [], "xray": []})
if __name__ == "__main__":
unittest.main()