fix: various fixes and additions

This commit is contained in:
fufsob committed 2026-09-15 13:46:02 +00:00
1 parent ea1922243a
commit e9b1542085
30 files changed
+447 -112

No files matched your search

+3 -1
View File
@@ -118,7 +118,9 @@ A group without a verb shows its status or list.
proxy [status|on|off] local proxy backend proxy [status|on|off] local proxy backend
proxy outbounds [list] outbounds, where each came from, and the pick proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url|json|-> add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin) proxy outbounds add <tag> <url|json|-> [--detour <tag>]
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
chained through another outbound with --detour
proxy outbounds rm <tag> remove a runtime outbound proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download] proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay) TCP ping, real delay, download speed (default: ping, delay)
+1
View File
@@ -174,6 +174,7 @@ services.proxy-suite = {
rules = [ ]; rules = [ ];
}; };
selection = "first"; selection = "first";
selectionExclude = [ ];
singBox = { singBox = {
clashApiPort = 9090; clashApiPort = 9090;
package = pkgs.sing-box; package = pkgs.sing-box;
+33 -4
View File
@@ -81,6 +81,7 @@ Part of the [proxy-suite options reference](./index.md).
- [ips](#services-proxy-suite-proxy-routing-rules-ips) - [ips](#services-proxy-suite-proxy-routing-rules-ips)
- [outbound](#services-proxy-suite-proxy-routing-rules-outbound) - [outbound](#services-proxy-suite-proxy-routing-rules-outbound)
- [selection](#services-proxy-suite-proxy-selection) - [selection](#services-proxy-suite-proxy-selection)
- [selectionExclude](#services-proxy-suite-proxy-selectionexclude)
- singBox - singBox
- [package](#services-proxy-suite-proxy-singbox-package) - [package](#services-proxy-suite-proxy-singbox-package)
- [clashApiPort](#services-proxy-suite-proxy-singbox-clashapiport) - [clashApiPort](#services-proxy-suite-proxy-singbox-clashapiport)
@@ -345,9 +346,9 @@ null
In TUN mode (global and per-app), answer A queries from the TUN with a fake address and In TUN mode (global and per-app), answer A queries from the TUN with a fake address and
AAAA ones with nothing; sing-box maps the address back to the name when the connection AAAA ones with nothing; sing-box maps the address back to the name when the connection
comes\. Saves a lookup per new site and no real lookup leaves for proxied names\. Names that comes\. Saves a lookup per new site and no real lookup leaves for proxied names\. Names that
proxy\.dns\.singBox\.rules or the direct geosites send elsewhere keep real answers\. Mappings proxy\.dns\.singBox\.rules or the direct routing lists send elsewhere keep real answers\. The
do not survive a restart: an app holding a fake address fails until it looks the name up addresses handed out are kept in /var/lib/proxy-suite/fakeip, so they survive a restart\.
again\. sing-box and hybrid backends; XRay’s TUN already uses its own fake DNS\. sing-box and hybrid backends; XRay’s TUN already uses its own fake DNS\.
*Type:* *Type:*
boolean boolean
@@ -444,7 +445,9 @@ one of “udp”, “tcp”, “tls”
<a id="services-proxy-suite-proxy-dns-remote"></a> <a id="services-proxy-suite-proxy-dns-remote"></a>
## services\.proxy-suite\.proxy\.dns\.remote ## services\.proxy-suite\.proxy\.dns\.remote
Resolver used through the proxy; the DNS default when proxy\.routing\.default is proxy\. Resolver used through the proxy; the DNS default when proxy\.routing\.default is proxy\. On
sing-box, names the routing sends through the proxy are always looked up here, so the ISP
never sees them, and direct ones locally\.
*Type:* *Type:*
submodule submodule
@@ -1401,6 +1404,32 @@ one of “first”, “selector”, “urltest”
"urltest" "urltest"
``` ```
<a id="services-proxy-suite-proxy-selectionexclude"></a>
## services\.proxy-suite\.proxy\.selectionExclude
Outbound tags selection never picks on its own: hops other outbounds chain through
(` detour `), or exits only routing rules name\. Subscription entries, ` warp `, ` ssh-proxy `
and AmneziaWG tags work too\. A pin still reaches them, and so does a selector switched by
hand\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"ru-vps"
"warp"
]
```
<a id="services-proxy-suite-proxy-singbox-package"></a> <a id="services-proxy-suite-proxy-singbox-package"></a>
## services\.proxy-suite\.proxy\.singBox\.package ## services\.proxy-suite\.proxy\.singBox\.package
@@ -20,7 +20,6 @@ let
inherit (constants) inherit (constants)
xrayDnsBridgePorts xrayDnsBridgePorts
; ;
direct = rules.direct;
defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex; defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex;
defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority; defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority;
@@ -62,14 +61,7 @@ let
# The route mode keeps the user's rules and fake IP, and may drop what sits between. # The route mode keeps the user's rules and fake IP, and may drop what sits between.
rules = rules =
proxyCfg.dns.singBox.rules proxyCfg.dns.singBox.rules
++ lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) { ++ rules.singBoxDnsRules
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
}
# Only what apps ask through the TUN: the XRay sidecar's and sing-box's own lookups # Only what apps ask through the TUN: the XRay sidecar's and sing-box's own lookups
# need real addresses. # need real addresses.
++ lib.optional fakeIp { ++ lib.optional fakeIp {
@@ -119,14 +111,19 @@ let
enableClashApi ? clashApiEnabled, enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled, enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks, xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
# Names the fake IP cache: TUN configs only.
fakeIpCache ? null,
}: }:
let
fakeIp = fakeIpCache != null && proxyCfg.dns.fakeIp.enable;
in
lib.recursiveUpdate (
{ {
log.level = "warn"; log.level = "warn";
dns = mkDnsConfig { dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null; localDetour = if forceLocalDnsViaProxy then "proxy" else null;
inherit useOutboundRoutingMark; inherit useOutboundRoutingMark fakeIp;
fakeIp = enableTun && proxyCfg.dns.fakeIp.enable;
}; };
inbounds = inbounds =
@@ -190,7 +187,17 @@ let
auto_detect_interface = true; auto_detect_interface = true;
}; };
} }
// lib.optionalAttrs enableClashApi clashApiBlock; // lib.optionalAttrs enableClashApi clashApiBlock)
# Fake addresses handed out survive a restart, so apps still holding one keep working. The
# start script creates the directory; nothing else is stored, since TUN configs have no
# Clash API to switch a selector with.
(lib.optionalAttrs fakeIp {
experimental.cache_file = {
enabled = true;
path = "${constants.fakeIpCacheDir}/${fakeIpCache}.db";
store_fakeip = true;
};
});
in in
{ {
tproxy = mkConfig { tproxy = mkConfig {
@@ -211,6 +218,7 @@ in
forceLocalDnsViaProxy = false; forceLocalDnsViaProxy = false;
enableClashApi = false; enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.tun; xrayDnsBridgePort = xrayDnsBridgePorts.tun;
fakeIpCache = "tun";
}; };
perAppTun = mkConfig { perAppTun = mkConfig {
@@ -225,5 +233,6 @@ in
useOutboundRoutingMark = globalTproxy.enable; useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false; enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
fakeIpCache = "per-app-tun";
}; };
} }
+17 -2
View File
@@ -104,8 +104,21 @@ let
proxyInboundViaTags = lib.unique ( proxyInboundViaTags = lib.unique (
builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds) builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds)
); );
# The pinned outbounds and every hop they chain through, which the inbound service renders
# too. A hop that is not a static outbound (a subscription entry, warp) has no tag here.
proxyInboundViaHops =
tags:
let
hops = lib.unique (
builtins.filter (hop: hop != null && !builtins.elem hop tags) (
map (ob: ob.detour) (builtins.filter (ob: builtins.elem ob.tag tags) proxyCfg.outbounds)
)
);
in
if hops == [ ] then tags else proxyInboundViaHops (tags ++ hops);
proxyInboundViaChain = proxyInboundViaHops proxyInboundViaTags;
proxyInboundViaOutbounds = builtins.filter ( proxyInboundViaOutbounds = builtins.filter (
ob: builtins.elem ob.tag proxyInboundViaTags ob: builtins.elem ob.tag proxyInboundViaChain
) proxyCfg.outbounds; ) proxyCfg.outbounds;
proxyInboundUdpTypes = [ proxyInboundUdpTypes = [
@@ -242,6 +255,8 @@ let
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json"; outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536; inboundStatsApiPort = 18536;
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
fakeIpCacheDir = "/var/lib/proxy-suite/fakeip";
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches. # Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
outboundTestPort = 18537; outboundTestPort = 18537;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json"; inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
@@ -275,7 +290,7 @@ let
# Subscription tags are deliberately not accepted: they only exist at runtime. # Subscription tags are deliberately not accepted: they only exist at runtime.
invalidInboundViaTargets = builtins.filter ( invalidInboundViaTargets = builtins.filter (
tag: !builtins.elem tag outboundTags tag: !builtins.elem tag outboundTags
) proxyInboundViaTags; ) proxyInboundViaChain;
invalidRoutingTargets = lib.unique ( invalidRoutingTargets = lib.unique (
map (rule: rule.outbound) ( map (rule: rule.outbound) (
+8 -4
View File
@@ -24,7 +24,11 @@ in
remote = mkOption { remote = mkOption {
type = t.dnsUpstreamType; type = t.dnsUpstreamType;
default = cloudflare; default = cloudflare;
description = "Resolver used through the proxy; the DNS default when proxy.routing.default is proxy."; description = ''
Resolver used through the proxy; the DNS default when proxy.routing.default is proxy. On
sing-box, names the routing sends through the proxy are always looked up here, so the ISP
never sees them, and direct ones locally.
'';
example = { example = {
type = "tls"; type = "tls";
address = "1.1.1.1"; address = "1.1.1.1";
@@ -64,9 +68,9 @@ in
In TUN mode (global and per-app), answer A queries from the TUN with a fake address and In TUN mode (global and per-app), answer A queries from the TUN with a fake address and
AAAA ones with nothing; sing-box maps the address back to the name when the connection AAAA ones with nothing; sing-box maps the address back to the name when the connection
comes. Saves a lookup per new site and no real lookup leaves for proxied names. Names that comes. Saves a lookup per new site and no real lookup leaves for proxied names. Names that
proxy.dns.singBox.rules or the direct geosites send elsewhere keep real answers. Mappings proxy.dns.singBox.rules or the direct routing lists send elsewhere keep real answers. The
do not survive a restart: an app holding a fake address fails until it looks the name up addresses handed out are kept in /var/lib/proxy-suite/fakeip, so they survive a restart.
again. sing-box and hybrid backends; XRay's TUN already uses its own fake DNS. sing-box and hybrid backends; XRay's TUN already uses its own fake DNS.
''; '';
}; };
@@ -68,6 +68,18 @@ in
example = "urltest"; example = "urltest";
}; };
selectionExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Outbound tags selection never picks on its own: hops other outbounds chain through
(`detour`), or exits only routing rules name. Subscription entries, `warp`, `ssh-proxy`
and AmneziaWG tags work too. A pin still reaches them, and so does a selector switched by
hand.
'';
example = [ "ru-vps" "warp" ];
};
urlTest = { urlTest = {
url = mkOption { url = mkOption {
type = types.str; type = types.str;
+5 -4
View File
@@ -5,7 +5,8 @@
# the backend: sing-box sets detour, XRay sockopt.dialerProxy. In hybrid, .xray holds the # the backend: sing-box sets detour, XRay sockopt.dialerProxy. In hybrid, .xray holds the
# sidecar's outbounds, each also standing in .outbounds as a loopback SOCKS hop: a # sidecar's outbounds, each also standing in .outbounds as a loopback SOCKS hop: a
# sing-box outbound may chain through either, a sidecar one only through another # sing-box outbound may chain through either, a sidecar one only through another
# sidecar one, since the sidecar cannot dial through sing-box. # sidecar one, since the sidecar cannot dial through sing-box. Each error is
# {tag, message}, the tag being the outbound that cannot be chained.
def dialer($h): .streamSettings.sockopt.dialerProxy = $h; def dialer($h): .streamSettings.sockopt.dialerProxy = $h;
([.outbounds[].tag]) as $tags ([.outbounds[].tag]) as $tags
@@ -19,14 +20,14 @@ def dialer($h): .streamSettings.sockopt.dialerProxy = $h;
) | from_entries) as $hops ) | from_entries) as $hops
| .errors = ( | .errors = (
[$hops | to_entries[] | select(.value as $v | $tags | index([$v]) | not) [$hops | to_entries[] | select(.value as $v | $tags | index([$v]) | not)
| "outbound '\(.key)' chains through '\(.value)', which is not an outbound"] | {tag: .key, message: "outbound '\(.key)' chains through '\(.value)', which is not an outbound"}]
+ [$hops | keys[] as $t + [$hops | keys[] as $t
| select([limit($hops | length + 1; $t | recurse($hops[.] // empty))][1:] | any(. == $t)) | select([limit($hops | length + 1; $t | recurse($hops[.] // empty))][1:] | any(. == $t))
| "outbound '\($t)' chains back to itself"] | {tag: $t, message: "outbound '\($t)' chains back to itself"}]
+ (if $kind == "hybrid" then + (if $kind == "hybrid" then
[$hops | to_entries[] [$hops | to_entries[]
| select((.key as $t | $xtags | index([$t])) and (.value as $v | $xtags | index([$v]) | not)) | select((.key as $t | $xtags | index([$t])) and (.value as $v | $xtags | index([$v]) | not))
| "outbound '\(.key)' runs on XRay and can only chain through another XRay outbound, not '\(.value)'"] | {tag: .key, message: "outbound '\(.key)' runs on XRay and can only chain through another XRay outbound, not '\(.value)'"}]
else [] end) else [] end)
) )
| if .errors != [] then . | if .errors != [] then .
+2
View File
@@ -84,6 +84,7 @@ let
geoIPRuleSets geoIPRuleSets
singBoxRoutingRules singBoxRoutingRules
singBoxRouteModeRules singBoxRouteModeRules
singBoxDnsRules
; ;
xrayRules = import ./rules/xray.nix { xrayRules = import ./rules/xray.nix {
@@ -111,6 +112,7 @@ in
geoIPRuleSets geoIPRuleSets
singBoxRoutingRules singBoxRoutingRules
singBoxRouteModeRules singBoxRouteModeRules
singBoxDnsRules
xrayRoutingRules xrayRoutingRules
xrayRouteModeRules xrayRouteModeRules
routeModeRules routeModeRules
+26
View File
@@ -116,6 +116,31 @@ let
++ blockRules ++ blockRules
++ proxyGeoRules; ++ proxyGeoRules;
# DNS follows the routing: a name that goes through the proxy is looked up through it, so
# the ISP's resolver never sees it and cannot spoof the answer; a direct one is looked up
# locally. In the routing's order; block entries resolve however the final says.
mkDnsRules =
server: domains: geosites:
lib.optional (domains != [ ]) {
domain_suffix = domains;
inherit server;
}
++ lib.optional (geosites != [ ]) {
rule_set = map (s: "geosite-${s}") geosites;
inherit server;
};
dnsServerFor = category: if category == "direct" then "local" else "remote";
singBoxDnsRules =
lib.concatMap (
rule:
lib.optionals (customRuleCategory rule.outbound != "block") (
mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites
)
) customRules
++ mkDnsRules "remote" r.proxy.domains [ ]
++ mkDnsRules "local" direct.domains direct.geosites
++ mkDnsRules "remote" [ ] r.proxy.geosites;
singBoxRouteModeRules = { singBoxRouteModeRules = {
common = commonRules; common = commonRules;
custom = customRouteRules; custom = customRouteRules;
@@ -132,5 +157,6 @@ in
geoIPRuleSets geoIPRuleSets
singBoxRoutingRules singBoxRoutingRules
singBoxRouteModeRules singBoxRouteModeRules
singBoxDnsRules
; ;
} }
+1 -4
View File
@@ -269,14 +269,11 @@ let
proxyInboundAssertions = [ proxyInboundAssertions = [
(mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ])
"proxy-suite: inbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those." "proxy-suite: inbounds via targets, or the hops they chain through, are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies, warp, ssh-proxy and AmneziaWG outbounds cannot be named here because the inbound service does not run them; use via = \"proxy\" to reach those."
) )
(mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ]) (mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ])
"proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson." "proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson."
) )
(mkAssertion (
!proxyInboundsEnabled || builtins.all (ob: ob.detour == null) derived.proxyInboundViaOutbounds
) "proxy-suite: inbounds via targets a chained outbound (one with detour), which the inbound service cannot render; use via = \"proxy\"")
(requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled (requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled
"proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true" "proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
) )
@@ -54,6 +54,10 @@ let
mkViaOutboundBlock = mkViaOutboundBlock =
ob: ob:
let let
# A chained one dials through its hop, which the chain put in this config too.
dialerBlock = lib.optionalString (ob.detour != null) ''
OB_JSON=$(${jq} -c --arg hop ${lib.escapeShellArg ob.detour} '.streamSettings.sockopt.dialerProxy = $hop' <<< "$OB_JSON")
'';
urlSource = urlSource =
if ob.urlFile != null then if ob.urlFile != null then
ob.urlFile ob.urlFile
@@ -70,6 +74,7 @@ let
builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }) builtins.toJSON (ob.xrayJson // { inherit (ob) tag; })
) )
}) })
${dialerBlock}
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'' ''
else else
@@ -78,6 +83,7 @@ let
URL=$(cat ${lib.escapeShellArg urlSource}) URL=$(cat ${lib.escapeShellArg urlSource})
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \ OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
--backend xray --tag ${lib.escapeShellArg ob.tag}) --backend xray --tag ${lib.escapeShellArg ob.tag})
${dialerBlock}
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
''; '';
@@ -3,7 +3,8 @@
pureXrayEnabled, pureXrayEnabled,
selectionMode, selectionMode,
proxyInboundsGuardPrivate, proxyInboundsGuardPrivate,
userDnsRules, userDnsRules ? [ ],
selectionExclude ? [ ],
}: }:
if pureXrayEnabled then if pureXrayEnabled then
@@ -76,6 +77,14 @@ if pureXrayEnabled then
| if $route_enabled then | if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end else . end
${lib.optionalString (selectionExclude != [ ]) ''
# The balancer's prefix would take in proxy.selectionExclude too: name the rest instead.
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
# rename one of them if that matters.
| ($xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
| if .observatory then .observatory.subjectSelector = $candidates else . end
''}
| if $xray_single_proxy_tag == "" then | if $xray_single_proxy_tag == "" then
. .
else else
@@ -441,13 +441,18 @@ let
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock; mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
runtimeOutboundsBlock = '' runtimeOutboundsBlock = ''
# outbounds added at runtime # outbounds added at runtime, and the hop each one chains through (<tag>.detour)
RUNTIME_DETOURS_JSON='{}'
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
[ -n "$RUNTIME_OB_TAG" ] || continue [ -n "$RUNTIME_OB_TAG" ] || continue
case "$RUNTIME_OB_SRC" in case "$RUNTIME_OB_SRC" in
*.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;; *.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;;
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;; *) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;;
esac || echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2 esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; }
if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then
RUNTIME_DETOURS_JSON=$(${jq} -c --arg t "$RUNTIME_OB_TAG" --rawfile h "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" \
'.[$t] = ($h | rtrimstr("\n"))' <<< "$RUNTIME_DETOURS_JSON")
fi
done < <(_proxy_suite_runtime_outbounds) done < <(_proxy_suite_runtime_outbounds)
''; '';
@@ -465,8 +470,15 @@ let
"xray" "xray"
else else
"sing-box"; "sing-box";
detourBlock = lib.optionalString (detours.outbounds != { } || detours.subscriptions != { }) '' # Always there: `proxy-ctl proxy outbounds add --detour` chains runtime outbounds too. A
# declared chain that cannot be built fails the start. A runtime one is left out with a
# warning, like any other runtime outbound that does not come up, rather than going out
# unchained; whatever chained through it is checked again.
detourBlock = ''
# outbound chaining # outbound chaining
DETOURS_JSON=$(${jq} -c --argjson runtime "$RUNTIME_DETOURS_JSON" '.outbounds = $runtime + .outbounds' \
<<< ${lib.escapeShellArg (builtins.toJSON detours)})
while [ "$DETOURS_JSON" != '{"outbounds":{},"subscriptions":{}}' ]; do
DETOUR_RESULT=$(${jq} -c --argjson xob "${ DETOUR_RESULT=$(${jq} -c --argjson xob "${
if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]" if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"
}" '{outbounds: ., xray: $xob}' <<< "$OUTBOUNDS_JSON" \ }" '{outbounds: ., xray: $xob}' <<< "$OUTBOUNDS_JSON" \
@@ -476,15 +488,25 @@ let
path = ../../outbound-detours.jq; path = ../../outbound-detours.jq;
} }
} \ } \
--argjson d ${lib.escapeShellArg (builtins.toJSON detours)} \ --argjson d "$DETOURS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \ --argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg kind ${detourKind}) --arg kind ${detourKind})
if ${jq} -e '.errors != []' <<< "$DETOUR_RESULT" >/dev/null; then DETOUR_DROP=$(${jq} -c --argjson sources "$OUTBOUND_SOURCES_JSON" \
${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$DETOUR_RESULT" >&2 '[.errors[] | select($sources[.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT")
if ${jq} -e --argjson sources "$OUTBOUND_SOURCES_JSON" 'any(.errors[]; $sources[.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then
${jq} -r '.errors[] | "proxy-suite: " + .message' <<< "$DETOUR_RESULT" >&2
exit 1 exit 1
fi fi
if [ "$DETOUR_DROP" = '[]' ]; then
OUTBOUNDS_JSON=$(${jq} -c '.outbounds' <<< "$DETOUR_RESULT") OUTBOUNDS_JSON=$(${jq} -c '.outbounds' <<< "$DETOUR_RESULT")
${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c '.xray' <<< "$DETOUR_RESULT")''} ${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c '.xray' <<< "$DETOUR_RESULT")''}
break
fi
${jq} -r '.[] | "proxy-suite: warning: ignoring runtime outbound '"'"'\(.tag)'"'"': \(.message)"' <<< "$DETOUR_DROP" >&2
OUTBOUNDS_JSON=$(${jq} -c --argjson drop "$DETOUR_DROP" '[.[] | select(.tag as $t | $drop | any(.tag == $t) | not)]' <<< "$OUTBOUNDS_JSON")
${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c --argjson drop "$DETOUR_DROP" '[.[] | select(.tag as $t | $drop | any(.tag == $t) | not)]' <<< "$XRAY_OUTBOUNDS_JSON")''}
DETOURS_JSON=$(${jq} -c --argjson drop "$DETOUR_DROP" '.outbounds |= with_entries(select(.key as $t | $drop | any(.tag == $t) | not))' <<< "$DETOURS_JSON")
done
''; '';
requireOutboundsBlock = '' requireOutboundsBlock = ''
@@ -510,14 +532,32 @@ let
fi fi
''; '';
# proxy-ctl reads this unprivileged: tags, where each came from, and the pin. # What selection may pick on its own: all but proxy.selectionExclude. A pin and a
# selector switched by hand still reach the excluded ones.
selectableBlock = ''
SELECTABLE_TAGS_JSON=$(${jq} -c --argjson ex ${lib.escapeShellArg (builtins.toJSON proxyCfg.selectionExclude)} \
'map(select(. as $t | $ex | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON")
if [ -z "$PINNED_OUTBOUND" ] && [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 0 ]; then
echo "proxy-suite: every outbound is in proxy.selectionExclude, so there is nothing to select; pin one, or exclude fewer" >&2
exit 1
fi
'';
# proxy-ctl reads this unprivileged: tags, where each came from, the pin, what each one
# chains through, and what selection leaves alone.
inventoryBlock = '' inventoryBlock = ''
${jq} -n \ ${jq} -n \
--argjson tags "$OUTBOUND_TAGS_JSON" \ --argjson tags "$OUTBOUND_TAGS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \ --argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg pinned "$PINNED_OUTBOUND" \ --arg pinned "$PINNED_OUTBOUND" \
--arg selection ${lib.escapeShellArg selectionMode} \ --arg selection ${lib.escapeShellArg selectionMode} \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \ --argjson obs "$OUTBOUNDS_JSON" \
--argjson xobs "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}" \
--argjson selectable "$SELECTABLE_TAGS_JSON" \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
detours: ([($xobs + $obs)[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h
| select($h != null) | {key: .tag, value: $h}] | from_entries),
excluded: ($tags - $selectable)}' \
> "$RUNTIME_DIR/outbounds.json" > "$RUNTIME_DIR/outbounds.json"
chmod 644 "$RUNTIME_DIR/outbounds.json" chmod 644 "$RUNTIME_DIR/outbounds.json"
''; '';
@@ -548,15 +588,15 @@ let
# which is the same path a single-outbound config already takes. # which is the same path a single-outbound config already takes.
if [ -n "$PINNED_OUTBOUND" ]; then if [ -n "$PINNED_OUTBOUND" ]; then
XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PINNED_OUTBOUND" XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PINNED_OUTBOUND"
elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then elif [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")" XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")"
fi fi
'' ''
else if collapseNamedOutbounds then else if collapseNamedOutbounds then
'' ''
PROXY_TAG="$PINNED_OUTBOUND" PROXY_TAG="$PINNED_OUTBOUND"
if [ -z "$PROXY_TAG" ]; then if [ -z "$PROXY_TAG" ]; then
PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") PROXY_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")
fi fi
OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \ OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end 'map(if .tag == $t then .tag = "proxy" else . end
@@ -568,7 +608,7 @@ let
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
DEFAULT_TAG="$PINNED_OUTBOUND" DEFAULT_TAG="$PINNED_OUTBOUND"
if [ -z "$DEFAULT_TAG" ]; then if [ -z "$DEFAULT_TAG" ]; then
DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") DEFAULT_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")
fi fi
WRAPPER=$(${jq} -n \ WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \ --argjson tags "$TAGS" \
@@ -588,7 +628,7 @@ let
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
else else
WRAPPER=$(${jq} -n \ WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \ --argjson tags "$SELECTABLE_TAGS_JSON" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \ --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
@@ -614,6 +654,7 @@ let
+ detourBlock + detourBlock
+ requireOutboundsBlock + requireOutboundsBlock
+ pinBlock + pinBlock
+ selectableBlock
+ inventoryBlock + inventoryBlock
+ wrapperBlock + wrapperBlock
+ exitTagsBlock; + exitTagsBlock;
+1
View File
@@ -151,6 +151,7 @@ let
proxyInboundsGuardPrivate proxyInboundsGuardPrivate
; ;
userDnsRules = proxyCfg.dns.singBox.rules; userDnsRules = proxyCfg.dns.singBox.rules;
inherit (proxyCfg) selectionExclude;
}; };
backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter; backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter;
@@ -338,6 +338,7 @@ let
--arg xray_loglevel "$XRAY_LOGLEVEL" \ --arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \ --arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \ --arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
--argjson xray_selectable "$SELECTABLE_TAGS_JSON" \
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \ --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_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \ --arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
@@ -349,6 +350,10 @@ let
${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$backend_config" ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$backend_config"
chmod ${if enableLocalProxyAuth then "640" else "g+r"} "$backend_config" chmod ${if enableLocalProxyAuth then "640" else "g+r"} "$backend_config"
done done
FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json")
if [ -n "$FAKE_IP_CACHE" ]; then
install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$(dirname "$FAKE_IP_CACHE")"
fi
${ ${
if hybridEnabled then if hybridEnabled then
+148 -2
View File
@@ -68,11 +68,71 @@ let
in in
{ {
assertions = [ assertions = [
# Detours are resolved at start, once subscription entries exist; without any, nothing is added. # Detours are resolved at start, once subscription and runtime entries exist.
( (
assert pkgs.lib.hasInfix ''{"outbounds":{"exit":"primary"},"subscriptions":{"sub":"primary"}}'' (startScript chained); assert pkgs.lib.hasInfix ''{"outbounds":{"exit":"primary"},"subscriptions":{"sub":"primary"}}'' (startScript chained);
assert pkgs.lib.hasInfix "proxy-suite-outbound-detours" (startScript chained); assert pkgs.lib.hasInfix "proxy-suite-outbound-detours" (startScript chained);
assert !(pkgs.lib.hasInfix "outbound chaining" (startScript (evalProxySuite [ baseModule ]))); assert pkgs.lib.hasInfix ''/var/lib/proxy-suite/outbounds.d/$RUNTIME_OB_TAG.detour'' (startScript chained);
true
)
# Selection leaves proxy.selectionExclude alone; the inventory says so.
(
let
script = startScript (evalProxySuite [
baseModule
{ services.proxy-suite.proxy.selectionExclude = [ "primary" ]; }
]);
in
assert pkgs.lib.hasInfix ''--argjson ex '["primary"]' '' script;
assert pkgs.lib.hasInfix ''excluded: ($tags - $selectable)'' script;
true
)
# An inbound pinned to a chained outbound gets the whole chain.
(
let
script = generated.readDerivation
(evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [
{
tag = "hop";
url = "http://hop.example.com:8080";
}
{
tag = "exit";
url = "http://exit.example.com:8080";
detour = "hop";
}
];
};
inbounds = {
enable = true;
serverAddress = "203.0.113.1";
listeners.main = {
type = "socks";
port = 1081;
via = "exit";
users = [
{
name = "a";
password = "b";
}
];
};
};
};
}
]).config.systemd.services."proxy-suite-inbounds".serviceConfig.ExecStart;
in
assert pkgs.lib.hasInfix "# via outbound: hop" script;
assert pkgs.lib.hasInfix "--arg hop hop '.streamSettings.sockopt.dialerProxy = $hop'" script;
true true
) )
@@ -89,9 +149,66 @@ in
assert tunDns.strategy == "ipv4_only"; assert tunDns.strategy == "ipv4_only";
true true
) )
# Fake addresses survive a restart, one cache per TUN config.
(
assert (mkTunConfig dnsFixture).experimental.cache_file.path == "/var/lib/proxy-suite/fakeip/tun.db";
assert (mkTunConfig dnsFixture).experimental.cache_file.store_fakeip;
true
)
# DNS follows the routing: proxied names through remote, direct ones local, in its order.
(
let
routed = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.routing = {
proxy = {
domains = [ "blocked.example" ];
geosites = [ "google" ];
};
rules = [
{
outbound = "direct";
domains = [ "bank.example" ];
}
{
outbound = "block";
domains = [ "ads.example" ];
}
];
};
}
];
rules = map (r: {
inherit (r) server;
match = r.domain_suffix or r.rule_set;
}) (mkTProxyConfig routed).dns.rules;
in
assert
rules == [
{
server = "local";
match = [ "bank.example" ];
}
{
server = "remote";
match = [ "blocked.example" ];
}
{
server = "local";
match = [ "geosite-category-ru" ];
}
{
server = "remote";
match = [ "geosite-google" ];
}
];
true
)
# TProxy has no TUN to hand fake addresses to. # TProxy has no TUN to hand fake addresses to.
( (
assert !(builtins.any (s: s.tag == "fakeip") tproxyDns.servers); assert !(builtins.any (s: s.tag == "fakeip") tproxyDns.servers);
assert !((mkTProxyConfig dnsFixture).experimental ? cache_file);
assert builtins.head tproxyDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; }; assert builtins.head tproxyDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; };
true true
) )
@@ -125,6 +242,35 @@ in
]; ];
}; };
} }
# An inbound cannot chain through what the inbound service does not run.
{
enable = true;
proxy = {
enable = true;
outbounds = [
{
tag = "exit";
url = "http://exit.example.com:8080";
detour = "warp";
}
];
};
inbounds = {
enable = true;
serverAddress = "203.0.113.1";
listeners.main = {
type = "socks";
port = 1081;
via = "exit";
users = [
{
name = "a";
password = "b";
}
];
};
};
}
# The sing-box DNS options need sing-box. # The sing-box DNS options need sing-box.
{ {
enable = true; enable = true;
-6
View File
@@ -8,8 +8,6 @@
hasRuleSet, hasRuleSet,
dnsHasRuleSet, dnsHasRuleSet,
dnsServerByTag, dnsServerByTag,
mkBadFixtureRaw,
mkFailingAssertions,
}: }:
let let
@@ -21,8 +19,6 @@ let
minimal minimal
mkRoutingRules mkRoutingRules
mkTProxyConfig mkTProxyConfig
mkBadFixtureRaw
mkFailingAssertions
; ;
}; };
inherit (fixtures) inherit (fixtures)
@@ -38,7 +34,6 @@ let
proxyDirectConfig proxyDirectConfig
urlTestCustomStartScript urlTestCustomStartScript
noProxyBackendDefaultFixture noProxyBackendDefaultFixture
invalidCoreProxyAssertions
blockGeoRules blockGeoRules
routingOrDomainRules routingOrDomainRules
routingOrGeoIPRules routingOrGeoIPRules
@@ -71,7 +66,6 @@ let
ruDefaultConfig ruDefaultConfig
urlTestCustomStartScript urlTestCustomStartScript
noProxyBackendDefaultFixture noProxyBackendDefaultFixture
invalidCoreProxyAssertions
; ;
}; };
in in
-18
View File
@@ -5,8 +5,6 @@
minimal, minimal,
mkRoutingRules, mkRoutingRules,
mkTProxyConfig, mkTProxyConfig,
mkBadFixtureRaw,
mkFailingAssertions,
}: }:
let let
@@ -138,21 +136,6 @@ let
} }
]; ];
invalidCoreProxyAssertions = mkFailingAssertions mkBadFixtureRaw [
[
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
};
};
}
]
];
blockGeoRules = mkRoutingRules (evalProxySuite [ blockGeoRules = mkRoutingRules (evalProxySuite [
baseModule baseModule
{ {
@@ -188,7 +171,6 @@ in
urlTestCustomFixture urlTestCustomFixture
urlTestCustomStartScript urlTestCustomStartScript
noProxyBackendDefaultFixture noProxyBackendDefaultFixture
invalidCoreProxyAssertions
blockGeoRules blockGeoRules
routingOrDomainRules routingOrDomainRules
routingOrGeoIPRules routingOrGeoIPRules
+1 -3
View File
@@ -7,7 +7,6 @@
ruDefaultConfig, ruDefaultConfig,
urlTestCustomStartScript, urlTestCustomStartScript,
noProxyBackendDefaultFixture, noProxyBackendDefaultFixture,
invalidCoreProxyAssertions,
}: }:
{ {
@@ -53,6 +52,5 @@
assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks"); assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks");
true true
) )
] ];
++ invalidCoreProxyAssertions;
} }
+21 -10
View File
@@ -176,21 +176,33 @@ let
}; };
}; };
}; };
mkFixture = # A bad fixture must fail on its own merits. Without a root file system and with a boot
# loader, NixOS's own assertions fail every system, so any case passed as bad.
mkBootableToplevel =
modules:
forceEval
(evalProxySuite (
[
{
fileSystems."/" = {
device = "none";
fsType = "tmpfs";
};
boot.loader.grub.enable = false;
}
]
++ modules
)).config.system.build.toplevel.drvPath;
mkBadFixture = modules: mkBootableToplevel ([ baseModule ] ++ modules);
mkBadFixtureRaw = mkBootableToplevel;
mkBadProxySuiteFixture =
proxySuiteConfig: proxySuiteConfig:
evalProxySuite [ mkBootableToplevel [
{ {
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = proxySuiteConfig; 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 = mkFailingAssertions =
evaluate: cases: evaluate: cases:
map ( map (
@@ -247,7 +259,6 @@ in
lineContaining lineContaining
shellValueByPrefix shellValueByPrefix
baseModule baseModule
mkFixture
mkBadFixture mkBadFixture
mkBadFixtureRaw mkBadFixtureRaw
mkBadProxySuiteFixture mkBadProxySuiteFixture
-2
View File
@@ -56,8 +56,6 @@ let
hasRuleSet hasRuleSet
dnsHasRuleSet dnsHasRuleSet
dnsServerByTag dnsServerByTag
mkBadFixtureRaw
mkFailingAssertions
; ;
}; };
inherit (coreProxyChecks) ruDefaultConfig; inherit (coreProxyChecks) ruDefaultConfig;
+14 -2
View File
@@ -122,7 +122,8 @@
printf '%s\n' '["community"]' > tags.json printf '%s\n' '["community"]' > tags.json
jq -n '{tags:["own-vps","community-de"], jq -n '{tags:["own-vps","community-de"],
sources:{"own-vps":"static","community-de":"sub:community"}, sources:{"own-vps":"static","community-de":"sub:community"},
pinned:"community-de", selection:"urltest"}' > inventory.json pinned:"community-de", selection:"urltest",
detours:{"community-de":"own-vps"}, excluded:["own-vps"]}' > inventory.json
run() { run() {
env \ env \
@@ -153,6 +154,9 @@
grep -q 'Pinned: community-de' listing grep -q 'Pinned: community-de' listing
grep -q '\*community-de' listing grep -q '\*community-de' listing
grep -q 'own-vps *static' listing grep -q 'own-vps *static' listing
# What each one chains through, and what selection leaves alone.
grep -q 'community-de *sub:community, via own-vps$' listing
grep -q 'own-vps *static, never picked$' listing
# The old spelling still dispatches. # The old spelling still dispatches.
run outbounds | cmp - listing run outbounds | cmp - listing
@@ -184,6 +188,14 @@
run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one' run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one'
[ ! -e obd/spool-one.url ] [ ! -e obd/spool-one.url ]
# --detour leaves the hop next to the entry, and only names an outbound that exists.
! run proxy outbounds add bad-hop http://example.com:1 --detour nope 2>/dev/null
[ ! -e obd/bad-hop.url ]
run proxy outbounds add chained http://example.com:1 --detour own-vps | grep -q 'Added outbound: chained'
[ "$(cat obd/chained.detour)" = own-vps ]
run proxy outbounds rm chained > /dev/null
[ ! -e obd/chained.detour ]
# JSON, as `link --json` prints it, lands as <tag>.json without its own tag; stdin too. # JSON, as `link --json` prints it, lands as <tag>.json without its own tag; stdin too.
run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \ run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \
| grep -q 'Added outbound: from-json' | grep -q 'Added outbound: from-json'
@@ -631,7 +643,7 @@
and .outbounds[0].detour == null and .outbounds[2].detour == "x1"' <<<"$r" > /dev/null and .outbounds[0].detour == null and .outbounds[2].detour == "x1"' <<<"$r" > /dev/null
r="$(d '{"outbounds":{"x1":"sb"},"subscriptions":{}}' '{"x1":"static","sb":"static"}' hybrid \ r="$(d '{"outbounds":{"x1":"sb"},"subscriptions":{}}' '{"x1":"static","sb":"static"}' hybrid \
'{"outbounds":[{"tag":"x1"},{"tag":"sb"}],"xray":[{"tag":"x1"}]}')" '{"outbounds":[{"tag":"x1"},{"tag":"sb"}],"xray":[{"tag":"x1"}]}')"
jq -e '.errors == ["outbound '"'x1'"' runs on XRay and can only chain through another XRay outbound, not '"'sb'"'"]' <<<"$r" > /dev/null jq -e '[.errors[].message] == ["outbound '"'x1'"' runs on XRay and can only chain through another XRay outbound, not '"'sb'"'"]' <<<"$r" > /dev/null
# A missing hop and a loop are errors, and nothing is rewritten. # A missing hop and a loop are errors, and nothing is rewritten.
r="$(d '{"outbounds":{"a":"b","b":"a","c":"gone"},"subscriptions":{}}' '{"a":"static","b":"static","c":"static"}' sing-box \ r="$(d '{"outbounds":{"a":"b","b":"a","c":"gone"},"subscriptions":{}}' '{"a":"static","b":"static","c":"static"}' sing-box \
'{"outbounds":[{"tag":"a"},{"tag":"b"},{"tag":"c"}],"xray":[]}')" '{"outbounds":[{"tag":"a"},{"tag":"b"},{"tag":"c"}],"xray":[]}')"
+3 -2
View File
@@ -95,7 +95,8 @@ in
assert pkgs.lib.hasInfix "all-bypass)" routeModeStartScript; assert pkgs.lib.hasInfix "all-bypass)" routeModeStartScript;
assert pkgs.lib.hasInfix ".route.rules = (sing_box_preserved_rules + $route_rules)" assert pkgs.lib.hasInfix ".route.rules = (sing_box_preserved_rules + $route_rules)"
routeModeBackendJqFilter; routeModeBackendJqFilter;
assert pkgs.lib.hasInfix ".dns.rules = []" routeModeBackendJqFilter; # all-proxy and all-bypass keep proxy.dns.singBox.rules and fake IP.
assert pkgs.lib.hasInfix ".dns.rules = .dns.rules[:0]" routeModeBackendJqFilter;
true true
) )
@@ -153,7 +154,7 @@ in
shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR=" shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR="
== "/var/lib/proxy-suite/subscriptions.d"; == "/var/lib/proxy-suite/subscriptions.d";
assert pkgs.lib.hasInfix "proxy pin [tag]" minimalProxyCtlScript; assert pkgs.lib.hasInfix "proxy pin [tag]" minimalProxyCtlScript;
assert pkgs.lib.hasInfix "proxy outbounds add <tag> <url>" minimalProxyCtlScript; assert pkgs.lib.hasInfix "proxy outbounds add <tag> <url|json|->" minimalProxyCtlScript;
true true
) )
]; ];
+3 -3
View File
@@ -78,7 +78,7 @@ in
( (
assert pkgs.lib.hasInfix ''PROXY_TAG="$PINNED_OUTBOUND"'' subscriptionFirstSelectionStartScript; assert pkgs.lib.hasInfix ''PROXY_TAG="$PINNED_OUTBOUND"'' subscriptionFirstSelectionStartScript;
assert assert
pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end)'' pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end''
subscriptionFirstSelectionStartScript; subscriptionFirstSelectionStartScript;
true true
) )
@@ -147,8 +147,8 @@ in
# The fetcher's output must land in the cache, not after a stray newline. # The fetcher's output must land in the cache, not after a stray newline.
( (
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" > "$cache.tmp"'' subscriptionOnlyStartScript; assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" > "$cache.tmp"'' subscriptionOnlyUpdateScript; assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' subscriptionOnlyUpdateScript;
true true
) )
+2
View File
@@ -131,6 +131,8 @@ let
services.proxy-suite.tgWsProxy = { services.proxy-suite.tgWsProxy = {
enable = true; enable = true;
secretFile = "/run/secrets/tg-ws-proxy"; secretFile = "/run/secrets/tg-ws-proxy";
# Only read when there is a log file to rotate.
log.file = "/var/log/proxy-suite-tg-ws-proxy/tg-ws-proxy.log";
log.keep = 0; log.keep = 0;
}; };
} }
+3 -12
View File
@@ -16,6 +16,9 @@ let
singBoxCfg = null; singBoxCfg = null;
proxyCfg = null; proxyCfg = null;
sshProxyCfg = null; sshProxyCfg = null;
warpCfg = null;
awgOutbounds = null;
constants = null;
hybridEnabled = null; hybridEnabled = null;
collapseNamedOutbounds = null; collapseNamedOutbounds = null;
selectionMode = null; selectionMode = null;
@@ -136,18 +139,6 @@ let
]; ];
}; };
} }
{
enable = true;
proxy = {
enable = true;
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
};
}
{ {
enable = true; enable = true;
proxy = { proxy = {
+28 -5
View File
@@ -53,7 +53,9 @@ A group without a verb shows its status or list.
proxy [status|on|off] local proxy backend proxy [status|on|off] local proxy backend
proxy outbounds [list] outbounds, where each came from, and the pick proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url|json|-> add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin) proxy outbounds add <tag> <url|json|-> [--detour <tag>]
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
chained through another outbound with --detour
proxy outbounds rm <tag> remove a runtime outbound proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download] proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay) TCP ping, real delay, download speed (default: ping, delay)
@@ -349,6 +351,7 @@ COMPLETE = {
"link": "its URL, QR code, JSON or client config", "link": "its URL, QR code, JSON or client config",
} }
}, },
"proxy outbounds add": {"flags": {"--detour": "chain it through another outbound"}},
"proxy outbounds link": { "proxy outbounds link": {
"args": _outbound_choices, "args": _outbound_choices,
"flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"}, "flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"},
@@ -748,7 +751,15 @@ def cmd_outbounds(verb="list", *args):
if verb == "list": if verb == "list":
_outbounds_list() _outbounds_list()
elif verb == "add": elif verb == "add":
_runtime_entry_add("outbound", *args) args = list(args)
detour = ""
if "--detour" in args:
i = args.index("--detour")
detour = args[i + 1] if i + 1 < len(args) else ""
del args[i : i + 2]
if not detour:
usage("proxy outbounds add <tag> <url|json|-> [--detour <tag>]")
_runtime_entry_add("outbound", *args, detour=detour)
elif verb in ("rm", "remove", "del"): elif verb in ("rm", "remove", "del"):
_runtime_entry_rm("outbound", *args) _runtime_entry_rm("outbound", *args)
elif verb == "test": elif verb == "test":
@@ -963,6 +974,8 @@ def _outbounds_list():
inventory = _outbound_inventory() inventory = _outbound_inventory()
pinned = _s(inventory.get("pinned") or "") pinned = _s(inventory.get("pinned") or "")
sources = inventory.get("sources") or {} sources = inventory.get("sources") or {}
detours = inventory.get("detours") or {}
excluded = set(inventory.get("excluded") or [])
current = _outbound_current() current = _outbound_current()
reputation = _reputation_by_tag() reputation = _reputation_by_tag()
@@ -980,7 +993,8 @@ def _outbounds_list():
mark = "*" mark = "*"
elif not pinned and tag == current: elif not pinned and tag == current:
mark = ">" mark = ">"
print(f" {mark}{tag:<34} {rep(tag)}{_s(sources.get(tag) or '-')}") notes = ([f"via {_s(detours[tag])}"] if tag in detours else []) + (["never picked"] if tag in excluded else [])
print(f" {mark}{tag:<34} {rep(tag)}{', '.join([_s(sources.get(tag) or '-'), *notes])}")
# --- sharing ------------------------------------------------------------------ # --- sharing ------------------------------------------------------------------
@@ -1160,11 +1174,14 @@ def _check_runtime_tag(kind, tag):
die(f"A subscription named '{tag}' is declared in the configuration.") die(f"A subscription named '{tag}' is declared in the configuration.")
def _runtime_entry_add(kind, tag="", url="", *_): def _runtime_entry_add(kind, tag="", url="", *_, detour=""):
what = "<url|json|->" if kind == "outbound" else "<url>" what = "<url|json|-> [--detour <tag>]" if kind == "outbound" else "<url>"
if not tag or not url: if not tag or not url:
usage(f"proxy {_runtime_noun(kind)} add <tag> {what}") usage(f"proxy {_runtime_noun(kind)} add <tag> {what}")
_check_runtime_tag(kind, tag) _check_runtime_tag(kind, tag)
# The start script checks the chain again, and leaves the outbound out if it breaks later.
if detour and (detour == tag or detour not in _outbound_tags()):
die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds")
if kind == "outbound" and url == "-": if kind == "outbound" and url == "-":
url = sys.stdin.read() url = sys.stdin.read()
ext = ".url" ext = ".url"
@@ -1177,6 +1194,10 @@ def _runtime_entry_add(kind, tag="", url="", *_):
path = os.path.join(_runtime_dir(kind), tag + ext) path = os.path.join(_runtime_dir(kind), tag + ext)
old = os.umask(0o027) old = os.umask(0o027)
try: try:
# The hop first: the entry is what the start script looks for.
if detour:
with open(os.path.join(_runtime_dir(kind), f"{tag}.detour"), "w", encoding="utf-8") as f:
f.write(f"{detour}\n")
with open(path, "w", encoding="utf-8") as f: with open(path, "w", encoding="utf-8") as f:
f.write(f"{url}\n") f.write(f"{url}\n")
except OSError: except OSError:
@@ -1195,6 +1216,8 @@ def _runtime_entry_rm(kind, tag="", *_):
die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.") die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.")
try: try:
os.unlink(path) os.unlink(path)
if kind == "outbound" and os.path.exists(os.path.join(_runtime_dir(kind), f"{tag}.detour")):
os.unlink(os.path.join(_runtime_dir(kind), f"{tag}.detour"))
except FileNotFoundError: except FileNotFoundError:
pass pass
except OSError: except OSError:
+6 -2
View File
@@ -24,6 +24,11 @@ def _die(message, status=1):
sys.exit(message) sys.exit(message)
# Clash API calls and systemctl spawns that several readers repeat within one load.
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state")
# proxy_ctl as the CLI has it, before the patching below: its own tests put these back.
CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)}
ctl.die = _die ctl.die = _die
_memo = {} # (reader, args) -> result, cleared at the start of every load _memo = {} # (reader, args) -> result, cleared at the start of every load
@@ -39,8 +44,7 @@ def _per_load(fn):
return wrapped return wrapped
# Clash API calls and systemctl spawns that several readers repeat within one load. for _name in MEMOIZED:
for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"):
setattr(ctl, _name, _per_load(getattr(ctl, _name))) setattr(ctl, _name, _per_load(getattr(ctl, _name)))
+13
View File
@@ -5,7 +5,9 @@ import datetime
import io import io
import json import json
import os import os
import shutil
import socket import socket
import sys
import tempfile import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
@@ -13,6 +15,16 @@ from unittest import mock
import proxy_ctl as ctl import proxy_ctl as ctl
def setUpModule():
"""proxy_model, once imported into the same run, patches proxy_ctl for the front ends;
these tests want it the way the CLI runs."""
model = sys.modules.get("proxy_model")
for name, fn in (model.CLI_FUNCTIONS if model else {}).items():
patcher = mock.patch.object(ctl, name, fn)
patcher.start()
unittest.addModuleCleanup(patcher.stop)
def run(fn, *args): def run(fn, *args):
"""(exit status, stdout, stderr) of a proxy-ctl function.""" """(exit status, stdout, stderr) of a proxy-ctl function."""
out, err = io.StringIO(), io.StringIO() out, err = io.StringIO(), io.StringIO()
@@ -642,6 +654,7 @@ class BadExitTest(EnvTest):
class WhereTest(EnvTest): class WhereTest(EnvTest):
"""The route walk has to agree with sing-box and XRay, rule-sets included.""" """The route walk has to agree with sing-box and XRay, rule-sets included."""
@unittest.skipUnless(shutil.which(os.environ.get("SING_BOX", "sing-box")), "sing-box not found; set SING_BOX")
def test_sing_box_walk(self): def test_sing_box_walk(self):
rs = self.write("rs.json", {"version": 1, "rules": [{"domain_suffix": ["youtube.com"]}]}) rs = self.write("rs.json", {"version": 1, "rules": [{"domain_suffix": ["youtube.com"]}]})
config = { config = {