feat: cahining + stats

This commit is contained in:
fufsob committed 2026-09-15 11:53:49 +00:00
1 parent 9c9658baa7
commit ea1922243a
28 files changed
+898 -72

No files matched your search

@@ -50,16 +50,26 @@ in
inbounds = [ ];
# Per-user counters for proxy-suite-inbound-stats, on loopback only.
# Counters per user, inbound and outbound for proxy-suite-inbound-stats, and who is
# connected right now, on loopback only.
stats = { };
api = {
tag = "api";
listen = "127.0.0.1:${toString derived.constants.inboundStatsApiPort}";
services = [ "StatsService" ];
};
policy.levels."0" = {
statsUserUplink = true;
statsUserDownlink = true;
policy = {
levels."0" = {
statsUserUplink = true;
statsUserDownlink = true;
statsUserOnline = true;
};
system = {
statsInboundUplink = true;
statsInboundDownlink = true;
statsOutboundUplink = true;
statsOutboundDownlink = true;
};
};
outbounds = localProxyOutbound ++ [
@@ -38,6 +38,7 @@ let
{
localDetour ? null,
useOutboundRoutingMark ? false,
fakeIp ? false,
}:
{
servers = [
@@ -51,17 +52,39 @@ let
bind_interface = ob.interface;
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
) derived.awgInterfaceOutbounds;
) derived.awgInterfaceOutbounds
++ lib.optional fakeIp {
tag = "fakeip";
type = "fakeip";
inet4_range = proxyCfg.dns.fakeIp.inet4Range;
}
++ proxyCfg.dns.singBox.servers;
# The route mode keeps the user's rules and fake IP, and may drop what sits between.
rules =
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
proxyCfg.dns.singBox.rules
++ lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
}
# Only what apps ask through the TUN: the XRay sidecar's and sing-box's own lookups
# need real addresses.
++ lib.optional fakeIp {
inbound = [ "tun-in" ];
query_type = [
"A"
"AAAA"
];
server = "fakeip";
};
final = if (proxyCfg.routing.default == "proxy") then "remote" else "local";
}
// lib.optionalAttrs (proxyCfg.dns.strategy != null) { inherit (proxyCfg.dns) strategy; }
// lib.optionalAttrs (proxyCfg.dns.clientSubnet != null) {
client_subnet = proxyCfg.dns.clientSubnet;
};
xrayDnsBridgeHijackRule = {
@@ -103,6 +126,7 @@ let
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
inherit useOutboundRoutingMark;
fakeIp = enableTun && proxyCfg.dns.fakeIp.enable;
};
inbounds =
+12 -8
View File
@@ -1,14 +1,18 @@
# Adds one reading of XRay's per-user counters ($q, taken with -reset) to the
# daily totals: {days: {"YYYY-MM-DD": {"<email>": {up, down}}}, at}.
# Adds one reading of XRay's counters ($q, taken with -reset) to the daily totals:
# {days: {"YYYY-MM-DD": {user|inbound|outbound: {"<name>": {up, down}}}}, seen, at}.
#
# A counter is named user>>>EMAIL>>>traffic>>>uplink|downlink, and a user's
# email is their name. Its value may come as a string, and a counter still at
# zero comes without one. Down is what the user received, up what they sent.
# The last 366 days are kept.
# A counter is named user|inbound|outbound>>>NAME>>>traffic>>>uplink|downlink, and a
# user's email is their name. Its value may come as a string, and a counter still at
# zero comes without one. Up is what went out towards the destination, down what came
# back. $online is `statsonlineiplist -all`: each online user's last seen time is kept
# in .seen, so an offline user still shows when they were last connected. The last 366
# days are kept.
reduce ($q.stat // [])[] as $s (.;
($s.name | split(">>>")) as $n
| if ($n | length) == 4 and $n[0] == "user" then
.days[$day][$n[1]][if $n[3] == "uplink" then "up" else "down" end] += (($s.value // 0) | tonumber)
| if ($n | length) == 4 and ($n[0] | IN("user", "inbound", "outbound")) and $n[2] == "traffic" then
.days[$day][$n[0]][$n[1]][if $n[3] == "uplink" then "up" else "down" end] += (($s.value // 0) | tonumber)
else . end)
| reduce ($online.users // [])[] as $u (.;
.seen[$u.email] = ([.seen[$u.email] // 0, ($u.ips // [])[].lastSeen] | max))
| .at = $now
| .days = ((.days // {}) | with_entries(select(.key >= ($now - 366 * 86400 | strftime("%Y-%m-%d")))))
+79 -1
View File
@@ -1,7 +1,7 @@
{ lib, ... }:
let
inherit (lib) mkOption;
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
cloudflare = {
type = "udp";
@@ -31,5 +31,83 @@ in
port = 853;
};
};
strategy = mkOption {
type = types.nullOr (
types.enum [
"prefer_ipv4"
"prefer_ipv6"
"ipv4_only"
"ipv6_only"
]
);
default = null;
description = "Which addresses sing-box asks for. `ipv4_only` for an uplink without IPv6. sing-box and hybrid backends.";
example = "ipv4_only";
};
clientSubnet = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
EDNS client subnet sent with every query, so a resolver reached through the proxy still
answers with CDN nodes near this network. sing-box and hybrid backends.
'';
example = "203.0.113.0/24";
};
fakeIp = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
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
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
do not survive a restart: an app holding a fake address fails until it looks the name up
again. sing-box and hybrid backends; XRay's TUN already uses its own fake DNS.
'';
};
inet4Range = mkOption {
type = types.str;
default = "198.18.0.0/15";
description = "Range the fake addresses come from.";
};
};
singBox = {
servers = mkOption {
type = types.listOf types.attrs;
default = [ ];
description = ''
Extra sing-box DNS servers, as sing-box JSON, for proxy.dns.singBox.rules to name. The
built-in ones are `local`, `remote`, and `fakeip` when fakeIp is on.
'';
example = [
{
tag = "corp";
type = "udp";
server = "10.0.0.53";
}
];
};
rules = mkOption {
type = types.listOf types.attrs;
default = [ ];
description = ''
sing-box DNS rules, as sing-box JSON, checked before the generated ones. Kept when the
route mode is all-proxy or all-bypass, which drop the generated ones.
'';
example = [
{
domain_suffix = [ "corp.example" ];
server = "corp";
}
];
};
};
};
}
@@ -17,6 +17,20 @@ let
inherit description example;
};
detourOption =
what:
mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Tag of the outbound ${what} connects through: a proxy chain. Any outbound can be the hop,
subscription entries, `warp`, `ssh-proxy` and AmneziaWG ones included. On hybrid, an
outbound that runs on XRay can only chain through another XRay one. ShadowTLS works this
way too: a `shadowtls` outbound in singBoxJson, and the shadowsocks one with detour naming it.
'';
example = "ru-vps";
};
subscriptionType = types.submodule {
options = {
tag = mkOption {
@@ -26,6 +40,7 @@ let
};
url = nullStr "Subscription URL. Ends up in the Nix store; prefer urlFile." "https://example.com/sub/token123";
urlFile = nullStr "Runtime path to the subscription URL." "/run/secrets/proxy-subscription-url";
detour = detourOption "every entry of this subscription";
};
};
@@ -39,6 +54,7 @@ let
url = nullStr "Proxy URL. Ends up in the Nix store; prefer urlFile." "hy2://password@example.com:443?sni=example.com";
urlFile = nullStr "Runtime path to the proxy URL." "/run/secrets/my-proxy-url";
detour = detourOption "this one";
singBoxJson = nullAttrs "Raw sing-box outbound (sing-box backend); tag is overridden." {
type = "vless";
+40
View File
@@ -0,0 +1,40 @@
# Chains outbounds through their detour hop: {outbounds, xray} -> {outbounds, xray, errors}.
#
# $d is {outbounds: {tag: hop}, subscriptions: {sub tag: hop}}; $sources maps every
# outbound tag to where it came from ("sub:<tag>" for a subscription entry). $kind is
# 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
# sing-box outbound may chain through either, a sidecar one only through another
# sidecar one, since the sidecar cannot dial through sing-box.
def dialer($h): .streamSettings.sockopt.dialerProxy = $h;
([.outbounds[].tag]) as $tags
| ([(.xray // [])[].tag]) as $xtags
| ($sources | to_entries | map(
.key as $t
| ($d.outbounds[$t]
// (if .value | startswith("sub:") then $d.subscriptions[.value[4:]] else null end))
| select(. != null)
| {key: $t, value: .}
) | from_entries) as $hops
| .errors = (
[$hops | to_entries[] | select(.value as $v | $tags | index([$v]) | not)
| "outbound '\(.key)' chains through '\(.value)', which is not an outbound"]
+ [$hops | keys[] as $t
| select([limit($hops | length + 1; $t | recurse($hops[.] // empty))][1:] | any(. == $t))
| "outbound '\($t)' chains back to itself"]
+ (if $kind == "hybrid" then
[$hops | to_entries[]
| 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)'"]
else [] end)
)
| if .errors != [] then .
elif $kind == "xray" then
.outbounds |= map(if $hops[.tag] then dialer($hops[.tag]) else . end)
elif $kind == "hybrid" then
.xray |= map(if $hops[.tag] then dialer($hops[.tag]) else . end)
| .outbounds |= map(.tag as $t | if $hops[$t] and ($xtags | index([$t]) | not) then .detour = $hops[$t] else . end)
else
.outbounds |= map(if $hops[.tag] then .detour = $hops[.tag] else . end)
end
+28 -1
View File
@@ -120,6 +120,16 @@ let
(!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.backend = \"xray\"; use udp/tcp DNS for XRay"
)
(mkAssertion (
!pureXrayEnabled
|| (
proxyCfg.dns.strategy == null
&& proxyCfg.dns.clientSubnet == null
&& !proxyCfg.dns.fakeIp.enable
&& proxyCfg.dns.singBox.servers == [ ]
&& proxyCfg.dns.singBox.rules == [ ]
)
) "proxy-suite: proxy.dns.strategy, clientSubnet, fakeIp and singBox require proxy.backend = \"sing-box\" or \"hybrid\"")
(requireEnabled globalTun.enable proxyEnabled
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
)
@@ -230,7 +240,21 @@ let
(mkAssertion (!(ob.backend == "sing-box") || singBoxEnabled)
"proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid"
)
]) proxyCfg.outbounds;
(mkAssertion (
ob.detour != ob.tag
) "proxy-suite: outbound '${ob.tag}': detour cannot name the outbound itself")
])
proxyCfg.outbounds
++ map (
e:
mkAssertion (
!builtins.elem e.detour [
"proxy"
"direct"
"block"
]
) "proxy-suite: '${e.tag}': detour must name a real outbound, not proxy, direct or block"
) (builtins.filter (e: e.detour != null) (proxyCfg.outbounds ++ proxyCfg.subscriptions));
proxyInboundsCfg = derived.proxyInboundsCfg;
proxyInboundsEnabled = derived.proxyInboundsEnabled;
@@ -250,6 +274,9 @@ let
(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."
)
(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
"proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
)
+1
View File
@@ -186,6 +186,7 @@ let
inherit proxyInboundsEnabled;
inherit (scripts) proxyInboundsLinksFile proxyInboundsSubscriptionsFile;
proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl;
proxyInboundsXray = "${proxyInboundsCfg.package}/bin/xray";
inherit amneziaWgProfileNamesFile;
guiRefreshInterval = cfg.gui.refreshInterval;
inherit (perAppRouting)
+3
View File
@@ -23,6 +23,7 @@
proxyInboundsLinksFile,
proxyInboundsSubscriptionsFile,
proxyInboundsSubscriptionsBaseUrl,
proxyInboundsXray,
guiRefreshInterval,
}:
{
@@ -55,6 +56,8 @@
inboundsEnabled = if proxyInboundsEnabled then "1" else "0";
inboundsLinksFile = proxyInboundsLinksFile;
inboundsStatsFile = constants.inboundStatsFile;
inboundsXray = proxyInboundsXray;
inboundsApi = "127.0.0.1:${toString constants.inboundStatsApiPort}";
inboundsSubscriptionsFile = proxyInboundsSubscriptionsFile;
inboundsSubscriptionsBaseUrl =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
@@ -181,21 +181,24 @@ let
exec ${runXray} ${xray} run -c "$RUNTIME_DIR/config.json"
'';
# Adds XRay's per-user counters to the daily totals, read and reset in one call.
# Adds XRay's counters to the daily totals, read and reset in one call, and notes who
# is online.
# ponytail: a restart of the inbounds loses what was counted since the last run, at
# most one timer interval; collect from ExecStop if that matters.
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" ''
set -euo pipefail
file=${lib.escapeShellArg constants.inboundStatsFile}
if ! reading=$(${xray} api statsquery --server=127.0.0.1:${toString constants.inboundStatsApiPort} \
-pattern 'user>>>' -reset 2> /dev/null); then
api=--server=127.0.0.1:${toString constants.inboundStatsApiPort}
if ! reading=$(${xray} api statsquery "$api" -pattern "" -reset 2> /dev/null); then
echo "the inbounds' stats API is not answering; nothing collected"
exit 0
fi
[ -n "$reading" ] || reading='{}'
online=$(${xray} api statsonlineiplist "$api" -all 2> /dev/null) || online=""
[ -n "$online" ] || online='{}'
[ -s "$file" ] || echo '{}' > "$file"
tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX")
${jq} --argjson q "$reading" \
${jq} --argjson q "$reading" --argjson online "$online" \
--arg day "$(${pkgs.coreutils}/bin/date +%F)" \
--argjson now "$(${pkgs.coreutils}/bin/date +%s)" \
-f ${
@@ -3,6 +3,7 @@
pureXrayEnabled,
selectionMode,
proxyInboundsGuardPrivate,
userDnsRules,
}:
if pureXrayEnabled then
@@ -97,7 +98,10 @@ else
.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
| if $clear_dns_rules then
.dns.rules = .dns.rules[:${toString (builtins.length userDnsRules)}]
+ [.dns.rules[${toString (builtins.length userDnsRules)}:][] | select(.server? == "fakeip")]
else . end
else . end
# autoProxy rules, after the route-mode replace so no mode drops them: pins first
# (they only match their own listener), learned rules last before final, so
@@ -451,6 +451,42 @@ let
done < <(_proxy_suite_runtime_outbounds)
'';
# Declared detours, resolved once every outbound - subscription entries included - exists.
detourMap =
entries: lib.listToAttrs (map (e: lib.nameValuePair e.tag e.detour) (lib.filter (e: e.detour != null) entries));
detours = {
outbounds = detourMap proxyCfg.outbounds;
subscriptions = detourMap proxyCfg.subscriptions;
};
detourKind =
if hybridEnabled then
"hybrid"
else if pureXrayEnabled then
"xray"
else
"sing-box";
detourBlock = lib.optionalString (detours.outbounds != { } || detours.subscriptions != { }) ''
# outbound chaining
DETOUR_RESULT=$(${jq} -c --argjson xob "${
if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"
}" '{outbounds: ., xray: $xob}' <<< "$OUTBOUNDS_JSON" \
| ${jq} -c -f ${
builtins.path {
name = "proxy-suite-outbound-detours";
path = ../../outbound-detours.jq;
}
} \
--argjson d ${lib.escapeShellArg (builtins.toJSON detours)} \
--argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg kind ${detourKind})
if ${jq} -e '.errors != []' <<< "$DETOUR_RESULT" >/dev/null; then
${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$DETOUR_RESULT" >&2
exit 1
fi
OUTBOUNDS_JSON=$(${jq} -c '.outbounds' <<< "$DETOUR_RESULT")
${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c '.xray' <<< "$DETOUR_RESULT")''}
'';
requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
echo "proxy-suite: no proxy outbounds are available; declare one, or add one with 'proxy-ctl proxy outbounds add'" >&2
@@ -506,7 +542,8 @@ let
wrapperBlock =
if pureXrayEnabled && selectionMode == "urltest" then
''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag)
| if .streamSettings.sockopt.dialerProxy? then .streamSettings.sockopt.dialerProxy |= "proxy-suite-ob-" + . else . end)' <<< "$OUTBOUNDS_JSON")
# XRay has no selector: a pin degrades the balancer to the one outbound,
# which is the same path a single-outbound config already takes.
if [ -n "$PINNED_OUTBOUND" ]; then
@@ -522,7 +559,9 @@ let
PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
'map(if .tag == $t then .tag = "proxy" else . end
| if .detour == $t then .detour = "proxy" else . end
| if .streamSettings.sockopt.dialerProxy? == $t then .streamSettings.sockopt.dialerProxy = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
''
else if selectionMode == "selector" then
''
@@ -572,6 +611,7 @@ let
+ sshProxyBlock
+ warpBlock
+ awgBlocks
+ detourBlock
+ requireOutboundsBlock
+ pinBlock
+ inventoryBlock
+1
View File
@@ -150,6 +150,7 @@ let
selectionMode
proxyInboundsGuardPrivate
;
userDnsRules = proxyCfg.dns.singBox.rules;
};
backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter;
@@ -252,7 +252,7 @@ let
elif .settings.vnext then {server: .settings.vnext[0].address, port: .settings.vnext[0].port}
elif .settings.servers then {server: .settings.servers[0].address, port: .settings.servers[0].port}
else null end;
def udp: (.type // .protocol) as $t | ["hysteria", "hysteria2", "tuic"] | index($t) != null;
def udp: (.type // .protocol) as $t | (["hysteria", "hysteria2", "tuic"] | index($t) != null) or .quic? == true;
($sidecar | map({key: .tag, value: .}) | from_entries) as $real
| [.[] | select(.type != "selector" and .type != "urltest")
| (.tag | ltrimstr("proxy-suite-ob-") | if . == "proxy" then $collapsed else . end) as $tag