feat: proxy-tui
This commit is contained in:
12 files changed
+1028
-48
No files matched your search
@@ -17,7 +17,7 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.
|
|||||||
- Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel
|
- Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel
|
||||||
- Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile
|
- Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile
|
||||||
- Server inbounds with share links, QR codes, per-user subscriptions and traffic stats
|
- Server inbounds with share links, QR codes, per-user subscriptions and traffic stats
|
||||||
- A tray indicator and the `proxy-ctl` CLI
|
- A tray indicator, the `proxy-ctl` CLI, and the `proxy-tui` terminal UI
|
||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
@@ -134,6 +134,7 @@ A group without a verb shows its status or list.
|
|||||||
zapret auto [list] hosts zapret2 learned as blocked
|
zapret auto [list] hosts zapret2 learned as blocked
|
||||||
zapret auto add|forget|exclude <domain>
|
zapret auto add|forget|exclude <domain>
|
||||||
pin, forget, or never learn a host (sudo)
|
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)
|
zapret auto clear forget learned hosts and strategies (sudo)
|
||||||
zapret cutoff [status] networks this line cuts at 16 KB, and their names
|
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 (sudo)
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ Update the module option docs there instead of editing these files by hand.
|
|||||||
- [sshProxy](./sshProxy.md)
|
- [sshProxy](./sshProxy.md)
|
||||||
- [tgWsProxy](./tgWsProxy.md)
|
- [tgWsProxy](./tgWsProxy.md)
|
||||||
- [tray](./tray.md)
|
- [tray](./tray.md)
|
||||||
|
- [tui](./tui.md)
|
||||||
- [userControl](./userControl.md)
|
- [userControl](./userControl.md)
|
||||||
- [warp](./warp.md)
|
- [warp](./warp.md)
|
||||||
- [zapret](./zapret.md)
|
- [zapret](./zapret.md)
|
||||||
@@ -244,6 +245,9 @@ services.proxy-suite = {
|
|||||||
enable = false;
|
enable = false;
|
||||||
pollInterval = 5;
|
pollInterval = 5;
|
||||||
};
|
};
|
||||||
|
tui = {
|
||||||
|
enable = true;
|
||||||
|
};
|
||||||
userControl = {
|
userControl = {
|
||||||
allow = [
|
allow = [
|
||||||
"global"
|
"global"
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# services.proxy-suite.tui
|
||||||
|
|
||||||
|
Part of the [proxy-suite options reference](./index.md).
|
||||||
|
|
||||||
|
## Options
|
||||||
|
|
||||||
|
- tui
|
||||||
|
- [enable](#services-proxy-suite-tui-enable)
|
||||||
|
|
||||||
|
<a id="services-proxy-suite-tui-enable"></a>
|
||||||
|
## services\.proxy-suite\.tui\.enable
|
||||||
|
|
||||||
|
Whether to enable proxy-tui, an interactive terminal UI for everything proxy-ctl controls at runtime\.
|
||||||
|
|
||||||
|
*Type:*
|
||||||
|
boolean
|
||||||
|
|
||||||
|
*Default:*
|
||||||
|
|
||||||
|
```nix
|
||||||
|
true
|
||||||
|
```
|
||||||
|
|
||||||
|
*Example:*
|
||||||
|
|
||||||
|
```nix
|
||||||
|
true
|
||||||
|
```
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
./tg-ws-proxy.nix
|
./tg-ws-proxy.nix
|
||||||
./geodata.nix
|
./geodata.nix
|
||||||
./tray.nix
|
./tray.nix
|
||||||
|
./tui.nix
|
||||||
./user-control.nix
|
./user-control.nix
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{ lib, ... }:
|
||||||
|
{
|
||||||
|
options.services.proxy-suite.tui.enable =
|
||||||
|
lib.mkEnableOption "proxy-tui, an interactive terminal UI for everything proxy-ctl controls at runtime"
|
||||||
|
// {
|
||||||
|
default = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -135,7 +135,7 @@ in
|
|||||||
lib.mkMerge [
|
lib.mkMerge [
|
||||||
autoProxyUnits
|
autoProxyUnits
|
||||||
{
|
{
|
||||||
environment.systemPackages = [ control.proxyCtl ];
|
environment.systemPackages = [ control.proxyCtl ] ++ lib.optional cfg.tui.enable control.proxyCtl.tui;
|
||||||
|
|
||||||
# nftables must be on for transparent routing backends. Global TUN uses
|
# nftables must be on for transparent routing backends. Global TUN uses
|
||||||
# SingBox auto_redirect programs an `inet sing-box` nftables table.
|
# SingBox auto_redirect programs an `inet sing-box` nftables table.
|
||||||
|
|||||||
@@ -240,6 +240,13 @@
|
|||||||
run add pinned.example > /dev/null
|
run add pinned.example > /dev/null
|
||||||
test "$(grep -c -x pinned.example "$state/zapret-hosts-user.txt")" = 1
|
test "$(grep -c -x pinned.example "$state/zapret-hosts-user.txt")" = 1
|
||||||
|
|
||||||
|
# unpin and include undo add and exclude.
|
||||||
|
run unpin pinned.example > /dev/null
|
||||||
|
! grep -qx pinned.example "$state/zapret-hosts-user.txt"
|
||||||
|
run include blocked.example > /dev/null
|
||||||
|
! grep -qx blocked.example "$state/zapret-hosts-user-exclude.txt"
|
||||||
|
run add pinned.example > /dev/null
|
||||||
|
|
||||||
# The lists stay readable by unprivileged proxy-ctl after a rewrite.
|
# The lists stay readable by unprivileged proxy-ctl after a rewrite.
|
||||||
test "$(stat -c %a "$state/zapret-hosts-user.txt")" = 644
|
test "$(stat -c %a "$state/zapret-hosts-user.txt")" = 644
|
||||||
|
|
||||||
@@ -406,6 +413,16 @@
|
|||||||
touch "$out"
|
touch "$out"
|
||||||
'';
|
'';
|
||||||
|
|
||||||
|
# proxy-tui driven headless: keys turn into the right proxy-ctl argv.
|
||||||
|
proxy-tui-unit =
|
||||||
|
pkgs.runCommand "proxy-suite-proxy-tui-unit-check"
|
||||||
|
{ nativeBuildInputs = [ (pkgs.python3.withPackages (ps: [ ps.textual ])) ]; }
|
||||||
|
''
|
||||||
|
export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl}
|
||||||
|
python ${../../pkgs/proxy-ctl}/test_proxy_tui.py
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
|
||||||
# autoProxy slowness routing: sampler and judge.
|
# autoProxy slowness routing: sampler and judge.
|
||||||
autoproxy-slowness =
|
autoproxy-slowness =
|
||||||
pkgs.runCommand "proxy-suite-autoproxy-slowness-check"
|
pkgs.runCommand "proxy-suite-autoproxy-slowness-check"
|
||||||
|
|||||||
@@ -21,9 +21,19 @@ let
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
tuiOffFixture = evalProxySuite [
|
||||||
|
baseModule
|
||||||
|
{ services.proxy-suite.tui.enable = false; }
|
||||||
|
];
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
assertions = [
|
assertions = [
|
||||||
|
(
|
||||||
|
assert packagePathMatches trayManualFixture.config.environment.systemPackages ".*/[^/]*proxy-tui$";
|
||||||
|
assert !(packagePathMatches tuiOffFixture.config.environment.systemPackages ".*/[^/]*proxy-tui$");
|
||||||
|
true
|
||||||
|
)
|
||||||
(
|
(
|
||||||
assert packagePathMatches trayAutostartFixture.config.environment.systemPackages
|
assert packagePathMatches trayAutostartFixture.config.environment.systemPackages
|
||||||
".*/[^/]*proxy-suite-tray(-[0-9.]+)?$";
|
".*/[^/]*proxy-suite-tray(-[0-9.]+)?$";
|
||||||
|
|||||||
+67
-44
@@ -75,48 +75,71 @@ let
|
|||||||
AUTOPROXY_ENABLED = autoProxyEnabled;
|
AUTOPROXY_ENABLED = autoProxyEnabled;
|
||||||
AUTOPROXY_STATE_DIR = autoProxyStateDir;
|
AUTOPROXY_STATE_DIR = autoProxyStateDir;
|
||||||
};
|
};
|
||||||
in
|
envFlags = lib.concatStringsSep " " (
|
||||||
pkgs.symlinkJoin {
|
lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv
|
||||||
name = "proxy-ctl";
|
);
|
||||||
paths = [ unwrapped ];
|
# A separate package: the Textual closure stays off hosts that don't enable it.
|
||||||
nativeBuildInputs = [ pkgs.makeWrapper ];
|
# It imports proxy_ctl for reads and runs proxy-ctl for every change.
|
||||||
passthru.proxySuiteCheck = {
|
tui = pkgs.symlinkJoin {
|
||||||
inherit
|
name = "proxy-tui";
|
||||||
wrapperEnv
|
paths = [
|
||||||
subscriptionTagsFile
|
(pkgs.writeScriptBin "proxy-tui" (
|
||||||
perAppRoutingProfilesFile
|
"#!${pkgs.python3.withPackages (ps: [ ps.textual ])}/bin/python3\n"
|
||||||
proxychainsConfigFile
|
+ builtins.readFile ./proxy-ctl/proxy_tui.py
|
||||||
amneziaWgProfileNamesFile
|
))
|
||||||
;
|
];
|
||||||
script = unwrapped.drvAttrs.text;
|
nativeBuildInputs = [ pkgs.makeWrapper ];
|
||||||
|
postBuild = ''
|
||||||
|
wrapProgram "$out/bin/proxy-tui" \
|
||||||
|
--prefix PYTHONPATH : ${pkgs.writeTextDir "proxy_ctl.py" (builtins.readFile ./proxy-ctl/proxy_ctl.py)} \
|
||||||
|
--prefix PATH : "${
|
||||||
|
lib.makeBinPath [
|
||||||
|
proxyCtl
|
||||||
|
pkgs.systemd
|
||||||
|
]
|
||||||
|
}" ${envFlags}
|
||||||
|
'';
|
||||||
};
|
};
|
||||||
# Probes present a browser's TLS fingerprint: bot protection refuses plain
|
proxyCtl = pkgs.symlinkJoin {
|
||||||
# curl. The newest Chrome profile the package ships, since the set varies by
|
name = "proxy-ctl";
|
||||||
# version; the build fails if there is none.
|
paths = [ unwrapped ];
|
||||||
postBuild = ''
|
nativeBuildInputs = [ pkgs.makeWrapper ];
|
||||||
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.bash} \
|
passthru.tui = tui;
|
||||||
"$out/share/bash-completion/completions/proxy-ctl"
|
passthru.proxySuiteCheck = {
|
||||||
install -Dm644 ${./proxy-ctl/completions/_proxy-ctl} "$out/share/zsh/site-functions/_proxy-ctl"
|
inherit
|
||||||
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.fish} \
|
wrapperEnv
|
||||||
"$out/share/fish/vendor_completions.d/proxy-ctl.fish"
|
subscriptionTagsFile
|
||||||
probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1)
|
perAppRoutingProfilesFile
|
||||||
[ -x "$probe_curl" ]
|
proxychainsConfigFile
|
||||||
wrapProgram "$out/bin/proxy-ctl" \
|
amneziaWgProfileNamesFile
|
||||||
--set PROBE_CURL "$probe_curl" \
|
;
|
||||||
--prefix PATH : "${
|
script = unwrapped.drvAttrs.text;
|
||||||
lib.makeBinPath [
|
};
|
||||||
# curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`.
|
# Probes present a browser's TLS fingerprint: bot protection refuses plain
|
||||||
pkgs.bash
|
# curl. The newest Chrome profile the package ships, since the set varies by
|
||||||
pkgs.curl
|
# version; the build fails if there is none.
|
||||||
pkgs.fzf
|
postBuild = ''
|
||||||
pkgs.proxychains-ng
|
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.bash} \
|
||||||
pkgs.qrencode
|
"$out/share/bash-completion/completions/proxy-ctl"
|
||||||
pkgs.systemd
|
install -Dm644 ${./proxy-ctl/completions/_proxy-ctl} "$out/share/zsh/site-functions/_proxy-ctl"
|
||||||
]
|
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.fish} \
|
||||||
}" ${
|
"$out/share/fish/vendor_completions.d/proxy-ctl.fish"
|
||||||
lib.concatStringsSep " " (
|
probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1)
|
||||||
lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv
|
[ -x "$probe_curl" ]
|
||||||
)
|
wrapProgram "$out/bin/proxy-ctl" \
|
||||||
}
|
--set PROBE_CURL "$probe_curl" \
|
||||||
'';
|
--prefix PATH : "${
|
||||||
}
|
lib.makeBinPath [
|
||||||
|
# curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`.
|
||||||
|
pkgs.bash
|
||||||
|
pkgs.curl
|
||||||
|
pkgs.fzf
|
||||||
|
pkgs.proxychains-ng
|
||||||
|
pkgs.qrencode
|
||||||
|
pkgs.systemd
|
||||||
|
]
|
||||||
|
}" ${envFlags}
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
in
|
||||||
|
proxyCtl
|
||||||
@@ -72,6 +72,7 @@ A group without a verb shows its status or list.
|
|||||||
zapret auto [list] hosts zapret2 learned as blocked
|
zapret auto [list] hosts zapret2 learned as blocked
|
||||||
zapret auto add|forget|exclude <domain>
|
zapret auto add|forget|exclude <domain>
|
||||||
pin, forget, or never learn a host (sudo)
|
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)
|
zapret auto clear forget learned hosts and strategies (sudo)
|
||||||
zapret cutoff [status] networks this line cuts at 16 KB, and their names
|
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 (sudo)
|
||||||
@@ -363,11 +364,15 @@ COMPLETE = {
|
|||||||
"add": "pin a host",
|
"add": "pin a host",
|
||||||
"forget": "forget a learned host",
|
"forget": "forget a learned host",
|
||||||
"exclude": "never learn a host",
|
"exclude": "never learn a host",
|
||||||
|
"unpin": "undo add",
|
||||||
|
"include": "undo exclude",
|
||||||
"clear": "forget learned hosts and strategies",
|
"clear": "forget learned hosts and strategies",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zapret auto forget": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))},
|
"zapret auto forget": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))},
|
||||||
"zapret auto exclude": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))},
|
"zapret auto exclude": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))},
|
||||||
|
"zapret auto unpin": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-user.txt"))))},
|
||||||
|
"zapret auto include": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-user-exclude.txt"))))},
|
||||||
"zapret cutoff": {"words": {"status": "networks this line cuts at 16 KB", "probe": "probe this line again now"}},
|
"zapret cutoff": {"words": {"status": "networks this line cuts at 16 KB", "probe": "probe this line again now"}},
|
||||||
"awg": {
|
"awg": {
|
||||||
"words": {
|
"words": {
|
||||||
@@ -1642,7 +1647,7 @@ def cmd_zapret_auto(verb="list", domain="", *_):
|
|||||||
user = _zapret_auto_file("zapret-hosts-user.txt")
|
user = _zapret_auto_file("zapret-hosts-user.txt")
|
||||||
exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt")
|
exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt")
|
||||||
|
|
||||||
if verb in ("add", "forget", "exclude") and not HOSTNAME.fullmatch(domain):
|
if verb in ("add", "forget", "exclude", "unpin", "include") and not HOSTNAME.fullmatch(domain):
|
||||||
usage(f"zapret auto {verb} <domain>")
|
usage(f"zapret auto {verb} <domain>")
|
||||||
if verb == "list":
|
if verb == "list":
|
||||||
if os.path.isfile(auto) and os.path.getsize(auto) > 0:
|
if os.path.isfile(auto) and os.path.getsize(auto) > 0:
|
||||||
@@ -1661,6 +1666,12 @@ def cmd_zapret_auto(verb="list", domain="", *_):
|
|||||||
_zapret_strategy_drop(domain)
|
_zapret_strategy_drop(domain)
|
||||||
_zapret_auto_edit(exclude, domain, "add")
|
_zapret_auto_edit(exclude, domain, "add")
|
||||||
print(f"Excluded {domain}. It is no longer touched or learned.")
|
print(f"Excluded {domain}. It is no longer touched or learned.")
|
||||||
|
elif verb == "unpin":
|
||||||
|
_zapret_auto_edit(user, domain, "drop")
|
||||||
|
print(f"Unpinned {domain}. It is bypassed again only if learned.")
|
||||||
|
elif verb == "include":
|
||||||
|
_zapret_auto_edit(exclude, domain, "drop")
|
||||||
|
print(f"Included {domain}. It can be learned again.")
|
||||||
elif verb == "clear":
|
elif verb == "clear":
|
||||||
_truncate(auto)
|
_truncate(auto)
|
||||||
state = _zapret_auto_file("circular/state.tsv")
|
state = _zapret_auto_file("circular/state.tsv")
|
||||||
@@ -1668,7 +1679,7 @@ def cmd_zapret_auto(verb="list", domain="", *_):
|
|||||||
_truncate(state)
|
_truncate(state)
|
||||||
print("Cleared learned hosts and remembered strategies.")
|
print("Cleared learned hosts and remembered strategies.")
|
||||||
else:
|
else:
|
||||||
usage("zapret auto [list|add|forget|exclude|clear]")
|
usage("zapret auto [list|add|forget|exclude|unpin|include|clear]")
|
||||||
|
|
||||||
|
|
||||||
# --- zapret cutoff ------------------------------------------------------------
|
# --- zapret cutoff ------------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,745 @@
|
|||||||
|
"""proxy-tui: an interactive front end to proxy-ctl.
|
||||||
|
|
||||||
|
Reads come from proxy_ctl in-process. Every change runs proxy-ctl itself, so
|
||||||
|
validation, permission errors and systemd triggers stay in one place, and its
|
||||||
|
die() cannot take the TUI down.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shlex
|
||||||
|
import subprocess
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from rich.text import Text
|
||||||
|
from textual import work
|
||||||
|
from textual.app import App, ComposeResult
|
||||||
|
from textual.binding import Binding
|
||||||
|
from textual.containers import Vertical
|
||||||
|
from textual.markup import escape
|
||||||
|
from textual.coordinate import Coordinate
|
||||||
|
from textual.screen import ModalScreen, Screen
|
||||||
|
from textual.widgets import DataTable, Footer, Input, Label, OptionList, RichLog, Static, TabbedContent, TabPane
|
||||||
|
from textual.widgets.option_list import Option
|
||||||
|
|
||||||
|
import proxy_ctl as ctl
|
||||||
|
|
||||||
|
CTL = "proxy-ctl"
|
||||||
|
REFRESH_SECONDS = 3
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Action:
|
||||||
|
key: str
|
||||||
|
label: str
|
||||||
|
argv: Callable # (selected row or None, prompt text) -> proxy-ctl argv
|
||||||
|
when: Callable = None # row -> applies; None: a tab-wide action that needs no row
|
||||||
|
prompt: str = "" # ask for text first
|
||||||
|
confirm: bool = False
|
||||||
|
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Tab:
|
||||||
|
id: str
|
||||||
|
title: str
|
||||||
|
available: Callable # unit states -> bool
|
||||||
|
columns: list # (row field, heading)
|
||||||
|
rows: Callable # unit states -> [row dict with a unique "key"]
|
||||||
|
summary: Callable = None # () -> text above the table, read on entering the tab and after actions
|
||||||
|
actions: list = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def ROW(_):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# --- readers ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def unit_states(units):
|
||||||
|
"""unit -> ActiveState for the units that exist, in one systemctl call."""
|
||||||
|
if not units:
|
||||||
|
return {}
|
||||||
|
_, out = ctl._run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True)
|
||||||
|
states = {}
|
||||||
|
for unit, block in zip(units, out.strip().split("\n\n")):
|
||||||
|
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
|
||||||
|
if props.get("LoadState") not in (None, "not-found"):
|
||||||
|
states[unit] = props.get("ActiveState", "unknown")
|
||||||
|
return states
|
||||||
|
|
||||||
|
|
||||||
|
def all_units():
|
||||||
|
return [*ctl.ALL_SERVICES, *map(ctl._awg_service, ctl._awg_profiles())]
|
||||||
|
|
||||||
|
|
||||||
|
def _lines(name):
|
||||||
|
try:
|
||||||
|
return [line for line in ctl.lines(ctl.read_text(ctl._zapret_auto_file(name))) if line]
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
TOGGLES = {
|
||||||
|
"proxy-suite-socks": ["proxy"],
|
||||||
|
"proxy-suite-tun": ["proxy", "tun"],
|
||||||
|
"proxy-suite-tproxy": ["proxy", "tproxy"],
|
||||||
|
"proxy-suite-ssh-proxy": ["ssh"],
|
||||||
|
"zapret-discord-youtube": ["zapret"],
|
||||||
|
}
|
||||||
|
AWG_PREFIX = ctl._awg_service("")
|
||||||
|
ZAPRET_LISTS = (
|
||||||
|
("learned", "zapret-hosts-auto.txt"),
|
||||||
|
("pinned", "zapret-hosts-user.txt"),
|
||||||
|
("excluded", "zapret-hosts-user-exclude.txt"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def toggle_argv(row, _):
|
||||||
|
verb = "off" if row["state"] == "active" else "on"
|
||||||
|
if row["unit"].startswith(AWG_PREFIX):
|
||||||
|
return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)]
|
||||||
|
return [*TOGGLES[row["unit"]], verb]
|
||||||
|
|
||||||
|
|
||||||
|
def service_rows(states):
|
||||||
|
return [{"key": u, "unit": u, "state": s} for u, s in states.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def route_rows(_):
|
||||||
|
current = ctl._route_mode_current()
|
||||||
|
return [
|
||||||
|
{"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)}
|
||||||
|
for m in ("default", *ctl.ROUTE_MODES)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def outbound_rows(_):
|
||||||
|
inventory = ctl._outbound_inventory()
|
||||||
|
pinned = ctl._s(inventory.get("pinned") or "")
|
||||||
|
sources = inventory.get("sources") or {}
|
||||||
|
current = ctl._outbound_current()
|
||||||
|
reputation = ctl._reputation_by_tag()
|
||||||
|
runtime = set(ctl._runtime_tags("outbound"))
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"key": t,
|
||||||
|
"mark": "★" if t == pinned else "▸" if t == current else "",
|
||||||
|
"tag": t,
|
||||||
|
"reputation": reputation.get(t, "-"),
|
||||||
|
"source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"),
|
||||||
|
"runtime": t in runtime,
|
||||||
|
}
|
||||||
|
for t in ctl._outbound_tags()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def outbound_summary():
|
||||||
|
inventory = ctl._outbound_inventory()
|
||||||
|
if not inventory:
|
||||||
|
return "No outbounds yet - is proxy-suite-socks running?"
|
||||||
|
return (
|
||||||
|
f"Selection: {ctl._s(inventory.get('selection') or 'first')} "
|
||||||
|
f"Pinned: {ctl._s(inventory.get('pinned') or '(auto)')} "
|
||||||
|
f"Current: {ctl._outbound_current() or '-'}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def subscription_rows(_):
|
||||||
|
rows = []
|
||||||
|
for source, tags in (("declared", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
|
||||||
|
for t in tags:
|
||||||
|
cache = ctl._subscription_cache(t)
|
||||||
|
count = ctl._subscription_proxy_count_text(cache) if os.path.isfile(cache) else "-"
|
||||||
|
rows.append({"key": t, "tag": t, "proxies": count, "source": source})
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def autoproxy_rows(_):
|
||||||
|
state = ctl._autoproxy_state(ctl._autoproxy_dir())
|
||||||
|
domains = state.get("domains") or {}
|
||||||
|
rows = [
|
||||||
|
{"key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}"}
|
||||||
|
for d, v in sorted(domains.items())
|
||||||
|
]
|
||||||
|
backlog = sorted((state.get("backlog") or {}).items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0))
|
||||||
|
rows += [
|
||||||
|
{"key": h, "domain": h, "kind": "queued", "detail": f"{ctl._s((v or {}).get('hits'))} hits"}
|
||||||
|
for h, v in backlog
|
||||||
|
if h not in domains
|
||||||
|
]
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def zapret_rows(_):
|
||||||
|
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||||
|
return []
|
||||||
|
rows = {}
|
||||||
|
for kind, name in ZAPRET_LISTS:
|
||||||
|
for host in _lines(name):
|
||||||
|
rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind})
|
||||||
|
return list(rows.values())
|
||||||
|
|
||||||
|
|
||||||
|
def zapret_summary():
|
||||||
|
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||||
|
return 'Learned hostlists need zapret.engine = "zapret2".'
|
||||||
|
text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS)
|
||||||
|
if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1":
|
||||||
|
text += "\n" + " ".join(line.strip() for line in _capture(["zapret", "cutoff", "status"]).splitlines()[:2])
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def inbound_rows(_):
|
||||||
|
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(_):
|
||||||
|
return [
|
||||||
|
{"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))}
|
||||||
|
for p in ctl._per_app_profiles()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def status_text(states):
|
||||||
|
parts = []
|
||||||
|
if "proxy-suite-socks" in states:
|
||||||
|
default = " (default)" if ctl._route_mode_current() == "default" else ""
|
||||||
|
parts.append(("mode ", ctl._route_mode_effective() + default))
|
||||||
|
parts.append(("outbound ", ctl._status_outbound() or "-"))
|
||||||
|
for name, value in (("autoProxy ", ctl._status_autoproxy()), ("zapret2 ", ctl._status_zapret())):
|
||||||
|
if value:
|
||||||
|
parts.append((name, value))
|
||||||
|
return "[b $accent]proxy-suite[/]" + "".join(f" [$text-muted]{label}[/][b]{escape(value)}[/]" for label, value in parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _link(row, *extra):
|
||||||
|
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra]
|
||||||
|
|
||||||
|
|
||||||
|
def _kind(*kinds):
|
||||||
|
return lambda row: row["kind"] in kinds
|
||||||
|
|
||||||
|
|
||||||
|
def _socks(states):
|
||||||
|
return "proxy-suite-socks" in states
|
||||||
|
|
||||||
|
|
||||||
|
def _enabled(name):
|
||||||
|
return lambda _: ctl.env(name) == "1"
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_toggle(row, _):
|
||||||
|
active = unit_states(["zapret-discord-youtube"]).get("zapret-discord-youtube") == "active"
|
||||||
|
return ["zapret", "off" if active else "on"]
|
||||||
|
|
||||||
|
|
||||||
|
TABS = [
|
||||||
|
Tab(
|
||||||
|
"services",
|
||||||
|
"Services",
|
||||||
|
lambda _: True,
|
||||||
|
[("unit", "Unit"), ("state", "State")],
|
||||||
|
service_rows,
|
||||||
|
actions=[
|
||||||
|
Action("space", "start / stop", toggle_argv, when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX)),
|
||||||
|
Action("l", "follow its logs", lambda r, _: ["logs", r["unit"]], when=ROW, mode="suspend"),
|
||||||
|
Action("R", "restart everything running", lambda r, _: ["restart"], confirm=True),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"routing",
|
||||||
|
"Routing",
|
||||||
|
_socks,
|
||||||
|
[("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"])],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"outbounds",
|
||||||
|
"Outbounds",
|
||||||
|
_socks,
|
||||||
|
[("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source")],
|
||||||
|
outbound_rows,
|
||||||
|
summary=outbound_summary,
|
||||||
|
actions=[
|
||||||
|
Action("p", "pin it", lambda r, _: ["proxy", "select", r["tag"]], when=lambda r: r["mark"] != "★"),
|
||||||
|
Action("a", "unpin: select automatically", lambda r, _: ["proxy", "select", "auto"]),
|
||||||
|
Action("t", "test it", lambda r, _: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
|
||||||
|
Action("T", "test all", lambda r, _: ["proxy", "outbounds", "test"], mode="dialog"),
|
||||||
|
Action("n", "add a runtime outbound…", lambda r, t: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||||
|
Action("d", "remove it", lambda r, _: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"subs",
|
||||||
|
"Subs",
|
||||||
|
_socks,
|
||||||
|
[("tag", "Tag"), ("proxies", "Proxies"), ("source", "Source")],
|
||||||
|
subscription_rows,
|
||||||
|
actions=[
|
||||||
|
Action("u", "refetch all", lambda r, _: ["proxy", "subs", "update"], mode="dialog"),
|
||||||
|
Action("n", "add a runtime subscription…", lambda r, t: ["proxy", "subs", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||||
|
Action("d", "remove it", lambda r, _: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"autoproxy",
|
||||||
|
"autoProxy",
|
||||||
|
_enabled("AUTOPROXY_ENABLED"),
|
||||||
|
[("domain", "Domain"), ("kind", "State"), ("detail", "")],
|
||||||
|
autoproxy_rows,
|
||||||
|
summary=ctl._status_autoproxy,
|
||||||
|
actions=[
|
||||||
|
Action("w", "how is it routed", lambda r, _: ["where", r["domain"]], when=ROW, mode="dialog"),
|
||||||
|
Action("e", "learn it now", lambda r, _: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"),
|
||||||
|
Action("p", "probe it through every exit", lambda r, _: ["proxy", "auto", "probe", r["domain"], "--keep-going"], when=ROW, mode="dialog"),
|
||||||
|
Action("P", "probe a domain…", lambda r, t: ["proxy", "auto", "probe", t], prompt="<domain>[/path]", mode="dialog"),
|
||||||
|
Action("E", "learn a domain…", lambda r, t: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
|
||||||
|
Action("i", "routed, judged and bad exits", lambda r, _: ["proxy", "auto", "list"], mode="dialog"),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"zapret",
|
||||||
|
"zapret",
|
||||||
|
lambda s: "zapret-discord-youtube" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
|
||||||
|
[("host", "Host"), ("kind", "List")],
|
||||||
|
zapret_rows,
|
||||||
|
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("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="<domain>"),
|
||||||
|
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("z", "start / stop zapret", _zapret_toggle),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"inbounds",
|
||||||
|
"Inbounds",
|
||||||
|
_enabled("INBOUNDS_ENABLED"),
|
||||||
|
[("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=[
|
||||||
|
Action("l", "share link", lambda r, _: _link(r), when=ROW, mode="dialog"),
|
||||||
|
Action("Q", "share link as QR", lambda r, _: _link(r, "--qr"), when=ROW, mode="dialog"),
|
||||||
|
Action("s", "subscription URL", lambda r, _: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"),
|
||||||
|
Action("S", "subscription URL as QR", lambda r, _: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"),
|
||||||
|
Action("t", "traffic per user", lambda r, _: ["inbounds", "stats"], mode="dialog"),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
"apps",
|
||||||
|
"Apps",
|
||||||
|
_enabled("PER_APP_ROUTING_ENABLED"),
|
||||||
|
[("profile", "Profile"), ("route", "Route")],
|
||||||
|
app_rows,
|
||||||
|
actions=[
|
||||||
|
Action("x", "run a command through it…", lambda r, t: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="suspend"),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
GLOBAL_KEYS = [
|
||||||
|
("enter", "actions for the selected row"),
|
||||||
|
("← → ⇥", "switch tab; 1-8 jump to one"),
|
||||||
|
("w", "how is a domain routed"),
|
||||||
|
("L", "follow all logs"),
|
||||||
|
("o", "output of the last command"),
|
||||||
|
("r", "refresh now"),
|
||||||
|
("?", "keys"),
|
||||||
|
("q", "quit"),
|
||||||
|
]
|
||||||
|
|
||||||
|
STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "red", "activating": "yellow", "deactivating": "yellow"}
|
||||||
|
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐"}
|
||||||
|
CELL_STYLES = {
|
||||||
|
"ok": "green",
|
||||||
|
"bad": "red",
|
||||||
|
"★": "bold yellow",
|
||||||
|
"▸": "bold cyan",
|
||||||
|
"●": "bold green",
|
||||||
|
"runtime": "cyan",
|
||||||
|
"learned": "yellow",
|
||||||
|
"pinned": "cyan",
|
||||||
|
"excluded": "magenta",
|
||||||
|
"routed": "green",
|
||||||
|
"queued": "yellow",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cell(name, value):
|
||||||
|
value = "" if value is None else str(value)
|
||||||
|
if name == "state":
|
||||||
|
return Text(f"{STATE_ICONS.get(value, '?')} {value}", style=STATE_STYLES.get(value, ""))
|
||||||
|
return Text(value, style=CELL_STYLES.get(value, ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _capture(argv):
|
||||||
|
try:
|
||||||
|
p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
||||||
|
except OSError as e:
|
||||||
|
return f"cannot run proxy-ctl: {e}"
|
||||||
|
return p.stdout + p.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def _safe(fn, *args, fallback=None):
|
||||||
|
try:
|
||||||
|
return fn(*args)
|
||||||
|
except (Exception, SystemExit):
|
||||||
|
return fallback # Unreadable state: the tab stays empty, and an action on it says why.
|
||||||
|
|
||||||
|
|
||||||
|
def _read_states():
|
||||||
|
return _safe(unit_states, _safe(all_units, fallback=list(ctl.ALL_SERVICES)), fallback={})
|
||||||
|
|
||||||
|
|
||||||
|
# --- dialogs ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class Prompt(ModalScreen):
|
||||||
|
BINDINGS = [Binding("escape", "dismiss", "cancel")]
|
||||||
|
|
||||||
|
def __init__(self, title, placeholder):
|
||||||
|
super().__init__()
|
||||||
|
self.heading, self.placeholder = title, placeholder
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
with Vertical(classes="dialog"):
|
||||||
|
yield Label(self.heading, classes="dialog-title")
|
||||||
|
yield Input(placeholder=self.placeholder)
|
||||||
|
yield Label("enter run · esc cancel", classes="dialog-hint")
|
||||||
|
|
||||||
|
def on_input_submitted(self, event):
|
||||||
|
self.dismiss(event.value.strip())
|
||||||
|
|
||||||
|
|
||||||
|
class Confirm(ModalScreen):
|
||||||
|
BINDINGS = [Binding("y,enter", "dismiss(True)", "yes"), Binding("n,escape", "dismiss(False)", "no")]
|
||||||
|
|
||||||
|
def __init__(self, command):
|
||||||
|
super().__init__()
|
||||||
|
self.command = command
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
with Vertical(classes="dialog"):
|
||||||
|
yield Label("Run this?", classes="dialog-title")
|
||||||
|
yield Label(self.command)
|
||||||
|
yield Label("y/enter run · n/esc cancel", classes="dialog-hint")
|
||||||
|
|
||||||
|
|
||||||
|
class Menu(ModalScreen):
|
||||||
|
"""The selected row's actions, picked with the arrows."""
|
||||||
|
|
||||||
|
BINDINGS = [Binding("escape,q", "dismiss", "close")]
|
||||||
|
|
||||||
|
def __init__(self, title, actions):
|
||||||
|
super().__init__()
|
||||||
|
self.heading, self.actions = title, actions
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
with Vertical(classes="dialog menu"):
|
||||||
|
yield Label(self.heading, classes="dialog-title")
|
||||||
|
yield OptionList(
|
||||||
|
*(Option(Text.assemble((f"{a.key:<7}", "bold cyan"), a.label), id=str(i)) for i, a in enumerate(self.actions))
|
||||||
|
)
|
||||||
|
yield Label("↑↓ choose · enter run · esc close", classes="dialog-hint")
|
||||||
|
|
||||||
|
def on_option_list_option_selected(self, event):
|
||||||
|
self.dismiss(self.actions[int(event.option.id)])
|
||||||
|
|
||||||
|
|
||||||
|
class Output(ModalScreen):
|
||||||
|
BINDINGS = [Binding("escape,q", "dismiss", "close")]
|
||||||
|
|
||||||
|
def __init__(self, title, text=None):
|
||||||
|
super().__init__()
|
||||||
|
self.heading, self.initial = title, text
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
with Vertical(classes="dialog output"):
|
||||||
|
yield Label(self.heading, classes="dialog-title")
|
||||||
|
# Follow a streaming command; show finished text from its top.
|
||||||
|
log = RichLog(wrap=False, markup=False, auto_scroll=self.initial is None)
|
||||||
|
if self.initial is not None:
|
||||||
|
log.write(self.initial if isinstance(self.initial, Text) else Text.from_ansi(self.initial))
|
||||||
|
yield log
|
||||||
|
yield Label("↑↓ scroll · esc close", classes="dialog-hint")
|
||||||
|
|
||||||
|
def write(self, line):
|
||||||
|
if self.is_attached:
|
||||||
|
self.query_one(RichLog).write(Text.from_ansi(line))
|
||||||
|
|
||||||
|
|
||||||
|
# --- main screen --------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _pane(tab):
|
||||||
|
"""A pane whose bindings are its tab's action keys, so the footer shows them."""
|
||||||
|
bindings = [Binding(a.key, f"app.act({i})", a.label.removesuffix("…"), show=False) for i, a in enumerate(tab.actions)]
|
||||||
|
return type(f"{tab.id.title()}Pane", (TabPane,), {"BINDINGS": bindings})
|
||||||
|
|
||||||
|
|
||||||
|
class MainScreen(Screen):
|
||||||
|
BINDINGS = [
|
||||||
|
Binding("left,shift+tab", "app.tab(-1)", "tabs", key_display="←→", priority=True),
|
||||||
|
Binding("right,tab", "app.tab(1)", "next tab", show=False, priority=True),
|
||||||
|
*(Binding(str(n), f"app.jump({n - 1})", show=False) for n in range(1, 9)),
|
||||||
|
Binding("enter", "app.menu", "actions", priority=True),
|
||||||
|
Binding("question_mark", "app.help", "keys"),
|
||||||
|
Binding("w", "app.where", "where", show=False),
|
||||||
|
Binding("L", "app.logs", "all logs", show=False),
|
||||||
|
Binding("o", "app.last_output", "last output", show=False),
|
||||||
|
Binding("r", "app.reload(True)", "refresh", show=False),
|
||||||
|
Binding("q", "app.quit", "quit"),
|
||||||
|
]
|
||||||
|
|
||||||
|
def __init__(self, tabs):
|
||||||
|
super().__init__()
|
||||||
|
self.tabs = tabs
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
yield Static(id="status")
|
||||||
|
with TabbedContent(id="tabs"):
|
||||||
|
for tab in self.tabs.values():
|
||||||
|
with _pane(tab)(tab.title, id=tab.id):
|
||||||
|
yield Static(id=f"{tab.id}-summary", classes="summary")
|
||||||
|
table = DataTable(id=f"{tab.id}-table", cursor_type="row")
|
||||||
|
for name, heading in tab.columns:
|
||||||
|
table.add_column(heading, key=name)
|
||||||
|
yield table
|
||||||
|
yield Static("enter: actions for the selected row · ←/→: tabs · ?: keys", id="feedback")
|
||||||
|
yield Footer(show_command_palette=False)
|
||||||
|
|
||||||
|
def on_mount(self):
|
||||||
|
self.app.start()
|
||||||
|
|
||||||
|
|
||||||
|
class ProxyTui(App):
|
||||||
|
TITLE = "proxy-tui"
|
||||||
|
CSS = """
|
||||||
|
#status { height: 1; background: $panel; }
|
||||||
|
#tabs { height: 1fr; }
|
||||||
|
#tabs ContentSwitcher { height: 1fr; }
|
||||||
|
#tabs TabPane { height: 1fr; padding: 0; }
|
||||||
|
.summary { display: none; height: auto; padding: 0 1; color: $text-muted; }
|
||||||
|
#tabs DataTable { height: 1fr; }
|
||||||
|
#feedback { height: 1; padding: 0 1; background: $panel; }
|
||||||
|
ModalScreen { align: center middle; }
|
||||||
|
.dialog { width: 76; max-width: 95%; height: auto; max-height: 90%; border: round $accent; background: $surface; padding: 0 1; }
|
||||||
|
.dialog-title { text-style: bold; color: $accent; margin-bottom: 1; }
|
||||||
|
.dialog-hint { color: $text-muted; margin-top: 1; }
|
||||||
|
.dialog Input { width: 1fr; }
|
||||||
|
.menu OptionList { height: auto; max-height: 20; border: none; padding: 0; }
|
||||||
|
.output { width: 95%; height: 90%; }
|
||||||
|
.output RichLog { height: 1fr; }
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.states = _read_states()
|
||||||
|
self.tabs = {t.id: t for t in TABS if _safe(t.available, self.states, fallback=False)}
|
||||||
|
self.rows = {} # tab id -> {row key: row}
|
||||||
|
self.last_output = None # (title, text)
|
||||||
|
|
||||||
|
def get_default_screen(self):
|
||||||
|
return MainScreen(self.tabs)
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
"""Once the main screen is up: it owns every widget read here."""
|
||||||
|
self.focus_table()
|
||||||
|
self.action_reload(True)
|
||||||
|
self.set_interval(REFRESH_SECONDS, self.action_reload)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def main(self):
|
||||||
|
return self.screen_stack[0]
|
||||||
|
|
||||||
|
# --- navigation -----------------------------------------------------------
|
||||||
|
|
||||||
|
def active_tab(self):
|
||||||
|
return self.main.query_one("#tabs", TabbedContent).active
|
||||||
|
|
||||||
|
def table(self, tab_id=None):
|
||||||
|
return self.main.query_one(f"#{tab_id or self.active_tab()}-table", DataTable)
|
||||||
|
|
||||||
|
def focus_table(self):
|
||||||
|
self.table().focus()
|
||||||
|
|
||||||
|
def action_tab(self, step):
|
||||||
|
ids = list(self.tabs)
|
||||||
|
self.action_jump((ids.index(self.active_tab()) + step) % len(ids))
|
||||||
|
|
||||||
|
def action_jump(self, index):
|
||||||
|
if 0 <= index < len(self.tabs):
|
||||||
|
self.main.query_one("#tabs", TabbedContent).active = list(self.tabs)[index]
|
||||||
|
|
||||||
|
def on_tabbed_content_tab_activated(self, _):
|
||||||
|
self.focus_table()
|
||||||
|
self.action_reload(True)
|
||||||
|
|
||||||
|
# --- reading --------------------------------------------------------------
|
||||||
|
|
||||||
|
def action_reload(self, full=False):
|
||||||
|
self.load(self.active_tab(), full)
|
||||||
|
|
||||||
|
@work(thread=True, exclusive=True, group="load")
|
||||||
|
def load(self, tab_id, full):
|
||||||
|
tab = self.tabs[tab_id]
|
||||||
|
states = _read_states()
|
||||||
|
status = _safe(status_text, states, fallback="status unavailable")
|
||||||
|
rows = _safe(tab.rows, states, fallback=[])
|
||||||
|
summary = (_safe(tab.summary, fallback="") or "") if full and tab.summary else None
|
||||||
|
self.call_from_thread(self.fill, tab_id, states, status, rows, summary)
|
||||||
|
|
||||||
|
def fill(self, tab_id, states, status, rows, summary):
|
||||||
|
self.states = states
|
||||||
|
self.main.query_one("#status", Static).update(status)
|
||||||
|
if summary is not None:
|
||||||
|
widget = self.main.query_one(f"#{tab_id}-summary", Static)
|
||||||
|
widget.update(summary)
|
||||||
|
widget.display = bool(summary)
|
||||||
|
self.rows[tab_id] = {r["key"]: r for r in rows}
|
||||||
|
tab, table = self.tabs[tab_id], self.table(tab_id)
|
||||||
|
keys = [r["key"] for r in rows]
|
||||||
|
if keys == [k.value for k in table.rows]:
|
||||||
|
# The same rows: change only the cells that changed, so cursor and scroll stay put.
|
||||||
|
for r in rows:
|
||||||
|
for name, _ in tab.columns:
|
||||||
|
value = cell(name, r.get(name))
|
||||||
|
if table.get_cell(r["key"], name) != value:
|
||||||
|
table.update_cell(r["key"], name, value)
|
||||||
|
return
|
||||||
|
selected = self.selected_key(tab_id)
|
||||||
|
table.clear()
|
||||||
|
for r in rows:
|
||||||
|
table.add_row(*(cell(name, r.get(name)) for name, _ in tab.columns), key=r["key"])
|
||||||
|
if selected in keys:
|
||||||
|
table.move_cursor(row=keys.index(selected), animate=False)
|
||||||
|
|
||||||
|
def selected_key(self, tab_id):
|
||||||
|
table = self.table(tab_id)
|
||||||
|
if not table.row_count:
|
||||||
|
return None
|
||||||
|
return table.coordinate_to_cell_key(Coordinate(table.cursor_row, 0)).row_key.value
|
||||||
|
|
||||||
|
def selected_row(self):
|
||||||
|
tab_id = self.active_tab()
|
||||||
|
return (self.rows.get(tab_id) or {}).get(self.selected_key(tab_id))
|
||||||
|
|
||||||
|
# --- acting ---------------------------------------------------------------
|
||||||
|
|
||||||
|
def applicable(self, row):
|
||||||
|
return [a for a in self.tabs[self.active_tab()].actions if a.when is None or (row is not None and a.when(row))]
|
||||||
|
|
||||||
|
def action_menu(self):
|
||||||
|
row = self.selected_row()
|
||||||
|
title = row["key"] if row else self.tabs[self.active_tab()].title
|
||||||
|
actions = self.applicable(row)
|
||||||
|
if not actions:
|
||||||
|
self.feedback(f"No actions for {title}.")
|
||||||
|
return
|
||||||
|
self.push_screen(Menu(title, actions), lambda a: a and self.perform(a, row))
|
||||||
|
|
||||||
|
def action_act(self, index):
|
||||||
|
action = self.tabs[self.active_tab()].actions[index]
|
||||||
|
row = self.selected_row()
|
||||||
|
if action.when is not None and (row is None or not action.when(row)):
|
||||||
|
target = row["key"] if row else "an empty list"
|
||||||
|
self.feedback(f"'{action.label.removesuffix('…')}' does not apply to {target}", ok=False)
|
||||||
|
return
|
||||||
|
self.perform(action, row)
|
||||||
|
|
||||||
|
def action_where(self):
|
||||||
|
self.perform(Action("w", "How is a domain routed", lambda r, t: ["where", t], prompt="<domain>", mode="dialog"), None)
|
||||||
|
|
||||||
|
def action_logs(self):
|
||||||
|
self.run_argv("suspend", ["logs"])
|
||||||
|
|
||||||
|
def action_last_output(self):
|
||||||
|
if self.last_output:
|
||||||
|
self.push_screen(Output(*self.last_output))
|
||||||
|
else:
|
||||||
|
self.feedback("Nothing has run yet.")
|
||||||
|
|
||||||
|
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)):
|
||||||
|
text.append(f"{heading}\n", style="bold")
|
||||||
|
for key, label in keys:
|
||||||
|
text.append(f" {key:<9}", style="bold cyan")
|
||||||
|
text.append(f"{label}\n")
|
||||||
|
text.append("\n")
|
||||||
|
self.push_screen(Output("Keys", text))
|
||||||
|
|
||||||
|
def perform(self, action, row):
|
||||||
|
def with_text(text=""):
|
||||||
|
argv = action.argv(row, text)
|
||||||
|
if action.confirm:
|
||||||
|
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv))
|
||||||
|
else:
|
||||||
|
self.run_argv(action.mode, argv)
|
||||||
|
|
||||||
|
if action.prompt:
|
||||||
|
title = action.label.removesuffix("…")
|
||||||
|
self.push_screen(Prompt(title[:1].upper() + title[1:], action.prompt), lambda text: text and with_text(text))
|
||||||
|
else:
|
||||||
|
with_text()
|
||||||
|
|
||||||
|
def run_argv(self, mode, argv):
|
||||||
|
command = f"proxy-ctl {shlex.join(argv)}"
|
||||||
|
if mode == "suspend":
|
||||||
|
with self.suspend():
|
||||||
|
ctl._run_foreground([CTL, *argv])
|
||||||
|
self.action_reload(True)
|
||||||
|
return
|
||||||
|
dialog = Output(command) if mode == "dialog" else None
|
||||||
|
if dialog:
|
||||||
|
self.push_screen(dialog)
|
||||||
|
self.feedback(f"… {command}")
|
||||||
|
self.stream(command, argv, dialog)
|
||||||
|
|
||||||
|
@work(thread=True)
|
||||||
|
def stream(self, command, argv, dialog):
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
p = subprocess.Popen(
|
||||||
|
[CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True
|
||||||
|
)
|
||||||
|
for line in p.stdout:
|
||||||
|
out.append(line.rstrip("\n"))
|
||||||
|
if dialog:
|
||||||
|
self.call_from_thread(dialog.write, out[-1])
|
||||||
|
status = p.wait()
|
||||||
|
except OSError as e:
|
||||||
|
out.append(f"cannot run proxy-ctl: {e}")
|
||||||
|
status = 127
|
||||||
|
last = Text.from_ansi(next((line for line in reversed(out) if line.strip()), "")).plain.strip()
|
||||||
|
message = f"{last} ({command})" if last else command
|
||||||
|
if status:
|
||||||
|
message = f"exit {status}: {message}"
|
||||||
|
if dialog:
|
||||||
|
self.call_from_thread(dialog.write, f"\x1b[31m(exit status {status})\x1b[0m")
|
||||||
|
if len(out) > 1 and not dialog:
|
||||||
|
message += " · o: full output"
|
||||||
|
self.last_output = (command, "\n".join(out))
|
||||||
|
self.call_from_thread(self.feedback, message, status == 0)
|
||||||
|
self.call_from_thread(self.action_reload, True)
|
||||||
|
|
||||||
|
def feedback(self, message, ok=None):
|
||||||
|
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok]
|
||||||
|
self.main.query_one("#feedback", Static).update(Text(icon + message, style=style, no_wrap=True, overflow="ellipsis"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
ProxyTui().run()
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
import proxy_ctl as ctl
|
||||||
|
import proxy_tui as tui
|
||||||
|
|
||||||
|
|
||||||
|
class TuiTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.units = {"proxy-suite-socks": "active", "proxy-suite-tun": "inactive"}
|
||||||
|
self.zapret = {
|
||||||
|
"zapret-hosts-auto.txt": ["learned.example"],
|
||||||
|
"zapret-hosts-user.txt": [],
|
||||||
|
"zapret-hosts-user-exclude.txt": ["kept.example"],
|
||||||
|
}
|
||||||
|
env = {"ZAPRET_AUTO_ENABLED": "1"}
|
||||||
|
for target, name, value in [
|
||||||
|
(tui, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}),
|
||||||
|
(tui, "_capture", lambda argv: ""),
|
||||||
|
(tui, "_lines", lambda name: self.zapret[name]),
|
||||||
|
(ctl, "env", lambda name, default="": env.get(name, default)),
|
||||||
|
(ctl, "_awg_profiles", lambda: []),
|
||||||
|
(ctl, "_route_mode_current", lambda: "default"),
|
||||||
|
(ctl, "_route_mode_effective", lambda: "whitelist"),
|
||||||
|
(ctl, "_outbound_inventory", lambda: {"tags": ["a", "b"], "pinned": "b", "sources": {"a": "config"}}),
|
||||||
|
(ctl, "_outbound_current", lambda: ""),
|
||||||
|
(ctl, "_reputation_by_tag", lambda: {}),
|
||||||
|
(ctl, "_runtime_tags", lambda kind: []),
|
||||||
|
(ctl, "_sub_tags", lambda: []),
|
||||||
|
(ctl, "_status_outbound", lambda: "b (pinned)"),
|
||||||
|
(ctl, "_status_autoproxy", lambda: ""),
|
||||||
|
(ctl, "_status_zapret", lambda: ""),
|
||||||
|
]:
|
||||||
|
patcher = mock.patch.object(target, name, value)
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
self.ran = []
|
||||||
|
patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv: self.ran.append(argv))
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
|
||||||
|
def test_ui(self):
|
||||||
|
# Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl.
|
||||||
|
asyncio.run(self.ui())
|
||||||
|
|
||||||
|
async def settle(self, app, pilot):
|
||||||
|
# Loads are exclusive: a newer one cancels the older, so wait until none runs.
|
||||||
|
await pilot.pause()
|
||||||
|
while any(not w.is_finished for w in app.workers if w.group == "load"):
|
||||||
|
await pilot.pause(0.01)
|
||||||
|
await pilot.pause()
|
||||||
|
|
||||||
|
def menu_labels(self, app):
|
||||||
|
return [a.label for a in app.screen.actions]
|
||||||
|
|
||||||
|
async def ui(self):
|
||||||
|
app = tui.ProxyTui()
|
||||||
|
async with app.run_test(size=(100, 30)) as pilot:
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
self.assertEqual(list(app.tabs), ["services", "routing", "outbounds", "subs", "zapret"])
|
||||||
|
self.assertEqual(app.focused.id, "services-table")
|
||||||
|
|
||||||
|
# Services: space toggles the selected unit.
|
||||||
|
await pilot.press("down", "space")
|
||||||
|
self.assertEqual(self.ran.pop(), ["proxy", "tun", "on"])
|
||||||
|
|
||||||
|
# A state change updates the row in place; the cursor stays on tun.
|
||||||
|
self.units["proxy-suite-tun"] = "active"
|
||||||
|
app.action_reload()
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
self.assertEqual(app.selected_key("services"), "proxy-suite-tun")
|
||||||
|
self.assertEqual(str(app.table().get_cell("proxy-suite-tun", "state")), "● active")
|
||||||
|
|
||||||
|
# Right arrow moves to Routing and its table has focus.
|
||||||
|
await pilot.press("right")
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table"))
|
||||||
|
|
||||||
|
# Enter opens the row's actions; arrows and enter pick one.
|
||||||
|
await pilot.press("down", "enter")
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertIsInstance(app.screen, tui.Menu)
|
||||||
|
self.assertEqual(self.menu_labels(app), ["switch to this mode"])
|
||||||
|
await pilot.press("enter")
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran.pop(), ["proxy", "mode", "whitelist"])
|
||||||
|
|
||||||
|
# Outbounds: letter shortcuts; the pinned row offers no pin, and nothing removes a declared one.
|
||||||
|
await pilot.press("right")
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
await pilot.press("p", "t", "a")
|
||||||
|
self.assertEqual(self.ran, [["proxy", "select", "a"], ["proxy", "outbounds", "test", "a"], ["proxy", "select", "auto"]])
|
||||||
|
self.ran.clear()
|
||||||
|
await pilot.press("down", "p", "d")
|
||||||
|
self.assertEqual(self.ran, [])
|
||||||
|
await pilot.press("enter")
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertNotIn("pin it", self.menu_labels(app))
|
||||||
|
self.assertNotIn("remove it", self.menu_labels(app))
|
||||||
|
await pilot.press("escape")
|
||||||
|
|
||||||
|
# Prompts: add takes "<tag> <url>".
|
||||||
|
await pilot.press("n", *"x vless://h", "enter")
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "x", "vless://h"])
|
||||||
|
|
||||||
|
# zapret: an excluded host can be included again, not forgotten.
|
||||||
|
await pilot.press("5")
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
await pilot.press("down", "enter")
|
||||||
|
await pilot.pause()
|
||||||
|
labels = self.menu_labels(app)
|
||||||
|
self.assertIn("include it (may be learned 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"])
|
||||||
|
|
||||||
|
# Confirmed actions run only on yes.
|
||||||
|
await pilot.press("C", "n")
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran, [])
|
||||||
|
await pilot.press("C", "y")
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran.pop(), ["zapret", "auto", "clear"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user