fix: bug fixes

This commit is contained in:
fufsob committed 2026-09-16 08:43:53 +00:00
1 parent 9cdd6dada7
commit 027dc7b1a9
31 files changed
+626 -121

No files matched your search

+44 -12
View File
@@ -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):
+10 -4
View File
@@ -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
+1 -2
View File
@@ -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):
+21 -12
View File
@@ -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
View File
@@ -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()
+11
View File
@@ -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):
+19
View File
@@ -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:]
+52 -6
View File
@@ -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()
+30
View File
@@ -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})