fix: zapret2 & naming fixes

This commit is contained in:
fufsob committed 2026-09-14 13:15:06 +00:00
1 parent eab3adf893
commit e2da83ba56
32 files changed
+580 -261

No files matched your search

+4 -1
View File
@@ -116,7 +116,8 @@ A group without a verb shows its status or list.
proxy outbounds rm <tag> remove a runtime outbound proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download] proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay) TCP ping, real delay, download speed (default: ping, delay)
proxy select [<tag>|auto] pin the priority outbound (no tag: pick from a menu) 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] proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
show or override the routing mode show or override the routing mode
proxy subs [list|update] subscription caches; update refetches them proxy subs [list|update] subscription caches; update refetches them
@@ -143,6 +144,8 @@ A group without a verb shows its status or list.
awg on <profile> | off [profile] | restart [profile] awg on <profile> | off [profile] | restart [profile]
ssh [status|on|off] SSH SOCKS5 tunnel ssh [status|on|off] SSH SOCKS5 tunnel
warp [status|on|off] WARP tunnel behind the warp outbound
tg [status|on|off] Telegram WebSocket proxy
apps [list] per-app routing profiles apps [list] per-app routing profiles
apps run <profile> -- <cmd> [args] run a command through a profile apps run <profile> -- <cmd> [args] run a command through a profile
+1 -1
View File
@@ -1220,7 +1220,7 @@ How to pick among outbounds:
- “selector”: all of them, pick by hand\. - “selector”: all of them, pick by hand\.
- “urltest”: all of them, ranked by latency unless one is pinned\. - “urltest”: all of them, ranked by latency unless one is pinned\.
` proxy-ctl proxy select ` pins an outbound in every mode, and the pin outlives a restart\. ` proxy-ctl proxy pin ` pins an outbound in every mode, and the pin outlives a restart\.
“selector” and “urltest” switch without restarting the backend (sing-box only); “first” “selector” and “urltest” switch without restarting the backend (sing-box only); “first”
and XRay restart it\. and XRay restart it\.
+2 -2
View File
@@ -186,7 +186,7 @@ let
# do not race it. # do not race it.
after = [ after = [
"network-online.target" "network-online.target"
"zapret-discord-youtube.service" "proxy-suite-zapret.service"
] ]
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
@@ -194,7 +194,7 @@ let
conflicts = allProfileConflicts name ++ [ conflicts = allProfileConflicts name ++ [
"proxy-suite-tun.service" "proxy-suite-tun.service"
"proxy-suite-tproxy.service" "proxy-suite-tproxy.service"
"zapret-discord-youtube.service" "proxy-suite-zapret.service"
"proxy-suite-per-app-zapret.service" "proxy-suite-per-app-zapret.service"
"proxy-suite-zapret-vm-exempt.service" "proxy-suite-zapret-vm-exempt.service"
]; ];
+3 -3
View File
@@ -28,9 +28,9 @@ let
lib.types.submodule ( lib.types.submodule (
{ name, ... }: { name, ... }:
{ {
config.serviceConfig.SyslogIdentifier = lib.mkIf ( config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) (
lib.hasPrefix "proxy-suite-" name || name == "zapret-discord-youtube" lib.mkDefault (lib.removeSuffix "@" name)
) (lib.mkDefault (lib.removeSuffix "@" name)); );
} }
) )
); );
+1 -1
View File
@@ -166,7 +166,7 @@ let
# Runtime outbound control. The spool dirs hold one proxy URL per file and are # Runtime outbound control. The spool dirs hold one proxy URL per file and are
# group-writable when userControl is on, so proxy-ctl edits them without sudo; # group-writable when userControl is on, so proxy-ctl edits them without sudo;
# the pin outlives a reboot, unlike the per-boot route-mode override. # the pin outlives a reboot, unlike the per-boot route-mode override.
priorityOutboundFile = "/var/lib/proxy-suite/priority-outbound"; pinnedOutboundFile = "/var/lib/proxy-suite/pinned-outbound";
runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d"; runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d";
runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d"; runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d";
# Written by every backend start script; proxy-ctl reads the socks copy. # Written by every backend start script; proxy-ctl reads the socks copy.
@@ -61,7 +61,7 @@ in
- "selector": all of them, pick by hand. - "selector": all of them, pick by hand.
- "urltest": all of them, ranked by latency unless one is pinned. - "urltest": all of them, ranked by latency unless one is pinned.
`proxy-ctl proxy select` pins an outbound in every mode, and the pin outlives a restart. `proxy-ctl proxy pin` pins an outbound in every mode, and the pin outlives a restart.
"selector" and "urltest" switch without restarting the backend (sing-box only); "first" "selector" and "urltest" switch without restarting the backend (sing-box only); "first"
and XRay restart it. and XRay restart it.
''; '';
@@ -5,7 +5,7 @@
proxyCfg, proxyCfg,
clashApi, clashApi,
routeModeStateFile, routeModeStateFile,
priorityOutboundFile, pinnedOutboundFile,
outboundInventoryFile, outboundInventoryFile,
subscriptionCacheDir, subscriptionCacheDir,
subscriptionCacheHelpersBlock, subscriptionCacheHelpersBlock,
@@ -77,20 +77,15 @@ let
${restartActiveConfigConsumersBlock} ${restartActiveConfigConsumersBlock}
''; '';
# Pins the outbound the proxy prefers, or "auto" to hand the choice back to the # Pins the outbound the proxy prefers; without a tag, unpins it and hands the choice
# configured selection. The pin is persisted either way; a live Clash API switch # back to the configured selection. The pin is persisted either way; a live Clash
# only saves the restart. # API switch only saves the restart.
setPriorityOutboundScript = pkgs.writeShellScript "proxy-suite-core" '' pinOutboundScript = pkgs.writeShellScript "proxy-suite-core" ''
set -euo pipefail set -euo pipefail
tag="''${1:-}" tag="''${1:-}"
if [ -z "$tag" ]; then if [ -z "$tag" ]; then
echo "proxy-suite: usage: proxy-suite-set-priority-outbound <tag|auto>" >&2 rm -f "${pinnedOutboundFile}"
exit 1
fi
if [ "$tag" = "auto" ]; then
rm -f "${priorityOutboundFile}"
else else
# The inventory only exists once the proxy has run. Without it there is # The inventory only exists once the proxy has run. Without it there is
# nothing to check against, so accept the tag and let the start script warn # nothing to check against, so accept the tag and let the start script warn
@@ -100,8 +95,8 @@ let
echo "proxy-suite: unknown outbound '$tag'" >&2 echo "proxy-suite: unknown outbound '$tag'" >&2
exit 1 exit 1
fi fi
mkdir -p "$(dirname "${priorityOutboundFile}")" mkdir -p "$(dirname "${pinnedOutboundFile}")"
printf '%s\n' "$tag" > "${priorityOutboundFile}" printf '%s\n' "$tag" > "${pinnedOutboundFile}"
# Live switch when the running config exposes a selector; the persisted pin # Live switch when the running config exposes a selector; the persisted pin
# is what keeps it after the next restart. # is what keeps it after the next restart.
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \ if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
@@ -146,7 +141,7 @@ in
inherit inherit
subscriptionUpdateScript subscriptionUpdateScript
setRouteModeScript setRouteModeScript
setPriorityOutboundScript pinOutboundScript
reloadOutboundsScript reloadOutboundsScript
; ;
} }
-1
View File
@@ -46,7 +46,6 @@
zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0"; zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0";
zapretStateDir = constants.zapret2StateDir; zapretStateDir = constants.zapret2StateDir;
zapretCutoffEnabled = if zapretCutoffEnabled then "1" else "0"; zapretCutoffEnabled = if zapretCutoffEnabled then "1" else "0";
priorityOutboundFile = constants.priorityOutboundFile;
outboundInventoryFile = constants.outboundInventoryFile; outboundInventoryFile = constants.outboundInventoryFile;
runtimeOutboundsDir = constants.runtimeOutboundsDir; runtimeOutboundsDir = constants.runtimeOutboundsDir;
runtimeSubscriptionsDir = constants.runtimeSubscriptionsDir; runtimeSubscriptionsDir = constants.runtimeSubscriptionsDir;
+2 -3
View File
@@ -15,9 +15,8 @@ let
} }
'' ''
+ lib.optionalString (builtins.elem "global" userControlCfg.allow) '' + lib.optionalString (builtins.elem "global" userControlCfg.allow) ''
if ((unit.indexOf("proxy-suite-") === 0 && if (unit.indexOf("proxy-suite-") === 0 &&
unit.indexOf("proxy-suite-per-app-") !== 0) || unit.indexOf("proxy-suite-per-app-") !== 0) {
unit === "zapret-discord-youtube.service") {
return polkit.Result.YES; return polkit.Result.YES;
} }
''; '';
@@ -12,7 +12,7 @@
backend, backend,
backendArg, backendArg,
xraySidecarRoutingMark, xraySidecarRoutingMark,
priorityOutboundFile, pinnedOutboundFile,
runtimeOutboundsDir, runtimeOutboundsDir,
jq, jq,
python3, python3,
@@ -373,14 +373,14 @@ let
# entry that went away, say - is dropped rather than left to break the config. # entry that went away, say - is dropped rather than left to break the config.
pinBlock = '' pinBlock = ''
OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON") OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON")
PRIORITY_OUTBOUND="" PINNED_OUTBOUND=""
if [ -r "${priorityOutboundFile}" ]; then if [ -r "${pinnedOutboundFile}" ]; then
PRIORITY_OUTBOUND="$(tr -d '\r\n[:space:]' < "${priorityOutboundFile}" 2>/dev/null || true)" PINNED_OUTBOUND="$(tr -d '\r\n[:space:]' < "${pinnedOutboundFile}" 2>/dev/null || true)"
fi fi
if [ -n "$PRIORITY_OUTBOUND" ] \ if [ -n "$PINNED_OUTBOUND" ] \
&& ! ${jq} -e --arg t "$PRIORITY_OUTBOUND" 'index($t) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then && ! ${jq} -e --arg t "$PINNED_OUTBOUND" 'index($t) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then
echo "proxy-suite: warning: pinned outbound '$PRIORITY_OUTBOUND' is not available; picking automatically" >&2 echo "proxy-suite: warning: pinned outbound '$PINNED_OUTBOUND' is not available; picking automatically" >&2
PRIORITY_OUTBOUND="" PINNED_OUTBOUND=""
fi fi
''; '';
@@ -389,7 +389,7 @@ let
${jq} -n \ ${jq} -n \
--argjson tags "$OUTBOUND_TAGS_JSON" \ --argjson tags "$OUTBOUND_TAGS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \ --argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg pinned "$PRIORITY_OUTBOUND" \ --arg pinned "$PINNED_OUTBOUND" \
--arg selection ${lib.escapeShellArg selectionMode} \ --arg selection ${lib.escapeShellArg selectionMode} \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \ '{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \
> "$RUNTIME_DIR/outbounds.json" > "$RUNTIME_DIR/outbounds.json"
@@ -416,15 +416,15 @@ let
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
# XRay has no selector: a pin degrades the balancer to the one outbound, # XRay has no selector: a pin degrades the balancer to the one outbound,
# which is the same path a single-outbound config already takes. # which is the same path a single-outbound config already takes.
if [ -n "$PRIORITY_OUTBOUND" ]; then if [ -n "$PINNED_OUTBOUND" ]; then
XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PRIORITY_OUTBOUND" XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PINNED_OUTBOUND"
elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")" XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi fi
'' ''
else if collapseNamedOutbounds then else if collapseNamedOutbounds then
'' ''
PROXY_TAG="$PRIORITY_OUTBOUND" PROXY_TAG="$PINNED_OUTBOUND"
if [ -z "$PROXY_TAG" ]; then if [ -z "$PROXY_TAG" ]; then
PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi fi
@@ -434,7 +434,7 @@ let
else if selectionMode == "selector" then else if selectionMode == "selector" then
'' ''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
DEFAULT_TAG="$PRIORITY_OUTBOUND" DEFAULT_TAG="$PINNED_OUTBOUND"
if [ -z "$DEFAULT_TAG" ]; then if [ -z "$DEFAULT_TAG" ]; then
DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi fi
@@ -447,12 +447,12 @@ let
else else
'' ''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
if [ -n "$PRIORITY_OUTBOUND" ]; then if [ -n "$PINNED_OUTBOUND" ]; then
# A pin beats latency ranking: the same outbounds, behind a selector # A pin beats latency ranking: the same outbounds, behind a selector
# the Clash API can also switch live. # the Clash API can also switch live.
WRAPPER=$(${jq} -n \ WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \ --argjson tags "$TAGS" \
--arg default "$PRIORITY_OUTBOUND" \ --arg default "$PINNED_OUTBOUND" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
else else
WRAPPER=$(${jq} -n \ WRAPPER=$(${jq} -n \
+6 -6
View File
@@ -57,7 +57,7 @@ let
null; null;
routeModeStateFile = "/run/proxy-suite/route-mode"; routeModeStateFile = "/run/proxy-suite/route-mode";
inherit (constants) inherit (constants)
priorityOutboundFile pinnedOutboundFile
runtimeOutboundsDir runtimeOutboundsDir
runtimeSubscriptionsDir runtimeSubscriptionsDir
outboundInventoryFile outboundInventoryFile
@@ -118,7 +118,7 @@ let
backend backend
backendArg backendArg
xraySidecarRoutingMark xraySidecarRoutingMark
priorityOutboundFile pinnedOutboundFile
runtimeOutboundsDir runtimeOutboundsDir
jq jq
python3 python3
@@ -220,7 +220,7 @@ let
proxyCfg proxyCfg
clashApi clashApi
routeModeStateFile routeModeStateFile
priorityOutboundFile pinnedOutboundFile
outboundInventoryFile outboundInventoryFile
subscriptionCacheDir subscriptionCacheDir
subscriptionCacheHelpersBlock subscriptionCacheHelpersBlock
@@ -232,7 +232,7 @@ let
inherit (controlScripts) inherit (controlScripts)
subscriptionUpdateScript subscriptionUpdateScript
setRouteModeScript setRouteModeScript
setPriorityOutboundScript pinOutboundScript
reloadOutboundsScript reloadOutboundsScript
; ;
@@ -250,13 +250,13 @@ in
proxyInboundsSubscriptionsFile proxyInboundsSubscriptionsFile
routeModeStateFile routeModeStateFile
setRouteModeScript setRouteModeScript
setPriorityOutboundScript pinOutboundScript
reloadOutboundsScript reloadOutboundsScript
subscriptionUpdateScript subscriptionUpdateScript
subscriptionTagsFile subscriptionTagsFile
subscriptionCacheDir subscriptionCacheDir
runtimeProxychainsConfig runtimeProxychainsConfig
priorityOutboundFile pinnedOutboundFile
runtimeOutboundsDir runtimeOutboundsDir
runtimeSubscriptionsDir runtimeSubscriptionsDir
outboundInventoryFile outboundInventoryFile
+13 -3
View File
@@ -242,10 +242,20 @@ let
} }
{ {
enable = proxyEnabled; enable = proxyEnabled;
name = "proxy-suite-outbound-select@"; name = "proxy-suite-outbound-pin@";
value = mkOneshotService { value = mkOneshotService {
description = "Pin the proxy-suite priority outbound to %i"; description = "Pin the proxy-suite outbound to %i";
execStart = "${scripts.setPriorityOutboundScript} %i"; execStart = "${scripts.pinOutboundScript} %i";
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-unpin";
value = mkOneshotService {
description = "Unpin the proxy-suite outbound";
execStart = "${scripts.pinOutboundScript}";
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false; extraServiceConfig.RemainAfterExit = false;
}; };
+3 -3
View File
@@ -83,7 +83,7 @@ in
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
); );
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService { systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret DPI bypass"; description = "zapret DPI bypass";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
@@ -121,8 +121,8 @@ in
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable) lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable)
(mkOneshotService { (mkOneshotService {
description = "Exempt CIDRs from zapret NFQUEUE"; description = "Exempt CIDRs from zapret NFQUEUE";
after = [ "zapret-discord-youtube.service" ]; after = [ "proxy-suite-zapret.service" ];
wants = [ "zapret-discord-youtube.service" ]; wants = [ "proxy-suite-zapret.service" ];
conflicts = awgServiceNames; conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
execStart = pkgs.writeShellScript "proxy-suite-zapret" exemptStart; execStart = pkgs.writeShellScript "proxy-suite-zapret" exemptStart;
+1 -1
View File
@@ -104,7 +104,7 @@ in
systemd.services.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.service; systemd.services.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.service;
systemd.timers.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.timer; systemd.timers.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.timer;
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService { systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret2 DPI bypass"; description = "zapret2 DPI bypass";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
+1 -1
View File
@@ -20,7 +20,7 @@ let
table = "proxy_suite_cutoff_probe"; table = "proxy_suite_cutoff_probe";
# try-restart fails on a unit that is not installed, so only name the ones built. # try-restart fails on a unit that is not installed, so only name the ones built.
restartUnits = restartUnits =
lib.optional cfg.zapret.enable "zapret-discord-youtube.service" lib.optional cfg.zapret.enable "proxy-suite-zapret.service"
++ lib.optional cfg.perAppRouting.zapret.enable "proxy-suite-per-app-zapret.service"; ++ lib.optional cfg.perAppRouting.zapret.enable "proxy-suite-per-app-zapret.service";
z2kDetect = pkgs.buildGoModule { z2kDetect = pkgs.buildGoModule {
+17 -3
View File
@@ -93,14 +93,28 @@ let
else else
pkgs.writeText "proxy-suite-zapret2" (lib.concatStringsSep " " source.blobArgs); pkgs.writeText "proxy-suite-zapret2" (lib.concatStringsSep " " source.blobArgs);
# The state layer undoes a rotation when the host succeeded within 30 s, unless
# a failure came later; only z2k's own detector stamps that failure. Without the
# stamp any success on a busy host (all of googlevideo.com) undoes every rotation.
failStamp = pkgs.writeText "proxy-suite-zapret2-fail-stamp.lua" ''
local count = automate_failure_counter
function automate_failure_counter(hrec, crec, fails, maxtime)
if not (crec and crec.failure) then
hrec.z2k_last_fail_ts = type(clock_getfloattime) == "function" and clock_getfloattime() or os.time()
end
return count(hrec, crec, fails, maxtime)
end
'';
# The state layer wraps circular, so it loads after the source's Lua. z2k-tcp16 # The state layer wraps circular, so it loads after the source's Lua. z2k-tcp16
# does nothing until the cutoff probe has written its maps. # does nothing until the cutoff probe has written its maps.
optPrefix = lib.concatStringsSep " " ( optPrefix = lib.concatStringsSep " " (
map (file: "--lua-init=@${file}") ( map (file: "--lua-init=@${file}") (
source.luaInit source.luaInit
++ map (name: "${zapret2Sources.z2k}/files/lua/${name}.lua") [ ++ [
"z2k-tcp16" "${zapret2Sources.z2k}/files/lua/z2k-tcp16.lua"
"z2k-state-persist" failStamp
"${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua"
] ]
) )
++ lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs ++ lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs
+5 -1
View File
@@ -61,7 +61,11 @@ let
# Its init script's order. QUIC reads the learned list but never adds to it: # Its init script's order. QUIC reads the learned list but never adds to it:
# browsers retry over TCP. The UDP profile carries no SNI, so no lists. # browsers retry over TCP. The UDP profile carries no SNI, so no lists.
profiles = [ profiles = [
(args "NFQWS_ARGS_UDP") # Its first UDP strategy's fake has no blob, which zapret2 rejects on every
# packet; nfqws1's default for unknown UDP was 64 zero bytes.
(replaceStrings [ "--lua-desync=fake:repeats=6:strategy=1" ] [
"--lua-desync=fake:blob=0x${lib.fixedWidthString 128 "0" ""}:repeats=6:strategy=1"
] (args "NFQWS_ARGS_UDP"))
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}" "${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}"
"${withSniPick (args "NFQWS_ARGS")} <HOSTLIST> ${lists}" "${withSniPick (args "NFQWS_ARGS")} <HOSTLIST> ${lists}"
]; ];
+2 -2
View File
@@ -184,7 +184,7 @@ in
assert builtins.elem "proxy-suite-awg-work.service" homeService.conflicts; assert builtins.elem "proxy-suite-awg-work.service" homeService.conflicts;
assert builtins.elem "proxy-suite-tun.service" homeService.conflicts; assert builtins.elem "proxy-suite-tun.service" homeService.conflicts;
assert builtins.elem "proxy-suite-tproxy.service" homeService.conflicts; assert builtins.elem "proxy-suite-tproxy.service" homeService.conflicts;
assert builtins.elem "zapret-discord-youtube.service" homeService.conflicts; assert builtins.elem "proxy-suite-zapret.service" homeService.conflicts;
assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts; assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts;
assert workService.wantedBy == [ ]; assert workService.wantedBy == [ ];
assert homeService.serviceConfig.NoNewPrivileges; assert homeService.serviceConfig.NoNewPrivileges;
@@ -240,7 +240,7 @@ in
assert builtins.elem "proxy-suite-awg-home.service" assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.proxy-suite-tproxy.conflicts; withGlobalTun.config.systemd.services.proxy-suite-tproxy.conflicts;
assert builtins.elem "proxy-suite-awg-home.service" assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.zapret-discord-youtube.conflicts; withGlobalTun.config.systemd.services.proxy-suite-zapret.conflicts;
assert builtins.elem "proxy-suite-awg-home.service" assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts; withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts;
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after; assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after;
+1 -1
View File
@@ -125,7 +125,7 @@ let
); );
in in
pkgs.lib.removePrefix "ZAPRET_BASE=" zapretBaseEnv; pkgs.lib.removePrefix "ZAPRET_BASE=" zapretBaseEnv;
mkZapretBase = fixture: mkZapretBaseFor fixture "zapret-discord-youtube"; mkZapretBase = fixture: mkZapretBaseFor fixture "proxy-suite-zapret";
packagePathMatches = packagePathMatches =
packages: pattern: packages: pattern:
builtins.any ( builtins.any (
+1 -1
View File
@@ -195,7 +195,7 @@ in
perAppRoutingZapretWithoutGlobalFixture.config.systemd.user.services perAppRoutingZapretWithoutGlobalFixture.config.systemd.user.services
? "proxy-suite-per-app-zapret-anchor"; ? "proxy-suite-per-app-zapret-anchor";
assert assert
!(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "zapret-discord-youtube"); !(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-zapret");
assert builtins.length perAppRoutingZapretWithoutGlobalProfiles == 2; assert builtins.length perAppRoutingZapretWithoutGlobalProfiles == 2;
assert builtins.any ( assert builtins.any (
profile: profile.name == "zapret" && profile.route == "zapret" profile: profile.name == "zapret" && profile.route == "zapret"
+9 -9
View File
@@ -196,11 +196,11 @@
run proxy subs add rejected https://example.com/sub > rejected 2>&1 && exit 1 run proxy subs add rejected https://example.com/sub > rejected 2>&1 && exit 1
grep -q 'did not come up' rejected grep -q 'did not come up' rejected
# Pinning goes through the unit, including "auto". # Pinning and unpinning go through their units.
run proxy select community-de | grep -q 'Pinned: community-de' run proxy pin community-de | grep -q 'Pinned: community-de'
run proxy select auto | grep -q 'Selecting automatically again' run proxy unpin | grep -q 'Unpinned'
# Without a terminal and without a tag there is nothing to pick from. # Without a terminal and without a tag there is nothing to pick from.
! run proxy select </dev/null 2>/dev/null ! run proxy pin </dev/null 2>/dev/null
touch "$out" touch "$out"
''; '';
@@ -326,8 +326,8 @@
has proxy-suite-awg-work logs has proxy-suite-awg-work logs
has work awg on has work awg on
has torrent apps run has torrent apps run
has auto proxy select has unpin proxy
has community-de proxy select has community-de proxy pin
# Flags, and completion past the first of several arguments. # Flags, and completion past the first of several arguments.
has --delay proxy outbounds test has --delay proxy outbounds test
@@ -338,7 +338,7 @@
has --qr inbounds sub has --qr inbounds sub
# Candidates carry a description after a tab. # Candidates carry a description after a tab.
run proxy select > words run proxy pin > words
grep -qx "$(printf 'own-vps\tproxy.outbounds')" words grep -qx "$(printf 'own-vps\tproxy.outbounds')" words
# A shell completing must never die, however unreadable the state is. # A shell completing must never die, however unreadable the state is.
@@ -390,8 +390,8 @@
# What proxy-ctl cannot see has to be said out loud. # What proxy-ctl cannot see has to be said out loud.
grep -q 'proxy.routing.rules are not visible' where grep -q 'proxy.routing.rules are not visible' where
verdict discord.com '-> direct, with the zapret2 bypass' verdict discord.com '-> direct, with the zapret bypass'
verdict nyt.com '-> direct, with the zapret2 bypass' verdict nyt.com '-> direct, with the zapret bypass'
# Excluded is not bypassed: it must not read as a zapret2 verdict. # Excluded is not bypassed: it must not read as a zapret2 verdict.
verdict ok.ru '-> nothing runtime matches it' verdict ok.ru '-> nothing runtime matches it'
verdict example.org '-> nothing runtime matches it' verdict example.org '-> nothing runtime matches it'
+13 -10
View File
@@ -55,7 +55,7 @@ let
proxyCfg = routeModeFixture.config.services.proxy-suite.proxy; proxyCfg = routeModeFixture.config.services.proxy-suite.proxy;
clashApi = "http://127.0.0.1:9090"; clashApi = "http://127.0.0.1:9090";
routeModeStateFile = "/run/proxy-suite/route-mode"; routeModeStateFile = "/run/proxy-suite/route-mode";
priorityOutboundFile = "/var/lib/proxy-suite/priority-outbound"; pinnedOutboundFile = "/var/lib/proxy-suite/pinned-outbound";
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json"; outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/sing-box"; subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/sing-box";
subscriptionCacheHelpersBlock = ""; subscriptionCacheHelpersBlock = "";
@@ -64,7 +64,7 @@ let
jq = "${pkgs.jq}/bin/jq"; jq = "${pkgs.jq}/bin/jq";
}; };
routeModeSetterScript = generated.readDerivation routeModeControlScripts.setRouteModeScript; routeModeSetterScript = generated.readDerivation routeModeControlScripts.setRouteModeScript;
prioritySetterScript = generated.readDerivation routeModeControlScripts.setPriorityOutboundScript; pinSetterScript = generated.readDerivation routeModeControlScripts.pinOutboundScript;
routeModeRules = mkRouteModeRules routeModeFixture; routeModeRules = mkRouteModeRules routeModeFixture;
in in
{ {
@@ -125,16 +125,19 @@ in
# across a reboot and prefers a live Clash switch over a restart. # across a reboot and prefers a live Clash switch over a restart.
( (
let let
selectSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-select@"; pinSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-pin@";
reloadSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-reload"; reloadSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-reload";
in in
assert selectSvc.serviceConfig.RemainAfterExit == false; assert pinSvc.serviceConfig.RemainAfterExit == false;
assert selectSvc.serviceConfig.StateDirectory == "proxy-suite"; assert
routeModeFixture.config.systemd.services."proxy-suite-outbound-unpin".serviceConfig.ExecStart
== "${routeModeControlScripts.pinOutboundScript}";
assert pinSvc.serviceConfig.StateDirectory == "proxy-suite";
assert reloadSvc.serviceConfig.RemainAfterExit == false; assert reloadSvc.serviceConfig.RemainAfterExit == false;
assert pkgs.lib.hasInfix "/var/lib/proxy-suite/priority-outbound" prioritySetterScript; assert pkgs.lib.hasInfix "/var/lib/proxy-suite/pinned-outbound" pinSetterScript;
assert pkgs.lib.hasInfix ''rm -f "/var/lib/proxy-suite/priority-outbound"'' prioritySetterScript; assert pkgs.lib.hasInfix ''rm -f "/var/lib/proxy-suite/pinned-outbound"'' pinSetterScript;
assert pkgs.lib.hasInfix "/proxies/proxy" prioritySetterScript; assert pkgs.lib.hasInfix "/proxies/proxy" pinSetterScript;
assert pkgs.lib.hasInfix "systemctl restart proxy-suite-socks" prioritySetterScript; assert pkgs.lib.hasInfix "systemctl restart proxy-suite-socks" pinSetterScript;
true true
) )
@@ -149,7 +152,7 @@ in
assert assert
shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR=" shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR="
== "/var/lib/proxy-suite/subscriptions.d"; == "/var/lib/proxy-suite/subscriptions.d";
assert pkgs.lib.hasInfix "proxy select [<tag>|auto]" minimalProxyCtlScript; assert pkgs.lib.hasInfix "proxy pin [tag]" minimalProxyCtlScript;
assert pkgs.lib.hasInfix "proxy outbounds add <tag> <url>" minimalProxyCtlScript; assert pkgs.lib.hasInfix "proxy outbounds add <tag> <url>" minimalProxyCtlScript;
true true
) )
+3 -3
View File
@@ -70,7 +70,7 @@ in
# selection=first renames the pinned outbound - or the first one, absent a # selection=first renames the pinned outbound - or the first one, absent a
# pin - to "proxy" at start, rather than collapsing at eval time. # pin - to "proxy" at start, rather than collapsing at eval time.
( (
assert pkgs.lib.hasInfix ''PROXY_TAG="$PRIORITY_OUTBOUND"'' subscriptionFirstSelectionStartScript; assert pkgs.lib.hasInfix ''PROXY_TAG="$PINNED_OUTBOUND"'' subscriptionFirstSelectionStartScript;
assert assert
pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end)'' pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end)''
subscriptionFirstSelectionStartScript; subscriptionFirstSelectionStartScript;
@@ -80,9 +80,9 @@ in
# The pin is read from state, and one that names nothing is dropped. # The pin is read from state, and one that names nothing is dropped.
( (
assert assert
pkgs.lib.hasInfix "/var/lib/proxy-suite/priority-outbound" subscriptionOnlyStartScript; pkgs.lib.hasInfix "/var/lib/proxy-suite/pinned-outbound" subscriptionOnlyStartScript;
assert assert
pkgs.lib.hasInfix "pinned outbound '$PRIORITY_OUTBOUND' is not available" pkgs.lib.hasInfix "pinned outbound '$PINNED_OUTBOUND' is not available"
subscriptionOnlyStartScript; subscriptionOnlyStartScript;
true true
) )
+1 -5
View File
@@ -79,8 +79,6 @@ in
assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlDefaultPolkitConfig; assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlDefaultPolkitConfig;
assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0"
userControlDefaultPolkitConfig; userControlDefaultPolkitConfig;
assert pkgs.lib.hasInfix "unit === \"zapret-discord-youtube.service\""
userControlDefaultPolkitConfig;
true true
) )
@@ -93,8 +91,6 @@ in
assert assert
builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) === 0.*" userControlGlobalOnlyPolkitConfig builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) === 0.*" userControlGlobalOnlyPolkitConfig
== null; == null;
assert pkgs.lib.hasInfix "unit === \"zapret-discord-youtube.service\""
userControlGlobalOnlyPolkitConfig;
true true
) )
@@ -107,7 +103,7 @@ in
builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) !== 0.*" userControlPerAppOnlyPolkitConfig builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) !== 0.*" userControlPerAppOnlyPolkitConfig
== null; == null;
assert assert
builtins.match ".*unit === \"zapret-discord-youtube\\.service\".*" userControlPerAppOnlyPolkitConfig builtins.match ".*unit\\.indexOf\\(\"proxy-suite-\"\\) === 0.*" userControlPerAppOnlyPolkitConfig
== null; == null;
true true
) )
@@ -22,7 +22,7 @@ let
backend = null; backend = null;
backendArg = null; backendArg = null;
xraySidecarRoutingMark = null; xraySidecarRoutingMark = null;
priorityOutboundFile = null; pinnedOutboundFile = null;
runtimeOutboundsDir = null; runtimeOutboundsDir = null;
jq = null; jq = null;
python3 = null; python3 = null;
+1 -1
View File
@@ -19,7 +19,7 @@ let
]; ];
zapretSyncFixture = evalZapret { }; zapretSyncFixture = evalZapret { };
zapretSyncService = zapretSyncFixture.config.systemd.services."zapret-discord-youtube"; zapretSyncService = zapretSyncFixture.config.systemd.services."proxy-suite-zapret";
zapretSyncRules = mkRoutingRules zapretSyncFixture; zapretSyncRules = mkRoutingRules zapretSyncFixture;
zapretSyncBase = mkZapretBase zapretSyncFixture; zapretSyncBase = mkZapretBase zapretSyncFixture;
+22 -3
View File
@@ -31,7 +31,7 @@ let
) )
); );
globalService = "zapret-discord-youtube"; globalService = "proxy-suite-zapret";
perAppService = "proxy-suite-per-app-zapret"; perAppService = "proxy-suite-per-app-zapret";
zapretBase = fixture: envValue fixture globalService "ZAPRET_BASE="; zapretBase = fixture: envValue fixture globalService "ZAPRET_BASE=";
@@ -101,7 +101,10 @@ in
runtime = runtime =
pkgs.runCommand "proxy-suite-zapret2-config-check" pkgs.runCommand "proxy-suite-zapret2-config-check"
{ {
nativeBuildInputs = [ pkgs.gnugrep ]; nativeBuildInputs = [
pkgs.gnugrep
pkgs.lua
];
} }
'' ''
base=${zapretBase zapret2Global} base=${zapretBase zapret2Global}
@@ -139,6 +142,22 @@ in
grep -qx 'NFQWS2_PORTS_TCP=80,443,1984,2053,2083,2087,2096,5222,8443' "${globalRuntime}/config" grep -qx 'NFQWS2_PORTS_TCP=80,443,1984,2053,2083,2087,2096,5222,8443' "${globalRuntime}/config"
grep -qx 'NFQWS2_PORTS_UDP=443,590-600,1400,3478-3481,5349,19294-19344,49152-65535' "${globalRuntime}/config" grep -qx 'NFQWS2_PORTS_UDP=443,590-600,1400,3478-3481,5349,19294-19344,49152-65535' "${globalRuntime}/config"
grep -qF -- '/files/lua/z2k-state-persist.lua' "${globalRuntime}/config" grep -qF -- '/files/lua/z2k-state-persist.lua' "${globalRuntime}/config"
# Counted failures are stamped before the state layer reads them, so a
# success on a busy host cannot undo every rotation.
grep -qE -- 'fail-stamp\.lua --lua-init=@[^ ]+/z2k-state-persist\.lua' "${globalRuntime}/config"
STAMP=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2-fail-stamp\.lua' "${globalRuntime}/config") lua -e '
function automate_failure_counter(hrec, crec) if crec then crec.failure = true end return "orig" end
function clock_getfloattime() return 42.5 end
dofile(os.getenv("STAMP"))
local hrec, crec = {}, {}
assert(automate_failure_counter(hrec, crec, 2, 60) == "orig" and hrec.z2k_last_fail_ts == 42.5)
hrec.z2k_last_fail_ts = 1
automate_failure_counter(hrec, crec, 2, 60)
assert(hrec.z2k_last_fail_ts == 1, "a duplicate failure is not counted, so not stamped")
'
# Every UDP fake carries a blob; zapret2 errors on each packet otherwise.
grep -qF -- '--lua-desync=fake:blob=0x0000' "${globalRuntime}/config"
if grep -qF -- '--lua-desync=fake:repeats=' "${globalRuntime}/config"; then exit 1; fi
# autoHostlist fills what circular leaves unset; the source keeps its fails and time. # autoHostlist fills what circular leaves unset; the source keeps its fails and time.
grep -qF -- '--lua-desync=circular:fails=2:time=300:retrans=3:nld=2:maxseq=32768:inseq=4096:udp_out=4:udp_in=1:reset ' "${globalRuntime}/config" grep -qF -- '--lua-desync=circular:fails=2:time=300:retrans=3:nld=2:maxseq=32768:inseq=4096:udp_out=4:udp_in=1:reset ' "${globalRuntime}/config"
@@ -175,7 +194,7 @@ in
"$detect/z2k-detect" tcp16 -h 2>/dev/null "$detect/z2k-detect" tcp16 -h 2>/dev/null
# New maps restart only the zapret units this config installs. # New maps restart only the zapret units this config installs.
grep -qF 'try-restart zapret-discord-youtube.service' ${cutoffProbe} grep -qF 'try-restart proxy-suite-zapret.service' ${cutoffProbe}
if grep -qF 'proxy-suite-per-app-zapret.service' ${cutoffProbe}; then exit 1; fi if grep -qF 'proxy-suite-per-app-zapret.service' ${cutoffProbe}; then exit 1; fi
# The proxy carries what no name fixes, unless the fallback is off. # The proxy carries what no name fixes, unless the fallback is off.
-2
View File
@@ -27,7 +27,6 @@
zapretAutoEnabled, zapretAutoEnabled,
zapretStateDir, zapretStateDir,
zapretCutoffEnabled, zapretCutoffEnabled,
priorityOutboundFile,
outboundInventoryFile, outboundInventoryFile,
runtimeOutboundsDir, runtimeOutboundsDir,
runtimeSubscriptionsDir, runtimeSubscriptionsDir,
@@ -66,7 +65,6 @@ let
ZAPRET_AUTO_ENABLED = zapretAutoEnabled; ZAPRET_AUTO_ENABLED = zapretAutoEnabled;
ZAPRET_STATE_DIR = zapretStateDir; ZAPRET_STATE_DIR = zapretStateDir;
ZAPRET_CUTOFF_ENABLED = zapretCutoffEnabled; ZAPRET_CUTOFF_ENABLED = zapretCutoffEnabled;
PRIORITY_OUTBOUND_FILE = priorityOutboundFile;
OUTBOUND_INVENTORY_FILE = outboundInventoryFile; OUTBOUND_INVENTORY_FILE = outboundInventoryFile;
RUNTIME_OUTBOUNDS_DIR = runtimeOutboundsDir; RUNTIME_OUTBOUNDS_DIR = runtimeOutboundsDir;
RUNTIME_SUBS_DIR = runtimeSubscriptionsDir; RUNTIME_SUBS_DIR = runtimeSubscriptionsDir;
+60 -44
View File
@@ -25,9 +25,11 @@ ALL_SERVICES = [
"proxy-suite-tun", "proxy-suite-tun",
"proxy-suite-inbounds", "proxy-suite-inbounds",
"proxy-suite-ssh-proxy", "proxy-suite-ssh-proxy",
"proxy-suite-warp",
"proxy-suite-warp-tunnel",
"proxy-suite-tg-ws-proxy", "proxy-suite-tg-ws-proxy",
"proxy-suite-zapret",
"proxy-suite-zapret-vm-exempt", "proxy-suite-zapret-vm-exempt",
"zapret-discord-youtube",
] ]
RESTART_SERVICES = [ RESTART_SERVICES = [
@@ -35,8 +37,9 @@ RESTART_SERVICES = [
"proxy-suite-tun", "proxy-suite-tun",
"proxy-suite-inbounds", "proxy-suite-inbounds",
"proxy-suite-ssh-proxy", "proxy-suite-ssh-proxy",
"proxy-suite-warp-tunnel",
"proxy-suite-tg-ws-proxy", "proxy-suite-tg-ws-proxy",
"zapret-discord-youtube", "proxy-suite-zapret",
] ]
HELP = """\ HELP = """\
@@ -54,7 +57,8 @@ A group without a verb shows its status or list.
proxy outbounds rm <tag> remove a runtime outbound proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download] proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay) TCP ping, real delay, download speed (default: ping, delay)
proxy select [<tag>|auto] pin the priority outbound (no tag: pick from a menu) 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] proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
show or override the routing mode show or override the routing mode
proxy subs [list|update] subscription caches; update refetches them proxy subs [list|update] subscription caches; update refetches them
@@ -81,6 +85,8 @@ A group without a verb shows its status or list.
awg on <profile> | off [profile] | restart [profile] awg on <profile> | off [profile] | restart [profile]
ssh [status|on|off] SSH SOCKS5 tunnel ssh [status|on|off] SSH SOCKS5 tunnel
warp [status|on|off] WARP tunnel behind the warp outbound
tg [status|on|off] Telegram WebSocket proxy
apps [list] per-app routing profiles apps [list] per-app routing profiles
apps run <profile> -- <cmd> [args] run a command through a profile apps run <profile> -- <cmd> [args] run a command through a profile
@@ -290,6 +296,8 @@ COMPLETE = {
"zapret": "DPI bypass", "zapret": "DPI bypass",
"awg": "AmneziaWG profiles", "awg": "AmneziaWG profiles",
"ssh": "SSH SOCKS5 tunnel", "ssh": "SSH SOCKS5 tunnel",
"warp": "WARP tunnel behind the warp outbound",
"tg": "Telegram WebSocket proxy",
"apps": "per-app routing profiles", "apps": "per-app routing profiles",
"inbounds": "server inbounds", "inbounds": "server inbounds",
"help": "usage", "help": "usage",
@@ -302,7 +310,8 @@ COMPLETE = {
"words": { "words": {
**TOGGLE, **TOGGLE,
"outbounds": "outbounds, where each came from, and the pick", "outbounds": "outbounds, where each came from, and the pick",
"select": "pin the priority outbound", "pin": "always use this outbound",
"unpin": "let the configured selection pick again",
"mode": "show or override the routing mode", "mode": "show or override the routing mode",
"subs": "subscription caches", "subs": "subscription caches",
"tun": "global TUN mode", "tun": "global TUN mode",
@@ -328,7 +337,7 @@ COMPLETE = {
"--download": "timed download through each outbound", "--download": "timed download through each outbound",
}, },
}, },
"proxy select": {"args": lambda: {"auto": "let the configured selection decide", **_outbound_choices()}}, "proxy pin": {"args": _outbound_choices},
"proxy mode": {"args": lambda: {"default": f"config default ({_route_mode_default()})", **ROUTE_MODE_LABELS}}, "proxy mode": {"args": lambda: {"default": f"config default ({_route_mode_default()})", **ROUTE_MODE_LABELS}},
"proxy subs": { "proxy subs": {
"words": { "words": {
@@ -386,6 +395,8 @@ COMPLETE = {
"awg off": {"args": lambda: _names(_awg_profiles())}, "awg off": {"args": lambda: _names(_awg_profiles())},
"awg restart": {"args": lambda: _names(_awg_profiles())}, "awg restart": {"args": lambda: _names(_awg_profiles())},
"ssh": {"words": TOGGLE}, "ssh": {"words": TOGGLE},
"warp": {"words": TOGGLE},
"tg": {"words": TOGGLE},
"apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}}, "apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}},
"apps run": {"args": lambda: {_s(p["name"]): _s(p.get("route") or "") for p in read_json(env("PER_APP_ROUTING_PROFILES_FILE"))}}, "apps run": {"args": lambda: {_s(p["name"]): _s(p.get("route") or "") for p in read_json(env("PER_APP_ROUTING_PROFILES_FILE"))}},
"inbounds": { "inbounds": {
@@ -454,7 +465,7 @@ def _route_mode_current():
def _route_mode_label(mode): def _route_mode_label(mode):
if mode == "default": if mode == "default":
return f"Default ({ROUTE_MODE_LABELS.get(_route_mode_default(), 'Unknown')})" return f"Default: {ROUTE_MODE_LABELS.get(_route_mode_default(), 'Unknown')}"
return ROUTE_MODE_LABELS.get(mode, "Unknown") return ROUTE_MODE_LABELS.get(mode, "Unknown")
@@ -463,7 +474,7 @@ def _status_tray():
("socks", "proxy-suite-socks"), ("socks", "proxy-suite-socks"),
("tproxy", "proxy-suite-tproxy"), ("tproxy", "proxy-suite-tproxy"),
("tun", "proxy-suite-tun"), ("tun", "proxy-suite-tun"),
("zapret", "zapret-discord-youtube"), ("zapret", "proxy-suite-zapret"),
): ):
print(f"{key}_available={_bool(svc_exists(svc))}") print(f"{key}_available={_bool(svc_exists(svc))}")
print(f"{key}_active={_bool(svc_active(svc))}") print(f"{key}_active={_bool(svc_active(svc))}")
@@ -529,7 +540,7 @@ def _status_zapret():
if not readable(auto): if not readable(auto):
return "" return ""
try: try:
return f"{sum(1 for line in lines(read_text(auto)) if line)} learned" return str(sum(1 for line in lines(read_text(auto)) if line))
except OSError: except OSError:
return "" return ""
@@ -543,15 +554,17 @@ def cmd_status(*args):
_svc_status(svc) _svc_status(svc)
for profile in _awg_profiles(): for profile in _awg_profiles():
_svc_status(_awg_service(profile)) _svc_status(_awg_service(profile))
socks = svc_exists("proxy-suite-socks") if svc_exists("proxy-suite-socks"):
if socks or env("ZAPRET_AUTO_ENABLED") == "1":
print() print()
print("routing:") print("routing:")
if socks: _status_row("active mode", _route_mode_label(_route_mode_current()))
_status_row("active mode", _route_mode_label(_route_mode_current())) _status_row_if("outbound", _status_outbound())
_status_row_if("outbound", _status_outbound()) _status_row_if("autoProxy", _status_autoproxy())
_status_row_if("autoProxy", _status_autoproxy()) zapret = _status_zapret()
_status_row_if("zapret2", _status_zapret()) if zapret:
print()
print("zapret:")
_status_row("learned hosts", zapret)
def cmd_restart(*_): def cmd_restart(*_):
@@ -579,8 +592,10 @@ def cmd_proxy(verb="status", *args):
must("stop", "proxy-suite-socks") must("stop", "proxy-suite-socks")
elif verb == "outbounds": elif verb == "outbounds":
cmd_outbounds(*args) cmd_outbounds(*args)
elif verb == "select": elif verb == "pin":
cmd_select(*args) cmd_pin(*args)
elif verb == "unpin":
cmd_unpin()
elif verb == "mode": elif verb == "mode":
cmd_route_mode(*args) cmd_route_mode(*args)
elif verb == "subs": elif verb == "subs":
@@ -594,7 +609,7 @@ def cmd_proxy(verb="status", *args):
elif verb in ("probe", "learn", "queue", "learned"): elif verb in ("probe", "learn", "queue", "learned"):
cmd_proxy_auto(verb, *args) cmd_proxy_auto(verb, *args)
else: else:
usage("proxy [status|on|off|outbounds|select|mode|subs|tun|tproxy|auto]") usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|tun|tproxy|auto]")
def cmd_outbounds(verb="list", *args): def cmd_outbounds(verb="list", *args):
@@ -818,7 +833,7 @@ def _outbounds_list():
reputation = _reputation_by_tag() reputation = _reputation_by_tag()
print(f"Selection: {_s(inventory.get('selection') or 'first')}") print(f"Selection: {_s(inventory.get('selection') or 'first')}")
print(f"Pinned: {pinned or '(auto)'}") print(f"Pinned: {pinned or '(none)'}")
if current: if current:
print(f"Current: {current}") print(f"Current: {current}")
print() print()
@@ -834,22 +849,16 @@ def _outbounds_list():
print(f" {mark}{tag:<34} {rep(tag)}{_s(sources.get(tag) or '-')}") print(f" {mark}{tag:<34} {rep(tag)}{_s(sources.get(tag) or '-')}")
def cmd_select(tag="", *_): def cmd_pin(tag="", *_):
if not tag: if not tag:
if not (os.isatty(0) and os.isatty(1)): if not (os.isatty(0) and os.isatty(1)):
usage("proxy select <tag>|auto") usage("proxy pin <tag>")
_require_outbound_inventory() _require_outbound_inventory()
pinned = _s(_outbound_inventory().get("pinned") or "") or "auto" pinned = _s(_outbound_inventory().get("pinned") or "") or "(none)"
status, tag = _run( status, tag = _run(
[ ["fzf", "--prompt=pin> ", "--height=40%", "--reverse", f"--header=pinned: {pinned}"],
"fzf",
"--prompt=outbound> ",
"--height=40%",
"--reverse",
f"--header=pinned: {pinned} (auto = let the configured selection decide)",
],
capture=True, capture=True,
stdin="".join(f"{t}\n" for t in ["auto", *_outbound_tags()]), stdin="".join(f"{t}\n" for t in _outbound_tags()),
) )
tag = tag.strip("\n") tag = tag.strip("\n")
# Dismissed. # Dismissed.
@@ -858,10 +867,16 @@ def cmd_select(tag="", *_):
status, escaped = _run(["systemd-escape", "--", tag], capture=True) status, escaped = _run(["systemd-escape", "--", tag], capture=True)
if status: if status:
sys.exit(status) sys.exit(status)
escaped = escaped.rstrip("\n") unit = "proxy-suite-outbound-pin@" + escaped.rstrip("\n")
if systemctl("start", f"proxy-suite-outbound-select@{escaped}.service")[0]: if systemctl("start", f"{unit}.service")[0]:
die(f"Failed - see: proxy-ctl logs proxy-suite-outbound-select@{escaped}") die(f"Failed - see: proxy-ctl logs {unit}")
print("Selecting automatically again." if tag == "auto" else f"Pinned: {tag}") print(f"Pinned: {tag}")
def cmd_unpin(*_):
if systemctl("start", "proxy-suite-outbound-unpin.service")[0]:
die("Failed - see: proxy-ctl logs proxy-suite-outbound-unpin")
print("Unpinned: the configured selection picks again.")
# --- runtime outbounds and subscriptions -------------------------------------- # --- runtime outbounds and subscriptions --------------------------------------
@@ -965,7 +980,7 @@ def cmd_route_mode(action="status", *_):
if not svc_exists("proxy-suite-socks"): if not svc_exists("proxy-suite-socks"):
die("proxy is not enabled in this configuration.") die("proxy is not enabled in this configuration.")
if action == "status": if action == "status":
print(_route_mode_current()) print(_route_mode_label(_route_mode_current()))
elif action in ("default", *ROUTE_MODES): elif action in ("default", *ROUTE_MODES):
must("start", f"proxy-suite-route-mode@{action}.service") must("start", f"proxy-suite-route-mode@{action}.service")
print(f"Switched to: {_route_mode_label(action)}") print(f"Switched to: {_route_mode_label(action)}")
@@ -1573,7 +1588,7 @@ def cmd_zapret(*args):
elif args[:1] == ("cutoff",): elif args[:1] == ("cutoff",):
cmd_zapret_cutoff(*args[1:]) cmd_zapret_cutoff(*args[1:])
else: else:
_toggle("zapret-discord-youtube", "zapret", *args) _toggle("proxy-suite-zapret", "zapret", *args)
def _zapret_state_dir(): def _zapret_state_dir():
@@ -1796,15 +1811,15 @@ def cmd_where(domain="", *_):
pinned = _where_in_list(_zapret_auto_file("zapret-hosts-user.txt"), 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) learned = _where_in_list(_zapret_auto_file("zapret-hosts-auto.txt"), domain)
if excluded: if excluded:
_where_row("zapret2", f"excluded ({excluded}) - never bypassed, never learned") _where_row("zapret", f"excluded ({excluded}) - never bypassed, never learned")
elif pinned: elif pinned:
_where_row("zapret2", f"pinned ({pinned}) - always bypassed") _where_row("zapret", f"pinned ({pinned}) - always bypassed")
verdict = verdict or "direct, with the zapret2 bypass" verdict = verdict or "direct, with the zapret bypass"
elif learned: elif learned:
_where_row("zapret2", f"learned ({learned}) - bypassed") _where_row("zapret", f"learned ({learned}) - bypassed")
verdict = verdict or "direct, with the zapret2 bypass" verdict = verdict or "direct, with the zapret bypass"
else: else:
_where_row("zapret2", "not learned, not pinned, not excluded") _where_row("zapret", "not learned, not pinned, not excluded")
print(f" -> {verdict or 'nothing runtime matches it; the configured routing decides'}") print(f" -> {verdict or 'nothing runtime matches it; the configured routing decides'}")
print(" Declared proxy.routing.rules are not visible here. Test what reaches it:") print(" Declared proxy.routing.rules are not visible here. Test what reaches it:")
@@ -2111,7 +2126,6 @@ ALIASES = {
"tun": ["proxy", "tun"], "tun": ["proxy", "tun"],
"tproxy": ["proxy", "tproxy"], "tproxy": ["proxy", "tproxy"],
"outbounds": ["proxy", "outbounds"], "outbounds": ["proxy", "outbounds"],
"select": ["proxy", "select"],
"route-mode": ["proxy", "mode"], "route-mode": ["proxy", "mode"],
"subscription": ["proxy", "subs"], "subscription": ["proxy", "subs"],
"wrap": ["apps", "run"], "wrap": ["apps", "run"],
@@ -2122,7 +2136,7 @@ def cmd_logs(*units):
if units: if units:
_exec(["journalctl", "-fu", *units]) _exec(["journalctl", "-fu", *units])
# journalctl takes unit globs, so the default needs no unit list of its own. # journalctl takes unit globs, so the default needs no unit list of its own.
_exec(["journalctl", "-f", "-u", "proxy-suite-*", "-u", "zapret-discord-youtube"]) _exec(["journalctl", "-f", "-u", "proxy-suite-*"])
COMMANDS = { COMMANDS = {
@@ -2136,6 +2150,8 @@ COMMANDS = {
"zapret": cmd_zapret, "zapret": cmd_zapret,
"awg": cmd_awg, "awg": cmd_awg,
"ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args), "ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args),
"warp": lambda *args: _toggle("proxy-suite-warp-tunnel", "warp", *args),
"tg": lambda *args: _toggle("proxy-suite-tg-ws-proxy", "tg", *args),
"apps": cmd_apps, "apps": cmd_apps,
"inbounds": cmd_inbounds, "inbounds": cmd_inbounds,
"where": cmd_where, "where": cmd_where,
+267 -95
View File
@@ -7,7 +7,10 @@ die() cannot take the TUI down.
import os import os
import shlex import shlex
import signal
import subprocess import subprocess
import sys
import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Callable from typing import Callable
@@ -28,15 +31,40 @@ CTL = "proxy-ctl"
REFRESH_SECONDS = 3 REFRESH_SECONDS = 3
def _die(message, status=1):
# Readers run in-process: the message rides the SystemExit, so an empty tab can say why.
sys.exit(message)
ctl.die = _die
_memo = {} # (reader, args) -> result, cleared at the start of every load
def _per_load(fn):
def wrapped(*args):
key = (fn, args)
if key not in _memo:
_memo[key] = fn(*args)
return _memo[key]
return wrapped
# Clash API calls and systemctl spawns that several readers repeat within one load.
for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"):
setattr(ctl, _name, _per_load(getattr(ctl, _name)))
@dataclass @dataclass
class Action: class Action:
key: str key: str
label: str label: str
argv: Callable # (selected row or None, prompt text) -> proxy-ctl argv argv: Callable # (selected row or None, prompt text, unit states) -> proxy-ctl argv
when: Callable = None # row -> applies; None: a tab-wide action that needs no row when: Callable = None # row -> applies; None: a tab-wide action that needs no row
prompt: str = "" # ask for text first prompt: str = "" # ask for text first
confirm: bool = False 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 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
@dataclass @dataclass
@@ -46,7 +74,7 @@ class Tab:
available: Callable # unit states -> bool available: Callable # unit states -> bool
columns: list # (row field, heading) columns: list # (row field, heading)
rows: Callable # unit states -> [row dict with a unique "key"] 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 summary: Callable = None # () -> text above the table, read with every load
actions: list = field(default_factory=list) actions: list = field(default_factory=list)
@@ -86,7 +114,9 @@ TOGGLES = {
"proxy-suite-tun": ["proxy", "tun"], "proxy-suite-tun": ["proxy", "tun"],
"proxy-suite-tproxy": ["proxy", "tproxy"], "proxy-suite-tproxy": ["proxy", "tproxy"],
"proxy-suite-ssh-proxy": ["ssh"], "proxy-suite-ssh-proxy": ["ssh"],
"zapret-discord-youtube": ["zapret"], "proxy-suite-warp-tunnel": ["warp"],
"proxy-suite-tg-ws-proxy": ["tg"],
"proxy-suite-zapret": ["zapret"],
} }
AWG_PREFIX = ctl._awg_service("") AWG_PREFIX = ctl._awg_service("")
ZAPRET_LISTS = ( ZAPRET_LISTS = (
@@ -96,7 +126,7 @@ ZAPRET_LISTS = (
) )
def toggle_argv(row, _): def toggle_argv(row, *_):
verb = "off" if row["state"] == "active" else "on" verb = "off" if row["state"] == "active" else "on"
if row["unit"].startswith(AWG_PREFIX): if row["unit"].startswith(AWG_PREFIX):
return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)] return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)]
@@ -141,18 +171,20 @@ def outbound_summary():
return "No outbounds yet - is proxy-suite-socks running?" return "No outbounds yet - is proxy-suite-socks running?"
return ( return (
f"Selection: {ctl._s(inventory.get('selection') or 'first')} " f"Selection: {ctl._s(inventory.get('selection') or 'first')} "
f"Pinned: {ctl._s(inventory.get('pinned') or '(auto)')} " f"Pinned: {ctl._s(inventory.get('pinned') or '(none)')} "
f"Current: {ctl._outbound_current() or '-'}" f"Current: {ctl._outbound_current() or '-'}"
) )
def subscription_rows(_): def subscription_rows(_):
rows = [] rows = []
for source, tags in (("declared", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))): for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
for t in tags: for t in tags:
cache = ctl._subscription_cache(t) cache = ctl._subscription_cache(t)
count = ctl._subscription_proxy_count_text(cache) if os.path.isfile(cache) else "-" cached = os.path.isfile(cache)
rows.append({"key": t, "tag": t, "proxies": count, "source": source}) count = ctl._subscription_proxy_count_text(cache) if cached else "-"
updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-"
rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source})
return rows return rows
@@ -187,10 +219,24 @@ def zapret_summary():
return 'Learned hostlists need zapret.engine = "zapret2".' return 'Learned hostlists need zapret.engine = "zapret2".'
text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS) text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS)
if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1": if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1":
text += "\n" + " ".join(line.strip() for line in _capture(["zapret", "cutoff", "status"]).splitlines()[:2]) text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2])
return text return text
_cutoff = {} # ts mtime -> status text: a probe rewrites ts
def _cutoff_status():
try:
mtime = os.path.getmtime(os.path.join(ctl._zapret_state_dir(), "cutoff", "ts"))
except OSError:
mtime = None
if mtime not in _cutoff:
_cutoff.clear()
_cutoff[mtime] = _capture(["zapret", "cutoff", "status"])
return _cutoff[mtime]
def inbound_rows(_): def inbound_rows(_):
return [ return [
{"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}} {"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
@@ -211,10 +257,16 @@ def status_text(states):
default = " (default)" if ctl._route_mode_current() == "default" else "" default = " (default)" if ctl._route_mode_current() == "default" else ""
parts.append(("mode ", ctl._route_mode_effective() + default)) parts.append(("mode ", ctl._route_mode_effective() + default))
parts.append(("outbound ", ctl._status_outbound() or "-")) parts.append(("outbound ", ctl._status_outbound() or "-"))
for name, value in (("autoProxy ", ctl._status_autoproxy()), ("zapret2 ", ctl._status_zapret())): if autoproxy := ctl._status_autoproxy():
if value: parts.append(("autoProxy ", autoproxy))
parts.append((name, value)) if zapret := ctl._status_zapret():
return "[b $accent]proxy-suite[/]" + "".join(f" [$text-muted]{label}[/][b]{escape(value)}[/]" for label, value in parts) parts.append(("zapret ", f"{zapret} learned"))
failed = sum(1 for s in states.values() if s == "failed")
return (
"[b $accent]proxy-suite[/]"
+ "".join(f" [$text-muted]{label}[/][b]{escape(value)}[/]" for label, value in parts)
+ (f" [b $error]{failed} failed[/]" if failed else "")
)
def _link(row, *extra): def _link(row, *extra):
@@ -233,9 +285,8 @@ def _enabled(name):
return lambda _: ctl.env(name) == "1" return lambda _: ctl.env(name) == "1"
def _zapret_toggle(row, _): def _zapret_toggle(row, _, states):
active = unit_states(["zapret-discord-youtube"]).get("zapret-discord-youtube") == "active" return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"]
return ["zapret", "off" if active else "on"]
TABS = [ TABS = [
@@ -246,9 +297,22 @@ TABS = [
[("unit", "Unit"), ("state", "State")], [("unit", "Unit"), ("state", "State")],
service_rows, service_rows,
actions=[ actions=[
Action("space", "start / stop", toggle_argv, when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX)), Action(
Action("l", "follow its logs", lambda r, _: ["logs", r["unit"]], when=ROW, mode="suspend"), "space",
Action("R", "restart everything running", lambda r, _: ["restart"], confirm=True), "start / stop",
toggle_argv,
when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX),
# proxy off takes tun and tproxy down with it.
confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active",
),
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
Action(
"ctrl+r",
"restart it",
lambda r, *_: ["awg", "restart", r["unit"].removeprefix(AWG_PREFIX)],
when=lambda r: r["unit"].startswith(AWG_PREFIX) and r["state"] == "active",
),
Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True),
], ],
), ),
Tab( Tab(
@@ -258,7 +322,7 @@ TABS = [
[("active", ""), ("key", "Mode"), ("mode", "Meaning")], [("active", ""), ("key", "Mode"), ("mode", "Meaning")],
route_rows, route_rows,
summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.", 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"])],
), ),
Tab( Tab(
"outbounds", "outbounds",
@@ -268,24 +332,26 @@ TABS = [
outbound_rows, outbound_rows,
summary=outbound_summary, summary=outbound_summary,
actions=[ actions=[
Action("p", "pin it", lambda r, _: ["proxy", "select", r["tag"]], when=lambda r: r["mark"] != "★"), Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"),
Action("a", "unpin: select automatically", lambda r, _: ["proxy", "select", "auto"]), Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
Action("t", "test it", lambda r, _: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"), 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("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("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), Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
], ],
), ),
Tab( Tab(
"subs", "subs",
"Subs", "Subs",
_socks, _socks,
[("tag", "Tag"), ("proxies", "Proxies"), ("source", "Source")], [("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")],
subscription_rows, subscription_rows,
summary=lambda: f"proxy-suite-subscription-update: {ctl.svc_state('proxy-suite-subscription-update') or 'unknown'}",
actions=[ actions=[
Action("u", "refetch all", lambda r, _: ["proxy", "subs", "update"], mode="dialog"), 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("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"),
Action("d", "remove it", lambda r, _: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True), 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( Tab(
@@ -296,29 +362,29 @@ TABS = [
autoproxy_rows, autoproxy_rows,
summary=ctl._status_autoproxy, summary=ctl._status_autoproxy,
actions=[ actions=[
Action("w", "how is it routed", lambda r, _: ["where", r["domain"]], when=ROW, mode="dialog"), 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("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 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("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("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"), Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"),
], ],
), ),
Tab( Tab(
"zapret", "zapret",
"zapret", "zapret",
lambda s: "zapret-discord-youtube" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1", lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
[("host", "Host"), ("kind", "List")], [("host", "Host"), ("kind", "List")],
zapret_rows, zapret_rows,
summary=zapret_summary, summary=zapret_summary,
actions=[ actions=[
Action("f", "forget it (may be learned again)", lambda r, _: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")), 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 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("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("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("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("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("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"),
Action("z", "start / stop zapret", _zapret_toggle), Action("z", "start / stop zapret", _zapret_toggle),
], ],
), ),
@@ -330,11 +396,13 @@ TABS = [
inbound_rows, inbound_rows,
summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}", summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}",
actions=[ actions=[
Action("l", "share link", lambda r, _: _link(r), when=ROW, mode="dialog"), 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("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"),
Action("s", "subscription URL", lambda r, _: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"), Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"),
Action("S", "subscription URL as QR", lambda r, _: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"), Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"),
Action("t", "traffic per user", lambda r, _: ["inbounds", "stats"], mode="dialog"), Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"),
Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="copy"),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
], ],
), ),
Tab( Tab(
@@ -344,14 +412,15 @@ TABS = [
[("profile", "Profile"), ("route", "Route")], [("profile", "Profile"), ("route", "Route")],
app_rows, app_rows,
actions=[ 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"), Action("x", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="pause"),
], ],
), ),
] ]
GLOBAL_KEYS = [ GLOBAL_KEYS = [
("enter", "actions for the selected row"), ("enter", "actions for the selected row (or click it)"),
("← → ⇥", "switch tab; 1-8 jump to one"), ("← → ⇥", "switch tab; 1-8 jump to one"),
("/", "filter the rows; esc clears the filter"),
("w", "how is a domain routed"), ("w", "how is a domain routed"),
("L", "follow all logs"), ("L", "follow all logs"),
("o", "output of the last command"), ("o", "output of the last command"),
@@ -360,6 +429,9 @@ GLOBAL_KEYS = [
("q", "quit"), ("q", "quit"),
] ]
HINT = "enter: actions for the selected row · ←/→: tabs · /: filter · ?: keys"
FEEDBACK_SECONDS = 10
STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "red", "activating": "yellow", "deactivating": "yellow"} STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "red", "activating": "yellow", "deactivating": "yellow"}
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐"} STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐"}
CELL_STYLES = { CELL_STYLES = {
@@ -396,7 +468,7 @@ def _safe(fn, *args, fallback=None):
try: try:
return fn(*args) return fn(*args)
except (Exception, SystemExit): except (Exception, SystemExit):
return fallback # Unreadable state: the tab stays empty, and an action on it says why. return fallback # Unreadable state: shown empty; a tab's own rows say why in its summary.
def _read_states(): def _read_states():
@@ -409,14 +481,14 @@ def _read_states():
class Prompt(ModalScreen): class Prompt(ModalScreen):
BINDINGS = [Binding("escape", "dismiss", "cancel")] BINDINGS = [Binding("escape", "dismiss", "cancel")]
def __init__(self, title, placeholder): def __init__(self, title, placeholder, value=""):
super().__init__() super().__init__()
self.heading, self.placeholder = title, placeholder self.heading, self.placeholder, self.value = title, placeholder, value
def compose(self) -> ComposeResult: def compose(self) -> ComposeResult:
with Vertical(classes="dialog"): with Vertical(classes="dialog"):
yield Label(self.heading, classes="dialog-title") yield Label(self.heading, classes="dialog-title")
yield Input(placeholder=self.placeholder) yield Input(self.value, placeholder=self.placeholder)
yield Label("enter run · esc cancel", classes="dialog-hint") yield Label("enter run · esc cancel", classes="dialog-hint")
def on_input_submitted(self, event): def on_input_submitted(self, event):
@@ -433,7 +505,7 @@ class Confirm(ModalScreen):
def compose(self) -> ComposeResult: def compose(self) -> ComposeResult:
with Vertical(classes="dialog"): with Vertical(classes="dialog"):
yield Label("Run this?", classes="dialog-title") yield Label("Run this?", classes="dialog-title")
yield Label(self.command) yield Label(self.command, markup=False)
yield Label("y/enter run · n/esc cancel", classes="dialog-hint") yield Label("y/enter run · n/esc cancel", classes="dialog-hint")
@@ -448,7 +520,7 @@ class Menu(ModalScreen):
def compose(self) -> ComposeResult: def compose(self) -> ComposeResult:
with Vertical(classes="dialog menu"): with Vertical(classes="dialog menu"):
yield Label(self.heading, classes="dialog-title") yield Label(self.heading, classes="dialog-title", markup=False)
yield OptionList( yield OptionList(
*(Option(Text.assemble((f"{a.key:<7}", "bold cyan"), a.label), id=str(i)) for i, a in enumerate(self.actions)) *(Option(Text.assemble((f"{a.key:<7}", "bold cyan"), a.label), id=str(i)) for i, a in enumerate(self.actions))
) )
@@ -459,25 +531,39 @@ class Menu(ModalScreen):
class Output(ModalScreen): class Output(ModalScreen):
BINDINGS = [Binding("escape,q", "dismiss", "close")] BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy")]
def __init__(self, title, text=None): def __init__(self, title, text=None):
super().__init__() super().__init__()
self.heading, self.initial = title, text self.heading, self.initial = title, text
self.proc = None # the streaming command, stopped when the dialog closes
self.text = [] # plain lines, for copying
def compose(self) -> ComposeResult: def compose(self) -> ComposeResult:
with Vertical(classes="dialog output"): with Vertical(classes="dialog output"):
yield Label(self.heading, classes="dialog-title") yield Label(self.heading, classes="dialog-title", markup=False)
# Follow a streaming command; show finished text from its top. # Follow a streaming command; show finished text from its top.
log = RichLog(wrap=False, markup=False, auto_scroll=self.initial is None) log = RichLog(wrap=False, markup=False, auto_scroll=self.initial is None)
if self.initial is not None: if self.initial is not None:
log.write(self.initial if isinstance(self.initial, Text) else Text.from_ansi(self.initial)) text = self.initial if isinstance(self.initial, Text) else Text.from_ansi(self.initial)
self.text.append(text.plain)
log.write(text)
yield log yield log
yield Label("↑↓ scroll · esc close", classes="dialog-hint") yield Label("↑↓ scroll · c copy · esc close", classes="dialog-hint")
def write(self, line): def write(self, line):
if self.is_attached: if self.is_attached:
self.query_one(RichLog).write(Text.from_ansi(line)) text = Text.from_ansi(line)
self.text.append(text.plain)
self.query_one(RichLog).write(text)
def action_copy(self):
self.app.copy_to_clipboard("\n".join(self.text))
self.notify("Copied the output.")
def on_unmount(self):
if self.proc and self.proc.poll() is None:
self.proc.terminate()
# --- main screen -------------------------------------------------------------- # --- main screen --------------------------------------------------------------
@@ -496,10 +582,12 @@ class MainScreen(Screen):
*(Binding(str(n), f"app.jump({n - 1})", show=False) for n in range(1, 9)), *(Binding(str(n), f"app.jump({n - 1})", show=False) for n in range(1, 9)),
Binding("enter", "app.menu", "actions", priority=True), Binding("enter", "app.menu", "actions", priority=True),
Binding("question_mark", "app.help", "keys"), Binding("question_mark", "app.help", "keys"),
Binding("slash", "app.filter", "filter"),
Binding("escape", "app.clear_filter", "clear filter", show=False),
Binding("w", "app.where", "where", show=False), Binding("w", "app.where", "where", show=False),
Binding("L", "app.logs", "all logs", show=False), Binding("L", "app.logs", "all logs", show=False),
Binding("o", "app.last_output", "last output", show=False), Binding("o", "app.last_output", "last output", show=False),
Binding("r", "app.reload(True)", "refresh", show=False), Binding("r", "app.reload", "refresh", show=False),
Binding("q", "app.quit", "quit"), Binding("q", "app.quit", "quit"),
] ]
@@ -517,12 +605,17 @@ class MainScreen(Screen):
for name, heading in tab.columns: for name, heading in tab.columns:
table.add_column(heading, key=name) table.add_column(heading, key=name)
yield table yield table
yield Static("enter: actions for the selected row · ←/→: tabs · ?: keys", id="feedback") yield Static(HINT, id="feedback")
yield Footer(show_command_palette=False) yield Footer(show_command_palette=False)
def on_mount(self): def on_mount(self):
self.app.start() self.app.start()
def on_screen_resume(self):
# Refreshes pause under dialogs; catch up once one closes.
if self.app.rows:
self.app.action_reload()
class ProxyTui(App): class ProxyTui(App):
TITLE = "proxy-tui" TITLE = "proxy-tui"
@@ -547,18 +640,33 @@ class ProxyTui(App):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.states = _read_states() self.states = _read_states()
self.tabs = {t.id: t for t in TABS if _safe(t.available, self.states, fallback=False)} self.tabs = {t.id: t for t in TABS}
self.shown = self.available_tabs(self.states)
self.rows = {} # tab id -> {row key: row} self.rows = {} # tab id -> {row key: row}
self.filters = {} # tab id -> text
self.typed = {} # prompt title -> what was last typed there
self.feedback_timer = None
self.last_output = None # (title, text) self.last_output = None # (title, text)
def available_tabs(self, states):
return [t.id for t in TABS if _safe(t.available, states, fallback=False)]
def get_default_screen(self): def get_default_screen(self):
return MainScreen(self.tabs) return MainScreen(self.tabs)
def start(self): def start(self):
"""Once the main screen is up: it owns every widget read here.""" """Once the main screen is up: it owns every widget read here."""
self.focus_table() self.focus_table()
self.action_reload(True) tabs = self.main.query_one("#tabs", TabbedContent)
self.set_interval(REFRESH_SECONDS, self.action_reload) for tab_id in self.tabs:
if tab_id not in self.shown:
tabs.hide_tab(tab_id)
self.action_reload()
self.set_interval(REFRESH_SECONDS, self.tick)
def tick(self):
if self.screen is self.main:
self.action_reload()
@property @property
def main(self): def main(self):
@@ -576,38 +684,52 @@ class ProxyTui(App):
self.table().focus() self.table().focus()
def action_tab(self, step): def action_tab(self, step):
ids = list(self.tabs) ids = self.shown
self.action_jump((ids.index(self.active_tab()) + step) % len(ids)) current = ids.index(self.active_tab()) if self.active_tab() in ids else -1
self.action_jump((current + step) % len(ids))
def action_jump(self, index): def action_jump(self, index):
if 0 <= index < len(self.tabs): if 0 <= index < len(self.shown):
self.main.query_one("#tabs", TabbedContent).active = list(self.tabs)[index] self.main.query_one("#tabs", TabbedContent).active = self.shown[index]
def on_tabbed_content_tab_activated(self, _): def on_tabbed_content_tab_activated(self, _):
self.focus_table() self.focus_table()
self.action_reload(True) self.action_reload()
# --- reading -------------------------------------------------------------- # --- reading --------------------------------------------------------------
def action_reload(self, full=False): def action_reload(self):
self.load(self.active_tab(), full) self.load(self.active_tab())
@work(thread=True, exclusive=True, group="load") @work(thread=True, exclusive=True, group="load")
def load(self, tab_id, full): def load(self, tab_id):
_memo.clear()
tab = self.tabs[tab_id] tab = self.tabs[tab_id]
states = _read_states() states = _read_states()
visible = self.available_tabs(states)
status = _safe(status_text, states, fallback="status unavailable") status = _safe(status_text, states, fallback="status unavailable")
rows = _safe(tab.rows, states, fallback=[]) summary = (_safe(tab.summary, fallback="") or "") if tab.summary else ""
summary = (_safe(tab.summary, fallback="") or "") if full and tab.summary else None try:
self.call_from_thread(self.fill, tab_id, states, status, rows, summary) rows = tab.rows(states)
except (Exception, SystemExit) as e:
rows = []
summary = f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "")
self.call_from_thread(self.fill, tab_id, states, visible, status, rows, summary)
def fill(self, tab_id, states, status, rows, summary): def fill(self, tab_id, states, visible, status, rows, summary):
self.states = states self.states = states
self.main.query_one("#status", Static).update(status) self.main.query_one("#status", Static).update(status)
if summary is not None: if visible != self.shown:
widget = self.main.query_one(f"#{tab_id}-summary", Static) self.show_tabs(visible)
widget.update(summary) if tab_id not in visible:
widget.display = bool(summary) return # show_tabs moved to another tab, which loads itself
if text := self.filters.get(tab_id):
needle = text.lower()
rows = [r for r in rows if any(needle in str(r.get(name, "")).lower() for name, _ in self.tabs[tab_id].columns)]
summary = f"filter: {text} ({len(rows)} rows) · esc clears" + (f"\n{summary}" if summary else "")
widget = self.main.query_one(f"#{tab_id}-summary", Static)
widget.update(Text(summary))
widget.display = bool(summary)
self.rows[tab_id] = {r["key"]: r for r in rows} self.rows[tab_id] = {r["key"]: r for r in rows}
tab, table = self.tabs[tab_id], self.table(tab_id) tab, table = self.tabs[tab_id], self.table(tab_id)
keys = [r["key"] for r in rows] keys = [r["key"] for r in rows]
@@ -626,6 +748,14 @@ class ProxyTui(App):
if selected in keys: if selected in keys:
table.move_cursor(row=keys.index(selected), animate=False) table.move_cursor(row=keys.index(selected), animate=False)
def show_tabs(self, visible):
tabs = self.main.query_one("#tabs", TabbedContent)
for tab_id in self.tabs:
(tabs.show_tab if tab_id in visible else tabs.hide_tab)(tab_id)
self.shown = visible
if tabs.active not in visible and visible:
tabs.active = visible[0]
def selected_key(self, tab_id): def selected_key(self, tab_id):
table = self.table(tab_id) table = self.table(tab_id)
if not table.row_count: if not table.row_count:
@@ -650,6 +780,10 @@ class ProxyTui(App):
return return
self.push_screen(Menu(title, actions), lambda a: a and self.perform(a, row)) self.push_screen(Menu(title, actions), lambda a: a and self.perform(a, row))
def on_data_table_row_selected(self, _):
# Only a click on the highlighted row: enter is bound above the table.
self.action_menu()
def action_act(self, index): def action_act(self, index):
action = self.tabs[self.active_tab()].actions[index] action = self.tabs[self.active_tab()].actions[index]
row = self.selected_row() row = self.selected_row()
@@ -660,7 +794,22 @@ class ProxyTui(App):
self.perform(action, row) self.perform(action, row)
def action_where(self): def action_where(self):
self.perform(Action("w", "How is a domain routed", lambda r, t: ["where", t], prompt="<domain>", mode="dialog"), None) self.perform(Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog"), None)
def action_filter(self):
tab_id = self.active_tab()
def apply(text):
if text is None:
return
self.filters[tab_id] = text
self.action_reload()
self.push_screen(Prompt("Filter rows", "text in any column; empty clears", self.filters.get(tab_id, "")), apply)
def action_clear_filter(self):
if self.filters.pop(self.active_tab(), ""):
self.action_reload()
def action_logs(self): def action_logs(self):
self.run_argv("suspend", ["logs"]) self.run_argv("suspend", ["logs"])
@@ -684,38 +833,51 @@ class ProxyTui(App):
def perform(self, action, row): def perform(self, action, row):
def with_text(text=""): def with_text(text=""):
argv = action.argv(row, text) argv = action.argv(row, text, self.states)
if action.confirm: confirm = action.confirm(row) if callable(action.confirm) else action.confirm
if confirm:
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv)) self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv))
else: else:
self.run_argv(action.mode, argv) self.run_argv(action.mode, argv)
def typed(text):
if text:
self.typed[action.label] = text
with_text(text)
if action.prompt: if action.prompt:
title = action.label.removesuffix("…") title = action.label.removesuffix("…")
self.push_screen(Prompt(title[:1].upper() + title[1:], action.prompt), lambda text: text and with_text(text)) self.push_screen(Prompt(title[:1].upper() + title[1:], action.prompt, self.typed.get(action.label, "")), typed)
else: else:
with_text() with_text()
def run_argv(self, mode, argv): def run_argv(self, mode, argv):
command = f"proxy-ctl {shlex.join(argv)}" command = f"proxy-ctl {shlex.join(argv)}"
if mode == "suspend": if mode in ("suspend", "pause"):
with self.suspend(): with self.suspend():
ctl._run_foreground([CTL, *argv]) ctl._run_foreground([CTL, *argv])
self.action_reload(True) if mode == "pause":
try:
input("\n[enter] back to proxy-tui")
except (EOFError, KeyboardInterrupt):
pass
self.action_reload()
return return
dialog = Output(command) if mode == "dialog" else None dialog = Output(command) if mode == "dialog" else None
if dialog: if dialog:
self.push_screen(dialog) self.push_screen(dialog)
self.feedback(f"… {command}") self.feedback(f"… {command}")
self.stream(command, argv, dialog) self.stream(command, argv, dialog, mode == "copy")
@work(thread=True) @work(thread=True)
def stream(self, command, argv, dialog): def stream(self, command, argv, dialog, copy=False):
out = [] out = []
try: try:
p = subprocess.Popen( p = subprocess.Popen(
[CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True
) )
if dialog:
dialog.proc = p
for line in p.stdout: for line in p.stdout:
out.append(line.rstrip("\n")) out.append(line.rstrip("\n"))
if dialog: if dialog:
@@ -726,19 +888,29 @@ class ProxyTui(App):
status = 127 status = 127
last = Text.from_ansi(next((line for line in reversed(out) if line.strip()), "")).plain.strip() last = Text.from_ansi(next((line for line in reversed(out) if line.strip()), "")).plain.strip()
message = f"{last} ({command})" if last else command 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)
return
if copy and not status and last:
self.call_from_thread(self.copy_to_clipboard, last)
message = f"copied: {last}"
if status: if status:
message = f"exit {status}: {message}" message = f"exit {status}: {message}"
if dialog: if dialog:
self.call_from_thread(dialog.write, f"\x1b[31m(exit status {status})\x1b[0m") self.call_from_thread(dialog.write, f"\x1b[31m(exit status {status})\x1b[0m")
if len(out) > 1 and not dialog: if len(out) > 1 and not dialog:
message += " · o: full output" 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.feedback, message, status == 0)
self.call_from_thread(self.action_reload, True) self.call_from_thread(self.action_reload)
def feedback(self, message, ok=None): def feedback(self, message, ok=None):
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok] 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")) self.main.query_one("#feedback", Static).update(Text(icon + message, style=style, no_wrap=True, overflow="ellipsis"))
if self.feedback_timer:
self.feedback_timer.stop()
if ok is not None:
self.feedback_timer = self.set_timer(FEEDBACK_SECONDS, lambda: self.feedback(HINT))
if __name__ == "__main__": if __name__ == "__main__":
+101 -10
View File
@@ -2,6 +2,7 @@
"""Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv.""" """Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv."""
import asyncio import asyncio
import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
@@ -11,29 +12,32 @@ import proxy_tui as tui
class TuiTest(unittest.TestCase): class TuiTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.units = {"proxy-suite-socks": "active", "proxy-suite-tun": "inactive"} self.units = {"proxy-suite-tun": "inactive"}
self.zapret = { self.zapret = {
"zapret-hosts-auto.txt": ["learned.example"], "zapret-hosts-auto.txt": ["learned.example"],
"zapret-hosts-user.txt": [], "zapret-hosts-user.txt": [],
"zapret-hosts-user-exclude.txt": ["kept.example"], "zapret-hosts-user-exclude.txt": ["kept.example"],
} }
env = {"ZAPRET_AUTO_ENABLED": "1"} self.capture, self.awg, self.current = "", [], mock.Mock(return_value="")
self.env = env = {"ZAPRET_AUTO_ENABLED": "1"}
for target, name, value in [ for target, name, value in [
(tui, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}), (tui, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}),
(tui, "_capture", lambda argv: ""), (tui, "_capture", lambda argv: self.capture),
(tui, "_lines", lambda name: self.zapret[name]), (tui, "_lines", lambda name: self.zapret[name]),
(ctl, "env", lambda name, default="": env.get(name, default)), (ctl, "env", lambda name, default="": env.get(name, default)),
(ctl, "_awg_profiles", lambda: []), (ctl, "_awg_profiles", lambda: self.awg),
(ctl, "_route_mode_current", lambda: "default"), (ctl, "_route_mode_current", lambda: "default"),
(ctl, "_route_mode_effective", lambda: "whitelist"), (ctl, "_route_mode_effective", lambda: "whitelist"),
(ctl, "_outbound_inventory", lambda: {"tags": ["a", "b"], "pinned": "b", "sources": {"a": "config"}}), (ctl, "_outbound_inventory", lambda: {"tags": ["a", "b"], "pinned": "b", "sources": {"a": "config"}}),
(ctl, "_outbound_current", lambda: ""), (ctl, "_outbound_current", tui._per_load(self.current)),
(ctl, "_reputation_by_tag", lambda: {}), (ctl, "_reputation_by_tag", lambda: {}),
(ctl, "_runtime_tags", lambda kind: []), (ctl, "_runtime_tags", lambda kind: []),
(ctl, "_sub_tags", lambda: []), (ctl, "_sub_tags", lambda: []),
(ctl, "_status_outbound", lambda: "b (pinned)"), (ctl, "_status_outbound", lambda: "b (pinned)"),
(ctl, "_status_autoproxy", lambda: ""), (ctl, "_status_autoproxy", lambda: ""),
(ctl, "_status_zapret", lambda: ""), (ctl, "_status_zapret", lambda: ""),
(ctl, "svc_state", lambda unit: ""),
(ctl, "_inbound_links", lambda: [{"tag": "vless", "user": "alice", "type": "vless", "port": 443}]),
]: ]:
patcher = mock.patch.object(target, name, value) patcher = mock.patch.object(target, name, value)
patcher.start() patcher.start()
@@ -43,6 +47,15 @@ class TuiTest(unittest.TestCase):
patcher.start() patcher.start()
self.addCleanup(patcher.stop) self.addCleanup(patcher.stop)
def test_subscription_age(self):
with tempfile.NamedTemporaryFile() as cache, mock.patch.multiple(
ctl,
_sub_tags=lambda: ["s"],
_subscription_cache=lambda tag: cache.name,
_subscription_proxy_count_text=lambda path: "3",
):
self.assertEqual(tui.subscription_rows({})[0]["updated"], "0m ago")
def test_ui(self): def test_ui(self):
# Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl. # Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl.
asyncio.run(self.ui()) asyncio.run(self.ui())
@@ -61,9 +74,23 @@ class TuiTest(unittest.TestCase):
app = tui.ProxyTui() app = tui.ProxyTui()
async with app.run_test(size=(100, 30)) as pilot: async with app.run_test(size=(100, 30)) as pilot:
await self.settle(app, pilot) await self.settle(app, pilot)
self.assertEqual(list(app.tabs), ["services", "routing", "outbounds", "subs", "zapret"]) self.assertEqual(app.shown, ["services", "zapret"])
self.assertEqual(app.focused.id, "services-table") self.assertEqual(app.focused.id, "services-table")
# Tabs follow what runs: socks starting brings its tabs in.
self.units = {"proxy-suite-socks": "active", **self.units}
app.action_reload()
await self.settle(app, pilot)
self.assertEqual(app.shown, ["services", "routing", "outbounds", "subs", "zapret"])
# Stopping socks asks first: it takes tun and tproxy down too.
await pilot.press("up", "space")
await pilot.pause()
self.assertIsInstance(app.screen, tui.Confirm)
await pilot.press("n")
await pilot.pause()
self.assertEqual(self.ran, [])
# Services: space toggles the selected unit. # Services: space toggles the selected unit.
await pilot.press("down", "space") await pilot.press("down", "space")
self.assertEqual(self.ran.pop(), ["proxy", "tun", "on"]) self.assertEqual(self.ran.pop(), ["proxy", "tun", "on"])
@@ -75,6 +102,18 @@ class TuiTest(unittest.TestCase):
self.assertEqual(app.selected_key("services"), "proxy-suite-tun") self.assertEqual(app.selected_key("services"), "proxy-suite-tun")
self.assertEqual(str(app.table().get_cell("proxy-suite-tun", "state")), "● active") self.assertEqual(str(app.table().get_cell("proxy-suite-tun", "state")), "● active")
# An active AmneziaWG profile restarts on its own; a failed unit shows in the status bar.
self.awg = ["p"]
self.units[tui.AWG_PREFIX + "p"] = "active"
self.units["proxy-suite-ssh-proxy"] = "failed"
app.action_reload()
await self.settle(app, pilot)
self.assertIn("1 failed", tui.status_text(app.states))
app.table().move_cursor(row=list(app.rows["services"]).index(tui.AWG_PREFIX + "p"))
await pilot.press("ctrl+r")
self.assertEqual(self.ran.pop(), ["awg", "restart", "p"])
app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun"))
# Right arrow moves to Routing and its table has focus. # Right arrow moves to Routing and its table has focus.
await pilot.press("right") await pilot.press("right")
await self.settle(app, pilot) await self.settle(app, pilot)
@@ -92,11 +131,16 @@ class TuiTest(unittest.TestCase):
# Outbounds: letter shortcuts; the pinned row offers no pin, and nothing removes a declared one. # Outbounds: letter shortcuts; the pinned row offers no pin, and nothing removes a declared one.
await pilot.press("right") await pilot.press("right")
await self.settle(app, pilot) await self.settle(app, pilot)
await pilot.press("p", "t", "a") # One load asks the backend what it dials once, however many readers need it.
self.assertEqual(self.ran, [["proxy", "select", "a"], ["proxy", "outbounds", "test", "a"], ["proxy", "select", "auto"]]) self.current.reset_mock()
app.action_reload()
await self.settle(app, pilot)
self.assertEqual(self.current.call_count, 1)
await pilot.press("p", "t", "u")
self.assertEqual(self.ran, [["proxy", "pin", "a"], ["proxy", "outbounds", "test", "a"]])
await pilot.press("down", "p", "d", "u")
self.assertEqual(self.ran.pop(), ["proxy", "unpin"])
self.ran.clear() self.ran.clear()
await pilot.press("down", "p", "d")
self.assertEqual(self.ran, [])
await pilot.press("enter") await pilot.press("enter")
await pilot.pause() await pilot.pause()
self.assertNotIn("pin it", self.menu_labels(app)) self.assertNotIn("pin it", self.menu_labels(app))
@@ -107,10 +151,20 @@ class TuiTest(unittest.TestCase):
await pilot.press("n", *"x vless://h", "enter") await pilot.press("n", *"x vless://h", "enter")
await pilot.pause() await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "x", "vless://h"]) self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "x", "vless://h"])
# A prompt remembers what was typed into it last.
await pilot.press("n")
await pilot.pause()
self.assertEqual(app.screen.query_one(tui.Input).value, "x vless://h")
await pilot.press("escape")
# zapret: an excluded host can be included again, not forgotten. # zapret: an excluded host can be included again, not forgotten.
# Brackets in a summary are text, not markup.
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
self.capture = "Probed: [b] from [/x]\nCutoff: none on this line\n"
await pilot.press("5") await pilot.press("5")
await self.settle(app, pilot) await self.settle(app, pilot)
self.assertIn("[/x]", str(app.main.query_one("#zapret-summary").content))
await self.settle(app, pilot)
await pilot.press("down", "enter") await pilot.press("down", "enter")
await pilot.pause() await pilot.pause()
labels = self.menu_labels(app) labels = self.menu_labels(app)
@@ -127,6 +181,43 @@ class TuiTest(unittest.TestCase):
await pilot.pause() await pilot.pause()
self.assertEqual(self.ran.pop(), ["zapret", "auto", "clear"]) self.assertEqual(self.ran.pop(), ["zapret", "auto", "clear"])
# / filters the rows on any column; esc shows them all again.
await pilot.press("slash", *"learned", "enter")
await self.settle(app, pilot)
self.assertEqual(list(app.rows["zapret"]), ["learned:learned.example"])
await pilot.press("escape")
await self.settle(app, pilot)
self.assertEqual(len(app.rows["zapret"]), 2)
# Inbounds appears once enabled; c copies the share link.
self.env["INBOUNDS_ENABLED"] = "1"
app.action_reload()
await self.settle(app, pilot)
await pilot.press("6")
await self.settle(app, pilot)
await pilot.press("c")
self.assertEqual(self.ran.pop(), ["inbounds", "link", "vless", "alice"])
# A reader that dies says why in place of the rows.
with mock.patch.object(ctl, "_inbound_links", lambda: ctl.die("Share links are not readable")):
app.action_reload()
await self.settle(app, pilot)
self.assertEqual(app.rows["inbounds"], {})
self.assertIn("Share links are not readable", str(app.main.query_one("#inbounds-summary").content))
# Closing a dialog stops the command still streaming into it; c copies what it showed.
dialog = tui.Output("proxy-ctl proxy outbounds test")
dialog.proc = mock.Mock(**{"poll.return_value": None})
app.push_screen(dialog)
await pilot.pause()
dialog.write("\x1b[32mok\x1b[0m a")
with mock.patch.object(app, "copy_to_clipboard") as copy:
await pilot.press("c")
copy.assert_called_once_with("ok a")
await pilot.press("escape")
await pilot.pause()
dialog.proc.terminate.assert_called_once()
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+14 -14
View File
@@ -559,7 +559,7 @@ static void update_status(void)
} }
if (controls_core_status_label) if (controls_core_status_label)
{ {
gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] SOCKS proxy: Unknown"); gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] Proxy: Unknown");
} }
if (controls_traffic_status_label) if (controls_traffic_status_label)
{ {
@@ -575,7 +575,7 @@ static void update_status(void)
} }
if (controls_zapret_status_label) if (controls_zapret_status_label)
{ {
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown"); gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] DPI bypass: Unknown");
} }
return; return;
} }
@@ -591,7 +591,7 @@ static void update_status(void)
route_mode, route_mode,
zapret); zapret);
gchar *core_text = g_strdup_printf( gchar *core_text = g_strdup_printf(
"[Core] SOCKS proxy: %s", "[Core] Proxy: %s",
state.socks ? "Running" : "Stopped"); state.socks ? "Running" : "Stopped");
gchar *route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode); gchar *route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode);
gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic); gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic);
@@ -599,7 +599,7 @@ static void update_status(void)
"[AmneziaWG] Profile: %s", "[AmneziaWG] Profile: %s",
state.awg_active[0] != '\0' ? state.awg_active : "Off"); state.awg_active[0] != '\0' ? state.awg_active : "Off");
gchar *zapret_text = g_strdup_printf( gchar *zapret_text = g_strdup_printf(
"[Zapret] zapret-discord-youtube: %s", "[Zapret] DPI bypass: %s",
zapret); zapret);
if (state.tproxy || state.tun || state.awg_active[0] != '\0') if (state.tproxy || state.tun || state.awg_active[0] != '\0')
@@ -665,12 +665,12 @@ static void update_status(void)
if (proxy_item) if (proxy_item)
{ {
gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item), gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item),
state.socks ? "[Core] Stop SOCKS Proxy" : "[Core] Start SOCKS Proxy"); state.socks ? "[Core] Stop Proxy" : "[Core] Start Proxy");
} }
if (controls_proxy_button) if (controls_proxy_button)
{ {
gtk_button_set_label(GTK_BUTTON(controls_proxy_button), gtk_button_set_label(GTK_BUTTON(controls_proxy_button),
state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy"); state.socks ? "Stop Proxy" : "Start Proxy");
} }
if (route_mode_item) if (route_mode_item)
{ {
@@ -713,13 +713,13 @@ static void update_status(void)
{ {
gtk_menu_item_set_label( gtk_menu_item_set_label(
GTK_MENU_ITEM(zapret_item), GTK_MENU_ITEM(zapret_item),
state.zapret ? "[Zapret] Stop zapret-discord-youtube" : "[Zapret] Start zapret-discord-youtube"); state.zapret ? "[Zapret] Stop zapret" : "[Zapret] Start zapret");
} }
if (controls_zapret_button) if (controls_zapret_button)
{ {
gtk_button_set_label( gtk_button_set_label(
GTK_BUTTON(controls_zapret_button), GTK_BUTTON(controls_zapret_button),
state.zapret ? "Stop zapret-discord-youtube" : "Start zapret-discord-youtube"); state.zapret ? "Stop zapret" : "Start zapret");
} }
g_free(summary_text); g_free(summary_text);
@@ -935,11 +935,11 @@ static void build_controls_window(void)
gtk_container_add(GTK_CONTAINER(core_frame), core_box); gtk_container_add(GTK_CONTAINER(core_frame), core_box);
gtk_box_pack_start(GTK_BOX(box), core_frame, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), core_frame, FALSE, FALSE, 0);
controls_core_status_label = gtk_label_new("[Core] SOCKS proxy: Unknown"); controls_core_status_label = gtk_label_new("[Core] Proxy: Unknown");
gtk_label_set_xalign(GTK_LABEL(controls_core_status_label), 0.0f); gtk_label_set_xalign(GTK_LABEL(controls_core_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(core_box), controls_core_status_label, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(core_box), controls_core_status_label, FALSE, FALSE, 0);
controls_proxy_button = gtk_button_new_with_label("Start SOCKS Proxy"); controls_proxy_button = gtk_button_new_with_label("Start Proxy");
g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL); g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL);
gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0);
@@ -1018,11 +1018,11 @@ static void build_controls_window(void)
gtk_container_add(GTK_CONTAINER(zapret_frame), zapret_box); gtk_container_add(GTK_CONTAINER(zapret_frame), zapret_box);
gtk_box_pack_start(GTK_BOX(box), zapret_frame, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), zapret_frame, FALSE, FALSE, 0);
controls_zapret_status_label = gtk_label_new("[Zapret] zapret-discord-youtube: Unknown"); controls_zapret_status_label = gtk_label_new("[Zapret] DPI bypass: Unknown");
gtk_label_set_xalign(GTK_LABEL(controls_zapret_status_label), 0.0f); gtk_label_set_xalign(GTK_LABEL(controls_zapret_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_status_label, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_status_label, FALSE, FALSE, 0);
controls_zapret_button = gtk_button_new_with_label("Start zapret-discord-youtube"); controls_zapret_button = gtk_button_new_with_label("Start zapret");
g_signal_connect(controls_zapret_button, "clicked", G_CALLBACK(on_zapret_toggle), NULL); g_signal_connect(controls_zapret_button, "clicked", G_CALLBACK(on_zapret_toggle), NULL);
gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_button, FALSE, FALSE, 0);
} }
@@ -1066,7 +1066,7 @@ static void build_menu(void)
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
proxy_item = gtk_menu_item_new_with_label("[Core] Start SOCKS Proxy"); proxy_item = gtk_menu_item_new_with_label("[Core] Start Proxy");
g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL); g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item);
@@ -1152,7 +1152,7 @@ static void build_menu(void)
{ {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret-discord-youtube"); zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret");
g_signal_connect(zapret_item, "activate", G_CALLBACK(on_zapret_toggle), NULL); g_signal_connect(zapret_item, "activate", G_CALLBACK(on_zapret_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item);
} }