From b91994e150dedd73a8d4265c71c7f87ab601f637 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Sat, 26 Sep 2026 22:34:25 +0500 Subject: [PATCH] fix: close some utilities gaps --- README.md | 2 +- pkgs/proxy-ctl/proxy_ctl.py | 14 ++-- pkgs/proxy-ctl/proxy_gui.py | 11 +-- pkgs/proxy-ctl/proxy_model.py | 109 ++++++++++++++++++++++++++--- pkgs/proxy-ctl/proxy_tui.py | 2 +- pkgs/proxy-ctl/test_proxy_model.py | 56 ++++++++++++++- pkgs/proxy-ctl/test_proxy_tui.py | 2 +- 7 files changed, 170 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index e2cec72..deb08d4 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ Changes and secrets need root or the userControl group. zapret [status|on|off] DPI bypass zapret auto [list] sites zapret2 learned as blocked zapret auto add|forget|exclude - pin, forget, or never learn a site + treat a site as blocked, forget it, or never touch it zapret auto unpin|include undo add or exclude zapret auto clear forget learned sites and strategies zapret cutoff [status] networks cut off at 16 KB, and names that pass diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 77b815d..bddfed9 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -96,7 +96,7 @@ Changes and secrets need root or the userControl group. zapret [status|on|off] DPI bypass zapret auto [list] sites zapret2 learned as blocked zapret auto add|forget|exclude - pin, forget, or never learn a site + treat a site as blocked, forget it, or never touch it zapret auto unpin|include undo add or exclude zapret auto clear forget learned sites and strategies zapret cutoff [status] networks cut off at 16 KB, and names that pass @@ -591,9 +591,9 @@ COMPLETE = { "zapret auto": { "words": { "list": "hosts zapret2 learned as blocked", - "add": "pin a host", + "add": "pin a host: treat it as blocked", "forget": "forget a learned host", - "exclude": "never learn a host", + "exclude": "never touch or learn a host", "unpin": "undo add", "include": "undo exclude", "clear": "forget learned hosts and strategies", @@ -2533,7 +2533,7 @@ def cmd_zapret_auto(verb="list", domain="", *_): print("No hostnames learned yet.") elif verb == "add": _zapret_auto_edit(user, domain, "add") - print(f"Pinned {domain} (always bypassed).") + print(f"Pinned {domain}: zapret treats it as blocked.") elif verb == "forget": _zapret_auto_edit(auto, domain, "drop") _zapret_strategy_drop(domain) @@ -2797,12 +2797,12 @@ def cmd_where(domain="", *_): pinned = _where_in_list(_zapret_auto_file("zapret-hosts-user.txt"), domain) learned = _where_in_list(_zapret_auto_file("zapret-hosts-auto.txt"), domain) if excluded: - _where_row("zapret", f"excluded ({excluded}) - never bypassed, never learned") + _where_row("zapret", f"excluded ({excluded}) - never touched, never learned") elif pinned: - _where_row("zapret", f"pinned ({pinned}) - always bypassed") + _where_row("zapret", f"pinned ({pinned}) - treated as blocked") verdict = verdict or "direct, with the zapret bypass" elif learned: - _where_row("zapret", f"learned ({learned}) - bypassed") + _where_row("zapret", f"learned ({learned}) - treated as blocked") verdict = verdict or "direct, with the zapret bypass" else: _where_row("zapret", "not learned, not pinned, not excluded") diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index 1b35e00..60976d8 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -503,9 +503,8 @@ class Page(Gtk.Box): def tab_actions_box(self): box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, halign=Gtk.Align.CENTER, css_classes=["empty-actions"]) - tab_actions = [(i, a) for i, a in enumerate(self.tab.actions) if a.when is None] - for n, (i, action) in enumerate(tab_actions): - box.append(self.action_button(i, action, suggested=n == 0)) + for n, action in enumerate(model.applicable(self.tab, None)): + box.append(self.action_button(self.tab.actions.index(action), action, suggested=n == 0)) return box def action_button(self, i, action, suggested=False): @@ -1039,9 +1038,9 @@ class Window(Adw.ApplicationWindow): def show_shortcuts(self): dialog = Adw.ShortcutsDialog() page = self.page() - if page and page.tab.actions: + if page and (actions := [a for a in page.tab.actions if model.offered(a)]): section = Adw.ShortcutsSection(title=page.tab.title) - for action in page.tab.actions: + for action in actions: section.add(Adw.ShortcutsItem(title=cap(action.label), accelerator=accelerator(action.key))) dialog.add(section) section = Adw.ShortcutsSection(title="Everywhere") @@ -1351,6 +1350,8 @@ class ProxySuiteGui(Adw.Application): def main(argv=None): + # Commands run with no terminal here: what asks on one is left out. + model.TTY = False return ProxySuiteGui().run(argv if argv is not None else sys.argv) diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index b940475..0c3362b 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -28,7 +28,7 @@ def _die(message, status=1): # Clash API calls and systemctl spawns that several readers repeat within one load. -MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state") +MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl") # proxy_ctl as the CLI has it, before the patching below: its own tests put these back. CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)} @@ -64,6 +64,8 @@ class Action: prompt: str = "" # ask for text first confirm: bool | Callable = False # or row -> ask first mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard + offered: Callable = None # () -> this configuration has it; None: every one does + tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it @dataclass @@ -81,6 +83,14 @@ def ROW(_): return True +# Whether the front end can hand a command the terminal to ask on. The GUI cannot: it clears this. +TTY = True + + +def offered(action): + return (TTY or not action.tty) and (action.offered is None or bool(_safe(action.offered, fallback=False))) + + def needs_confirm(action, row): return action.confirm(row) if callable(action.confirm) else action.confirm @@ -147,6 +157,30 @@ ZAPRET_LISTS = ( ) +def _wl_entry(row): + """The whitelist-bypass creator or joiner behind a row, or None.""" + return next((w for w in ctl._wl() if ctl._wl_unit(w) == row["unit"]), None) + + +def _wl_role(*roles, platforms=None, fixed=None): + def check(row): + w = _wl_entry(row) + return bool(w) and w["role"] in roles and (platforms is None or w.get("platform") in platforms) and (fixed is None or bool(w.get("fixedLink")) == fixed) + + return check + + +def _path(text): + """A typed path, whole: proxy-ctl may run elsewhere (pkexec starts it in /root).""" + if not text.strip(): + raise ValueError("no path given") + return os.path.abspath(os.path.expanduser(text.strip())) + + +def _wl_argv(verb, *extra): + return lambda r, *_: ["wl", verb, _wl_entry(r)["name"], *extra] + + def _awg_profile(row): """The global AmneziaWG profile behind a row, or empty.""" name = row["unit"].removeprefix(AWG_PREFIX) @@ -156,6 +190,8 @@ def _awg_profile(row): def _unit_argv(row, verb): if profile := _awg_profile(row): return ["awg", verb, profile] + if w := _wl_entry(row): + return ["wl", verb, w["name"]] return [*TOGGLES[row["unit"]], verb] @@ -168,7 +204,7 @@ def restart_argv(row, *_): def _controllable(row): - return row["unit"] in TOGGLES or bool(_awg_profile(row)) + return row["unit"] in TOGGLES or bool(_awg_profile(row)) or bool(_wl_entry(row)) def service_rows(states): @@ -410,6 +446,14 @@ def _add_args(text): return [text] if text.startswith("{") else text.split(None, 1) +def _zapret_auto(): + return ctl.env("ZAPRET_AUTO_ENABLED") == "1" + + +def _rule_sets(): + return bool(ctl.read_json_or(ctl.env("RULE_SETS_FILE"), [])) + + def _zapret_toggle(row, _, states): return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"] @@ -434,6 +478,45 @@ TABS = [ # A failed unit restarts too: that is how it gets another try. Action("ctrl+r", "restart it", restart_argv, when=lambda r: _controllable(r) and r["state"] in ("active", "failed")), Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True), + Action( + "n", + "new Tor circuits for new connections", + lambda r, *_: ["tor", "newnym"], + when=lambda r: r["unit"] == "proxy-suite-tor" and r["state"] == "active", + ), + # whitelist-bypass: a creator makes the call its joiner joins. + Action("k", "its call link", _wl_argv("link"), when=_wl_role("creator"), mode="dialog"), + Action("c", "copy its call link", _wl_argv("link"), when=_wl_role("creator"), mode="copy"), + Action("Q", "its call link as QR", _wl_argv("link", "--qr"), when=_wl_role("creator"), mode="dialog"), + Action( + "N", + "drop its call for a new one", + _wl_argv("new"), + when=_wl_role("creator", fixed=False), + confirm=True, + ), + Action( + "j", + "set the call it joins…", + lambda r, t, _: ["wl", "join", _wl_entry(r)["name"], t.strip()], + when=_wl_role("joiner"), + prompt=" - a room id, a slug or a URL", + ), + Action( + "a", + "replace its login with a cookies file…", + lambda r, t, _: ["wl", "auth", _wl_entry(r)["name"], _path(t)], + when=_wl_role("creator"), + prompt=" - cookies exported from the desktop Creator", + ), + Action( + "A", + "replace its login with an email and password", + _wl_argv("auth"), + when=_wl_role("creator", platforms=ctl.WL_PASSWORD_LOGIN), + mode="pause", + tty=True, + ), ], ), Tab( @@ -443,7 +526,11 @@ TABS = [ [("active", ""), ("key", "Mode"), ("mode", "Meaning")], route_rows, summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.", - actions=[Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"])], + actions=[ + Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"]), + Action("i", "rule sets and when each was fetched", lambda r, *_: ["proxy", "rulesets", "list"], mode="dialog", offered=_rule_sets), + Action("u", "fetch the rule sets now", lambda r, *_: ["proxy", "rulesets", "update"], mode="dialog", offered=_rule_sets), + ], ), Tab( "outbounds", @@ -502,6 +589,7 @@ TABS = [ Action("J", "its JSON", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--json"], when=ROW, mode="dialog"), Action("F", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=ROW, mode="dialog"), Action("X", "client config with every outbound and rule", lambda r, *_: ["proxy", "config"], mode="dialog"), + Action("C", "the config as it runs here", lambda r, *_: ["proxy", "config", "--raw"], mode="dialog"), ], ), Tab( @@ -554,12 +642,13 @@ TABS = [ summary=zapret_summary, actions=[ Action("f", "forget it (may be learned again)", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")), - Action("x", "exclude it (never learn)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")), + Action("x", "exclude it (never touch or learn it)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")), Action("u", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")), - Action("i", "include it (may be learned again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")), - Action("a", "pin a host (always bypass)…", lambda r, t, _: ["zapret", "auto", "add", t], prompt=""), - Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True), - Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"), + Action("i", "include it (zapret may touch or learn it again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")), + Action("a", "pin a host (treat it as blocked)…", lambda r, t, _: ["zapret", "auto", "add", t.strip()], prompt="", offered=_zapret_auto), + Action("X", "exclude a host (never touch or learn it)…", lambda r, t, _: ["zapret", "auto", "exclude", t.strip()], prompt="", offered=_zapret_auto), + Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True, offered=_zapret_auto), + Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog", offered=lambda: ctl.env("ZAPRET_CUTOFF_ENABLED") == "1"), Action("z", "start / stop zapret", _zapret_toggle), Action("Z", "restart zapret", lambda *_: ["zapret", "restart"]), ], @@ -644,7 +733,7 @@ def available_tabs(states): def applicable(tab, row): - return [a for a in tab.actions if a.when is None or (row is not None and a.when(row))] + return [a for a in tab.actions if offered(a) and (a.when is None or (row is not None and a.when(row)))] def load_tab(tab, states): @@ -655,7 +744,7 @@ def load_tab(tab, states): except (Exception, SystemExit) as e: return [], f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "") if not rows: - hints = " ".join(f"{a.key}: {short(a.label)}" for a in tab.actions if a.prompt) + hints = " ".join(f"{a.key}: {short(a.label)}" for a in tab.actions if a.prompt and a.when is None and offered(a)) summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "") return rows, summary diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index 848a36e..82904a3 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -692,7 +692,7 @@ class ProxyTui(App): def action_help(self): tab = self.tabs[self.active_tab()] text = Text() - for heading, keys in ((tab.title, [(a.key, a.label) for a in tab.actions]), ("Everywhere", GLOBAL_KEYS)): + for heading, keys in ((tab.title, [(a.key, a.label) for a in tab.actions if model.offered(a)]), ("Everywhere", GLOBAL_KEYS)): text.append(f"{heading}\n", style="bold") for key, label in keys: text.append(f" {key:<9}", style=ACCENT) diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index 3516751..337dfce 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -132,6 +132,60 @@ class ModelTest(unittest.TestCase): self.assertFalse(model._amneziawg(onion)) self.assertEqual(model.TOGGLES["proxy-suite-tor"], ["tor"]) + def test_whitelist_bypass_rows(self): + """A creator or joiner is a unit on the services tab: toggled, restarted, and its call handled there.""" + tab = model.TABS[0] + wl = [ + {"name": "vk", "role": "creator", "platform": "vk"}, + {"name": "dion", "role": "creator", "platform": "dion", "fixedLink": True}, + {"name": "home", "role": "joiner", "platform": "vk"}, + ] + with mock.patch.object(ctl, "_wl", lambda: wl): + vk, dion, home = ( + {"key": u, "unit": u, "name": u, "state": "active"} for u in ("proxy-suite-wb-creator-vk", "proxy-suite-wb-creator-dion", "proxy-suite-wb-joiner-home") + ) + keys = lambda row: {a.key: a for a in model.applicable(tab, row)} + self.assertEqual(model.toggle_argv(vk), ["wl", "off", "vk"]) + self.assertEqual(model.restart_argv(home), ["wl", "restart", "home"]) + self.assertEqual(keys(vk)["k"].argv(vk), ["wl", "link", "vk"]) + self.assertEqual(keys(vk)["Q"].argv(vk), ["wl", "link", "vk", "--qr"]) + self.assertEqual(keys(vk)["N"].argv(vk), ["wl", "new", "vk"]) + self.assertEqual(keys(vk)["a"].argv(vk, "/tmp/c.json", {}), ["wl", "auth", "vk", "/tmp/c.json"]) + self.assertEqual(keys(home)["j"].argv(home, " abc-def ", {}), ["wl", "join", "home", "abc-def"]) + self.assertNotIn("N", keys(dion)) # a fixed link: its linkFile sets the call + self.assertNotIn("A", keys(vk)) # VK logs in only in a browser + self.assertEqual(keys(dion)["A"].argv(dion), ["wl", "auth", "dion"]) + self.assertFalse({"k", "N", "a", "A"} & set(keys(home))) + self.assertNotIn("j", keys(vk)) + with mock.patch.object(model, "TTY", False): + self.assertNotIn("A", keys(dion)) # it asks on a terminal the GUI does not have + + def test_tor_newnym(self): + tab = model.TABS[0] + tor = {"key": "proxy-suite-tor", "unit": "proxy-suite-tor", "name": "tor", "state": "active"} + newnym = next(a for a in tab.actions if a.key == "n") + self.assertIn(newnym, model.applicable(tab, tor)) + self.assertEqual(newnym.argv(tor), ["tor", "newnym"]) + self.assertNotIn(newnym, model.applicable(tab, {**tor, "state": "inactive"})) + + def test_actions_this_configuration_has(self): + """A tab-wide action for a feature the configuration leaves out is not offered.""" + routing = next(t for t in model.TABS if t.id == "routing") + zapret = next(t for t in model.TABS if t.id == "zapret") + env = {} + with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)): + self.assertEqual([a.key for a in model.applicable(routing, None)], []) + self.assertEqual([a.key for a in model.applicable(zapret, None)], ["z", "Z"]) + with tempfile.NamedTemporaryFile("w", suffix=".json") as f: + json.dump([{"name": "ru", "path": "/nonexistent"}], f) + f.flush() + env.update(RULE_SETS_FILE=f.name, ZAPRET_AUTO_ENABLED="1", ZAPRET_CUTOFF_ENABLED="1") + self.assertEqual([a.argv(None, "", {}) for a in model.applicable(routing, None)], [["proxy", "rulesets", "list"], ["proxy", "rulesets", "update"]]) + self.assertEqual([a.key for a in model.applicable(zapret, None)], ["a", "X", "C", "P", "z", "Z"]) + actions = {a.key: a for a in zapret.actions} + self.assertEqual(actions["a"].argv(None, "example.com", {}), ["zapret", "auto", "add", "example.com"]) + self.assertEqual(actions["X"].argv(None, "example.com", {}), ["zapret", "auto", "exclude", "example.com"]) + def test_tray_menu(self): states = { "proxy-suite-socks": "active", @@ -202,7 +256,7 @@ class ModelTest(unittest.TestCase): self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")]) self.assertIn("Pinned: b", summary) with mock.patch.object(ctl, "env", lambda name, default="": ""): - self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "H", "x", "l", "c", "Q", "J", "F", "X"]) + self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "H", "x", "l", "c", "Q", "J", "F", "X", "C"]) chain = next(a for a in tab.actions if a.key == "h") self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"]) # Probe exits go by the backend's tag. diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 5680ff3..62f4c27 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -287,7 +287,7 @@ class TuiTest(unittest.TestCase): await pilot.press("down", "enter") await pilot.pause() labels = self.menu_labels(app) - self.assertIn("include it (may be learned again)", labels) + self.assertIn("include it (zapret may touch or learn it again)", labels) self.assertNotIn("forget it (may be learned again)", labels) await pilot.press("escape", "i") self.assertEqual(self.ran.pop(), ["zapret", "auto", "include", "kept.example"])