From 2255e1f9f07bd6252f288bcaae3d37364749c433 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Sat, 26 Sep 2026 18:35:32 +0500 Subject: [PATCH] fix: behavior and docs fixes --- docs/options/index.md | 3 + docs/options/zapret.md | 14 +++- .../usage/.snippets/examples-multi-exit-1.nix | 13 ++-- .../.snippets/examples-private-vpn-1.nix | 4 +- .../.snippets/examples-relay-server-1.nix | 3 +- .../.snippets/examples-workstation-1.nix | 4 +- docs/usage/.snippets/server-1.nix | 2 +- docs/usage/.snippets/wrap-apps-1.nix | 2 +- docs/usage/.snippets/zapret-3.nix | 15 +++++ docs/usage/control.md | 1 - docs/usage/examples/multi-exit.md | 52 ++++++++++----- docs/usage/examples/private-vpn.md | 10 ++- docs/usage/examples/relay-server.md | 3 +- docs/usage/examples/workstation.md | 6 +- docs/usage/per-app.md | 5 +- docs/usage/server.md | 2 +- docs/usage/system-wide.md | 3 +- docs/usage/whitelist-bypass.md | 2 +- docs/usage/wrap-apps.md | 2 +- docs/usage/zapret.md | 30 ++++++++- modules/proxy-suite/core.nix | 54 +++++++-------- modules/proxy-suite/derived.nix | 10 +-- modules/proxy-suite/options/zapret.nix | 8 ++- modules/proxy-suite/rules-zapret-direct.nix | 8 ++- modules/proxy-suite/service-assertions.nix | 10 ++- modules/proxy-suite/service/control.nix | 4 +- .../service/per-app-routing/profiles.nix | 2 +- .../script-blocks/hybrid-runtime-helpers.nix | 66 ++++++++++++------- modules/proxy-suite/service/start-scripts.nix | 12 ++-- modules/proxy-suite/zapret.nix | 7 +- modules/proxy-suite/zapret2.nix | 8 ++- modules/proxy-suite/zapret2/cutoff.nix | 8 ++- nix/checks/hybrid-backend.nix | 14 ++-- nix/checks/per-app-routing-tproxy.nix | 3 +- nix/checks/per-app-routing-tun.nix | 3 +- .../per-app-routing-validation-profiles.nix | 23 ++++--- nix/checks/per-app-routing-zapret.nix | 5 +- nix/checks/proxy-inbounds-runtime.nix | 3 +- nix/checks/zapret-hostlist-routing.nix | 6 ++ .../zapret-hostlist-routing/fixtures.nix | 19 ++++++ pkgs/proxy-ctl/proxy_ctl.py | 18 +++-- pkgs/proxy-ctl/test_proxy_ctl.py | 14 ++-- 42 files changed, 320 insertions(+), 161 deletions(-) create mode 100644 docs/usage/.snippets/zapret-3.nix diff --git a/docs/options/index.md b/docs/options/index.md index 7f48eee..8977685 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -336,6 +336,9 @@ services.proxy-suite = { }; enable = false; engine = "zapret-discord-youtube"; + global = { + enable = true; + }; zapret-discord-youtube = { configName = "general(ALT)"; domains = [ ]; diff --git a/docs/options/zapret.md b/docs/options/zapret.md index 9a4bee1..e6d6c67 100644 --- a/docs/options/zapret.md +++ b/docs/options/zapret.md @@ -16,6 +16,8 @@ Part of the [proxy-suite options reference](./index.md). - [upstreamIps](#services-proxy-suite-zapret-directsync-upstreamips) - [userIps](#services-proxy-suite-zapret-directsync-userips) - [engine](#services-proxy-suite-zapret-engine) + - global + - [enable](#services-proxy-suite-zapret-global-enable) - zapret-discord-youtube - [configName](#services-proxy-suite-zapret-zapret-discord-youtube-configname) - [domains](#services-proxy-suite-zapret-zapret-discord-youtube-domains) @@ -63,7 +65,7 @@ Part of the [proxy-suite options reference](./index.md). ## services\.proxy-suite\.zapret\.enable -Whether to enable zapret DPI bypass\. +Whether to enable zapret DPI bypass\. Needed by ` perAppRouting.zapret ` too\. **Type:** boolean\ **Default:** `false` @@ -121,6 +123,16 @@ Which zapret to run: **Default:** `"zapret-discord-youtube"`\ **Example:** `"zapret2"` + +## services\.proxy-suite\.zapret\.global\.enable + +Run zapret system-wide\. Turn off to keep zapret to apps started with +` proxy-ctl apps run zapret ` (` perAppRouting.zapret `); ` directSync `, ` cidrExemption ` and +zapret2’s learned sites then do nothing\. + +**Type:** boolean\ +**Default:** `true` + ## services\.proxy-suite\.zapret\.zapret-discord-youtube\.configName diff --git a/docs/usage/.snippets/examples-multi-exit-1.nix b/docs/usage/.snippets/examples-multi-exit-1.nix index 483da70..fc93d60 100644 --- a/docs/usage/.snippets/examples-multi-exit-1.nix +++ b/docs/usage/.snippets/examples-multi-exit-1.nix @@ -30,10 +30,10 @@ in routing = { # Unlisted sites leave directly, where zapret2 unblocks what DPI blocks. default = "direct"; - # Russian sites are routed by the last rule below instead. + # Russian sites go to WARP by the last rule below instead. directRu = false; - # Checked in order; the first match wins. + # Checked in order, before the lists; the first match wins. rules = [ { outbound = "ssh-proxy"; @@ -43,7 +43,7 @@ in outbound = "warp"; geosites = [ "youtube" ]; } - # To mask your IP from Russian services + # Russian services see WARP's address instead of this host's. { outbound = "warp"; geosites = [ "category-ru" ]; @@ -60,8 +60,8 @@ in }; }; - # For blocked sites no list names yet. YouTube is pinned to WARP above, so it - # is kept out of the probes. + # For blocked sites no list names yet. YouTube already has its rule, so its video + # hosts are not worth probing. autoProxy = { enable = true; exclude = [ "googlevideo.com" "gvt1.com" ]; @@ -85,7 +85,8 @@ in hostKeyFile = "/run/secrets/proxy-ssh-known-hosts"; }; - # Tor through the proxy, since this network blocks Tor. + # .onion names go to Tor without a rule. Tor is blocked here, so it connects + # through the proxy. tor = { enable = true; asOutbound = true; diff --git a/docs/usage/.snippets/examples-private-vpn-1.nix b/docs/usage/.snippets/examples-private-vpn-1.nix index 33da723..6d84da5 100644 --- a/docs/usage/.snippets/examples-private-vpn-1.nix +++ b/docs/usage/.snippets/examples-private-vpn-1.nix @@ -18,8 +18,8 @@ in listeners.vpn = { type = "amneziawg"; port = 51820; - # Fixed addresses, so firewall rules and DNS can name each device. Keys are - # generated on first start. + # Fixed addresses, so firewall rules and DNS can name each device. + # Keys are generated on first start. users = [ { name = "laptop"; address = "10.77.77.2"; } { name = "phone"; address = "10.77.77.3"; } diff --git a/docs/usage/.snippets/examples-relay-server-1.nix b/docs/usage/.snippets/examples-relay-server-1.nix index 6a064ae..c8b850c 100644 --- a/docs/usage/.snippets/examples-relay-server-1.nix +++ b/docs/usage/.snippets/examples-relay-server-1.nix @@ -25,8 +25,7 @@ let sharePort = 443; # share links name nginx's port, not the listener's transport = extra // { inherit path; - # nginx sets this header, so XRay sees each client's real address (for - # `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it. + # nginx sets this header, so XRay sees each client's real address (for `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it. trustedXForwardedFor = [ "X-Real-IP" ]; }; inherit tls; diff --git a/docs/usage/.snippets/examples-workstation-1.nix b/docs/usage/.snippets/examples-workstation-1.nix index ecf166d..c54a51f 100644 --- a/docs/usage/.snippets/examples-workstation-1.nix +++ b/docs/usage/.snippets/examples-workstation-1.nix @@ -8,6 +8,8 @@ in proxy = { enable = true; + # Support all available protocols by enabling hybrid backend. + backend = "hybrid"; # The server's subscription: every listener, each a separate outbound. subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ]; # The fastest listener that gets through the current network. @@ -16,7 +18,7 @@ in routing.default = "direct"; autoProxy.enable = true; - tun.enable = true; # when everything should go through: proxy-ctl proxy tun on + tun.enable = true; # when everything should go through: `proxy-ctl proxy tun on` }; zapret = { diff --git a/docs/usage/.snippets/server-1.nix b/docs/usage/.snippets/server-1.nix index def3b67..21f67fb 100644 --- a/docs/usage/.snippets/server-1.nix +++ b/docs/usage/.snippets/server-1.nix @@ -19,7 +19,7 @@ enable = true; serverNames = [ "www.microsoft.com" ]; privateKeyFile = "/run/secrets/reality-private-key"; - publicKey = "jNXH…"; # from the same `xray x25519` run + publicKey = "jNXH…"; # both keys from `xray x25519` shortIds = [ "0123abcd" ]; }; }; diff --git a/docs/usage/.snippets/wrap-apps-1.nix b/docs/usage/.snippets/wrap-apps-1.nix index b611c35..e26d836 100644 --- a/docs/usage/.snippets/wrap-apps-1.nix +++ b/docs/usage/.snippets/wrap-apps-1.nix @@ -19,7 +19,7 @@ in environment.systemPackages = [ (proxySuite.wrapEnv { } pkgs.yt-dlp) - (proxySuite.wrapProxychains { } pkgs.telegram-desktop) + (proxySuite.wrapProxychains { } pkgs.curl) (proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox) ]; diff --git a/docs/usage/.snippets/zapret-3.nix b/docs/usage/.snippets/zapret-3.nix new file mode 100644 index 0000000..5d3622b --- /dev/null +++ b/docs/usage/.snippets/zapret-3.nix @@ -0,0 +1,15 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite = { + enable = true; + zapret = { + enable = true; + global.enable = false; # no system-wide zapret + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; # adds a profile named "zapret" + zapret.enable = true; + }; +}; +} diff --git a/docs/usage/control.md b/docs/usage/control.md index b254544..71b97c2 100644 --- a/docs/usage/control.md +++ b/docs/usage/control.md @@ -64,7 +64,6 @@ proxy-ctl status # everything at a glance proxy-ctl status --json # the same, for scripts proxy-ctl logs # follow the logs of every proxy-suite service proxy-ctl restart # restart what is running -proxy-ctl where example.com ``` ## See also diff --git a/docs/usage/examples/multi-exit.md b/docs/usage/examples/multi-exit.md index 40003ea..463097a 100644 --- a/docs/usage/examples/multi-exit.md +++ b/docs/usage/examples/multi-exit.md @@ -1,8 +1,18 @@ # Example: several exits, picked per site -One host with four ways out: direct (with zapret2 for DPI), a VPS, WARP and an SSH server. -Each site goes to whichever works best for it, and autoProxy covers the sites nobody -listed. Everything runs in global TUN mode, so every app on the host follows these rules. +A host in Russia with five ways out: direct (with zapret2 for DPI), a VPS, WARP, an SSH +server and Tor. Each site goes to whichever works best for it, and autoProxy covers the +sites nobody listed. On a [relay server](./relay-server.md), its clients get the same +choice, with a few differences shown below. + +| Exit | Tag | Gets | +|---|---|---| +| This host, with zapret2 | `direct` | Everything not listed below | +| The VPS | `primary`, as the selected `proxy` | AI services, Telegram, Netflix, WARP's registration | +| The SSH server | `ssh-proxy` | pixiv, Twitter | +| WARP | `warp` | YouTube, Russian sites | +| Tor | `tor` | `.onion` names | +| Whichever reaches it first | set by autoProxy | Blocked sites no list names | ```nix { ... }: @@ -37,10 +47,10 @@ in routing = { # Unlisted sites leave directly, where zapret2 unblocks what DPI blocks. default = "direct"; - # Russian sites are routed by the last rule below instead. + # Russian sites go to WARP by the last rule below instead. directRu = false; - # Checked in order; the first match wins. + # Checked in order, before the lists; the first match wins. rules = [ { outbound = "ssh-proxy"; @@ -50,7 +60,7 @@ in outbound = "warp"; geosites = [ "youtube" ]; } - # To mask your IP from Russian services + # Russian services see WARP's address instead of this host's. { outbound = "warp"; geosites = [ "category-ru" ]; @@ -67,7 +77,8 @@ in }; }; - # For blocked sites no list names yet. YouTube is pinned to WARP above, so it is kept out of the probes. + # For blocked sites no list names yet. YouTube already has its rule, so its video + # hosts are not worth probing. autoProxy = { enable = true; exclude = [ "googlevideo.com" "gvt1.com" ]; @@ -91,6 +102,14 @@ in hostKeyFile = "/run/secrets/proxy-ssh-known-hosts"; }; + # .onion names go to Tor without a rule. Tor is blocked here, so it connects + # through the proxy. + tor = { + enable = true; + asOutbound = true; + upstream = "proxy"; + }; + zapret = { enable = true; engine = "zapret2"; @@ -103,6 +122,7 @@ in ```sh proxy-ctl where youtube.com # -> warp, by the rule for youtube +proxy-ctl where pixiv.net # -> ssh-proxy, by the first rule proxy-ctl where chatgpt.com # -> proxy -> primary, by geosite openai proxy-ctl proxy auto # what autoProxy routed, and through which exit proxy-ctl zapret auto # what zapret2 learned @@ -110,24 +130,25 @@ proxy-ctl zapret auto # what zapret2 learned ## With relay clients -On a [relay server](./relay-server.md) with `inbounds.routing.via = "proxy"`, clients follow -these rules too, with two exceptions. Russian sites are blocked for them (`blockRu`), and -sites on zapret's list go straight out, so this host's zapret handles them (`zapretDirect`). -Sites listed in `inbounds.routing.proxy` skip both exceptions and go to the rules above: +With `inbounds.routing.via = "proxy"`, relay clients go through the routing above. Two +checks come first by default: Russian sites are blocked for them (`blockRu`), and sites on +zapret's list leave directly, so this host's zapret handles them (`zapretDirect`). Sites in +`inbounds.routing.proxy` skip both and reach the rules above: ```nix no-check services.proxy-suite.inbounds.routing = { via = "proxy"; - blockRu = false; # clients may reach Russian sites, through WARP by the rule above + blockRu = false; # clients reach Russian sites too, through WARP by the rule above proxy = { - domains = youtubeDomains; # on zapret's list, but WARP works better here + # YouTube is on zapret's list, but WARP works better for it. geosites = [ "youtube" "category-ru" ]; geoips = [ "ru" ]; }; }; ``` -The same list applies to listeners with their own `via`, including `"direct"` ones. +`inbounds.routing.proxy` covers listeners with their own `via` too, `"direct"` ones +included, so their YouTube and Russian sites also go through WARP. ## Notes @@ -135,4 +156,5 @@ The same list applies to listeners with their own `via`, including `"direct"` on country). - Rules can name any outbound tag: yours, `warp`, `ssh-proxy`, `tor`, or an AmneziaWG outbound. -- `.onion` names go to Tor without a rule. +- Selection and autoProxy skip `tor`; it gets only `.onion` names and what rules send to it. +- See [Chain proxies and add exits](../chains.md) for each kind of exit on its own. diff --git a/docs/usage/examples/private-vpn.md b/docs/usage/examples/private-vpn.md index 069a1a8..09a86df 100644 --- a/docs/usage/examples/private-vpn.md +++ b/docs/usage/examples/private-vpn.md @@ -29,8 +29,8 @@ in listeners.vpn = { type = "amneziawg"; port = 51820; - # Fixed addresses, so firewall rules and DNS can name each device. Keys are - # generated on first start. + # Fixed addresses, so firewall rules and DNS can name each device. + # Keys are generated on first start. users = [ { name = "laptop"; address = "10.77.77.2"; } { name = "phone"; address = "10.77.77.3"; } @@ -84,8 +84,6 @@ On a laptop that also runs proxy-suite, the `.conf` becomes a profile: see ## Notes -- `mode = "lan"` turns on IP forwarding. The default, `"proxy"`, gives devices the - internet only, like the other listeners. +- `mode = "lan"` turns on IP forwarding. The default, `"proxy"`, gives devices the internet only, like the other listeners. - Only TCP and UDP reach the internet; ping and other protocols stop at the server. -- A device that keeps its own private key can be added with `users.*.publicKey` instead; - it gets no generated config. +- A device that keeps its own private key can be added with `users.*.publicKey` instead; it gets no generated config. diff --git a/docs/usage/examples/relay-server.md b/docs/usage/examples/relay-server.md index e5c3a09..1f7e1f3 100644 --- a/docs/usage/examples/relay-server.md +++ b/docs/usage/examples/relay-server.md @@ -45,8 +45,7 @@ let sharePort = 443; # share links name nginx's port, not the listener's transport = extra // { inherit path; - # nginx sets this header, so XRay sees each client's real address (for - # `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it. + # nginx sets this header, so XRay sees each client's real address (for `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it. trustedXForwardedFor = [ "X-Real-IP" ]; }; inherit tls; diff --git a/docs/usage/examples/workstation.md b/docs/usage/examples/workstation.md index 4b6d53e..0ba183f 100644 --- a/docs/usage/examples/workstation.md +++ b/docs/usage/examples/workstation.md @@ -16,6 +16,8 @@ in proxy = { enable = true; + # Support all available protocols by enabling hybrid backend. + backend = "hybrid"; # The server's subscription: every listener, each a separate outbound. subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ]; # The fastest listener that gets through the current network. @@ -24,7 +26,7 @@ in routing.default = "direct"; autoProxy.enable = true; - tun.enable = true; # when everything should go through: proxy-ctl proxy tun on + tun.enable = true; # when everything should go through: `proxy-ctl proxy tun on` }; zapret = { @@ -84,7 +86,7 @@ The tray app shows the same, and switches with a click. do not know. - The kill switch guards whichever global tunnel is on (TUN or the VPN), and does nothing while both are off. -- Per-app `tun` profiles refuse to start while global TUN is on. Everything already goes +- While global TUN is on, per-app `tun` profiles run the app as it is. Everything already goes through the proxy then. - See [Wrap programs with the proxy](../wrap-apps.md) for the helpers, and [Keep secrets out of the Nix store](../secrets.md) for the files under `/run/secrets`. diff --git a/docs/usage/per-app.md b/docs/usage/per-app.md index dc893c6..cbe0e93 100644 --- a/docs/usage/per-app.md +++ b/docs/usage/per-app.md @@ -38,7 +38,7 @@ Run it as yourself, not with sudo. | `proxychains` | TCP | Preloads a library into the app. Needs no privileges, but does not work with statically linked programs or most Go programs. | | `tun` | TCP and UDP | Puts the app in its own cgroup and routes it into a separate TUN. Works with any program. | | `tproxy` | TCP and UDP | Like `tun`, but intercepts with nftables. | -| `zapret` | What zapret handles | No proxy: runs a separate zapret for the app, to get past DPI. | +| `zapret` | What zapret handles | No proxy: runs a separate zapret for the app, to get past DPI. Needs `zapret.enable`; see [Unblock sites without a server](./zapret.md). | `tun` works with any program. `proxychains` is handy for a quick command. @@ -68,7 +68,8 @@ Then run `proxy-ctl apps run browser -- chromium`. - `tun`, `tproxy` and `zapret` profiles start a system service, so they ask for an admin password unless `userControl` grants the `perApp` scope (see [Control it day to day](./control.md)). -- These three refuse to start while a global TUN or TProxy is running. +- While a global TUN or TProxy is running, these three run the app without their route: + the global mode already carries its traffic. `proxy-ctl` prints a note when it does. - If `/etc/resolv.conf` points only at a local resolver (such as systemd-resolved on 127.0.0.53), the app's DNS queries skip its route. `proxy-ctl` warns about this. - The app follows your [routing rules](./routing.md) like any other proxied traffic. diff --git a/docs/usage/server.md b/docs/usage/server.md index 4227631..de31258 100644 --- a/docs/usage/server.md +++ b/docs/usage/server.md @@ -41,7 +41,7 @@ services.proxy-suite = { enable = true; serverNames = [ "www.microsoft.com" ]; privateKeyFile = "/run/secrets/reality-private-key"; - publicKey = "jNXH…"; # from the same `xray x25519` run + publicKey = "jNXH…"; # both keys from `xray x25519` shortIds = [ "0123abcd" ]; }; }; diff --git a/docs/usage/system-wide.md b/docs/usage/system-wide.md index 422dd9e..a0b3506 100644 --- a/docs/usage/system-wide.md +++ b/docs/usage/system-wide.md @@ -50,7 +50,8 @@ proxy-ctl killswitch off # lift the kill switch without stopping the tunnel direct IPv6 connections hang instead of falling back to IPv4. - `proxy.tproxy.localSubnets` lists networks that skip TProxy. Add your LAN and VM bridges if they are not in `192.168.0.0/16`. -- Per-app `tun`, `tproxy` and `zapret` profiles refuse to start while a global mode is on. +- While a global mode is on, per-app `tun`, `tproxy` and `zapret` profiles run the app + without their route, so wrapped programs still start. ## See also diff --git a/docs/usage/whitelist-bypass.md b/docs/usage/whitelist-bypass.md index 466dadc..016ed2d 100644 --- a/docs/usage/whitelist-bypass.md +++ b/docs/usage/whitelist-bypass.md @@ -31,7 +31,7 @@ services.proxy-suite = { }; ``` -The cookies come from the upstream desktop Creator app. They are read on first start, and +The cookies come from the upstream desktop Creator app or a browser. They are read on first start, and the login refreshes itself after that. `proxy-ctl wl auth laptop` replaces them at runtime, and asks for an email and password instead on DION and Bitrix. diff --git a/docs/usage/wrap-apps.md b/docs/usage/wrap-apps.md index 984dd16..231857a 100644 --- a/docs/usage/wrap-apps.md +++ b/docs/usage/wrap-apps.md @@ -35,7 +35,7 @@ in environment.systemPackages = [ (proxySuite.wrapEnv { } pkgs.yt-dlp) - (proxySuite.wrapProxychains { } pkgs.telegram-desktop) + (proxySuite.wrapProxychains { } pkgs.curl) (proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox) ]; diff --git a/docs/usage/zapret.md b/docs/usage/zapret.md index bce86aa..b14019e 100644 --- a/docs/usage/zapret.md +++ b/docs/usage/zapret.md @@ -41,8 +41,8 @@ services.proxy-suite = { }; ``` -`zapret2.strategySource = "z2k"` switches to z2k's strategies and site lists, which include -the full RKN list and use more memory. It also turns on a workaround for ISPs that cut +`zapret2.strategySource = "z2k"` switches to z2k's strategies and site lists, which includes +the full RKN list and uses more memory. It also turns on a workaround for ISPs that cut TLS to some hosting networks after about 16 KB. ## Commands @@ -63,7 +63,30 @@ zapret and the proxy work side by side. By default (`zapret.directSync`), the si handles are sent direct, so they skip the proxy and reach zapret. Everything else follows your [routing rules](./routing.md). -To use zapret for a single app only, see [Route a single app](./per-app.md). +## Only for some apps + +To leave the rest of the system alone, turn the system-wide zapret off and run apps through +it one by one: + +```nix +services.proxy-suite = { + enable = true; + zapret = { + enable = true; + global.enable = false; # no system-wide zapret + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; # adds a profile named "zapret" + zapret.enable = true; + }; +}; +``` + +Then run `proxy-ctl apps run zapret -- firefox`. The app gets zapret's strategy for every +site, not only the listed ones. `directSync`, `cidrExemption` and the sites zapret2 learns +belong to the system-wide zapret, so they do nothing here. See +[Route a single app](./per-app.md) for more. ## Good to know @@ -74,6 +97,7 @@ To use zapret for a single app only, see [Route a single app](./per-app.md). ## See also - [`zapret.engine`](../options/zapret.md#services-proxy-suite-zapret-engine) +- [`zapret.global.enable`](../options/zapret.md#services-proxy-suite-zapret-global-enable) - [`zapret-discord-youtube.configName`](../options/zapret.md#services-proxy-suite-zapret-zapret-discord-youtube-configname) - [`zapret2.strategySource`](../options/zapret.md#services-proxy-suite-zapret-zapret2-strategysource) - [`zapret.directSync`](../options/zapret.md#services-proxy-suite-zapret-directsync-enable) diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index e2f35a2..db81508 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -94,38 +94,30 @@ in inherit (assembly) context; }) - (lib.mkIf - ( - cfg.zapret.engine == "zapret-discord-youtube" - && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable) - ) - ( - import ./zapret.nix { - inherit - lib - pkgs - cfg - zapret - ; - inherit (nftr) perAppZapretRulesFile nft; - } - ) - ) + (lib.mkIf (cfg.zapret.engine == "zapret-discord-youtube" && cfg.zapret.enable) ( + import ./zapret.nix { + inherit + lib + pkgs + cfg + zapret + ; + inherit (nftr) perAppZapretRulesFile nft; + } + )) - (lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) - ( - import ./zapret2.nix { - inherit - lib - pkgs - cfg - packages - ; - inherit (nftr) perAppZapretRulesFile nft; - zapret2Sources = { inherit nfqws2-keenetic z2k; }; - } - ) - ) + (lib.mkIf (cfg.zapret.engine == "zapret2" && cfg.zapret.enable) ( + import ./zapret2.nix { + inherit + lib + pkgs + cfg + packages + ; + inherit (nftr) perAppZapretRulesFile nft; + zapret2Sources = { inherit nfqws2-keenetic z2k; }; + } + )) (lib.mkIf cfg.tgWsProxy.enable ( (import ./tg-ws-proxy.nix { diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 594ab12..55fbd07 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -321,10 +321,10 @@ let # Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode. clashApiEnabled = singBoxEnabled; perAppZapretEnabled = perAppZapretCfg.enable; + # The system-wide instance; per-app zapret runs its own. + zapretGlobalEnabled = zapretCfg.enable && zapretCfg.global.enable; zapretCutoffEnabled = - zapretEngine == "zapret2" - && (zapretCfg.enable || perAppZapretEnabled) - && zapretCfg.zapret2.cutoff.enable; + zapretEngine == "zapret2" && zapretCfg.enable && zapretCfg.zapret2.cutoff.enable; # The cut-off networks no whitelisted name fixes go through the proxy outbound. zapretCutoffProxyFallback = zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds; @@ -464,7 +464,8 @@ let perAppTun = 18535; }; - xraySidecarBasePorts = { + # One loopback VLESS inbound per stack's XRay sidecar, however many outbounds it carries. + xraySidecarPorts = { socks = 33080; tun = 33180; perAppTun = 33280; @@ -509,6 +510,7 @@ in zapretEngine perAppZapretCfg perAppZapretEnabled + zapretGlobalEnabled zapretCutoffEnabled zapretCutoffProxyFallback userControlCfg diff --git a/modules/proxy-suite/options/zapret.nix b/modules/proxy-suite/options/zapret.nix index 7dbe477..be816c0 100644 --- a/modules/proxy-suite/options/zapret.nix +++ b/modules/proxy-suite/options/zapret.nix @@ -7,7 +7,13 @@ let in { options.services.proxy-suite.zapret = { - enable = mkEnableOption "zapret DPI bypass"; + enable = mkEnableOption "zapret DPI bypass. Needed by `perAppRouting.zapret` too"; + + global.enable = bool true '' + Run zapret system-wide. Turn off to keep zapret to apps started with + `proxy-ctl apps run zapret` (`perAppRouting.zapret`); `directSync`, `cidrExemption` and + zapret2's learned sites then do nothing. + ''; engine = mkOption { type = types.enum [ diff --git a/modules/proxy-suite/rules-zapret-direct.nix b/modules/proxy-suite/rules-zapret-direct.nix index a324c9f..dc68f22 100644 --- a/modules/proxy-suite/rules-zapret-direct.nix +++ b/modules/proxy-suite/rules-zapret-direct.nix @@ -25,9 +25,11 @@ let subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items; - syncZapretDirectDomains = zapretCfg.enable && zapretCfg.directSync.enable; - syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.directSync.upstreamIps; - syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.directSync.userIps; + # Only the system-wide instance handles traffic the proxy would send direct. + globalEnabled = zapretCfg.enable && zapretCfg.global.enable; + syncZapretDirectDomains = globalEnabled && zapretCfg.directSync.enable; + syncZapretDirectUpstreamIps = globalEnabled && zapretCfg.directSync.upstreamIps; + syncZapretDirectUserIps = globalEnabled && zapretCfg.directSync.userIps; syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps; zapretDefaultDomainFiles = [ diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index f90e354..a4a7ca2 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -69,6 +69,7 @@ let reservedLoopbackPorts = builtins.attrValues constants.xrayDnsBridgePorts ++ [ constants.outboundTestPort ] + ++ lib.optionals hybridEnabled (builtins.attrValues constants.xraySidecarPorts) ++ lib.optionals derived.warpOutboundEnabled [ derived.warpCfg.tunnelPort derived.warpCfg.directPort @@ -334,6 +335,9 @@ let (requires perAppZapretCfg.enable perAppRoutingCfg.enable "perAppRouting.zapret.enable" "perAppRouting.enable" ) + (mkAssertion (!perAppZapretCfg.enable || zapretCfg.enable) '' + proxy-suite: perAppRouting.zapret.enable requires zapret.enable = true. For per-app zapret + alone, also set zapret.global.enable = false.'') (requires hasZapretProfiles perAppZapretCfg.enable "route=zapret in perAppRouting.profiles" "perAppRouting.zapret.enable" ) @@ -455,9 +459,10 @@ let || !lib.any (port: builtins.elem port derived.proxyInboundPorts) ( map (listener: listener.internalPort) derived.proxyInboundsAwg ++ builtins.attrValues derived.constants.xrayDnsBridgePorts + ++ lib.optionals hybridEnabled (builtins.attrValues derived.constants.xraySidecarPorts) ) ) - "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, or 18533-18535)" + "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)" ) # The prober opens one loopback listener per exit from probeBasePort; the WARP # and AmneziaWG tunnels open two each from their own bases. They all bind @@ -858,7 +863,8 @@ let (distinct perAppTunWithTproxy perAppRoutingTun.routeTable globalTproxy.routeTable "perAppRouting.tun.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled" ) - (distinct (perAppZapretCfg.enable && zapretCfg.enable) perAppZapretCfg.qnum globalZapretQnum + (distinct (perAppZapretCfg.enable && derived.zapretGlobalEnabled) perAppZapretCfg.qnum + globalZapretQnum "perAppRouting.zapret.qnum must differ from the global zapret instance's NFQUEUE ${toString globalZapretQnum}" ) (distinct perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark globalTproxy.fwmark diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 3f22e0b..7e72e14 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -14,6 +14,7 @@ let perAppRoutingTproxy perAppZapretCfg zapretEngine + zapretGlobalEnabled zapretCutoffEnabled constants selectionMode @@ -100,7 +101,8 @@ in INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile; INBOUNDS_SUB_BASE_URL = if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; - ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2"); + # Only the system-wide instance reads the site lists; per-app zapret handles all traffic. + ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled); ZAPRET_STATE_DIR = constants.zapret2StateDir; ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled; OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile; diff --git a/modules/proxy-suite/service/per-app-routing/profiles.nix b/modules/proxy-suite/service/per-app-routing/profiles.nix index 271efbe..dc6c7aa 100644 --- a/modules/proxy-suite/service/per-app-routing/profiles.nix +++ b/modules/proxy-suite/service/per-app-routing/profiles.nix @@ -15,7 +15,7 @@ let inherit (constants) runtimeDir; perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles; defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles ( - [ + lib.optionals perAppRoutingCfg.proxychains.enable [ { name = "proxychains"; route = "proxychains"; diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix index aad9997..1da7d77 100644 --- a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix @@ -9,14 +9,18 @@ let ; in -routingMark: xraySidecarBasePort: xrayDnsBridgePort: +routingMark: xraySidecarPort: xrayDnsBridgePort: lib.optionalString hybridEnabled '' XRAY_OUTBOUNDS_JSON='[]' - XRAY_INBOUNDS_JSON='[]' + XRAY_CLIENTS_JSON='[]' XRAY_ROUTE_RULES_JSON='[]' - XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort} + XRAY_SIDECAR_PORT=${toString xraySidecarPort} XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort} + # Client ids: this run's random prefix plus a counter, so every sidecar outbound has its + # own and no other local user can guess one. + XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid) + XRAY_SIDECAR_NEXT_ID=0 _proxy_suite_add_sing_box_ob() { local ob="$1" @@ -24,37 +28,42 @@ lib.optionalString hybridEnabled '' } # $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a - # loopback SOCKS inbound on the sidecar and stands in sing-box as a hop to it. + # client on the sidecar's one loopback VLESS inbound, routed to it by its email, and + # stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream + # (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by. _proxy_suite_add_xray_sidecar_obs() { local batch batch=$(${jq} -c \ - --argjson base "$XRAY_SIDECAR_NEXT_PORT" \ + --argjson next "$XRAY_SIDECAR_NEXT_ID" \ + --arg secret "$XRAY_SIDECAR_SECRET" \ + --argjson port "$XRAY_SIDECAR_PORT" \ --argjson mark ${ if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark } ' + def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add; to_entries | map( - ($base + .key) as $port - | ("proxy-suite-xray-" + ($port | tostring)) as $auth + ($secret[:24] + ($next + .key | hex12)) as $id | .value.tag as $tag | {outbound: (.value ${lib.optionalString ( xraySidecarRoutingMark != null ) "| .streamSettings.sockopt.mark = $mark"} | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")), - inbound: {tag: ($tag + "-inbound"), listen: "127.0.0.1", port: $port, protocol: "socks", - settings: {auth: "password", udp: true, accounts: [{user: $auth, pass: $auth}]}}, - rule: {type: "field", inboundTag: [$tag + "-inbound"], outboundTag: $tag}, - hop: ({type: "socks", tag: $tag, server: "127.0.0.1", server_port: $port, version: "5", - username: $auth, password: $auth}${ + client: {id: $id, email: $tag}, + rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag}, + hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id, + packet_encoding: "xudp"}${ lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}" })}) - | {outbounds: map(.outbound), inbounds: map(.inbound), rules: map(.rule), hops: map(.hop)} + | {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)} ' <<< "$1") - XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + $(${jq} '.outbounds | length' <<< "$batch"))) - XRAY_OUTBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.outbounds' <<< "$XRAY_OUTBOUNDS_JSON") - XRAY_INBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.inbounds' <<< "$XRAY_INBOUNDS_JSON") - XRAY_ROUTE_RULES_JSON=$(${jq} -c --argjson b "$batch" '. + $b.rules' <<< "$XRAY_ROUTE_RULES_JSON") - OUTBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.hops' <<< "$OUTBOUNDS_JSON") + XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(${jq} '.outbounds | length' <<< "$batch"))) + # Through a file, not --argjson: a big subscription's batch outgrows the kernel's + # 128 KiB limit on one argument. + XRAY_OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON") + XRAY_CLIENTS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON") + XRAY_ROUTE_RULES_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON") + OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON") } # $1 one XRay outbound, $2 its tag. @@ -69,9 +78,10 @@ lib.optionalString hybridEnabled '' ${jq} -n \ --arg loglevel "$XRAY_LOGLEVEL" \ --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ - --argjson inbounds "$XRAY_INBOUNDS_JSON" \ - --argjson outbounds "$XRAY_OUTBOUNDS_JSON" \ - --argjson route_rules "$XRAY_ROUTE_RULES_JSON" \ + --argjson port "$XRAY_SIDECAR_PORT" \ + --slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \ + --slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \ + --slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \ ' { log: { @@ -88,11 +98,19 @@ lib.optionalString hybridEnabled '' } ] }, - inbounds: $inbounds, - outbounds: ($outbounds + [{protocol:"freedom",tag:"direct"}]), + inbounds: [ + { + tag: "sidecar-in", + listen: "127.0.0.1", + port: $port, + protocol: "vless", + settings: {clients: $clients[0], decryption: "none"} + } + ], + outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]), routing: { domainStrategy: "AsIs", - rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) + rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) } }' > "$RUNTIME_DIR/xray-sidecar.json" } diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 3b893f3..5fd3ba6 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -38,7 +38,7 @@ let autoProxyStateDir outboundTestPort xrayDnsBridgePorts - xraySidecarBasePorts + xraySidecarPorts ; autoProxyRender = import ../autoproxy-render.nix { @@ -175,7 +175,7 @@ let routingMark ? null, enableLocalProxyAuth ? false, xrayTunDnsRuntime ? false, - xraySidecarBasePort ? xraySidecarBasePorts.socks, + xraySidecarPort ? xraySidecarPorts.socks, xrayDnsBridgePort ? xrayDnsBridgePorts.socks, enableAutoProxy ? false, enableOutboundTest ? false, @@ -197,7 +197,7 @@ let ROUTE_RULES_JSON='[]' ROUTE_MODE_ACTIVE=false CLEAR_DNS_RULES=false - ${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort} + ${hybridRuntimeHelpersBlock routingMark xraySidecarPort xrayDnsBridgePort} ${subscriptionCacheHelpersBlock} ${lib.optionalString enableLocalProxyAuth '' LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" @@ -447,7 +447,7 @@ let # TProxy takes the system resolver's own upstream queries too, so a proxy server's name # has to resolve inside XRay, as under the TUN. xrayTunDnsRuntime = pureXrayEnabled && globalTproxy.enable; - xraySidecarBasePort = xraySidecarBasePorts.socks; + xraySidecarPort = xraySidecarPorts.socks; xrayDnsBridgePort = xrayDnsBridgePorts.socks; # Only the socks unit: relayed traffic reaches it, and the prober needs one home. enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled; @@ -460,7 +460,7 @@ let configFile = tunFile; routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; xrayTunDnsRuntime = pureXrayEnabled; - xraySidecarBasePort = xraySidecarBasePorts.tun; + xraySidecarPort = xraySidecarPorts.tun; xrayDnsBridgePort = xrayDnsBridgePorts.tun; # Pure XRay's TUN routes by ip rules instead: see xrayTunUpScript. excludeServiceUserFromTun = !pureXrayEnabled; @@ -471,7 +471,7 @@ let configFile = perAppTunFile; routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; xrayTunDnsRuntime = pureXrayEnabled; - xraySidecarBasePort = xraySidecarBasePorts.perAppTun; + xraySidecarPort = xraySidecarPorts.perAppTun; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; }; in diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 6420081..6e25250 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -14,6 +14,7 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; + inherit (import ./derived.nix { inherit lib cfg; }) zapretGlobalEnabled; inherit (import ./zapret/common.nix { inherit @@ -80,12 +81,12 @@ in assertions = zapretPackages.assertions; services.proxy-suite.internal.earlyPackages = ( - lib.optionals zapretCfg.enable [ globalZapretPackage ] + lib.optionals zapretGlobalEnabled [ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ] ); services.proxy-suite.internal.services.proxy-suite-zapret = - lib.mkIf zapretCfg.enable + lib.mkIf zapretGlobalEnabled (mkOneshotService { description = "zapret DPI bypass"; after = [ "network-online.target" ]; @@ -119,7 +120,7 @@ in }); services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt = - lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable) + lib.mkIf (zapretGlobalEnabled && zapretCfg.cidrExemption.enable) ( mkOneshotService { description = "Exempt CIDRs from zapret NFQUEUE"; diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index 2a9f28e..1296e39 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -16,7 +16,11 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; cutoffCfg = zapretCfg.zapret2.cutoff; - inherit (import ./derived.nix { inherit lib cfg; }) constants userControlAllows; + inherit (import ./derived.nix { inherit lib cfg; }) + constants + userControlAllows + zapretGlobalEnabled + ; inherit (import ./zapret/common.nix { inherit @@ -117,7 +121,7 @@ in lib.mkIf cutoffCfg.enable cutoff.timer; services.proxy-suite.internal.services.proxy-suite-zapret = - lib.mkIf zapretCfg.enable + lib.mkIf zapretGlobalEnabled (mkRestartingService { description = "zapret2 DPI bypass"; after = [ "network-online.target" ]; diff --git a/modules/proxy-suite/zapret2/cutoff.nix b/modules/proxy-suite/zapret2/cutoff.nix index 9139d40..5d32497 100644 --- a/modules/proxy-suite/zapret2/cutoff.nix +++ b/modules/proxy-suite/zapret2/cutoff.nix @@ -12,7 +12,11 @@ }: let - inherit (import ../derived.nix { inherit lib cfg; }) constants userControlAllows; + inherit (import ../derived.nix { inherit lib cfg; }) + constants + userControlAllows + zapretGlobalEnabled + ; z2k = zapret2Sources.z2k; lists = "${z2k}/files/lists"; dir = constants.zapret2CutoffDir; @@ -20,7 +24,7 @@ let table = "proxy_suite_cutoff_probe"; # try-restart fails on a unit that is not installed, so only name the ones built. restartUnits = - lib.optional cfg.zapret.enable "proxy-suite-zapret.service" + lib.optional zapretGlobalEnabled "proxy-suite-zapret.service" ++ lib.optional cfg.perAppRouting.zapret.enable "proxy-suite-per-app-zapret.service"; z2kDetect = pkgs.buildGoModule { diff --git a/nix/checks/hybrid-backend.nix b/nix/checks/hybrid-backend.nix index 144d66d..a566a15 100644 --- a/nix/checks/hybrid-backend.nix +++ b/nix/checks/hybrid-backend.nix @@ -74,18 +74,15 @@ in assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript; assert pkgs.lib.hasInfix "/bin/xray run -c" hybridStartScript; assert pkgs.lib.hasInfix "xray-sidecar.json" hybridStartScript; - assert pkgs.lib.hasInfix - "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}" + assert pkgs.lib.hasInfix "XRAY_SIDECAR_PORT=${toString checkConstants.xraySidecarPorts.socks}" hybridStartScript; assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}" hybridStartScript; - assert pkgs.lib.hasInfix - "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}" + assert pkgs.lib.hasInfix "XRAY_SIDECAR_PORT=${toString checkConstants.xraySidecarPorts.tun}" hybridTunStartScript; assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}" hybridTunStartScript; - assert pkgs.lib.hasInfix - "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.perAppTun}" + assert pkgs.lib.hasInfix "XRAY_SIDECAR_PORT=${toString checkConstants.xraySidecarPorts.perAppTun}" hybridPerAppTunStartScript; assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}" @@ -94,9 +91,10 @@ in assert pkgs.lib.hasInfix "--backend xray" hybridStartScript; assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript; assert pkgs.lib.hasInfix "hybrid XRay json sidecar" hybridXrayRawStartScript; - assert pkgs.lib.hasInfix ''{type: "socks", tag: $tag, server: "127.0.0.1"'' + assert pkgs.lib.hasInfix ''{type: "vless", tag: $tag, server: "127.0.0.1"'' hybridXrayRawStartScript; - assert pkgs.lib.hasInfix "udp: true" hybridXrayRawStartScript; + assert pkgs.lib.hasInfix ''packet_encoding: "xudp"'' hybridXrayRawStartScript; + assert pkgs.lib.hasInfix "user: [$tag]" hybridXrayRawStartScript; assert pkgs.lib.hasInfix "{routing_mark: 2}" hybridXrayRawStartScript; assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter; assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter; diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix index 455989e..e65269d 100644 --- a/nix/checks/per-app-routing-tproxy.nix +++ b/nix/checks/per-app-routing-tproxy.nix @@ -45,7 +45,8 @@ in assertions = [ # -- perAppRouting: createDefaultProfiles injects curated tproxy profile when backend is enabled -- ( - assert builtins.length perAppRoutingTproxyProfiles == 2; + # proxychains is off, so no proxychains profile. + assert builtins.length perAppRoutingTproxyProfiles == 1; assert builtins.any ( profile: profile.name == "tproxy" && profile.route == "tproxy" ) perAppRoutingTproxyProfiles; diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index d4e19b6..72d012b 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -73,7 +73,8 @@ in assertions = [ # -- perAppRouting: createDefaultProfiles injects curated tun profile when backend is enabled -- ( - assert builtins.length perAppRoutingTunProfiles == 2; + # proxychains is off, so no proxychains profile. + assert builtins.length perAppRoutingTunProfiles == 1; assert builtins.any ( profile: profile.name == "tun" && profile.route == "tun" ) perAppRoutingTunProfiles; diff --git a/nix/checks/per-app-routing-validation-profiles.nix b/nix/checks/per-app-routing-validation-profiles.nix index 8e9ac09..5664c8c 100644 --- a/nix/checks/per-app-routing-validation-profiles.nix +++ b/nix/checks/per-app-routing-validation-profiles.nix @@ -38,16 +38,6 @@ { services.proxy-suite.perAppRouting.profiles = [ { name = "oops"; } ]; } ] - # default proxychains profile still requires proxychains.enable. - [ - { - services.proxy-suite.perAppRouting = { - enable = true; - createDefaultProfiles = true; - }; - } - ] - # route=tun requires perAppRouting.tun.enable. [ { @@ -154,6 +144,19 @@ } ] + # perAppRouting.zapret requires zapret.enable (global.enable = false keeps it per-app). + [ + { + services.proxy-suite = { + zapret.enable = false; + perAppRouting = { + enable = true; + zapret.enable = true; + }; + }; + } + ] + # profile names must be unique. [ { diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix index ae4d530..cb0dd63 100644 --- a/nix/checks/per-app-routing-zapret.nix +++ b/nix/checks/per-app-routing-zapret.nix @@ -44,7 +44,10 @@ let baseModule { services.proxy-suite = { - zapret.enable = false; + zapret = { + enable = true; + global.enable = false; + }; perAppRouting = { enable = true; createDefaultProfiles = true; diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index 9e0b581..7744705 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -116,7 +116,8 @@ pkgs.testers.runNixOSTest { with subtest("the rendered config carries both listeners"): cfg = "/run/proxy-suite-inbounds/config.json" - server.succeed(f"test $(jq -r '.inbounds | length' {cfg}) = 2") + # Plus api-in, the stats API's socket. + server.succeed(f"jq -e '[.inbounds[].tag] | sort == [\"api-in\", \"ss-in\", \"vless-in\"]' {cfg}") server.succeed(f"jq -e '.inbounds[] | select(.tag == \"vless-in\" and .port == 8443)' {cfg}") server.succeed(f"jq -e '.inbounds[] | select(.tag == \"ss-in\" and .port == 8388)' {cfg}") # Credentials live only in the runtime config, never in the store. diff --git a/nix/checks/zapret-hostlist-routing.nix b/nix/checks/zapret-hostlist-routing.nix index 2c00f5d..010750e 100644 --- a/nix/checks/zapret-hostlist-routing.nix +++ b/nix/checks/zapret-hostlist-routing.nix @@ -30,6 +30,7 @@ let inherit (fixtures) zapretHostlistRules zapretHostlistBase + zapretPerAppOnlyRules invalidHostlistAssertions ; @@ -66,6 +67,11 @@ in assert !(hasDirectIP zapretHostlistRules "1.1.1.0/24"); true ) + ( + assert !(hasDirectDomain zapretPerAppOnlyRules "youtube.com"); + assert !(hasDirectDomain zapretPerAppOnlyRules "example.com"); + true + ) ] ++ invalidHostlistAssertions; } diff --git a/nix/checks/zapret-hostlist-routing/fixtures.nix b/nix/checks/zapret-hostlist-routing/fixtures.nix index c3078a2..725faf0 100644 --- a/nix/checks/zapret-hostlist-routing/fixtures.nix +++ b/nix/checks/zapret-hostlist-routing/fixtures.nix @@ -76,6 +76,24 @@ let zapretHostlistRules = mkRoutingRules zapretHostlistRulesFixture; zapretHostlistBase = mkZapretBase zapretHostlistRulesFixture; + # directSync belongs to the system-wide instance: per-app zapret alone leaves routing alone. + zapretPerAppOnlyRules = mkRoutingRules (evalProxySuite [ + baseModule + { + services.proxy-suite = { + zapret = { + enable = true; + global.enable = false; + zapret-discord-youtube.domains = [ "example.com" ]; + }; + perAppRouting = { + enable = true; + zapret.enable = true; + }; + }; + } + ]); + invalidHostlistAssertions = mkFailingAssertions mkBadFixture [ [ { @@ -158,6 +176,7 @@ in inherit zapretHostlistRules zapretHostlistBase + zapretPerAppOnlyRules invalidHostlistAssertions ; } diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 7e7a44e..77b815d 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -2451,6 +2451,8 @@ def cmd_zapret(*args): elif args[:1] == ("cutoff",): cmd_zapret_cutoff(*args[1:]) else: + if env("PER_APP_ROUTING_ZAPRET_ENABLED") == "1" and not svc_exists("proxy-suite-zapret"): + die("zapret runs per app only (zapret.global.enable = false): proxy-ctl apps run -- ") _toggle("proxy-suite-zapret", "zapret", *args) @@ -2517,7 +2519,7 @@ def _truncate(path): def cmd_zapret_auto(verb="list", domain="", *_): if env("ZAPRET_AUTO_ENABLED") != "1": - die('Learned hostlists need zapret.engine = "zapret2".') + die('Learned hostlists need zapret.engine = "zapret2" with zapret.global.enable.') auto = _zapret_auto_file("zapret-hosts-auto.txt") user = _zapret_auto_file("zapret-hosts-user.txt") exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt") @@ -3028,10 +3030,9 @@ def _ensure_app_routing(): require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting") -def _check_no_global_proxy(route): - for svc in ("proxy-suite-tun", "proxy-suite-tproxy"): - if svc_active(f"{svc}.service"): - die(f"Global {svc}.service is active. Stop it before using route={route} profiles.") +def _active_global_proxy(): + """The global TUN or TProxy unit that is up, which the per-app backends would clash with.""" + return next((svc for svc in ("proxy-suite-tun", "proxy-suite-tproxy") if svc_active(f"{svc}.service")), "") def _has_units(*args): @@ -3143,7 +3144,12 @@ def cmd_apps_run(profile="", *cmd): _exec(["proxychains4", *env("PROXYCHAINS_QUIET_ARG").split(), "-f", config, *cmd]) elif route in SLICE_ROUTES: slice_base, enabled, option = SLICE_ROUTES[route] - _check_no_global_proxy(route) + # The global mode already carries the app's traffic, and wrapPerApp launchers must + # still start the app: run it as it is rather than refuse. + global_svc = _active_global_proxy() + if global_svc: + print(f"note: {global_svc}.service is active; running without route={route}.", file=sys.stderr) + _exec(list(cmd)) if env(enabled) != "1": die(f"Profile '{profile}' uses route={route}, but {option} is false.") _warn_stub_resolver(route) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index af064c8..7bf1b50 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -376,6 +376,10 @@ class ServiceManagerTest(EnvTest): ctl.cmd_zapret("restart") ctl.cmd_tor("restart") self.assertEqual(verbs(), [["restart", u] for u in ("proxy-suite-socks", "proxy-suite-tproxy", "proxy-suite-zapret", "proxy-suite-tor")]) + # Per-app zapret only: no system-wide unit to toggle, so point at the profile instead. + os.environ["PER_APP_ROUTING_ZAPRET_ENABLED"] = "1" + with mock.patch.object(ctl, "svc_exists", lambda unit: unit != "proxy-suite-zapret"): + self.assertIn("zapret.global.enable = false", run(ctl.cmd_zapret, "on")[2]) # awg toggle: a named profile flips; without one, only stopping is possible. seen.clear() self.patch("_awg_profiles", lambda: ["p", "q"]) @@ -920,11 +924,13 @@ class AppsRunTest(EnvTest): self.assertEqual(status, 3) self.assertIn(("stop", "proxy-suite-per-app-tun.service"), self.calls) - def test_global_proxy_refused(self): + def test_global_proxy_runs_plain(self): + # A wrapPerApp launcher must still start the app; the global mode carries it. self.active = {"proxy-suite-tun.service"} - status, _, err = run(ctl.cmd_apps, "run", "tproxy", "--", "curl") - self.assertNotEqual(status, 0) - self.assertIn("Global proxy-suite-tun.service is active", err) + status, _, err = run(ctl.cmd_apps, "run", "tproxy", "--", "curl", "x") + self.assertEqual(status, 0) + self.assertEqual(self.execed, ["curl", "x"]) + self.assertIn("proxy-suite-tun.service is active", err) self.assertFalse(any(c[0] == "systemd-run" for c in self.calls)) def test_disabled_route(self):