fix: behavior and docs fixes

This commit is contained in:
FUFSoB committed 2026-09-26 18:35:32 +05:00
1 parent e4458dcae8
commit 2255e1f9f0
42 files changed
+301 -142

No files matched your search

+3
View File
@@ -336,6 +336,9 @@ services.proxy-suite = {
}; };
enable = false; enable = false;
engine = "zapret-discord-youtube"; engine = "zapret-discord-youtube";
global = {
enable = true;
};
zapret-discord-youtube = { zapret-discord-youtube = {
configName = "general(ALT)"; configName = "general(ALT)";
domains = [ ]; domains = [ ];
+13 -1
View File
@@ -16,6 +16,8 @@ Part of the [proxy-suite options reference](./index.md).
- [upstreamIps](#services-proxy-suite-zapret-directsync-upstreamips) - [upstreamIps](#services-proxy-suite-zapret-directsync-upstreamips)
- [userIps](#services-proxy-suite-zapret-directsync-userips) - [userIps](#services-proxy-suite-zapret-directsync-userips)
- [engine](#services-proxy-suite-zapret-engine) - [engine](#services-proxy-suite-zapret-engine)
- global
- [enable](#services-proxy-suite-zapret-global-enable)
- zapret-discord-youtube - zapret-discord-youtube
- [configName](#services-proxy-suite-zapret-zapret-discord-youtube-configname) - [configName](#services-proxy-suite-zapret-zapret-discord-youtube-configname)
- [domains](#services-proxy-suite-zapret-zapret-discord-youtube-domains) - [domains](#services-proxy-suite-zapret-zapret-discord-youtube-domains)
@@ -63,7 +65,7 @@ Part of the [proxy-suite options reference](./index.md).
<a id="services-proxy-suite-zapret-enable"></a> <a id="services-proxy-suite-zapret-enable"></a>
## services\.proxy-suite\.zapret\.enable ## services\.proxy-suite\.zapret\.enable
Whether to enable zapret DPI bypass\. Whether to enable zapret DPI bypass\. Needed by ` perAppRouting.zapret ` too\.
**Type:** boolean\ **Type:** boolean\
**Default:** `false` **Default:** `false`
@@ -121,6 +123,16 @@ Which zapret to run:
**Default:** `"zapret-discord-youtube"`\ **Default:** `"zapret-discord-youtube"`\
**Example:** `"zapret2"` **Example:** `"zapret2"`
<a id="services-proxy-suite-zapret-global-enable"></a>
## 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`
<a id="services-proxy-suite-zapret-zapret-discord-youtube-configname"></a> <a id="services-proxy-suite-zapret-zapret-discord-youtube-configname"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.configName ## services\.proxy-suite\.zapret\.zapret-discord-youtube\.configName
@@ -30,10 +30,10 @@ in
routing = { routing = {
# Unlisted sites leave directly, where zapret2 unblocks what DPI blocks. # Unlisted sites leave directly, where zapret2 unblocks what DPI blocks.
default = "direct"; 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; directRu = false;
# Checked in order; the first match wins. # Checked in order, before the lists; the first match wins.
rules = [ rules = [
{ {
outbound = "ssh-proxy"; outbound = "ssh-proxy";
@@ -43,7 +43,7 @@ in
outbound = "warp"; outbound = "warp";
geosites = [ "youtube" ]; geosites = [ "youtube" ];
} }
# To mask your IP from Russian services # Russian services see WARP's address instead of this host's.
{ {
outbound = "warp"; outbound = "warp";
geosites = [ "category-ru" ]; geosites = [ "category-ru" ];
@@ -60,8 +60,8 @@ in
}; };
}; };
# For blocked sites no list names yet. YouTube is pinned to WARP above, so it # For blocked sites no list names yet. YouTube already has its rule, so its video
# is kept out of the probes. # hosts are not worth probing.
autoProxy = { autoProxy = {
enable = true; enable = true;
exclude = [ "googlevideo.com" "gvt1.com" ]; exclude = [ "googlevideo.com" "gvt1.com" ];
@@ -85,7 +85,8 @@ in
hostKeyFile = "/run/secrets/proxy-ssh-known-hosts"; 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 = { tor = {
enable = true; enable = true;
asOutbound = true; asOutbound = true;
@@ -18,8 +18,8 @@ in
listeners.vpn = { listeners.vpn = {
type = "amneziawg"; type = "amneziawg";
port = 51820; port = 51820;
# Fixed addresses, so firewall rules and DNS can name each device. Keys are # Fixed addresses, so firewall rules and DNS can name each device.
# generated on first start. # Keys are generated on first start.
users = [ users = [
{ name = "laptop"; address = "10.77.77.2"; } { name = "laptop"; address = "10.77.77.2"; }
{ name = "phone"; address = "10.77.77.3"; } { name = "phone"; address = "10.77.77.3"; }
@@ -25,8 +25,7 @@ let
sharePort = 443; # share links name nginx's port, not the listener's sharePort = 443; # share links name nginx's port, not the listener's
transport = extra // { transport = extra // {
inherit path; inherit path;
# nginx sets this header, so XRay sees each client's real address (for # 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.
# `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it.
trustedXForwardedFor = [ "X-Real-IP" ]; trustedXForwardedFor = [ "X-Real-IP" ];
}; };
inherit tls; inherit tls;
@@ -8,6 +8,8 @@ in
proxy = { proxy = {
enable = true; enable = true;
# Support all available protocols by enabling hybrid backend.
backend = "hybrid";
# The server's subscription: every listener, each a separate outbound. # The server's subscription: every listener, each a separate outbound.
subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ]; subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ];
# The fastest listener that gets through the current network. # The fastest listener that gets through the current network.
@@ -16,7 +18,7 @@ in
routing.default = "direct"; routing.default = "direct";
autoProxy.enable = true; 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 = { zapret = {
+1 -1
View File
@@ -19,7 +19,7 @@
enable = true; enable = true;
serverNames = [ "www.microsoft.com" ]; serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/reality-private-key"; privateKeyFile = "/run/secrets/reality-private-key";
publicKey = "jNXH…"; # from the same `xray x25519` run publicKey = "jNXH…"; # both keys from `xray x25519`
shortIds = [ "0123abcd" ]; shortIds = [ "0123abcd" ];
}; };
}; };
+1 -1
View File
@@ -19,7 +19,7 @@ in
environment.systemPackages = [ environment.systemPackages = [
(proxySuite.wrapEnv { } pkgs.yt-dlp) (proxySuite.wrapEnv { } pkgs.yt-dlp)
(proxySuite.wrapProxychains { } pkgs.telegram-desktop) (proxySuite.wrapProxychains { } pkgs.curl)
(proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox) (proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox)
]; ];
+15
View File
@@ -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;
};
};
}
-1
View File
@@ -64,7 +64,6 @@ proxy-ctl status # everything at a glance
proxy-ctl status --json # the same, for scripts proxy-ctl status --json # the same, for scripts
proxy-ctl logs # follow the logs of every proxy-suite service proxy-ctl logs # follow the logs of every proxy-suite service
proxy-ctl restart # restart what is running proxy-ctl restart # restart what is running
proxy-ctl where example.com
``` ```
## See also ## See also
+37 -15
View File
@@ -1,8 +1,18 @@
# Example: several exits, picked per site # Example: several exits, picked per site
One host with four ways out: direct (with zapret2 for DPI), a VPS, WARP and an SSH server. A host in Russia with five ways out: direct (with zapret2 for DPI), a VPS, WARP, an SSH
Each site goes to whichever works best for it, and autoProxy covers the sites nobody server and Tor. Each site goes to whichever works best for it, and autoProxy covers the
listed. Everything runs in global TUN mode, so every app on the host follows these rules. 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 ```nix
{ ... }: { ... }:
@@ -37,10 +47,10 @@ in
routing = { routing = {
# Unlisted sites leave directly, where zapret2 unblocks what DPI blocks. # Unlisted sites leave directly, where zapret2 unblocks what DPI blocks.
default = "direct"; 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; directRu = false;
# Checked in order; the first match wins. # Checked in order, before the lists; the first match wins.
rules = [ rules = [
{ {
outbound = "ssh-proxy"; outbound = "ssh-proxy";
@@ -50,7 +60,7 @@ in
outbound = "warp"; outbound = "warp";
geosites = [ "youtube" ]; geosites = [ "youtube" ];
} }
# To mask your IP from Russian services # Russian services see WARP's address instead of this host's.
{ {
outbound = "warp"; outbound = "warp";
geosites = [ "category-ru" ]; 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 = { autoProxy = {
enable = true; enable = true;
exclude = [ "googlevideo.com" "gvt1.com" ]; exclude = [ "googlevideo.com" "gvt1.com" ];
@@ -91,6 +102,14 @@ in
hostKeyFile = "/run/secrets/proxy-ssh-known-hosts"; 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 = { zapret = {
enable = true; enable = true;
engine = "zapret2"; engine = "zapret2";
@@ -103,6 +122,7 @@ in
```sh ```sh
proxy-ctl where youtube.com # -> warp, by the rule for youtube 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 where chatgpt.com # -> proxy -> primary, by geosite openai
proxy-ctl proxy auto # what autoProxy routed, and through which exit proxy-ctl proxy auto # what autoProxy routed, and through which exit
proxy-ctl zapret auto # what zapret2 learned proxy-ctl zapret auto # what zapret2 learned
@@ -110,24 +130,25 @@ proxy-ctl zapret auto # what zapret2 learned
## With relay clients ## With relay clients
On a [relay server](./relay-server.md) with `inbounds.routing.via = "proxy"`, clients follow With `inbounds.routing.via = "proxy"`, relay clients go through the routing above. Two
these rules too, with two exceptions. Russian sites are blocked for them (`blockRu`), and checks come first by default: Russian sites are blocked for them (`blockRu`), and sites on
sites on zapret's list go straight out, so this host's zapret handles them (`zapretDirect`). zapret's list leave directly, so this host's zapret handles them (`zapretDirect`). Sites in
Sites listed in `inbounds.routing.proxy` skip both exceptions and go to the rules above: `inbounds.routing.proxy` skip both and reach the rules above:
```nix no-check ```nix no-check
services.proxy-suite.inbounds.routing = { services.proxy-suite.inbounds.routing = {
via = "proxy"; 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 = { 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" ]; geosites = [ "youtube" "category-ru" ];
geoips = [ "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 ## Notes
@@ -135,4 +156,5 @@ The same list applies to listeners with their own `via`, including `"direct"` on
country). country).
- Rules can name any outbound tag: yours, `warp`, `ssh-proxy`, `tor`, or an AmneziaWG - Rules can name any outbound tag: yours, `warp`, `ssh-proxy`, `tor`, or an AmneziaWG
outbound. 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.
+4 -6
View File
@@ -29,8 +29,8 @@ in
listeners.vpn = { listeners.vpn = {
type = "amneziawg"; type = "amneziawg";
port = 51820; port = 51820;
# Fixed addresses, so firewall rules and DNS can name each device. Keys are # Fixed addresses, so firewall rules and DNS can name each device.
# generated on first start. # Keys are generated on first start.
users = [ users = [
{ name = "laptop"; address = "10.77.77.2"; } { name = "laptop"; address = "10.77.77.2"; }
{ name = "phone"; address = "10.77.77.3"; } { 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 ## Notes
- `mode = "lan"` turns on IP forwarding. The default, `"proxy"`, gives devices the - `mode = "lan"` turns on IP forwarding. The default, `"proxy"`, gives devices the internet only, like the other listeners.
internet only, like the other listeners.
- Only TCP and UDP reach the internet; ping and other protocols stop at the server. - 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; - A device that keeps its own private key can be added with `users.*.publicKey` instead; it gets no generated config.
it gets no generated config.
+1 -2
View File
@@ -45,8 +45,7 @@ let
sharePort = 443; # share links name nginx's port, not the listener's sharePort = 443; # share links name nginx's port, not the listener's
transport = extra // { transport = extra // {
inherit path; inherit path;
# nginx sets this header, so XRay sees each client's real address (for # 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.
# `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it.
trustedXForwardedFor = [ "X-Real-IP" ]; trustedXForwardedFor = [ "X-Real-IP" ];
}; };
inherit tls; inherit tls;
+4 -2
View File
@@ -16,6 +16,8 @@ in
proxy = { proxy = {
enable = true; enable = true;
# Support all available protocols by enabling hybrid backend.
backend = "hybrid";
# The server's subscription: every listener, each a separate outbound. # The server's subscription: every listener, each a separate outbound.
subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ]; subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ];
# The fastest listener that gets through the current network. # The fastest listener that gets through the current network.
@@ -24,7 +26,7 @@ in
routing.default = "direct"; routing.default = "direct";
autoProxy.enable = true; 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 = { zapret = {
@@ -84,7 +86,7 @@ The tray app shows the same, and switches with a click.
do not know. do not know.
- The kill switch guards whichever global tunnel is on (TUN or the VPN), and does nothing - The kill switch guards whichever global tunnel is on (TUN or the VPN), and does nothing
while both are off. 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. through the proxy then.
- See [Wrap programs with the proxy](../wrap-apps.md) for the helpers, and - 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`. [Keep secrets out of the Nix store](../secrets.md) for the files under `/run/secrets`.
+3 -2
View File
@@ -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. | | `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. | | `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. | | `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. `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 - `tun`, `tproxy` and `zapret` profiles start a system service, so they ask for an admin
password unless `userControl` grants the `perApp` scope (see password unless `userControl` grants the `perApp` scope (see
[Control it day to day](./control.md)). [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 - 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. 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. - The app follows your [routing rules](./routing.md) like any other proxied traffic.
+1 -1
View File
@@ -41,7 +41,7 @@ services.proxy-suite = {
enable = true; enable = true;
serverNames = [ "www.microsoft.com" ]; serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/reality-private-key"; privateKeyFile = "/run/secrets/reality-private-key";
publicKey = "jNXH…"; # from the same `xray x25519` run publicKey = "jNXH…"; # both keys from `xray x25519`
shortIds = [ "0123abcd" ]; shortIds = [ "0123abcd" ];
}; };
}; };
+2 -1
View File
@@ -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. 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 - `proxy.tproxy.localSubnets` lists networks that skip TProxy. Add your LAN and VM bridges if
they are not in `192.168.0.0/16`. 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 ## See also
+1 -1
View File
@@ -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, 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. and asks for an email and password instead on DION and Bitrix.
+1 -1
View File
@@ -35,7 +35,7 @@ in
environment.systemPackages = [ environment.systemPackages = [
(proxySuite.wrapEnv { } pkgs.yt-dlp) (proxySuite.wrapEnv { } pkgs.yt-dlp)
(proxySuite.wrapProxychains { } pkgs.telegram-desktop) (proxySuite.wrapProxychains { } pkgs.curl)
(proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox) (proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox)
]; ];
+27 -3
View File
@@ -41,8 +41,8 @@ services.proxy-suite = {
}; };
``` ```
`zapret2.strategySource = "z2k"` switches to z2k's strategies and site lists, which include `zapret2.strategySource = "z2k"` switches to z2k's strategies and site lists, which includes
the full RKN list and use more memory. It also turns on a workaround for ISPs that cut 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. TLS to some hosting networks after about 16 KB.
## Commands ## 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 handles are sent direct, so they skip the proxy and reach zapret. Everything else follows
your [routing rules](./routing.md). 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 ## 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 ## See also
- [`zapret.engine`](../options/zapret.md#services-proxy-suite-zapret-engine) - [`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) - [`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) - [`zapret2.strategySource`](../options/zapret.md#services-proxy-suite-zapret-zapret2-strategysource)
- [`zapret.directSync`](../options/zapret.md#services-proxy-suite-zapret-directsync-enable) - [`zapret.directSync`](../options/zapret.md#services-proxy-suite-zapret-directsync-enable)
+4 -12
View File
@@ -94,12 +94,7 @@ in
inherit (assembly) context; inherit (assembly) context;
}) })
(lib.mkIf (lib.mkIf (cfg.zapret.engine == "zapret-discord-youtube" && cfg.zapret.enable) (
(
cfg.zapret.engine == "zapret-discord-youtube"
&& (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)
)
(
import ./zapret.nix { import ./zapret.nix {
inherit inherit
lib lib
@@ -109,11 +104,9 @@ in
; ;
inherit (nftr) perAppZapretRulesFile nft; inherit (nftr) perAppZapretRulesFile nft;
} }
) ))
)
(lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) (lib.mkIf (cfg.zapret.engine == "zapret2" && cfg.zapret.enable) (
(
import ./zapret2.nix { import ./zapret2.nix {
inherit inherit
lib lib
@@ -124,8 +117,7 @@ in
inherit (nftr) perAppZapretRulesFile nft; inherit (nftr) perAppZapretRulesFile nft;
zapret2Sources = { inherit nfqws2-keenetic z2k; }; zapret2Sources = { inherit nfqws2-keenetic z2k; };
} }
) ))
)
(lib.mkIf cfg.tgWsProxy.enable ( (lib.mkIf cfg.tgWsProxy.enable (
(import ./tg-ws-proxy.nix { (import ./tg-ws-proxy.nix {
+6 -4
View File
@@ -321,10 +321,10 @@ let
# Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode. # Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode.
clashApiEnabled = singBoxEnabled; clashApiEnabled = singBoxEnabled;
perAppZapretEnabled = perAppZapretCfg.enable; perAppZapretEnabled = perAppZapretCfg.enable;
# The system-wide instance; per-app zapret runs its own.
zapretGlobalEnabled = zapretCfg.enable && zapretCfg.global.enable;
zapretCutoffEnabled = zapretCutoffEnabled =
zapretEngine == "zapret2" zapretEngine == "zapret2" && zapretCfg.enable && zapretCfg.zapret2.cutoff.enable;
&& (zapretCfg.enable || perAppZapretEnabled)
&& zapretCfg.zapret2.cutoff.enable;
# The cut-off networks no whitelisted name fixes go through the proxy outbound. # The cut-off networks no whitelisted name fixes go through the proxy outbound.
zapretCutoffProxyFallback = zapretCutoffProxyFallback =
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds; zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
@@ -464,7 +464,8 @@ let
perAppTun = 18535; perAppTun = 18535;
}; };
xraySidecarBasePorts = { # One loopback VLESS inbound per stack's XRay sidecar, however many outbounds it carries.
xraySidecarPorts = {
socks = 33080; socks = 33080;
tun = 33180; tun = 33180;
perAppTun = 33280; perAppTun = 33280;
@@ -509,6 +510,7 @@ in
zapretEngine zapretEngine
perAppZapretCfg perAppZapretCfg
perAppZapretEnabled perAppZapretEnabled
zapretGlobalEnabled
zapretCutoffEnabled zapretCutoffEnabled
zapretCutoffProxyFallback zapretCutoffProxyFallback
userControlCfg userControlCfg
+7 -1
View File
@@ -7,7 +7,13 @@ let
in in
{ {
options.services.proxy-suite.zapret = { 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 { engine = mkOption {
type = types.enum [ type = types.enum [
+5 -3
View File
@@ -25,9 +25,11 @@ let
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items; subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.directSync.enable; # Only the system-wide instance handles traffic the proxy would send direct.
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.directSync.upstreamIps; globalEnabled = zapretCfg.enable && zapretCfg.global.enable;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.directSync.userIps; syncZapretDirectDomains = globalEnabled && zapretCfg.directSync.enable;
syncZapretDirectUpstreamIps = globalEnabled && zapretCfg.directSync.upstreamIps;
syncZapretDirectUserIps = globalEnabled && zapretCfg.directSync.userIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps; syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [ zapretDefaultDomainFiles = [
+8 -2
View File
@@ -69,6 +69,7 @@ let
reservedLoopbackPorts = reservedLoopbackPorts =
builtins.attrValues constants.xrayDnsBridgePorts builtins.attrValues constants.xrayDnsBridgePorts
++ [ constants.outboundTestPort ] ++ [ constants.outboundTestPort ]
++ lib.optionals hybridEnabled (builtins.attrValues constants.xraySidecarPorts)
++ lib.optionals derived.warpOutboundEnabled [ ++ lib.optionals derived.warpOutboundEnabled [
derived.warpCfg.tunnelPort derived.warpCfg.tunnelPort
derived.warpCfg.directPort derived.warpCfg.directPort
@@ -334,6 +335,9 @@ let
(requires perAppZapretCfg.enable perAppRoutingCfg.enable "perAppRouting.zapret.enable" (requires perAppZapretCfg.enable perAppRoutingCfg.enable "perAppRouting.zapret.enable"
"perAppRouting.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" (requires hasZapretProfiles perAppZapretCfg.enable "route=zapret in perAppRouting.profiles"
"perAppRouting.zapret.enable" "perAppRouting.zapret.enable"
) )
@@ -455,9 +459,10 @@ let
|| !lib.any (port: builtins.elem port derived.proxyInboundPorts) ( || !lib.any (port: builtins.elem port derived.proxyInboundPorts) (
map (listener: listener.internalPort) derived.proxyInboundsAwg map (listener: listener.internalPort) derived.proxyInboundsAwg
++ builtins.attrValues derived.constants.xrayDnsBridgePorts ++ 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 # 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 # and AmneziaWG tunnels open two each from their own bases. They all bind
@@ -858,7 +863,8 @@ let
(distinct perAppTunWithTproxy perAppRoutingTun.routeTable globalTproxy.routeTable (distinct perAppTunWithTproxy perAppRoutingTun.routeTable globalTproxy.routeTable
"perAppRouting.tun.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled" "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}" "perAppRouting.zapret.qnum must differ from the global zapret instance's NFQUEUE ${toString globalZapretQnum}"
) )
(distinct perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark globalTproxy.fwmark (distinct perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark globalTproxy.fwmark
+3 -1
View File
@@ -14,6 +14,7 @@ let
perAppRoutingTproxy perAppRoutingTproxy
perAppZapretCfg perAppZapretCfg
zapretEngine zapretEngine
zapretGlobalEnabled
zapretCutoffEnabled zapretCutoffEnabled
constants constants
selectionMode selectionMode
@@ -100,7 +101,8 @@ in
INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile; INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile;
INBOUNDS_SUB_BASE_URL = INBOUNDS_SUB_BASE_URL =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; 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_STATE_DIR = constants.zapret2StateDir;
ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled; ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled;
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile; OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
@@ -15,7 +15,7 @@ let
inherit (constants) runtimeDir; inherit (constants) runtimeDir;
perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles; perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles;
defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles ( defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles (
[ lib.optionals perAppRoutingCfg.proxychains.enable [
{ {
name = "proxychains"; name = "proxychains";
route = "proxychains"; route = "proxychains";
@@ -9,14 +9,18 @@ let
; ;
in in
routingMark: xraySidecarBasePort: xrayDnsBridgePort: routingMark: xraySidecarPort: xrayDnsBridgePort:
lib.optionalString hybridEnabled '' lib.optionalString hybridEnabled ''
XRAY_OUTBOUNDS_JSON='[]' XRAY_OUTBOUNDS_JSON='[]'
XRAY_INBOUNDS_JSON='[]' XRAY_CLIENTS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]' XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort} XRAY_SIDECAR_PORT=${toString xraySidecarPort}
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort} 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() { _proxy_suite_add_sing_box_ob() {
local ob="$1" 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 # $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() { _proxy_suite_add_xray_sidecar_obs() {
local batch local batch
batch=$(${jq} -c \ 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 ${ --argjson mark ${
if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark 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( to_entries | map(
($base + .key) as $port ($secret[:24] + ($next + .key | hex12)) as $id
| ("proxy-suite-xray-" + ($port | tostring)) as $auth
| .value.tag as $tag | .value.tag as $tag
| {outbound: (.value | {outbound: (.value
${lib.optionalString ( ${lib.optionalString (
xraySidecarRoutingMark != null xraySidecarRoutingMark != null
) "| .streamSettings.sockopt.mark = $mark"} ) "| .streamSettings.sockopt.mark = $mark"}
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")), | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
inbound: {tag: ($tag + "-inbound"), listen: "127.0.0.1", port: $port, protocol: "socks", client: {id: $id, email: $tag},
settings: {auth: "password", udp: true, accounts: [{user: $auth, pass: $auth}]}}, rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
rule: {type: "field", inboundTag: [$tag + "-inbound"], outboundTag: $tag}, hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id,
hop: ({type: "socks", tag: $tag, server: "127.0.0.1", server_port: $port, version: "5", packet_encoding: "xudp"}${
username: $auth, password: $auth}${
lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}" 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") ' <<< "$1")
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + $(${jq} '.outbounds | length' <<< "$batch"))) XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(${jq} '.outbounds | length' <<< "$batch")))
XRAY_OUTBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.outbounds' <<< "$XRAY_OUTBOUNDS_JSON") # Through a file, not --argjson: a big subscription's batch outgrows the kernel's
XRAY_INBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.inbounds' <<< "$XRAY_INBOUNDS_JSON") # 128 KiB limit on one argument.
XRAY_ROUTE_RULES_JSON=$(${jq} -c --argjson b "$batch" '. + $b.rules' <<< "$XRAY_ROUTE_RULES_JSON") XRAY_OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON")
OUTBOUNDS_JSON=$(${jq} -c --argjson b "$batch" '. + $b.hops' <<< "$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. # $1 one XRay outbound, $2 its tag.
@@ -69,9 +78,10 @@ lib.optionalString hybridEnabled ''
${jq} -n \ ${jq} -n \
--arg loglevel "$XRAY_LOGLEVEL" \ --arg loglevel "$XRAY_LOGLEVEL" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson inbounds "$XRAY_INBOUNDS_JSON" \ --argjson port "$XRAY_SIDECAR_PORT" \
--argjson outbounds "$XRAY_OUTBOUNDS_JSON" \ --slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \
--argjson route_rules "$XRAY_ROUTE_RULES_JSON" \ --slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \
--slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \
' '
{ {
log: { log: {
@@ -88,11 +98,19 @@ lib.optionalString hybridEnabled ''
} }
] ]
}, },
inbounds: $inbounds, inbounds: [
outbounds: ($outbounds + [{protocol:"freedom",tag:"direct"}]), {
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: { routing: {
domainStrategy: "AsIs", 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" }' > "$RUNTIME_DIR/xray-sidecar.json"
} }
@@ -38,7 +38,7 @@ let
autoProxyStateDir autoProxyStateDir
outboundTestPort outboundTestPort
xrayDnsBridgePorts xrayDnsBridgePorts
xraySidecarBasePorts xraySidecarPorts
; ;
autoProxyRender = import ../autoproxy-render.nix { autoProxyRender = import ../autoproxy-render.nix {
@@ -175,7 +175,7 @@ let
routingMark ? null, routingMark ? null,
enableLocalProxyAuth ? false, enableLocalProxyAuth ? false,
xrayTunDnsRuntime ? false, xrayTunDnsRuntime ? false,
xraySidecarBasePort ? xraySidecarBasePorts.socks, xraySidecarPort ? xraySidecarPorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks, xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false, enableAutoProxy ? false,
enableOutboundTest ? false, enableOutboundTest ? false,
@@ -197,7 +197,7 @@ let
ROUTE_RULES_JSON='[]' ROUTE_RULES_JSON='[]'
ROUTE_MODE_ACTIVE=false ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false CLEAR_DNS_RULES=false
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort} ${hybridRuntimeHelpersBlock routingMark xraySidecarPort xrayDnsBridgePort}
${subscriptionCacheHelpersBlock} ${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth '' ${lib.optionalString enableLocalProxyAuth ''
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" 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 # 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. # has to resolve inside XRay, as under the TUN.
xrayTunDnsRuntime = pureXrayEnabled && globalTproxy.enable; xrayTunDnsRuntime = pureXrayEnabled && globalTproxy.enable;
xraySidecarBasePort = xraySidecarBasePorts.socks; xraySidecarPort = xraySidecarPorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks; xrayDnsBridgePort = xrayDnsBridgePorts.socks;
# Only the socks unit: relayed traffic reaches it, and the prober needs one home. # Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled; enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
@@ -460,7 +460,7 @@ let
configFile = tunFile; configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled; xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.tun; xraySidecarPort = xraySidecarPorts.tun;
xrayDnsBridgePort = xrayDnsBridgePorts.tun; xrayDnsBridgePort = xrayDnsBridgePorts.tun;
# Pure XRay's TUN routes by ip rules instead: see xrayTunUpScript. # Pure XRay's TUN routes by ip rules instead: see xrayTunUpScript.
excludeServiceUserFromTun = !pureXrayEnabled; excludeServiceUserFromTun = !pureXrayEnabled;
@@ -471,7 +471,7 @@ let
configFile = perAppTunFile; configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled; xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.perAppTun; xraySidecarPort = xraySidecarPorts.perAppTun;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
}; };
in in
+4 -3
View File
@@ -14,6 +14,7 @@ let
zapretCfg = cfg.zapret; zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret; perAppZapretCfg = cfg.perAppRouting.zapret;
inherit (import ./derived.nix { inherit lib cfg; }) zapretGlobalEnabled;
inherit inherit
(import ./zapret/common.nix { (import ./zapret/common.nix {
inherit inherit
@@ -80,12 +81,12 @@ in
assertions = zapretPackages.assertions; assertions = zapretPackages.assertions;
services.proxy-suite.internal.earlyPackages = ( services.proxy-suite.internal.earlyPackages = (
lib.optionals zapretCfg.enable [ globalZapretPackage ] lib.optionals zapretGlobalEnabled [ globalZapretPackage ]
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
); );
services.proxy-suite.internal.services.proxy-suite-zapret = services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable lib.mkIf zapretGlobalEnabled
(mkOneshotService { (mkOneshotService {
description = "zapret DPI bypass"; description = "zapret DPI bypass";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
@@ -119,7 +120,7 @@ in
}); });
services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt = services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt =
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable) lib.mkIf (zapretGlobalEnabled && zapretCfg.cidrExemption.enable)
( (
mkOneshotService { mkOneshotService {
description = "Exempt CIDRs from zapret NFQUEUE"; description = "Exempt CIDRs from zapret NFQUEUE";
+6 -2
View File
@@ -16,7 +16,11 @@ let
zapretCfg = cfg.zapret; zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret; perAppZapretCfg = cfg.perAppRouting.zapret;
cutoffCfg = zapretCfg.zapret2.cutoff; cutoffCfg = zapretCfg.zapret2.cutoff;
inherit (import ./derived.nix { inherit lib cfg; }) constants userControlAllows; inherit (import ./derived.nix { inherit lib cfg; })
constants
userControlAllows
zapretGlobalEnabled
;
inherit inherit
(import ./zapret/common.nix { (import ./zapret/common.nix {
inherit inherit
@@ -117,7 +121,7 @@ in
lib.mkIf cutoffCfg.enable cutoff.timer; lib.mkIf cutoffCfg.enable cutoff.timer;
services.proxy-suite.internal.services.proxy-suite-zapret = services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable lib.mkIf zapretGlobalEnabled
(mkRestartingService { (mkRestartingService {
description = "zapret2 DPI bypass"; description = "zapret2 DPI bypass";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
+6 -2
View File
@@ -12,7 +12,11 @@
}: }:
let let
inherit (import ../derived.nix { inherit lib cfg; }) constants userControlAllows; inherit (import ../derived.nix { inherit lib cfg; })
constants
userControlAllows
zapretGlobalEnabled
;
z2k = zapret2Sources.z2k; z2k = zapret2Sources.z2k;
lists = "${z2k}/files/lists"; lists = "${z2k}/files/lists";
dir = constants.zapret2CutoffDir; dir = constants.zapret2CutoffDir;
@@ -20,7 +24,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 "proxy-suite-zapret.service" lib.optional zapretGlobalEnabled "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 {
+6 -8
View File
@@ -74,18 +74,15 @@ in
assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript; assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript;
assert pkgs.lib.hasInfix "/bin/xray 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.json" hybridStartScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix "XRAY_SIDECAR_PORT=${toString checkConstants.xraySidecarPorts.socks}"
"XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}"
hybridStartScript; hybridStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}" assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}"
hybridStartScript; hybridStartScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix "XRAY_SIDECAR_PORT=${toString checkConstants.xraySidecarPorts.tun}"
"XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}"
hybridTunStartScript; hybridTunStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}" assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}"
hybridTunStartScript; hybridTunStartScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix "XRAY_SIDECAR_PORT=${toString checkConstants.xraySidecarPorts.perAppTun}"
"XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.perAppTun}"
hybridPerAppTunStartScript; hybridPerAppTunStartScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix
"XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}" "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}"
@@ -94,9 +91,10 @@ in
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript; assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" 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 "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; 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 "{routing_mark: 2}" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter; assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter;
assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter; assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter;
+2 -1
View File
@@ -45,7 +45,8 @@ in
assertions = [ assertions = [
# -- perAppRouting: createDefaultProfiles injects curated tproxy profile when backend is enabled -- # -- 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 ( assert builtins.any (
profile: profile.name == "tproxy" && profile.route == "tproxy" profile: profile.name == "tproxy" && profile.route == "tproxy"
) perAppRoutingTproxyProfiles; ) perAppRoutingTproxyProfiles;
+2 -1
View File
@@ -73,7 +73,8 @@ in
assertions = [ assertions = [
# -- perAppRouting: createDefaultProfiles injects curated tun profile when backend is enabled -- # -- 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 ( assert builtins.any (
profile: profile.name == "tun" && profile.route == "tun" profile: profile.name == "tun" && profile.route == "tun"
) perAppRoutingTunProfiles; ) perAppRoutingTunProfiles;
@@ -38,16 +38,6 @@
{ services.proxy-suite.perAppRouting.profiles = [ { name = "oops"; } ]; } { 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. # 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. # profile names must be unique.
[ [
{ {
+4 -1
View File
@@ -44,7 +44,10 @@ let
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
zapret.enable = false; zapret = {
enable = true;
global.enable = false;
};
perAppRouting = { perAppRouting = {
enable = true; enable = true;
createDefaultProfiles = true; createDefaultProfiles = true;
+2 -1
View File
@@ -116,7 +116,8 @@ pkgs.testers.runNixOSTest {
with subtest("the rendered config carries both listeners"): with subtest("the rendered config carries both listeners"):
cfg = "/run/proxy-suite-inbounds/config.json" 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 == \"vless-in\" and .port == 8443)' {cfg}")
server.succeed(f"jq -e '.inbounds[] | select(.tag == \"ss-in\" and .port == 8388)' {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. # Credentials live only in the runtime config, never in the store.
+6
View File
@@ -30,6 +30,7 @@ let
inherit (fixtures) inherit (fixtures)
zapretHostlistRules zapretHostlistRules
zapretHostlistBase zapretHostlistBase
zapretPerAppOnlyRules
invalidHostlistAssertions invalidHostlistAssertions
; ;
@@ -66,6 +67,11 @@ in
assert !(hasDirectIP zapretHostlistRules "1.1.1.0/24"); assert !(hasDirectIP zapretHostlistRules "1.1.1.0/24");
true true
) )
(
assert !(hasDirectDomain zapretPerAppOnlyRules "youtube.com");
assert !(hasDirectDomain zapretPerAppOnlyRules "example.com");
true
)
] ]
++ invalidHostlistAssertions; ++ invalidHostlistAssertions;
} }
@@ -76,6 +76,24 @@ let
zapretHostlistRules = mkRoutingRules zapretHostlistRulesFixture; zapretHostlistRules = mkRoutingRules zapretHostlistRulesFixture;
zapretHostlistBase = mkZapretBase 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 [ invalidHostlistAssertions = mkFailingAssertions mkBadFixture [
[ [
{ {
@@ -158,6 +176,7 @@ in
inherit inherit
zapretHostlistRules zapretHostlistRules
zapretHostlistBase zapretHostlistBase
zapretPerAppOnlyRules
invalidHostlistAssertions invalidHostlistAssertions
; ;
} }
+12 -6
View File
@@ -2451,6 +2451,8 @@ def cmd_zapret(*args):
elif args[:1] == ("cutoff",): elif args[:1] == ("cutoff",):
cmd_zapret_cutoff(*args[1:]) cmd_zapret_cutoff(*args[1:])
else: 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 <zapret profile> -- <command>")
_toggle("proxy-suite-zapret", "zapret", *args) _toggle("proxy-suite-zapret", "zapret", *args)
@@ -2517,7 +2519,7 @@ def _truncate(path):
def cmd_zapret_auto(verb="list", domain="", *_): def cmd_zapret_auto(verb="list", domain="", *_):
if env("ZAPRET_AUTO_ENABLED") != "1": 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") auto = _zapret_auto_file("zapret-hosts-auto.txt")
user = _zapret_auto_file("zapret-hosts-user.txt") user = _zapret_auto_file("zapret-hosts-user.txt")
exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt") exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt")
@@ -3028,10 +3030,9 @@ def _ensure_app_routing():
require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting") require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting")
def _check_no_global_proxy(route): def _active_global_proxy():
for svc in ("proxy-suite-tun", "proxy-suite-tproxy"): """The global TUN or TProxy unit that is up, which the per-app backends would clash with."""
if svc_active(f"{svc}.service"): return next((svc 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 _has_units(*args): def _has_units(*args):
@@ -3143,7 +3144,12 @@ def cmd_apps_run(profile="", *cmd):
_exec(["proxychains4", *env("PROXYCHAINS_QUIET_ARG").split(), "-f", config, *cmd]) _exec(["proxychains4", *env("PROXYCHAINS_QUIET_ARG").split(), "-f", config, *cmd])
elif route in SLICE_ROUTES: elif route in SLICE_ROUTES:
slice_base, enabled, option = SLICE_ROUTES[route] 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": if env(enabled) != "1":
die(f"Profile '{profile}' uses route={route}, but {option} is false.") die(f"Profile '{profile}' uses route={route}, but {option} is false.")
_warn_stub_resolver(route) _warn_stub_resolver(route)
+10 -4
View File
@@ -376,6 +376,10 @@ class ServiceManagerTest(EnvTest):
ctl.cmd_zapret("restart") ctl.cmd_zapret("restart")
ctl.cmd_tor("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")]) 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. # awg toggle: a named profile flips; without one, only stopping is possible.
seen.clear() seen.clear()
self.patch("_awg_profiles", lambda: ["p", "q"]) self.patch("_awg_profiles", lambda: ["p", "q"])
@@ -920,11 +924,13 @@ class AppsRunTest(EnvTest):
self.assertEqual(status, 3) self.assertEqual(status, 3)
self.assertIn(("stop", "proxy-suite-per-app-tun.service"), self.calls) 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"} self.active = {"proxy-suite-tun.service"}
status, _, err = run(ctl.cmd_apps, "run", "tproxy", "--", "curl") status, _, err = run(ctl.cmd_apps, "run", "tproxy", "--", "curl", "x")
self.assertNotEqual(status, 0) self.assertEqual(status, 0)
self.assertIn("Global proxy-suite-tun.service is active", err) 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)) self.assertFalse(any(c[0] == "systemd-run" for c in self.calls))
def test_disabled_route(self): def test_disabled_route(self):