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

+5 -2
View File
@@ -10,7 +10,8 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.
- Global TProxy or TUN mode, on demand or at boot
- Per-app routing: `proxy-ctl apps run <profile> -- <cmd>` through proxychains, a per-app TUN/TProxy, or zapret
- Outbounds from URLs, raw JSON or subscriptions; manual or latency-based selection; per-outbound routing
- vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC on sing-box, XHTTP/ECH on XRay
- vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC, AnyTLS and NaïveProxy on sing-box, XHTTP/ECH on XRay
- Proxy chains: any outbound or a whole subscription can connect through another (`detour`)
- autoProxy: finds which exit reaches a blocked site and routes it there
- zapret DPI bypass, including zapret2, which learns blocked sites at runtime
- AmneziaWG 1.x–3.x tunnels from `.conf`, `vpn://`, or Nix
@@ -164,6 +165,8 @@ A group without a verb shows its status or list.
client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo)
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] traffic per user (sudo, or userControl)
inbounds stats [days] [--by user|inbound|outbound]
traffic per user, listener or exit (sudo, or userControl)
inbounds online who is connected now, and when the rest were last seen
```
<!-- proxy-ctl-help:end -->
+10
View File
@@ -118,6 +118,11 @@ services.proxy-suite = {
autostart = null;
backend = "sing-box";
dns = {
clientSubnet = null;
fakeIp = {
enable = false;
inet4Range = "198.18.0.0/15";
};
local = {
address = "1.1.1.1";
port = 53;
@@ -128,6 +133,11 @@ services.proxy-suite = {
port = 53;
type = "udp";
};
singBox = {
rules = [ ];
servers = [ ];
};
strategy = null;
};
enable = false;
listener = {
+185
View File
@@ -18,6 +18,10 @@ Part of the [proxy-suite options reference](./index.md).
- [autostart](#services-proxy-suite-proxy-autostart)
- [backend](#services-proxy-suite-proxy-backend)
- dns
- [clientSubnet](#services-proxy-suite-proxy-dns-clientsubnet)
- fakeIp
- [enable](#services-proxy-suite-proxy-dns-fakeip-enable)
- [inet4Range](#services-proxy-suite-proxy-dns-fakeip-inet4range)
- [local](#services-proxy-suite-proxy-dns-local)
- [address](#services-proxy-suite-proxy-dns-local-address)
- [port](#services-proxy-suite-proxy-dns-local-port)
@@ -26,6 +30,10 @@ Part of the [proxy-suite options reference](./index.md).
- [address](#services-proxy-suite-proxy-dns-remote-address)
- [port](#services-proxy-suite-proxy-dns-remote-port)
- [type](#services-proxy-suite-proxy-dns-remote-type)
- singBox
- [rules](#services-proxy-suite-proxy-dns-singbox-rules)
- [servers](#services-proxy-suite-proxy-dns-singbox-servers)
- [strategy](#services-proxy-suite-proxy-dns-strategy)
- listener
- [address](#services-proxy-suite-proxy-listener-address)
- auth
@@ -36,6 +44,7 @@ Part of the [proxy-suite options reference](./index.md).
- [outbounds](#services-proxy-suite-proxy-outbounds)
- item
- [backend](#services-proxy-suite-proxy-outbounds-backend)
- [detour](#services-proxy-suite-proxy-outbounds-detour)
- routing
- [domains](#services-proxy-suite-proxy-outbounds-routing-domains)
- [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips)
@@ -78,6 +87,7 @@ Part of the [proxy-suite options reference](./index.md).
- [subscriptionUpdateInterval](#services-proxy-suite-proxy-subscriptionupdateinterval)
- [subscriptions](#services-proxy-suite-proxy-subscriptions)
- item
- [detour](#services-proxy-suite-proxy-subscriptions-detour)
- [tag](#services-proxy-suite-proxy-subscriptions-tag)
- [url](#services-proxy-suite-proxy-subscriptions-url)
- [urlFile](#services-proxy-suite-proxy-subscriptions-urlfile)
@@ -308,6 +318,60 @@ one of “sing-box”, “xray”, “hybrid”
"hybrid"
```
<a id="services-proxy-suite-proxy-dns-clientsubnet"></a>
## services\.proxy-suite\.proxy\.dns\.clientSubnet
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\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"203.0.113.0/24"
```
<a id="services-proxy-suite-proxy-dns-fakeip-enable"></a>
## services\.proxy-suite\.proxy\.dns\.fakeIp\.enable
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\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-proxy-dns-fakeip-inet4range"></a>
## services\.proxy-suite\.proxy\.dns\.fakeIp\.inet4Range
Range the fake addresses come from\.
*Type:*
string
*Default:*
```nix
"198.18.0.0/15"
```
<a id="services-proxy-suite-proxy-dns-local"></a>
## services\.proxy-suite\.proxy\.dns\.local
@@ -447,6 +511,81 @@ one of “udp”, “tcp”, “tls”
"udp"
```
<a id="services-proxy-suite-proxy-dns-singbox-rules"></a>
## services\.proxy-suite\.proxy\.dns\.singBox\.rules
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\.
*Type:*
list of (attribute set)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
{
domain_suffix = [
"corp.example"
];
server = "corp";
}
]
```
<a id="services-proxy-suite-proxy-dns-singbox-servers"></a>
## services\.proxy-suite\.proxy\.dns\.singBox\.servers
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\.
*Type:*
list of (attribute set)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
{
server = "10.0.0.53";
tag = "corp";
type = "udp";
}
]
```
<a id="services-proxy-suite-proxy-dns-strategy"></a>
## services\.proxy-suite\.proxy\.dns\.strategy
Which addresses sing-box asks for\. ` ipv4_only ` for an uplink without IPv6\. sing-box and hybrid backends\.
*Type:*
null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only”
*Default:*
```nix
null
```
*Example:*
```nix
"ipv4_only"
```
<a id="services-proxy-suite-proxy-listener-address"></a>
## services\.proxy-suite\.proxy\.listener\.address
@@ -587,6 +726,29 @@ one of “auto”, “sing-box”, “xray”
"xray"
```
<a id="services-proxy-suite-proxy-outbounds-detour"></a>
## services\.proxy-suite\.proxy\.outbounds\.\*\.detour
Tag of the outbound this one 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\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"ru-vps"
```
<a id="services-proxy-suite-proxy-outbounds-routing-domains"></a>
## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.domains
@@ -1317,6 +1479,29 @@ list of (submodule)
]
```
<a id="services-proxy-suite-proxy-subscriptions-detour"></a>
## services\.proxy-suite\.proxy\.subscriptions\.\*\.detour
Tag of the outbound every entry of this subscription 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\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"ru-vps"
```
<a id="services-proxy-suite-proxy-subscriptions-tag"></a>
## services\.proxy-suite\.proxy\.subscriptions\.\*\.tag
@@ -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
+144
View File
@@ -0,0 +1,144 @@
{
pkgs,
evalProxySuite,
baseModule,
mkTunConfig,
mkTProxyConfig,
mkBadProxySuiteFixture,
mkFailingAssertions,
}:
let
generated = import ./read-generated.nix;
startScript =
fixture: generated.readDerivation fixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart;
chained = evalProxySuite [
baseModule
{
services.proxy-suite.proxy = {
outbounds = [
{
tag = "exit";
url = "http://exit.example.com:8080";
detour = "primary";
}
];
subscriptions = [
{
tag = "sub";
url = "https://example.com/sub";
detour = "primary";
}
];
};
}
];
dnsModule = {
services.proxy-suite.proxy = {
tun.enable = true;
dns = {
strategy = "ipv4_only";
fakeIp.enable = true;
singBox = {
servers = [
{
tag = "corp";
type = "udp";
server = "10.0.0.53";
}
];
rules = [
{
domain_suffix = [ "corp.example" ];
server = "corp";
}
];
};
};
};
};
dnsFixture = evalProxySuite [
baseModule
dnsModule
];
tunDns = (mkTunConfig dnsFixture).dns;
tproxyDns = (mkTProxyConfig dnsFixture).dns;
in
{
assertions = [
# Detours are resolved at start, once subscription entries exist; without any, nothing is added.
(
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 "outbound chaining" (startScript (evalProxySuite [ baseModule ])));
true
)
# User rules first, fake IP last and only for what comes through the TUN.
(
assert builtins.head tunDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; };
assert pkgs.lib.last tunDns.rules == {
inbound = [ "tun-in" ];
query_type = [ "A" "AAAA" ];
server = "fakeip";
};
assert builtins.any (s: s.tag == "fakeip") tunDns.servers;
assert builtins.any (s: s.tag == "corp") tunDns.servers;
assert tunDns.strategy == "ipv4_only";
true
)
# TProxy has no TUN to hand fake addresses to.
(
assert !(builtins.any (s: s.tag == "fakeip") tproxyDns.servers);
assert builtins.head tproxyDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; };
true
)
]
++ mkFailingAssertions mkBadProxySuiteFixture [
# An outbound cannot chain through itself...
{
enable = true;
proxy = {
enable = true;
outbounds = [
{
tag = "loop";
url = "http://proxy.example.com:8080";
detour = "loop";
}
];
};
}
# ...nor through the selector it belongs to.
{
enable = true;
proxy = {
enable = true;
subscriptions = [
{
tag = "sub";
url = "https://example.com/sub";
detour = "proxy";
}
];
};
}
# The sing-box DNS options need sing-box.
{
enable = true;
proxy = {
enable = true;
backend = "xray";
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
dns.fakeIp.enable = true;
};
}
];
}
+12
View File
@@ -157,6 +157,17 @@ let
outboundValidationChecks = import ./outbound-validation.nix {
inherit mkBadProxySuiteFixture mkFailingAssertions;
};
chainingDnsChecks = import ./chaining-dns.nix {
inherit
pkgs
evalProxySuite
baseModule
mkTunConfig
mkTProxyConfig
mkBadProxySuiteFixture
mkFailingAssertions
;
};
amneziaWgChecks = import ./amnezia-wg.nix {
inherit
@@ -264,6 +275,7 @@ let
++ tgWsProxyChecks.assertions
++ xrayBackendChecks.assertions
++ outboundValidationChecks.assertions
++ chainingDnsChecks.assertions
++ amneziaWgChecks.assertions
++ amneziaWgOutboundChecks.assertions
++ zapretChecks.assertions
+48 -5
View File
@@ -578,25 +578,68 @@
''
add=${../../modules/proxy-suite/inbound-stats-add.jq}
now=1789135690 # 2026-09-11
a() { jq -c --argjson q "$1" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; }
a() { jq -c --argjson q "$1" --argjson online "''${3:-{\}}" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; }
# XRay gives values as strings and leaves a zero counter without one.
r='{"stat":[{"name":"user>>>fufsob>>>traffic>>>downlink","value":"3000000"},
{"name":"user>>>fufsob>>>traffic>>>uplink","value":"2000"},
{"name":"user>>>phone>>>traffic>>>uplink"}]}'
{"name":"user>>>phone>>>traffic>>>uplink"},
{"name":"inbound>>>vless-in>>>traffic>>>downlink","value":5},
{"name":"outbound>>>direct>>>traffic>>>uplink","value":6}]}'
s="$(a "$r" '{}')"
s="$(a "$r" "$s")"
jq -e '.days["2026-09-11"].fufsob == {down: 6000000, up: 4000}
and .days["2026-09-11"].phone.up == 0 and .at == 1789135690' <<<"$s" > /dev/null
jq -e '.days["2026-09-11"] | .user.fufsob == {down: 6000000, up: 4000}
and .user.phone.up == 0 and .inbound["vless-in"].down == 10 and .outbound.direct.up == 12' <<<"$s" > /dev/null
jq -e '.at == 1789135690' <<<"$s" > /dev/null
# Nothing counted since the last reading: nothing changes.
jq -e --argjson s "$s" '.days == $s.days' <<<"$(a '{}' "$s")" > /dev/null
# An online user's last seen time is kept, and never goes back.
o='{"users":[{"email":"phone","ips":[{"ip":"203.0.113.7","lastSeen":1789135000},{"ip":"203.0.113.8","lastSeen":1789135600}]}]}'
s="$(a '{}' "$s" "$o")"
jq -e '.seen.phone == 1789135600' <<<"$s" > /dev/null
s="$(a '{}' "$s" '{"users":[{"email":"phone","ips":[{"ip":"203.0.113.7","lastSeen":1}]}]}')"
jq -e '.seen.phone == 1789135600' <<<"$s" > /dev/null
# Days more than a year old are let go.
old="$(jq -c '.days["2024-01-01"] = {fufsob: {up: 1}}' <<<"$s")"
old="$(jq -c '.days["2024-01-01"] = {user: {fufsob: {up: 1}}}' <<<"$s")"
jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null
touch "$out"
'';
# Proxy chains, resolved at start once subscription entries exist.
outbound-detours =
pkgs.runCommand "proxy-suite-outbound-detours-check"
{
nativeBuildInputs = [ pkgs.jq ];
}
''
f=${../../modules/proxy-suite/outbound-detours.jq}
d() { jq -c -f "$f" --argjson d "$1" --argjson sources "$2" --arg kind "$3" <<<"$4"; }
# sing-box: a declared outbound and every entry of a subscription.
r="$(d '{"outbounds":{"de":"ru"},"subscriptions":{"s":"warp"}}' '{"ru":"static","de":"static","s-a":"sub:s","warp":"warp"}' sing-box \
'{"outbounds":[{"tag":"ru"},{"tag":"de"},{"tag":"s-a"},{"tag":"warp"}],"xray":[]}')"
jq -e '.errors == [] and ([.outbounds[] | .detour] == [null, "ru", "warp", null])' <<<"$r" > /dev/null
# XRay: dialerProxy, next to what sockopt already had.
r="$(d '{"outbounds":{"de":"ru"},"subscriptions":{}}' '{"ru":"static","de":"static"}' xray \
'{"outbounds":[{"tag":"ru"},{"tag":"de","streamSettings":{"sockopt":{"mark":1}}}],"xray":[]}')"
jq -e '.outbounds[1].streamSettings.sockopt == {mark: 1, dialerProxy: "ru"}' <<<"$r" > /dev/null
# Hybrid: sidecar outbounds chain in the sidecar, sing-box ones through anything.
r="$(d '{"outbounds":{"x1":"x2","sb":"x1"},"subscriptions":{}}' '{"x1":"static","x2":"static","sb":"static"}' hybrid \
'{"outbounds":[{"tag":"x1"},{"tag":"x2"},{"tag":"sb"}],"xray":[{"tag":"x1"},{"tag":"x2"}]}')"
jq -e '.errors == [] and .xray[0].streamSettings.sockopt.dialerProxy == "x2"
and .outbounds[0].detour == null and .outbounds[2].detour == "x1"' <<<"$r" > /dev/null
r="$(d '{"outbounds":{"x1":"sb"},"subscriptions":{}}' '{"x1":"static","sb":"static"}' hybrid \
'{"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
# 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 \
'{"outbounds":[{"tag":"a"},{"tag":"b"},{"tag":"c"}],"xray":[]}')"
jq -e '(.errors | length) == 3 and all(.outbounds[]; .detour == null)' <<<"$r" > /dev/null
touch "$out"
'';
proxy-ctl-amneziawg =
pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check"
{
+4
View File
@@ -22,6 +22,8 @@
inboundsEnabled,
inboundsLinksFile,
inboundsStatsFile,
inboundsXray,
inboundsApi,
inboundsSubscriptionsFile,
inboundsSubscriptionsBaseUrl,
zapretAutoEnabled,
@@ -62,6 +64,8 @@ let
INBOUNDS_ENABLED = inboundsEnabled;
INBOUNDS_LINKS_FILE = inboundsLinksFile;
INBOUNDS_STATS_FILE = inboundsStatsFile;
INBOUNDS_XRAY = inboundsXray;
INBOUNDS_API = inboundsApi;
INBOUNDS_SUBS_FILE = inboundsSubscriptionsFile;
INBOUNDS_SUB_BASE_URL = inboundsSubscriptionsBaseUrl;
ZAPRET_AUTO_ENABLED = zapretAutoEnabled;
+75 -21
View File
@@ -100,7 +100,9 @@ A group without a verb shows its status or list.
client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo)
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] traffic per user (sudo, or userControl)
inbounds stats [days] [--by user|inbound|outbound]
traffic per user, listener or exit (sudo, or userControl)
inbounds online who is connected now, and when the rest were last seen
"""
ROUTE_MODES = ["whitelist", "blacklist", "all-proxy", "all-bypass"]
@@ -430,9 +432,11 @@ COMPLETE = {
"list": "server inbounds",
"link": "client share link",
"sub": "subscription users, or one user's URL",
"stats": "traffic per user",
"stats": "traffic per user, listener or exit",
"online": "who is connected now",
}
},
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
"inbounds link": {
"args": _inbound_link_choices,
"flags": {"--qr": "print a QR code", "--json": "the client's outbound JSON", "--server-json": "the server's inbound JSON"},
@@ -2408,11 +2412,21 @@ def _today():
return datetime.date.today()
def _inbound_stats(days):
"""Per-user traffic over the last `days` days, newest first, then totals."""
STATS_KINDS = ("user", "inbound", "outbound")
def _inbound_stats(*args):
"""Traffic over the last `days` days by user, inbound or outbound, newest first, then totals."""
days, kind, rest = "7", "user", list(args)
if "--by" in rest:
i = rest.index("--by")
kind = rest[i + 1] if i + 1 < len(rest) else ""
del rest[i : i + 2]
if rest:
days = rest.pop(0)
if rest or kind not in STATS_KINDS or not re.fullmatch(r"[1-9][0-9]*", days):
usage("inbounds stats [days] [--by user|inbound|outbound]")
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
if not re.fullmatch(r"[1-9][0-9]*", days):
usage("inbounds stats [days]")
# Collect what XRay counted since the last run first; root and userControl
# members may, anyone else reads what the timer last wrote.
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
@@ -2420,32 +2434,70 @@ def _inbound_stats(days):
die("No traffic recorded yet - the collector runs every 5 minutes.")
if not readable(path):
die(f"Cannot read {path} - enable userControl, or run with sudo.")
stats = read_json(path)
since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat()
print(f"Traffic through the inbounds since {since}, by user:")
print(f"Traffic through the inbounds since {since}, by {kind}:")
records = [
(day, user, (c or {}).get("down") or 0, (c or {}).get("up") or 0)
for day, users in (read_json(path).get("days") or {}).items()
(day, name, (c or {}).get("down") or 0, (c or {}).get("up") or 0)
for day, kinds in (stats.get("days") or {}).items()
if day >= since
for user, c in users.items()
for name, c in ((kinds or {}).get(kind) or {}).items()
]
if not records:
print(" (nothing recorded)")
return
row = " {:<12} {:<20} {:>10} {:>10}"
print(row.format("DAY", "USER", "DOWN", "UP"))
# Newest day first, users in order within a day.
for day, user, down, up in sorted(sorted(records, key=lambda r: r[1]), key=lambda r: r[0], reverse=True):
print(row.format(day, user, _human_bytes(down), _human_bytes(up)))
print(row.format("DAY", kind.upper(), "DOWN", "UP"))
# Newest day first, names in order within a day.
for day, name, down, up in sorted(sorted(records, key=lambda r: r[1]), key=lambda r: r[0], reverse=True):
print(row.format(day, name, _human_bytes(down), _human_bytes(up)))
totals = {}
for _, user, down, up in records:
d, u = totals.get(user, (0, 0))
totals[user] = (d + down, u + up)
for _, name, down, up in records:
d, u = totals.get(name, (0, 0))
totals[name] = (d + down, u + up)
total = " {:<33} {:>10} {:>10}"
print()
print(total.format("TOTAL", "DOWN", "UP"))
for user, (down, up) in sorted(totals.items()):
print(total.format(user, _human_bytes(down), _human_bytes(up)))
for name, (down, up) in sorted(totals.items()):
print(total.format(name, _human_bytes(down), _human_bytes(up)))
def _inbound_online():
"""Users connected right now with their addresses, then when the others were last seen."""
status, out = _run(
[env("INBOUNDS_XRAY", "xray"), "api", "statsonlineiplist", f"--server={env('INBOUNDS_API', '127.0.0.1:18536')}", "-all"],
capture=True,
quiet=True,
)
if status != 0:
die("The inbounds' stats API is not answering - is proxy-suite-inbounds running?")
try:
online = {_s(u.get("email")): u.get("ips") or [] for u in json.loads(out or "{}").get("users") or []}
except (ValueError, AttributeError):
die("Unexpected answer from the inbounds' stats API.")
# As the timer last wrote it: the API already told who is online now.
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
seen = (read_json(path).get("seen") or {}) if readable(path) else {}
# Users nobody has seen yet, when the links say who exists.
path = env("INBOUNDS_LINKS_FILE")
known = {_s(x.get("user")) for x in read_json(path) if x.get("user")} if readable(path) else set()
def when(ts):
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
row = " {:<20} {:<24} {}"
print(row.format("USER", "STATE", "ADDRESSES"))
for user in sorted(set(online) | set(seen) | known):
ips = online.get(user)
if ips:
print(row.format(user, "online", ", ".join(_s(i.get("ip")) for i in ips)))
elif user in seen:
print(row.format(user, f"seen {when(seen[user])}", ""))
else:
print(row.format(user, "never seen", ""))
sys.stdout.flush()
print("A user counts as online while a connection is open; one relayed through a local web server shows as never seen.", file=sys.stderr)
def _inbound_subscriptions(*args):
@@ -2505,11 +2557,13 @@ def cmd_inbounds(verb="list", *args):
else:
_emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args)
elif verb == "stats":
_inbound_stats(args[0] if args else "7")
_inbound_stats(*args)
elif verb == "online":
_inbound_online()
elif verb == "sub":
_inbound_subscriptions(*args)
else:
usage("inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days]")
usage("inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days] [--by user|inbound|outbound] | online")
# --- main ---------------------------------------------------------------------
+39 -17
View File
@@ -44,6 +44,37 @@ def portable_outbound(ob):
return ob
def _hop(ob):
"""The outbound this one chains through: detour on sing-box, dialerProxy on XRay."""
return ob.get("detour") or ((ob.get("streamSettings") or {}).get("sockopt") or {}).get("dialerProxy")
def _dropped(exits, keep):
"""Exits that stay behind, and why: all but `keep` and the hops it chains through,
loopback hops, and whatever chains through something left behind."""
hops = {o["tag"]: _hop(o) for o in exits}
chain, tag = set(), keep
while tag and tag not in chain:
chain.add(tag)
tag = hops.get(tag)
dropped, warnings = set(), []
for o in exits:
if keep and o["tag"] not in chain:
dropped.add(o["tag"])
elif _loopback(o):
dropped.add(o["tag"])
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
grew = True
while grew:
grew = False
for tag, hop in hops.items():
if tag not in dropped and hop in dropped:
dropped.add(tag)
warnings.append(f"left out {tag}: it chains through {hop}")
grew = True
return dropped, warnings
def _backend_tag(tags, only, prefix=""):
"""The tag `only` has in the backend: as given, prefixed by the XRay wrapper, or the
outbound collapsed into "proxy"."""
@@ -55,24 +86,18 @@ def _backend_tag(tags, only, prefix=""):
def portable_sing_box(cfg, only=None):
cfg = copy.deepcopy(cfg)
warnings = []
obs = cfg.get("outbounds") or []
exits = [o for o in obs if o.get("type") not in SING_BOX_SYSTEM]
keep = _backend_tag({o["tag"] for o in exits}, only) if only else None
dropped = set()
for o in exits:
if keep and o["tag"] != keep:
dropped.add(o["tag"])
elif _loopback(o):
dropped.add(o["tag"])
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
dropped, warnings = _dropped(exits, keep)
dropped |= {o["tag"] for o in obs if o["tag"].startswith("proxy-suite-test")}
obs = [portable_outbound(o) for o in obs if o["tag"] not in dropped]
for o in obs:
if o.get("type") in GROUPS:
o["outbounds"] = [t for t in o.get("outbounds") or [] if t not in dropped]
# Not the hops `keep` chains through: they stay only to be chained through.
o["outbounds"] = [t for t in o.get("outbounds") or [] if t not in dropped and (not keep or t == keep)]
if o.get("default") in dropped:
o.pop("default")
tags = {o["tag"] for o in obs}
@@ -132,18 +157,11 @@ def portable_sing_box(cfg, only=None):
def portable_xray(cfg, only=None):
cfg = copy.deepcopy(cfg)
warnings = []
obs = cfg.get("outbounds") or []
exits = [o for o in obs if o.get("protocol") not in XRAY_SYSTEM]
keep = _backend_tag({o["tag"] for o in exits}, only, "proxy-suite-ob-") if only else None
dropped = set()
for o in exits:
if keep and o["tag"] != keep:
dropped.add(o["tag"])
elif _loopback(o):
dropped.add(o["tag"])
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
dropped, warnings = _dropped(exits, keep)
obs = [portable_outbound(o) for o in obs if o["tag"] not in dropped]
remaining = [o["tag"] for o in obs if o.get("protocol") not in XRAY_SYSTEM]
if not remaining:
@@ -172,6 +190,10 @@ def portable_xray(cfg, only=None):
rule["outboundTag"] = keep or remaining[0]
rules.append(rule)
routing["rules"] = rules
if keep:
# The selector is a tag prefix, which would also pick the hops `keep` chains through.
for balancer in routing.get("balancers") or []:
balancer["selector"] = [keep]
for key in ("api", "stats", "policy"):
cfg.pop(key, None)
return cfg, warnings
+1
View File
@@ -432,6 +432,7 @@ TABS = [
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=ROW, mode="dialog"),
Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
Action("o", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
],
),
Tab(
+22 -3
View File
@@ -351,13 +351,19 @@ class InboundsTest(EnvTest):
"stats.json",
{
"days": {
"2026-09-11": {"fufsob": {"down": 6000000, "up": 4000}, "phone": {"up": 0}},
"2026-09-10": {"fufsob": {"down": 1073741824, "up": 1048576}},
"2026-09-01": {"fufsob": {"down": 1, "up": 1}},
"2026-09-11": {
"user": {"fufsob": {"down": 6000000, "up": 4000}, "phone": {"up": 0}},
"outbound": {"direct": {"down": 7, "up": 8}},
},
"2026-09-10": {"user": {"fufsob": {"down": 1073741824, "up": 1048576}}},
"2026-09-01": {"user": {"fufsob": {"down": 1, "up": 1}}},
}
},
)
out = ok(ctl._inbound_stats, "2")
self.assertNotIn("direct", out)
self.assertRegex(ok(ctl._inbound_stats, "--by", "outbound"), r"(?m)^ 2026-09-11 +direct +7 B +8 B$")
self.assertNotEqual(run(ctl._inbound_stats, "--by", "listener")[0], 0)
# Newest day first, sizes readable, then totals over the period.
self.assertLess(out.index(" 2026-09-11"), out.index(" 2026-09-10"))
self.assertNotIn("2026-09-01", out)
@@ -372,6 +378,19 @@ class InboundsTest(EnvTest):
self.assertNotEqual(status, 0)
self.assertIn("No traffic recorded yet", err)
def test_online(self):
answer = {"users": [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": 1789471207}]}]}
self.patch("_run", lambda *a, **kw: (0, json.dumps(answer)))
os.environ["INBOUNDS_STATS_FILE"] = self.write("stats.json", {"seen": {"phone": 1789135690}})
os.environ["INBOUNDS_LINKS_FILE"] = self.write("links.json", [{"tag": "a", "user": "fufsob"}, {"tag": "a", "user": "teri"}])
out = ok(ctl._inbound_online)
self.assertRegex(out, r"(?m)^ fufsob +online +203\.0\.113\.7$")
self.assertRegex(out, r"(?m)^ phone +seen 2026-09-1\d \d\d:\d\d")
self.assertRegex(out, r"(?m)^ teri +never seen")
# XRay not running is an error, not an empty table.
self.patch("_run", lambda *a, **kw: (1, ""))
self.assertNotEqual(run(ctl._inbound_online)[0], 0)
def test_subscriptions(self):
os.environ["INBOUNDS_SUBS_FILE"] = self.write("subs.json", [{"user": "fufsob", "token": "aaa"}, {"user": "teri", "token": "bbb"}])
os.environ["INBOUNDS_SUB_BASE_URL"] = "https://vpn.example/sub/"
+21
View File
@@ -120,6 +120,20 @@ class SingBoxTest(unittest.TestCase):
with self.assertRaises(ValueError):
export.portable(sing_box_config(), only="nope")
def test_chains(self):
base = sing_box_config()
base["outbounds"][1]["detour"] = "vps"
base["outbounds"].insert(4, {"type": "trojan", "tag": "via-warp", "server": "nl.example.com", "server_port": 443, "password": "x", "detour": "warp"})
base["outbounds"][5]["outbounds"].append("via-warp")
# One server takes its hop along, but not into the group.
cfg, _ = export.portable(base, only="sub-de")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["vps", "sub-de", "proxy", "direct", "block"])
self.assertEqual(cfg["outbounds"][2]["outbounds"], ["sub-de"])
# Chained through a hop that stays behind: stays behind too.
cfg, warnings = export.portable(base)
self.assertNotIn("via-warp", [o["tag"] for o in cfg["outbounds"]])
self.assertIn("left out via-warp: it chains through warp", warnings)
def test_collapsed_proxy(self):
base = sing_box_config()
base["outbounds"] = [{**base["outbounds"][0], "tag": "proxy"}, base["outbounds"][1], *base["outbounds"][6:]]
@@ -164,6 +178,13 @@ class XrayTest(unittest.TestCase):
cfg, _ = export.portable(xray_config(), only="de")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy-suite-ob-de", "direct", "block"])
def test_chains(self):
base = xray_config()
base["outbounds"][1]["streamSettings"] = {"sockopt": {"dialerProxy": "proxy-suite-ob-vps"}}
cfg, _ = export.portable(base, only="de")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy-suite-ob-vps", "proxy-suite-ob-de", "direct", "block"])
self.assertEqual(cfg["routing"]["balancers"][0]["selector"], ["proxy-suite-ob-de"])
if __name__ == "__main__":
unittest.main()
+41
View File
@@ -419,6 +419,44 @@ def parse_tuic(url: str, tag: str) -> dict:
}
def parse_anytls(url: str, tag: str) -> dict:
# anytls://password@host:port?sni=example.com&insecure=1&fp=chrome&alpn=h2
userinfo, host, port, params = _parse_url_parts(url, "anytls")
if not userinfo:
raise ValueError("anytls link is missing the password")
tls = _mk_tls(params.get("sni") or params.get("peer") or host, params.get("fp"), params.get("alpn"))
if params.get("insecure", params.get("allowInsecure", "0")) == "1":
tls["insecure"] = True
return {
"type": "anytls",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": tls,
}
def parse_naive(url: str, tag: str) -> dict:
# naive+https://user:pass@host:port, or naive+quic:// for HTTP/3 (NekoBox's form).
scheme = url.split("://", 1)[0].lower()
userinfo, host, port, params = _parse_url_parts(url, scheme)
ob: dict = {
"type": "naive",
"tag": tag,
"server": host,
"server_port": int(port),
"tls": {"enabled": True, "server_name": params.get("sni") or host},
}
username, password = _mk_auth(userinfo)
if username is not None:
ob["username"] = username
ob["password"] = password
if scheme == "naive+quic":
ob["quic"] = True
return ob
def parse_socks(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5"
@@ -461,6 +499,9 @@ PARSERS = {
"hysteria2": parse_hysteria2,
"hy2": parse_hysteria2,
"tuic": parse_tuic,
"anytls": parse_anytls,
"naive+https": parse_naive,
"naive+quic": parse_naive,
"socks5": parse_socks,
"socks5h": parse_socks,
"socks4": parse_socks,
+16
View File
@@ -274,6 +274,22 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["type"], "tuic")
self.assertEqual(ob["tls"]["alpn"], ["h3", "hq-29"])
def test_anytls(self):
ob = run_parser("anytls://p%40ss@example.com:443?sni=a.example.com&insecure=1&fp=chrome#name")
self.assertEqual(ob["type"], "anytls")
self.assertEqual(ob["password"], "p@ss")
self.assertEqual(ob["tls"], {"enabled": True, "server_name": "a.example.com", "insecure": True,
"utls": {"enabled": True, "fingerprint": "chrome"}})
with self.assertRaisesRegex(ValueError, "unsupported XRay outbound type"):
run_xray_parser("anytls://pw@example.com:443")
def test_naive(self):
ob = run_parser("naive+https://user:pass@example.com:443#name")
self.assertEqual((ob["type"], ob["username"], ob["password"]), ("naive", "user", "pass"))
self.assertEqual(ob["tls"]["server_name"], "example.com")
self.assertNotIn("quic", ob)
self.assertTrue(run_parser("naive+quic://user:pass@example.com:443")["quic"])
def test_socks5(self):
ob = run_parser("socks5://user:pass@example.com:1080")
self.assertEqual(ob["type"], "socks")