fix: bug fixes
This commit is contained in:
31 files changed
+626
-121
No files matched your search
@@ -36,6 +36,7 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [mode](#services-proxy-suite-inbounds-listeners-name-transport-mode)
|
||||
- [path](#services-proxy-suite-inbounds-listeners-name-transport-path)
|
||||
- [serviceName](#services-proxy-suite-inbounds-listeners-name-transport-servicename)
|
||||
- [trustedXForwardedFor](#services-proxy-suite-inbounds-listeners-name-transport-trustedxforwardedfor)
|
||||
- [type](#services-proxy-suite-inbounds-listeners-name-transport-type)
|
||||
- [type](#services-proxy-suite-inbounds-listeners-name-type)
|
||||
- [users](#services-proxy-suite-inbounds-listeners-name-users)
|
||||
@@ -644,6 +645,36 @@ string
|
||||
"GunService"
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-inbounds-listeners-name-transport-trustedxforwardedfor"></a>
|
||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.transport\.trustedXForwardedFor
|
||||
|
||||
Header names that mark a request as coming from the web server in front (ws, httpupgrade,
|
||||
xhttp, grpc)\. When one of them is present, XRay takes the client address from
|
||||
“X-Forwarded-For” instead of the socket\. Needed for a listener on a loopback ` address `:
|
||||
XRay otherwise sees 127\.0\.0\.1, which it refuses to record, so ` proxy-ctl inbounds online `
|
||||
shows every user as never seen and the stats keep no last-seen time\.
|
||||
|
||||
Set it only when the web server in front sets both the named header and “X-Forwarded-For”
|
||||
on every request it forwards, overwriting whatever the client sent: any client that can
|
||||
reach the listener directly could otherwise claim any address\.
|
||||
|
||||
*Type:*
|
||||
list of string
|
||||
|
||||
*Default:*
|
||||
|
||||
```nix
|
||||
[ ]
|
||||
```
|
||||
|
||||
*Example:*
|
||||
|
||||
```nix
|
||||
[
|
||||
"X-Real-IP"
|
||||
]
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-inbounds-listeners-name-transport-type"></a>
|
||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.transport\.type
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# because sing-box refuses to start when a local rule-set path is missing, so
|
||||
# every file it will be told about must exist first; the prober needs it to
|
||||
# publish what it learns, which sing-box then picks up without a restart.
|
||||
{ pkgs }:
|
||||
{ pkgs, serviceUser }:
|
||||
|
||||
pkgs.writeShellScript "proxy-suite-autoproxy" ''
|
||||
set -euo pipefail
|
||||
@@ -17,13 +17,17 @@ pkgs.writeShellScript "proxy-suite-autoproxy" ''
|
||||
jq -c '.[]' "$1" | while IFS= read -r exit; do
|
||||
tag=$(jq -r '.tag' <<<"$exit")
|
||||
path=$(jq -r '.path' <<<"$exit")
|
||||
# sing-box, running as ${serviceUser}, watches this directory to reload the
|
||||
# files: that takes read on it, not just the search the state dir grants.
|
||||
# Asserted on every render, since StateDirectory= re-owns the tree when the
|
||||
# units' Group= changes.
|
||||
install -d -m 0750 -g ${serviceUser} "$(dirname "$path")"
|
||||
# Written aside and renamed into place: sing-box reloads on rename (as well
|
||||
# as on in-place writes), and it never reads a half-written file.
|
||||
jq -c --arg t "$tag" '
|
||||
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
|
||||
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
|
||||
' "$2" > "$path.tmp"
|
||||
# sing-box reads it as proxy-suite-daemon through the 0751 state dir.
|
||||
chmod 644 "$path.tmp"
|
||||
mv -f "$path.tmp" "$path"
|
||||
done
|
||||
|
||||
@@ -14,7 +14,10 @@ let
|
||||
apCfg = cfg.proxy.autoProxy;
|
||||
# The autoProxy scope's group writes the directory: `proxy auto learn` queues there.
|
||||
stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751";
|
||||
render = import ./autoproxy-render.nix { inherit pkgs; };
|
||||
render = import ./autoproxy-render.nix {
|
||||
inherit pkgs;
|
||||
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
|
||||
};
|
||||
jqFile =
|
||||
path:
|
||||
builtins.path {
|
||||
@@ -213,13 +216,24 @@ let
|
||||
round1=$(jq -r .r1 <<<"$rounds")
|
||||
round2=$(jq -r .r2 <<<"$rounds")
|
||||
|
||||
# Every probe goes through here: a zero exit with nothing on stdout is no verdict
|
||||
# either, and empty is the one answer that slips through the checks downstream --
|
||||
# jq reads it as no input at all, so `.verdict // "error"' yields "" rather than
|
||||
# "error", and `--argjson r ""' then kills the run. Stdin is the caller's loop.
|
||||
probe_json() {
|
||||
local out
|
||||
out=$(proxy-ctl proxy auto probe --json "$@" < /dev/null 2>/dev/null || true)
|
||||
[ -n "$out" ] || out='{}'
|
||||
printf '%s' "$out"
|
||||
}
|
||||
|
||||
walk() {
|
||||
local out first verdict
|
||||
out=$(proxy-ctl proxy auto probe --json --exits "$round1" "$1" 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --exits "$round1" "$1")
|
||||
verdict=$(jq -r '.verdict // "error"' <<<"$out")
|
||||
if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then
|
||||
first=$out
|
||||
out=$(proxy-ctl proxy auto probe --json --exits "$round2" "$1" 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --exits "$round2" "$1")
|
||||
# Round 1's refusals count against its exits too (see record).
|
||||
out=$(jq -c --argjson f "$first" '.exits = ($f.exits // []) + (.exits // [])' <<<"$out")
|
||||
fi
|
||||
@@ -234,7 +248,7 @@ let
|
||||
# --- 3. re-check remembered exits, once per TTL ---
|
||||
# Probed routes only; slowness routes are judged by the sampler (4b).
|
||||
while IFS=$'\t' read -r dom host exit; do
|
||||
out=$(proxy-ctl proxy auto probe --json --exits "$exit" "$host" 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --exits "$exit" "$host")
|
||||
verdict=$(jq -r '.verdict // "error"' <<<"$out")
|
||||
if [ "$verdict" = destination ] && [ "$(jq -r '.exit // ""' <<<"$out")" = "$exit" ]; then
|
||||
update --arg d "$dom" --argjson now "$now" '.domains[$d].at = $now'
|
||||
@@ -293,14 +307,17 @@ let
|
||||
# --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) ---
|
||||
if [ -s "$state_dir/samples" ]; then
|
||||
mv -f "$state_dir/samples" "$state_dir/samples.taking"
|
||||
# Not `|| echo '[]'`: a grep that matches nothing fails the pipeline after
|
||||
# jq already printed [], and "[]\n[]" is no JSON for --argjson.
|
||||
obs=$(
|
||||
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}'$'\t' "$state_dir/samples.taking" |
|
||||
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"}
|
||||
to_reg |
|
||||
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
|
||||
| {d: .[0], h: .[1], exit: .[2], slow: (.[3] == "slow"), peak: (.[4] | tonumber)})' ||
|
||||
echo '[]'
|
||||
true
|
||||
)
|
||||
[ -n "$obs" ] || obs='[]'
|
||||
rm -f "$state_dir/samples.taking"
|
||||
before=$(jq -c '.domains' "$state")
|
||||
update --argjson o "$obs" --argjson now "$now" --argjson ttl "$ttl" --argjson hits 3 \
|
||||
@@ -317,7 +334,7 @@ let
|
||||
while IFS= read -r tag; do
|
||||
[[ ",$tried," != *",$tag,"* ]] || continue
|
||||
tried="''${tried:+$tried,}$tag"
|
||||
out=$(proxy-ctl proxy auto probe --json --via "$tag" "$host" < /dev/null 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --via "$tag" "$host")
|
||||
verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true)
|
||||
if [ "$verdict" = ok ]; then
|
||||
via=$tag
|
||||
@@ -402,8 +419,8 @@ let
|
||||
# on each start.
|
||||
stateDirConfig = {
|
||||
StateDirectory = "proxy-suite/autoproxy";
|
||||
# 0751 and a 027 umask: sing-box (proxy-suite) can open the rule-sets, which are
|
||||
# made 0644, and nothing else.
|
||||
# 0751 and a 027 umask: sing-box (proxy-suite-daemon) reaches the rule-sets through
|
||||
# rules/, which its group reads (autoproxy-render.nix), and nothing else.
|
||||
StateDirectoryMode = stateDirMode;
|
||||
UMask = "0027";
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ let
|
||||
# The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list.
|
||||
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox";
|
||||
|
||||
# Two ports per "singBox" AmneziaWG outbound, above the autoProxy prober's own
|
||||
# listeners (proxy.autoProxy.probeBasePort, 18540 by default, one per exit):
|
||||
# both bind loopback, so an overlap leaves whichever unit starts second dead.
|
||||
awgTunnelBasePort = 18600;
|
||||
|
||||
# AmneziaWG profiles are either global (proxy-ctl awg on) or outbounds tagged with their name.
|
||||
awgProfiles = lib.optionalAttrs cfg.amneziaWg.enable cfg.amneziaWg.profiles;
|
||||
awgGlobalProfiles = lib.filterAttrs (_: profile: profile.asOutbound == null) awgProfiles;
|
||||
@@ -65,8 +70,8 @@ let
|
||||
kind = profile.asOutbound;
|
||||
interface = profile.interfaceName;
|
||||
# Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort.
|
||||
tunnelPort = 18540 + 2 * index;
|
||||
directPort = 18541 + 2 * index;
|
||||
tunnelPort = awgTunnelBasePort + 2 * index;
|
||||
directPort = awgTunnelBasePort + 1 + 2 * index;
|
||||
}
|
||||
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
|
||||
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
|
||||
|
||||
@@ -69,6 +69,23 @@ let
|
||||
description = "gRPC service name.";
|
||||
example = "GunService";
|
||||
};
|
||||
|
||||
trustedXForwardedFor = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = ''
|
||||
Header names that mark a request as coming from the web server in front (ws, httpupgrade,
|
||||
xhttp, grpc). When one of them is present, XRay takes the client address from
|
||||
"X-Forwarded-For" instead of the socket. Needed for a listener on a loopback `address`:
|
||||
XRay otherwise sees 127.0.0.1, which it refuses to record, so `proxy-ctl inbounds online`
|
||||
shows every user as never seen and the stats keep no last-seen time.
|
||||
|
||||
Set it only when the web server in front sets both the named header and "X-Forwarded-For"
|
||||
on every request it forwards, overwriting whatever the client sent: any client that can
|
||||
reach the listener directly could otherwise claim any address.
|
||||
'';
|
||||
example = [ "X-Real-IP" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -87,11 +87,28 @@ let
|
||||
++ (if syncZapretDirectUserIps then zapretCfg.zapret-discord-youtube.excludeIps else [ ])
|
||||
);
|
||||
|
||||
# A zapret hostlist marks an exact-match entry with "^" (nfqws syntax, used by
|
||||
# list-general.txt for the DoH resolvers). No proxy backend has such a prefix, so
|
||||
# "^dns.google" copied straight through matches nothing and the entry silently
|
||||
# stops bypassing; as a plain suffix it covers the name itself, which is the point.
|
||||
# The generated nfqws hostlists keep the prefix: only the routing sync drops it.
|
||||
stripExactPrefix = lib.removePrefix "^";
|
||||
|
||||
zapretDirectDomains =
|
||||
if syncZapretDirectDomains then
|
||||
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains)) (
|
||||
lib.unique (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
|
||||
)
|
||||
subtractItems
|
||||
(lib.unique (
|
||||
map stripExactPrefix (
|
||||
zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains
|
||||
)
|
||||
))
|
||||
(
|
||||
lib.unique (
|
||||
map stripExactPrefix (
|
||||
zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains
|
||||
)
|
||||
)
|
||||
)
|
||||
else
|
||||
[ ];
|
||||
zapretDirectIps =
|
||||
|
||||
@@ -56,6 +56,23 @@ let
|
||||
condition: value: disallowed: message:
|
||||
mkAssertion (!(condition && builtins.elem value disallowed)) message;
|
||||
|
||||
# Every loopback listener proxy-suite opens with a fixed port of its own, which
|
||||
# the autoProxy prober's range must stay clear of.
|
||||
reservedLoopbackPorts =
|
||||
builtins.attrValues constants.xrayDnsBridgePorts
|
||||
++ [
|
||||
constants.inboundStatsApiPort
|
||||
constants.outboundTestPort
|
||||
]
|
||||
++ lib.optionals derived.warpOutboundEnabled [
|
||||
derived.warpCfg.tunnelPort
|
||||
derived.warpCfg.directPort
|
||||
]
|
||||
++ lib.concatMap (ob: [
|
||||
ob.tunnelPort
|
||||
ob.directPort
|
||||
]) (builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds);
|
||||
|
||||
featureAssertions = [
|
||||
# Declaring no outbound at all is legal: they can be added at runtime with
|
||||
# `proxy-ctl proxy outbounds add`. Only a warning here; the backend still
|
||||
@@ -322,6 +339,22 @@ let
|
||||
)
|
||||
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the inbounds' stats API on ${toString derived.constants.inboundStatsApiPort}, or 18533-18535)"
|
||||
)
|
||||
# The prober opens one loopback listener per exit from probeBasePort; the WARP
|
||||
# and AmneziaWG tunnels open two each from their own bases. They all bind
|
||||
# 127.0.0.1, so an overlap leaves whichever unit starts second dead.
|
||||
(mkAssertion
|
||||
(
|
||||
!(proxyEnabled && proxyCfg.autoProxy.enable)
|
||||
|| !lib.any (
|
||||
port:
|
||||
port >= proxyCfg.autoProxy.probeBasePort
|
||||
&& port < proxyCfg.autoProxy.probeBasePort + proxyCfg.autoProxy.maxExits
|
||||
) reservedLoopbackPorts
|
||||
)
|
||||
"proxy-suite: proxy.autoProxy.probeBasePort ${toString proxyCfg.autoProxy.probeBasePort} and the next ${toString proxyCfg.autoProxy.maxExits} ports cover one proxy-suite already listens on (${
|
||||
lib.concatMapStringsSep ", " toString reservedLoopbackPorts
|
||||
}); move probeBasePort"
|
||||
)
|
||||
]
|
||||
++ lib.concatMap (
|
||||
ib:
|
||||
|
||||
@@ -102,6 +102,18 @@ let
|
||||
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(${jq} -cn --arg name "$tag" '{name:$name}')" >/dev/null 2>&1; then
|
||||
# A live switch skips the restart that rewrites the inventory, and the pin
|
||||
# is only ever read from there: without this the outbound reads as merely
|
||||
# current, and the front ends offer no unpin until the next restart.
|
||||
if [ -f "${outboundInventoryFile}" ]; then
|
||||
INVENTORY_TMP=$(mktemp "${outboundInventoryFile}.XXXXXX")
|
||||
if ${jq} --arg t "$tag" '.pinned = $t' "${outboundInventoryFile}" > "$INVENTORY_TMP"; then
|
||||
chmod 644 "$INVENTORY_TMP"
|
||||
mv -f "$INVENTORY_TMP" "${outboundInventoryFile}"
|
||||
else
|
||||
rm -f "$INVENTORY_TMP"
|
||||
fi
|
||||
fi
|
||||
${restartActiveBlock tunConsumers}
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -275,4 +275,39 @@ lib.mkMerge [
|
||||
|
||||
systemd.timers = mkNamedUnits timerEntries;
|
||||
}
|
||||
|
||||
# A certificate or key XRay cannot read is copied in at start (proxy-inbounds-scripts.nix),
|
||||
# and a copy never sees a renewal: restart the inbounds when a declared one changes.
|
||||
# ponytail: files named only inside xrayJson are not watched; declare tls.* for those.
|
||||
(
|
||||
let
|
||||
certFiles = lib.unique (
|
||||
lib.concatMap (
|
||||
l:
|
||||
lib.filter (f: f != null) [
|
||||
l.tls.certificateFile
|
||||
l.tls.keyFile
|
||||
]
|
||||
) (builtins.attrValues cfg.inbounds.listeners)
|
||||
);
|
||||
in
|
||||
lib.mkIf (cfg.enable && proxyInboundsEnabled && certFiles != [ ]) {
|
||||
systemd.paths.proxy-suite-inbounds-certs = {
|
||||
description = "proxy-suite - watch the inbounds' TLS certificates for renewals";
|
||||
wantedBy = [ "paths.target" ];
|
||||
pathConfig.PathChanged = certFiles;
|
||||
};
|
||||
systemd.services.proxy-suite-inbounds-certs = {
|
||||
description = "proxy-suite - restart the inbounds onto a renewed certificate";
|
||||
serviceConfig.Type = "oneshot";
|
||||
script = ''
|
||||
# XRay reloads the files it reads itself; only copies go stale.
|
||||
[ -d /run/proxy-suite-inbounds/tls ] || exit 0
|
||||
# A renewal writes the chain and the key one after the other.
|
||||
sleep 10
|
||||
${pkgs.systemd}/bin/systemctl try-restart proxy-suite-inbounds.service
|
||||
'';
|
||||
};
|
||||
}
|
||||
)
|
||||
]
|
||||
@@ -200,13 +200,14 @@ let
|
||||
'';
|
||||
|
||||
# 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.
|
||||
# is online. Run by a timer, and by the inbounds' ExecStop, so a restart loses nothing.
|
||||
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" ''
|
||||
set -euo pipefail
|
||||
file=${lib.escapeShellArg constants.inboundStatsFile}
|
||||
api=--server=127.0.0.1:${toString constants.inboundStatsApiPort}
|
||||
# A timer run and a stop can overlap: each reads and resets part, and both rewrite the file.
|
||||
exec 9> "$file.lock"
|
||||
${pkgs.util-linux}/bin/flock 9
|
||||
if ! reading=$(${xray} api statsquery "$api" -pattern "" -reset 2> /dev/null); then
|
||||
echo "the inbounds' stats API is not answering; nothing collected"
|
||||
exit 0
|
||||
|
||||
@@ -40,7 +40,10 @@ let
|
||||
xraySidecarBasePorts
|
||||
;
|
||||
|
||||
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
|
||||
autoProxyRender = import ../autoproxy-render.nix {
|
||||
inherit pkgs;
|
||||
inherit (constants) serviceUser;
|
||||
};
|
||||
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
|
||||
userControlGroup = lib.escapeShellArg userControlCfg.group;
|
||||
chgrp = "${pkgs.coreutils}/bin/chgrp";
|
||||
@@ -171,9 +174,13 @@ let
|
||||
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
|
||||
${subscriptionCacheHelpersBlock}
|
||||
${lib.optionalString enableLocalProxyAuth ''
|
||||
umask 077
|
||||
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
|
||||
${writeProxychainsConfigBlock}
|
||||
# The umask stays in the subshell: left set, it also narrowed everything
|
||||
# written below, and autoProxy's state.json is group-readable by design.
|
||||
(
|
||||
umask 077
|
||||
${writeProxychainsConfigBlock}
|
||||
)
|
||||
''}
|
||||
${lib.optionalString xrayEnabled ''
|
||||
if [ -r "${xrayLoglevelFile}" ]; then
|
||||
@@ -210,7 +217,7 @@ let
|
||||
AUTOPROXY_RULES_JSON='[]'
|
||||
${lib.optionalString enableAutoProxy ''
|
||||
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
|
||||
# 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside;
|
||||
# 0751: sing-box, running as ${constants.serviceUser}, reaches the rules/ inside;
|
||||
# 0771 with userControl's autoProxy scope, whose group queues learn requests there.
|
||||
install -d -m ${if userControlAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR"
|
||||
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
|
||||
@@ -225,7 +232,7 @@ let
|
||||
| to_entries
|
||||
| map({i: .key, tag: .value, port: ($base + .key),
|
||||
rule_set: ("autoproxy-" + (.key | tostring)),
|
||||
path: ($dir + "/rs-" + (.key | tostring) + ".json")})
|
||||
path: ($dir + "/rules/rs-" + (.key | tostring) + ".json")})
|
||||
' <<< "$EXIT_TAGS_JSON")
|
||||
printf '%s\n' "$PROBE_EXITS_JSON" > "$RUNTIME_DIR/probe-exits.json"
|
||||
# proxy-ctl reads it unprivileged; it holds tags and loopback ports only.
|
||||
|
||||
@@ -105,7 +105,12 @@ let
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = scripts.startInbounds;
|
||||
runtimeDirectory = serviceNames.inbounds;
|
||||
extraServiceConfig = xrayAssetEnv;
|
||||
# The collector's file.
|
||||
stateDirectory = "proxy-suite";
|
||||
# While XRay still runs: what it counted since the last timer run.
|
||||
extraServiceConfig = xrayAssetEnv // {
|
||||
ExecStop = scripts.collectInboundStats;
|
||||
};
|
||||
};
|
||||
}
|
||||
{
|
||||
@@ -246,8 +251,9 @@ let
|
||||
enable = proxyEnabled;
|
||||
name = "proxy-suite-outbound-pin@";
|
||||
value = mkOneshotService {
|
||||
description = "Pin the proxy-suite outbound to %i";
|
||||
execStart = "${scripts.pinOutboundScript} %i";
|
||||
# %I: proxy-ctl systemd-escapes the tag, so "ssh-proxy" arrives as ssh\x2dproxy.
|
||||
description = "Pin the proxy-suite outbound to %I";
|
||||
execStart = "${scripts.pinOutboundScript} %I";
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
};
|
||||
|
||||
@@ -117,12 +117,12 @@ in
|
||||
)
|
||||
# "singBox": a tunnel unit behind a loopback SOCKS hop, fed the prepared profile.
|
||||
(
|
||||
assert hasInfix ''"server":"127.0.0.1","server_port":18542,"tag":"plain","type":"socks"''
|
||||
assert hasInfix ''"server":"127.0.0.1","server_port":18602,"tag":"plain","type":"socks"''
|
||||
singBoxStart;
|
||||
assert hasInfix "_proxy_suite_record_tag_source plain awg" singBoxStart;
|
||||
assert hasInfix "--output \"$profile\"" plainTunnel && !(hasInfix "--outbound-fwmark" plainTunnel);
|
||||
assert hasInfix "warp_outbound.py --tag plain --routing-mark 2" plainTunnel;
|
||||
assert hasInfix "listen_port: 18542" plainTunnel;
|
||||
assert hasInfix "listen_port: 18602" plainTunnel;
|
||||
assert hasInfix ''detour: "plain"'' plainTunnel;
|
||||
assert !(services ? proxy-suite-awg-plain-watchdog);
|
||||
true
|
||||
|
||||
@@ -568,6 +568,13 @@ let
|
||||
(assert !builtins.elem "proxy-suite-socks.service" (service exitFixture).after; true)
|
||||
# Not `requires`: direct-routed listeners keep serving if the client is down.
|
||||
(assert (service relayFixture).requires == [ ]; true)
|
||||
# A stop collects what XRay counted since the last timer run.
|
||||
(
|
||||
assert
|
||||
(service relayFixture).serviceConfig.ExecStop
|
||||
== relayFixture.config.systemd.services."proxy-suite-inbound-stats".serviceConfig.ExecStart;
|
||||
true
|
||||
)
|
||||
|
||||
# The collected stats are group-readable with userControl, root-only without.
|
||||
(
|
||||
|
||||
@@ -588,6 +588,41 @@
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
# A probe that exits 0 printing nothing: jq reads "" as no input at all, so the
|
||||
# "error" guard downstream saw "" instead of "error" and let it through to
|
||||
# `--argjson r ""`, which failed every autoProxy run until the state changed.
|
||||
# The helper is taken from the module, so it is the code the runner really uses.
|
||||
autoproxy-probe-json =
|
||||
pkgs.runCommand "proxy-suite-autoproxy-probe-json-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.jq
|
||||
pkgs.gnused
|
||||
pkgs.coreutils
|
||||
];
|
||||
}
|
||||
''
|
||||
sed -n '/^ probe_json() {$/,/^ }$/p' ${../../modules/proxy-suite/autoproxy.nix} > helper.sh
|
||||
test -s helper.sh
|
||||
|
||||
mkdir -p stub
|
||||
printf '%s\n' '#!/bin/sh' 'exit 0' > stub/proxy-ctl
|
||||
chmod +x stub/proxy-ctl
|
||||
export PATH="$PWD/stub:$PATH"
|
||||
|
||||
set -euo pipefail
|
||||
. ./helper.sh
|
||||
# $out is the derivation's; the helper's own "out" is local to it.
|
||||
res=$(probe_json --exits direct example.test)
|
||||
test "$res" = '{}'
|
||||
# What the callers ask, and what used to come back empty.
|
||||
test "$(jq -r '.verdict // "error"' <<<"$res")" = error
|
||||
# And an update() built from it still runs.
|
||||
jq -e -n --argjson r "$res" '$r == {}' > /dev/null
|
||||
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
# Per-user inbound traffic collection; `proxy-ctl inbounds stats` is in proxy-ctl-unit.
|
||||
inbound-stats =
|
||||
pkgs.runCommand "proxy-suite-inbound-stats-check"
|
||||
|
||||
@@ -130,6 +130,8 @@ in
|
||||
reloadSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-reload";
|
||||
in
|
||||
assert pinSvc.serviceConfig.RemainAfterExit == false;
|
||||
# proxy-ctl escapes the tag into the instance name; the script needs it back.
|
||||
assert pkgs.lib.hasSuffix " %I" pinSvc.serviceConfig.ExecStart;
|
||||
assert
|
||||
routeModeFixture.config.systemd.services."proxy-suite-outbound-unpin".serviceConfig.ExecStart
|
||||
== "${routeModeControlScripts.pinOutboundScript}";
|
||||
|
||||
+44
-12
@@ -826,10 +826,12 @@ def _clash(method, path, body=None, timeout=10):
|
||||
# The API is on loopback: never through the shell's HTTP(S)_PROXY.
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(
|
||||
f"{env('CLASH_API')}{path}", data=data, method=method, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
try:
|
||||
# Building the request is part of reaching the API: an unset or malformed
|
||||
# CLASH_API is "unreachable", not a traceback out of `status` or `where`.
|
||||
request = urllib.request.Request(
|
||||
f"{env('CLASH_API')}{path}", data=data, method=method, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
with opener.open(request, timeout=timeout) as r:
|
||||
status, raw = r.status, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
@@ -1143,6 +1145,12 @@ def _runtime_dir(kind):
|
||||
return env("RUNTIME_SUBS_DIR", "/var/lib/proxy-suite/subscriptions.d")
|
||||
|
||||
|
||||
def _runtime_hidden(kind):
|
||||
"""The runtime entry dir when it cannot be listed, empty otherwise: the URLs in it make it root-only."""
|
||||
path = _runtime_dir(kind)
|
||||
return path if os.path.isdir(path) and not os.access(path, os.R_OK | os.X_OK) else ""
|
||||
|
||||
|
||||
def _runtime_noun(kind):
|
||||
return "outbounds" if kind == "outbound" else "subs"
|
||||
|
||||
@@ -1315,7 +1323,10 @@ def _subscription_row(tag, source):
|
||||
def _subscription_list():
|
||||
static = _sub_tags()
|
||||
runtime = _runtime_tags("subscription")
|
||||
hidden = _runtime_hidden("subscription")
|
||||
if not static and not runtime:
|
||||
if hidden:
|
||||
denied(hidden)
|
||||
print("No subscriptions configured.")
|
||||
return
|
||||
print(f" {'TAG':<30} {'LAST UPDATED':<22} {'PROXIES':<9} SOURCE")
|
||||
@@ -1323,6 +1334,8 @@ def _subscription_list():
|
||||
_subscription_row(tag, "static")
|
||||
for tag in runtime:
|
||||
_subscription_row(tag, "runtime")
|
||||
if hidden:
|
||||
print(f" (runtime subscriptions are not listed: cannot read {hidden} - {ask_group()})")
|
||||
next_run = _timer_next_run(f"{SUBSCRIPTION_UPDATE}.timer")
|
||||
if next_run:
|
||||
print()
|
||||
@@ -1736,12 +1749,27 @@ def _require_autoproxy():
|
||||
die("proxy.autoProxy is not enabled in this configuration.")
|
||||
|
||||
|
||||
def _autoproxy_unreadable(path):
|
||||
"""The path a refused read stops at, empty when the state is readable or simply not there yet.
|
||||
|
||||
The state dir is 0751, opened to 0771 for the autoProxy scope's group, and
|
||||
state.json inside it stays 0640: a member gets past the directory and a
|
||||
stranger does not, so both are checked.
|
||||
"""
|
||||
if not os.path.isdir(path):
|
||||
return ""
|
||||
if not os.access(path, os.R_OK | os.X_OK):
|
||||
return path
|
||||
state = os.path.join(path, "state.json")
|
||||
return state if os.path.exists(state) and not readable(state) else ""
|
||||
|
||||
|
||||
def _require_autoproxy_readable(path):
|
||||
"""Root-only without userControl: say so rather than show an empty queue."""
|
||||
if not os.path.isdir(path):
|
||||
die("No autoProxy state yet - the prober has not completed a run.")
|
||||
if not os.access(path, os.R_OK | os.X_OK):
|
||||
denied(path)
|
||||
if blocked := _autoproxy_unreadable(path):
|
||||
denied(blocked)
|
||||
|
||||
|
||||
def _autoproxy_state(path):
|
||||
@@ -2045,16 +2073,16 @@ def cmd_zapret_cutoff(verb="status", *_):
|
||||
except OSError:
|
||||
egress = ""
|
||||
print(f"Probed: {datetime.datetime.fromtimestamp(ts):%Y-%m-%d %H:%M} from {egress}")
|
||||
asn = _tsv(os.path.join(path, "asn.txt"))
|
||||
cut = sum(1 for row in asn if row[0][:1].isdigit())
|
||||
# Same test as the probe's own awk (cutoff.nix): a row is a network only when
|
||||
# its first field is entirely digits, so the count and the list cannot disagree.
|
||||
cut = [row[0] for row in _tsv(os.path.join(path, "asn.txt")) if row[0].isdigit()]
|
||||
if not cut:
|
||||
print("Cutoff: none on this line")
|
||||
return
|
||||
print(f"Cutoff: {cut} network(s)")
|
||||
print(f"Cutoff: {len(cut)} network(s)")
|
||||
names = {row[0]: row[1] if len(row) > 1 else "" for row in _tsv(os.path.join(path, "sni.txt")) if row[0].isdigit()}
|
||||
for row in asn:
|
||||
if row[0].isdigit():
|
||||
print(f" AS{row[0]:<8} {names.get(row[0], 'no name - proxy fallback')}")
|
||||
for asn in cut:
|
||||
print(f" AS{asn:<8} {names.get(asn, 'no name - proxy fallback')}")
|
||||
|
||||
|
||||
# --- where --------------------------------------------------------------------
|
||||
@@ -2567,7 +2595,11 @@ def _inbound_online():
|
||||
for user, (state, addresses) in presence.items():
|
||||
print(row.format(user, state, addresses))
|
||||
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 unless it sets X-Forwarded-For.", file=sys.stderr)
|
||||
print(
|
||||
"A user counts as online while a connection is open. Behind a web server that needs the "
|
||||
"listener's transport.trustedXForwardedFor, or everyone reads as never seen.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def _inbound_subscriptions(*args):
|
||||
|
||||
@@ -101,9 +101,13 @@ def portable_sing_box(cfg, only=None):
|
||||
if o.get("default") in dropped:
|
||||
o.pop("default")
|
||||
tags = {o["tag"] for o in obs}
|
||||
if not any(o.get("type") not in SING_BOX_SYSTEM for o in obs):
|
||||
survivors = [o["tag"] for o in obs if o.get("type") not in SING_BOX_SYSTEM]
|
||||
if not survivors:
|
||||
raise ValueError("no outbound here can be used from another device")
|
||||
target = "proxy" if "proxy" in tags else keep or next(o["tag"] for o in obs if o.get("type") not in SING_BOX_SYSTEM)
|
||||
# `keep` is dropped when it is itself a loopback hop, kept in the chain only to be
|
||||
# chained through; a rule still pointing at it stops sing-box on the other device
|
||||
# with "default outbound not found".
|
||||
target = "proxy" if "proxy" in tags else keep if keep in tags else survivors[0]
|
||||
# A group left empty (every exit it had was dropped) routes through what remains.
|
||||
for o in obs:
|
||||
if o.get("type") in GROUPS and not o["outbounds"]:
|
||||
@@ -166,6 +170,8 @@ def portable_xray(cfg, only=None):
|
||||
remaining = [o["tag"] for o in obs if o.get("protocol") not in XRAY_SYSTEM]
|
||||
if not remaining:
|
||||
raise ValueError("no outbound here can be used from another device")
|
||||
# As in portable_sing_box: `keep` is gone when it was a loopback hop.
|
||||
target = keep if keep in remaining else remaining[0]
|
||||
cfg["outbounds"] = obs
|
||||
|
||||
mixed = next((i for i in cfg.get("inbounds") or [] if i.get("tag") == "mixed-in"), {})
|
||||
@@ -187,13 +193,13 @@ def portable_xray(cfg, only=None):
|
||||
rule.pop("outboundTag")
|
||||
rule["balancerTag"] = "proxy"
|
||||
else:
|
||||
rule["outboundTag"] = keep or remaining[0]
|
||||
rule["outboundTag"] = target
|
||||
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]
|
||||
balancer["selector"] = [target]
|
||||
for key in ("api", "stats", "policy"):
|
||||
cfg.pop(key, None)
|
||||
return cfg, warnings
|
||||
|
||||
@@ -45,7 +45,6 @@ CELL_CLASSES = {
|
||||
"pinned": ["accent"],
|
||||
"excluded": ["dim-label"],
|
||||
"queued": ["warning"],
|
||||
"online": ["success"],
|
||||
}
|
||||
TAB_ICONS = {
|
||||
"services": "system-run-symbolic",
|
||||
@@ -252,7 +251,7 @@ def cell_text(name, value):
|
||||
return value, CELL_CLASSES.get(value, [])
|
||||
|
||||
|
||||
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "queued", "online"}
|
||||
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "queued"}
|
||||
|
||||
|
||||
def is_badge(name, value):
|
||||
|
||||
@@ -212,17 +212,28 @@ def subscription_rows(_):
|
||||
count = ctl._subscription_proxy_count_text(cache) if cached else "-"
|
||||
updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-"
|
||||
rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source})
|
||||
# Nothing visible and the runtime entries out of reach: an error, not an empty tab.
|
||||
if not rows and (hidden := ctl._runtime_hidden("subscription")):
|
||||
ctl.denied(hidden)
|
||||
return rows
|
||||
|
||||
|
||||
def subscription_summary():
|
||||
text = f"{ctl.SUBSCRIPTION_UPDATE}: {ctl.svc_state(ctl.SUBSCRIPTION_UPDATE) or 'unknown'}"
|
||||
next_run = ctl._timer_next_run(f"{ctl.SUBSCRIPTION_UPDATE}.timer")
|
||||
return text + (f", next update {ctl._in_time(next_run)}" if next_run else "")
|
||||
text += f", next update {ctl._in_time(next_run)}" if next_run else ""
|
||||
# The path is left out: an empty tab already names it in its "✗ Cannot read" line.
|
||||
if ctl._runtime_hidden("subscription"):
|
||||
text += f"\nRuntime subscriptions are not listed - {ctl.ask_group()}."
|
||||
return text
|
||||
|
||||
|
||||
def autoproxy_rows(_):
|
||||
state = ctl._autoproxy_state(ctl._autoproxy_dir())
|
||||
path = ctl._autoproxy_dir()
|
||||
# Unreadable is not empty: without the autoProxy scope the state stays root-only.
|
||||
if blocked := ctl._autoproxy_unreadable(path):
|
||||
ctl.denied(blocked)
|
||||
state = ctl._autoproxy_state(path)
|
||||
domains = state.get("domains") or {}
|
||||
rows = [
|
||||
{"key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}"}
|
||||
@@ -271,15 +282,13 @@ def _cutoff_status():
|
||||
|
||||
|
||||
def inbound_rows(_):
|
||||
links = ctl._inbound_links()
|
||||
# One XRay API call per load, and only while this tab loads; empty when the API is not answering.
|
||||
presence = _safe(ctl._inbound_presence, fallback=None) or {}
|
||||
rows = []
|
||||
for x in links:
|
||||
row = {"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
|
||||
row["online"] = (presence.get(row["user"]) or ("",))[0]
|
||||
rows.append(row)
|
||||
return rows
|
||||
# No presence column: XRay keys the online map by user alone (no inbound dimension),
|
||||
# so a per-listener row could only repeat the same verdict once per listener. The
|
||||
# "who is online" action shows it once per user, which is the shape the data has.
|
||||
return [
|
||||
{"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
|
||||
for x in ctl._inbound_links()
|
||||
]
|
||||
|
||||
|
||||
def app_rows(_):
|
||||
@@ -485,7 +494,7 @@ TABS = [
|
||||
"inbounds",
|
||||
"Inbounds",
|
||||
_enabled("INBOUNDS_ENABLED"),
|
||||
[("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port"), ("online", "Online")],
|
||||
[("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")],
|
||||
inbound_rows,
|
||||
summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}",
|
||||
actions=[
|
||||
|
||||
+27
-16
@@ -121,7 +121,6 @@ CELL_STYLES = {
|
||||
"pinned": "cyan",
|
||||
"excluded": "dim",
|
||||
"queued": "yellow",
|
||||
"online": "green",
|
||||
}
|
||||
|
||||
|
||||
@@ -496,6 +495,9 @@ class ProxyTui(App):
|
||||
def fill(self, tab_id, states, visible, status, rows, summary):
|
||||
self.loaded[tab_id] = (states, visible, status, rows, summary)
|
||||
self.states, self.status = states, status
|
||||
# A read root could do: ! retries runs, not reads, so the way out is the whole TUI under sudo.
|
||||
if summary.startswith("✗") and model.needs_root(summary.splitlines(), 1):
|
||||
summary += "\n#: run proxy-tui as root (sudo)"
|
||||
self.show_status()
|
||||
if visible != self.shown:
|
||||
self.show_tabs(visible)
|
||||
@@ -711,15 +713,14 @@ class ProxyTui(App):
|
||||
message = f"exit {status}: {message}"
|
||||
if dialog:
|
||||
dialog.write(f"\x1b[31m(exit status {status})\x1b[0m")
|
||||
if len(out) > 1 and not dialog:
|
||||
message += " · o: full output"
|
||||
hints = ["o: full output"] if len(out) > 1 and not dialog else []
|
||||
self.retry = None
|
||||
if model.needs_root(out, status):
|
||||
self.retry = ("dialog" if dialog else "copy" if copy else "run", argv)
|
||||
message = f"{message} · !: retry as root"
|
||||
hints.append("!: retry as root")
|
||||
if dialog:
|
||||
dialog.offer_retry()
|
||||
self.feedback(message, status == 0)
|
||||
self.feedback(message, status == 0, hints)
|
||||
self.action_reload()
|
||||
|
||||
def action_retry_root(self):
|
||||
@@ -730,20 +731,25 @@ class ProxyTui(App):
|
||||
command = f"sudo proxy-ctl {shlex.join(argv)}"
|
||||
root_argv = model.elevated(argv, "sudo")
|
||||
# sudo asks on the terminal, so the run happens there; the output comes back as usual.
|
||||
out, p = [], None
|
||||
out = []
|
||||
with self.suspend():
|
||||
print(f"$ {command}", flush=True)
|
||||
try:
|
||||
p = subprocess.Popen(root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace")
|
||||
for line in p.stdout:
|
||||
print(line, end="", flush=True)
|
||||
out.append(line.rstrip("\n"))
|
||||
status = p.wait()
|
||||
except OSError as e:
|
||||
out.append(f"cannot run sudo: {e}")
|
||||
status = 127
|
||||
except KeyboardInterrupt: # the terminal's Ctrl-C reached sudo too
|
||||
status = p.wait() if p else 130
|
||||
p, status, out = None, 127, [f"cannot run sudo: {e}"]
|
||||
if p:
|
||||
# Ctrl-C at sudo's password prompt is sudo's to handle: raised here it would
|
||||
# escape the app and take the TUI down. Set after the fork, so sudo inherits
|
||||
# the handler it needs, as ctl._run_foreground does.
|
||||
old = signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
try:
|
||||
for line in p.stdout:
|
||||
print(line, end="", flush=True)
|
||||
out.append(line.rstrip("\n"))
|
||||
status = p.wait()
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, old)
|
||||
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
|
||||
if dialog:
|
||||
self.push_screen(dialog)
|
||||
@@ -763,10 +769,15 @@ class ProxyTui(App):
|
||||
|
||||
self.push_screen(Confirm("sudo proxy-tui"), switch)
|
||||
|
||||
def feedback(self, message, ok=None):
|
||||
def feedback(self, message, ok=None, hints=()):
|
||||
"""The bar is one line: what to press next is pinned, so only the message is ellipsized."""
|
||||
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok]
|
||||
text = Text(icon + message, style=style, no_wrap=True, overflow="ellipsis")
|
||||
if tail := "".join(f" · {h}" for h in hints):
|
||||
text.truncate(max(len(icon) + 1, self.size.width - 2 - len(tail)), overflow="ellipsis")
|
||||
text.append(tail, ACCENT) # a rich style: the theme's ansi_* names are markup, not rich colors
|
||||
bar = self.main.query_one("#feedback", Static)
|
||||
bar.update(Text(icon + message, style=style, no_wrap=True, overflow="ellipsis"))
|
||||
bar.update(text)
|
||||
bar.display = True
|
||||
if self.feedback_timer:
|
||||
self.feedback_timer.stop()
|
||||
|
||||
@@ -68,6 +68,17 @@ class EnvTest(unittest.TestCase):
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
|
||||
class ClashApiTest(EnvTest):
|
||||
def test_unset_api_reads_as_unreachable(self):
|
||||
# selection = "first" and the XRay backend leave the API off; a bare
|
||||
# path is not a URL, and it used to escape as a traceback out of
|
||||
# `status`, `where` and `proxy outbounds`.
|
||||
for value in ("", "127.0.0.1:9090"):
|
||||
with self.subTest(api=value), mock.patch.dict(os.environ, {"CLASH_API": value}):
|
||||
self.assertEqual(ctl._clash("GET", "/proxies/proxy", timeout=1), (0, None))
|
||||
self.assertEqual(ctl._outbound_current(), "")
|
||||
|
||||
|
||||
# The verdict table, fed tuples measured on a real censored network.
|
||||
class ProbeVerdictTest(unittest.TestCase):
|
||||
def expect(self, want, direct, via):
|
||||
|
||||
@@ -141,6 +141,25 @@ class SingBoxTest(unittest.TestCase):
|
||||
cfg, _ = export.portable(base, only="vps")
|
||||
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy", "direct", "block"])
|
||||
|
||||
def test_kept_loopback_hop_leaves_no_dangling_reference(self):
|
||||
"""Asking for a loopback hop drops it, so nothing may still point at it:
|
||||
sing-box stops with "default outbound not found" (which `check` does not catch)."""
|
||||
base = sing_box_config()
|
||||
# No group named "proxy", so the export has to choose the target itself.
|
||||
base["outbounds"] = [
|
||||
{"type": "socks", "tag": "warp", "server": "127.0.0.1", "server_port": 40000, "detour": "vps"},
|
||||
base["outbounds"][0],
|
||||
*base["outbounds"][6:],
|
||||
]
|
||||
base["route"] = {"rules": [{"domain": ["a.test"], "outbound": "warp"}], "final": "warp"}
|
||||
cfg, warnings = export.portable(base, only="warp")
|
||||
tags = {o["tag"] for o in cfg["outbounds"]}
|
||||
self.assertNotIn("warp", tags)
|
||||
referenced = {r["outbound"] for r in cfg["route"]["rules"]} | {cfg["route"]["final"]}
|
||||
for o in cfg["outbounds"]:
|
||||
referenced |= set(o.get("outbounds") or [])
|
||||
self.assertEqual(referenced - tags, set(), warnings)
|
||||
|
||||
def test_nothing_portable(self):
|
||||
base = sing_box_config()
|
||||
base["outbounds"] = base["outbounds"][2:4] + base["outbounds"][6:]
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""proxy_model without a front end: the status line and the tray menu turn state into the right proxy-ctl argv."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
@@ -73,12 +75,23 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertEqual(model.toggle_argv(row), ["awg", "on", "warp"]) # a global profile named warp
|
||||
self.assertIn("ctrl+r", keys())
|
||||
|
||||
def test_inbound_presence(self):
|
||||
links = [{"tag": "vless", "user": "alice", "type": "vless", "port": 443}, {"tag": "vless", "user": "bob", "type": "vless", "port": 443}]
|
||||
with mock.patch.object(ctl, "_inbound_links", lambda: links), mock.patch.object(ctl, "_inbound_presence", lambda: {"alice": ("online", "10.0.0.2")}):
|
||||
self.assertEqual([r["online"] for r in model.inbound_rows({})], ["online", ""])
|
||||
with mock.patch.object(ctl, "_inbound_links", lambda: links), mock.patch.object(ctl, "_inbound_presence", lambda: ctl.die("API silent")):
|
||||
self.assertEqual([r["online"] for r in model.inbound_rows({})], ["", ""])
|
||||
def test_inbound_rows_carry_no_presence(self):
|
||||
"""XRay keys the online map by user, not by inbound, so a per-listener row
|
||||
could only repeat one verdict per listener; it must not claim to have one."""
|
||||
links = [
|
||||
{"tag": "ws", "user": "alice", "type": "vless", "port": 443},
|
||||
{"tag": "reality", "user": "alice", "type": "vless", "port": 2053},
|
||||
]
|
||||
called = []
|
||||
with mock.patch.object(ctl, "_inbound_links", lambda: links), mock.patch.object(
|
||||
ctl, "_inbound_presence", lambda: called.append(1) or {}
|
||||
):
|
||||
rows = model.inbound_rows({})
|
||||
self.assertEqual([r["tag"] for r in rows], ["ws", "reality"])
|
||||
self.assertNotIn("online", rows[0])
|
||||
# And the tab no longer pays for the API call on every load.
|
||||
self.assertEqual(called, [])
|
||||
self.assertNotIn("online", [c for c, _ in next(t for t in model.TABS if t.id == "inbounds").columns])
|
||||
|
||||
def test_tray_menu(self):
|
||||
states = {
|
||||
@@ -136,6 +149,39 @@ class ModelTest(unittest.TestCase):
|
||||
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
|
||||
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
|
||||
def test_unreadable_is_not_empty(self):
|
||||
"""A tab that cannot read its state says so; "Nothing here yet." would be a lie."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
state = os.path.join(tmp, "state.json")
|
||||
with open(state, "w") as f:
|
||||
f.write("{}")
|
||||
tab = next(t for t in model.TABS if t.id == "autoproxy")
|
||||
with mock.patch.object(ctl, "_autoproxy_dir", lambda: tmp), mock.patch.object(ctl, "_status_autoproxy", lambda: ""):
|
||||
self.assertIn("Nothing here yet.", model.load_tab(tab, {})[1]) # readable and empty: really empty
|
||||
os.chmod(state, 0)
|
||||
model.new_load()
|
||||
self.assertIn(f"✗ Cannot read {state}", model.load_tab(tab, {})[1])
|
||||
os.chmod(tmp, 0o751) # a stranger to the group: past the dir, stopped at the state
|
||||
model.new_load()
|
||||
self.assertIn(f"✗ Cannot read {state}", model.load_tab(tab, {})[1])
|
||||
os.chmod(tmp, 0)
|
||||
model.new_load()
|
||||
self.assertIn(f"✗ Cannot read {tmp}", model.load_tab(tab, {})[1])
|
||||
os.chmod(tmp, 0o700)
|
||||
|
||||
subs = next(t for t in model.TABS if t.id == "subs")
|
||||
runtime = os.path.join(tmp, "subscriptions.d")
|
||||
os.mkdir(runtime, 0o700)
|
||||
env = {"RUNTIME_SUBS_DIR": runtime, "SUB_CACHE_DIR": tmp}
|
||||
with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)), mock.patch.object(ctl, "_sub_tags", list):
|
||||
model.new_load()
|
||||
self.assertIn("Nothing here yet.", model.load_tab(subs, {})[1])
|
||||
os.chmod(runtime, 0)
|
||||
model.new_load()
|
||||
self.assertIn(f"✗ Cannot read {runtime}", model.load_tab(subs, {})[1])
|
||||
os.chmod(runtime, 0o700)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import io
|
||||
import signal
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
@@ -60,6 +62,19 @@ class TuiTest(unittest.TestCase):
|
||||
):
|
||||
self.assertEqual(model.subscription_rows({})[0]["updated"], "0m ago")
|
||||
|
||||
def test_retry_root_leaves_sigint_to_sudo(self):
|
||||
"""Ctrl-C at sudo's password prompt is sudo's: raised here it would take the TUI down with it."""
|
||||
app = mock.MagicMock(retry=("run", ["proxy", "on"]))
|
||||
app.suspend.return_value = contextlib.nullcontext()
|
||||
before, during = signal.getsignal(signal.SIGINT), []
|
||||
with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()):
|
||||
popen.return_value.stdout = iter(["done\n"])
|
||||
popen.return_value.wait.side_effect = lambda: during.append(signal.getsignal(signal.SIGINT)) or 0
|
||||
tui.ProxyTui.action_retry_root(app)
|
||||
self.assertEqual(during, [signal.SIG_IGN])
|
||||
self.assertEqual(signal.getsignal(signal.SIGINT), before)
|
||||
self.assertEqual(app.finish.call_args.args[-2:], (["done"], 0))
|
||||
|
||||
def test_filter_sort_pack(self):
|
||||
rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}]
|
||||
columns = [("host", "Host"), ("kind", "List")]
|
||||
@@ -197,6 +212,15 @@ class TuiTest(unittest.TestCase):
|
||||
await self.settle(app, pilot)
|
||||
self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content))
|
||||
|
||||
# A tab that cannot read its state says so instead, and how to get the rights for it.
|
||||
with mock.patch.object(ctl, "_runtime_hidden", lambda kind: "/var/lib/proxy-suite/subscriptions.d"), \
|
||||
mock.patch.object(model.os, "geteuid", lambda: 1000):
|
||||
app.action_reload()
|
||||
await self.settle(app, pilot)
|
||||
summary = str(app.main.query_one("#subs-summary").content)
|
||||
self.assertIn("✗ Cannot read /var/lib/proxy-suite/subscriptions.d", summary)
|
||||
self.assertIn("#: run proxy-tui as root", summary)
|
||||
|
||||
# zapret: an excluded host can be included again, not forgotten.
|
||||
# Brackets in a summary are text, not markup.
|
||||
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
|
||||
@@ -282,6 +306,12 @@ class TuiTest(unittest.TestCase):
|
||||
|
||||
# A copy only root may make offers ! to retry it under sudo, and still copies.
|
||||
with mock.patch.object(model.os, "geteuid", lambda: 1000):
|
||||
# The bar is one line: a long error is ellipsized, what to press next is not.
|
||||
app.finish("proxy-ctl proxy tun on", ["proxy", "tun", "on"], None, False, [f"Cannot read {'x' * 300} - re-run with sudo."], 1)
|
||||
content = str(app.main.query_one("#feedback").content)
|
||||
self.assertIn("!: retry as root", content)
|
||||
self.assertIn("…", content)
|
||||
|
||||
app.finish("proxy-ctl proxy outbounds link b", ["proxy", "outbounds", "link", "b"], None, True, ["Cannot read x - re-run with sudo."], 1)
|
||||
self.assertIn("!: retry as root", str(app.main.query_one("#feedback").content))
|
||||
sudo = mock.Mock(stdout=iter(["vless://b\n"]), **{"wait.return_value": 0})
|
||||
|
||||
@@ -107,6 +107,11 @@ def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
settings["mode"] = transport["mode"]
|
||||
stream[settings_key] = settings
|
||||
|
||||
# Behind a web server the socket address is loopback, which XRay will not record as
|
||||
# online; the forwarded address is only trusted when one of these headers is present.
|
||||
if transport.get("trustedXForwardedFor"):
|
||||
stream["sockopt"] = {"trustedXForwardedFor": transport["trustedXForwardedFor"]}
|
||||
|
||||
reality = listener["reality"]
|
||||
tls = listener["tls"]
|
||||
if reality["enable"]:
|
||||
|
||||
@@ -211,6 +211,12 @@ def build_outbound(
|
||||
return outbound
|
||||
|
||||
|
||||
# A subscription is a list of share links; the biggest real ones are tens of KiB.
|
||||
# Read runs as root at service start, so a server that never stops sending must not
|
||||
# take the whole proxy down with it.
|
||||
MAX_SUBSCRIPTION_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def fetch_raw(url: str) -> bytes:
|
||||
# urlopen also speaks file:, ftp: and data:. This runs as root over a URL that
|
||||
# reaches it from a group-writable spool, so only the two a subscription is
|
||||
@@ -222,12 +228,17 @@ def fetch_raw(url: str) -> bytes:
|
||||
headers={"User-Agent": "v2rayN/6.0"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.read()
|
||||
data = response.read(MAX_SUBSCRIPTION_BYTES + 1)
|
||||
if len(data) > MAX_SUBSCRIPTION_BYTES:
|
||||
raise ValueError(f"subscription is larger than {MAX_SUBSCRIPTION_BYTES} bytes")
|
||||
return data
|
||||
|
||||
|
||||
def decode_subscription(data: bytes) -> list[str]:
|
||||
text = None
|
||||
stripped = data.strip()
|
||||
# Line-wrapped and URL-safe base64 both occur; the lenient decoder would drop
|
||||
# "-" and "_" as junk instead of reading them as "+" and "/".
|
||||
stripped = b"".join(data.split()).translate(bytes.maketrans(b"-_", b"+/"))
|
||||
try:
|
||||
pad = b"=" * (-len(stripped) % 4)
|
||||
decoded = base64.b64decode(stripped + pad).decode("utf-8")
|
||||
|
||||
@@ -27,6 +27,26 @@ def _qs(query: str) -> dict:
|
||||
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
|
||||
|
||||
|
||||
# Panels write the unset half of a share link as "&sni=&host=&path=", so a blank
|
||||
# parameter is an absent one: "sni=" must fall back to the server name, not blank
|
||||
# out the SNI, and "host=" must not become an empty Host header.
|
||||
def _param(params: dict, name: str, default: str = "") -> str:
|
||||
return params.get(name) or default
|
||||
|
||||
|
||||
# sing-box stores a port as uint16 and refuses to start on anything else, so one
|
||||
# bad share link would otherwise take the whole config down with it, the same way
|
||||
# an unknown transport or fingerprint would (see _check_transport below).
|
||||
def _port(value) -> int:
|
||||
try:
|
||||
port = int(value)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"invalid port '{value}'") from None
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError(f"port {port} is out of range (1-65535)")
|
||||
return port
|
||||
|
||||
|
||||
def _split_host_port(hostpart: str) -> tuple[str, str]:
|
||||
host, separator, port = hostpart.rpartition(":")
|
||||
if not separator or not host or not port:
|
||||
@@ -155,10 +175,17 @@ SING_BOX_FINGERPRINTS = {
|
||||
}
|
||||
|
||||
|
||||
# Panels write alpn either as "h2,http/1.1" or as a JSON list; str() on the list
|
||||
# would hand sing-box "['h2'" as an ALPN value and break the handshake.
|
||||
def _alpn(value) -> list:
|
||||
values = value if isinstance(value, list) else str(value).split(",")
|
||||
return [str(a).strip() for a in values if str(a).strip()]
|
||||
|
||||
|
||||
def _mk_tls(
|
||||
server_name: str,
|
||||
fp: "str | None" = None,
|
||||
alpn: "str | None" = None,
|
||||
alpn=None,
|
||||
backend: str = "sing-box",
|
||||
) -> dict:
|
||||
tls: dict = {"enabled": True, "server_name": server_name}
|
||||
@@ -169,20 +196,22 @@ def _mk_tls(
|
||||
)
|
||||
tls["utls"] = {"enabled": True, "fingerprint": fp}
|
||||
if alpn:
|
||||
tls["alpn"] = alpn.split(",")
|
||||
tls["alpn"] = _alpn(alpn)
|
||||
return tls
|
||||
|
||||
|
||||
# SOCKS4 authenticates with a bare userid, so "socks4://me@host:1080" carries a
|
||||
# username and no password; dropping it made the outbound connect anonymously.
|
||||
def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||
if userinfo and ":" in userinfo:
|
||||
username, _, password = userinfo.partition(":")
|
||||
return urllib.parse.unquote(username), urllib.parse.unquote(password)
|
||||
return None, None
|
||||
if not userinfo:
|
||||
return None, None
|
||||
username, separator, password = userinfo.partition(":")
|
||||
return urllib.parse.unquote(username), urllib.parse.unquote(password) if separator else None
|
||||
|
||||
|
||||
def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
||||
security = params.get("security", "none")
|
||||
security = _param(params, "security", "none")
|
||||
|
||||
if "ech" in params and backend != "xray":
|
||||
raise ValueError(
|
||||
@@ -191,22 +220,22 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
)
|
||||
|
||||
normalized_transport = _check_transport(
|
||||
params.get("type", "tcp"), backend, "VLESS"
|
||||
_param(params, "type", "tcp"), backend, "VLESS"
|
||||
)
|
||||
|
||||
ob: dict = {
|
||||
"type": "vless",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(port),
|
||||
"uuid": userinfo,
|
||||
"packet_encoding": "xudp",
|
||||
}
|
||||
|
||||
if security == "reality":
|
||||
ob["tls"] = _mk_tls(
|
||||
params.get("sni", host),
|
||||
fp=params.get("fp") or "chrome",
|
||||
_param(params, "sni", host),
|
||||
fp=_param(params, "fp", "chrome"),
|
||||
backend=backend,
|
||||
)
|
||||
ob["tls"]["reality"] = {
|
||||
@@ -218,7 +247,7 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
ob["tls"]["reality"]["spider_x"] = params["spx"]
|
||||
elif security == "tls":
|
||||
ob["tls"] = _mk_tls(
|
||||
params.get("sni", host),
|
||||
_param(params, "sni", host),
|
||||
fp=params.get("fp"),
|
||||
alpn=params.get("alpn"),
|
||||
backend=backend,
|
||||
@@ -228,8 +257,8 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
|
||||
tr = _mk_transport(
|
||||
normalized_transport,
|
||||
path=params.get("path", "/"),
|
||||
host_header=params.get("host", host),
|
||||
path=_param(params, "path", "/"),
|
||||
host_header=_param(params, "host", host),
|
||||
service_name=params.get("serviceName", ""),
|
||||
mode=params.get("mode", ""),
|
||||
extra=params.get("extra", ""),
|
||||
@@ -257,7 +286,7 @@ def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
|
||||
|
||||
host = str(data["add"])
|
||||
port = int(data["port"])
|
||||
port = _port(data["port"])
|
||||
net = _check_transport(str(data.get("net", "tcp")), backend, "VMess")
|
||||
tls_field = str(data.get("tls", ""))
|
||||
sni = str(data.get("sni") or data.get("host") or host)
|
||||
@@ -268,15 +297,16 @@ def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
"server": host,
|
||||
"server_port": port,
|
||||
"uuid": data["id"],
|
||||
"security": data.get("scy", "auto"),
|
||||
"alter_id": int(data.get("aid", 0)),
|
||||
# Panels write unset fields as "": that is the default, not a value.
|
||||
"security": data.get("scy") or "auto",
|
||||
"alter_id": int(data.get("aid") or 0),
|
||||
}
|
||||
|
||||
if tls_field in ("tls", "reality"):
|
||||
ob["tls"] = _mk_tls(
|
||||
sni,
|
||||
fp=str(data["fp"]) if data.get("fp") else None,
|
||||
alpn=str(data["alpn"]) if data.get("alpn") else None,
|
||||
alpn=data.get("alpn") or None,
|
||||
backend=backend,
|
||||
)
|
||||
|
||||
@@ -297,16 +327,16 @@ def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
|
||||
def parse_trojan(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "trojan")
|
||||
transport = _check_transport(params.get("type", "tcp"), backend, "Trojan")
|
||||
transport = _check_transport(_param(params, "type", "tcp"), backend, "Trojan")
|
||||
|
||||
ob: dict = {
|
||||
"type": "trojan",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(port),
|
||||
"password": urllib.parse.unquote(userinfo),
|
||||
"tls": _mk_tls(
|
||||
params.get("sni", host),
|
||||
_param(params, "sni", host),
|
||||
fp=params.get("fp"),
|
||||
alpn=params.get("alpn"),
|
||||
backend=backend,
|
||||
@@ -315,8 +345,8 @@ def parse_trojan(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
|
||||
tr = _mk_transport(
|
||||
transport,
|
||||
path=params.get("path", "/"),
|
||||
host_header=params.get("host", host),
|
||||
path=_param(params, "path", "/"),
|
||||
host_header=_param(params, "host", host),
|
||||
service_name=params.get("serviceName", ""),
|
||||
)
|
||||
if tr is not None:
|
||||
@@ -368,7 +398,7 @@ def parse_shadowsocks(url: str, tag: str) -> dict:
|
||||
"type": "shadowsocks",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(port),
|
||||
"method": method,
|
||||
"password": password,
|
||||
}
|
||||
@@ -382,11 +412,11 @@ def parse_hysteria2(url: str, tag: str) -> dict:
|
||||
"type": "hysteria2",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(port),
|
||||
"password": urllib.parse.unquote(userinfo),
|
||||
"tls": {
|
||||
"enabled": True,
|
||||
"server_name": params.get("sni", host),
|
||||
"server_name": _param(params, "sni", host),
|
||||
"insecure": params.get("insecure", "0") == "1",
|
||||
},
|
||||
}
|
||||
@@ -400,20 +430,20 @@ def parse_hysteria2(url: str, tag: str) -> dict:
|
||||
def parse_tuic(url: str, tag: str) -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "tuic")
|
||||
uuid, _, password = userinfo.partition(":")
|
||||
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
|
||||
alpn = _alpn(_param(params, "alpn", "h3"))
|
||||
|
||||
return {
|
||||
"type": "tuic",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(port),
|
||||
"uuid": uuid,
|
||||
"password": urllib.parse.unquote(password),
|
||||
"congestion_control": params.get("congestion_control", "bbr"),
|
||||
"udp_relay_mode": params.get("udp_relay_mode", "native"),
|
||||
"congestion_control": _param(params, "congestion_control", "bbr"),
|
||||
"udp_relay_mode": _param(params, "udp_relay_mode", "native"),
|
||||
"tls": {
|
||||
"enabled": True,
|
||||
"server_name": params.get("sni", host),
|
||||
"server_name": _param(params, "sni", host),
|
||||
"alpn": alpn,
|
||||
},
|
||||
}
|
||||
@@ -431,7 +461,7 @@ def parse_anytls(url: str, tag: str) -> dict:
|
||||
"type": "anytls",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(port),
|
||||
"password": urllib.parse.unquote(userinfo),
|
||||
"tls": tls,
|
||||
}
|
||||
@@ -445,13 +475,14 @@ def parse_naive(url: str, tag: str) -> dict:
|
||||
"type": "naive",
|
||||
"tag": tag,
|
||||
"server": host,
|
||||
"server_port": int(port),
|
||||
"server_port": _port(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 password is not None:
|
||||
ob["password"] = password
|
||||
if scheme == "naive+quic":
|
||||
ob["quic"] = True
|
||||
return ob
|
||||
@@ -466,9 +497,10 @@ def parse_socks(url: str, tag: str) -> dict:
|
||||
username, password = _mk_auth(userinfo)
|
||||
if username is not None:
|
||||
ob["username"] = username
|
||||
ob["password"] = password
|
||||
if password is not None:
|
||||
ob["password"] = password
|
||||
ob["server"] = host
|
||||
ob["server_port"] = int(port)
|
||||
ob["server_port"] = _port(port)
|
||||
|
||||
return ob
|
||||
|
||||
@@ -481,9 +513,10 @@ def parse_http_proxy(url: str, tag: str) -> dict:
|
||||
username, password = _mk_auth(userinfo)
|
||||
if username is not None:
|
||||
ob["username"] = username
|
||||
ob["password"] = password
|
||||
if password is not None:
|
||||
ob["password"] = password
|
||||
ob["server"] = host
|
||||
ob["server_port"] = int(port)
|
||||
ob["server_port"] = _port(port)
|
||||
|
||||
if scheme == "https":
|
||||
ob["tls"] = {"enabled": True, "server_name": host}
|
||||
|
||||
@@ -23,7 +23,14 @@ def listener(**overrides):
|
||||
"users": [{"name": "", "uuid": "uuid-1", "uuidFile": None, "password": None, "passwordFile": None}],
|
||||
"flow": None,
|
||||
"method": "2022-blake3-aes-128-gcm",
|
||||
"transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": ""},
|
||||
"transport": {
|
||||
"type": "raw",
|
||||
"path": "/",
|
||||
"host": None,
|
||||
"mode": None,
|
||||
"serviceName": "",
|
||||
"trustedXForwardedFor": [],
|
||||
},
|
||||
"tls": {"enable": False, "certificateFile": None, "keyFile": None, "serverName": None},
|
||||
"reality": {
|
||||
"enable": False,
|
||||
@@ -146,6 +153,16 @@ class RenderInboundTests(unittest.TestCase):
|
||||
{"certificateFile": "/cert.pem", "keyFile": "/key.pem"},
|
||||
)
|
||||
|
||||
def test_trusted_x_forwarded_for_reaches_sockopt(self):
|
||||
"""Without it XRay sees the web server's loopback address and records nobody online."""
|
||||
plain = {"type": "ws", "path": "/", "host": None, "serviceName": "", "trustedXForwardedFor": []}
|
||||
self.assertNotIn("sockopt", render_xray_inbound(listener(transport=plain))["streamSettings"])
|
||||
behind = dict(plain, trustedXForwardedFor=["X-Real-IP"])
|
||||
self.assertEqual(
|
||||
render_xray_inbound(listener(transport=behind))["streamSettings"]["sockopt"],
|
||||
{"trustedXForwardedFor": ["X-Real-IP"]},
|
||||
)
|
||||
|
||||
def test_grpc_transport(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(transport={"type": "grpc", "path": "/", "host": None, "serviceName": "GunService"})
|
||||
|
||||
@@ -79,6 +79,17 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
)
|
||||
self.assertEqual(ob["server_port"], 23576)
|
||||
|
||||
def test_port_out_of_range_is_rejected(self):
|
||||
"""sing-box stores it as uint16 and refuses to start, so one bad entry in a
|
||||
subscription would take every other outbound down with it."""
|
||||
for url in (
|
||||
"vless://uuid@example.com:70000?type=tcp",
|
||||
"trojan://pw@example.com:0",
|
||||
"ss://YWVzLTI1Ni1nY206cHc@example.com:99999",
|
||||
):
|
||||
with self.subTest(url=url), self.assertRaisesRegex(ValueError, "out of range"):
|
||||
build_outbound(url, "test-outbound")
|
||||
|
||||
def test_reality_empty_fingerprint_falls_back_to_chrome(self):
|
||||
# sing-box's REALITY client refuses to start without a uTLS block.
|
||||
ob = run_parser(
|
||||
@@ -193,6 +204,33 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["type"], "vmess")
|
||||
self.assertEqual(ob["server"], "vmess.example.com")
|
||||
|
||||
def test_vmess_blank_fields_are_defaults(self):
|
||||
payload = {"add": "vmess.example.com", "port": 443, "id": "u", "aid": "", "scy": ""}
|
||||
encoded = base64.b64encode(json.dumps(payload).encode()).decode()
|
||||
ob = run_parser(f"vmess://{encoded}")
|
||||
self.assertEqual((ob["alter_id"], ob["security"]), (0, "auto"))
|
||||
|
||||
def test_socks4_keeps_its_bare_userid(self):
|
||||
ob = run_parser("socks4://me@10.0.0.1:1080")
|
||||
self.assertEqual((ob["version"], ob["username"]), ("4", "me"))
|
||||
self.assertNotIn("password", ob)
|
||||
|
||||
def test_blank_parameters_fall_back_to_the_server(self):
|
||||
# Panels emit "&sni=&host=&path=" for everything left unset.
|
||||
ob = run_parser("vless://uuid@example.com:443?security=tls&sni=&type=ws&host=&path=")
|
||||
self.assertEqual(ob["tls"]["server_name"], "example.com")
|
||||
self.assertEqual(ob["transport"]["headers"]["Host"], "example.com")
|
||||
self.assertEqual(ob["transport"]["path"], "/")
|
||||
tuic = run_parser("tuic://uuid:pw@example.com:443?alpn=&congestion_control=&udp_relay_mode=")
|
||||
self.assertEqual(tuic["tls"]["alpn"], ["h3"])
|
||||
self.assertEqual((tuic["congestion_control"], tuic["udp_relay_mode"]), ("bbr", "native"))
|
||||
|
||||
def test_vmess_alpn_list_and_string_agree(self):
|
||||
as_list = run_parser(vmess_url({"tls": "tls", "alpn": ["h2", "http/1.1"]}))
|
||||
as_text = run_parser(vmess_url({"tls": "tls", "alpn": "h2, http/1.1"}))
|
||||
self.assertEqual(as_list["tls"]["alpn"], ["h2", "http/1.1"])
|
||||
self.assertEqual(as_text["tls"]["alpn"], ["h2", "http/1.1"])
|
||||
|
||||
def test_trojan(self):
|
||||
ob = run_parser("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome")
|
||||
self.assertEqual(ob["type"], "trojan")
|
||||
|
||||
@@ -51,6 +51,15 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
types = {ob["type"] for ob in obs}
|
||||
self.assertEqual(types, {"vless", "shadowsocks", "hysteria2"})
|
||||
|
||||
def test_urlsafe_and_wrapped_base64_payloads(self):
|
||||
text = "\n".join([VLESS_URI, SS_URI, HY2_URI]).encode() + b"~?>"
|
||||
urlsafe = base64.urlsafe_b64encode(text).rstrip(b"=")
|
||||
self.assertTrue(b"-" in urlsafe or b"_" in urlsafe)
|
||||
std = base64.b64encode(text)
|
||||
wrapped = b"\r\n".join(std[i : i + 76] for i in range(0, len(std), 76))
|
||||
for payload in (urlsafe, wrapped):
|
||||
self.assertEqual(len(run_fetcher(payload)), 3)
|
||||
|
||||
def test_plain_text_payload(self):
|
||||
payload = "\n".join([VLESS_URI, SS_URI]).encode()
|
||||
obs = run_fetcher(payload)
|
||||
|
||||
Reference in new issue
Block a user