fix: more fixes

This commit is contained in:
fufsob committed 2026-09-16 15:59:25 +00:00
1 parent 32341ba323
commit 65fc4a7915
23 files changed
+207 -146

No files matched your search

+1 -1
View File
@@ -1384,7 +1384,7 @@ list of string
<a id="services-proxy-suite-proxy-routing-rules-outbound"></a>
## services\.proxy-suite\.proxy\.routing\.rules\.\*\.outbound
Outbound tag, or “proxy”, “direct”, “block”\. With selection = “first” every proxy tag means “proxy”\.
Outbound tag, or “proxy”, “direct”, “block”\.
*Type:*
string
+1 -1
View File
@@ -22,7 +22,7 @@ let
options = {
outbound = mkOption {
type = types.str;
description = ''Outbound tag, or "proxy", "direct", "block". With selection = "first" every proxy tag means "proxy".'';
description = ''Outbound tag, or "proxy", "direct", "block".'';
example = "vps-de";
};
}
@@ -67,13 +67,6 @@ let
settings.address = "example.com";
};
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = "Deprecated alias for singBoxJson.";
};
backend = mkOption {
type = types.enum [
"auto"
@@ -88,7 +81,7 @@ let
example = "xray";
};
# Destinations sent to this outbound (selection "selector" or "urltest").
# Destinations sent to this outbound, whatever the selection.
routing = routingFields;
};
};
+2 -6
View File
@@ -30,14 +30,10 @@ let
else
"proxy";
# In "first" mode the start script renames the first outbound to "proxy",
# so any per-outbound routing tag that isn't direct/block/proxy must map
# to "proxy" instead of the original tag (which won't exist in sing-box).
# Pure XRay's urltest prefixes every outbound for its balancer.
resolveTag =
tag:
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then
"proxy"
else if
if
derived.pureXrayEnabled
&& derived.selectionMode == "urltest"
&& !builtins.elem tag derived.builtinTags
+4 -5
View File
@@ -244,16 +244,15 @@ let
ob.url
ob.singBoxJson
ob.xrayJson
ob.json
]
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, or xrayJson"
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson requires proxy.backend = xray or hybrid")
(mkAssertion (
!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null)
) "proxy-suite: outbound '${ob.tag}': singBoxJson/json require proxy.backend = sing-box or hybrid")
!xrayEnabled || hybridEnabled || ob.singBoxJson == null
) "proxy-suite: outbound '${ob.tag}': singBoxJson requires proxy.backend = sing-box or hybrid")
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.backend = xray or hybrid")
@@ -284,7 +283,7 @@ let
# A pinned outbound is rendered by the XRay renderer inside the inbound
# service, so a sing-box-only definition cannot serve as one.
singBoxOnlyPinnedTags = map (ob: ob.tag) (
builtins.filter (ob: ob.singBoxJson != null || ob.json != null) derived.proxyInboundViaOutbounds
builtins.filter (ob: ob.singBoxJson != null) derived.proxyInboundViaOutbounds
);
proxyInboundAssertions = [
@@ -16,7 +16,8 @@ if pureXrayEnabled then
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
# "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit.
if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then
.outboundTag = $single_tag | del(.balancerTag)
else
.
@@ -19,46 +19,39 @@ lib.optionalString hybridEnabled ''
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_next_xray_sidecar_port() {
local port="$XRAY_SIDECAR_NEXT_PORT"
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1))
printf '%s\n' "$port"
# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a
# loopback SOCKS inbound on the sidecar and stands in sing-box as a hop to it.
_proxy_suite_add_xray_sidecar_obs() {
local batch
batch=$(${jq} -c \
--argjson base "$XRAY_SIDECAR_NEXT_PORT" \
--argjson mark ${toString xraySidecarRoutingMark} '
to_entries | map(
($base + .key) as $port
| ("proxy-suite-xray-" + ($port | tostring)) as $auth
| .value.tag as $tag
| {outbound: (.value
| .streamSettings.sockopt.mark = $mark
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
inbound: {tag: ($tag + "-inbound"), listen: "127.0.0.1", port: $port, protocol: "socks",
settings: {auth: "password", udp: true, accounts: [{user: $auth, pass: $auth}]}},
rule: {type: "field", inboundTag: [$tag + "-inbound"], outboundTag: $tag},
hop: ({type: "socks", tag: $tag, server: "127.0.0.1", server_port: $port, version: "5",
username: $auth, password: $auth}${
lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}"
})})
| {outbounds: map(.outbound), inbounds: map(.inbound), rules: map(.rule), hops: map(.hop)}
' <<< "$1")
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + $(${jq} '.outbounds | length' <<< "$batch")))
XRAY_OUTBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.outbounds' <<< "$XRAY_OUTBOUNDS_JSON")
XRAY_INBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.inbounds' <<< "$XRAY_INBOUNDS_JSON")
XRAY_ROUTE_RULES_JSON=$(${jq} -c --argjson b "$batch" '. + $b.rules' <<< "$XRAY_ROUTE_RULES_JSON")
OUTBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.hops' <<< "$OUTBOUNDS_JSON")
}
# $1 one XRay outbound, $2 its tag.
_proxy_suite_add_xray_sidecar_ob() {
local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule
port="$(_proxy_suite_next_xray_sidecar_port)"
auth="proxy-suite-xray-$port"
inbound_tag="$tag-inbound"
ob=$(${jq} \
--arg tag "$tag" \
--argjson mark ${toString xraySidecarRoutingMark} \
'.tag = $tag
| .streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| .streamSettings.sockopt.mark = $mark
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \
<<< "$ob")
XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON")
inbound=$(${jq} -n \
--arg tag "$inbound_tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}')
XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON")
route_rule=$(${jq} -n \
--arg inbound "$inbound_tag" \
--arg outbound "$tag" \
'{type:"field",inboundTag:[$inbound],outboundTag:$outbound}')
XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON")
sing_ob=$(${jq} -n \
--arg tag "$tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${
lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}"
}}')
OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_add_xray_sidecar_obs "$(${jq} -c --arg tag "$2" '[.tag = $tag]' <<< "$1")"
}
_proxy_suite_write_xray_sidecar_config() {
@@ -39,13 +39,7 @@ let
rawOutboundJson =
ob: tag: routingMark:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
backendRaw = if pureXrayEnabled then ob.xrayJson else ob.singBoxJson;
markAttrs =
if routingMark == null then
{ }
@@ -218,16 +212,7 @@ let
mkOutboundBlock =
ob: routingMark: tag:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
in
if backendRaw != null then
if (if pureXrayEnabled then ob.xrayJson else ob.singBoxJson) != null then
let
outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
@@ -249,26 +234,14 @@ let
singBoxRawOutboundJson =
ob: tag: routingMark:
let
backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json;
markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
in
backendRaw // { inherit tag; } // markAttrs;
xrayRawOutboundJson =
ob: tag:
lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) {
streamSettings.sockopt = {
mark = xraySidecarRoutingMark;
domainStrategy = "UseIP";
};
};
ob.singBoxJson // { inherit tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
mkHybridOutboundBlock =
ob: routingMark: tag:
if ob.xrayJson != null then
let
outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag);
# The sidecar helper adds the tag, its mark, and UseIP unless one is set.
outboundJson = builtins.toJSON ob.xrayJson;
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
in
''
@@ -277,7 +250,7 @@ let
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else if ob.singBoxJson != null || ob.json != null then
else if ob.singBoxJson != null then
let
outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
@@ -598,10 +571,14 @@ let
if [ -z "$PROXY_TAG" ]; then
PROXY_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")
fi
OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \
'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")
# Every tag stays, so rules naming another outbound still reach it; "proxy"
# only stands for the pick.
${
if pureXrayEnabled then
''XRAY_SINGLE_PROXY_TAG="$PROXY_TAG"''
else
''OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" '[{type:"selector",tag:"proxy",outbounds:[$t],default:$t}] + .' <<< "$OUTBOUNDS_JSON")''
}
''
else if selectionMode == "selector" then
''
@@ -116,10 +116,7 @@ let
''
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$cache")
_proxy_suite_add_xray_sidecar_obs "$(${jq} -c '.xray' "$cache")"
''
else
''
@@ -235,11 +235,11 @@ let
${lib.optionalString enableOutboundTest ''
# proxy-ctl proxy outbounds test. Servers for its ping, keyed by the user's tag:
# the wrapper may have renamed one outbound "proxy" or prefixed them all, and a
# XRay's urltest wrapper prefixes them all, and a
# hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's.
# A loopback hop (the WARP tunnel, XRay's SSH listener) has no server worth timing.
ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp"
${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" '
${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" '
def endpoint:
if .server then {server, port: .server_port}
elif .settings.address then {server: .settings.address, port: .settings.port}
@@ -249,7 +249,7 @@ let
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
| (.tag | ltrimstr("proxy-suite-ob-")) as $tag
| ($real[.tag] // .) | select(endpoint != null and (endpoint.server | test("^(127\\.|::1$|localhost$)") | not))
| {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}]
| from_entries
@@ -269,11 +269,11 @@ let
# proxy-ctl's share links: the URL each outbound was given, and its backend JSON.
# Credentials: root and the userControl group only.
SHARE_TMP="$RUNTIME_DIR/outbound-share.json.tmp"
(umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" \
(umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" \
--argjson urls "$OUTBOUND_URLS_JSON" --argjson subs "$SUBSCRIPTION_URLS_JSON" '
($sidecar | map({key: .tag, value: .}) | from_entries) as $real
| {outbounds: ([.[] | select(.type != "selector" and .type != "urltest")
| (.tag | ltrimstr("proxy-suite-ob-") | if . == "proxy" then $collapsed else . end) as $tag
| (.tag | ltrimstr("proxy-suite-ob-")) as $tag
| {key: $tag, value: {url: $urls[$tag], outbound: (($real[$tag] // $real[.tag] // .) | .tag = $tag)}}]
| from_entries),
subscriptions: $subs}
@@ -291,10 +291,10 @@ let
listen: "127.0.0.1", listen_port: ${toString outboundTestPort}}]' <<< "$PROBE_INBOUNDS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c \
'. + [{inbound: ["proxy-suite-test-in"], outbound: "proxy-suite-test"}]' <<< "$PROBE_PIN_RULES_JSON")
${jq} -n --argjson tags "$EXIT_TAGS_JSON" --arg collapsed "''${PROXY_TAG:-}" \
${jq} -n --argjson tags "$EXIT_TAGS_JSON" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} '
{port: ${toString outboundTestPort}, selector: "proxy-suite-test", url: $url,
outbounds: ($tags | map({key: (if . == "proxy" then $collapsed else . end), value: .}) | from_entries)}
outbounds: ($tags | map({key: ., value: .}) | from_entries)}
' > "$RUNTIME_DIR/outbound-test.json"
# Tags and a loopback port only.
chmod 644 "$RUNTIME_DIR/outbound-test.json"
+3 -3
View File
@@ -16,7 +16,7 @@
{
assertions = [
# -- routing rule entries with domains and geoips preserve both matchers --
# -- routing rule entries with domains and geoips preserve both matchers, and the named outbound --
(
assert builtins.length routingOrDomainRules == 1;
true
@@ -26,11 +26,11 @@
true
)
(
assert (builtins.head routingOrDomainRules).outbound == "proxy";
assert (builtins.head routingOrDomainRules).outbound == "primary";
true
)
(
assert (builtins.head routingOrGeoIPRules).outbound == "proxy";
assert (builtins.head routingOrGeoIPRules).outbound == "primary";
true
)
+4 -4
View File
@@ -92,9 +92,9 @@ in
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript;
assert pkgs.lib.hasInfix "hybrid XRay json sidecar" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix ''{type:"socks",tag:$tag,server:"127.0.0.1"'' hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "udp:true" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "routing_mark:2" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix ''{type: "socks", tag: $tag, server: "127.0.0.1"'' hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "udp: true" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "{routing_mark: 2}" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter;
assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter;
assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionStartScript;
@@ -103,7 +103,7 @@ in
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix ".singBox" hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix ".xray[]" hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_obs \"$(" hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridSubscriptionStartScript;
true
)
+3 -3
View File
@@ -73,12 +73,12 @@ in
true
)
# selection=first renames the pinned outbound - or the first one, absent a
# pin - to "proxy" at start, rather than collapsing at eval time.
# selection=first puts "proxy" in front of the pinned outbound - or the first one,
# absent a pin - at start, keeping every tag for rules that name one.
(
assert pkgs.lib.hasInfix ''PROXY_TAG="$PINNED_OUTBOUND"'' subscriptionFirstSelectionStartScript;
assert
pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end''
pkgs.lib.hasInfix ''[{type:"selector",tag:"proxy",outbounds:[$t],default:$t}] + .''
subscriptionFirstSelectionStartScript;
true
)
+4 -2
View File
@@ -102,6 +102,7 @@ let
];
nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = ''
# /run/wrappers/bin first: the store's sudo, earlier on a PATH, refuses to run without setuid.
wrapProgram "$out/bin/proxy-tui" \
--prefix PYTHONPATH : ${pythonModules} \
--prefix PATH : "${
@@ -110,7 +111,7 @@ let
pkgs.systemd
]
}" \
--suffix PATH : /run/wrappers/bin ${envFlags}
--prefix PATH : /run/wrappers/bin ${envFlags}
'';
};
guiPython = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]);
@@ -184,6 +185,7 @@ let
runHook postInstall
'';
postFixup = ''
# /run/wrappers/bin first: the store's pkexec, earlier on a PATH, refuses to run without setuid.
makeWrapper ${guiPython}/bin/python3 "$out/bin/proxy-suite-gui" \
--add-flags "$out/lib/proxy-suite-gui/proxy_gui.py" \
"''${gappsWrapperArgs[@]}" \
@@ -195,7 +197,7 @@ let
pkgs.qrencode
]
}" \
--suffix PATH : /run/wrappers/bin \
--prefix PATH : /run/wrappers/bin \
--set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \
--set PROXY_GUI_REFRESH ${toString guiRefreshInterval} ${envFlags}
'';
+19 -4
View File
@@ -5,6 +5,7 @@ Configuration arrives through the environment the Nix wrapper sets.
import datetime
import http.client
import importlib
import json
import os
import re
@@ -625,6 +626,15 @@ def _status_tray():
print(f"awg_profiles={','.join(snapshot['awg']['profiles'])}")
def _status_tab(tab_id=""):
"""A front end's tab as JSON [rows, summary]: how the GUI reads, through pkexec, what only root can."""
model = _module("proxy_model")
tab = next((t for t in model.TABS if t.id == tab_id), None)
if tab is None:
usage(f"status --tab <{'|'.join(t.id for t in model.TABS)}>")
print(json.dumps(model.load_tab(tab, model._read_states())))
def _status_json():
snapshot = _status_snapshot()
if snapshot["proxy"]["active"]:
@@ -700,6 +710,9 @@ def cmd_status(*args):
if args[:1] == ("--tray",):
_status_tray()
return
if args[:1] == ("--tab",):
_status_tab(*args[1:2])
return
print("proxy-suite services:")
for svc in _snapshot_units():
if svc != SUBSCRIPTION_UPDATE:
@@ -814,7 +827,7 @@ def _require_outbound_inventory():
def _outbound_current():
"""What the backend dials right now, when it exposes a selector.
Empty otherwise, which is normal for selection = "first" and for XRay.
Empty otherwise, which is normal for XRay.
"""
status, body = _clash("GET", "/proxies/proxy", timeout=5)
now = body.get("now") if status == 200 and isinstance(body, dict) else None
@@ -1071,12 +1084,14 @@ def _subscription_link(*args):
_emit(_s(url), flag == "--qr")
def _proxy_export():
def _module(name):
# Not PYTHONPATH: that would reach every command `apps run` starts.
sys.path.append(env("PROXY_CTL_MODULES", os.path.dirname(os.path.abspath(__file__))))
import proxy_export
return importlib.import_module(name)
return proxy_export
def _proxy_export():
return _module("proxy_export")
def _config_export(*args, only=None):
+2 -3
View File
@@ -76,9 +76,8 @@ def _dropped(exits, keep):
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"."""
for tag in (only, prefix + only, "proxy"):
"""The tag `only` has in the backend: as given, or prefixed by the XRay wrapper."""
for tag in (only, prefix + only):
if tag in tags:
return tag
raise ValueError(f"no outbound {only} in the running config")
+25 -6
View File
@@ -66,7 +66,7 @@ GLOBAL_SHORTCUTS = [
("w", "How is a domain routed"),
("<Shift>l", "Follow all logs"),
("o", "Output of the last command"),
("<Control>e", "Run actions as root (pkexec)"),
("<Control>e", "Read and run as root (pkexec)"),
("F5 r", "Refresh now"),
("<Control>question", "Keyboard shortcuts"),
("<Control>w", "Close the window (the tray keeps running)"),
@@ -755,7 +755,7 @@ class Window(Adw.ApplicationWindow):
self.refresh_stack.add_named(Adw.Spinner(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER), "busy")
self.busy_timer = None
header.pack_start(self.refresh_stack)
self.root_badge = Gtk.Image(icon_name="dialog-password-symbolic", tooltip_text="Actions run as root (Ctrl+E)", visible=app.elevated(), css_classes=["warning"])
self.root_badge = Gtk.Image(icon_name="dialog-password-symbolic", tooltip_text="Reads and actions run as root (Ctrl+E)", visible=app.elevated(), css_classes=["warning"])
header.pack_start(self.root_badge)
menu = Gio.Menu()
section = Gio.Menu()
@@ -764,7 +764,7 @@ class Window(Adw.ApplicationWindow):
section.append("Output of the last command", "win.last-output")
menu.append_section(None, section)
section = Gio.Menu()
section.append("Run actions as root", "app.elevated")
section.append("Read and run as root", "app.elevated")
menu.append_section(None, section)
section = Gio.Menu()
section.append("Keyboard Shortcuts", "win.shortcuts")
@@ -1027,6 +1027,7 @@ class ProxySuiteGui(Adw.Application):
self.pending = False
self.generation = 0
self.failed = None # units in failed state at the last load; None before the first
self.root_read_refused = False # pkexec for a tab read was dismissed: not asked again until Ctrl+E flips
self.timer = None
def do_startup(self):
@@ -1088,8 +1089,10 @@ class ProxySuiteGui(Adw.Application):
def on_elevated(self, action, value):
action.set_state(value)
self.root_read_refused = False
if self.window:
self.window.root_badge.set_visible(value.get_boolean())
self.reload() # tabs only root can read
def present(self, tab=None):
if self.window is None:
@@ -1129,9 +1132,9 @@ class ProxySuiteGui(Adw.Application):
if window:
window.set_busy(True)
tab = window.pages[window.stack.get_visible_child_name()].tab if window and window.stack.get_visible_child_name() else None
threading.Thread(target=self.load, args=(self.generation, tab), daemon=True).start()
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated()), daemon=True).start()
def load(self, generation, tab):
def load(self, generation, tab, elevated):
model.new_load()
states = model._read_states()
snap = model.snapshot(states) if states else None
@@ -1141,9 +1144,25 @@ class ProxySuiteGui(Adw.Application):
if tab is not None:
result["visible"] = model.available_tabs(states)
result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")])
result["tab"] = (tab.id, *model.load_tab(tab, states))
result["tab"] = (tab.id, *self.load_tab(tab, states, elevated))
GLib.idle_add(self.landed, generation, result)
def load_tab(self, tab, states, elevated):
"""The tab as this user reads it; what only root can read, through pkexec when actions run as root."""
rows, summary = model.load_tab(tab, states)
if not model.needs_root(summary.splitlines(), 1):
return rows, summary
if not elevated:
return rows, summary + "\nCtrl+E: read and run as root (pkexec)"
if self.root_read_refused:
return rows, summary + "\nRoot read cancelled: Ctrl+E twice to ask again."
root_rows, why = model.load_tab_as_root(tab, "pkexec")
if root_rows is None:
# ponytail: one refusal stops the asking, else the password dialog is back every refresh
self.root_read_refused = why == "authentication cancelled"
return rows, summary + f"\nAs root: {why}"
return root_rows, why
def landed(self, generation, result):
self.loading = False
if self.window:
+18 -1
View File
@@ -5,6 +5,7 @@ validation, permission errors and systemd triggers stay in one place, and its
die() cannot take a front end down.
"""
import json
import os
import re
import shlex
@@ -176,7 +177,8 @@ def outbound_rows(_):
excluded = set(inventory.get("excluded") or [])
current = ctl._outbound_current()
reputation = ctl._reputation_by_tag()
runtime = set(ctl._runtime_tags("outbound"))
# outbounds.d is root-only; the inventory says "runtime" for what the backend loaded from it.
runtime = set(ctl._runtime_tags("outbound")) | {t for t, s in sources.items() if s == "runtime"}
return [
{
"key": t,
@@ -567,6 +569,21 @@ def elevated(argv, via):
return [via, shutil.which(CTL) or CTL, *argv]
def load_tab_as_root(tab, via):
"""load_tab in proxy-ctl run through via (pkexec): (rows, summary), or None and why it did not run."""
try:
p = subprocess.run(elevated(["status", "--tab", tab.id], via), capture_output=True, text=True, stdin=subprocess.DEVNULL)
except OSError as e:
return None, f"cannot run {via}: {e}"
if p.returncode in (126, 127) and not p.stdout and not p.stderr.strip():
return None, "authentication cancelled" # pkexec: dismissed, or not allowed
try:
rows, summary = json.loads(p.stdout)
return rows, summary
except ValueError:
return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1]
def popen(argv, root=None):
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.
root: "pkexec" to run it as root, asking through the desktop's polkit agent."""
+1 -1
View File
@@ -496,7 +496,7 @@ class ProxyTui(App):
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):
if model.needs_root(summary.splitlines(), 1):
summary += "\n#: run proxy-tui as root (sudo)"
self.show_status()
if visible != self.shown:
+4 -5
View File
@@ -70,7 +70,7 @@ class EnvTest(unittest.TestCase):
class ClashApiTest(EnvTest):
def test_unset_api_reads_as_unreachable(self):
# selection = "first" and the XRay backend leave the API off; a bare
# The XRay backend leaves 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"):
@@ -529,8 +529,7 @@ class OutboundTestTest(EnvTest):
"port": 18537,
"selector": "proxy-suite-test",
"url": "https://t.test/204",
# selection = "first": the backend knows the pick as "proxy".
"outbounds": {"own-vps": "proxy", "de": "de", "wg": "wg"},
"outbounds": {"own-vps": "own-vps", "de": "de", "wg": "wg"},
},
)
self.calls = []
@@ -563,10 +562,10 @@ class OutboundTestTest(EnvTest):
self.assertRegex(out, r"(?m)^ TAG +PING +DELAY +DOWNLOAD$")
self.assertRegex(out, r"(?m)^ own-vps +udp +88 ms +12\.3 Mbit/s$")
self.assertRegex(out, r"(?m)^ de +- +failed +12\.3 Mbit/s$")
self.assertTrue(any(c[1].startswith("/proxies/proxy/delay?") and "t.test" in c[1] for c in self.calls))
self.assertTrue(any(c[1].startswith("/proxies/own-vps/delay?") and "t.test" in c[1] for c in self.calls))
# Downloads switch the test selector, one outbound at a time, in order.
puts = [c for c in self.calls if c[0] == "PUT"]
self.assertEqual([c[2]["name"] for c in puts], ["proxy", "de", "wg"])
self.assertEqual([c[2]["name"] for c in puts], ["own-vps", "de", "wg"])
self.assertEqual({c[1] for c in puts}, {"/proxies/proxy-suite-test"})
def test_default_and_arguments(self):
-7
View File
@@ -135,13 +135,6 @@ class SingBoxTest(unittest.TestCase):
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:]]
base["route"]["rules"] = []
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)."""
+28
View File
@@ -5,7 +5,9 @@ key names become GTK accelerators, and every icon the tray can ask for is drawn.
import os
import sys
import tempfile
import types
import unittest
from unittest import mock
import proxy_ctl as ctl
import proxy_gui as gui
@@ -81,6 +83,32 @@ class GuiTest(unittest.TestCase):
[("failed", ("bold", "red")), (" ok", ())],
)
def test_root_toggle_reads_too(self):
"""A tab only root can read goes through pkexec when the toggle is on, and one refusal stops the asking."""
tab = model.Tab("x", "X", model.ROW, [], list)
app = types.SimpleNamespace(root_read_refused=False)
denied = ([], "✗ Cannot read /x - join the proxy-suite group, or re-run with sudo.")
asked = []
def as_root(result):
return mock.patch.object(model, "load_tab_as_root", lambda tab, via: asked.append(via) or result)
load = lambda elevated: gui.ProxySuiteGui.load_tab(app, tab, {}, elevated)
with mock.patch.object(model, "load_tab", lambda tab, states: denied), mock.patch.object(model.os, "geteuid", lambda: 1000):
with as_root(([{"key": "a"}], "")):
self.assertIn("Ctrl+E", load(False)[1])
self.assertEqual(asked, [])
self.assertEqual(load(True), ([{"key": "a"}], ""))
self.assertEqual(asked, ["pkexec"])
with as_root((None, "authentication cancelled")):
self.assertIn("As root: authentication cancelled", load(True)[1])
self.assertIn("Ctrl+E twice", load(True)[1])
self.assertEqual(len(asked), 2)
with mock.patch.object(model, "load_tab", lambda tab, states: ([], "Nothing here yet.")), as_root(None):
app.root_read_refused = False
self.assertEqual(load(True), ([], "Nothing here yet.")) # readable: no pkexec
self.assertEqual(len(asked), 2)
def test_every_tray_icon_is_drawn(self):
here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
with tempfile.TemporaryDirectory() as out:
+33
View File
@@ -1,7 +1,11 @@
#!/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 contextlib
import io
import json
import os
import subprocess
import tempfile
import unittest
from unittest import mock
@@ -148,6 +152,35 @@ class ModelTest(unittest.TestCase):
self.assertEqual(probe.argv(rows[1], "example.com", {}), ["proxy", "auto", "probe", "example.com", "--via", "b-backend"])
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
# outbounds.d is root-only: the inventory still says which are runtime, so they can be removed.
inventory["sources"] = {"a": "runtime"}
with mock.patch.object(ctl, "_outbound_current", lambda: ""), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []), mock.patch.object(ctl, "_outbound_inventory", lambda: inventory):
rows, _ = model.load_tab(tab, {})
self.assertEqual([(r["source"], r["runtime"]) for r in rows], [("runtime", True), ("-", False)])
def test_load_tab_as_root(self):
"""The GUI's root read: proxy-ctl status --tab through pkexec, and what a refusal says."""
tab = next(t for t in model.TABS if t.id == "routing")
with mock.patch.object(ctl, "_route_mode_current", lambda: "default"), mock.patch.object(ctl, "_route_mode_default", lambda: "rules"):
out = io.StringIO()
with contextlib.redirect_stdout(out):
ctl._status_tab("routing")
self.assertEqual(json.loads(out.getvalue()), list(model.load_tab(tab, {})))
with self.assertRaises(SystemExit) as e:
ctl._status_tab("nope")
self.assertIn("status --tab <services|", str(e.exception))
def ran(returncode, stdout="", stderr=""):
return mock.patch.object(model.subprocess, "run", lambda argv, **_: subprocess.CompletedProcess(argv, returncode, stdout, stderr))
with ran(0, '[[{"key": "a"}], "ok"]'):
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), ([{"key": "a"}], "ok"))
with ran(126):
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), (None, "authentication cancelled"))
with ran(127, stderr="pkexec must be setuid root\n"): # not a refusal: asked again next refresh
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), (None, "pkexec must be setuid root"))
with ran(1, stderr="boom\nUsage: proxy-ctl status\n"):
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), (None, "Usage: proxy-ctl status"))
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable_is_not_empty(self):