fix: root actions in tui/gui & userControl

This commit is contained in:
fufsob committed 2026-09-15 20:02:43 +00:00
1 parent 2ce8da3f43
commit 9cdd6dada7
32 files changed
+665 -317

No files matched your search

+42 -35
View File
@@ -45,6 +45,7 @@ RESTART_SERVICES = [
HELP = """\
Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list.
Secrets and changes need root, or the userControl group.
status [--json] services and routing mode (--tray: deprecated key=value lines)
restart restart active services
@@ -60,7 +61,7 @@ A group without a verb shows its status or list.
proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay)
proxy outbounds link <tag> [--qr|--json|--config]
its URL, QR code, backend JSON, or a client config for it (sudo)
its URL, QR code, backend JSON, or a client config for it
proxy pin [tag] always use this outbound (no tag: pick from a menu)
proxy unpin let the configured selection pick again
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
@@ -68,24 +69,24 @@ A group without a verb shows its status or list.
proxy subs [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL (sudo)
proxy config [--raw] client config to import elsewhere; --raw: as running (sudo)
proxy subs link <tag> [--qr] its URL
proxy config [--raw] client config to import elsewhere; --raw: as running
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl)
proxy auto [list] what autoProxy routed, and via which exit
proxy auto probe <domain>[/path] [--json] [--keep-going] [--exits a,b | --via tag]
find an exit that reaches a domain
proxy auto learn <domain> probe now and route it if an exit works (sudo)
proxy auto queue [count] destinations waiting to be probed (sudo, or userControl)
proxy auto learn <domain> probe now and route it if an exit works
proxy auto queue [count] destinations waiting to be probed
zapret [status|on|off] DPI bypass
zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo)
zapret auto unpin|include <domain> undo add, or undo exclude (sudo)
zapret auto clear forget learned hosts and strategies (sudo)
pin, forget, or never learn a host
zapret auto unpin|include <domain> undo add, or undo exclude
zapret auto clear forget learned hosts and strategies
zapret cutoff [status] networks this line cuts at 16 KB, and their names
zapret cutoff probe probe this line again now (sudo)
zapret cutoff probe probe this line again now
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
@@ -100,10 +101,10 @@ A group without a verb shows its status or list.
inbounds [list] server inbounds
inbounds link <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo)
inbounds link <tag> --server-json the server's inbound JSON
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] [--by user|inbound|outbound]
traffic per user, listener or exit (sudo, or userControl)
traffic per user, listener or exit
inbounds online who is connected now, and when the rest were last seen
"""
@@ -163,6 +164,15 @@ def readable(path):
return bool(path) and os.access(path, os.R_OK)
def ask_group():
"""What lets a refused user in: root, or userControl's group with the scope for it."""
return f"join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo"
def denied(path, what="read"):
die(f"Cannot {what} {path} - {ask_group()}.")
def _run(argv, capture=False, quiet=False, stdin=None):
"""Runs argv; (exit status, stdout if captured). A missing binary is 127."""
sys.stdout.flush()
@@ -937,7 +947,7 @@ def cmd_outbounds_test(*args):
try:
endpoints = read_json(_runtime_file("outbound-endpoints.json"))
except PermissionError:
notes.append("ping: cannot read the servers - enable userControl, or run with sudo.")
notes.append(f"ping: cannot read the servers - {ask_group()}.")
except (OSError, ValueError):
pass
test = {}
@@ -1006,9 +1016,9 @@ def _outbounds_list():
# --- sharing ------------------------------------------------------------------
#
# The socks start script writes outbound-share.json, root only: the URL each outbound
# was given (none for one declared as JSON, WARP or SSH) and its backend JSON. A URL is
# never rebuilt from JSON. `proxy config` turns the running config into one another
# The socks start script writes outbound-share.json, root and userControl's group only:
# the URL each outbound was given (none for one declared as JSON, WARP or SSH) and its
# backend JSON. A URL is never rebuilt from JSON. `proxy config` turns the running config into one another
# device can import (proxy_export).
@@ -1016,7 +1026,7 @@ def _read_root_json(path, what):
if not os.path.isfile(path):
die(f"No {what} yet - is proxy-suite-socks running?")
if not readable(path):
die(f"Cannot read {path} - re-run with sudo.")
denied(path)
return read_json(path)
@@ -1211,7 +1221,7 @@ def _runtime_entry_add(kind, tag="", url="", *_, detour=""):
with open(path, "w", encoding="utf-8") as f:
f.write(f"{url}\n")
except OSError:
die(f"Cannot write {path} - join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo.")
denied(path, "write")
finally:
os.umask(old)
_runtime_reload()
@@ -1231,7 +1241,7 @@ def _runtime_entry_rm(kind, tag="", *_):
except FileNotFoundError:
pass
except OSError:
die(f"Cannot remove {path} - join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo.")
denied(path, "remove")
_runtime_reload()
print(f"Removed {kind}: {tag}")
@@ -1731,7 +1741,7 @@ def _require_autoproxy_readable(path):
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):
die(f"Cannot read {path} - enable userControl, or run with sudo.")
denied(path)
def _autoproxy_state(path):
@@ -1866,7 +1876,7 @@ def cmd_proxy_learn(host="", *_):
with open(requests, "a", encoding="utf-8") as f:
f.write(f"{host}\n")
except OSError:
die(f"Cannot write {requests} - re-run with sudo.")
denied(requests, "write")
print(f"Probing {host} through each exit...")
if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]:
sys.stdout.flush()
@@ -1911,7 +1921,7 @@ def _replace_lines(path, keep, extra=()):
old = lines(read_text(path)) if os.path.exists(path) else []
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".")
except OSError:
die(f"Cannot write {path} - re-run with sudo.")
denied(path, "write")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.writelines(f"{line}\n" for line in [*filter(keep, old), *extra])
@@ -1922,7 +1932,7 @@ def _replace_lines(path, keep, extra=()):
os.unlink(tmp)
except OSError:
pass
die(f"Cannot replace {path} - re-run with sudo.")
denied(path, "replace")
def _zapret_auto_edit(path, domain, action):
@@ -1951,10 +1961,7 @@ def _zapret_strategy_drop(domain):
def _truncate(path):
try:
open(path, "w").close()
except OSError:
die(f"Cannot write {path} - re-run with sudo.")
_replace_lines(path, lambda _: False)
def cmd_zapret_auto(verb="list", domain="", *_):
@@ -2021,7 +2028,7 @@ def cmd_zapret_cutoff(verb="status", *_):
try:
open(os.path.join(path, "force"), "w").close()
except OSError:
die(f"Cannot write {path} - re-run with sudo.")
denied(path, "write")
print("Probing this line; this takes a few minutes...")
if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]:
die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30")
@@ -2205,7 +2212,7 @@ def cmd_where(domain="", *_):
if env("INBOUNDS_ENABLED") == "1":
inbounds_path = "/run/proxy-suite-inbounds/config.json"
if not readable(inbounds_path):
_where_row("inbounds", "routing is not readable - run with sudo")
_where_row("inbounds", f"routing is not readable - {ask_group()}")
else:
try:
tag, why = _where_inbounds(read_json(inbounds_path), domain, geosite_dir)
@@ -2217,7 +2224,7 @@ def cmd_where(domain="", *_):
if env("AUTOPROXY_ENABLED") == "1":
if not readable(os.path.join(_autoproxy_dir(), "state.json")):
_where_row("autoProxy", "state is not readable - enable userControl, or run with sudo")
_where_row("autoProxy", f"state is not readable - {ask_group()}")
else:
domains = _autoproxy_state(_autoproxy_dir()).get("domains")
hit = _where_in(domains if isinstance(domains, dict) else {}, domain)
@@ -2418,7 +2425,7 @@ def _inbound_links():
if not os.path.isfile(path):
die("No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?")
if not readable(path):
die("Share links are not readable by this user. Enable userControl, or run as root.")
denied(path)
return read_json(path)
@@ -2428,7 +2435,7 @@ def _inbound_server_json(tag):
if not os.path.isfile(path):
die("No inbound config yet - is proxy-suite-inbounds running?")
if not readable(path):
die(f"Cannot read {path} - re-run with sudo.")
denied(path)
inbound = next((x for x in read_json(path).get("inbounds") or [] if x.get("tag") == tag), None)
if inbound is None:
die(f"Unknown inbound: {tag}")
@@ -2487,7 +2494,7 @@ def _inbound_stats(*args):
if not os.path.exists(path):
die("No traffic recorded yet - the collector runs every 5 minutes.")
if not readable(path):
die(f"Cannot read {path} - enable userControl, or run with sudo.")
denied(path)
stats = read_json(path)
since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat()
print(f"Traffic through the inbounds since {since}, by {kind}:")
@@ -2560,7 +2567,7 @@ 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.", file=sys.stderr)
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)
def _inbound_subscriptions(*args):
@@ -2577,7 +2584,7 @@ def _inbound_subscriptions(*args):
if not os.path.isfile(path):
die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?")
if not readable(path):
die("Subscriptions are not readable by this user. Enable userControl, or run as root.")
denied(path)
subs = read_json(path)
if not user:
if qr:
+60 -17
View File
@@ -67,6 +67,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)"),
("F5 r", "Refresh now"),
("<Control>question", "Keyboard shortcuts"),
("<Control>w", "Close the window (the tray keeps running)"),
@@ -637,6 +638,10 @@ class OutputDialog(Adw.Dialog):
self.stop = Gtk.Button(label="Stop", css_classes=["destructive-action"], visible=False, valign=Gtk.Align.CENTER)
self.stop.connect("clicked", lambda *_: self.terminate())
header.pack_end(self.stop)
self.retry_with = None # () -> run it again as root
self.retry = Gtk.Button(label="Retry as Root", css_classes=["suggested-action"], visible=False, valign=Gtk.Align.CENTER)
self.retry.connect("clicked", lambda *_: (self.close(), self.retry_with()))
header.pack_end(self.retry)
self.spinner = Adw.Spinner(visible=False)
header.pack_end(self.spinner)
self.result = Gtk.Label(visible=False, valign=Gtk.Align.CENTER)
@@ -676,14 +681,16 @@ class OutputDialog(Adw.Dialog):
self.tags[name].set_property("foreground_rgba", rgba(dark_color if dark else light_color))
self.tags["dim"].set_property("foreground_rgba", rgba("#9a9996" if dark else "#77767b"))
def running(self, proc):
def running(self, proc, stoppable=True):
self.proc = proc
self.stop.set_visible(True)
self.stop.set_visible(stoppable) # a run as root is not ours to stop
self.spinner.set_visible(True)
def finished(self, status=0):
def finished(self, status=0, retry=None):
self.stop.set_visible(False)
self.spinner.set_visible(False)
self.retry.set_visible(retry is not None)
self.retry_with = retry
if status == -signal.SIGTERM:
text, classes = "stopped", ["dim-label"]
elif status:
@@ -733,6 +740,7 @@ class Window(Adw.ApplicationWindow):
self.pages = {}
self.typed = {} # action label -> what was last typed there
self.last_output = None # (title, text)
self.last_retry = None # () -> the last run again as root, when only root could do it
self.toasts = Adw.ToastOverlay()
view = Adw.ToolbarView(top_bar_style=Adw.ToolbarStyle.RAISED)
@@ -748,6 +756,8 @@ 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"])
header.pack_start(self.root_badge)
menu = Gio.Menu()
section = Gio.Menu()
section.append("How is a domain routed…", "win.where")
@@ -755,6 +765,9 @@ 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")
menu.append_section(None, section)
section = Gio.Menu()
section.append("Keyboard Shortcuts", "win.shortcuts")
section.append("About Proxy Suite", "win.about")
section.append("Quit", "app.quit")
@@ -807,6 +820,7 @@ class Window(Adw.ApplicationWindow):
action.connect("activate", callback)
self.add_action(action)
app.set_accels_for_action("win.filter", ["<Control>f"])
app.set_accels_for_action("app.elevated", ["<Control>e"])
app.set_accels_for_action("win.shortcuts", ["<Control>question"])
app.set_accels_for_action("app.reload", ["F5"])
app.set_accels_for_action("app.quit", ["<Control>q"])
@@ -910,7 +924,10 @@ class Window(Adw.ApplicationWindow):
def show_last_output(self):
if self.last_output:
OutputDialog(self, *self.last_output).present(self)
dialog = OutputDialog(self, *self.last_output)
dialog.retry.set_visible(self.last_retry is not None)
dialog.retry_with = self.last_retry
dialog.present(self)
else:
self.toast("Nothing has run yet.")
return True
@@ -950,9 +967,12 @@ class Window(Adw.ApplicationWindow):
dialog.present(self)
entry.grab_focus()
def toast(self, message, output=None):
def toast(self, message, output=None, retry=None):
toast = Adw.Toast(title=GLib.markup_escape_text(message), timeout=6)
if output:
if retry: # one button: the output stays a keypress away (o)
toast.set_button_label("Retry as Root")
toast.connect("button-clicked", lambda *_: retry())
elif output:
toast.set_button_label("Output")
toast.connect("button-clicked", lambda *_: OutputDialog(self, *output).present(self))
self.toasts.add_toast(toast)
@@ -1023,6 +1043,12 @@ class ProxySuiteGui(Adw.Application):
action = Gio.SimpleAction.new(name, None)
action.connect("activate", callback)
self.add_action(action)
elevated = Gio.SimpleAction.new_stateful("elevated", None, GLib.Variant.new_boolean(False))
elevated.connect("change-state", self.on_elevated)
self.add_action(elevated)
retry = Gio.SimpleAction.new("retry-root", GLib.VariantType.new("as"))
retry.connect("activate", lambda _, argv: self.run_argv("run", argv.unpack(), None, root=True))
self.add_action(retry)
self.hold() # the tray and notifications outlive the window
try:
from proxy_sni import StatusNotifierItem
@@ -1058,6 +1084,14 @@ class ProxySuiteGui(Adw.Application):
# --- window ------------------------------------------------------------------------------
def elevated(self):
return self.lookup_action("elevated").get_state().get_boolean()
def on_elevated(self, action, value):
action.set_state(value)
if self.window:
self.window.root_badge.set_visible(value.get_boolean())
def present(self, tab=None):
if self.window is None:
self.window = Window(self)
@@ -1169,9 +1203,12 @@ class ProxySuiteGui(Adw.Application):
dialog.connect("response", lambda _, r: r == "run" and then())
dialog.present(parent)
def run_argv(self, mode, argv, win):
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard."""
command = f"proxy-ctl {shlex.join(argv)}"
def run_argv(self, mode, argv, win, root=False):
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user."""
root = (root or self.elevated()) and argv[:1] != ["apps"]
command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}"
retry_argv = argv
qr = "--qr" in argv
if qr:
argv = [a for a in argv if a != "--qr"]
@@ -1181,14 +1218,14 @@ class ProxySuiteGui(Adw.Application):
dialog.present(win)
elif win is not None:
win.toast(f"… {command}")
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr), daemon=True).start()
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv), daemon=True).start()
def stream(self, command, argv, mode, win, dialog, qr):
def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv):
out = []
try:
p = model.popen(argv)
p = model.popen(argv, "pkexec" if root else None)
if dialog:
GLib.idle_add(lambda: dialog.running(p) and False)
GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False)
for line in p.stdout:
out.append(line.rstrip("\n"))
if dialog:
@@ -1197,16 +1234,20 @@ class ProxySuiteGui(Adw.Application):
except OSError as e:
out.append(f"cannot run proxy-ctl: {e}")
status = 127
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status) and False)
if root and status == 126 and not out:
out.append("authentication cancelled") # pkexec: the password dialog was dismissed
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv) and False)
def ran(self, command, mode, win, dialog, qr, out, status):
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv):
last = last_line(out)
text = "\n".join(out)
output = (command, text)
retry = (lambda: self.run_argv(mode, retry_argv, win, root=True)) if model.needs_root(out, status) else None
if win is not None:
win.last_output = output
win.last_retry = retry
if dialog:
dialog.finished(status)
dialog.finished(status, retry)
if status == -signal.SIGTERM:
dialog.write("\x1b[2m(stopped)\x1b[0m")
elif status:
@@ -1218,12 +1259,14 @@ class ProxySuiteGui(Adw.Application):
win.copy_text(last, f"Copied: {last}")
else:
message = f"{last} ({command})" if last else command
win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status else None)
win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status else None, retry)
elif status:
# From the tray: nothing else would say it failed.
note = Gio.Notification.new(f"{command} failed")
note.set_body(last or f"exit status {status}")
note.set_default_action("app.present")
if retry:
note.add_button_with_target("Retry as Root", "app.retry-root", GLib.Variant("as", retry_argv))
self.send_notification(None, note)
self.reload()
+32 -7
View File
@@ -8,6 +8,7 @@ die() cannot take a front end down.
import os
import re
import shlex
import shutil
import signal
import subprocess
import sys
@@ -83,6 +84,20 @@ def needs_confirm(action, row):
return action.confirm(row) if callable(action.confirm) else action.confirm
# What proxy-ctl and systemctl print when only root may do it.
# ponytail: matches the wording; an exit status of its own (77) if that ever drifts.
ROOT_HINT = re.compile(r"re-run with sudo|run with sudo|run as root|Interactive authentication required|Access denied")
def is_root():
return os.geteuid() == 0
def needs_root(out, status):
"""A failed run that root could do: the front ends offer to retry it elevated."""
return bool(status) and status > 0 and not is_root() and any(ROOT_HINT.search(line) for line in out)
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"}
@@ -281,7 +296,7 @@ def snapshot(states):
def status_items(states):
"""(label, value, style) for the status line: style is "", "ok", "warn" or "bad"."""
items = []
items = [("", "root", "warn")] if is_root() else []
overall = ctl._overall_state(snapshot(states) if states else None)
items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], "")))
if "proxy-suite-socks" in states:
@@ -406,7 +421,7 @@ TABS = [
prompt="<tag> <url or JSON>",
),
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
# Credentials: proxy-ctl refuses these without root, and the dialog says so.
# Credentials: proxy-ctl refuses these without root or the group, and the dialog says so.
Action("l", "its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
Action("c", "copy its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "its URL as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
@@ -492,7 +507,8 @@ TABS = [
Tab(
"apps",
"Apps",
_enabled("PER_APP_ROUTING_ENABLED"),
# `apps run` is per user (its uid, systemctl --user): nothing a root session can use.
lambda states: not is_root() and _enabled("PER_APP_ROUTING_ENABLED")(states),
[("profile", "Profile"), ("route", "Route")],
app_rows,
actions=[
@@ -537,10 +553,16 @@ def _capture(argv):
return p.stdout + p.stderr
def popen(argv):
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too."""
def elevated(argv, via):
"""proxy-ctl argv run as root through via (sudo, pkexec): by its full path, the one the polkit rule names."""
return [via, shutil.which(CTL) or CTL, *argv]
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."""
return subprocess.Popen(
[CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
text=True, errors="replace", start_new_session=True,
)
@@ -550,7 +572,10 @@ def stop(proc):
try:
os.killpg(proc.pid, signal.SIGTERM)
except OSError:
proc.terminate()
try:
proc.terminate()
except OSError:
pass # running as root: not ours to signal
def _safe(fn, *args, fallback=None):
+106 -19
View File
@@ -3,8 +3,11 @@
What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing.
"""
import os
import shlex
import shutil
import signal
import subprocess
from rich.text import Text
from textual import events, work
@@ -51,6 +54,8 @@ GLOBAL_KEYS = [
("w", "how is a domain routed"),
("L", "follow all logs"),
("o", "output of the last command"),
("!", "retry what just failed as root (sudo)"),
("#", "switch to root: proxy-tui again under sudo"),
("r", "refresh now"),
("?", "keys"),
("q", "quit"),
@@ -229,14 +234,32 @@ class Menu(Dialog):
class Output(Dialog):
BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy")]
BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy"), Binding("exclamation_mark", "retry_root", "retry as root")]
def __init__(self, title, text=None, wrap=True):
def __init__(self, title, text=None, wrap=True, retry=False):
super().__init__()
self.heading, self.initial, self.wrap = title, text, wrap
self.heading, self.initial, self.wrap, self.retry = title, text, wrap, retry
self.proc = None # the streaming command, stopped when the dialog closes
self.text = [] # plain lines, for copying
def hints(self):
retry = [("! retry as root", "retry_root")] if self.retry else []
return hint(*retry, ("c copy", "copy"), ("esc close", "dismiss"))
def offer_retry(self):
"""The run failed where root could do it: ! and a click on the hint run it again under sudo."""
self.retry = True
if self.is_attached:
self.query_one(".dialog-hint").remove()
self.query_one(".dialog").mount(self.hints())
def check_action(self, action, parameters):
return self.retry if action == "retry_root" else True
def action_retry_root(self):
self.dismiss()
self.app.action_retry_root()
def compose(self) -> ComposeResult:
with Vertical(classes="dialog output"):
yield Label(self.heading, classes="dialog-title", markup=False)
@@ -247,7 +270,7 @@ class Output(Dialog):
self.text.append(text.plain)
log.write(text)
yield log
yield hint(("c copy", "copy"), ("esc close", "dismiss"))
yield self.hints()
def write(self, line):
if self.is_attached:
@@ -297,6 +320,8 @@ class MainScreen(Screen):
Binding("w", "app.where"),
Binding("L", "app.logs"),
Binding("o", "app.last_output"),
Binding("exclamation_mark", "app.retry_root"),
Binding("number_sign", "app.switch_root"),
Binding("r", "app.reload"),
Binding("q", "app.quit"),
]
@@ -381,6 +406,7 @@ class ProxyTui(App):
self.typed = {} # prompt title -> what was last typed there
self.feedback_timer = None
self.last_output = None # (title, text)
self.retry = None # (mode, argv) of the last run that only root could do
self.animation_level = "none" # tab switches land at once
self.register_theme(THEME)
self.theme = THEME.name
@@ -529,6 +555,8 @@ class ProxyTui(App):
return model.applicable(self.tabs[self.active_tab()], row)
def check_action(self, action, parameters):
if action in ("retry_root", "switch_root"):
return not model.is_root()
# A row action that does not apply: its key does nothing.
if action != "act" or self.screen is not self.main:
return True
@@ -588,7 +616,7 @@ class ProxyTui(App):
def action_last_output(self):
if self.last_output:
self.push_screen(Output(*self.last_output))
self.push_screen(Output(*self.last_output, retry=self.retry is not None))
else:
self.feedback("Nothing has run yet.")
@@ -629,14 +657,7 @@ class ProxyTui(App):
def run_argv(self, mode, argv):
command = f"proxy-ctl {shlex.join(argv)}"
if mode in ("suspend", "pause"):
with self.suspend():
ctl._run_foreground([CTL, *argv])
if mode == "pause":
try:
input("\n[enter] back to proxy-tui")
except (EOFError, KeyboardInterrupt):
pass
self.action_reload()
self.foreground(mode, [CTL, *argv])
return
# A wrapped QR code no longer scans: it scrolls sideways instead.
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
@@ -645,6 +666,16 @@ class ProxyTui(App):
self.feedback(f"… {command}")
self.stream(command, argv, dialog, mode == "copy")
def foreground(self, mode, argv):
with self.suspend():
ctl._run_foreground(argv)
if mode == "pause":
try:
input("\n[enter] back to proxy-tui")
except (EOFError, KeyboardInterrupt):
pass
self.action_reload()
@work(thread=True)
def stream(self, command, argv, dialog, copy=False):
out = []
@@ -660,23 +691,77 @@ class ProxyTui(App):
except OSError as e:
out.append(f"cannot run proxy-ctl: {e}")
status = 127
self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True)
def finish(self, command, argv, dialog, copy, out, status, stream_shown=False):
"""A run's end: the feedback line, the clipboard, and the dialog's tail."""
if dialog and not stream_shown:
for line in out:
dialog.write(line)
last = Text.from_ansi(next((line for line in reversed(out) if line.strip()), "")).plain.strip()
message = f"{last} ({command})" if last else command
self.last_output = (command, "\n".join(out))
if status == -signal.SIGTERM and dialog:
self.call_from_thread(self.feedback, f"stopped: {command}", False)
self.feedback(f"stopped: {command}", False)
return
if copy and not status and last:
self.call_from_thread(self.copy_to_clipboard, last)
self.copy_to_clipboard(last)
message = f"copied: {last}"
if status:
message = f"exit {status}: {message}"
if dialog:
self.call_from_thread(dialog.write, f"\x1b[31m(exit status {status})\x1b[0m")
dialog.write(f"\x1b[31m(exit status {status})\x1b[0m")
if len(out) > 1 and not dialog:
message += " · o: full output"
self.call_from_thread(self.feedback, message, status == 0)
self.call_from_thread(self.action_reload)
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"
if dialog:
dialog.offer_retry()
self.feedback(message, status == 0)
self.action_reload()
def action_retry_root(self):
if not self.retry:
self.feedback("Nothing to retry as root.")
return
(mode, argv), self.retry = self.retry, None
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
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
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
if dialog:
self.push_screen(dialog)
self.finish(command, argv, dialog, mode == "copy", out, status)
def action_switch_root(self):
def switch(ok):
if not ok:
return
with self.suspend():
# Asks here, once: the TUI under sudo then starts without asking again.
status = ctl._run_foreground(["sudo", "-v"])
if status:
self.feedback("sudo: not authenticated", False)
else:
self.exit("root")
self.push_screen(Confirm("sudo proxy-tui"), switch)
def feedback(self, message, ok=None):
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok]
@@ -690,4 +775,6 @@ class ProxyTui(App):
if __name__ == "__main__":
ProxyTui().run()
if ProxyTui().run() == "root":
# The wrapper by name: sudo resets the environment, and the wrapper sets it again.
os.execvp("sudo", ["sudo", shutil.which("proxy-tui") or "proxy-tui"])
+16 -2
View File
@@ -352,7 +352,21 @@ class AutoProxyTest(EnvTest):
finally:
os.chmod(self.dir, 0o755)
self.assertNotEqual(status, 0)
self.assertIn("enable userControl, or run with sudo", err)
self.assertIn("proxy-suite group, or re-run with sudo", err)
class ZapretAutoTest(EnvTest):
@unittest.skipIf(os.geteuid() == 0, "root writes anything")
def test_clear_replaces_what_it_cannot_write(self):
"""The group writes the state directory, not root's list files in it."""
os.environ.update(ZAPRET_AUTO_ENABLED="1", ZAPRET_STATE_DIR=self.dir)
auto = self.write("zapret-hosts-auto.txt", "a.example\n")
state = self.write("circular/state.tsv", "1\ta.example\n")
os.chmod(auto, 0o444)
os.chmod(state, 0o444)
ok(ctl.cmd_zapret_auto, "clear")
self.assertEqual(ctl.read_text(auto), "")
self.assertEqual(ctl.read_text(state), "")
class InboundsTest(EnvTest):
@@ -568,7 +582,7 @@ class OutboundTestTest(EnvTest):
os.chmod(self.write("outbound-endpoints.json", {}), 0)
status, _, err = run(ctl.cmd_outbounds, "test", "--ping")
self.assertEqual(status, 0)
self.assertIn("enable userControl, or run with sudo", err)
self.assertIn("proxy-suite group, or re-run with sudo", err)
class ShareTest(EnvTest):
+16
View File
@@ -43,6 +43,22 @@ class ModelTest(unittest.TestCase):
self.assertEqual(items[-1], ("", "1 failed", "bad"))
self.assertEqual(model.status_items({})[0], ("", "Status unavailable", "bad"))
def test_root(self):
with mock.patch.object(model.os, "geteuid", lambda: 1000):
self.assertTrue(model.needs_root(["Cannot read /run/x - re-run with sudo."], 1))
self.assertTrue(model.needs_root(["Failed to start proxy-suite-tun.service: Access denied"], 1))
self.assertFalse(model.needs_root(["re-run with sudo"], 0))
self.assertFalse(model.needs_root(["Unknown outbound: x"], 1))
self.assertFalse(model.needs_root(["re-run with sudo"], -15)) # stopped, not refused
with mock.patch.object(model.os, "geteuid", lambda: 0):
self.assertFalse(model.needs_root(["re-run with sudo"], 1))
self.assertEqual(model.status_items({})[0], ("", "root", "warn"))
apps = next(t for t in model.TABS if t.id == "apps")
with mock.patch.object(ctl, "env", lambda name, default="": "1"):
self.assertFalse(apps.available({}))
with mock.patch.object(model.shutil, "which", lambda name: f"/nix/store/x/bin/{name}"):
self.assertEqual(model.elevated(["proxy", "config"], "pkexec"), ["pkexec", "/nix/store/x/bin/proxy-ctl", "proxy", "config"])
def test_services_skip_the_subscription_update(self):
rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"})
self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"])
+33
View File
@@ -2,6 +2,7 @@
"""Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv."""
import asyncio
import contextlib
import tempfile
import unittest
from unittest import mock
@@ -279,6 +280,38 @@ class TuiTest(unittest.TestCase):
await pilot.pause()
killpg.assert_called_once_with(4242, model.signal.SIGTERM)
# A copy only root may make offers ! to retry it under sudo, and still copies.
with mock.patch.object(model.os, "geteuid", lambda: 1000):
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})
popen = mock.Mock(return_value=sudo)
# proxy-tui's own subprocess only: reads in the background spawn through proxy_ctl's.
with mock.patch.object(app, "suspend", contextlib.nullcontext), \
mock.patch.object(tui, "subprocess", mock.Mock(Popen=popen)), \
mock.patch.object(model.shutil, "which", lambda name: f"/bin/{name}"), \
mock.patch.object(app, "copy_to_clipboard") as copy, \
mock.patch("builtins.print"):
await pilot.press("exclamation_mark")
await pilot.pause()
self.assertEqual(popen.call_args[0][0], ["sudo", "/bin/proxy-ctl", "proxy", "outbounds", "link", "b"])
copy.assert_called_once_with("vless://b")
self.assertIsNone(app.retry)
# A dialog run only root may do offers it in the dialog itself, and ! there retries.
dialog = tui.Output("proxy-ctl inbounds stats")
app.push_screen(dialog)
await pilot.pause()
self.assertFalse(dialog.check_action("retry_root", ()))
app.finish("proxy-ctl inbounds stats", ["inbounds", "stats"], dialog, False, ["Cannot read x - enable userControl, or run with sudo."], 1, stream_shown=True)
await pilot.pause()
self.assertIn("retry as root", str(dialog.query_one(".dialog-hint").render()))
with mock.patch.object(app, "action_retry_root") as retry:
await pilot.press("exclamation_mark")
await pilot.pause()
retry.assert_called_once_with()
self.assertIsNot(app.screen, dialog)
if __name__ == "__main__":
unittest.main()