refactor: overhaul of options and features

Includes, but not limited to:
- zapret2 support
- declarative inbounds
- proxy-ctl revamp
- automatic proxy learning
This commit is contained in:
FUFSoB committed 2026-09-13 22:37:45 +05:00
1 parent b892384527
commit fdb2b08790
144 files changed
+13198 -14066

No files matched your search

+55 -23
View File
@@ -4,6 +4,11 @@ on:
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:
inputs:
force_nixpkgs:
description: "Update nixpkgs even when no watched package version changed"
type: boolean
default: false
permissions:
contents: write
@@ -27,38 +32,73 @@ jobs:
id: nixpkgs_gate
run: |
set -euo pipefail
chmod +x scripts/check-nixpkgs-relevance.sh
scripts/check-nixpkgs-relevance.sh >> "$GITHUB_OUTPUT"
- name: Update flake inputs
run: |
set -euo pipefail
if [[ "${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}" == "true" ]]; then
nix flake lock --update-input nixpkgs
if [[ "${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}" == "true" || "${{ inputs.force_nixpkgs }}" == "true" ]]; then
nix flake update nixpkgs
else
echo "Skipping nixpkgs update: watched package versions on nixos-unstable are unchanged."
fi
nix flake lock --update-input zapret
nix flake update zapret
- name: Update tg-ws-proxy pin
- name: Update pinned sources
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
chmod +x scripts/update-tg-ws-proxy.sh
scripts/update-tg-ws-proxy.sh
scripts/update-pins.sh --self-test
scripts/update-pins.sh | tee "$RUNNER_TEMP/pin-updates.txt"
- name: Detect dependency file changes
id: changes
run: |
set -euo pipefail
if git diff --quiet -- flake.lock pkgs/tg-ws-proxy.nix; then
if git diff --quiet -- flake.lock pkgs; then
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
- name: Build updated packages
if: steps.changes.outputs.has_changes == 'true'
run: |
set -euo pipefail
mapfile -t attrs < <(scripts/update-pins.sh --attrs)
nix build --no-link "${attrs[@]}"
- name: Run flake checks
if: steps.changes.outputs.has_changes == 'true'
run: nix flake check
run: nix flake check --print-build-logs
- name: Compose pull request body
if: steps.changes.outputs.has_changes == 'true'
run: |
set -euo pipefail
{
echo "## Automated dependency update"
echo
echo "Managed by CI; the \`ci/update-dependencies\` branch is reused across runs."
echo
echo "### Pinned sources"
if [[ -s "$RUNNER_TEMP/pin-updates.txt" ]]; then
sed 's/^/- /' "$RUNNER_TEMP/pin-updates.txt"
else
echo "- no pin changes"
fi
echo
echo "### Flake inputs"
echo "- nixpkgs updated: \`${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}\`"
echo "- changed watched attrs: \`${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}\`"
echo "- zapret: refreshed every run"
echo
echo '```'
git diff --stat -- flake.lock pkgs
echo '```'
} > "$RUNNER_TEMP/pr-body.md"
cat "$RUNNER_TEMP/pr-body.md" >> "$GITHUB_STEP_SUMMARY"
- name: Create or update pull request
if: steps.changes.outputs.has_changes == 'true'
@@ -66,23 +106,15 @@ jobs:
with:
branch: ci/update-dependencies
delete-branch: false
commit-message: "chore(deps): refresh flakes and external pins"
title: "chore(deps): refresh flakes and external pins"
add-paths: |
flake.lock
pkgs
commit-message: "chore(deps): refresh flake inputs and pinned sources"
title: "chore(deps): refresh flake inputs and pinned sources"
body-path: ${{ runner.temp }}/pr-body.md
labels: |
dependencies
nix
body: |
## Automated dependency update
This PR is managed by CI and the same branch is reused across runs.
### Included updates
- `flake.lock` updates (`zapret` always, `nixpkgs` only when watched package versions change on `nixos-unstable`)
- `pkgs/tg-ws-proxy.nix` pin refresh (`rev` + `hash`)
### Nixpkgs gate result
- should update nixpkgs: `${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}`
- changed watched attrs: `${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}`
- name: No dependency changes
if: steps.changes.outputs.has_changes != 'true'
+88 -138
View File
@@ -1,50 +1,34 @@
# proxy-suite-flake
Declarative proxy stack for NixOS.
Declarative proxy stack for NixOS, built for dealing with Roskomnadzor and the usual Russian ISP nonsense. Configure it in Nix, rebuild, and it runs as systemd services.
Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), native [AmneziaWG](https://github.com/amnezia-vpn/amneziawg-go) client tunnels, [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense.
Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), [AmneziaWG](https://github.com/amnezia-vpn/amneziawg-go), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), [zapret2](https://github.com/bol-van/zapret2) and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy).
The goal is to replace GUI clients like v2rayN and throne – you configure your proxies in Nix, rebuild, and they just work as systemd services.
## Features
---
## What it gives you
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` when `proxy.enable = true`
- **Backend choice** – use SingBox or XRay through the same `services.proxy-suite.proxy` option tree
- **Transparent proxy (TProxy)** – redirect all system traffic through the active backend without configuring each app; start/stop on demand or autostart at boot
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart
- **AmneziaWG profiles** – native AWG 1.x–3.x tunnels from `.conf`, self-contained `vpn://`, or declarative Nix configuration
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
- **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer
- **Multiple outbounds** with automatic latency-based switching or manual selection
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, socks5, socks4, http/https proxy; SingBox also supports TUIC v5, while XRay supports XHTTP/ECH share links
- **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites defined by the project
- **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy
- **SSH SOCKS5 proxy** – create a local SOCKS5 listener from an SSH connection
- **Server inbounds** – accept connections *from* outside over vless (REALITY), vmess, trojan, shadowsocks, socks, or http; relay them through your outbounds or exit directly, with share links and QR codes for clients
---
- Local SOCKS5/HTTP proxy on `127.0.0.1:1080`, backed by sing-box, XRay, or both
- Global TProxy or TUN mode, on demand or at boot
- Per-app routing: `proxy-ctl apps run <profile> -- <cmd>` through proxychains, a per-app TUN/TProxy, or zapret
- Outbounds from URLs, raw JSON or subscriptions; manual or latency-based selection; per-outbound routing
- vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC on sing-box, XHTTP/ECH on XRay
- autoProxy: finds which exit reaches a blocked site and routes it there
- zapret DPI bypass, including zapret2, which learns blocked sites at runtime
- AmneziaWG 1.x–3.x tunnels from `.conf`, `vpn://`, or Nix
- Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel
- Server inbounds with share links, QR codes, per-user subscriptions and traffic stats
- A tray indicator and the `proxy-ctl` CLI
## Setup
Add to your flake inputs:
```nix
inputs.proxy-suite.url = "github:FUFSoB/proxy-suite-flake";
```
No need to add zapret separately – it comes along as a transitive input.
Add the module to your NixOS configuration:
```nix
modules = [ inputs.proxy-suite.nixosModules.default ];
```
Feature-complete starter config:
Starter config:
```nix
services.proxy-suite = {
@@ -52,96 +36,51 @@ services.proxy-suite = {
proxy = {
enable = true;
singBox.enable = true;
# Or use XRay instead:
# xray.enable = true;
backend = "sing-box"; # or "xray", or "hybrid"
port = 1080;
# url ends up in the Nix store; use urlFile for real secrets.
outbounds = [ { tag = "nl-vps"; url = "hy2://password@example.com:443?sni=example.com"; } ];
subscriptions = [ { tag = "main-sub"; urlFile = "/run/secrets/sub-url"; } ];
selection = "urltest"; # Default is "first", without any complex selector
# Individual proxy example
outbounds = [
{
tag = "nl-vps";
# Inline url is convenient for testing, but ends up in the Nix store.
# For real use, prefer urlFile with a url file.
url = "hy2://password@example.com:443?sni=example.com";
}
];
# Subscription example
subscriptions = [
{
tag = "main-sub";
# urlFile is also available to keep the URL out of the Nix store.
url = "https://example.com/subscription-list.txt";
}
];
# Automatic switching of outbound based on latency.
# Default is "first", which just uses the first one in the list.
selection = "urltest";
# Keep both available; autostart only one global tunnel.
tproxy = {
enable = true;
autostart = false;
perApp.enable = true;
};
tun = {
enable = true;
autostart = false;
perApp.enable = true;
};
};
# Optional SSH tunnel. Set asOutbound = true to make it an ordinary proxy
# outbound tagged "ssh-proxy".
sshProxy = {
enable = true;
user = "root";
host = "ssh.example.com";
asOutbound = false;
identityFile = "/run/secrets/proxy-suite-ssh-key";
hostKeyFile = "/run/secrets/proxy-suite-ssh-known-hosts";
};
# Native AmneziaWG profiles are independent of the SingBox/XRay backend.
# Only one AWG, TUN, or TProxy global tunnel can be active at once;
# zapret is mutually exclusive with AWG while its service is running.
amneziaWg = {
enable = true;
profiles.home = {
# Secret-managed exported .conf files are the simplest input.
configFile = "/run/secrets/home-amneziawg.conf";
autostart = false;
};
# Self-contained AmneziaVPN exports are supported too:
profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn";
};
zapret = {
enable = true;
perApp.enable = true;
tproxy.enable = true;
tun.enable = true;
};
perAppRouting = {
enable = true;
createDefaultProfiles = true;
proxychains.enable = true;
tun.enable = true;
tproxy.enable = true;
zapret.enable = true;
};
tray = {
zapret.enable = true;
sshProxy = {
enable = true;
autostart = true;
server = {
user = "root";
host = "ssh.example.com";
};
identityFile = "/run/secrets/proxy-suite-ssh-key";
hostKeyFile = "/run/secrets/proxy-suite-ssh-known-hosts";
};
# Only one AWG, TUN or TProxy global tunnel runs at a time.
amneziaWg = {
enable = true;
profiles.home.configFile = "/run/secrets/home-amneziawg.conf";
profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn";
};
tgWsProxy = {
enable = true;
port = 1443;
# Inline secret is convenient for testing, but ends up in the Nix store.
# For real use, prefer secretFile with a secret file.
secret = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
secretFile = "/run/secrets/tg-ws-proxy-secret";
};
tray.enable = true;
};
```
@@ -149,44 +88,55 @@ services.proxy-suite = {
## Options
To see options and documentation, check out the [options reference](./docs/options.md).
Options and generated README help are refreshed with `nix run .#update-docs`.
---
See the [options reference](./docs/options/index.md), one page per option group. Regenerate it and the help below with `nix run .#update-docs`.
## `proxy-ctl help`
Generated from current `proxy-ctl help` output.
<!-- proxy-ctl-help:start -->
```text
Usage: proxy-ctl <command> [args]
Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list.
Commands:
help show this help message
status [--tray] show status of all proxy-suite services
proxy on|off enable/disable the proxy backend stack
tproxy on|off enable/disable TProxy transparent mode
tun on|off enable/disable TUN mode
ssh on|off enable/disable the SSH SOCKS5 proxy
awg list|status [profile] list profiles or show AmneziaWG status
awg on <profile> start an AmneziaWG profile
awg off [profile] stop one or all active AmneziaWG profiles
awg restart [profile] restart one or all active AmneziaWG profiles
route-mode default|whitelist|blacklist|all-proxy|all-bypass|status
set temporary routing override
zapret on|off enable/disable zapret-discord-youtube
restart restart active global proxy-suite services
logs [service] follow service logs (default: proxy-suite-socks)
outbounds list outbounds and current selection
select <tag> switch to a specific outbound (selector mode)
apps list configured per-app routing profiles
wrap <profile> -- <cmd> run a command via a perAppRouting profile
subscription list show subscriptions, cache age, and proxy count
subscription update force-refresh all subscription caches and restart active proxy services
inbounds [list] list server inbounds and their state
inbounds link <tag> [user] print the client share link for an inbound
inbounds qr <tag> [user] print the client share link as a QR code
status [--tray] services and routing mode
restart restart active services
logs [unit] follow logs (default: every proxy-suite unit)
where <domain> how this host is routed right now
proxy [status|on|off] local proxy backend
proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url> add an outbound at runtime
proxy outbounds rm <tag> remove a runtime outbound
proxy select [<tag>|auto] pin the priority outbound (no tag: pick from a menu)
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
show or override the routing mode
proxy subs [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl)
proxy auto probe <domain>[/path] [--json] [--exits a,b | --via tag]
find an exit that reaches a domain
proxy auto learn <domain> probe now and route it if an exit works (sudo)
proxy auto queue [count] destinations waiting to be probed (sudo, or userControl)
zapret [status|on|off] DPI bypass
zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo)
zapret auto clear forget every learned host (sudo)
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
ssh [status|on|off] SSH SOCKS5 tunnel
apps [list] per-app routing profiles
apps run <profile> -- <cmd> [args] run a command through a profile
inbounds [list] server inbounds
inbounds link <tag> [user] [--qr] client share link
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] traffic per user (sudo, or userControl)
```
<!-- proxy-ctl-help:end -->
-9592
View File
File diff suppressed because it is too large. Load diff
+885
View File
@@ -0,0 +1,885 @@
# services.proxy-suite.amneziaWg
Part of the [proxy-suite options reference](./index.md).
## Options
- amneziaWg
- [enable](#services-proxy-suite-amneziawg-enable)
- [kernelModulePackage](#services-proxy-suite-amneziawg-kernelmodulepackage)
- [profiles](#services-proxy-suite-amneziawg-profiles)
- `<name>`
- [allowConfigHooks](#services-proxy-suite-amneziawg-profiles-name-allowconfighooks)
- [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart)
- [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile)
- [interfaceName](#services-proxy-suite-amneziawg-profiles-name-interfacename)
- [settings](#services-proxy-suite-amneziawg-profiles-name-settings)
- [addresses](#services-proxy-suite-amneziawg-profiles-name-settings-addresses)
- [dns](#services-proxy-suite-amneziawg-profiles-name-settings-dns)
- [listenPort](#services-proxy-suite-amneziawg-profiles-name-settings-listenport)
- [mtu](#services-proxy-suite-amneziawg-profiles-name-settings-mtu)
- [obfuscation](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation)
- [contentPaddingAddition](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-contentpaddingaddition)
- [disableCookies](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-disablecookies)
- [h1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h1)
- [h2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h2)
- [h3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h3)
- [h4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h4)
- [headerProtectionKey](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkey)
- [headerProtectionKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkeyfile)
- [i1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i1)
- [i2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i2)
- [i3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i3)
- [i4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i4)
- [i5](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i5)
- [jc](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jc)
- [jmax](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmax)
- [jmin](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmin)
- [keepaliveTimeout](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-keepalivetimeout)
- [maxHandshakeAttempts](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-maxhandshakeattempts)
- [randomTrailers](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-randomtrailers)
- [rejectAfterTime](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rejectaftertime)
- [rekeyAfterTime](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeyaftertime)
- [rekeyTimeout](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeytimeout)
- [s1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s1)
- [s2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s2)
- [s3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s3)
- [s4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s4)
- [obfuscationFile](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscationfile)
- [peers](#services-proxy-suite-amneziawg-profiles-name-settings-peers)
- item
- [advancedSecurity](#services-proxy-suite-amneziawg-profiles-name-settings-peers-advancedsecurity)
- [allowedIPs](#services-proxy-suite-amneziawg-profiles-name-settings-peers-allowedips)
- [endpoint](#services-proxy-suite-amneziawg-profiles-name-settings-peers-endpoint)
- [persistentKeepalive](#services-proxy-suite-amneziawg-profiles-name-settings-peers-persistentkeepalive)
- [presharedKey](#services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkey)
- [presharedKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkeyfile)
- [publicKey](#services-proxy-suite-amneziawg-profiles-name-settings-peers-publickey)
- [privateKey](#services-proxy-suite-amneziawg-profiles-name-settings-privatekey)
- [privateKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-privatekeyfile)
- [table](#services-proxy-suite-amneziawg-profiles-name-settings-table)
- [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn)
- [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer)
- [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile)
- [toolsPackage](#services-proxy-suite-amneziawg-toolspackage)
- [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage)
<a id="services-proxy-suite-amneziawg-enable"></a>
## services\.proxy-suite\.amneziaWg\.enable
Whether to enable native AmneziaWG client profiles\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-amneziawg-kernelmodulepackage"></a>
## services\.proxy-suite\.amneziaWg\.kernelModulePackage
AWG 3\.1 kernel module package\. Set null to use userspace-only fallback\.
*Type:*
null or package
*Default:*
```nix
<derivation amneziawg-3.1.20260812>
```
<a id="services-proxy-suite-amneziawg-profiles"></a>
## services\.proxy-suite\.amneziaWg\.profiles
Named AmneziaWG client profiles\. Only one global profile can be active\.
*Type:*
attribute set of (submodule)
*Default:*
```nix
{ }
```
<a id="services-proxy-suite-amneziawg-profiles-name-allowconfighooks"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.allowConfigHooks
Allow trusted imported configs to execute wg-quick hooks or use SaveConfig\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-amneziawg-profiles-name-autostart"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.autostart
Whether to start this profile at boot\. At most one profile may autostart\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-amneziawg-profiles-name-configfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.configFile
Runtime path to an AmneziaWG \.conf file\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-interfacename"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.interfaceName
Linux interface name\. It must fit Linux’s 15-character limit\.
*Type:*
string matching the pattern ^\[A-Za-z0-9_\.-]{1,15}$
*Default:*
```nix
"awg-‹name›"
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings
Typed declarative AmneziaWG client configuration\.
*Type:*
null or (submodule)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-addresses"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.addresses
IP prefixes assigned to the AWG interface\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"10.8.0.2/32"
]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-dns"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.dns
DNS servers installed while this profile is active\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-listenport"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.listenPort
Optional local UDP listen port\.
*Type:*
null or 16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-mtu"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.mtu
Optional interface MTU\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation
AmneziaWG 1\.x through 3\.x obfuscation parameters\.
*Type:*
submodule
*Default:*
```nix
{ }
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-contentpaddingaddition"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.contentPaddingAddition
AWG 3 content-padding addition or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-disablecookies"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.disableCookies
AWG 3 cookie suppression (DisableCookies)\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h1"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h1
Handshake-init header or range (H1)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h2"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h2
Handshake-response header or range (H2)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h3"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h3
Cookie-reply header or range (H3)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h4"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h4
Transport-message header or range (H4)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.headerProtectionKey
Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkeyfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.headerProtectionKeyFile
Runtime path containing the AWG 3 header-protection key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i1"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i1
First custom signature packet (I1)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i2"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i2
Second custom signature packet (I2)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i3"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i3
Third custom signature packet (I3)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i4"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i4
Fourth custom signature packet (I4)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i5"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i5
Fifth custom signature packet (I5)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jc"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.jc
Junk packet count (Jc)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmax"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.jmax
Maximum junk packet size (Jmax)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmin"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.jmin
Minimum junk packet size (Jmin)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-keepalivetimeout"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.keepaliveTimeout
AWG 3 keepalive timeout or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-maxhandshakeattempts"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.maxHandshakeAttempts
AWG 3 maximum handshake attempts or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-randomtrailers"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.randomTrailers
AWG 3 random transport trailers (RandomTrailers)\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rejectaftertime"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.rejectAfterTime
AWG 3 reject-after interval or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeyaftertime"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.rekeyAfterTime
AWG 3 rekey interval or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeytimeout"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.rekeyTimeout
AWG 3 rekey timeout or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s1"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s1
Handshake-init padding (S1)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s2"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s2
Handshake-response padding (S2)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s3"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s3
Cookie-reply padding (S3)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s4"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s4
Transport-message padding (S4)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscationfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscationFile
Runtime path to a partial JSON object using the same field names and
value types as obfuscation, excluding headerProtectionKeyFile\.
Values are combined with public obfuscation settings at service startup
without putting the file contents in the Nix store\. Omitted or null
fields are unset; duplicate JSON keys and fields set in both sources
are rejected\. A file-provided headerProtectionKey also conflicts with
obfuscation\.headerProtectionKeyFile\. Private and preshared keys use
their existing file options\. Restart the profile after secret rotation\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/awg-obfuscation.json"
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers
AmneziaWG peers\.
*Type:*
list of (submodule)
*Default:*
```nix
[ ]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-advancedsecurity"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.advancedSecurity
Optional AWG peer AdvancedSecurity setting\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-allowedips"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.allowedIPs
IP prefixes routed to and accepted from this peer\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"0.0.0.0/0"
"::/0"
]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-endpoint"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.endpoint
Optional peer endpoint in host:port form\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"vpn.example.com:51820"
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-persistentkeepalive"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.persistentKeepalive
Persistent keepalive seconds, optionally expressed as an AWG 3 range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.presharedKey
Inline peer preshared key\. Prefer presharedKeyFile for secrets\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkeyfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.presharedKeyFile
Runtime path containing the peer preshared key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-publickey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.publicKey
AmneziaWG peer public key\.
*Type:*
string matching the pattern \[^\[:space:]]+
<a id="services-proxy-suite-amneziawg-profiles-name-settings-privatekey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.privateKey
Inline client private key\. Prefer privateKeyFile\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-privatekeyfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.privateKeyFile
Runtime path containing the client private key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-table"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.table
wg-quick routing table name/number, auto, or off\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-vpn"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.vpn
Inline self-contained vpn:// export\. This value is stored in the Nix store\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-vpncontainer"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.vpnContainer
AWG container/protocol identifier to select when a vpn:// bundle is ambiguous\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-vpnfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.vpnFile
Runtime path containing a self-contained vpn:// export\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-toolspackage"></a>
## services\.proxy-suite\.amneziaWg\.toolsPackage
AWG 3\.1 package providing awg and awg-quick\.
*Type:*
package
*Default:*
```nix
<derivation amneziawg-tools-3.1.20260812>
```
<a id="services-proxy-suite-amneziawg-userspacepackage"></a>
## services\.proxy-suite\.amneziaWg\.userspacePackage
AWG 3\.1 userspace implementation used when the kernel interface is unavailable\.
*Type:*
package
*Default:*
```nix
<derivation amneziawg-go-3.1.20260828>
```
+55
View File
@@ -0,0 +1,55 @@
# services.proxy-suite.geodata
Part of the [proxy-suite options reference](./index.md).
## Options
- geodata
- singBox
- [geoip](#services-proxy-suite-geodata-singbox-geoip)
- [geosite](#services-proxy-suite-geodata-singbox-geosite)
- xray
- [assets](#services-proxy-suite-geodata-xray-assets)
<a id="services-proxy-suite-geodata-singbox-geoip"></a>
## services\.proxy-suite\.geodata\.singBox\.geoip
Package with share/sing-box/rule-set/geoip-NAME\.srs (country codes by default)\.
*Type:*
package
*Default:*
```nix
pkgs.sing-geoip
```
<a id="services-proxy-suite-geodata-singbox-geosite"></a>
## services\.proxy-suite\.geodata\.singBox\.geosite
Package with share/sing-box/rule-set/geosite-NAME\.srs\.
*Type:*
package
*Default:*
```nix
pkgs.sing-geosite
```
<a id="services-proxy-suite-geodata-xray-assets"></a>
## services\.proxy-suite\.geodata\.xray\.assets
Package with share/v2ray/{geoip,geosite}\.dat for every XRay process\. Null uses XRay’s own
country-only data, where a tag like “geoip:telegram” stops XRay from starting\.
*Type:*
null or package
*Default:*
```nix
pkgs.v2ray-rules-dat
```
File diff suppressed because it is too large. Load diff
+353
View File
@@ -0,0 +1,353 @@
# proxy-suite options
Generated from the `services.proxy-suite` option descriptions under
[`modules/proxy-suite/options/`](/modules/proxy-suite/options/).
Update the module option docs there instead of editing these files by hand.
## Option groups
- [amneziaWg](./amneziaWg.md)
- [geodata](./geodata.md)
- [inbounds](./inbounds.md)
- [perAppRouting](./perAppRouting.md)
- [proxy](./proxy.md)
- [sshProxy](./sshProxy.md)
- [tgWsProxy](./tgWsProxy.md)
- [tray](./tray.md)
- [userControl](./userControl.md)
- [zapret](./zapret.md)
## Complete default config
```nix
services.proxy-suite = {
amneziaWg = {
enable = false;
kernelModulePackage = pkgs.amneziawg;
profiles = { };
toolsPackage = pkgs.amneziawg-tools;
userspacePackage = pkgs.amneziawg-go;
};
enable = false;
geodata = {
singBox = {
geoip = pkgs.sing-geoip;
geosite = pkgs.sing-geosite;
};
xray = {
assets = pkgs.v2ray-rules-dat;
};
};
inbounds = {
enable = false;
listeners = { };
openFirewall = true;
package = pkgs.xray;
routing = {
blockPrivate = true;
blockRu = true;
proxy = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
via = "proxy";
zapretDirect = true;
};
serverAddress = null;
shareLinks = true;
subscriptions = {
baseUrl = null;
enable = false;
group = "nginx";
};
};
perAppRouting = {
createDefaultProfiles = false;
enable = false;
profiles = [ ];
proxychains = {
enable = false;
proxyDns = true;
quiet = true;
};
tproxy = {
enable = false;
fwmark = 17;
localSubnets = [
"192.168.0.0/16"
];
routeTable = 102;
};
tun = {
address = "172.20.0.1/30";
enable = false;
fwmark = 16;
interface = "psperapptun0";
localSubnets = [
"192.168.0.0/16"
];
mtu = 1400;
routeTable = 101;
};
zapret = {
enable = false;
filterMark = 268435456;
qnum = 201;
};
};
proxy = {
auth = { };
autoProxy = {
enable = false;
exclude = [ ];
interval = "10m";
maxExits = 12;
probeBasePort = 18540;
probesPerRun = 200;
slowBelowKiBps = 150;
ttlDays = 30;
};
autostart = null;
backend = "sing-box";
dns = {
local = {
address = "1.1.1.1";
port = 53;
type = "udp";
};
remote = {
address = "1.1.1.1";
port = 53;
type = "udp";
};
};
enable = false;
listener = {
address = "127.0.0.1";
auth = {
password = null;
passwordFile = null;
username = null;
};
port = 1080;
};
outbounds = [ ];
routing = {
block = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
default = "proxy";
direct = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
directRu = true;
proxy = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
rules = [ ];
};
selection = "first";
singBox = {
clashApiPort = 9090;
package = pkgs.sing-box;
urlTest = { };
};
subscriptionUpdateInterval = "1d";
subscriptions = [ ];
tproxy = {
enable = false;
fwmark = 1;
localSubnets = [
"192.168.0.0/16"
];
port = 1085;
proxyMark = 2;
routeTable = 100;
};
tun = {
address = "172.19.0.1/30";
enable = false;
interface = "singtun0";
mtu = 1400;
};
urlTest = {
interval = "3m";
tolerance = 50;
url = "https://www.gstatic.com/generate_204";
};
xray = {
package = pkgs.xray;
};
};
sshProxy = {
asOutbound = false;
domainStrategy = null;
enable = false;
extraArgs = [ ];
hostKey = [ ];
hostKeyFile = null;
identityFile = null;
knownHostsFile = null;
listener = {
address = "127.0.0.1";
port = 1091;
};
server = {
host = null;
port = 22;
user = null;
};
serviceUser = null;
strictHostKeyChecking = "accept-new";
};
tgWsProxy = {
bufferKiB = 256;
bypassTransparentProxy = true;
cloudflare = {
domains = [ ];
fallback = true;
workerDomains = [ ];
};
dcIps = { };
enable = false;
fakeTlsDomain = null;
fwmark = 4;
listener = {
address = "127.0.0.1";
port = 1443;
};
log = {
file = null;
keep = 1;
maxSizeMiB = 5.0;
verbose = false;
};
poolSize = 4;
proxyProtocol = false;
secret = null;
secretFile = null;
};
tray = {
autostart = true;
enable = false;
pollInterval = 5;
};
userControl = {
allow = [
"global"
"perApp"
];
global = { };
group = "proxy-suite";
perApp = { };
};
zapret = {
cidrExemption = {
cidrs = [ ];
enable = false;
};
directSync = {
enable = true;
upstreamIps = false;
userIps = true;
};
enable = false;
engine = "zapret-discord-youtube";
zapret-discord-youtube = {
configName = "general(ALT)";
domains = [ ];
excludeDomains = [ ];
excludeIps = [ ];
gameFilter = "null";
hostlistRules = [ ];
includeExtraUpstreamLists = false;
ips = [ ];
};
zapret2 = {
autoHostlist = {
debugLog = false;
enable = true;
failThreshold = 3;
failTime = 300;
incomingMaxseq = 4096;
retransMaxseq = 32768;
retransReset = true;
retransThreshold = 3;
udpIn = 1;
udpOut = 4;
};
blobs = {
quic_initial = "quic_initial_www_google_com.bin";
tls_clienthello = "tls_clienthello_www_google_com.bin";
};
domains = [ ];
excludeDomains = [ ];
ipv6 = false;
ports = {
tcp = "80,443,1984,2053,2083,2087,2096,5222,8443";
udp = "443,590-600,1400,3478-3481,5349,19294-19344,49152-65535";
};
profiles = [
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
];
};
};
};
```
<a id="services-proxy-suite-enable"></a>
## services\.proxy-suite\.enable
Whether to enable proxy-suite\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
+407
View File
@@ -0,0 +1,407 @@
# services.proxy-suite.perAppRouting
Part of the [proxy-suite options reference](./index.md).
## Options
- perAppRouting
- [enable](#services-proxy-suite-perapprouting-enable)
- [createDefaultProfiles](#services-proxy-suite-perapprouting-createdefaultprofiles)
- [profiles](#services-proxy-suite-perapprouting-profiles)
- item
- [name](#services-proxy-suite-perapprouting-profiles-name)
- [route](#services-proxy-suite-perapprouting-profiles-route)
- proxychains
- [enable](#services-proxy-suite-perapprouting-proxychains-enable)
- [proxyDns](#services-proxy-suite-perapprouting-proxychains-proxydns)
- [quiet](#services-proxy-suite-perapprouting-proxychains-quiet)
- tproxy
- [enable](#services-proxy-suite-perapprouting-tproxy-enable)
- [fwmark](#services-proxy-suite-perapprouting-tproxy-fwmark)
- [localSubnets](#services-proxy-suite-perapprouting-tproxy-localsubnets)
- [routeTable](#services-proxy-suite-perapprouting-tproxy-routetable)
- tun
- [enable](#services-proxy-suite-perapprouting-tun-enable)
- [address](#services-proxy-suite-perapprouting-tun-address)
- [fwmark](#services-proxy-suite-perapprouting-tun-fwmark)
- [interface](#services-proxy-suite-perapprouting-tun-interface)
- [localSubnets](#services-proxy-suite-perapprouting-tun-localsubnets)
- [mtu](#services-proxy-suite-perapprouting-tun-mtu)
- [routeTable](#services-proxy-suite-perapprouting-tun-routetable)
- zapret
- [enable](#services-proxy-suite-perapprouting-zapret-enable)
- [filterMark](#services-proxy-suite-perapprouting-zapret-filtermark)
- [qnum](#services-proxy-suite-perapprouting-zapret-qnum)
<a id="services-proxy-suite-perapprouting-enable"></a>
## services\.proxy-suite\.perAppRouting\.enable
Whether to enable per-app routing (` proxy-ctl apps run `)\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-createdefaultprofiles"></a>
## services\.proxy-suite\.perAppRouting\.createDefaultProfiles
Add a profile named after each enabled backend (proxychains, tun, tproxy, zapret) unless
one with that name already exists\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-perapprouting-profiles"></a>
## services\.proxy-suite\.perAppRouting\.profiles
Profiles for ` proxy-ctl apps run <name> -- <command> `\.
*Type:*
list of (submodule)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
{
name = "steam-browser";
route = "proxychains";
}
]
```
<a id="services-proxy-suite-perapprouting-profiles-name"></a>
## services\.proxy-suite\.perAppRouting\.profiles\.\*\.name
Profile name, unique\.
*Type:*
string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$
*Example:*
```nix
"steam-browser"
```
<a id="services-proxy-suite-perapprouting-profiles-route"></a>
## services\.proxy-suite\.perAppRouting\.profiles\.\*\.route
Backend: “direct” (unchanged), “proxychains”, or the per-app “tun”, “tproxy” or “zapret”
backend of perAppRouting\.
*Type:*
one of “direct”, “proxychains”, “tun”, “tproxy”, “zapret”
*Default:*
```nix
"proxychains"
```
<a id="services-proxy-suite-perapprouting-proxychains-enable"></a>
## services\.proxy-suite\.perAppRouting\.proxychains\.enable
Whether to enable the proxychains backend (TCP apps, through LD_PRELOAD)\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-proxychains-proxydns"></a>
## services\.proxy-suite\.perAppRouting\.proxychains\.proxyDns
Resolve DNS through the proxy (proxy_dns)\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-proxychains-quiet"></a>
## services\.proxy-suite\.perAppRouting\.proxychains\.quiet
Silence proxychains (quiet_mode)\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-tproxy-enable"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.enable
Whether to enable the per-app TProxy backend\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-tproxy-fwmark"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.fwmark
Mark that steers wrapped apps into routeTable\.
*Type:*
signed integer
*Default:*
```nix
17
```
<a id="services-proxy-suite-perapprouting-tproxy-localsubnets"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.localSubnets
Subnets that bypass interception (DNS excepted)\.
*Type:*
list of string
*Default:*
```nix
[
"192.168.0.0/16"
]
```
*Example:*
```nix
[
"192.168.0.0/16"
"10.0.0.0/8"
]
```
<a id="services-proxy-suite-perapprouting-tproxy-routetable"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.routeTable
Policy-routing table of the per-app TProxy\.
*Type:*
signed integer
*Default:*
```nix
102
```
<a id="services-proxy-suite-perapprouting-tun-enable"></a>
## services\.proxy-suite\.perAppRouting\.tun\.enable
Whether to enable the per-app TUN backend\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-tun-address"></a>
## services\.proxy-suite\.perAppRouting\.tun\.address
Per-app TUN interface address (CIDR)\.
*Type:*
string
*Default:*
```nix
"172.20.0.1/30"
```
<a id="services-proxy-suite-perapprouting-tun-fwmark"></a>
## services\.proxy-suite\.perAppRouting\.tun\.fwmark
Mark that steers wrapped apps into routeTable\.
*Type:*
signed integer
*Default:*
```nix
16
```
<a id="services-proxy-suite-perapprouting-tun-interface"></a>
## services\.proxy-suite\.perAppRouting\.tun\.interface
Per-app TUN interface name\.
*Type:*
string
*Default:*
```nix
"psperapptun0"
```
<a id="services-proxy-suite-perapprouting-tun-localsubnets"></a>
## services\.proxy-suite\.perAppRouting\.tun\.localSubnets
Subnets wrapped apps reach directly\.
*Type:*
list of string
*Default:*
```nix
[
"192.168.0.0/16"
]
```
*Example:*
```nix
[
"192.168.0.0/16"
"10.0.0.0/8"
]
```
<a id="services-proxy-suite-perapprouting-tun-mtu"></a>
## services\.proxy-suite\.perAppRouting\.tun\.mtu
Per-app TUN interface MTU\.
*Type:*
signed integer
*Default:*
```nix
1400
```
<a id="services-proxy-suite-perapprouting-tun-routetable"></a>
## services\.proxy-suite\.perAppRouting\.tun\.routeTable
Policy-routing table of the per-app TUN\.
*Type:*
signed integer
*Default:*
```nix
101
```
<a id="services-proxy-suite-perapprouting-zapret-enable"></a>
## services\.proxy-suite\.perAppRouting\.zapret\.enable
Whether to enable the per-app zapret backend: a second zapret instance for wrapped apps only\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-zapret-filtermark"></a>
## services\.proxy-suite\.perAppRouting\.zapret\.filterMark
Mark bit that selects wrapped app traffic\.
*Type:*
signed integer
*Default:*
```nix
268435456
```
<a id="services-proxy-suite-perapprouting-zapret-qnum"></a>
## services\.proxy-suite\.perAppRouting\.zapret\.qnum
NFQUEUE number\. Must differ from the global instance’s\.
*Type:*
signed integer
*Default:*
```nix
201
```
File diff suppressed because it is too large. Load diff
+307
View File
@@ -0,0 +1,307 @@
# services.proxy-suite.sshProxy
Part of the [proxy-suite options reference](./index.md).
## Options
- sshProxy
- [enable](#services-proxy-suite-sshproxy-enable)
- [asOutbound](#services-proxy-suite-sshproxy-asoutbound)
- [domainStrategy](#services-proxy-suite-sshproxy-domainstrategy)
- [extraArgs](#services-proxy-suite-sshproxy-extraargs)
- [hostKey](#services-proxy-suite-sshproxy-hostkey)
- [hostKeyFile](#services-proxy-suite-sshproxy-hostkeyfile)
- [identityFile](#services-proxy-suite-sshproxy-identityfile)
- [knownHostsFile](#services-proxy-suite-sshproxy-knownhostsfile)
- listener
- [address](#services-proxy-suite-sshproxy-listener-address)
- [port](#services-proxy-suite-sshproxy-listener-port)
- server
- [host](#services-proxy-suite-sshproxy-server-host)
- [port](#services-proxy-suite-sshproxy-server-port)
- [user](#services-proxy-suite-sshproxy-server-user)
- [serviceUser](#services-proxy-suite-sshproxy-serviceuser)
- [strictHostKeyChecking](#services-proxy-suite-sshproxy-stricthostkeychecking)
<a id="services-proxy-suite-sshproxy-enable"></a>
## services\.proxy-suite\.sshProxy\.enable
Whether to enable an SSH dynamic SOCKS5 tunnel\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-sshproxy-asoutbound"></a>
## services\.proxy-suite\.sshProxy\.asOutbound
Add the tunnel as an outbound tagged “ssh-proxy”\. sing-box dials SSH itself; XRay goes
through the OpenSSH unit’s SOCKS listener\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-sshproxy-domainstrategy"></a>
## services\.proxy-suite\.sshProxy\.domainStrategy
Resolve destinations locally before the tunnel (XRay only)\. Can break geo-steered CDNs\.
*Type:*
null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only”
*Default:*
```nix
null
```
*Example:*
```nix
"prefer_ipv4"
```
<a id="services-proxy-suite-sshproxy-extraargs"></a>
## services\.proxy-suite\.sshProxy\.extraArgs
Extra OpenSSH arguments\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"-J"
"jump.example.com"
]
```
<a id="services-proxy-suite-sshproxy-hostkey"></a>
## services\.proxy-suite\.sshProxy\.hostKey
Accepted host keys (sing-box)\. List every key ` ssh-keyscan ` prints: the algorithm is
negotiated\. Empty accepts any key\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..."
]
```
<a id="services-proxy-suite-sshproxy-hostkeyfile"></a>
## services\.proxy-suite\.sshProxy\.hostKeyFile
Known-hosts file to read hostKey from at runtime (sing-box)\. Wins over hostKey\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/root/.ssh/known_hosts"
```
<a id="services-proxy-suite-sshproxy-identityfile"></a>
## services\.proxy-suite\.sshProxy\.identityFile
Runtime path to the private key\. Null uses the agent or OpenSSH defaults\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/proxy-suite-ssh-key"
```
<a id="services-proxy-suite-sshproxy-knownhostsfile"></a>
## services\.proxy-suite\.sshProxy\.knownHostsFile
Known-hosts file for OpenSSH\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/proxy-suite-ssh-known-hosts"
```
<a id="services-proxy-suite-sshproxy-listener-address"></a>
## services\.proxy-suite\.sshProxy\.listener\.address
Address of the OpenSSH SOCKS5 listener\.
*Type:*
string matching the pattern \[^\[:space:]]+
*Default:*
```nix
"127.0.0.1"
```
<a id="services-proxy-suite-sshproxy-listener-port"></a>
## services\.proxy-suite\.sshProxy\.listener\.port
Port of the OpenSSH SOCKS5 listener\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
1091
```
<a id="services-proxy-suite-sshproxy-server-host"></a>
## services\.proxy-suite\.sshProxy\.server\.host
SSH server\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
null
```
*Example:*
```nix
"ssh.example.com"
```
<a id="services-proxy-suite-sshproxy-server-port"></a>
## services\.proxy-suite\.sshProxy\.server\.port
SSH server port\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
22
```
<a id="services-proxy-suite-sshproxy-server-user"></a>
## services\.proxy-suite\.sshProxy\.server\.user
SSH login user\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
null
```
*Example:*
```nix
"root"
```
<a id="services-proxy-suite-sshproxy-serviceuser"></a>
## services\.proxy-suite\.sshProxy\.serviceUser
Unix user running the OpenSSH unit\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
null
```
*Example:*
```nix
"proxy"
```
<a id="services-proxy-suite-sshproxy-stricthostkeychecking"></a>
## services\.proxy-suite\.sshProxy\.strictHostKeyChecking
OpenSSH host key policy\.
*Type:*
one of “yes”, “accept-new”, “no”
*Default:*
```nix
"accept-new"
```
*Example:*
```nix
"yes"
```
+349
View File
@@ -0,0 +1,349 @@
# services.proxy-suite.tgWsProxy
Part of the [proxy-suite options reference](./index.md).
## Options
- tgWsProxy
- [enable](#services-proxy-suite-tgwsproxy-enable)
- [bufferKiB](#services-proxy-suite-tgwsproxy-bufferkib)
- [bypassTransparentProxy](#services-proxy-suite-tgwsproxy-bypasstransparentproxy)
- cloudflare
- [domains](#services-proxy-suite-tgwsproxy-cloudflare-domains)
- [fallback](#services-proxy-suite-tgwsproxy-cloudflare-fallback)
- [workerDomains](#services-proxy-suite-tgwsproxy-cloudflare-workerdomains)
- [dcIps](#services-proxy-suite-tgwsproxy-dcips)
- [fakeTlsDomain](#services-proxy-suite-tgwsproxy-faketlsdomain)
- [fwmark](#services-proxy-suite-tgwsproxy-fwmark)
- listener
- [address](#services-proxy-suite-tgwsproxy-listener-address)
- [port](#services-proxy-suite-tgwsproxy-listener-port)
- log
- [file](#services-proxy-suite-tgwsproxy-log-file)
- [keep](#services-proxy-suite-tgwsproxy-log-keep)
- [maxSizeMiB](#services-proxy-suite-tgwsproxy-log-maxsizemib)
- [verbose](#services-proxy-suite-tgwsproxy-log-verbose)
- [poolSize](#services-proxy-suite-tgwsproxy-poolsize)
- [proxyProtocol](#services-proxy-suite-tgwsproxy-proxyprotocol)
- [secret](#services-proxy-suite-tgwsproxy-secret)
- [secretFile](#services-proxy-suite-tgwsproxy-secretfile)
<a id="services-proxy-suite-tgwsproxy-enable"></a>
## services\.proxy-suite\.tgWsProxy\.enable
Whether to enable the Telegram MTProto WebSocket proxy\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-tgwsproxy-bufferkib"></a>
## services\.proxy-suite\.tgWsProxy\.bufferKiB
Socket buffer size, in KiB\.
*Type:*
integer between 4 and 2147483647 (both inclusive)
*Default:*
```nix
256
```
<a id="services-proxy-suite-tgwsproxy-bypasstransparentproxy"></a>
## services\.proxy-suite\.tgWsProxy\.bypassTransparentProxy
Keep the relay’s own connections out of TUN/TProxy, which would otherwise loop them\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-tgwsproxy-cloudflare-domains"></a>
## services\.proxy-suite\.tgWsProxy\.cloudflare\.domains
Cloudflare-proxied domains for WebSocket fallback\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"cdn.example.com"
]
```
<a id="services-proxy-suite-tgwsproxy-cloudflare-fallback"></a>
## services\.proxy-suite\.tgWsProxy\.cloudflare\.fallback
Fall back to Cloudflare when direct WebSocket fails\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-tgwsproxy-cloudflare-workerdomains"></a>
## services\.proxy-suite\.tgWsProxy\.cloudflare\.workerDomains
Cloudflare Worker domains, tried first\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"worker.example.com"
]
```
<a id="services-proxy-suite-tgwsproxy-dcips"></a>
## services\.proxy-suite\.tgWsProxy\.dcIps
Relay IP per Telegram DC ID\.
*Type:*
attribute set of string
*Default:*
```nix
{ }
```
*Example:*
```nix
{
"2" = "149.154.167.220";
}
```
<a id="services-proxy-suite-tgwsproxy-faketlsdomain"></a>
## services\.proxy-suite\.tgWsProxy\.fakeTlsDomain
SNI for Fake TLS masking (ee-secret links)\.
*Type:*
null or string matching the pattern \.+
*Default:*
```nix
null
```
*Example:*
```nix
"www.example.com"
```
<a id="services-proxy-suite-tgwsproxy-fwmark"></a>
## services\.proxy-suite\.tgWsProxy\.fwmark
Packet mark bypassTransparentProxy uses\.
*Type:*
signed integer
*Default:*
```nix
4
```
<a id="services-proxy-suite-tgwsproxy-listener-address"></a>
## services\.proxy-suite\.tgWsProxy\.listener\.address
Bind address\.
*Type:*
string
*Default:*
```nix
"127.0.0.1"
```
<a id="services-proxy-suite-tgwsproxy-listener-port"></a>
## services\.proxy-suite\.tgWsProxy\.listener\.port
Listen port\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
1443
```
<a id="services-proxy-suite-tgwsproxy-log-file"></a>
## services\.proxy-suite\.tgWsProxy\.log\.file
Rotating log file\. Null logs to stderr\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/var/log/tg-ws-proxy.log"
```
<a id="services-proxy-suite-tgwsproxy-log-keep"></a>
## services\.proxy-suite\.tgWsProxy\.log\.keep
Rotated logs kept\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
1
```
<a id="services-proxy-suite-tgwsproxy-log-maxsizemib"></a>
## services\.proxy-suite\.tgWsProxy\.log\.maxSizeMiB
Log size before rotation, in MiB\.
*Type:*
positive integer or floating point number, meaning >0
*Default:*
```nix
5.0
```
<a id="services-proxy-suite-tgwsproxy-log-verbose"></a>
## services\.proxy-suite\.tgWsProxy\.log\.verbose
Debug logging\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-tgwsproxy-poolsize"></a>
## services\.proxy-suite\.tgWsProxy\.poolSize
WebSocket pool size per DC; 0 disables pooling\.
*Type:*
unsigned integer, meaning >=0
*Default:*
```nix
4
```
<a id="services-proxy-suite-tgwsproxy-proxyprotocol"></a>
## services\.proxy-suite\.tgWsProxy\.proxyProtocol
Accept a PROXY protocol v1 header from a fronting reverse proxy\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-tgwsproxy-secret"></a>
## services\.proxy-suite\.tgWsProxy\.secret
Inline MTProto secret (` openssl rand -hex 16 `)\. Ends up in the Nix store; prefer secretFile\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
```
<a id="services-proxy-suite-tgwsproxy-secretfile"></a>
## services\.proxy-suite\.tgWsProxy\.secretFile
Runtime path to the MTProto secret\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/tg-ws-proxy-secret"
```
+58
View File
@@ -0,0 +1,58 @@
# services.proxy-suite.tray
Part of the [proxy-suite options reference](./index.md).
## Options
- tray
- [enable](#services-proxy-suite-tray-enable)
- [autostart](#services-proxy-suite-tray-autostart)
- [pollInterval](#services-proxy-suite-tray-pollinterval)
<a id="services-proxy-suite-tray-enable"></a>
## services\.proxy-suite\.tray\.enable
Whether to enable the system tray indicator\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-tray-autostart"></a>
## services\.proxy-suite\.tray\.autostart
Start the tray in graphical sessions (XDG autostart)\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-tray-pollinterval"></a>
## services\.proxy-suite\.tray\.pollInterval
Status refresh interval, in seconds\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
5
```
+52
View File
@@ -0,0 +1,52 @@
# services.proxy-suite.userControl
Part of the [proxy-suite options reference](./index.md).
## Options
- userControl
- [allow](#services-proxy-suite-usercontrol-allow)
- [group](#services-proxy-suite-usercontrol-group)
<a id="services-proxy-suite-usercontrol-allow"></a>
## services\.proxy-suite\.userControl\.allow
What userControl\.group may control without a password:
- “global”: the global units (proxy, tun, tproxy, zapret, restart, subs update)\.
- “perApp”: the per-app backend units used by ` proxy-ctl apps run `\.
Empty grants no passwordless control\.
*Type:*
list of (one of “global”, “perApp”)
*Default:*
```nix
[
"global"
"perApp"
]
```
*Example:*
```nix
[
"global"
]
```
<a id="services-proxy-suite-usercontrol-group"></a>
## services\.proxy-suite\.userControl\.group
Group whose members may run privileged ` proxy-ctl ` commands without a password\.
*Type:*
string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$
*Default:*
```nix
"proxy-suite"
```
+848
View File
@@ -0,0 +1,848 @@
# services.proxy-suite.zapret
Part of the [proxy-suite options reference](./index.md).
## Options
- zapret
- [enable](#services-proxy-suite-zapret-enable)
- cidrExemption
- [enable](#services-proxy-suite-zapret-cidrexemption-enable)
- [cidrs](#services-proxy-suite-zapret-cidrexemption-cidrs)
- directSync
- [enable](#services-proxy-suite-zapret-directsync-enable)
- [upstreamIps](#services-proxy-suite-zapret-directsync-upstreamips)
- [userIps](#services-proxy-suite-zapret-directsync-userips)
- [engine](#services-proxy-suite-zapret-engine)
- zapret-discord-youtube
- [configName](#services-proxy-suite-zapret-zapret-discord-youtube-configname)
- [domains](#services-proxy-suite-zapret-zapret-discord-youtube-domains)
- [excludeDomains](#services-proxy-suite-zapret-zapret-discord-youtube-excludedomains)
- [excludeIps](#services-proxy-suite-zapret-zapret-discord-youtube-excludeips)
- [gameFilter](#services-proxy-suite-zapret-zapret-discord-youtube-gamefilter)
- [hostlistRules](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules)
- item
- [enableDirectSync](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-enabledirectsync)
- [configName](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-configname)
- [defaultDomains](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultdomains)
- [defaultIps](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultips)
- [domains](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-domains)
- [ips](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-ips)
- [name](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-name)
- [nfqwsArgs](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-nfqwsargs)
- [preset](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-preset)
- [includeExtraUpstreamLists](#services-proxy-suite-zapret-zapret-discord-youtube-includeextraupstreamlists)
- [ips](#services-proxy-suite-zapret-zapret-discord-youtube-ips)
- zapret2
- autoHostlist
- [enable](#services-proxy-suite-zapret-zapret2-autohostlist-enable)
- [debugLog](#services-proxy-suite-zapret-zapret2-autohostlist-debuglog)
- [failThreshold](#services-proxy-suite-zapret-zapret2-autohostlist-failthreshold)
- [failTime](#services-proxy-suite-zapret-zapret2-autohostlist-failtime)
- [incomingMaxseq](#services-proxy-suite-zapret-zapret2-autohostlist-incomingmaxseq)
- [retransMaxseq](#services-proxy-suite-zapret-zapret2-autohostlist-retransmaxseq)
- [retransReset](#services-proxy-suite-zapret-zapret2-autohostlist-retransreset)
- [retransThreshold](#services-proxy-suite-zapret-zapret2-autohostlist-retransthreshold)
- [udpIn](#services-proxy-suite-zapret-zapret2-autohostlist-udpin)
- [udpOut](#services-proxy-suite-zapret-zapret2-autohostlist-udpout)
- [blobs](#services-proxy-suite-zapret-zapret2-blobs)
- [domains](#services-proxy-suite-zapret-zapret2-domains)
- [excludeDomains](#services-proxy-suite-zapret-zapret2-excludedomains)
- [ipv6](#services-proxy-suite-zapret-zapret2-ipv6)
- ports
- [tcp](#services-proxy-suite-zapret-zapret2-ports-tcp)
- [udp](#services-proxy-suite-zapret-zapret2-ports-udp)
- [profiles](#services-proxy-suite-zapret-zapret2-profiles)
<a id="services-proxy-suite-zapret-enable"></a>
## services\.proxy-suite\.zapret\.enable
Whether to enable zapret DPI bypass\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-zapret-cidrexemption-enable"></a>
## services\.proxy-suite\.zapret\.cidrExemption\.enable
Whether to enable exempting subnets from zapret, e\.g\. NATed VMs whose traffic it would break\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-zapret-cidrexemption-cidrs"></a>
## services\.proxy-suite\.zapret\.cidrExemption\.cidrs
Exempted subnets\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"192.168.123.0/24"
]
```
<a id="services-proxy-suite-zapret-directsync-enable"></a>
## services\.proxy-suite\.zapret\.directSync\.enable
Add zapret’s domain hostlists to proxy\.routing\.direct\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-directsync-upstreamips"></a>
## services\.proxy-suite\.zapret\.directSync\.upstreamIps
Add zapret’s upstream ipsets to proxy\.routing\.direct\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-directsync-userips"></a>
## services\.proxy-suite\.zapret\.directSync\.userIps
Add zapret-discord-youtube\.ips, minus zapret-discord-youtube\.excludeIps, to proxy\.routing\.direct\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-engine"></a>
## services\.proxy-suite\.zapret\.engine
“zapret-discord-youtube”: nfqws with curated presets and static hostlists (zapret\.zapret-discord-youtube)\.
“zapret2”: nfqws2, which learns blocked hosts at runtime (zapret\.zapret2)\.
*Type:*
one of “zapret-discord-youtube”, “zapret2”
*Default:*
```nix
"zapret-discord-youtube"
```
*Example:*
```nix
"zapret2"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-configname"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.configName
Upstream strategy preset\. Names that differ only in whitespace match\.
*Type:*
string
*Default:*
```nix
"general(ALT)"
```
*Example:*
```nix
"general (ALT9)"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-domains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.domains
Extra domains to bypass\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"youtube.com"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-excludedomains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.excludeDomains
Domains never bypassed\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"music.youtube.com"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-excludeips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.excludeIps
IPs/CIDRs never bypassed\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.10/32"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-gamefilter"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.gameFilter
Game traffic filter, or “null” for off\.
*Type:*
one of “all”, “tcp”, “udp”, “null”
*Default:*
```nix
"null"
```
*Example:*
```nix
"all"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules
Extra named hostlists, each with its own strategy: cloned from a preset or configName,
or given as nfqwsArgs\.
*Type:*
list of (submodule)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
{
configName = "general(ALT9)";
defaultDomains = [
"youtube"
];
name = "youtube-alt9";
}
{
domains = [
"example.com"
];
name = "custom-sites";
preset = "general";
}
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-enabledirectsync"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.enableDirectSync
Include these domains in zapret\.directSync\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-configname"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.configName
Config to clone strategies from\. Exclusive with nfqwsArgs\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"general(ALT9)"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultdomains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.defaultDomains
Upstream lists to include (“discord” = “general”, “youtube” = “google”)\. Without preset,
use one per rule so the strategy family can be inferred\.
*Type:*
list of (one of “general”, “google”, “discord”, “youtube”, “instagram”, “soundcloud”, “twitter”)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"google"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.defaultIps
Upstream ipsets to include (“all” is ipset-all\.txt)\.
*Type:*
list of value “all” (singular enum)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"all"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-domains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.domains
Domains in this hostlist\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"example.com"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-ips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.ips
IPs/CIDRs in this rule’s ipset\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.0/24"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-name"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.name
Hostlist name (hostlists/list-\<name>\.txt)\.
*Type:*
string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$
*Example:*
```nix
"cloudflare"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-nfqwsargs"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.nfqwsArgs
Raw NFQWS arguments; --hostlist and --new are added\. Exclusive with configName\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"--filter-tcp=443 --dpi-desync=fake,multisplit"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-preset"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.preset
Strategy family to clone, from configName or the active config\.
*Type:*
null or one of “general”, “google”, “instagram”, “soundcloud”, “twitter”
*Default:*
```nix
null
```
*Example:*
```nix
"google"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-includeextraupstreamlists"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.includeExtraUpstreamLists
Also use the upstream instagram, soundcloud and twitter lists\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-ips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.ips
Extra IPs/CIDRs to bypass\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.0/24"
]
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-enable"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.enable
Learn blocked hosts: after failThreshold failures (retransmissions, early RST, DPI
redirect, one-sided UDP) a host joins /var/lib/proxy-suite/zapret2/zapret-hosts-auto\.txt\.
Off, only zapret2\.domains and ` proxy-ctl zapret auto add ` are acted on\.
*Type:*
boolean
*Default:*
```nix
true
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-debuglog"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.debugLog
Log why hosts are or are not learned to zapret-hosts-auto-debug\.log\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-failthreshold"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failThreshold
Failures before a host is learned\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
3
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-failtime"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failTime
Seconds allowed between two failures before the count resets\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
300
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-incomingmaxseq"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.incomingMaxseq
Incoming sequence number past which an RST or redirect is not a failure\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
4096
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-retransmaxseq"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransMaxseq
Outgoing sequence number past which failure detection stops\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
32768
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-retransreset"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransReset
RST a stalled client once retransThreshold is hit, so failures are counted fast\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-retransthreshold"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransThreshold
Retransmissions of the first request that count as one failure\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
3
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-udpin"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.udpIn
Incoming UDP packets at or below which an exchange is one-sided\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
1
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-udpout"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.udpOut
Outgoing UDP packets before a one-sided exchange counts as a failure\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
4
```
<a id="services-proxy-suite-zapret-zapret2-blobs"></a>
## services\.proxy-suite\.zapret\.zapret2\.blobs
Fake payloads by name (blob=\<name>): a file in zapret2’s files/fake, or an absolute path\.
*Type:*
attribute set of string
*Default:*
```nix
{
quic_initial = "quic_initial_www_google_com.bin";
tls_clienthello = "tls_clienthello_www_google_com.bin";
}
```
*Example:*
```nix
{
tls_clienthello = "/etc/proxy-suite/my_clienthello.bin";
}
```
<a id="services-proxy-suite-zapret-zapret2-domains"></a>
## services\.proxy-suite\.zapret\.zapret2\.domains
Domains always treated as blocked\. At runtime: ` proxy-ctl zapret auto add `\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"rutracker.org"
]
```
<a id="services-proxy-suite-zapret-zapret2-excludedomains"></a>
## services\.proxy-suite\.zapret\.zapret2\.excludeDomains
Domains never touched or learned\. At runtime: ` proxy-ctl zapret auto exclude `\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"bank.example.com"
]
```
<a id="services-proxy-suite-zapret-zapret2-ipv6"></a>
## services\.proxy-suite\.zapret\.zapret2\.ipv6
Intercept IPv6 as well as IPv4\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-zapret2-ports-tcp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.tcp
TCP ports sent to NFQUEUE\. Must cover every port a profile filters on\.
*Type:*
string
*Default:*
```nix
"80,443,1984,2053,2083,2087,2096,5222,8443"
```
<a id="services-proxy-suite-zapret-zapret2-ports-udp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.udp
UDP ports sent to NFQUEUE\. Must cover every port a profile filters on\.
*Type:*
string
*Default:*
```nix
"443,590-600,1400,3478-3481,5349,19294-19344,49152-65535"
```
<a id="services-proxy-suite-zapret-zapret2-profiles"></a>
## services\.proxy-suite\.zapret\.zapret2\.profiles
nfqws2 profiles, joined with --new; first match wins\. \<HOSTLIST> expands to the hostlist
arguments, \<HOSTLIST_NOAUTO> to the same without learning\. --qnum, --fwmark and --lua-init
are added automatically\.
*Type:*
list of string
*Default:*
```nix
[
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
]
```
*Example:*
```nix
[
"--filter-tcp=443 --filter-l7=tls <HOSTLIST> --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld"
]
```
+8 -3
View File
@@ -22,7 +22,7 @@
];
forAll = nixpkgs.lib.genAttrs systems;
pkgsFor = system: import nixpkgs { inherit system; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret nixpkgs; };
mkOptionsDoc = import ./nix/options-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule;
};
@@ -51,6 +51,7 @@
mkTgWsProxy
tg-ws-proxy
proxy-suite-tray
zapret2
;
};
@@ -79,10 +80,12 @@
options_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
readme_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#readmeDoc")"
install -Dm644 "''${options_output_path}" "''${repo_root}/docs/options.md"
mkdir -p "''${repo_root}/docs"
rm -rf "''${repo_root}/docs/options"
cp -r --no-preserve=mode,ownership "''${options_output_path}" "''${repo_root}/docs/options"
install -Dm644 "''${readme_output_path}" "''${repo_root}/README.md"
echo "updated ''${repo_root}/docs/options.md"
echo "updated ''${repo_root}/docs/options/"
echo "updated ''${repo_root}/README.md"
'';
};
@@ -93,7 +96,9 @@
amneziawg-go
tg-ws-proxy
proxy-suite-tray
zapret2
;
xray = import ./pkgs/xray.nix { inherit pkgs; };
optionsDoc = mkOptionsDoc system;
readmeDoc = mkReadmeDoc system;
update-docs = updateDocs;
+13 -23
View File
@@ -62,9 +62,7 @@ let
configTool = ../../scripts/amneziawg_config.py;
runtimeDir = name: "/run/${serviceName name}";
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
# Keep proxy backend sockets (which already carry proxyMark) out of AWG's
# default-route policy table. This priority sits ahead of the global TUN
# rules while leaving the per-app rules at 8996/8997 untouched.
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
proxyBypassRulePriority = 8998;
mkService =
@@ -89,10 +87,8 @@ let
if ! ${pkgs.iproute2}/bin/ip "$family" rule add \
pref ${toString proxyBypassRulePriority} \
fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; then
# IPv4 is required: without this rule the proxy backend itself is
# captured by AWG's default-route table and HTTP_PROXY clients can
# hang or recurse. IPv6 is best-effort for hosts without IPv6
# policy-routing support.
# IPv4 is required, or the proxy backend is captured by AWG; IPv6 is best-
# effort.
if [ "$family" = "-4" ]; then
echo "proxy-suite: unable to install the AWG proxy-backend bypass rule" >&2
return 1
@@ -120,8 +116,8 @@ let
set +e
${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath}
# If the userspace control socket died, awg-quick cannot discover its
# fwmark. Remove only routing/firewall state tied to this interface.
# Without the control socket awg-quick cannot find its fwmark; clean up this
# interface only.
for family in -4 -6; do
had_table=0
for table in $(${pkgs.iproute2}/bin/ip "$family" route show table all 2>/dev/null \
@@ -150,9 +146,8 @@ let
implementation="$(${pkgs.python3}/bin/python3 ${configTool} \
--transport-implementation ${lib.escapeShellArg configPath})"
# The official 3.1.20260812 kernel module silently drops transport
# packets for RandomTrailers with ranged H1-H3. The bundled userspace
# build carries the receive-path repair until upstream publishes it.
# The 3.1.20260812 kernel module drops RandomTrailers packets with ranged H1-H3;
# userspace carries the fix.
if [[ "$implementation" == userspace ]]; then
WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \
WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \
@@ -182,10 +177,8 @@ let
in
{
description = "proxy-suite AmneziaWG client profile ${name}";
# When the normal proxy stack is enabled, bring its local HTTP/SOCKS
# listener up before installing AWG's default-route policy. This keeps
# applications using HTTP_PROXY/HTTPS_PROXY (for example Codex) from
# racing the proxy backend during boot or an explicit `awg on`.
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
# do not race it.
after = [
"network-online.target"
"zapret-discord-youtube.service"
@@ -285,10 +278,7 @@ let
interfaceNames = map (name: profiles.${name}.interfaceName) profileNames;
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) profileNames;
globalAutostartCount =
builtins.length autostartProfiles
+ (if cfg.proxy.tun.autostart then 1 else 0)
+ (if cfg.proxy.tproxy.autostart then 1 else 0);
globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
in
{
environment.systemPackages = [
@@ -337,9 +327,9 @@ in
}
{
assertion =
!cfg.proxy.tun.perApp.enable
|| builtins.all (interface: interface != cfg.proxy.tun.perApp.interface) interfaceNames;
message = "proxy-suite: AmneziaWG interfaces must differ from proxy.tun.perApp.interface";
!cfg.perAppRouting.tun.enable
|| builtins.all (interface: interface != cfg.perAppRouting.tun.interface) interfaceNames;
message = "proxy-suite: AmneziaWG interfaces must differ from perAppRouting.tun.interface";
}
];
}
+28
View File
@@ -0,0 +1,28 @@
# Renders every per-exit autoProxy rule-set file from the learned state.
#
# Shared by the socks start script and the prober. The start script needs it
# because sing-box refuses to start when a local rule-set path is missing, so
# every file it will be told about must exist first; the prober needs it to
# publish what it learns, which sing-box then picks up without a restart.
{ pkgs }:
pkgs.writeShellScript "proxy-suite-autoproxy-render" ''
set -euo pipefail
# $1 - probe-exits.json (index -> tag -> path), $2 - state.json
export PATH=${pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.jq
]}
jq -c '.[]' "$1" | while IFS= read -r exit; do
tag=$(jq -r '.tag' <<<"$exit")
path=$(jq -r '.path' <<<"$exit")
# Written aside and renamed into place: sing-box reloads on rename (as well
# as on in-place writes), and it never reads a half-written file.
jq -c --arg t "$tag" '
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
' "$2" > "$path.tmp"
mv -f "$path.tmp" "$path"
done
''
@@ -0,0 +1,27 @@
# Folds sampler observations ($o: [{d, h, exit, slow, peak}]) into the state. $hits
# crawls on direct within a day make a domain owed an exit (.slowWant); once routed it
# is judged on that exit only: a fast transfer keeps it, two slow ones move it to the
# next. Never moved: censor verdicts (zapret's) and .slowSkip domains.
.slowHits = ((.slowHits // {}) | with_entries(select(.value.first + 86400 > $now)))
| .slowWant = (.slowWant // {})
| reduce $o[] as $x (.;
.domains[$x.d] as $r
| if $r.verdict == "slow" then
if $x.exit != $r.exit then .
elif $x.slow then .domains[$x.d].bad = (($r.bad // 0) + 1)
else .domains[$x.d] += {bad: 0, at: $now} end
elif $r.exit != null or $x.exit != "direct" or ($x.slow | not)
or .slowWant[$x.d] != null
or ((.slowSkip[$x.d] // 0) > $now)
or (.hosts[$x.h].verdict == "censor") then .
else
.slowHits[$x.h] = {n: ((.slowHits[$x.h].n // 0) + 1), first: (.slowHits[$x.h].first // $now)}
| if .slowHits[$x.h].n >= $hits then
.slowWant[$x.d] = {host: $x.h, tried: []} | del(.slowHits[$x.h])
else . end
end)
| ([.domains | to_entries[] | select(.value.verdict == "slow" and (.value.bad // 0) >= 2)]) as $moved
| reduce $moved[] as $e (.;
del(.domains[$e.key])
| .slowWant[$e.key] = {host: $e.value.host, tried: ($e.value.tried // [$e.value.exit])})
| .slowSkip = ((.slowSkip // {}) | with_entries(select(.value > $now)))
@@ -0,0 +1,19 @@
# Slurped Clash API /connections snapshots, a second apart, in; per host and exit that
# moved at least $min bytes: host<TAB>exit<TAB>slow|fast<TAB>peak. Slow never beat
# $below in any second (paced streams burst, so they read fast). Probe listeners are
# skipped; chains[0] is the carrying exit.
[.[] | [(.connections // [])[]
| select((.metadata.type // "") | test("/probe-in-") | not)
| {id, host: (.metadata.host // ""), exit: (.chains[0] // ""), d: .download}]]
| . as $s
| [range(1; length) as $i
| ($s[$i - 1] | map({key: .id, value: .d}) | from_entries) as $p
| $s[$i][] | select($p[.id] != null)
| {id, host, exit, delta: (.d - $p[.id])}]
| group_by(.id)
| map({host: .[0].host, exit: .[0].exit, total: (map(.delta) | add), peak: (map(.delta) | max)})
| map(select(.host != "" and .exit != "" and .total >= $min))
# One line per host and exit; its best connection decides.
| group_by(.host + "\t" + .exit)
| map(max_by(.peak))[]
| "\(.host)\t\(.exit)\t\(if .peak < $below then "slow" else "fast" end)\t\(.peak)"
+418
View File
@@ -0,0 +1,418 @@
# autoProxy: probes the destinations the inbound listener dials through each
# exit in turn and remembers the first exit that gets content. The probe itself
# is `proxy-ctl proxy auto probe --json`, so every verdict is reproducible by hand.
{
lib,
pkgs,
cfg,
proxyCtl,
autoProxyStateDir,
}:
let
apCfg = cfg.proxy.autoProxy;
render = import ./autoproxy-render.nix { inherit pkgs; };
bin = lib.makeBinPath [
pkgs.coreutils
pkgs.curl
pkgs.gawk
pkgs.gnugrep
pkgs.gnused
pkgs.jq
pkgs.systemd
pkgs.util-linux
proxyCtl
];
excludePattern = lib.concatStringsSep "|" (map lib.escapeRegex apCfg.exclude);
# Sets $clash_api (empty when the API is off) and $clash_auth (curl args).
clashApiBlock = ''
socks_config="$(dirname "$index")/config.json"
clash_api=$(jq -r '.experimental.clash_api.external_controller // empty' "$socks_config" 2>/dev/null || true)
clash_secret=$(jq -r '.experimental.clash_api.secret // empty' "$socks_config" 2>/dev/null || true)
clash_auth=()
[ -z "$clash_secret" ] || clash_auth=(-H "Authorization: Bearer $clash_secret")
'';
sampler = pkgs.writeShellScript "proxy-suite-autoproxy-sample" ''
set -euo pipefail
export PATH=${bin}
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
index=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
${clashApiBlock}
if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0
fi
install -d -m 0750 "$state_dir"
# Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$(
for i in $(seq 0 10); do
[ "$i" -eq 0 ] || sleep 1
curl -sS --noproxy '*' --max-time 1 "''${clash_auth[@]}" "http://$clash_api/connections" 2>/dev/null ||
echo '{}'
done | jq -s -r --argjson min ${toString (300 * 1024)} \
--argjson below ${toString (apCfg.slowBelowKiBps * 1024)} -f ${./autoproxy-slow-sample.jq} || true
)
[ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples"
'';
runner = pkgs.writeShellScript "proxy-suite-autoproxy-run" ''
set -euo pipefail
export PATH=${bin}
# --requests-only: just the `proxy-ctl proxy auto learn` requests.
mode=''${1:-full}
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
now=$(date +%s)
ttl=$(( ${toString apCfg.ttlDays} * 86400 ))
if [ ! -r "$index" ]; then
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
exit 0
fi
install -d -m 0750 "$state_dir"
# Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock"
flock 9
# Leftovers of a run that died partway; taken requests go back in line.
rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking"
if [ -e "$requests.taking" ]; then
cat "$requests.taking" >> "$requests"
rm -f "$requests.taking"
fi
if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then
echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2
mv -f "$state" "$state.broken"
fi
[ -s "$state" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$state"
# Written aside and renamed, so a killed run never truncates the state.
update() {
local tmp
tmp=$(mktemp "$state.XXXXXX")
if ! jq "$@" "$state" > "$tmp"; then
rm -f "$tmp"
echo "could not update $state; it is left as it was" >&2
return 1
fi
# mktemp makes it 0600; the state dir is 0750, so group-readable is enough.
chmod 0640 "$tmp"
mv -f "$tmp" "$state"
}
# $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the
# whole domain (geo-blocks are drawn around sites); other verdicts only to
# the host probed.
record() {
update --arg d "$1" --arg h "$2" --argjson r "$3" --argjson now "$now" '
(if $r.verdict == "destination" then
.domains[$d] = {verdict: "destination", exit: $r.exit, host: $h,
path: ($r.path // "/"), at: $now}
else . end)
| .hosts[$h] = {
domain: $d,
verdict: ($r.verdict // "error"),
exit: (if $r.verdict == "destination" then $r.exit else null end),
at: $now
}
| del(.backlog[$h])'
}
# Prefixes each host line with "registrable-domain<TAB>".
# ponytail: last two labels, or three under a short list of two-label
# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly.
to_reg() {
awk -F'\t' '
BEGIN {
n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ")
for (i = 1; i <= n; i++) two[s[i]] = 1
}
{
n = split($1, l, ".")
if (n < 2) next
k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n]
print k "\t" $0
}'
}
# The pinned direct listener, since TUN/TProxy capture --noproxy too.
direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index")
# --- 1. verdicts are about this host's address; drop them if it changed ---
egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true)
# An error page or a captive portal must not pass for a new address: anything
# that is not one discards every verdict this host learned.
[[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress=""
if [ -n "$egress" ] && [ "$(jq -r '.egress // ""' "$state")" != "$egress" ]; then
echo "egress is now $egress; discarding everything learned for the old address"
update --arg e "$egress" \
'{egress: $e, domains: {}, hosts: {}, exits: {}, backlog: (.backlog // {}), lastRun: (.lastRun // 0)}'
fi
# --- 2. which network (AS) each exit leaves from, once per TTL ---
while IFS=$'\t' read -r tag port; do
at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state")
[ $(( now - at )) -ge "$ttl" ] || continue
info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true)
asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true)
[ -n "$ip" ] || continue
update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \
'.exits[$t] = {ip: $ip, asn: $asn, at: $now}'
done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index")
# Round 1: one exit per AS. Round 2, only if all refused: the rest.
rounds=$(jq -c --slurpfile s "$state" '
[.[1:][] | {tag, asn: ($s[0].exits[.tag].asn // "")}]
| reduce .[] as $e ({seen: {}, r1: [], r2: []};
if $e.asn == "" or (.seen[$e.asn] | not)
then .r1 += [$e.tag] | .seen[$e.asn] = true
else .r2 += [$e.tag] end)
| {r1: (.r1 | join(",")), r2: (.r2 | join(","))}' "$index")
round1=$(jq -r .r1 <<<"$rounds")
round2=$(jq -r .r2 <<<"$rounds")
walk() {
local out verdict
out=$(proxy-ctl proxy auto probe --json --exits "$round1" "$1" 2>/dev/null || echo '{}')
verdict=$(jq -r '.verdict // "error"' <<<"$out")
if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then
out=$(proxy-ctl proxy auto probe --json --exits "$round2" "$1" 2>/dev/null || echo '{}')
fi
printf '%s' "$out"
}
# Route changes take effect immediately, not at the end of the run.
publish() { ${render} "$index" "$state"; }
requeue=()
if [ "$mode" = full ]; then
# --- 3. re-check remembered exits, once per TTL ---
# Probed routes only; slowness routes are judged by the sampler (4b).
while IFS=$'\t' read -r dom host exit; do
out=$(proxy-ctl proxy auto probe --json --exits "$exit" "$host" 2>/dev/null || echo '{}')
verdict=$(jq -r '.verdict // "error"' <<<"$out")
if [ "$verdict" = destination ] && [ "$(jq -r '.exit // ""' <<<"$out")" = "$exit" ]; then
update --arg d "$dom" --argjson now "$now" '.domains[$d].at = $now'
elif [ "$verdict" = ok ]; then
echo "recheck $dom: reachable directly now, dropping $exit"
update --arg d "$dom" 'del(.domains[$d])'
record "$dom" "$host" "$out"
publish
else
echo "recheck $dom: $exit no longer works ($verdict), walking again"
update --arg d "$dom" 'del(.domains[$d])'
publish
requeue+=("$dom"$'\t'"$host")
fi
done < <(jq -r --argjson now "$now" --argjson every "$ttl" '
.domains | to_entries[]
| select(.value.verdict == "destination" and ($now - .value.at) >= $every)
| "\(.key)\t\(.value.host)\t\(.value.exit)"' "$state")
# --- 4. what clients dialled since the last run, counted per host ---
# Hit counts accumulate in a backlog that survives between runs.
last=$(jq -r '.lastRun // 0' "$state")
if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi
dialled=$(
journalctl -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' |
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"}
to_reg || true
)
counts=$(
printf '%s\n' "$dialled" |
awk -F'\t' 'NF == 2 { n[$2]++; d[$2] = $1 } END { for (h in n) print h "\t" d[h] "\t" n[h] }' |
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
| {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries'
)
# Skipped: hosts of an already routed domain, hosts judged within the TTL.
# Dropped: entries older than the TTL, and those a route now covers.
update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" '
. as $s
| .lastRun = $now
| .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {});
if ($s.domains[$e.value.domain].exit != null)
or ((($s.hosts[$e.key].at // 0) + $ttl) > $now)
then .
else .[$e.key] = {
domain: $e.value.domain,
hits: ((.[$e.key].hits // 0) + $e.value.hits),
first: (.[$e.key].first // $now)
} end))
| .backlog |= with_entries(select(.value.first + $ttl > $now
and $s.domains[.value.domain].exit == null))'
# --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) ---
if [ -s "$state_dir/samples" ]; then
mv -f "$state_dir/samples" "$state_dir/samples.taking"
obs=$(
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}'$'\t' "$state_dir/samples.taking" |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"}
to_reg |
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
| {d: .[0], h: .[1], exit: .[2], slow: (.[3] == "slow"), peak: (.[4] | tonumber)})' ||
echo '[]'
)
rm -f "$state_dir/samples.taking"
before=$(jq -c '.domains' "$state")
update --argjson o "$obs" --argjson now "$now" --argjson ttl "$ttl" --argjson hits 3 \
-f ${./autoproxy-slow-judge.jq}
# Each crawling destination gets the next exit, in probe order, that
# answers it as well as direct does (`probe --via`). None left: it
# stays direct for a TTL.
while IFS=$'\t' read -r dom host tried; do
was=''${tried##*,}
via=""
while IFS= read -r tag; do
[[ ",$tried," != *",$tag,"* ]] || continue
tried="''${tried:+$tried,}$tag"
if [ "$(proxy-ctl proxy auto probe --json --via "$tag" "$host" < /dev/null 2>/dev/null |
jq -r '.verdict // ""' 2>/dev/null)" = ok ]; then
via=$tag
break
fi
done < <(jq -r '.[1:][] | .tag' "$index")
if [ -n "$via" ]; then
echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, routed via $via"
update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" '
.domains[$d] = {verdict: "slow", exit: $e, host: $h, at: $now, tried: ($tried | split(","))}
| del(.slowWant[$d])'
else
echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, and no other exit reaches it; left direct"
update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])'
fi
done < <(jq -r '(.slowWant // {}) | to_entries[]
| "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state")
[ "$(jq -c '.domains' "$state")" = "$before" ] || publish
fi
fi
# --- 5. probe: requests (uncapped), then broken routes, then the backlog ---
asked=()
if [ -s "$requests" ]; then
mv -f "$requests" "$requests.taking"
mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true)
rm -f "$requests.taking"
fi
backlog=()
if [ "$mode" = full ]; then
mapfile -t backlog < <(jq -r --argjson now "$now" --argjson ttl "$ttl" '
. as $s | (.backlog // {}) | to_entries
| map(select(($s.domains[.value.domain].exit == null)
and ((($s.hosts[.key].at // 0) + $ttl) <= $now)))
| sort_by(-.value.hits) | .[] | "\(.value.domain)\t\(.key)"' "$state")
fi
declare -A seen routed
probe_row() {
local dom=''${1%%$'\t'*} host=''${1#*$'\t'} out
{ [ -z "''${seen[$host]:-}" ] && [ -z "''${routed[$dom]:-}" ]; } || return 1
seen[$host]=1
out=$(walk "$host")
# A probe that failed to run is no verdict; the host is probed again.
if [ "$(jq -r '.verdict // "error"' <<<"$out")" = error ]; then
echo "probe $host -> error, not recorded"
return 0
fi
record "$dom" "$host" "$out"
if [ "$(jq -r '.verdict // ""' <<<"$out")" = destination ]; then
routed[$dom]=1
publish
fi
# A censor verdict names an exit that got through, but zapret owns it.
echo "probe $host -> $(jq -r '(.verdict // "error") + (if .verdict == "destination" then " via " + .exit
elif .exit then " (" + .exit + " reaches it; left to zapret)" else "" end)' <<<"$out")"
}
for row in "''${asked[@]}"; do probe_row "$row" || true; done
probed=0
for row in "''${requeue[@]}" "''${backlog[@]}"; do
[ "$probed" -lt ${toString apCfg.probesPerRun} ] || break
if probe_row "$row"; then probed=$(( probed + 1 )); fi
done
echo "probed ''${#asked[@]} requested and $probed queued host(s); $(jq '(.backlog // {}) | length' "$state") still waiting"
# sing-box reloads the rewritten rule-sets itself.
${render} "$index" "$state"
'';
# Group: `proxy-ctl proxy auto list|queue` reads state.json. Set on every unit that
# declares the directory - systemd re-applies the ownership on each start.
stateDirConfig = {
StateDirectory = "proxy-suite/autoproxy";
StateDirectoryMode = "0750";
}
// lib.optionalAttrs (cfg.userControl.allow != [ ]) { Group = cfg.userControl.group; };
mkUnit = description: args: {
inherit description;
after = [
"proxy-suite-socks.service"
"proxy-suite-inbounds.service"
];
wants = [ "proxy-suite-socks.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${runner}${args}";
}
// stateDirConfig;
};
in
{
systemd.services.proxy-suite-autoproxy =
mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" "";
systemd.services.proxy-suite-autoproxy-learn =
mkUnit "proxy-suite - probe the destinations asked for with proxy-ctl proxy auto learn" " --requests-only";
systemd.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite - watch live transfers for destinations that crawl directly";
after = [ "proxy-suite-socks.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${sampler}";
}
// stateDirConfig;
};
systemd.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite autoProxy transfer sampling";
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "1m";
OnUnitActiveSec = "1m";
AccuracySec = "5s";
};
};
systemd.timers.proxy-suite-autoproxy = {
description = "proxy-suite autoProxy probe schedule";
wantedBy = [ "timers.target" ];
timerConfig = {
# Not OnBootSec: after a rebuild restarts the timer, OnUnitActiveSec had
# nothing to count from and the prober never ran again.
OnActiveSec = "10m";
OnUnitActiveSec = apCfg.interval;
RandomizedDelaySec = "2m";
Persistent = true;
};
};
}
@@ -1,6 +1,5 @@
# Build-time XRay configuration template for the server-side inbound service.
# Inbounds and proxy outbounds are both injected at service start time, so no
# credential reaches the Nix store.
# XRay config template for the inbound service. Inbounds and pinned outbounds
# are injected at start, so no credential reaches the Nix store.
{
lib,
derived,
@@ -9,23 +8,25 @@
}:
let
inherit (derived) proxyCfg proxyInboundsCfg proxyInboundsNeedLocalProxy;
inherit (derived)
proxyCfg
proxyInboundsNeedLocalProxy
proxyInboundsResolveInSingBox
;
# Relaying goes through the client stack's SOCKS listener rather than a second
# copy of the outbound machinery, so the inbound service always follows the
# currently selected outbound. Connect over loopback when the listener is on a
# wildcard address.
localProxyAddress =
if builtins.elem proxyCfg.listenAddress [
"0.0.0.0"
"::"
""
] then
if
builtins.elem proxyCfg.listener.address [
"0.0.0.0"
"::"
""
]
then
"127.0.0.1"
else
proxyCfg.listenAddress;
proxyCfg.listener.address;
# Credentials, when the local proxy has them, are injected at start time.
# The client stack's SOCKS listener; credentials are injected at start.
localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy {
protocol = "socks";
tag = "proxy";
@@ -33,7 +34,7 @@ let
servers = [
{
address = localProxyAddress;
port = proxyCfg.port;
port = proxyCfg.listener.port;
}
];
};
@@ -47,9 +48,20 @@ in
(mkDnsServer "local" proxyCfg.dns.local)
];
# Filled in at start time from the listener spec.
inbounds = [ ];
# Per-user counters for proxy-suite-inbound-stats, on loopback only.
stats = { };
api = {
tag = "api";
listen = "127.0.0.1:${toString derived.constants.inboundStatsApiPort}";
services = [ "StatsService" ];
};
policy.levels."0" = {
statsUserUplink = true;
statsUserDownlink = true;
};
outbounds = localProxyOutbound ++ [
{
protocol = "freedom";
@@ -64,7 +76,11 @@ in
];
routing = {
domainStrategy = "IPIfNonMatch";
# AsIs where sing-box dials: resolving here made every new site wait on a
# lookup through the proxy, and sing-box enforces blockPrivate after its
# own. Where XRay dials itself it must resolve, and IPOnDemand: under
# IPIfNonMatch the network-only final rule matches names unresolved.
domainStrategy = if proxyInboundsResolveInSingBox then "AsIs" else "IPOnDemand";
domainMatcher = "hybrid";
rules = inboundRules.xrayInboundRules;
};
@@ -52,7 +52,7 @@ let
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if proxyCfg.proxyByDefault then "remote" else "local";
final = if (proxyCfg.routing.default == "proxy") then "remote" else "local";
};
xrayDnsBridgeHijackRule = {
@@ -105,8 +105,8 @@ let
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listenAddress;
listen_port = proxyCfg.port;
listen = proxyCfg.listener.address;
listen_port = proxyCfg.listener.port;
}
++ lib.optional enableTProxy {
type = "tproxy";
@@ -150,7 +150,7 @@ let
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
@@ -42,7 +42,7 @@ let
mkTunDnsConfig =
{
preferRemote ? proxyCfg.proxyByDefault,
preferRemote ? (proxyCfg.routing.default == "proxy"),
}:
let
primaryTag = if preferRemote then "remote" else "local";
@@ -143,8 +143,8 @@ let
}:
let
tunDnsServers = [
(if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
(if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
(if (proxyCfg.routing.default == "proxy") then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
(if (proxyCfg.routing.default == "proxy") then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
];
tunSniffing = mkSniffing { fakeDnsOnly = enableTunFakeDns; };
dnsConfig =
@@ -178,7 +178,7 @@ let
tunDnsHijackRule
]
++ rules.xrayRoutingRules
++ [ (finalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ];
++ [ (finalRule (if (proxyCfg.routing.default == "proxy") then "proxy" else "direct")) ];
in
{
log.loglevel = "warning";
@@ -187,12 +187,12 @@ let
lib.optional enableMixed {
tag = "mixed-in";
protocol = "socks";
listen = proxyCfg.listenAddress;
port = proxyCfg.port;
listen = proxyCfg.listener.address;
port = proxyCfg.listener.port;
settings = {
auth = "noauth";
udp = true;
ip = proxyCfg.listenAddress;
ip = proxyCfg.listener.address;
};
sniffing = standardSniffing;
}
+1 -1
View File
@@ -55,7 +55,7 @@ let
xrayJson
jsonFile
;
listen = ib.listener.listenAddress;
listen = ib.listener.address;
}) derived.proxyInbounds;
};
+118 -89
View File
@@ -1,6 +1,7 @@
# Factory function – receives the zapret flake, returns a NixOS module.
# This lets consumers add a single flake input and get everything transitively.
{ zapret }:
# Factory function – receives the zapret flake and this flake's own nixpkgs,
# returns a NixOS module. This lets consumers add a single flake input and get
# everything transitively.
{ zapret, nixpkgs }:
{
config,
@@ -20,100 +21,42 @@ in
./options
];
config = lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
in
lib.mkMerge [
(import ./service {
inherit
config
lib
pkgs
packages
cfg
;
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
config = lib.mkMerge [
{
# xray and sing-box default to this flake's own nixpkgs (redirect it
# with inputs.nixpkgs.follows), not the system's: a stable release lags
# both by months, and current xray needs a newer Go than stable ships.
_module.args.proxySuiteUpstream =
let
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf (cfg.zapret.enable || cfg.zapret.perApp.enable) (
import ./zapret.nix {
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
))
(lib.mkIf cfg.tgWsProxy.enable (
import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
;
}
))
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
# outbound, and a standalone tunnel has no backend at all, so both keep it.
(lib.mkIf derived.sshProxyUnitEnabled (
import ./ssh-proxy.nix {
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
config
lib
pkgs
cfg
;
}
))
(lib.mkIf cfg.tray.enable (
import ./tray.nix {
};
in
lib.mkMerge [
(import ./service {
inherit
config
lib
@@ -121,8 +64,94 @@ in
packages
cfg
;
}
))
]
);
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
(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 == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) (
import ./zapret2.nix {
inherit
lib
pkgs
cfg
packages
;
inherit (nftr) perAppZapretRulesFile nft;
}
))
(lib.mkIf cfg.tgWsProxy.enable (
import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
;
}
))
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
# outbound, and a standalone tunnel has no backend at all, so both keep it.
(lib.mkIf derived.sshProxyUnitEnabled (
import ./ssh-proxy.nix {
inherit
lib
pkgs
cfg
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
config
lib
pkgs
cfg
;
}
))
(lib.mkIf cfg.tray.enable (
import ./tray.nix {
inherit
config
lib
pkgs
packages
cfg
;
}
))
]
))
];
}
+81 -42
View File
@@ -6,63 +6,66 @@
let
proxyCfg = cfg.proxy;
singBoxCfg = proxyCfg // {
enable = proxyCfg.enable && proxyCfg.singBox.enable;
enable = singBoxEnabled;
package = proxyCfg.singBox.package;
clashApiPort = proxyCfg.singBox.clashApiPort;
urlTest = proxyCfg.urlTest // {
tolerance = proxyCfg.singBox.urlTest.tolerance;
};
};
xrayCfg = proxyCfg.xray;
proxyEnabled = proxyCfg.enable;
singBoxEnabled = proxyCfg.enable && proxyCfg.singBox.enable;
xrayEnabled = proxyCfg.enable && proxyCfg.xray.enable;
hybridEnabled = singBoxEnabled && xrayEnabled;
pureSingBoxEnabled = singBoxEnabled && !xrayEnabled;
pureXrayEnabled = xrayEnabled && !singBoxEnabled;
activeBackend =
if hybridEnabled then
"hybrid"
else if pureXrayEnabled then
"xray"
else if pureSingBoxEnabled then
"sing-box"
else
null;
# "hybrid" runs both; the pure* flags are what backend-specific code branches on.
singBoxEnabled = proxyEnabled && proxyCfg.backend != "xray";
xrayEnabled = proxyEnabled && proxyCfg.backend != "sing-box";
hybridEnabled = proxyEnabled && proxyCfg.backend == "hybrid";
pureSingBoxEnabled = proxyEnabled && proxyCfg.backend == "sing-box";
pureXrayEnabled = proxyEnabled && proxyCfg.backend == "xray";
activeBackend = if proxyEnabled then proxyCfg.backend else null;
perAppRoutingCfg = cfg.perAppRouting;
globalTun = proxyCfg.tun;
globalTproxy = proxyCfg.tproxy;
perAppRoutingTun = proxyCfg.tun.perApp;
perAppRoutingTproxy = proxyCfg.tproxy.perApp;
perAppZapretCfg = cfg.zapret.perApp;
perAppRoutingTun = cfg.perAppRouting.tun;
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
zapretCfg = cfg.zapret;
zapretEngine = cfg.zapret.engine;
perAppZapretCfg = cfg.perAppRouting.zapret;
userControlCfg = cfg.userControl;
sshProxyCfg = cfg.sshProxy;
sshProxyOutboundTag = "ssh-proxy";
sshProxyOutboundEnabled = sshProxyCfg.enable && sshProxyCfg.asOutbound;
# Only sing-box has a native `ssh` outbound. XRay has none, so it keeps the
# OpenSSH `ssh -D` unit and its local SOCKS listener -- as does a standalone
# tunnel that is not wired in as an outbound at all.
# Only sing-box dials SSH natively; XRay and standalone tunnels use the OpenSSH unit.
sshProxyNativeOutbound = sshProxyOutboundEnabled && !pureXrayEnabled;
sshProxyUnitEnabled = sshProxyCfg.enable && !sshProxyNativeOutbound;
proxyInboundsCfg = cfg.proxyInbounds;
proxyInboundsCfg = cfg.inbounds;
proxyInboundsEnabled = proxyInboundsCfg.enable;
# Listener attrset flattened to a list with `via` resolved against the
# tree-wide default. Everything downstream (rules, spec, firewall) uses this.
# Listeners as a list, with `via` resolved against the default.
proxyInbounds = lib.mapAttrsToList (tag: listener: {
inherit tag listener;
via = if listener.via == null then proxyInboundsCfg.via else listener.via;
via = if listener.via == null then proxyInboundsCfg.routing.via else listener.via;
}) proxyInboundsCfg.listeners;
# "direct" and "block" are self-contained; "proxy" chains through the client
# stack's local SOCKS listener, so it needs the client side to be running.
proxyInboundsNeedLocalProxy = lib.any (ib: ib.via == "proxy") proxyInbounds;
# Whether any listener or inbounds.routing.proxy exception relays through the local SOCKS
# listener.
proxyInboundsNeedLocalProxy =
lib.any (ib: ib.via == "proxy") proxyInbounds
|| lib.any (field: proxyInboundsCfg.routing.proxy.${field} != [ ]) [
"domains"
"ips"
"geosites"
"geoips"
];
# Any other via names a static outbound, which is rendered into the inbound
# service's own config so it stays pinned regardless of the client's
# selection. Only referenced outbounds are built, so an unused (or
# sing-box-only) one never has to be XRay-representable.
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
proxyInboundsResolveInSingBox =
!pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds;
proxyInboundsGuardPrivate =
proxyInboundsEnabled
&& proxyInboundsCfg.routing.blockPrivate
&& proxyInboundsNeedLocalProxy
&& proxyInboundsResolveInSingBox;
# Other vias name static outbounds, rendered into the inbound service's own config.
proxyInboundViaTags = lib.unique (
builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds)
);
@@ -75,22 +78,30 @@ let
"socks"
];
proxyInboundPorts = lib.unique (map (ib: ib.listener.port) proxyInbounds);
# A loopback-bound listener is reached through something else on this host (an
# nginx vhost, say), so opening its port would expose the endpoint that
# arrangement exists to hide.
# Loopback listeners are fronted locally; their ports stay closed.
proxyInboundsPublic = builtins.filter (
ib:
!builtins.elem ib.listener.listenAddress [
!builtins.elem ib.listener.address [
"127.0.0.1"
"::1"
]
) proxyInbounds;
proxyInboundFirewallPorts = lib.unique (map (ib: ib.listener.port) proxyInboundsPublic);
# h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server.
proxyInboundIsH3Only =
l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ];
proxyInboundFirewallPorts = lib.unique (
map (ib: ib.listener.port) (
builtins.filter (ib: !proxyInboundIsH3Only ib.listener) proxyInboundsPublic
)
);
# A raw-JSON listener could serve anything, so open both protocols for it.
proxyInboundFirewallUdpPorts = lib.unique (
map (ib: ib.listener.port) (
builtins.filter (
ib: ib.listener.type == null || builtins.elem ib.listener.type proxyInboundUdpTypes
ib:
ib.listener.type == null
|| builtins.elem ib.listener.type proxyInboundUdpTypes
|| proxyInboundIsH3Only ib.listener
) proxyInboundsPublic
)
);
@@ -111,8 +122,32 @@ let
collapseNamedOutbounds = selectionMode == "first";
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
perAppZapretEnabled = perAppZapretCfg.enable;
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
userControlEnabled = userControlCfg.allow != [ ];
constants = {
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
# NFQUEUE of the global zapret instance, per engine. Both are the engine's own
# default, which proxy-suite never overrides; the per-app instance opens a
# second queue and must not land on this one.
zapretGlobalQnum = {
zapret-discord-youtube = 200;
zapret2 = 300;
};
autoProxyStateDir = "/var/lib/proxy-suite/autoproxy";
# Runtime outbound control. The spool dirs hold one proxy URL per file and are
# group-writable when userControl is on, so proxy-ctl edits them without sudo;
# the pin outlives a reboot, unlike the per-boot route-mode override.
priorityOutboundFile = "/var/lib/proxy-suite/priority-outbound";
runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d";
runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d";
# Written by every backend start script; proxy-ctl reads the socks copy.
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
xrayTunPerAppTproxyRulePriority = 8996;
@@ -164,6 +199,8 @@ in
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
zapretCfg
zapretEngine
perAppZapretCfg
perAppZapretEnabled
userControlCfg
@@ -177,6 +214,8 @@ in
proxyInboundsEnabled
proxyInbounds
proxyInboundsNeedLocalProxy
proxyInboundsResolveInSingBox
proxyInboundsGuardPrivate
proxyInboundViaTags
proxyInboundViaOutbounds
invalidInboundViaTargets
+14
View File
@@ -0,0 +1,14 @@
# Adds one reading of XRay's per-user counters ($q, taken with -reset) to the
# daily totals: {days: {"YYYY-MM-DD": {"<email>": {up, down}}}, at}.
#
# A counter is named user>>>EMAIL>>>traffic>>>uplink|downlink, and a user's
# email is their name. Its value may come as a string, and a counter still at
# zero comes without one. Down is what the user received, up what they sent.
# The last 366 days are kept.
reduce ($q.stat // [])[] as $s (.;
($s.name | split(">>>")) as $n
| if ($n | length) == 4 and $n[0] == "user" then
.days[$day][$n[1]][if $n[3] == "uplink" then "up" else "down" end] += (($s.value // 0) | tonumber)
else . end)
| .at = $now
| .days = ((.days // {}) | with_entries(select(.key >= ($now - 366 * 86400 | strftime("%Y-%m-%d")))))
+4 -4
View File
@@ -8,13 +8,13 @@
let
proxyCfg = cfg.proxy;
globalTproxy = proxyCfg.tproxy;
perAppTun = proxyCfg.tun.perApp;
perAppTproxy = proxyCfg.tproxy.perApp;
zapretApp = cfg.zapret.perApp;
perAppTun = cfg.perAppRouting.tun;
perAppTproxy = cfg.perAppRouting.tproxy;
zapretApp = cfg.perAppRouting.zapret;
tgWsProxyCfg = cfg.tgWsProxy;
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled ''
meta mark ${toString tgWsProxyCfg.routingMark} return
meta mark ${toString tgWsProxyCfg.fwmark} return
'';
# Shared across all three nftables rule files that do IPv4 routing.
+2 -2
View File
@@ -11,7 +11,7 @@ let
mkOption
types
;
awgTypes = import ./types/amnezia-wg.nix { inherit lib; };
t = import ./types.nix { inherit lib; };
awgPackages = import ../../../pkgs/amneziawg.nix { inherit pkgs; };
in
{
@@ -37,7 +37,7 @@ in
};
profiles = mkOption {
type = types.attrsOf awgTypes.profileType;
type = types.attrsOf t.profileType;
default = { };
description = "Named AmneziaWG client profiles. Only one global profile can be active.";
};
+18 -13
View File
@@ -1,19 +1,24 @@
# All option declarations for services.proxy-suite, split by feature area.
{ ... }:
{ lib, ... }:
{
imports = [
./other.nix
./ssh-proxy.nix
./proxy-inbounds.nix
./amnezia-wg.nix
./legacy-sing-box.nix
./sing-box.nix
./sing-box-outbounds.nix
./sing-box-dns.nix
./sing-box-tun.nix
./sing-box-tproxy.nix
./sing-box-routing.nix
./removed.nix
./proxy.nix
./proxy-outbounds.nix
./proxy-dns.nix
./proxy-routing.nix
./proxy-tun.nix
./proxy-tproxy.nix
./inbounds.nix
./per-app-routing.nix
./zapret.nix
./zapret2.nix
./amnezia-wg.nix
./ssh-proxy.nix
./tg-ws-proxy.nix
./geodata.nix
./tray.nix
./user-control.nix
];
options.services.proxy-suite.enable = lib.mkEnableOption "proxy-suite";
}
+35
View File
@@ -0,0 +1,35 @@
{ lib, pkgs, ... }:
let
inherit (lib) literalExpression mkOption types;
in
{
# Shared by the client backends and the inbound service, so not under proxy.
options.services.proxy-suite.geodata = {
xray.assets = mkOption {
type = types.nullOr types.package;
default = pkgs.v2ray-rules-dat;
defaultText = literalExpression "pkgs.v2ray-rules-dat";
description = ''
Package with share/v2ray/{geoip,geosite}.dat for every XRay process. Null uses XRay's own
country-only data, where a tag like "geoip:telegram" stops XRay from starting.
'';
};
singBox = {
geoip = mkOption {
type = types.package;
default = pkgs.sing-geoip;
defaultText = literalExpression "pkgs.sing-geoip";
description = "Package with share/sing-box/rule-set/geoip-NAME.srs (country codes by default).";
};
geosite = mkOption {
type = types.package;
default = pkgs.sing-geosite;
defaultText = literalExpression "pkgs.sing-geosite";
description = "Package with share/sing-box/rule-set/geosite-NAME.srs.";
};
};
};
}
+111
View File
@@ -0,0 +1,111 @@
{ lib, proxySuiteUpstream, ... }:
let
inherit (lib)
literalExpression
literalMD
mkEnableOption
mkOption
types
;
t = import ./types.nix { inherit lib; };
bool =
default: description:
mkOption {
type = types.bool;
inherit default description;
};
in
{
options.services.proxy-suite.inbounds = {
enable = mkEnableOption "server inbounds that accept proxy connections from outside";
package = mkOption {
type = types.package;
default = proxySuiteUpstream.xray;
defaultText = literalMD "proxy-suite's `xray` (`pkgs/xray.nix`)";
example = literalExpression "pkgs.xray";
description = "XRay package serving the inbounds, whatever the client-side backend.";
};
serverAddress = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = "Public address clients connect to, used in share links. Null detects the uplink IPv4.";
example = "vpn.example.com";
};
openFirewall = bool true "Open every non-loopback listener port.";
shareLinks = bool true "Write client share links for `proxy-ctl inbounds link` (root and userControl.group only).";
subscriptions = {
enable = mkEnableOption "" // {
description = ''
Write one subscription file per user (their links from every listener, base64) to
/run/proxy-suite-inbounds/subscriptions/<token>. Serve that directory with a web server;
see the README.
'';
};
group = mkOption {
type = types.str;
default = "nginx";
description = "Group allowed to read the subscription files: the web server serving them.";
example = "caddy";
};
baseUrl = mkOption {
type = types.nullOr types.str;
default = null;
description = "URL the subscription directory is served at, for `proxy-ctl inbounds sub`.";
example = "https://vpn.example.com/sub";
};
};
# Mirrors proxy.routing, for traffic arriving from outside instead of from this host.
routing = {
via = mkOption {
type = types.str;
default = "proxy";
description = ''
Default egress of inbound traffic; listeners can override it:
- "proxy": through the local proxy and its current selection (needs proxy.enable).
- a proxy.outbounds tag: pinned to that server (url, urlFile or xrayJson outbounds only).
- "direct": out from this machine.
- "block": dropped.
'';
example = "direct";
};
proxy = t.routingFields;
blockRu = bool true ''Block Russian destinations (geosite "category-ru", geoip "ru").'';
blockPrivate = bool true "Block private and loopback destinations, so clients cannot reach this host's LAN or local services.";
zapretDirect = bool true "Send zapret's hostlist destinations direct, so this host's zapret unblocks them (default via only).";
};
listeners = mkOption {
type = types.attrsOf t.inboundType;
default = { };
description = "Listeners by tag.";
example = literalExpression ''
{
vless-reality = {
type = "vless";
port = 443;
users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
flow = "xtls-rprx-vision";
reality = {
enable = true;
serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/proxy-inbound-reality-key";
publicKey = "jNXH...";
shortIds = [ "0123abcd" ];
};
};
}
'';
};
};
}
@@ -1,72 +0,0 @@
{ lib, config, ... }:
let
inherit (lib) mkIf mkOption types;
cfg = config.services.proxy-suite;
legacy = cfg.singBox or { };
legacyUsed = legacy != { };
has = name: builtins.hasAttr name legacy;
hasNested = path: lib.hasAttrByPath path legacy;
getNested = path: lib.getAttrFromPath path legacy;
setIf = condition: value: lib.optionalAttrs condition value;
in
{
options.services.proxy-suite.singBox = mkOption {
type = types.submodule {
freeformType = types.anything;
};
default = { };
visible = false;
description = ''
Deprecated compatibility tree for the old services.proxy-suite.singBox
options. Use services.proxy-suite.proxy instead.
'';
};
config = mkIf legacyUsed {
warnings = [
''
services.proxy-suite.singBox is deprecated. Move shared options to
services.proxy-suite.proxy and SingBox-specific options to
services.proxy-suite.proxy.singBox.
''
];
services.proxy-suite.proxy = lib.mkMerge [
(setIf (!has "enable") {
enable = lib.mkDefault true;
singBox.enable = lib.mkDefault true;
})
(setIf (has "enable") {
enable = lib.mkDefault legacy.enable;
singBox.enable = lib.mkDefault legacy.enable;
})
(setIf (has "listenAddress") { listenAddress = lib.mkDefault legacy.listenAddress; })
(setIf (has "port") { port = lib.mkDefault legacy.port; })
(setIf (has "auth") { auth = lib.mkDefault legacy.auth; })
(setIf (has "proxyByDefault") { proxyByDefault = lib.mkDefault legacy.proxyByDefault; })
(setIf (has "outbounds") { outbounds = lib.mkDefault legacy.outbounds; })
(setIf (has "subscriptions") { subscriptions = lib.mkDefault legacy.subscriptions; })
(setIf (has "subscriptionUpdateInterval") {
subscriptionUpdateInterval = lib.mkDefault legacy.subscriptionUpdateInterval;
})
(setIf (has "selection") { selection = lib.mkDefault legacy.selection; })
(setIf (has "dns") { dns = lib.mkDefault legacy.dns; })
(setIf (has "routing") { routing = lib.mkDefault legacy.routing; })
(setIf (has "tun") { tun = lib.mkDefault legacy.tun; })
(setIf (has "tproxy") { tproxy = lib.mkDefault legacy.tproxy; })
(setIf (hasNested [ "urlTest" "url" ]) {
urlTest.url = lib.mkDefault (getNested [ "urlTest" "url" ]);
})
(setIf (hasNested [ "urlTest" "interval" ]) {
urlTest.interval = lib.mkDefault (getNested [ "urlTest" "interval" ]);
})
(setIf (hasNested [ "urlTest" "tolerance" ]) {
singBox.urlTest.tolerance = lib.mkDefault (getNested [ "urlTest" "tolerance" ]);
})
(setIf (has "package") { singBox.package = lib.mkDefault legacy.package; })
(setIf (has "clashApiPort") { singBox.clashApiPort = lib.mkDefault legacy.clashApiPort; })
];
};
}
-78
View File
@@ -1,78 +0,0 @@
# Miscellaneous top-level proxy-suite options.
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
tgWsProxyOptions = import ./other/tg-ws-proxy.nix { inherit lib; };
userControlOptions = {
userControl = {
group = mkOption {
type = types.strMatching "^[a-z_][a-z0-9_-]*$";
default = "proxy-suite";
description = ''
Local group allowed to use passwordless polkit-backed `proxy-ctl`
commands when userControl.global.enable or userControl.perApp.enable
is turned on.
'';
example = "proxy-suite";
};
global.enable = (mkEnableOption "passwordless proxy-ctl control over global proxy-suite units") // {
default = true;
description = ''
Whether members of userControl.group may manage global
proxy-suite units without password prompts via commands like
`proxy-ctl tun on|off`, `proxy-ctl tproxy on|off`,
`proxy-ctl restart`, or `proxy-ctl subscription update`.
'';
};
perApp.enable = (mkEnableOption "passwordless proxy-ctl control over per-app routing helpers") // {
default = true;
description = ''
Whether members of userControl.group may start and stop the
app-scoped backend units used by `proxy-ctl wrap ...` for
route = "tun", route = "tproxy", or route = "zapret" profiles
without password prompts.
'';
};
};
};
trayOptions = {
tray = {
enable = mkEnableOption "system tray indicator for proxy-suite";
pollInterval = mkOption {
type = types.int;
default = 5;
description = ''
Tray status refresh interval in seconds.
Lower values make UI state changes appear faster, while higher values
reduce background polling overhead.
'';
example = 5;
};
autostart = mkOption {
type = types.bool;
default = true;
description = ''
Whether to install an XDG autostart entry for the tray application
for graphical users.
'';
example = true;
};
};
};
in
{
options.services.proxy-suite = {
enable = lib.mkEnableOption "proxy suite (proxy backend + AmneziaWG + zapret + tg-ws-proxy)";
}
// userControlOptions
// trayOptions
// tgWsProxyOptions;
}
@@ -1,212 +0,0 @@
# Telegram MTProto WebSocket proxy options.
{ lib }:
let
inherit (lib) mkOption mkEnableOption types;
in
{
tgWsProxy = {
enable = mkEnableOption "Telegram MTProto WebSocket proxy";
port = mkOption {
type = types.port;
default = 1443;
description = ''
TCP listen port for tg-ws-proxy.
Telegram clients connect to this endpoint when using the local MTProto
WebSocket proxy.
'';
example = 1076;
};
host = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Bind address for tg-ws-proxy.
Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you
intentionally expose the proxy to other hosts.
'';
example = "127.0.0.1";
};
secret = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
MTProto proxy secret (hex string). Legacy inline form; this value ends up
in the Nix store. Prefer secretFile for real deployments.
Set exactly one of secret or secretFile when tgWsProxy.enable = true.
Generate one with: openssl rand -hex 16
'';
example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the MTProto proxy secret.
Intended for use with secret managers so the secret stays out of the Nix store.
Set exactly one of secretFile or secret when tgWsProxy.enable = true.
'';
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = ''
Mapping of Telegram DC IDs to relay IPs.
Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by
tg-ws-proxy for MTProto relay selection.
'';
example = {
"2" = "149.154.167.220";
"4" = "149.154.167.220";
"203" = "149.154.167.220";
};
};
verbose = mkOption {
type = types.bool;
default = false;
description = ''
Whether to enable debug logging in tg-ws-proxy.
'';
example = true;
};
logFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Optional path where tg-ws-proxy writes rotating logs.
When unset, tg-ws-proxy logs to stderr only.
'';
example = "/var/log/tg-ws-proxy.log";
};
logMaxMb = mkOption {
type = types.numbers.positive;
default = 5.0;
description = ''
Maximum tg-ws-proxy log file size in MiB before rotation.
Only used when tgWsProxy.logFile is set.
'';
example = 10.0;
};
logBackups = mkOption {
type = types.ints.positive;
default = 1;
description = ''
Number of rotated tg-ws-proxy log files to keep.
Only used when tgWsProxy.logFile is set.
'';
example = 3;
};
bufKb = mkOption {
type = types.ints.between 4 2147483647;
default = 256;
description = ''
Socket send and receive buffer size for tg-ws-proxy, in KiB.
'';
example = 512;
};
poolSize = mkOption {
type = types.ints.unsigned;
default = 4;
description = ''
WebSocket connection pool size per Telegram DC.
Set to 0 to disable connection pooling.
'';
example = 8;
};
cfProxyDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
User-defined Cloudflare-proxied domains used by tg-ws-proxy for
WebSocket fallback. Each entry is passed as a separate
--cfproxy-domain argument.
'';
example = [
"cdn.example.com"
"edge.example.net"
];
};
cfProxyWorkerDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback.
These are tried before other fallback methods.
'';
example = [ "worker.example.com" ];
};
cfProxyFallback = mkOption {
type = types.bool;
default = true;
description = ''
Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when
direct WebSocket routing is unavailable.
'';
example = false;
};
fakeTlsDomain = mkOption {
type = types.nullOr (types.strMatching ".+");
default = null;
description = ''
Optional SNI domain used to enable tg-ws-proxy Fake TLS masking.
When set, tg-ws-proxy emits an ee-secret connection link.
'';
example = "www.example.com";
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = ''
Whether tg-ws-proxy should accept a PROXY protocol v1 header from a
fronting reverse proxy such as nginx or HAProxy.
'';
example = true;
};
bypassTransparentProxy = mkOption {
type = types.bool;
default = true;
description = ''
Whether to keep tg-ws-proxy's own relay connections out of proxy-suite
transparent routing backends.
When enabled and global TUN or TProxy mode is configured, the
tg-ws-proxy systemd service receives a packet mark and an earlier
policy-routing rule back to the main table. This prevents global TUN
from routing the local Telegram MTProto relay through the proxy backend again,
which can otherwise break tg-ws-proxy after enabling TUN mode.
'';
example = true;
};
routingMark = mkOption {
type = types.int;
default = 4;
description = ''
Packet mark used by tgWsProxy.bypassTransparentProxy to bypass
proxy-suite transparent routing. Override this only if it collides
with another local policy-routing mark on your host.
'';
example = 4;
};
};
}
+59 -61
View File
@@ -1,101 +1,99 @@
# Per-app routing options (backends and profiles).
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
inherit (lib) mkEnableOption mkOption types;
t = import ./types.nix { inherit lib; };
int =
default: description:
mkOption {
type = types.int;
inherit default description;
};
localSubnets =
description:
mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
inherit description;
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
in
{
options.services.proxy-suite.perAppRouting = {
enable = mkEnableOption "per-app routing helpers via proxy-ctl wrap";
enable = mkEnableOption "per-app routing (`proxy-ctl apps run`)";
createDefaultProfiles = mkOption {
type = types.bool;
default = false;
description = ''
Whether to automatically add curated perAppRouting profiles.
This is opt-in. Generated defaults are appended only when no
user-defined profile with the same name already exists.
Current curated defaults:
- `proxychains`: route = "proxychains"
- `tun`: route = "tun" when proxy.tun.perApp.enable = true
- `tproxy`: route = "tproxy" when proxy.tproxy.perApp.enable = true
- `zapret`: route = "zapret" when zapret.perApp.enable = true
This makes `proxy-ctl wrap proxychains -- <command>` available
without defining the profile manually, and similarly exposes
`proxy-ctl wrap tun -- <command>` or
`proxy-ctl wrap tproxy -- <command>` or
`proxy-ctl wrap zapret -- <command>` when the corresponding backend
is enabled.
Add a profile named after each enabled backend (proxychains, tun, tproxy, zapret) unless
one with that name already exists.
'';
example = true;
};
profiles = mkOption {
type = types.listOf t.perAppRoutingProfileType;
default = [ ];
description = ''
Named per-app route profiles consumed by `proxy-ctl wrap`.
This initial implementation supports:
- "direct" for running a command unchanged
- "proxychains" for TCP apps that can use an LD_PRELOAD wrapper
instead of global TUN or TProxy interception
- "tun" for per-app-scoped policy routing into the dedicated app TUN
backend
- "tproxy" for per-app-scoped transparent interception through the
dedicated app TProxy backend
- "zapret" for per-app-scoped zapret handling through a separate
zapret instance without changing the app's network path or exit IP
proxychains-based wrapping depends on proxy.enable = true and the
local proxy-suite proxy listener provided by the active backend. The
"tun" route depends on proxy.tun.perApp.enable = true. The "tproxy"
route depends on proxy.tproxy.perApp.enable = true. The "zapret"
route depends on zapret.perApp.enable = true.
When createDefaultProfiles = true, curated defaults are added on top
of this list unless a user-defined profile already uses the same
name.
'';
description = "Profiles for `proxy-ctl apps run <name> -- <command>`.";
example = [
{
name = "steam-browser";
route = "proxychains";
}
{
name = "native-direct";
route = "direct";
}
];
};
proxychains = {
enable = mkEnableOption "proxychains-backed perAppRouting profiles";
enable = mkEnableOption "the proxychains backend (TCP apps, through LD_PRELOAD)";
quiet = mkOption {
type = types.bool;
default = true;
description = ''
Whether generated proxychains wrappers should suppress their normal
startup chatter. This maps to proxychains-ng quiet_mode.
'';
example = true;
description = "Silence proxychains (quiet_mode).";
};
proxyDns = mkOption {
type = types.bool;
default = true;
description = ''
Whether generated proxychains wrappers should resolve DNS through
the proxy instead of the local resolver. This maps to proxychains-ng
proxy_dns.
'';
example = true;
description = "Resolve DNS through the proxy (proxy_dns).";
};
};
tun = {
enable = mkEnableOption "the per-app TUN backend";
fwmark = int 16 "Mark that steers wrapped apps into routeTable.";
routeTable = int 101 "Policy-routing table of the per-app TUN.";
localSubnets = localSubnets "Subnets wrapped apps reach directly.";
interface = mkOption {
type = types.str;
default = "psperapptun0";
description = "Per-app TUN interface name.";
};
address = mkOption {
type = types.str;
default = "172.20.0.1/30";
description = "Per-app TUN interface address (CIDR).";
};
mtu = int 1400 "Per-app TUN interface MTU.";
};
tproxy = {
enable = mkEnableOption "the per-app TProxy backend";
fwmark = int 17 "Mark that steers wrapped apps into routeTable.";
routeTable = int 102 "Policy-routing table of the per-app TProxy.";
localSubnets = localSubnets "Subnets that bypass interception (DNS excepted).";
};
zapret = {
enable = mkEnableOption "the per-app zapret backend: a second zapret instance for wrapped apps only";
filterMark = int 268435456 "Mark bit that selects wrapped app traffic.";
qnum = int 201 "NFQUEUE number. Must differ from the global instance's.";
};
};
}
+35
View File
@@ -0,0 +1,35 @@
{ lib, ... }:
let
inherit (lib) mkOption;
t = import ./types.nix { inherit lib; };
cloudflare = {
type = "udp";
address = "1.1.1.1";
port = 53;
};
in
{
options.services.proxy-suite.proxy.dns = {
local = mkOption {
type = t.dnsUpstreamType;
default = cloudflare;
description = "Resolver for direct traffic and the default domain resolver. Goes through the proxy in global TUN mode.";
example = {
type = "tcp";
address = "9.9.9.9";
};
};
remote = mkOption {
type = t.dnsUpstreamType;
default = cloudflare;
description = "Resolver used through the proxy; the DNS default when proxy.routing.default is proxy.";
example = {
type = "tls";
address = "1.1.1.1";
port = 853;
};
};
};
}
@@ -1,172 +0,0 @@
# Server-side proxy inbound options.
{ lib, pkgs, ... }:
let
inherit (lib)
literalExpression
mkEnableOption
mkOption
types
;
inboundTypes = import ./types/proxy-inbounds.nix { inherit lib; };
in
{
options.services.proxy-suite.proxyInbounds = {
enable = mkEnableOption "server-side proxy inbounds (accept connections from outside)";
package = mkOption {
type = types.package;
default = pkgs.xray;
defaultText = literalExpression "pkgs.xray";
example = literalExpression "pkgs.xray";
description = ''
XRay package serving the inbounds.
This is independent of proxy.xray.package: the inbound service always
runs XRay, whichever backend the client side uses, and works with
proxy.enable = false.
'';
};
serverAddress = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Public hostname or address clients connect to. Used for generated share
links only; it does not affect what the listeners bind.
Leave null to detect the machine's uplink IPv4 address at service start
time. Set it explicitly when the server is behind NAT or reached by a
domain name.
'';
example = "vpn.example.com";
};
openFirewall = mkOption {
type = types.bool;
default = true;
description = ''
Add every listener port to networking.firewall. Disable to manage the
firewall yourself.
'';
example = false;
};
shareLinks = mkOption {
type = types.bool;
default = true;
description = ''
Write client share links to /run/proxy-suite-inbounds/links.json at
service start, for `proxy-ctl inbounds link` and
`proxy-ctl inbounds qr`.
The file is readable by root and the userControl group only, because
the links carry the listener credentials.
'';
example = false;
};
via = mkOption {
type = types.str;
default = "proxy";
description = ''
Default egress for traffic arriving on the inbounds. Individual
listeners can override it with their own via option, which is how two
listeners can leave through two different servers.
- "proxy": chain out through the local proxy stack, so the machine
relays rather than exits. Requires proxy.enable. The inbound service
hands traffic to the SOCKS listener on proxy.listenAddress, so it
follows whatever the client side is currently doing: the selected
outbound, subscriptions, urltest, and `proxy-ctl select` all apply,
with no second copy of that machinery.
- A proxy.outbounds tag: pin this traffic to that specific server,
independently of what the client side has selected. The outbound is
built into the inbound service's own config, so it must be one XRay
can represent (a url/urlFile entry, or xrayJson). Subscription
proxies cannot be named here, because their tags only exist at
runtime; use "proxy" to reach those.
- "direct": leave from this machine, making it a plain exit node. Needs
no client-side proxy configuration at all.
- "block": drop the traffic.
'';
example = "direct";
};
zapretDirect = mkOption {
type = types.bool;
default = true;
description = ''
Route zapret's hostlist domains and IPs to the direct outbound instead
of through the proxy, so this host's own zapret unblocks them for
inbound clients.
Has no effect unless zapret.enable and zapret.syncDirectRouting are on:
the rules are built from the same hostlists that already feed
routing.direct on the client side, so they are empty when zapret is not
running here.
On by default because a zapret host is by definition inside the filtered
network, and paying for a proxy hop to reach something zapret already
unblocks locally is pure latency. Only applies to listeners using the
default via; an explicit per-listener via still wins.
'';
example = false;
};
blockRu = mkOption {
type = types.bool;
default = true;
description = ''
Send traffic destined for Russian domains and IP ranges
("category-ru" geosite, "ru" geoip) to the block outbound.
On by default: a relay whose whole point is leaving the RKN-filtered
network has no reason to carry traffic back into it, and it keeps the
server out of the way of domestic services that geo-check.
'';
example = false;
};
blockPrivate = mkOption {
type = types.bool;
default = true;
description = ''
Send traffic destined for private and loopback addresses to the block
outbound.
On by default: without it, anyone holding an inbound credential can
reach the server's LAN, its localhost services, and the local proxy
ports of proxy-suite itself.
'';
example = false;
};
listeners = mkOption {
type = types.attrsOf inboundTypes.inboundType;
default = { };
description = ''
Named inbound listeners. The attribute name becomes the inbound tag
used in routing rules and in `proxy-ctl inbounds`.
'';
example = literalExpression ''
{
vless-reality = {
type = "vless";
port = 443;
users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
flow = "xtls-rprx-vision";
reality = {
enable = true;
dest = "www.microsoft.com:443";
serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/proxy-inbound-reality-key";
publicKey = "jNXH...";
shortIds = [ "0123abcd" ];
};
};
}
'';
};
};
}
@@ -0,0 +1,94 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy = {
outbounds = mkOption {
type = types.listOf t.outboundType;
default = [ ];
description = ''
Static proxy outbounds. The proxy needs at least one outbound or subscription to start;
`proxy-ctl proxy outbounds add` supplies one at runtime if none is declared here.
'';
example = [
{
tag = "de-vps";
urlFile = "/run/secrets/proxy-de-url";
}
{
tag = "nl-vps";
url = "hy2://password@example.com:443?sni=example.com";
}
];
};
subscriptions = mkOption {
type = types.listOf t.subscriptionType;
default = [ ];
description = ''
Subscription URLs serving a base64 or plain list of proxy URIs. Fetched on first start,
cached under /var/lib/proxy-suite/subscriptions, refreshed by a timer. Ones added with
`proxy-ctl proxy subs add` live in /var/lib/proxy-suite/subscriptions.d and refresh alongside.
'';
example = [
{
tag = "private";
urlFile = "/run/secrets/private-sub-url";
}
];
};
subscriptionUpdateInterval = mkOption {
type = types.str;
default = "1d";
description = "How often subscriptions are refreshed (systemd time span).";
example = "6h";
};
selection = mkOption {
type = types.enum [
"first"
"selector"
"urltest"
];
default = "first";
description = ''
How to pick among outbounds:
- "first": one at a time - the pinned outbound, or the first available.
- "selector": all of them, pick by hand.
- "urltest": all of them, ranked by latency unless one is pinned.
`proxy-ctl proxy select` pins an outbound in every mode, and the pin outlives a restart.
"selector" and "urltest" switch without restarting the backend (sing-box only); "first"
and XRay restart it.
'';
example = "urltest";
};
urlTest = {
url = mkOption {
type = types.str;
default = "https://www.gstatic.com/generate_204";
description = "URL fetched through each outbound to rank them. Pick one blocked in your region.";
example = "https://telegram.org";
};
interval = mkOption {
type = types.str;
default = "3m";
description = "How often outbounds are re-tested (Go duration).";
example = "1m";
};
tolerance = mkOption {
type = types.int;
default = 50;
description = "Milliseconds a faster outbound must win by to replace the current one (sing-box only).";
example = 100;
};
};
};
}
@@ -0,0 +1,71 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
in
{
options.services.proxy-suite.proxy.routing = {
default = mkOption {
type = types.enum [
"proxy"
"direct"
];
default = "proxy";
description = "Where traffic no routing rule matches goes.";
example = "direct";
};
directRu = mkOption {
type = types.bool;
default = true;
description = ''Send geosite "category-ru" and geoip "ru" direct.'';
};
proxy = {
domains = list "Domain suffixes sent through the proxy." [ "youtube.com" ];
ips = list "IP CIDRs sent through the proxy." [ "1.1.1.0/24" ];
geosites = list "Geosite names sent through the proxy." [ "netflix" ];
geoips = list "Geoip names sent through the proxy." [ "us" ];
};
direct = {
domains = list "Domain suffixes sent direct. zapret hostlists join them when zapret.directSync.enable is on." [
"internal.example"
];
ips = list "IP CIDRs sent direct." [ "10.10.0.0/16" ];
geosites = list "Geosite names sent direct." [ "category-ru" ];
geoips = list "Geoip names sent direct." [ "ru" ];
};
block = {
domains = list "Domain suffixes blocked." [ "ads.example.com" ];
ips = list "IP CIDRs blocked." [ "203.0.113.0/24" ];
geosites = list "Geosite names blocked." [ "category-ads-all" ];
geoips = list "Geoip names blocked." [ "cn" ];
};
rules = mkOption {
type = types.listOf t.routingRuleType;
default = [ ];
description = "Rules checked before the proxy/direct/block lists, in order; the first match wins.";
example = [
{
outbound = "vps-de";
geosites = [ "netflix" ];
}
{
outbound = "direct";
domains = [ "internal.corp" ];
}
];
};
};
}
@@ -0,0 +1,44 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
in
{
options.services.proxy-suite.proxy.tproxy = {
enable = mkEnableOption "global TProxy mode (proxy-suite-tproxy)";
port = mkOption {
type = types.port;
default = 1085;
description = "Port of the TProxy inbound.";
};
fwmark = mkOption {
type = types.int;
default = 1;
description = "Mark of intercepted packets, routed through routeTable.";
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = "Mark of the backend's own traffic, so it is not intercepted again.";
};
routeTable = mkOption {
type = types.int;
default = 100;
description = "Policy-routing table for intercepted traffic.";
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = "Subnets that bypass interception (DNS excepted): your LAN, VM bridges.";
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
};
}
+28
View File
@@ -0,0 +1,28 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
in
{
options.services.proxy-suite.proxy.tun = {
enable = mkEnableOption "global TUN mode (proxy-suite-tun)";
interface = mkOption {
type = types.str;
default = "singtun0";
description = "TUN interface name.";
};
address = mkOption {
type = types.str;
default = "172.19.0.1/30";
description = "TUN interface address (CIDR).";
};
mtu = mkOption {
type = types.int;
default = 1400;
description = "TUN interface MTU.";
};
};
}
+184
View File
@@ -0,0 +1,184 @@
{
lib,
proxySuiteUpstream,
...
}:
let
inherit (lib)
literalExpression
literalMD
mkEnableOption
mkOption
types
;
in
{
options.services.proxy-suite.proxy = {
enable = mkEnableOption "the local proxy";
backend = mkOption {
type = types.enum [
"sing-box"
"xray"
"hybrid"
];
default = "sing-box";
description = ''
Proxy backend. "hybrid" runs sing-box in front and hands XRay-only outbounds
(XHTTP, ECH) to XRay.
'';
example = "hybrid";
};
autostart = mkOption {
type = types.nullOr (
types.enum [
"tun"
"tproxy"
]
);
default = null;
description = ''
Transparent mode started at boot, or null for neither. The mode named here must
also be enabled (proxy.tun.enable or proxy.tproxy.enable).
'';
example = "tun";
};
listener = {
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''Bind address of the local SOCKS5/HTTP proxy. Use "0.0.0.0" only to expose it to the network.'';
};
port = mkOption {
type = types.port;
default = 1080;
description = "Port of the local SOCKS5/HTTP proxy.";
};
auth = {
username = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = "Username the local proxy requires. Set together with password or passwordFile.";
example = "proxy-user";
};
password = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = "Inline local proxy password. Ends up in the Nix store; prefer passwordFile.";
example = "change-me";
};
passwordFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the local proxy password. With perAppRouting.proxychains it must be a
single token, and it is readable by userControl.group through the proxychains config.
'';
example = "/run/secrets/proxy-suite-local-proxy-password";
};
};
};
autoProxy = {
enable = mkEnableOption "autoProxy" // {
description = ''
Probe each exit for the destinations clients dial, and route each one through the first
exit that reaches it for as long as it keeps working (`proxy-ctl proxy auto probe` shows a
verdict). Censor-side failures stay direct for zapret. Needs the sing-box backend, and
makes this host fetch every new destination itself.
'';
};
interval = mkOption {
type = types.str;
default = "10m";
description = "Time between probe runs. `proxy-ctl proxy auto learn` does not wait for it.";
example = "30m";
};
probesPerRun = mkOption {
type = types.ints.positive;
default = 200;
description = "Most destinations probed per run; the rest wait in a backlog, most-dialled first.";
};
maxExits = mkOption {
type = types.ints.positive;
default = 12;
description = ''
Most exits probed, direct included. The first round tries one exit per network (AS), a
second round the rest.
'';
};
ttlDays = mkOption {
type = types.ints.positive;
default = 30;
description = ''
Days a verdict stands, routed destinations included: a route is re-probed once this long
has passed. Everything is relearned when this host's public address changes, and
`proxy-ctl proxy auto learn <domain>` re-probes one destination right away.
'';
};
slowBelowKiBps = mkOption {
type = types.ints.unsigned;
default = 150;
description = ''
Also route destinations that work directly but crawl: at least 300 KiB in a 10 s sample,
never faster than this. 0 disables. Needs `selection` other than "first".
'';
example = 0;
};
exclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes never probed or auto-routed.";
example = [ "internal.example" ];
};
probeBasePort = mkOption {
type = types.port;
default = 18540;
description = ''
First loopback port of the per-exit probe listeners (one per exit, maxExits in total).
They are unauthenticated even when proxy.listener.auth is set.
'';
};
};
singBox = {
package = mkOption {
type = types.package;
default = proxySuiteUpstream.sing-box;
defaultText = literalMD "`sing-box` from proxy-suite's own `nixpkgs` input";
example = literalExpression "pkgs.sing-box";
description = ''sing-box package, used when backend is "sing-box" or "hybrid".'';
};
clashApiPort = mkOption {
type = types.port;
default = 9090;
description = ''Port of sing-box's Clash API, used with selection "selector" or "urltest".'';
};
};
xray = {
package = mkOption {
type = types.package;
default = proxySuiteUpstream.xray;
defaultText = literalMD "proxy-suite's `xray` (`pkgs/xray.nix`)";
example = literalExpression "pkgs.xray";
description = ''XRay package, used when backend is "xray" or "hybrid".'';
};
};
};
}
+75
View File
@@ -0,0 +1,75 @@
{ lib, ... }:
let
p = path: [ "services" "proxy-suite" ] ++ lib.splitString "." path;
rm = path: replacement: lib.mkRemovedOptionModule (p path) replacement;
# Top-level zapret options that moved under the engine namespace; the value is
# the leaf name they carry there.
zapretMoved = {
configName = "configName";
gameFilter = "gameFilter";
hostlistRules = "hostlistRules";
includeExtraUpstreamLists = "includeExtraUpstreamLists";
listGeneral = "domains";
listExclude = "excludeDomains";
ipsetAll = "ips";
ipsetExclude = "excludeIps";
};
in
{
imports = [
# These were aliases; they are removal notices now, so there is one
# compatibility policy instead of two.
(rm "proxyInbounds" "Use services.proxy-suite.inbounds.")
(rm "proxy.tun.perApp" "Use services.proxy-suite.perAppRouting.tun.")
(rm "proxy.tproxy.perApp" "Use services.proxy-suite.perAppRouting.tproxy.")
(rm "zapret.perApp" "Use services.proxy-suite.perAppRouting.zapret.")
(rm "proxy.singBox.urlTest.tolerance" "Use services.proxy-suite.proxy.urlTest.tolerance.")
(rm "tgWsProxy.host" "Use services.proxy-suite.tgWsProxy.listener.address.")
(rm "singBox" "Use services.proxy-suite.proxy, with sing-box-specific options under proxy.singBox.")
# proxy.
(rm "proxy.singBox.enable" ''Use services.proxy-suite.proxy.backend = "sing-box" (or "hybrid").'')
(rm "proxy.xray.enable" ''Use services.proxy-suite.proxy.backend = "xray" (or "hybrid").'')
(rm "proxy.listenAddress" "Use services.proxy-suite.proxy.listener.address.")
(rm "proxy.port" "Use services.proxy-suite.proxy.listener.port.")
(rm "proxy.auth.username" "Use services.proxy-suite.proxy.listener.auth.username.")
(rm "proxy.auth.password" "Use services.proxy-suite.proxy.listener.auth.password.")
(rm "proxy.auth.passwordFile" "Use services.proxy-suite.proxy.listener.auth.passwordFile.")
(rm "proxy.proxyByDefault" ''Use services.proxy-suite.proxy.routing.default = "proxy" or "direct".'')
(rm "proxy.routing.enableRuDirect" "Use services.proxy-suite.proxy.routing.directRu.")
(rm "proxy.tun.autostart" ''Use services.proxy-suite.proxy.autostart = "tun".'')
(rm "proxy.tproxy.autostart" ''Use services.proxy-suite.proxy.autostart = "tproxy".'')
# zapret. Both engines now spell their lists the same way.
(rm "zapret.syncDirectRouting" "Use services.proxy-suite.zapret.directSync.enable.")
(rm "zapret.syncDirectRoutingUpstreamIps" "Use services.proxy-suite.zapret.directSync.upstreamIps.")
(rm "zapret.syncDirectRoutingUserIps" "Use services.proxy-suite.zapret.directSync.userIps.")
# sshProxy splits into server (where it dials) and listener (what it opens).
(rm "sshProxy.user" "Use services.proxy-suite.sshProxy.server.user.")
(rm "sshProxy.host" "Use services.proxy-suite.sshProxy.server.host.")
(rm "sshProxy.sshPort" "Use services.proxy-suite.sshProxy.server.port.")
(rm "sshProxy.listenAddress" "Use services.proxy-suite.sshProxy.listener.address.")
(rm "sshProxy.listenPort" "Use services.proxy-suite.sshProxy.listener.port.")
# tgWsProxy groups its listener, Cloudflare and logging knobs.
(rm "tgWsProxy.port" "Use services.proxy-suite.tgWsProxy.listener.port.")
(rm "tgWsProxy.cfProxyDomains" "Use services.proxy-suite.tgWsProxy.cloudflare.domains.")
(rm "tgWsProxy.cfProxyWorkerDomains" "Use services.proxy-suite.tgWsProxy.cloudflare.workerDomains.")
(rm "tgWsProxy.cfProxyFallback" "Use services.proxy-suite.tgWsProxy.cloudflare.fallback.")
(rm "tgWsProxy.bufKb" "Use services.proxy-suite.tgWsProxy.bufferKiB.")
(rm "tgWsProxy.routingMark" "Use services.proxy-suite.tgWsProxy.fwmark.")
(rm "tgWsProxy.verbose" "Use services.proxy-suite.tgWsProxy.log.verbose.")
(rm "tgWsProxy.logFile" "Use services.proxy-suite.tgWsProxy.log.file.")
(rm "tgWsProxy.logMaxMb" "Use services.proxy-suite.tgWsProxy.log.maxSizeMiB.")
(rm "tgWsProxy.logBackups" "Use services.proxy-suite.tgWsProxy.log.keep.")
# userControl.
(rm "userControl.global.enable" ''Use services.proxy-suite.userControl.allow, which lists "global" by default.'')
(rm "userControl.perApp.enable" ''Use services.proxy-suite.userControl.allow, which lists "perApp" by default.'')
]
++ lib.mapAttrsToList (
old: new: rm "zapret.${old}" "Use services.proxy-suite.zapret.zapret-discord-youtube.${new}."
) zapretMoved;
}
@@ -1,52 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy.dns = {
local = mkOption {
type = t.dnsUpstreamType;
default = {
type = "udp";
address = "1.1.1.1";
port = 53;
};
description = ''
DNS upstream used for the built-in "local" resolver role.
This resolver is also used as the backend's default domain resolver.
The module keeps detour policy automatic: in mixed/TProxy mode and
per-app-routing TUN mode, "local" stays on the direct path (without an
explicit detour); in global TUN mode, it is forced through the proxy to avoid
auto_redirect conflicts.
'';
example = {
type = "tcp";
address = "9.9.9.9";
port = 53;
};
};
remote = mkOption {
type = t.dnsUpstreamType;
default = {
type = "udp";
address = "1.1.1.1";
port = 53;
};
description = ''
DNS upstream used for the built-in "remote" resolver role.
This resolver always detours through the proxy and becomes the
generated dns.final target when proxy.proxyByDefault = true.
'';
example = {
type = "tls";
address = "1.1.1.1";
port = 853;
};
};
};
}
@@ -1,133 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy = {
outbounds = mkOption {
type = types.listOf t.outboundType;
default = [ ];
description = ''
List of static proxy outbounds.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or the
deprecated json field per entry. Backend-specific raw JSON fields are
only valid with their matching backend.
At least one outbound or one subscription is required when
proxy.enable = true.
'';
example = [
{
tag = "de-vps";
urlFile = "/run/secrets/proxy-de-url";
}
{
tag = "nl-vps";
url = "hy2://password@example.com:443?sni=example.com";
}
];
};
subscriptions = mkOption {
type = types.listOf t.subscriptionType;
default = [ ];
description = ''
Subscription URLs that provide dynamic lists of proxy outbounds.
Each URL must return a base64-encoded newline-separated list of proxy URIs
(standard v2rayN / Clash subscription format) or plain text of the same.
On first service start, each subscription is fetched live and cached
under /var/lib/proxy-suite/subscriptions/<backend>/<tag>.json. Later restarts
reuse the cache, so ordinary service restarts do not need network access.
A systemd timer (proxy-suite-subscription-update) refreshes all caches
on the interval set by subscriptionUpdateInterval and restarts the
running proxy services after a successful refresh.
'';
example = [
{
tag = "community";
url = "https://example.com/sub/token";
}
{
tag = "private";
urlFile = "/run/secrets/private-sub-url";
}
];
};
subscriptionUpdateInterval = mkOption {
type = types.str;
default = "1d";
description = ''
How often the proxy-suite-subscription-update timer fires and refreshes
all subscription caches. Accepts any systemd time span string
(e.g. "1h", "6h", "1d", "12h").
Only used when proxy.subscriptions is non-empty. The timer also runs
once shortly after boot.
'';
example = "6h";
};
selection = mkOption {
type = types.enum [
"first"
"selector"
"urltest"
];
default = "first";
description = ''
How to pick between multiple proxy outbounds:
- "first": route through a single active outbound tagged "proxy".
The first static outbound is used, or the first subscription
outbound if only subscriptions are configured.
- "selector": create a Clash-compatible selector outbound tagged
"proxy" and keep all configured outbounds available for manual
switching via the Clash API.
- "urltest": create automatic latency testing tagged "proxy" and
keep all configured outbounds available so the active backend can
periodically probe and switch to a faster one.
proxy.singBox.clashApiPort is only used with "selector" or "urltest"
on the SingBox backend. "selector" is SingBox-only. "urltest" maps to
SingBox urltest or XRay observatory/balancer depending on backend.
urlTest.* options are only used with "urltest".
Per-outbound tags are only individually meaningful with "selector"
or "urltest".
'';
example = "urltest";
};
urlTest = {
url = mkOption {
type = types.str;
default = "https://www.gstatic.com/generate_204";
description = ''
URL that the active backend fetches through each proxy to measure latency.
Only used when selection = "urltest".
Set this to a URL that is actually blocked in your region (e.g.
"https://telegram.org") so that only proxies that bypass the
blocking get selected. If left at the default, any responding proxy
wins – including ones that might not unblock your target site.
'';
example = "https://telegram.org";
};
interval = mkOption {
type = types.str;
default = "3m";
description = ''
How often the active backend re-tests all outbounds. Accepts a Go
duration string (e.g. "1m", "3m", "10m").
Only used when selection = "urltest".
'';
example = "1m";
};
};
};
}
@@ -1,122 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy.routing = {
enableRuDirect = mkOption {
type = types.bool;
default = true;
description = ''
Automatically append "category-ru" to routing.direct.geosites and
"ru" to routing.direct.geoips.
This is additive: user-defined routing.direct.* entries still apply.
'';
example = true;
};
proxy = t.routingFields;
direct = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domain suffixes to send direct (bypass proxy).
Merged with zapret-synced direct domains when zapret direct sync
options are enabled.
'';
example = [ "internal.example" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IP CIDRs to send direct.
Merged with zapret-synced direct IPs when the corresponding zapret
sync options are enabled.
'';
example = [ "10.10.0.0/16" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geosite names to send direct.
"category-ru" is added automatically when enableRuDirect = true.
'';
example = [ "category-ru" ];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geoip names to send direct.
"ru" is added automatically when enableRuDirect = true.
'';
example = [ "ru" ];
};
};
block = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes to block entirely.";
example = [ "ads.example.com" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IP CIDRs to block.";
example = [ "203.0.113.0/24" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geosite names to block.";
example = [ "category-ads-all" ];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geoip names to block.";
example = [ "cn" ];
};
};
rules = mkOption {
type = types.listOf t.routingRuleType;
default = [ ];
description = ''
Explicit routing rules evaluated before global proxy/direct/block lists.
Each rule routes matching traffic to a specific outbound tag.
The outbound can be a configured outbound tag (useful with selector/urltest),
or one of: "proxy" (active proxy), "direct", "block".
Order is preserved. The first matching rule wins in the active backend.
With selection = "first", non-built-in outbound tags are effectively
routed to the single active "proxy" outbound.
'';
example = [
{
outbound = "vps-de";
domains = [ "netflix.com" ];
geosites = [ "netflix" ];
}
{
outbound = "direct";
domains = [ "internal.corp" ];
}
{
outbound = "block";
domains = [ "ads.example.com" ];
}
];
};
};
}
@@ -1,119 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
in
{
options.services.proxy-suite.proxy.tproxy = {
enable = mkEnableOption "global proxy TProxy mode service";
autostart = mkOption {
type = types.bool;
default = false;
description = ''
Whether to start proxy-suite-tproxy automatically during boot by
attaching it to multi-user.target.
Cannot be enabled together with proxy.tun.autostart.
'';
example = true;
};
port = mkOption {
type = types.port;
default = 1085;
description = ''
Local listen port for the proxy backend's TProxy inbound.
nftables redirection created by proxy-suite-tproxy sends intercepted
TCP/UDP traffic to this port.
'';
example = 1085;
};
fwmark = mkOption {
type = types.int;
default = 1;
description = ''
Mark applied to intercepted packets in global TProxy mode.
A matching `ip rule` routes this mark to
proxy.tproxy.routeTable, which points traffic to
loopback for local proxy processing.
'';
example = 1;
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = ''
Mark applied to backend egress packets in global TProxy mode so
they bypass re-interception and do not loop back into the
transparent proxy path.
'';
example = 2;
};
routeTable = mkOption {
type = types.int;
default = 100;
description = ''
Policy-routing table number used for global TProxy interception flow.
The module installs a local default route in this table and binds it
to proxy.tproxy.fwmark.
'';
example = 100;
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Subnets whose traffic bypasses global TProxy interception, except
DNS (port 53).
Typically this should include your LAN subnet(s). VM bridge networks
should usually go here too, or use zapret.cidrExemption for
subnet-specific NFQUEUE exemption on the zapret side.
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
perApp = {
enable = mkEnableOption "per-app-scoped proxy TProxy backend for perAppRouting profiles";
fwmark = mkOption {
type = types.int;
default = 17;
description = ''
Packet mark used to steer wrapped app traffic into the per-app-scoped
TProxy policy-routing table.
'';
example = 17;
};
routeTable = mkOption {
type = types.int;
default = 102;
description = ''
Policy-routing table used by the per-app-scoped TProxy backend.
'';
example = 102;
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Subnets whose traffic bypasses per-app-scoped TProxy interception,
except DNS (port 53).
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
};
};
}
@@ -1,111 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
mkTunCommonFields =
{
interfaceDefault,
interfaceDescription,
addressDefault,
addressDescription,
mtuDefault,
mtuDescription,
}:
{
interface = mkOption {
type = types.str;
default = interfaceDefault;
description = interfaceDescription;
example = interfaceDefault;
};
address = mkOption {
type = types.str;
default = addressDefault;
description = addressDescription;
example = addressDefault;
};
mtu = mkOption {
type = types.int;
default = mtuDefault;
description = mtuDescription;
example = mtuDefault;
};
};
in
{
options.services.proxy-suite.proxy.tun = {
enable = mkEnableOption "global proxy TUN mode service";
autostart = mkOption {
type = types.bool;
default = false;
description = ''
Whether to start proxy-suite-tun automatically during boot by
attaching it to multi-user.target.
Cannot be enabled together with proxy.tproxy.autostart.
'';
example = true;
};
perApp = {
enable = mkEnableOption "per-app-scoped proxy TUN backend for perAppRouting profiles";
fwmark = mkOption {
type = types.int;
default = 16;
description = ''
Packet mark used to steer wrapped app traffic into the per-app-scoped
TUN policy-routing table.
'';
example = 16;
};
routeTable = mkOption {
type = types.int;
default = 101;
description = ''
Policy-routing table used by the per-app-scoped TUN backend.
'';
example = 101;
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Destination subnets that should bypass the per-app-scoped TUN mark,
so wrapped apps can still reach local LAN resources directly.
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
}
// mkTunCommonFields {
interfaceDefault = "psperapptun0";
interfaceDescription = ''
Name of the dedicated per-app-routing TUN interface used by
proxy-suite-per-app-tun.
'';
addressDefault = "172.20.0.1/30";
addressDescription = ''
Address assigned to the dedicated per-app-routing TUN interface in CIDR
notation.
'';
mtuDefault = 1400;
mtuDescription = "MTU for the dedicated per-app-routing TUN interface.";
};
}
// mkTunCommonFields {
interfaceDefault = "singtun0";
interfaceDescription = "Name of the TUN interface created by proxy-suite-tun.";
addressDefault = "172.19.0.1/30";
addressDescription = "Address assigned to the global TUN interface in CIDR notation.";
mtuDefault = 1400;
mtuDescription = "MTU for the global TUN interface created by proxy-suite-tun.";
};
}
-166
View File
@@ -1,166 +0,0 @@
# Core proxy options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix.
{ lib, pkgs, ... }:
let
inherit (lib)
literalExpression
mkOption
mkEnableOption
types
;
in
{
options.services.proxy-suite.proxy = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Whether to configure and run the proxy backend services.
This is disabled by default; enable it explicitly and choose at least
one backend with proxy.singBox.enable or proxy.xray.enable. Enabling
both runs sing-box as the frontend and XRay as a sidecar for outbounds
that require XRay.
'';
};
listenAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Address for the local SOCKS5/HTTP inbound to bind to.
This affects the proxy-suite-socks service.
Use "0.0.0.0" only if you intentionally want to expose the proxy to
other machines on your network.
'';
example = "127.0.0.1";
};
port = mkOption {
type = types.port;
default = 1080;
description = ''
Listen port for the local SOCKS5/HTTP proxy inbound provided by
proxy-suite-socks. SingBox exposes SOCKS5 and HTTP on this port.
XRay's Socks inbound also accepts SOCKS and HTTP.
'';
example = 1080;
};
auth = {
username = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Optional username for the local SOCKS5/HTTP mixed inbound.
Set this together with exactly one of auth.password or
auth.passwordFile to require clients to authenticate before using the
local proxy. Leave unset to keep the local proxy unauthenticated.
'';
example = "proxy-user";
};
password = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Optional inline password for the local SOCKS5/HTTP mixed inbound.
Convenient for testing, but the password ends up in the Nix store.
Prefer auth.passwordFile for real deployments.
'';
example = "change-me";
};
passwordFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the local proxy password.
Intended for use with secret managers so the password stays out of
the Nix store. The file is read when proxy-suite-socks starts.
If perAppRouting.proxychains.enable is also used, keep this password
as a single non-whitespace token so it can be written to the
proxychains-ng config format. The generated proxychains config is
readable by members of userControl.group.
'';
example = "/run/secrets/proxy-suite-local-proxy-password";
};
};
proxyByDefault = mkOption {
type = types.bool;
default = true;
description = ''
Whether traffic that does not match any explicit routing rule should
go through the proxy or go direct.
This affects the generated backend route final and DNS final in the
config.
'';
example = true;
};
singBox = {
enable = mkEnableOption "SingBox proxy backend";
package = mkOption {
type = types.package;
default = pkgs.sing-box;
defaultText = literalExpression "pkgs.sing-box";
example = literalExpression "pkgs.sing-box";
description = ''
sing-box package used by proxy-suite systemd services.
Override this to pin or test a specific sing-box build when upstream
protocol behavior changes.
'';
};
clashApiPort = mkOption {
type = types.port;
default = 9090;
description = ''
Port for the Clash-compatible REST API exposed by sing-box.
Only used when proxy.selection is "selector" or "urltest". Ignored
in "first" mode because there is no selector-style outbound to
control.
'';
example = 9090;
};
urlTest.tolerance = mkOption {
type = types.int;
default = 50;
description = ''
Latency tolerance in milliseconds for sing-box urltest. The current
proxy is only replaced when a competing one is faster by more than
this value.
Only used when proxy.selection = "urltest" and the SingBox backend
is active.
'';
example = 100;
};
};
xray = {
enable = mkEnableOption "XRay proxy backend";
package = mkOption {
type = types.package;
default = pkgs.xray;
defaultText = literalExpression "pkgs.xray";
example = literalExpression "pkgs.xray";
description = ''
XRay package used by proxy-suite systemd services.
Override this to pin or test a specific XRay build when upstream
protocol behavior changes.
'';
};
};
};
}
+85 -179
View File
@@ -1,138 +1,110 @@
# SSH dynamic SOCKS5 proxy options.
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
token = types.nullOr (types.strMatching "[^[:space:]]+");
path =
description: example:
mkOption {
type = types.nullOr types.str;
default = null;
inherit description example;
};
in
{
options.services.proxy-suite.sshProxy = {
enable = mkEnableOption "SSH dynamic SOCKS5 proxy";
enable = mkEnableOption "an SSH dynamic SOCKS5 tunnel";
user = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
# Where the tunnel goes.
server = {
user = mkOption {
type = token;
default = null;
description = "SSH login user.";
example = "root";
};
host = mkOption {
type = token;
default = null;
description = "SSH server.";
example = "ssh.example.com";
};
port = mkOption {
type = types.port;
default = 22;
description = "SSH server port.";
};
};
asOutbound = mkOption {
type = types.bool;
default = false;
description = ''
SSH login user. Required when sshProxy.enable is true.
Add the tunnel as an outbound tagged "ssh-proxy". sing-box dials SSH itself; XRay goes
through the OpenSSH unit's SOCKS listener.
'';
example = "root";
};
serviceUser = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Unix user for the systemd SSH proxy service. Leave unset to use
systemd's default user.
OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH
natively and no separate unit is created.
'';
example = "proxy";
};
host = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
SSH server hostname or address. Required when sshProxy.enable is true.
'';
example = "ssh.example.com";
};
sshPort = mkOption {
type = types.port;
default = 22;
description = "Remote SSH server port.";
example = 22;
};
listenAddress = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "127.0.0.1";
description = ''
Local address for the SSH-created SOCKS5 listener.
OpenSSH path only: a SingBox or hybrid backend dials SSH natively and
creates no local listener.
'';
example = "127.0.0.1";
};
listenPort = mkOption {
type = types.port;
default = 1091;
description = ''
Local port for the SSH-created SOCKS5 listener.
OpenSSH path only: a SingBox or hybrid backend dials SSH natively and
creates no local listener.
'';
example = 1091;
};
identityFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the SSH private key. Leave unset to use the SSH agent
or OpenSSH's normal identity-file lookup.
'';
example = "/run/secrets/proxy-suite-ssh-key";
};
knownHostsFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Optional runtime path to the known-hosts file passed to OpenSSH.
OpenSSH path only. A SingBox or hybrid backend verifies host keys with
sshProxy.hostKey instead.
'';
example = "/run/secrets/proxy-suite-ssh-known-hosts";
};
identityFile = path "Runtime path to the private key. Null uses the agent or OpenSSH defaults." "/run/secrets/proxy-suite-ssh-key";
hostKey = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Accepted SSH host public keys, in `authorized_keys` one-line form.
Used by the sing-box backend, which verifies host keys by value rather
than against a known-hosts file.
List **every** key the server offers, not just one. The host key
algorithm is negotiated, so pinning a single key fails the handshake
outright whenever the server picks a different algorithm. Get the full
set with `ssh-keyscan -p PORT HOST`, or from an existing known-hosts
entry with `ssh-keygen -F '[HOST]:PORT'`.
Leaving this empty accepts **any** host key, which allows a
machine-in-the-middle on the tunnel. Set it whenever sshProxy.asOutbound
is used with a SingBox or hybrid backend.
Ignored by the XRay backend and by a standalone tunnel, which use
knownHostsFile and strictHostKeyChecking instead.
Accepted host keys (sing-box). List every key `ssh-keyscan` prints: the algorithm is
negotiated. Empty accepts any key.
'';
example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." ];
};
hostKeyFile = mkOption {
type = types.nullOr types.str;
hostKeyFile = path "Known-hosts file to read hostKey from at runtime (sing-box). Wins over hostKey." "/root/.ssh/known_hosts";
# The rest only apply to the OpenSSH unit (XRay, or asOutbound = false).
knownHostsFile = path "Known-hosts file for OpenSSH." "/run/secrets/proxy-suite-ssh-known-hosts";
strictHostKeyChecking = mkOption {
type = types.enum [
"yes"
"accept-new"
"no"
];
default = "accept-new";
description = "OpenSSH host key policy.";
example = "yes";
};
# The local SOCKS5 listener the OpenSSH unit opens.
listener = {
address = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "127.0.0.1";
description = "Address of the OpenSSH SOCKS5 listener.";
};
port = mkOption {
type = types.port;
default = 1091;
description = "Port of the OpenSSH SOCKS5 listener.";
};
};
serviceUser = mkOption {
type = token;
default = null;
description = ''
Runtime path to a known-hosts file to read the accepted host keys from,
instead of listing them inline in sshProxy.hostKey. Every key recorded
there for `host:sshPort` is accepted, so a single known-hosts file stays
the one source of truth. Hashed known-hosts files work.
description = "Unix user running the OpenSSH unit.";
example = "proxy";
};
Read when the service starts, not at evaluation time, so the file never
enters the Nix store. Set either this or sshProxy.hostKey; if both are
set the file wins.
Used by the sing-box backend. The XRay backend and a standalone tunnel
pass knownHostsFile to OpenSSH instead.
'';
example = "/root/.ssh/known_hosts";
extraArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Extra OpenSSH arguments.";
example = [
"-J"
"jump.example.com"
];
};
domainStrategy = mkOption {
@@ -145,74 +117,8 @@ in
]
);
default = null;
description = ''
Resolve destination domains locally before sending them through the
SSH SOCKS5 proxy, so the remote SSH server never has to resolve them.
Null preserves the backend's default behavior.
Only applies to the XRay backend, which reaches the tunnel through the
local SOCKS5 listener and maps this onto the outbound's
`sockopt.domainStrategy`. SingBox and hybrid backends dial SSH natively
and resolve destinations themselves, so this option is ignored there.
Note that local resolution hands the remote server an address chosen by
*this* machine's DNS. For anycast or geo-steered CDNs that address can
be unreachable from the remote network, which surfaces as connection
timeouts rather than as a DNS error. Prefer fixing DNS on the remote
server if you have access to it.
'';
description = "Resolve destinations locally before the tunnel (XRay only). Can break geo-steered CDNs.";
example = "prefer_ipv4";
};
strictHostKeyChecking = mkOption {
type = types.enum [
"yes"
"accept-new"
"no"
];
default = "accept-new";
description = ''
OpenSSH host-key verification policy. Use "yes" with pinned
knownHostsFile contents for strict verification.
OpenSSH path only. A SingBox or hybrid backend verifies host keys with
sshProxy.hostKey instead.
'';
example = "yes";
};
extraArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Additional arguments passed to OpenSSH before the destination.
This can be used for options such as jump hosts or agent forwarding.
OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH
natively. Keepalive, connect-timeout and restart behavior are already
set by the module, so they do not need to be repeated here.
'';
example = [
"-o"
"ServerAliveInterval=30"
];
};
asOutbound = mkOption {
type = types.bool;
default = false;
description = ''
Add the SSH tunnel as a proxy-suite outbound tagged "ssh-proxy".
Requires proxy.enable and an active SingBox or XRay backend.
How the tunnel is built depends on the backend. SingBox and hybrid
backends dial SSH natively, with no systemd unit and no local SOCKS5
listener. XRay has no SSH outbound, so it keeps the OpenSSH `ssh -D`
unit and proxies through its local SOCKS5 listener. With
asOutbound = false the OpenSSH unit is always used, since the tunnel is
then a standalone listener the backends know nothing about.
'';
example = true;
};
};
}
+129
View File
@@ -0,0 +1,129 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
domains =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
in
{
options.services.proxy-suite.tgWsProxy = {
enable = mkEnableOption "the Telegram MTProto WebSocket proxy";
listener = {
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Bind address.";
};
port = mkOption {
type = types.port;
default = 1443;
description = "Listen port.";
};
};
secret = mkOption {
type = types.nullOr types.str;
default = null;
description = "Inline MTProto secret (`openssl rand -hex 16`). Ends up in the Nix store; prefer secretFile.";
example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = "Runtime path to the MTProto secret.";
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = "Relay IP per Telegram DC ID.";
example = {
"2" = "149.154.167.220";
};
};
fakeTlsDomain = mkOption {
type = types.nullOr (types.strMatching ".+");
default = null;
description = "SNI for Fake TLS masking (ee-secret links).";
example = "www.example.com";
};
cloudflare = {
domains = domains "Cloudflare-proxied domains for WebSocket fallback." [ "cdn.example.com" ];
workerDomains = domains "Cloudflare Worker domains, tried first." [ "worker.example.com" ];
fallback = mkOption {
type = types.bool;
default = true;
description = "Fall back to Cloudflare when direct WebSocket fails.";
};
};
poolSize = mkOption {
type = types.ints.unsigned;
default = 4;
description = "WebSocket pool size per DC; 0 disables pooling.";
};
bufferKiB = mkOption {
type = types.ints.between 4 2147483647;
default = 256;
description = "Socket buffer size, in KiB.";
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = "Accept a PROXY protocol v1 header from a fronting reverse proxy.";
};
bypassTransparentProxy = mkOption {
type = types.bool;
default = true;
description = "Keep the relay's own connections out of TUN/TProxy, which would otherwise loop them.";
};
fwmark = mkOption {
type = types.int;
default = 4;
description = "Packet mark bypassTransparentProxy uses.";
};
log = {
verbose = mkOption {
type = types.bool;
default = false;
description = "Debug logging.";
};
file = mkOption {
type = types.nullOr types.str;
default = null;
description = "Rotating log file. Null logs to stderr.";
example = "/var/log/tg-ws-proxy.log";
};
maxSizeMiB = mkOption {
type = types.numbers.positive;
default = 5.0;
description = "Log size before rotation, in MiB.";
};
keep = mkOption {
type = types.ints.positive;
default = 1;
description = "Rotated logs kept.";
};
};
};
}
+22
View File
@@ -0,0 +1,22 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
in
{
options.services.proxy-suite.tray = {
enable = mkEnableOption "the system tray indicator";
autostart = mkOption {
type = types.bool;
default = true;
description = "Start the tray in graphical sessions (XDG autostart).";
};
pollInterval = mkOption {
type = types.ints.positive;
default = 5;
description = "Status refresh interval, in seconds.";
};
};
}
+23 -96
View File
@@ -1,84 +1,34 @@
# Type submodule definitions shared across options sub-files.
{ lib }:
let
inherit (lib) mkOption types;
# Reused in both outboundType.routing and routing.rules entries.
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
routingFields = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domain suffixes to match in this routing rule.
Leave empty to skip domain-based matching for this rule entry.
'';
example = [
"youtube.com"
"discord.com"
];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IP CIDRs to match in this routing rule.
Leave empty to skip IP-based matching for this rule entry.
'';
example = [ "1.1.1.0/24" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geosite rule-set names to match in this routing rule.
Each name becomes a backend geosite rule-set reference.
'';
example = [
"netflix"
"google"
];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geoip rule-set names to match in this routing rule.
Each name becomes a backend geoip rule-set reference.
'';
example = [
"us"
"de"
];
};
domains = list "Domain suffixes to match." [ "youtube.com" ];
ips = list "IP CIDRs to match." [ "1.1.1.0/24" ];
geosites = list "Geosite names to match (see geodata)." [ "netflix" ];
geoips = list "Geoip names to match (see geodata; the defaults are country codes only)." [ "us" ];
};
routingRuleType = types.submodule {
options = {
outbound = mkOption {
type = types.str;
description = ''
Target outbound tag. Can be a specific server tag (only useful with
selection = "selector" or "urltest"), or one of the built-in tags:
"proxy" (the active proxy outbound), "direct", "block".
With selection = "first", named proxy outbounds are collapsed into the
single active "proxy" outbound at runtime, so per-tag routing no longer
distinguishes between individual proxy servers.
'';
description = ''Outbound tag, or "proxy", "direct", "block". With selection = "first" every proxy tag means "proxy".'';
example = "vps-de";
};
}
// routingFields;
};
outboundTypes = import ./types/outbounds.nix {
inherit lib;
inherit routingFields;
};
zapretTypes = import ./types/zapret.nix { inherit lib; };
dnsUpstreamType = types.submodule {
options = {
type = mkOption {
@@ -88,27 +38,19 @@ let
"tls"
];
default = "udp";
description = ''
DNS transport type for this upstream resolver.
'';
example = "tls";
description = "DNS transport.";
};
address = mkOption {
type = types.strMatching ".+";
description = ''
Resolver address or hostname used for this DNS upstream.
'';
description = "Resolver address.";
example = "1.1.1.1";
};
port = mkOption {
type = types.port;
default = 53;
description = ''
Destination port for this DNS upstream.
'';
example = 853;
description = "Resolver port.";
};
};
};
@@ -117,10 +59,7 @@ let
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = ''
Profile name used by `proxy-ctl wrap <name> -- <command>`.
Must be unique within perAppRouting.profiles.
'';
description = "Profile name, unique.";
example = "steam-browser";
};
@@ -134,23 +73,9 @@ let
];
default = "proxychains";
description = ''
Per-app route backend used by proxy-ctl wrap.
- "direct": run the command unchanged.
- "proxychains": run the command through proxychains-ng using the
local proxy-suite mixed SOCKS endpoint.
- "tun": launch the command in the dedicated per-app-routing TUN slice so
only that app's traffic is policy-routed into the app TUN backend.
- "tproxy": launch the command in the dedicated per-app-routing TProxy
slice so only that app's traffic is transparently intercepted by
the local proxy TProxy inbound.
- "zapret": launch the command in the dedicated per-app-routing zapret
slice so only that app's traffic is handled by the separate
per-app-scoped zapret instance.
Additional route backends may be added in the future.
Backend: "direct" (unchanged), "proxychains", or the per-app "tun", "tproxy" or "zapret"
backend of perAppRouting.
'';
example = "proxychains";
};
};
};
@@ -163,5 +88,7 @@ in
routingRuleType
;
}
// outboundTypes
// zapretTypes
// import ./types/outbounds.nix { inherit lib routingFields; }
// import ./types/zapret.nix { inherit lib; }
// import ./types/inbounds.nix { inherit lib; }
// import ./types/amnezia-wg.nix { inherit lib; }
@@ -304,11 +304,5 @@ let
);
in
{
inherit
profileType
settingsType
peerType
obfuscationType
rangeValue
;
inherit profileType;
}
@@ -0,0 +1,235 @@
{ lib }:
let
inherit (lib) mkOption types;
nullStr =
description: example:
mkOption {
type = types.nullOr types.str;
default = null;
inherit description example;
};
userType = types.submodule {
options = {
name = mkOption {
type = types.str;
default = "";
description = "Account label: the share link's name, and what subscriptions and stats group by.";
example = "phone";
};
uuid = nullStr "UUID (vless, vmess). Ends up in the Nix store; prefer uuidFile." "b831381d-6324-4d53-ad4f-8cda48b30811";
uuidFile = nullStr "Runtime path to the UUID." "/run/secrets/proxy-inbound-uuid";
password = nullStr "Password (trojan, shadowsocks, socks, http). Ends up in the Nix store; prefer passwordFile." "hunter2";
passwordFile = nullStr "Runtime path to the password." "/run/secrets/proxy-inbound-password";
};
};
transportType = types.submodule {
options = {
type = mkOption {
type = types.enum [
"raw"
"ws"
"grpc"
"httpupgrade"
"xhttp"
];
default = "raw";
description = ''Stream transport. "raw" is plain TCP, the usual choice for REALITY.'';
example = "ws";
};
path = mkOption {
type = types.str;
default = "/";
description = "Request path (ws, httpupgrade, xhttp).";
example = "/download";
};
host = nullStr "Expected Host header (ws, httpupgrade, xhttp). Null accepts any." "cdn.example.com";
mode = mkOption {
type = types.nullOr (
types.enum [
"auto"
"packet-up"
"stream-up"
"stream-one"
]
);
default = null;
description = ''xhttp mode. Null lets the client choose; behind an HTTP/1.1 proxy use "packet-up".'';
example = "packet-up";
};
serviceName = mkOption {
type = types.str;
default = "";
description = "gRPC service name.";
example = "GunService";
};
};
};
tlsType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = "Terminate TLS (always on for trojan). Exclusive with reality.";
};
certificateFile = nullStr "Runtime path to the PEM certificate chain." "/var/lib/acme/example.com/fullchain.pem";
keyFile = nullStr "Runtime path to the PEM private key." "/var/lib/acme/example.com/key.pem";
serverName = nullStr "SNI in share links. Defaults to inbounds.serverAddress." "example.com";
alpn = mkOption {
type = types.nullOr (
types.listOf (
types.enum [
"h3"
"h2"
"http/1.1"
]
)
);
default = null;
description = ''
ALPN offered and put in share links. [ "h3" ] alone makes an xhttp listener UDP-only, so
a web server can keep the TCP port.
'';
example = [ "h3" ];
};
};
};
realityType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = "Enable REALITY. Exclusive with tls.";
};
dest = mkOption {
type = types.str;
default = "www.microsoft.com:443";
description = "TLS 1.3 + HTTP/2 server that unauthenticated probes are forwarded to.";
};
serverNames = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Accepted SNIs, served by dest. The first goes into share links.";
example = [ "www.microsoft.com" ];
};
privateKeyFile = nullStr "Runtime path to the x25519 private key (`xray x25519`)." "/run/secrets/proxy-inbound-reality-key";
privateKey = nullStr "x25519 private key. Ends up in the Nix store; prefer privateKeyFile." "gG1Yz...";
publicKey = nullStr "x25519 public key, required for share links." "jNXH...";
shortIds = mkOption {
type = types.listOf types.str;
default = [ "" ];
description = "Accepted short IDs (hex). The first goes into share links.";
example = [ "0123abcd" ];
};
};
};
inboundType = types.submodule {
options = {
type = mkOption {
type = types.nullOr (
types.enum [
"vless"
"vmess"
"trojan"
"shadowsocks"
"socks"
"http"
]
);
default = null;
description = "Protocol. Set exactly one of type, xrayJson, or jsonFile.";
example = "vless";
};
port = mkOption {
type = types.port;
default = 443;
description = "Bound port.";
};
sharePort = mkOption {
type = types.nullOr types.port;
default = null;
description = "Port share links advertise, when something in front owns the public port. Null uses port.";
example = 443;
};
address = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "::";
description = "Bound address. A loopback address keeps the port closed in the firewall.";
example = "127.0.0.1";
};
via = nullStr "Egress, as in inbounds.routing.via. Null inherits it." "nl-vps";
users = mkOption {
type = types.listOf userType;
default = [ ];
description = "Accepted accounts.";
example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
};
flow = mkOption {
type = types.nullOr (types.enum [ "xtls-rprx-vision" ]);
default = null;
description = "VLESS flow; raw transport only.";
example = "xtls-rprx-vision";
};
method = mkOption {
type = types.str;
default = "2022-blake3-aes-128-gcm";
description = "Shadowsocks cipher. 2022 ciphers take a base64 key of matching length as password.";
example = "aes-128-gcm";
};
transport = mkOption {
type = transportType;
default = { };
description = "Stream transport.";
};
tls = mkOption {
type = tlsType;
default = { };
description = "TLS termination.";
};
reality = mkOption {
type = realityType;
default = { };
description = "REALITY.";
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = "Raw XRay inbound, built into the store; tag is overridden.";
example = {
protocol = "dokodemo-door";
settings.port = 8080;
};
};
jsonFile = nullStr "Runtime path to a raw XRay inbound (no share link); tag is overridden." "/run/secrets/proxy-inbound-vless.json";
};
};
in
{
inherit inboundType;
}
+36 -125
View File
@@ -1,51 +1,31 @@
# Subscription and outbound option type definitions.
{ lib, routingFields }:
let
inherit (lib) mkOption types;
nullStr =
description: example:
mkOption {
type = types.nullOr types.str;
default = null;
inherit description example;
};
nullAttrs =
description: example:
mkOption {
type = types.nullOr types.attrs;
default = null;
inherit description example;
};
subscriptionType = types.submodule {
options = {
tag = mkOption {
type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$";
description = ''
Unique identifier for this subscription.
Used as a prefix for all outbound tags generated from its proxy list,
e.g. "my-sub" -> tags like "my-sub-Server-DE".
This value is also used as the subscription cache filename stem under
/var/lib/proxy-suite/subscriptions/<backend>/, so it must be a safe
identifier.
'';
description = "Unique name; prefixes the tags of its outbounds and names its cache file.";
example = "community-list";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal subscription URL. The response must be a base64-encoded
newline-separated list of proxy URIs (standard v2rayN format) or
a plain-text list of the same.
This value is embedded in the Nix store. Prefer urlFile for private
subscription links or tokens.
'';
example = "https://example.com/sub/token123";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the subscription URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile or url for each subscription entry.
'';
example = "/run/secrets/proxy-subscription-url";
};
url = nullStr "Subscription URL. Ends up in the Nix store; prefer urlFile." "https://example.com/sub/token123";
urlFile = nullStr "Runtime path to the subscription URL." "/run/secrets/proxy-subscription-url";
};
};
@@ -53,41 +33,29 @@ let
options = {
tag = mkOption {
type = types.str;
description = ''
Outbound tag used in routing rules and multi-outbound selection.
With selection = "selector" or "urltest", each outbound keeps its own
tag and can be selected directly. With selection = "first", proxy-suite
routes through a single active outbound tagged "proxy", so individual
proxy tags are mainly useful for documentation and config structure.
'';
description = "Outbound tag, for routing rules and selection.";
example = "vps-de";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the proxy URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
url = nullStr "Proxy URL. Ends up in the Nix store; prefer urlFile." "hy2://password@example.com:443?sni=example.com";
urlFile = nullStr "Runtime path to the proxy URL." "/run/secrets/my-proxy-url";
Set exactly one of urlFile, url, or json for each outbound.
'';
example = "/run/secrets/my-proxy-url";
singBoxJson = nullAttrs "Raw sing-box outbound (sing-box backend); tag is overridden." {
type = "vless";
server = "example.com";
server_port = 443;
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal proxy URL. Convenient for non-secret configs, but the URL
will end up in the Nix store.
xrayJson = nullAttrs "Raw XRay outbound (XRay backend); tag is overridden." {
protocol = "vless";
settings.address = "example.com";
};
Set exactly one of urlFile, url, or json for each outbound.
Prefer urlFile for real credentials.
'';
example = "hy2://password@example.com:443?sni=example.com";
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = "Deprecated alias for singBoxJson.";
};
backend = mkOption {
@@ -98,70 +66,13 @@ let
];
default = "auto";
description = ''
Backend preference for this outbound when both SingBox and XRay are
enabled. "auto" uses SingBox when the URL or JSON can be represented
there and falls back to XRay for XRay-only transports such as XHTTP
or ECH. Ignored by single-backend configurations.
Backend for this outbound when both run. "auto" prefers sing-box and falls back to XRay
for XRay-only transports (XHTTP, ECH).
'';
example = "xray";
};
singBoxJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw sing-box outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field
is overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound.
Use this when the proxy definition is easier to generate as native Nix
than as a single URL string. Only valid with the SingBox backend.
'';
example = {
type = "vless";
server = "example.com";
server_port = 443;
uuid = "...";
};
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw XRay outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field is
overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound. Only valid with the XRay backend.
'';
example = {
protocol = "vless";
settings = {
address = "example.com";
port = 443;
id = "...";
encryption = "none";
};
};
};
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = ''
Deprecated alias for singBoxJson. Use singBoxJson instead.
'';
};
# Shorthand for attaching routing rules directly to an outbound definition.
# Traffic matching these patterns is sent to this specific outbound.
# Only meaningful when selection = "selector" or "urltest" (with "first",
# all proxy traffic goes to the single "proxy" outbound anyway).
# Destinations sent to this outbound (selection "selector" or "urltest").
routing = routingFields;
};
};
@@ -1,432 +0,0 @@
# Server-side inbound listener option type definitions.
{ lib }:
let
inherit (lib) mkOption types;
userType = types.submodule {
options = {
name = mkOption {
type = types.str;
default = "";
description = ''
Optional label for this account. Used as the share-link fragment so
clients show a readable server name, and as the XRay user email.
'';
example = "phone";
};
uuid = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal UUID for vless/vmess accounts.
This value is embedded in the Nix store. Prefer uuidFile for real
credentials.
Set exactly one of uuid or uuidFile for vless and vmess listeners.
'';
example = "b831381d-6324-4d53-ad4f-8cda48b30811";
};
uuidFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the account UUID.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
'';
example = "/run/secrets/proxy-inbound-uuid";
};
password = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal password for trojan, shadowsocks, socks, and http listeners.
This value is embedded in the Nix store. Prefer passwordFile for real
credentials.
'';
example = "hunter2";
};
passwordFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the account password.
The file is read at service start time and never lands in the Nix store.
'';
example = "/run/secrets/proxy-inbound-password";
};
};
};
transportType = types.submodule {
options = {
type = mkOption {
type = types.enum [
"raw"
"ws"
"grpc"
"httpupgrade"
"xhttp"
];
default = "raw";
description = ''
Stream transport for this listener. "raw" is plain TCP and is what
REALITY setups normally use.
'';
example = "ws";
};
path = mkOption {
type = types.str;
default = "/";
description = ''
Request path for the "ws", "httpupgrade", and "xhttp" transports.
Ignored by the other transports.
'';
example = "/download";
};
host = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Expected Host header for the "ws", "httpupgrade", and "xhttp"
transports. Leave null to accept any host.
'';
example = "cdn.example.com";
};
mode = mkOption {
type = types.nullOr (
types.enum [
"auto"
"packet-up"
"stream-up"
"stream-one"
]
);
default = null;
description = ''
Transfer mode for the "xhttp" transport. Ignored by the others.
Leave null for XRay's own default, which lets the client choose.
Behind an HTTP/1.1 reverse proxy, "packet-up" is the mode that works:
"stream-one" needs a full-duplex HTTP/2 path from the client all the
way to the listener, which a proxy speaking HTTP/1.1 upstream cannot
provide.
'';
example = "packet-up";
};
serviceName = mkOption {
type = types.str;
default = "";
description = ''
gRPC service name for the "grpc" transport. Ignored otherwise.
'';
example = "GunService";
};
};
};
tlsType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Terminate TLS on this listener. Mutually exclusive with reality.
Always on for trojan listeners regardless of this setting.
'';
example = true;
};
certificateFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the PEM certificate chain. Compose with
security.acme to keep it renewed.
'';
example = "/var/lib/acme/example.com/fullchain.pem";
};
keyFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the PEM private key matching certificateFile.
'';
example = "/var/lib/acme/example.com/key.pem";
};
serverName = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
SNI advertised in generated share links. Defaults to
proxyInbounds.serverAddress when unset.
'';
example = "example.com";
};
};
};
realityType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable REALITY on this listener. Mutually exclusive with tls.enable.
'';
example = true;
};
dest = mkOption {
type = types.str;
default = "www.microsoft.com:443";
description = ''
Real TLS server that unauthenticated probes are proxied to. Must be a
host:port that serves TLS 1.3 with HTTP/2.
'';
example = "www.microsoft.com:443";
};
serverNames = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
SNI values accepted by this listener. These must be names the dest
server actually serves. The first entry is used in share links.
'';
example = [ "www.microsoft.com" ];
};
privateKeyFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the REALITY x25519 private key, as produced by
`xray x25519`. Read at service start time; never lands in the Nix
store.
'';
example = "/run/secrets/proxy-inbound-reality-key";
};
privateKey = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal REALITY x25519 private key.
This value is embedded in the Nix store. Prefer privateKeyFile.
'';
example = "gG1Yz...";
};
publicKey = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
REALITY x25519 public key matching privateKeyFile, as printed
alongside it by `xray x25519`. Not a secret: clients need it, and it
is what generated share links carry as `pbk`.
Required when proxyInbounds.shareLinks is enabled.
'';
example = "jNXH...";
};
shortIds = mkOption {
type = types.listOf types.str;
default = [ "" ];
description = ''
Accepted REALITY short IDs (hex, up to 16 characters). The default
accepts the empty short ID. The first entry is used in share links.
'';
example = [ "0123abcd" ];
};
};
};
inboundType = types.submodule {
options = {
type = mkOption {
type = types.nullOr (types.enum [
"vless"
"vmess"
"trojan"
"shadowsocks"
"socks"
"http"
]);
default = null;
description = ''
Proxy protocol served by this listener.
Set exactly one of type, xrayJson, or jsonFile for each listener.
'';
example = "vless";
};
port = mkOption {
type = types.port;
default = 443;
description = ''
Port this listener binds. Opened in the firewall automatically unless
proxyInbounds.openFirewall is disabled.
'';
example = 443;
};
sharePort = mkOption {
type = types.nullOr types.port;
default = null;
description = ''
Port generated share links advertise, for when clients do not reach
this listener on the port it binds. Set it when something in front of
it owns the public port: an nginx vhost proxying to a loopback bind,
a container port mapping, a DNAT rule.
Leave null to advertise port.
'';
example = 443;
};
listenAddress = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "::";
description = ''
Address this listener binds. The default accepts both IPv4 and IPv6
connections from anywhere.
'';
example = "0.0.0.0";
};
via = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Egress for traffic arriving on this listener: "proxy" (out through
the local proxy stack, following its current selection), a
proxy.outbounds tag (pinned to that specific server), "direct" (out
from this machine), or "block".
Give two listeners two different tags to have them leave through two
different servers.
Leave null to inherit proxyInbounds.via.
'';
example = "nl-vps";
};
users = mkOption {
type = types.listOf userType;
default = [ ];
description = ''
Accounts accepted by this listener. vless and vmess use uuid/uuidFile;
trojan, shadowsocks, socks, and http use password/passwordFile.
A share link is generated for the first user of each listener.
'';
example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
};
flow = mkOption {
type = types.nullOr (types.enum [ "xtls-rprx-vision" ]);
default = null;
description = ''
VLESS flow control. "xtls-rprx-vision" is the usual pairing with
REALITY on the "raw" transport; it is not valid over ws, grpc,
httpupgrade, or xhttp.
'';
example = "xtls-rprx-vision";
};
method = mkOption {
type = types.str;
default = "2022-blake3-aes-128-gcm";
description = ''
Shadowsocks cipher. Ignored by other protocols.
The 2022 ciphers require a base64 pre-shared key of the matching
length as the password, not a passphrase.
'';
example = "aes-128-gcm";
};
transport = mkOption {
type = transportType;
default = { };
description = ''
Stream transport settings for this listener.
'';
};
tls = mkOption {
type = tlsType;
default = { };
description = ''
TLS termination settings for this listener. Mutually exclusive with
reality.
'';
};
reality = mkOption {
type = realityType;
default = { };
description = ''
REALITY settings for this listener. Mutually exclusive with tls.
'';
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw XRay inbound configuration as a Nix attribute set, for protocols
or options the typed fields do not cover. Embedded into the config at
build time, so avoid putting credentials here; use jsonFile instead.
The tag field is overridden by the listener name.
Set exactly one of type, xrayJson, or jsonFile for each listener.
'';
example = {
protocol = "dokodemo-door";
settings = {
address = "127.0.0.1";
port = 8080;
};
};
};
jsonFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing a complete XRay inbound object as
JSON. Read at service start time, so the whole inbound including its
credentials can be rendered by a secret manager and never lands in
the Nix store. The tag field is overridden by the listener name.
No share link is generated for listeners defined this way.
Set exactly one of type, xrayJson, or jsonFile for each listener.
'';
example = "/run/secrets/proxy-inbound-vless.json";
};
};
};
in
{
inherit inboundType;
}
+15 -82
View File
@@ -1,4 +1,3 @@
# zapret hostlist and preset option type definitions.
{ lib }:
let
@@ -22,55 +21,29 @@ let
"twitter"
];
zapretDefaultIpType = types.enum [
"all"
];
zapretDefaultIpType = types.enum [ "all" ];
zapretHostlistRuleType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = ''
Custom hostlist name. Used to generate hostlists/list-<name>.txt
inside the derived zapret config directory.
'';
description = "Hostlist name (hostlists/list-<name>.txt).";
example = "cloudflare";
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domains written into the generated custom zapret hostlist file.
Can be combined with defaultDomains.
'';
example = [
"example.com"
"example.de"
];
description = "Domains in this hostlist.";
example = [ "example.com" ];
};
defaultDomains = mkOption {
type = types.listOf zapretDefaultDomainType;
default = [ ];
description = ''
Built-in domain groups copied from zapret-discord-youtube hostlists.
These are expanded and combined with domains.
Each value maps directly to the same-named upstream file:
"general" uses list-general.txt, "google" uses list-google.txt,
and the remaining values use their corresponding list-<name>.txt.
"discord" is an alias for "general"; "youtube" is an alias for
"google".
When "general" or "discord" is used together with configName, the
module also clones the selected config's Discord UDP voice rule
(--filter-l7=discord,stun).
When preset is unset, use one defaultDomains entry per rule so the
module can infer a single rule family. Split groups into separate
rules when they need different strategies.
Upstream lists to include ("discord" = "general", "youtube" = "google"). Without preset,
use one per rule so the strategy family can be inferred.
'';
example = [ "google" ];
};
@@ -78,86 +51,46 @@ let
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IPs or CIDRs written into the generated custom zapret ipset file.
Can be combined with defaultIps.
'';
example = [
"203.0.113.0/24"
"2001:db8::/32"
];
description = "IPs/CIDRs in this rule's ipset.";
example = [ "203.0.113.0/24" ];
};
defaultIps = mkOption {
type = types.listOf zapretDefaultIpType;
default = [ ];
description = ''
Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets.
"all" uses the upstream ipset-all.txt list. The upstream bundle does
not split this list by service, so site-specific defaults remain in
defaultDomains.
'';
description = ''Upstream ipsets to include ("all" is ipset-all.txt).'';
example = [ "all" ];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = ''
Clone this built-in NFQWS rule family for this hostlist. When
configName is set, the family is cloned from that zapret config;
otherwise it is cloned from the active global zapret config.
When unset and defaultDomains is non-empty, rule families are
inferred from defaultDomains.
'';
description = "Strategy family to clone, from configName or the active config.";
example = "google";
};
configName = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
zapret config name to clone NFQWS rules from for this hostlist.
Names use the same matching rules as services.proxy-suite.zapret.configName.
This is a higher-level alternative to nfqwsArgs and cannot be used
together with nfqwsArgs.
'';
description = "Config to clone strategies from. Exclusive with nfqwsArgs.";
example = "general(ALT9)";
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Additional NFQWS argument fragments for this hostlist.
The module injects --hostlist=... and trailing --new automatically.
This cannot be used together with configName.
'';
example = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
description = "Raw NFQWS arguments; --hostlist and --new are added. Exclusive with configName.";
example = [ "--filter-tcp=443 --dpi-desync=fake,multisplit" ];
};
enableDirectSync = mkOption {
type = types.bool;
default = true;
description = ''
Whether this custom hostlist should also be mirrored into proxy
direct domain routing when zapret.syncDirectRouting = true.
'';
description = "Include these domains in zapret.directSync.";
};
};
};
in
{
inherit
zapretDefaultDomainType
zapretDefaultIpType
zapretPresetType
zapretHostlistRuleType
;
inherit zapretHostlistRuleType;
}
@@ -0,0 +1,34 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
in
{
options.services.proxy-suite.userControl = {
group = mkOption {
type = types.strMatching "^[a-z_][a-z0-9_-]*$";
default = "proxy-suite";
description = "Group whose members may run privileged `proxy-ctl` commands without a password.";
};
allow = mkOption {
type = types.listOf (
types.enum [
"global"
"perApp"
]
);
default = [
"global"
"perApp"
];
description = ''
What userControl.group may control without a password:
- "global": the global units (proxy, tun, tproxy, zapret, restart, subs update).
- "perApp": the per-app backend units used by `proxy-ctl apps run`.
Empty grants no passwordless control.
'';
example = [ "global" ];
};
};
}
+79 -183
View File
@@ -1,202 +1,98 @@
# zapret DPI bypass options.
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
inherit (lib) mkEnableOption mkOption types;
t = import ./types.nix { inherit lib; };
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
bool =
default: description:
mkOption {
type = types.bool;
inherit default description;
};
in
{
options.services.proxy-suite.zapret = {
enable = mkEnableOption "zapret DPI bypass";
perApp = {
enable = mkEnableOption "per-app-scoped zapret backend for perAppRouting profiles";
filterMark = mkOption {
type = types.int;
default = 268435456;
description = ''
Packet mark bit used to mark wrapped app traffic for the
dedicated per-app-scoped zapret instance.
'';
example = 268435456;
};
qnum = mkOption {
type = types.int;
default = 201;
description = ''
NFQUEUE number used by the dedicated per-app-scoped zapret instance.
This backend runs as a second zapret daemon and should use a
queue distinct from the global zapret instance.
'';
example = 201;
};
};
syncDirectRouting = mkOption {
type = types.bool;
default = true;
description = ''
When zapret.enable = true, mirror zapret's upstream domain hostlists
into proxy direct domain routing.
This includes the default zapret domain lists and any custom
hostlistRules entries with enableDirectSync = true.
'';
example = true;
};
syncDirectRoutingUpstreamIps = mkOption {
type = types.bool;
default = false;
description = ''
When zapret.enable = true, mirror zapret's upstream ipset ranges
(such as ipset-all.txt minus exclusions) into proxy direct IP routing.
'';
example = false;
};
syncDirectRoutingUserIps = mkOption {
type = types.bool;
default = true;
description = ''
When zapret.enable = true, mirror user-defined zapret.ipsetAll and
zapret.ipsetExclude entries into proxy direct IP routing.
'';
example = true;
};
configName = mkOption {
type = types.str;
default = "general(ALT)";
description = ''
zapret strategy preset name selected from the upstream configs
directory. Exact filenames are accepted, and names that differ only by
whitespace are treated as aliases.
'';
example = "general(ALT)";
};
gameFilter = mkOption {
type = types.str;
default = "null";
description = ''zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.'';
example = "null";
};
listGeneral = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Extra domains to include in zapret's interception list.
When syncDirectRouting = true, these domains are also mirrored into
proxy direct routing.
'';
example = [ "youtube.com" ];
};
listExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domains to exclude from zapret interception.
When syncDirectRouting = true, these exclusions also remove matching
domains from the zapret-derived proxy direct-routing set.
'';
example = [ "music.youtube.com" ];
};
ipsetAll = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Extra IPs/CIDRs to add to zapret's ipset.
Mirrored into proxy direct IP routing when
syncDirectRoutingUserIps = true.
'';
example = [ "203.0.113.0/24" ];
};
ipsetExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IPs/CIDRs to exclude from zapret's ipset.
Also excluded from zapret-derived proxy direct IP routing when
syncDirectRoutingUserIps = true.
'';
example = [ "203.0.113.10/32" ];
};
includeExtraUpstreamLists = mkOption {
type = types.bool;
default = false;
description = ''
Automatically activate upstream list-instagram.txt, list-soundcloud.txt,
and list-twitter.txt in the generated zapret config when the selected
upstream preset does not already reference them.
When syncDirectRouting = true, domains from these extra lists are also
mirrored into proxy direct routing.
'';
example = false;
};
hostlistRules = mkOption {
type = types.listOf t.zapretHostlistRuleType;
default = [ ];
description = ''
Additional named zapret hostlists with per-list DPI mitigation rules.
Each entry generates hostlists/list-<name>.txt and can clone a built-in
zapret family from the active config, clone it from another configName,
add custom NFQWS rule fragments, or combine these pieces.
defaultDomains selects same-named upstream zapret-discord-youtube
hostlists such as "general" and "google", with the aliases "discord"
and "youtube" for readability. defaultIps provides upstream IP/CIDR
groups such as "all". configName is a higher-level alternative to
nfqwsArgs and cannot be used together with nfqwsArgs.
'';
example = [
{
name = "youtube-alt9";
defaultDomains = [ "youtube" ];
configName = "general(ALT9)";
}
{
name = "discord-alt12";
defaultDomains = [ "discord" ];
configName = "general (ALT12)";
}
{
name = "custom-sites";
domains = [
"example.com"
"example.org"
];
ips = [ "203.0.113.0/24" ];
preset = "general";
configName = "general (SIMPLE FAKE)";
}
engine = mkOption {
type = types.enum [
"zapret-discord-youtube"
"zapret2"
];
default = "zapret-discord-youtube";
description = ''
"zapret-discord-youtube": nfqws with curated presets and static hostlists (zapret.zapret-discord-youtube).
"zapret2": nfqws2, which learns blocked hosts at runtime (zapret.zapret2).
'';
example = "zapret2";
};
cidrExemption = {
enable = mkEnableOption "CIDR exemption from zapret NFQUEUE";
# What zapret feeds back into the client routing table.
directSync = {
enable = bool true "Add zapret's domain hostlists to proxy.routing.direct.";
upstreamIps = bool false "Add zapret's upstream ipsets to proxy.routing.direct.";
userIps = bool true "Add zapret-discord-youtube.ips, minus zapret-discord-youtube.excludeIps, to proxy.routing.direct.";
};
cidrs = mkOption {
type = types.listOf types.str;
default = [ ];
example = [
"192.168.123.0/24"
"10.0.0.0/8"
# Shared by both engines: a netfilter-level bypass, not an engine-specific concept.
cidrExemption = {
enable = mkEnableOption "exempting subnets from zapret, e.g. NATed VMs whose traffic it would break";
cidrs = list "Exempted subnets." [ "192.168.123.0/24" ];
};
zapret-discord-youtube = {
configName = mkOption {
type = types.str;
default = "general(ALT)";
description = "Upstream strategy preset. Names that differ only in whitespace match.";
example = "general (ALT9)";
};
gameFilter = mkOption {
type = types.enum [
"all"
"tcp"
"udp"
"null"
];
default = "null";
description = ''Game traffic filter, or "null" for off.'';
example = "all";
};
domains = list "Extra domains to bypass." [ "youtube.com" ];
excludeDomains = list "Domains never bypassed." [ "music.youtube.com" ];
ips = list "Extra IPs/CIDRs to bypass." [ "203.0.113.0/24" ];
excludeIps = list "IPs/CIDRs never bypassed." [ "203.0.113.10/32" ];
includeExtraUpstreamLists = bool false "Also use the upstream instagram, soundcloud and twitter lists.";
hostlistRules = mkOption {
type = types.listOf t.zapretHostlistRuleType;
default = [ ];
description = ''
Subnets to exempt from zapret's NFQUEUE mangle rules.
Useful when a VM (libvirt, etc.) is behind NAT and zapret
would corrupt its traffic through the host's nftables.
Extra named hostlists, each with its own strategy: cloned from a preset or configName,
or given as nfqwsArgs.
'';
example = [
{
name = "youtube-alt9";
defaultDomains = [ "youtube" ];
configName = "general(ALT9)";
}
{
name = "custom-sites";
domains = [ "example.com" ];
preset = "general";
}
];
};
};
};
+139
View File
@@ -0,0 +1,139 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
int =
default: description:
mkOption {
type = types.ints.positive;
inherit default description;
};
# Ported from nfqws2-keenetic. `circular` rotates strategy=1/2/3 per
# second-level domain whenever the failure detector fires.
defaultProfiles = [
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
# QUIC reads the learned list but never adds to it: browsers retry over TCP.
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
# No hostlist: these protocols carry no SNI.
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
];
in
{
options.services.proxy-suite.zapret.zapret2 = {
profiles = mkOption {
type = types.listOf types.str;
default = defaultProfiles;
description = ''
nfqws2 profiles, joined with --new; first match wins. <HOSTLIST> expands to the hostlist
arguments, <HOSTLIST_NOAUTO> to the same without learning. --qnum, --fwmark and --lua-init
are added automatically.
'';
example = [
"--filter-tcp=443 --filter-l7=tls <HOSTLIST> --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld"
];
};
blobs = mkOption {
type = types.attrsOf types.str;
default = {
tls_clienthello = "tls_clienthello_www_google_com.bin";
quic_initial = "quic_initial_www_google_com.bin";
};
description = "Fake payloads by name (blob=<name>): a file in zapret2's files/fake, or an absolute path.";
example = {
tls_clienthello = "/etc/proxy-suite/my_clienthello.bin";
};
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains always treated as blocked. At runtime: `proxy-ctl zapret auto add`.";
example = [ "rutracker.org" ];
};
excludeDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains never touched or learned. At runtime: `proxy-ctl zapret auto exclude`.";
example = [ "bank.example.com" ];
};
ports = {
tcp = mkOption {
type = types.str;
default = "80,443,1984,2053,2083,2087,2096,5222,8443";
description = "TCP ports sent to NFQUEUE. Must cover every port a profile filters on.";
};
udp = mkOption {
type = types.str;
default = "443,590-600,1400,3478-3481,5349,19294-19344,49152-65535";
description = "UDP ports sent to NFQUEUE. Must cover every port a profile filters on.";
};
};
ipv6 = mkOption {
type = types.bool;
default = false;
description = "Intercept IPv6 as well as IPv4.";
};
autoHostlist = {
enable = mkEnableOption "learning blocked hosts at runtime" // {
default = true;
description = ''
Learn blocked hosts: after failThreshold failures (retransmissions, early RST, DPI
redirect, one-sided UDP) a host joins /var/lib/proxy-suite/zapret2/zapret-hosts-auto.txt.
Off, only zapret2.domains and `proxy-ctl zapret auto add` are acted on.
'';
};
failThreshold = int 3 "Failures before a host is learned.";
failTime = int 300 "Seconds allowed between two failures before the count resets.";
retransThreshold = int 3 "Retransmissions of the first request that count as one failure.";
retransReset = mkOption {
type = types.bool;
default = true;
description = "RST a stalled client once retransThreshold is hit, so failures are counted fast.";
};
retransMaxseq = int 32768 "Outgoing sequence number past which failure detection stops.";
incomingMaxseq = int 4096 "Incoming sequence number past which an RST or redirect is not a failure.";
udpOut = int 4 "Outgoing UDP packets before a one-sided exchange counts as a failure.";
udpIn = int 1 "Incoming UDP packets at or below which an exchange is one-sided.";
debugLog = mkOption {
type = types.bool;
default = false;
description = "Log why hosts are or are not learned to zapret-hosts-auto-debug.log.";
};
};
};
}
+13 -13
View File
@@ -25,16 +25,16 @@ let
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.directSync.enable;
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.directSync.upstreamIps;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.directSync.userIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [
"list-general.txt"
"list-google.txt"
]
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
++ lib.optionals zapretCfg.zapret-discord-youtube.includeExtraUpstreamLists [
"list-instagram.txt"
"list-soundcloud.txt"
"list-twitter.txt"
@@ -49,20 +49,20 @@ let
[ ];
zapretDefaultIps =
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.zapret-discord-youtube.ips else [ ];
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule)
) zapretCfg.hostlistRules
) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
zapretCustomUserIps =
if syncZapretDirectUserIps then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.hostlistRules
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
@@ -71,7 +71,7 @@ let
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps)
) zapretCfg.hostlistRules
) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
@@ -84,13 +84,13 @@ let
else
[ ]
)
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
++ (if syncZapretDirectUserIps then zapretCfg.zapret-discord-youtube.excludeIps else [ ])
);
zapretDirectDomains =
if syncZapretDirectDomains then
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
)
else
[ ];
@@ -114,7 +114,7 @@ in
direct = {
domains = lib.unique (r.direct.domains ++ zapretDirectDomains);
ips = lib.unique (r.direct.ips ++ zapretDirectIps);
geosites = lib.unique (r.direct.geosites ++ lib.optional r.enableRuDirect "category-ru");
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
geosites = lib.unique (r.direct.geosites ++ lib.optional r.directRu "category-ru");
geoips = lib.unique (r.direct.geoips ++ lib.optional r.directRu "ru");
};
}
+1 -1
View File
@@ -71,13 +71,13 @@ let
singBoxRules = import ./rules/sing-box.nix {
inherit
lib
pkgs
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
inherit (cfg) geodata;
};
inherit (singBoxRules)
geositeRuleSets
+41 -30
View File
@@ -1,12 +1,5 @@
# XRay routing rules for the server-side inbound service.
#
# Deliberately separate from the client ruleset: inbound traffic belongs to
# somebody else's session, so it is not subject to routing.rules, route-mode
# overrides, or the DNS-hijack machinery the client config needs.
#
# The "proxy" outbound here is the local client stack's SOCKS listener, so
# anything the client decides (selected outbound, urltest, route-mode) applies
# to relayed traffic without being reimplemented.
# XRay routing for the inbound service. Separate from the client ruleset:
# "proxy" here is the client stack's SOCKS listener, so its selection applies.
{
lib,
proxyInboundsCfg,
@@ -15,30 +8,21 @@
}:
let
defaultVia = proxyInboundsCfg.via;
defaultVia = proxyInboundsCfg.routing.via;
# Listeners that follow the tree-wide default need no rule of their own; the
# final rule already sends them there.
# Listeners on the default egress are covered by the final rule.
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds);
blockPrivateRule = lib.optional proxyInboundsCfg.blockPrivate {
blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate {
type = "field";
ruleTag = "inbound-block-private";
ip = [ "geoip:private" ];
outboundTag = "block";
};
# A relay must not blackhole the address clients dial to reach it. Without
# this, a server on a .ru domain (or a .ru IP) blocks itself under blockRu:
# anyone connected through the host cannot open the very site the listeners
# are hidden behind, and a blackholed connection reads as a refusal rather
# than as a rule. Placed after blockPrivate so a NATed serverAddress cannot
# be used to reach the LAN.
#
# It may be given in either form, and geoip:ru catches a literal IP just as
# geosite catches the name. An IPv6 literal is the only form carrying a colon;
# a bare name cannot.
# The address clients dial must stay reachable even when blockRu covers it
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN.
serverAddressIsIp =
let
addr = proxyInboundsCfg.serverAddress;
@@ -60,7 +44,7 @@ let
)
);
blockRuRules = lib.optionals proxyInboundsCfg.blockRu [
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
{
type = "field";
ruleTag = "inbound-block-ru-domain";
@@ -75,12 +59,29 @@ let
}
];
# Only meaningful when the default egress leaves through a proxy: zapret works
# on traffic this host emits itself, so destinations it can already unblock
# are better left direct than sent through a proxy hop. Scoped to the
# listeners on the default egress, so an explicit per-listener `via` wins.
inboundProxy = proxyInboundsCfg.routing.proxy;
proxyDomainRule = lib.optional (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]) {
type = "field";
ruleTag = "inbound-proxy-domain";
domain =
map (domain: "domain:${domain}") inboundProxy.domains
++ map (name: "geosite:${name}") inboundProxy.geosites;
inboundTag = map (ib: ib.tag) proxyInbounds;
outboundTag = "proxy";
};
proxyIpRule = lib.optional (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]) {
type = "field";
ruleTag = "inbound-proxy-ip";
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
inboundTag = map (ib: ib.tag) proxyInbounds;
outboundTag = "proxy";
};
# Only when the default egress is a proxy, and only for its listeners.
zapretDirectEnabled =
proxyInboundsCfg.zapretDirect
proxyInboundsCfg.routing.zapretDirect
&& defaultInboundTags != [ ]
&& !builtins.elem defaultVia [
"direct"
@@ -117,7 +118,17 @@ let
outboundTag = defaultVia;
};
xrayInboundRules = blockPrivateRule ++ serverAddressRule ++ blockRuRules ++ zapretRules ++ overrideRules ++ [ finalRule ];
# Explicit proxy exceptions beat blockRu: RU-geolocated ranges (Telegram's,
# at times) would otherwise swallow them.
xrayInboundRules =
blockPrivateRule
++ serverAddressRule
++ proxyDomainRule
++ proxyIpRule
++ blockRuRules
++ zapretRules
++ overrideRules
++ [ finalRule ];
in
{
inherit xrayInboundRules;
+3 -3
View File
@@ -1,12 +1,12 @@
# sing-box routing rules and local rule-set definitions.
{
lib,
pkgs,
r,
direct,
tgWsProxyCfg,
customRules,
customRuleCategory,
geodata,
}:
let
@@ -47,8 +47,8 @@ let
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
};
geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames;
geositeRuleSets = map (mkRuleSet "geosite" geodata.singBox.geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" geodata.singBox.geoip) allGeoIPNames;
commonRules = [
{
+106 -90
View File
@@ -30,6 +30,8 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretCfg
zapretEngine
;
mkAssertion = assertion: message: { inherit assertion message; };
@@ -55,17 +57,9 @@ let
mkAssertion (!(condition && builtins.elem value disallowed)) message;
featureAssertions = [
(requireAvailable proxyCfg.singBox.enable proxyEnabled
"proxy-suite: proxy.singBox.enable requires proxy.enable = true"
)
(requireAvailable proxyCfg.xray.enable proxyEnabled
"proxy-suite: proxy.xray.enable requires proxy.enable = true"
)
(mkAssertion (!proxyEnabled || proxyCfg.singBox.enable || proxyCfg.xray.enable)
"proxy-suite: at least one of proxy.singBox.enable or proxy.xray.enable must be true when proxy.enable = true"
)
(requireAvailable proxyEnabled (derived.hasAvailableOutbounds
) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true")
# Declaring no outbound at all is legal: they can be added at runtime with
# `proxy-ctl proxy outbounds add`. Only a warning here; the backend still
# refuses to start with nothing to dial.
(uniqueValues proxyEnabled effectiveOutboundTags "proxy-suite: outbound tags must be unique")
(uniqueValues proxyEnabled subscriptionTags
"proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes"
@@ -79,24 +73,30 @@ let
(requireEnabled cfg.sshProxy.asOutbound proxyEnabled
"proxy-suite: sshProxy.asOutbound requires proxy.enable = true"
)
(requireEnabled proxyCfg.autoProxy.enable proxyEnabled
"proxy-suite: proxy.autoProxy.enable requires proxy.enable = true"
)
(mkAssertion (!(proxyCfg.autoProxy.enable && pureXrayEnabled))
"proxy-suite: proxy.autoProxy needs the sing-box backend: learned routes are local rule-sets that sing-box reloads from disk, and pure XRay has no equivalent"
)
(mkAssertion (
!cfg.sshProxy.enable || (cfg.sshProxy.user != null && cfg.sshProxy.host != null)
) "proxy-suite: sshProxy.user and sshProxy.host are required when sshProxy.enable = true")
!cfg.sshProxy.enable || (cfg.sshProxy.server.user != null && cfg.sshProxy.server.host != null)
) "proxy-suite: sshProxy.server.user and sshProxy.server.host are required when sshProxy.enable = true")
# SingBox dials SSH itself and verifies host keys by value, with no
# knownHostsFile and no trust-on-first-use fallback. An empty list accepts
# any host key, so refuse rather than silently downgrade the tunnel.
(mkAssertion (
!derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null
) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p <sshPort> <host>` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm.")
) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p <server.port> <server.host>` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm.")
(mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ])
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
)
(mkAssertion (
!(pureXrayEnabled && proxyCfg.selection == "selector")
) "proxy-suite: proxy.selection = \"selector\" is only available with proxy.singBox.enable = true")
) "proxy-suite: proxy.selection = \"selector\" requires proxy.backend = \"sing-box\" or \"hybrid\"")
(mkAssertion
(!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.xray.enable = true; use udp/tcp DNS for XRay"
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.backend = \"xray\"; use udp/tcp DNS for XRay"
)
(requireEnabled globalTun.enable proxyEnabled
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
@@ -104,15 +104,11 @@ let
(requireEnabled globalTproxy.enable proxyEnabled
"proxy-suite: proxy.tproxy.enable requires proxy.enable = true"
)
(requireEnabled globalTun.autostart globalTun.enable
"proxy-suite: proxy.tun.autostart requires proxy.tun.enable = true"
(requireEnabled (proxyCfg.autostart == "tun") globalTun.enable
''proxy-suite: proxy.autostart = "tun" requires proxy.tun.enable = true''
)
(requireEnabled globalTproxy.autostart globalTproxy.enable
"proxy-suite: proxy.tproxy.autostart requires proxy.tproxy.enable = true"
)
(mkAssertion
(!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart))
"proxy-suite: proxy.tproxy.autostart and proxy.tun.autostart cannot both be enabled at the same time"
(requireEnabled (proxyCfg.autostart == "tproxy") globalTproxy.enable
''proxy-suite: proxy.autostart = "tproxy" requires proxy.tproxy.enable = true''
)
];
@@ -136,38 +132,38 @@ let
"proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable
"proxy-suite: proxy.tun.perApp.enable requires perAppRouting.enable = true"
"proxy-suite: perAppRouting.tun.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingTun.enable proxyEnabled
"proxy-suite: proxy.tun.perApp.enable requires proxy.enable = true"
"proxy-suite: perAppRouting.tun.enable requires proxy.enable = true"
)
(requireAvailable hasTunProfiles perAppRoutingTun.enable
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.tun.perApp.enable = true"
"proxy-suite: route=tun in perAppRouting.profiles requires perAppRouting.tun.enable = true"
)
(requireAvailable hasTunProfiles proxyEnabled
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable
"proxy-suite: proxy.tproxy.perApp.enable requires perAppRouting.enable = true"
"proxy-suite: perAppRouting.tproxy.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingTproxy.enable proxyEnabled
"proxy-suite: proxy.tproxy.perApp.enable requires proxy.enable = true"
"proxy-suite: perAppRouting.tproxy.enable requires proxy.enable = true"
)
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.tproxy.perApp.enable = true"
"proxy-suite: route=tproxy in perAppRouting.profiles requires perAppRouting.tproxy.enable = true"
)
(requireAvailable hasTproxyProfiles proxyEnabled
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true"
"proxy-suite: perAppRouting.zapret.enable requires perAppRouting.enable = true"
)
(requireAvailable hasZapretProfiles perAppZapretCfg.enable
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true"
"proxy-suite: route=zapret in perAppRouting.profiles requires perAppRouting.zapret.enable = true"
)
];
localProxyAuthCfg = proxyCfg.auth;
localProxyAuthCfg = proxyCfg.listener.auth;
localProxyAuthUsed =
localProxyAuthCfg.username != null
|| localProxyAuthCfg.password != null
@@ -175,11 +171,11 @@ let
localProxyAuthAssertions = [
(mkAssertion (
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
) "proxy-suite: proxy.auth requires username when password or passwordFile is set")
) "proxy-suite: proxy.listener.auth requires username when password or passwordFile is set")
(exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
localProxyAuthCfg.password
localProxyAuthCfg.passwordFile
] "proxy-suite: proxy.auth requires exactly one of password or passwordFile")
] "proxy-suite: proxy.listener.auth requires exactly one of password or passwordFile")
];
secretAssertions = [
@@ -202,16 +198,16 @@ let
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true")
) "proxy-suite: outbound '${ob.tag}': xrayJson requires proxy.backend = xray or hybrid")
(mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null))
"proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true"
"proxy-suite: outbound '${ob.tag}': singBoxJson/json require proxy.backend = sing-box or hybrid"
)
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true")
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.backend = xray or hybrid")
(mkAssertion (
!(ob.backend == "sing-box") || singBoxEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid")
]) proxyCfg.outbounds;
proxyInboundsCfg = derived.proxyInboundsCfg;
@@ -230,33 +226,37 @@ let
proxyInboundAssertions =
[
(mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ])
"proxy-suite: proxyInbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those."
"proxy-suite: inbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those."
)
(mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ])
"proxy-suite: proxyInbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson."
"proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson."
)
(requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled
"proxy-suite: proxyInbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
"proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
)
(requireEnabled proxyInboundsEnabled (proxyInbounds != [ ])
"proxy-suite: proxyInbounds.enable requires at least one entry in proxyInbounds.listeners"
"proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners"
)
(requireEnabled proxyInboundsNeedLocalProxy proxyEnabled
"proxy-suite: proxyInbounds.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
)
(requireEnabled proxyInboundsNeedLocalProxy derived.hasAvailableOutbounds
"proxy-suite: proxyInbounds.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required"
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required"
)
(uniqueValues proxyInboundsEnabled (map (ib: ib.listener.port) proxyInbounds)
"proxy-suite: proxyInbounds.listeners must each use a distinct port"
"proxy-suite: inbounds.listeners must each use a distinct port"
)
(requireEnabled (proxyInboundsEnabled && proxyInboundsCfg.subscriptions.enable)
proxyInboundsCfg.shareLinks
"proxy-suite: inbounds.subscriptions are made of the share links, so they need inbounds.shareLinks = true"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !proxyEnabled
|| !builtins.elem proxyCfg.port derived.proxyInboundPorts
|| !builtins.elem proxyCfg.listener.port derived.proxyInboundPorts
)
"proxy-suite: a proxyInbounds listener port collides with proxy.port (${toString proxyCfg.port})"
"proxy-suite: a proxyInbounds listener port collides with proxy.listener.port (${toString proxyCfg.listener.port})"
)
(mkAssertion
(
@@ -271,7 +271,7 @@ let
ib:
let
l = ib.listener;
prefix = "proxy-suite: proxyInbounds listener '${ib.tag}'";
prefix = "proxy-suite: inbounds listener '${ib.tag}'";
firstUser = if l.users == [ ] then null else builtins.head l.users;
needsUuid = builtins.elem l.type [
"vless"
@@ -314,7 +314,7 @@ let
) "${prefix}: reality.serverNames must not be empty")
(requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks)
(l.reality.publicKey != null)
"${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set proxyInbounds.shareLinks = false."
"${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set inbounds.shareLinks = false."
)
(mkAssertion
(
@@ -333,6 +333,15 @@ let
)
"${prefix}: flow is only valid on a vless listener with transport.type = \"raw\""
)
(mkAssertion
(
!proxyInboundsEnabled
|| l.tls.alpn == null
|| !builtins.elem "h3" l.tls.alpn
|| (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable)
)
"${prefix}: tls.alpn \"h3\" is served only by the xhttp transport with tls.enable (not REALITY)"
)
]
) proxyInbounds;
@@ -344,127 +353,134 @@ let
]) proxyCfg.subscriptions;
globalTunAutoRouteTable = constants.tunAutoRouteTableIndex;
globalZapretQnum = constants.zapretGlobalQnum.${zapretEngine};
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.interface;
right = perAppRoutingTun.interface;
message = "proxy-suite: proxy.tun.interface and proxy.tun.perApp.interface must differ";
message = "proxy-suite: proxy.tun.interface and perAppRouting.tun.interface must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.address;
right = perAppRoutingTun.address;
message = "proxy-suite: proxy.tun.address and proxy.tun.perApp.address must differ";
message = "proxy-suite: proxy.tun.address and perAppRouting.tun.address must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = perAppRoutingTun.routeTable;
right = globalTunAutoRouteTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from the global TUN auto-route table ${toString globalTunAutoRouteTable}";
message = "proxy-suite: perAppRouting.tun.routeTable must differ from the global TUN auto-route table ${toString globalTunAutoRouteTable}";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled";
message = "proxy-suite: perAppRouting.tun.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled";
message = "proxy-suite: perAppRouting.tun.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.routeTable;
right = globalTproxy.routeTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled";
message = "proxy-suite: perAppRouting.tun.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled";
}
{
condition = perAppZapretCfg.enable && zapretCfg.enable;
left = perAppZapretCfg.qnum;
right = globalZapretQnum;
message = "proxy-suite: perAppRouting.zapret.qnum must differ from the global zapret instance's NFQUEUE ${toString globalZapretQnum}";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.fwmark";
message = "proxy-suite: perAppRouting.tproxy.fwmark must differ from proxy.tproxy.fwmark";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.proxyMark";
message = "proxy-suite: perAppRouting.tproxy.fwmark must differ from proxy.tproxy.proxyMark";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.routeTable;
right = globalTproxy.routeTable;
message = "proxy-suite: proxy.tproxy.perApp.routeTable must differ from proxy.tproxy.routeTable";
message = "proxy-suite: perAppRouting.tproxy.routeTable must differ from proxy.tproxy.routeTable";
}
{
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.fwmark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: proxy.tun.perApp.fwmark and proxy.tproxy.perApp.fwmark must differ";
message = "proxy-suite: perAppRouting.tun.fwmark and perAppRouting.tproxy.fwmark must differ";
}
{
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.routeTable;
right = perAppRoutingTproxy.routeTable;
message = "proxy-suite: proxy.tun.perApp.routeTable and proxy.tproxy.perApp.routeTable must differ";
message = "proxy-suite: perAppRouting.tun.routeTable and perAppRouting.tproxy.routeTable must differ";
}
{
condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark;
right = globalTproxy.fwmark;
message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.fwmark";
message = "proxy-suite: perAppRouting.zapret.filterMark must differ from proxy.tproxy.fwmark";
}
{
condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark;
right = globalTproxy.proxyMark;
message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.proxyMark";
message = "proxy-suite: perAppRouting.zapret.filterMark must differ from proxy.tproxy.proxyMark";
}
{
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
left = perAppRoutingTun.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: proxy.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
message = "proxy-suite: perAppRouting.tun.fwmark and perAppRouting.zapret.filterMark must differ";
}
{
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
left = perAppRoutingTproxy.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
message = "proxy-suite: perAppRouting.tproxy.fwmark and perAppRouting.zapret.filterMark must differ";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark;
left = tgWsProxyCfg.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.fwmark";
message = "proxy-suite: tgWsProxy.fwmark must differ from proxy.tproxy.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark;
left = tgWsProxyCfg.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.proxyMark";
message = "proxy-suite: tgWsProxy.fwmark must differ from proxy.tproxy.proxyMark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
left = tgWsProxyCfg.routingMark;
left = tgWsProxyCfg.fwmark;
right = perAppRoutingTun.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark";
message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.tun.fwmark";
}
{
condition =
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
left = tgWsProxyCfg.routingMark;
left = tgWsProxyCfg.fwmark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark";
message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.tproxy.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
left = tgWsProxyCfg.routingMark;
left = tgWsProxyCfg.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: tgWsProxy.routingMark must differ from zapret.perApp.filterMark";
message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.zapret.filterMark";
}
];
@@ -483,7 +499,7 @@ let
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.mtu;
message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero";
message = "proxy-suite: perAppRouting.tun.mtu must be greater than zero";
}
{
condition = globalTproxy.enable;
@@ -503,37 +519,37 @@ let
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.fwmark;
message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero";
message = "proxy-suite: perAppRouting.tun.fwmark must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.routeTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero";
message = "proxy-suite: perAppRouting.tun.routeTable must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.fwmark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero";
message = "proxy-suite: perAppRouting.tproxy.fwmark must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.routeTable;
message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero";
message = "proxy-suite: perAppRouting.tproxy.routeTable must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
message = "proxy-suite: zapret.perApp.filterMark must be greater than zero";
message = "proxy-suite: perAppRouting.zapret.filterMark must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.qnum;
message = "proxy-suite: zapret.perApp.qnum must be greater than zero";
message = "proxy-suite: perAppRouting.zapret.qnum must be greater than zero";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
value = tgWsProxyCfg.routingMark;
message = "proxy-suite: tgWsProxy.routingMark must be greater than zero";
value = tgWsProxyCfg.fwmark;
message = "proxy-suite: tgWsProxy.fwmark must be greater than zero";
}
];
@@ -547,7 +563,7 @@ let
536870912
1073741824
];
message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits";
message = "proxy-suite: perAppRouting.zapret.filterMark must not use zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
@@ -565,25 +581,25 @@ let
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
value = perAppRoutingTun.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
message = "proxy-suite: perAppRouting.tun.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
value = perAppRoutingTproxy.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
message = "proxy-suite: perAppRouting.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
message = "proxy-suite: perAppRouting.zapret.filterMark must not use per-app-zapret internal desync mark bits";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
value = tgWsProxyCfg.routingMark;
value = tgWsProxyCfg.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits";
message = "proxy-suite: tgWsProxy.fwmark must not use per-app-zapret internal desync mark bits";
}
];
in
+8 -3
View File
@@ -36,6 +36,7 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
userControlCfg
selectionMode
builtinTags
@@ -43,13 +44,13 @@ let
subscriptionTags
invalidRoutingTargets
collapseNamedOutbounds
hasSubscriptions
sshProxyCfg
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
;
@@ -96,7 +97,6 @@ let
userControlCfg
selectionMode
collapseNamedOutbounds
hasSubscriptions
constants
;
inherit
@@ -120,6 +120,7 @@ let
inherit
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
builders
@@ -161,12 +162,16 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
constants
selectionMode
userControlCfg
;
inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
inherit (scripts) routeModeStateFile;
inherit proxyInboundsEnabled;
inherit (scripts) proxyInboundsLinksFile;
inherit (scripts) proxyInboundsLinksFile proxyInboundsSubscriptionsFile;
proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl;
inherit amneziaWgProfileNamesFile;
inherit (perAppRouting)
perAppRoutingProfilesFile
@@ -1,16 +1,22 @@
# Subscription refresh and route-mode control scripts.
# Subscription refresh, route-mode and outbound control scripts.
{
lib,
pkgs,
proxyCfg,
clashApi,
routeModeStateFile,
priorityOutboundFile,
outboundInventoryFile,
subscriptionCacheDir,
subscriptionCacheHelpersBlock,
mkSubscriptionFetchBlock,
runtimeSubscriptionsFetchBlock,
jq,
}:
let
systemctl = "${pkgs.systemd}/bin/systemctl";
curl = "${pkgs.curl}/bin/curl";
restartActiveConfigConsumersBlock =
lib.concatMapStrings
@@ -32,6 +38,7 @@ let
FAILED=0
${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
${runtimeSubscriptionsFetchBlock}
if [ "$FAILED" -eq 0 ]; then
${restartActiveConfigConsumersBlock}
@@ -69,10 +76,77 @@ let
${restartActiveConfigConsumersBlock}
'';
# Pins the outbound the proxy prefers, or "auto" to hand the choice back to the
# configured selection. The pin is persisted either way; a live Clash API switch
# only saves the restart.
setPriorityOutboundScript = pkgs.writeShellScript "proxy-suite-set-priority-outbound" ''
set -euo pipefail
tag="''${1:-}"
if [ -z "$tag" ]; then
echo "proxy-suite: usage: proxy-suite-set-priority-outbound <tag|auto>" >&2
exit 1
fi
if [ "$tag" = "auto" ]; then
rm -f "${priorityOutboundFile}"
else
# The inventory only exists once the proxy has run. Without it there is
# nothing to check against, so accept the tag and let the start script warn
# if it turns out to name nothing.
if [ -r "${outboundInventoryFile}" ] \
&& ! ${jq} -e --arg t "$tag" '.tags | index($t) != null' "${outboundInventoryFile}" >/dev/null; then
echo "proxy-suite: unknown outbound '$tag'" >&2
exit 1
fi
mkdir -p "$(dirname "${priorityOutboundFile}")"
printf '%s\n' "$tag" > "${priorityOutboundFile}"
# Live switch when the running config exposes a selector; the persisted pin
# is what keeps it after the next restart.
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
-H "Content-Type: application/json" \
-d "$(${jq} -cn --arg name "$tag" '{name:$name}')" >/dev/null 2>&1; then
exit 0
fi
fi
${restartActiveConfigConsumersBlock}
'';
# Applies whatever is now in the runtime spool directories. A removed runtime
# subscription leaves a root-owned cache behind that the group cannot unlink,
# so the cache dir is reconciled against the sources here.
reloadOutboundsScript = pkgs.writeShellScript "proxy-suite-reload-outbounds" ''
set -euo pipefail
${subscriptionCacheHelpersBlock}
KEEP="|${
lib.concatMapStrings (sub: "${sub.tag}|") proxyCfg.subscriptions
}"
while IFS=$'\t' read -r TAG _; do
[ -n "$TAG" ] || continue
KEEP="$KEEP$TAG|"
done < <(_proxy_suite_runtime_subscriptions)
for CACHE in "$SUB_CACHE_DIR"/*.json; do
[ -e "$CACHE" ] || continue
TAG="''${CACHE##*/}"
TAG="''${TAG%.json}"
case "$KEEP" in
*"|$TAG|"*) ;;
*) rm -f "$CACHE" ;;
esac
done
${restartActiveConfigConsumersBlock}
'';
in
{
inherit
subscriptionUpdateScript
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
;
}
+22 -1
View File
@@ -7,7 +7,10 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
zapretEngine,
constants,
selectionMode,
userControlCfg,
subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingProfilesFile,
@@ -17,6 +20,8 @@
amneziaWgProfileNamesFile,
proxyInboundsEnabled,
proxyInboundsLinksFile,
proxyInboundsSubscriptionsFile,
proxyInboundsSubscriptionsBaseUrl,
}:
{
proxyCtl = packages.mkProxyCtl {
@@ -31,13 +36,29 @@
routeModeStateFile
amneziaWgProfileNamesFile
;
defaultRouteMode = if proxyCfg.proxyByDefault then "blacklist" else "whitelist";
defaultRouteMode = if (proxyCfg.routing.default == "proxy") then "blacklist" else "whitelist";
perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0";
perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0";
perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0";
perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0";
perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0";
zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0";
zapretStateDir = constants.zapret2StateDir;
priorityOutboundFile = constants.priorityOutboundFile;
outboundInventoryFile = constants.outboundInventoryFile;
runtimeOutboundsDir = constants.runtimeOutboundsDir;
runtimeSubscriptionsDir = constants.runtimeSubscriptionsDir;
userControlGroup = userControlCfg.group;
inboundsEnabled = if proxyInboundsEnabled then "1" else "0";
inboundsLinksFile = proxyInboundsLinksFile;
inboundsStatsFile = constants.inboundStatsFile;
inboundsSubscriptionsFile = proxyInboundsSubscriptionsFile;
inboundsSubscriptionsBaseUrl =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0";
autoProxyStateDir = constants.autoProxyStateDir;
localProxyUrl = "http://${
if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address
}:${toString proxyCfg.listener.port}";
};
}
+101 -66
View File
@@ -63,7 +63,6 @@ let
userControlCfg
userControlEnabled
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
@@ -106,7 +105,6 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
@@ -115,6 +113,7 @@ let
perAppRouting
routingScripts
;
inherit (cfg) geodata;
};
inherit (serviceUnits)
localProxyAuthEnabled
@@ -122,72 +121,108 @@ let
userServiceEntries
timerEntries
;
in
{
environment.systemPackages = [ control.proxyCtl ];
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.proxyInbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${polkit.userControlPolkitRules}
return null;
});
''
# autoProxy shells out to the built proxy-ctl, which only exists in this
# scope, so its units are merged in here rather than alongside the other
# feature modules in ../default.nix.
autoProxyUnits = lib.mkIf cfg.proxy.autoProxy.enable (
import ../autoproxy.nix {
inherit lib pkgs cfg;
inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir;
}
);
in
lib.mkMerge [
autoProxyUnits
{
environment.systemPackages = [ control.proxyCtl ];
systemd.user.services = mkNamedUnits userServiceEntries;
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
inherit
builtinTags
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting)
effectivePerAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
};
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
systemd.services = mkNamedUnits systemServiceEntries;
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
systemd.timers = mkNamedUnits timerEntries;
}
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${polkit.userControlPolkitRules}
return null;
});
''
);
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without userControl only root
# writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlEnabled then "2770 root ${userControlCfg.group}" else "0700 root root"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
systemd.user.services = mkNamedUnits userServiceEntries;
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
inherit
builtinTags
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting)
effectivePerAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
};
warnings = lib.optional (proxyEnabled && !derived.hasAvailableOutbounds) (
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
+ " until one is added with `proxy-ctl proxy outbounds add`"
);
systemd.services = mkNamedUnits systemServiceEntries;
systemd.timers = mkNamedUnits timerEntries;
}
]
@@ -44,7 +44,7 @@ let
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = proxyCfg.auth;
localProxyAuth = proxyCfg.listener.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
@@ -65,7 +65,7 @@ let
tcp_connect_time_out 8000
[ProxyList]
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
socks5 ${proxyCfg.listener.address} ${toString proxyCfg.listener.port}
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
+3 -3
View File
@@ -6,15 +6,15 @@
}:
let
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
userControlEnabled = userControlCfg.allow != [ ];
userControlPolkitRules =
lib.optionalString userControlCfg.perApp.enable ''
lib.optionalString (builtins.elem "perApp" userControlCfg.allow) ''
if (unit.indexOf("proxy-suite-per-app-") === 0) {
return polkit.Result.YES;
}
''
+ lib.optionalString userControlCfg.global.enable ''
+ lib.optionalString (builtins.elem "global" userControlCfg.allow) ''
if ((unit.indexOf("proxy-suite-") === 0 &&
unit.indexOf("proxy-suite-per-app-") !== 0) ||
unit === "zapret-discord-youtube.service") {
@@ -1,8 +1,5 @@
# Startup script for the server-side inbound service.
#
# Much smaller than the client start script: no route-mode, no TUN/TProxy, no
# hybrid sidecar. It renders the listeners (reading their secrets), merges them
# into the build-time template, and hands the result to XRay.
# Start script of the inbound service: renders the listeners with their secrets into the
# template and runs XRay.
{
lib,
pkgs,
@@ -23,16 +20,16 @@
proxyInboundsFile,
proxyInboundsSpecFile,
builders,
constants,
}:
let
runtimeDir = "/run/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
# This service's own package, not the client backend's.
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
xray = "${proxyInboundsCfg.package}/bin/xray";
# Only the local proxy needs credentials injected; the listeners' own secrets
# are resolved by build-inbound.py.
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
serverAddressBlock =
@@ -43,17 +40,15 @@ let
${builders.mkDefaultUplinkIPv4Source {
ip = "${pkgs.iproute2}/bin/ip";
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set proxyInbounds.serverAddress";
errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set inbounds.serverAddress";
}}
SERVER_ADDRESS="$uplink_addr"
''
else
''SERVER_ADDRESS=""'';
# Outbounds a listener pins itself to with `via = "<tag>"`. Rendered here, at
# start time, so a urlFile's contents stay out of the Nix store. Subscriptions
# are deliberately not duplicated into this service: their cache is refreshed
# for the client backend only, and `via = "proxy"` already reaches them.
# Outbounds pinned with `via = "<tag>"`, rendered at start so urlFile contents stay
# out of the store.
mkViaOutboundBlock =
ob:
let
@@ -86,8 +81,6 @@ let
viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds;
# Share links carry the listener credentials, so they are no more public than
# the config itself.
writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks ''
${jq} -c '.links' <<< "$RENDERED" > "${linksFile}"
${lib.optionalString userControlEnabled ''
@@ -96,6 +89,28 @@ let
chmod ${if userControlEnabled then "640" else "600"} "${linksFile}"
'';
# One file per user for the web server, plus a token index for proxy-ctl. Filled aside
# and swapped in whole; a missing group leaves them root-only.
writeSubscriptionsBlock = lib.optionalString (proxyInboundsCfg.shareLinks && subsCfg.enable) ''
SUB_DIR="${runtimeDir}/subscriptions"
rm -rf "$SUB_DIR.new"
mkdir -m 0750 "$SUB_DIR.new"
${jq} -r '.subscriptions[] | "\(.token)\t\(.body)"' <<< "$RENDERED" |
while IFS=$'\t' read -r token body; do
printf '%s' "$body" > "$SUB_DIR.new/$token"
done
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2
rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}"
''}
chmod ${if userControlEnabled then "640" else "600"} "${subscriptionsFile}"
'';
startInbounds = pkgs.writeShellScript "proxy-suite-start-inbounds" ''
set -euo pipefail
umask 077
@@ -133,10 +148,42 @@ let
chmod 600 "$RUNTIME_DIR/config.json"
${writeLinksBlock}
${writeSubscriptionsBlock}
exec ${xray} run -c "$RUNTIME_DIR/config.json"
'';
# Adds XRay's per-user counters to the daily totals, read and reset in one call.
# ponytail: a restart of the inbounds loses what was counted since the last run, at
# most one timer interval; collect from ExecStop if that matters.
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbound-stats" ''
set -euo pipefail
file=${lib.escapeShellArg constants.inboundStatsFile}
if ! reading=$(${xray} api statsquery --server=127.0.0.1:${toString constants.inboundStatsApiPort} \
-pattern 'user>>>' -reset 2> /dev/null); then
echo "the inbounds' stats API is not answering; nothing collected"
exit 0
fi
[ -n "$reading" ] || reading='{}'
[ -s "$file" ] || echo '{}' > "$file"
tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX")
${jq} --argjson q "$reading" \
--arg day "$(${pkgs.coreutils}/bin/date +%F)" \
--argjson now "$(${pkgs.coreutils}/bin/date +%s)" \
-f ${../inbound-stats-add.jq} "$file" > "$tmp"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" ||
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2
''}
chmod ${if userControlEnabled then "640" else "600"} "$tmp"
mv -f "$tmp" "$file"
'';
in
{
inherit startInbounds linksFile;
inherit
startInbounds
collectInboundStats
linksFile
subscriptionsFile
;
}
@@ -117,7 +117,7 @@ in
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop.
# interface after `proxy-ctl proxy tun off` or an unclean service stop.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
@@ -1,6 +1,8 @@
{
lib,
pureXrayEnabled,
selectionMode,
proxyInboundsGuardPrivate,
}:
if pureXrayEnabled then
@@ -95,4 +97,21 @@ else
| .dns.final = $dns_final
| if $clear_dns_rules then .dns.rules = [] else . end
else . end
# autoProxy rules, after the route-mode replace so no mode drops them: pins first
# (they only match their own listener), learned rules last before final, so
# explicit rules win. All [] when off.
| .inbounds += $probe_inbounds
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
''
+ lib.optionalString proxyInboundsGuardPrivate ''
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Last, so only traffic falling through to a direct final is resolved. Local mixed-
# in clients lose names that resolve private.
| if (.route.final // "direct") == "direct" then
.route.rules += [
{inbound: ["mixed-in"], action: "resolve"},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}
]
else . end
''
@@ -1,4 +1,3 @@
# Outbound construction script fragments for backend startup scripts.
{
lib,
pkgs,
@@ -12,18 +11,21 @@
backend,
backendArg,
xraySidecarRoutingMark,
priorityOutboundFile,
runtimeOutboundsDir,
jq,
python3,
parserScriptsPythonPath,
buildOutboundPy,
mkSubscriptionBlock,
mkSubscriptionLoadHelperBlock,
runtimeSubscriptionsBlock,
}:
let
sshProxyTag = "ssh-proxy";
# sing-box domain-strategy names mapped onto XRay's sockopt.domainStrategy.
# XRay's "UseIPv4v6" means "IPv4 first, fall back to IPv6", i.e. prefer_ipv4.
# sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4).
xrayDomainStrategies = {
prefer_ipv4 = "UseIPv4v6";
prefer_ipv6 = "UseIPv6v4";
@@ -54,6 +56,114 @@ let
in
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
# Every outbound that comes from a URL goes through these, whether it was
# declared in Nix or dropped into outbounds.d at runtime.
mkUrlOutboundHelpersBlock =
routingMark:
let
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
parse = backendFlag: markFlag: ''
printf '%s' "$2" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
${backendFlag} --tag "$1"${markFlag}
'';
addBlock =
if hybridEnabled then
''
case "$pref" in
xray)
ob=$(_proxy_suite_parse_xray_url "$tag" "$url") || return 1
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
;;
sing-box)
ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url") || return 1
_proxy_suite_add_sing_box_ob "$ob"
;;
*)
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$ob"
elif ob=$(_proxy_suite_parse_xray_url "$tag" "$url"); then
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
else
echo "proxy-suite: outbound '$tag' cannot be parsed by SingBox or XRay" >&2
if [ -s "$RUNTIME_DIR/sing-box-parser.err" ]; then
cat "$RUNTIME_DIR/sing-box-parser.err" >&2
fi
return 1
fi
;;
esac
''
else
''
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
in
''
OUTBOUND_SOURCES_JSON='{}'
_proxy_suite_record_tag_source() {
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
}
# $1 source label, $2 array length before the add, $3 after. Subscriptions
# append an unknown number of outbounds, so they label them by range.
_proxy_suite_record_outbound_source() {
[ "$3" -gt "$2" ] || return 0
OUTBOUND_SOURCES_JSON=$(${jq} \
--argjson sources "$OUTBOUND_SOURCES_JSON" --arg s "$1" \
--argjson b "$2" --argjson a "$3" \
'reduce .[$b:$a][].tag as $t ($sources; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
}
${
if hybridEnabled then
''
_proxy_suite_parse_sing_box_url() {
${parse "--backend sing-box" markArg}
}
_proxy_suite_parse_xray_url() {
${parse "--backend xray" " --routing-mark ${toString xraySidecarRoutingMark}"}
}
''
else
''
_proxy_suite_parse_url() {
${parse backendArg markArg}
}
''
}
# $1 tag, $2 URL, $3 source label, $4 backend preference (auto|sing-box|xray).
# Returns non-zero when the URL cannot be parsed; the caller decides whether
# that is fatal.
_proxy_suite_add_url_outbound() {
local tag="$1" url="$2" source="$3" pref="''${4:-auto}" ob
${addBlock}
_proxy_suite_record_tag_source "$tag" "$source"
}
# Every runtime outbound, as "<tag>\t<url file>" lines. proxy-ctl refuses
# the reserved names, but the spool is group-writable, so check again here:
# a second outbound tagged "proxy" would quietly shadow the real one.
_proxy_suite_runtime_outbounds() {
local f tag
[ -d "${runtimeOutboundsDir}" ] || return 0
for f in "${runtimeOutboundsDir}"/*.url; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
case "$tag" in
proxy | direct | block)
echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2
continue
;;
esac
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
mkOutboundBlock =
ob: routingMark: tag:
let
@@ -74,6 +184,7 @@ let
# outbound: ${tag} (static ${backend} json)
OB_JSON=$(cat "${jsonFile}")
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else
let
@@ -82,11 +193,7 @@ let
in
''
# outbound: ${tag}
URL=$(cat "${urlSource}")
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static || exit 1
'';
singBoxRawOutboundJson =
@@ -117,6 +224,7 @@ let
# outbound: ${tag} (hybrid XRay json sidecar)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else if ob.singBoxJson != null || ob.json != null then
let
@@ -127,66 +235,27 @@ let
# outbound: ${tag} (hybrid SingBox json)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_sing_box_ob "$OB_JSON"
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else
let
urlSource =
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
singBoxCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
}
'';
xrayCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark}
'';
in
if ob.backend == "xray" then
''
# outbound: ${tag} (hybrid forced XRay sidecar)
URL=$(cat "${urlSource}")
OB_JSON=$(${xrayCommand})
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
''
else if ob.backend == "sing-box" then
''
# outbound: ${tag} (hybrid forced SingBox)
URL=$(cat "${urlSource}")
OB_JSON=$(${singBoxCommand})
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${tag} (hybrid auto)
URL=$(cat "${urlSource}")
if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$OB_JSON"
else
SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)"
if OB_JSON=$(${xrayCommand}); then
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
else
echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2
if [ -n "$SING_BOX_PARSE_ERROR" ]; then
printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2
fi
exit 1
fi
fi
'';
''
# outbound: ${tag} (hybrid ${ob.backend})
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static ${ob.backend} || exit 1
'';
mkSshProxyOutboundBlock =
routingMark:
let
# sing-box dials SSH itself, so there is no OpenSSH unit and no local
# SOCKS5 hop. It resolves destinations natively, which is why this shape
# takes no domainStrategy.
singBoxOutbound = {
type = "ssh";
tag = sshProxyTag;
server = sshProxyCfg.host;
server_port = sshProxyCfg.sshPort;
user = sshProxyCfg.user;
server = sshProxyCfg.server.host;
server_port = sshProxyCfg.server.port;
user = sshProxyCfg.server.user;
}
// lib.optionalAttrs (sshProxyCfg.identityFile != null) {
private_key_path = sshProxyCfg.identityFile;
@@ -197,9 +266,7 @@ let
// lib.optionalAttrs (routingMark != null) {
routing_mark = routingMark;
};
# XRay has no SSH outbound, so it proxies through the listener the
# OpenSSH unit creates. sockopt.domainStrategy is what makes XRay resolve
# destinations here instead of handing the domain to the remote sshd.
# XRay has no SSH outbound: it goes through the OpenSSH unit's listener.
xraySockopt =
lib.optionalAttrs (routingMark != null) { mark = routingMark; }
// lib.optionalAttrs (sshProxyCfg.domainStrategy != null) {
@@ -209,8 +276,8 @@ let
protocol = "socks";
tag = sshProxyTag;
settings = {
address = sshProxyCfg.listenAddress;
port = sshProxyCfg.listenPort;
address = sshProxyCfg.listener.address;
port = sshProxyCfg.listener.port;
};
}
// lib.optionalAttrs (xraySockopt != { }) {
@@ -220,13 +287,12 @@ let
outboundJson = builtins.toJSON outbound;
jsonFile = pkgs.writeText "proxy-suite-ob-ssh-proxy-${backend}.json" outboundJson;
# Host keys come from a known-hosts file at start time so the file stays
# out of the Nix store. ssh-keygen -F also resolves hashed entries.
# Read at start so the known-hosts file stays out of the store.
knownHostsTarget =
if sshProxyCfg.sshPort == 22 then
sshProxyCfg.host
if sshProxyCfg.server.port == 22 then
sshProxyCfg.server.host
else
"[${sshProxyCfg.host}]:${toString sshProxyCfg.sshPort}";
"[${sshProxyCfg.server.host}]:${toString sshProxyCfg.server.port}";
hostKeyFileBlock =
lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null)
''
@@ -240,38 +306,71 @@ let
OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON")
'';
in
if hybridEnabled then
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
else
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source ${sshProxyTag} ssh
'';
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
runtimeOutboundsBlock = ''
# outbounds added at runtime
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
[ -n "$RUNTIME_OB_TAG" ] || continue
_proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime \
|| echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2
done < <(_proxy_suite_runtime_outbounds)
'';
requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2
echo "proxy-suite: no proxy outbounds are available; declare one, or add one with 'proxy-ctl proxy outbounds add'" >&2
exit 1
fi
'';
# The pin names a user-facing tag, so it is resolved before the wrapper block
# renames anything. A pin that no longer matches any outbound - a subscription
# entry that went away, say - is dropped rather than left to break the config.
pinBlock = ''
OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON")
PRIORITY_OUTBOUND=""
if [ -r "${priorityOutboundFile}" ]; then
PRIORITY_OUTBOUND="$(tr -d '\r\n[:space:]' < "${priorityOutboundFile}" 2>/dev/null || true)"
fi
if [ -n "$PRIORITY_OUTBOUND" ] \
&& ! ${jq} -e --arg t "$PRIORITY_OUTBOUND" 'index($t) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then
echo "proxy-suite: warning: pinned outbound '$PRIORITY_OUTBOUND' is not available; picking automatically" >&2
PRIORITY_OUTBOUND=""
fi
'';
# proxy-ctl reads this unprivileged: tags, where each came from, and the pin.
inventoryBlock = ''
${jq} -n \
--argjson tags "$OUTBOUND_TAGS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg pinned "$PRIORITY_OUTBOUND" \
--arg selection ${lib.escapeShellArg selectionMode} \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \
> "$RUNTIME_DIR/outbounds.json"
chmod 644 "$RUNTIME_DIR/outbounds.json"
'';
mkOutboundScript =
routingMark:
let
outboundBlocks =
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
mkBackendOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy"
else
lib.concatMapStrings (ob: mkBackendOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds;
outboundBlocks = lib.concatMapStrings (
ob: mkBackendOutboundBlock ob routingMark ob.tag
) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark
@@ -283,43 +382,74 @@ let
if pureXrayEnabled && selectionMode == "urltest" then
''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
# XRay has no selector: a pin degrades the balancer to the one outbound,
# which is the same path a single-outbound config already takes.
if [ -n "$PRIORITY_OUTBOUND" ]; then
XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PRIORITY_OUTBOUND"
elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi
''
else if collapseNamedOutbounds then
lib.optionalString
(proxyCfg.outbounds == [ ] && (proxyCfg.subscriptions != [ ] || sshProxyCfg.asOutbound))
''
FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON")
if [ -n "$FIRST_TAG" ]; then
OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
fi
''
''
PROXY_TAG="$PRIORITY_OUTBOUND"
if [ -z "$PROXY_TAG" ]; then
PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
''
else if selectionMode == "selector" then
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
DEFAULT_TAG="$PRIORITY_OUTBOUND"
if [ -z "$DEFAULT_TAG" ]; then
DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$FIRST" \
--arg default "$DEFAULT_TAG" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
''
else
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
if [ -n "$PRIORITY_OUTBOUND" ]; then
# A pin beats latency ranking: the same outbounds, behind a selector
# the Clash API can also switch live.
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$PRIORITY_OUTBOUND" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
else
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
fi
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'';
# Real exits for autoProxy, taken after the wrapper may have renamed one to
# "proxy".
exitTagsBlock = ''
EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest") | .tag]' <<< "$OUTBOUNDS_JSON")
'';
in
outboundBlocks + subscriptionBlocks + sshProxyBlock + requireOutboundsBlock + wrapperBlock;
mkUrlOutboundHelpersBlock routingMark
+ mkSubscriptionLoadHelperBlock routingMark
+ outboundBlocks
+ subscriptionBlocks
+ runtimeSubscriptionsBlock
+ runtimeOutboundsBlock
+ sshProxyBlock
+ requireOutboundsBlock
+ pinBlock
+ inventoryBlock
+ wrapperBlock
+ exitTagsBlock;
in
{
inherit mkOutboundScript rawOutboundJson;
@@ -1,12 +1,16 @@
# Subscription cache and outbound-loading script fragments.
#
# Everything is emitted as shell functions taking a tag and a file holding the
# subscription URL, so a subscription declared in Nix and one added at runtime
# under `subscriptions.d/` go through exactly the same code.
{
lib,
pkgs,
proxyCfg,
hasSubscriptions,
hybridEnabled,
mainBackend,
backend,
runtimeSubscriptionsDir,
jq,
python3,
parserScriptsPythonPath,
@@ -19,8 +23,6 @@ let
subscriptionBackendArg = "--backend ${subscriptionBackend}";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
mkSubscriptionUrlSource =
sub:
if sub.urlFile != null then
@@ -28,20 +30,12 @@ let
else
pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url;
mkSubscriptionFetchCommand =
sub:
let
urlSource = mkSubscriptionUrlSource sub;
in
# Both call sites append their own `> "$CACHE_FILE.tmp"`, so this must not
# end in a newline: that would close the pipeline and turn the redirect
# into a separate command that just truncates the cache to zero bytes.
lib.removeSuffix "\n" ''
printf '%s' "$(cat "${urlSource}")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
'';
# Defined in every script that touches a cache: the start scripts and the
# update unit.
subscriptionCacheHelpersBlock = ''
SUB_CACHE_DIR="${subscriptionCacheDir}"
RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}"
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
@@ -71,77 +65,122 @@ let
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(cat "$src")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
${subscriptionBackendArg} --tag-prefix "$tag" > "$cache.tmp"; then
_proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"
return
fi
rm -f "$cache.tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
# Every runtime subscription, as "<tag>\t<url file>" lines.
_proxy_suite_runtime_subscriptions() {
local f tag
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
for f in "$RUNTIME_SUBS_DIR"/*.url; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
mkSubscriptionBlock =
sub: routingMark:
# Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per
# start script, so this one is emitted separately from the cache helpers.
mkSubscriptionLoadHelperBlock =
routingMark:
let
cacheFile = mkSubscriptionCacheFile sub;
markFilter = routingMarkJq routingMark;
in
''
# subscription: ${sub.tag}
CACHE_DIR="${subscriptionCacheDir}"
CACHE_FILE="${cacheFile}"
_proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag}
if [ ! -f "$CACHE_FILE" ]; then
mkdir -p "$CACHE_DIR"
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
_proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true
else
rm -f "$CACHE_FILE.tmp"
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
fi
fi
${
subVar = if hybridEnabled then "SUB_SING_BOX_JSON" else "SUB_JSON";
# Plain string concatenation: "$" next to an interpolation is exactly the
# spot where an indented string's escaping bites.
markBlock = lib.optionalString (routingMark != null) (
subVar + "=$(${jq} 'map(.${markFilter})' <<< \"$" + subVar + "\")\n"
);
mergeBlock =
if hybridEnabled then
''
if [ -f "$CACHE_FILE" ]; then
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$CACHE_FILE")
fi
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$cache")
''
else
''
if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi
''
SUB_JSON=$(cat "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
'';
in
''
# $1 tag, $2 file holding the subscription URL. Fetches on a cold cache and
# merges whatever is cached; a subscription that cannot be fetched is a
# warning, never a failed start.
_proxy_suite_load_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" before after
_proxy_suite_drop_invalid_subscription_cache "$cache" "$tag"
if [ ! -f "$cache" ]; then
_proxy_suite_fetch_subscription "$tag" "$src" \
|| echo "proxy-suite: warning: could not fetch subscription '$tag'" >&2
fi
[ -f "$cache" ] || return 0
before=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
${mergeBlock}
after=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_outbound_source "sub:$tag" "$before" "$after"
}
'';
mkSubscriptionBlock =
sub: _routingMark:
''
# subscription: ${sub.tag}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}
'';
runtimeSubscriptionsBlock = ''
# subscriptions added at runtime
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"
done < <(_proxy_suite_runtime_subscriptions)
'';
mkSubscriptionFetchBlock =
sub:
let
cacheFile = mkSubscriptionCacheFile sub;
in
''
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}; then
echo "Updated subscription: ${sub.tag}"
else
rm -f "${cacheFile}.tmp"
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
FAILED=1
fi
'';
runtimeSubscriptionsFetchBlock = ''
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"; then
echo "Updated subscription: $RUNTIME_SUB_TAG"
else
FAILED=1
fi
done < <(_proxy_suite_runtime_subscriptions)
'';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
);
@@ -150,8 +189,11 @@ in
inherit
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionLoadHelperBlock
mkSubscriptionBlock
runtimeSubscriptionsBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
subscriptionTagsFile
;
}
+44 -6
View File
@@ -13,7 +13,6 @@
userControlCfg,
selectionMode,
collapseNamedOutbounds,
hasSubscriptions,
constants,
jq,
python3,
@@ -28,6 +27,7 @@
routeModeRulesFile,
proxyInboundsCfg,
proxyInboundsNeedLocalProxy,
proxyInboundsGuardPrivate,
proxyInboundViaOutbounds,
userControlEnabled,
buildInboundPy,
@@ -42,7 +42,7 @@ let
mainBackend = if pureXrayEnabled then "xray" else "sing-box";
backendArg = "--backend ${mainBackend}";
backendBin = if pureXrayEnabled then xray else singBox;
localProxyAuth = proxyCfg.auth;
localProxyAuth = proxyCfg.listener.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
@@ -54,6 +54,13 @@ let
else
null;
routeModeStateFile = "/run/proxy-suite/route-mode";
inherit (constants)
priorityOutboundFile
runtimeOutboundsDir
runtimeSubscriptionsDir
outboundInventoryFile
;
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
@@ -72,10 +79,10 @@ let
lib
pkgs
proxyCfg
hasSubscriptions
hybridEnabled
mainBackend
backend
runtimeSubscriptionsDir
jq
python3
parserScriptsPythonPath
@@ -86,8 +93,11 @@ let
inherit (subscriptionScripts)
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionLoadHelperBlock
mkSubscriptionBlock
runtimeSubscriptionsBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
subscriptionTagsFile
;
@@ -105,11 +115,15 @@ let
backend
backendArg
xraySidecarRoutingMark
priorityOutboundFile
runtimeOutboundsDir
jq
python3
parserScriptsPythonPath
buildOutboundPy
mkSubscriptionBlock
mkSubscriptionLoadHelperBlock
runtimeSubscriptionsBlock
;
};
inherit (outboundScripts) mkOutboundScript;
@@ -125,8 +139,10 @@ let
backendJqFilter = import ./script-blocks/backend-jq-filter.nix {
inherit
lib
pureXrayEnabled
selectionMode
proxyInboundsGuardPrivate
;
};
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" backendJqFilter;
@@ -186,38 +202,60 @@ let
proxyInboundsFile
proxyInboundsSpecFile
builders
constants
;
};
inherit (proxyInboundsScripts) startInbounds;
inherit (proxyInboundsScripts) startInbounds collectInboundStats;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
controlScripts = import ./control-scripts.nix {
inherit
lib
pkgs
proxyCfg
clashApi
routeModeStateFile
priorityOutboundFile
outboundInventoryFile
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
jq
;
};
inherit (controlScripts)
subscriptionUpdateScript
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
;
in
{
inherit startSocks startTun startPerAppTun startInbounds;
inherit
startSocks
startTun
startPerAppTun
startInbounds
collectInboundStats
;
inherit
proxyInboundsLinksFile
proxyInboundsSubscriptionsFile
routeModeStateFile
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
subscriptionUpdateScript
hasSubscriptions
subscriptionTagsFile
subscriptionCacheDir
runtimeProxychainsConfig
priorityOutboundFile
runtimeOutboundsDir
runtimeSubscriptionsDir
outboundInventoryFile
clashApi
;
}
+52 -2
View File
@@ -32,10 +32,13 @@
let
inherit (constants)
autoProxyStateDir
xrayDnsBridgePorts
xraySidecarBasePorts
;
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
routeModeBlacklistTail =
if pureXrayEnabled then
''
@@ -119,8 +122,8 @@ let
printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg proxyCfg.listenAddress} \
${lib.escapeShellArg (toString proxyCfg.port)} \
${lib.escapeShellArg proxyCfg.listener.address} \
${lib.escapeShellArg (toString proxyCfg.listener.port)} \
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
@@ -139,6 +142,7 @@ let
xrayTunDnsRuntime ? false,
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false,
}:
pkgs.writeShellScript name ''
set -euo pipefail
@@ -190,8 +194,52 @@ let
${mkOutboundScript routingMark}
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
# autoProxy: a loopback listener and a learned rule-set per exit, generated here
# because subscription tags only exist at runtime.
PROBE_INBOUNDS_JSON='[]'
PROBE_PIN_RULES_JSON='[]'
AUTOPROXY_RULE_SETS_JSON='[]'
AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
install -d -m 0750 "$AUTOPROXY_DIR"
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
# direct is always exit 0; state is keyed by tag, so shifting indices are
# harmless.
PROBE_EXITS_JSON=$(${jq} -c \
--argjson max ${toString proxyCfg.autoProxy.maxExits} \
--argjson base ${toString proxyCfg.autoProxy.probeBasePort} \
--arg dir "$AUTOPROXY_DIR" '
(["direct"] + map(select(. != "direct")))[0:$max]
| to_entries
| map({i: .key, tag: .value, port: ($base + .key),
rule_set: ("autoproxy-" + (.key | tostring)),
path: ($dir + "/rs-" + (.key | tostring) + ".json")})
' <<< "$EXIT_TAGS_JSON")
printf '%s\n' "$PROBE_EXITS_JSON" > "$RUNTIME_DIR/probe-exits.json"
# proxy-ctl reads it unprivileged; it holds tags and loopback ports only.
chmod 644 "$RUNTIME_DIR/probe-exits.json"
${autoProxyRender} "$RUNTIME_DIR/probe-exits.json" "$AUTOPROXY_DIR/state.json"
PROBE_INBOUNDS_JSON=$(${jq} -c 'map({type: "mixed", tag: ("probe-in-" + (.i | tostring)),
listen: "127.0.0.1", listen_port: .port})' <<< "$PROBE_EXITS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c 'map({inbound: ["probe-in-" + (.i | tostring)],
outbound: .tag})' <<< "$PROBE_EXITS_JSON")
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c 'map({type: "local", format: "source",
tag: .rule_set, path: .path})' <<< "$PROBE_EXITS_JSON")
# all-bypass means everything direct; learned exits must not override it.
if [ "$ROUTE_MODE" != all-bypass ]; then
AUTOPROXY_RULES_JSON=$(${jq} -c 'map({rule_set: [.rule_set], outbound: .tag})' <<< "$PROBE_EXITS_JSON")
fi
''}
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \
--argjson probe_pin_rules "$PROBE_PIN_RULES_JSON" \
--argjson autoproxy_rule_sets "$AUTOPROXY_RULE_SETS_JSON" \
--argjson autoproxy_rules "$AUTOPROXY_RULES_JSON" \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
@@ -259,6 +307,8 @@ let
enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = xraySidecarBasePorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
};
startTun = mkStartScript {
+66 -13
View File
@@ -11,7 +11,6 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretEnabled,
hasSubscriptions,
sshProxyOutboundEnabled,
sshProxyUnitEnabled,
proxyInboundsEnabled,
@@ -19,6 +18,7 @@
scripts,
perAppRouting,
routingScripts,
geodata,
}:
let
@@ -45,6 +45,7 @@ let
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
inbounds = "proxy-suite-inbounds";
inboundStats = "proxy-suite-inbound-stats";
};
backendDescription =
@@ -56,8 +57,13 @@ let
"sing-box";
localProxyAuthEnabled =
proxyCfg.auth.username != null
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
proxyCfg.listener.auth.username != null
&& (proxyCfg.listener.auth.password != null || proxyCfg.listener.auth.passwordFile != null);
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ];
};
systemServiceEntries = [
{
@@ -65,8 +71,7 @@ let
name = serviceNames.socks;
value = mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
# Only the XRay backend proxies through the OpenSSH unit's listener;
# SingBox dials SSH inside its own process and needs no ordering.
# Only XRay goes through the OpenSSH unit's listener.
after = [
"network-online.target"
]
@@ -79,6 +84,7 @@ let
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
extraServiceConfig = xrayAssetEnv;
};
}
{
@@ -89,9 +95,8 @@ let
after = [
"network-online.target"
]
# Relayed traffic leaves through the client stack's SOCKS listener, so
# start after it. Not `requires`: the listeners should keep serving
# direct-routed traffic even if the client stack is down.
# After the client stack, but not `requires`: direct listeners keep serving
# without it.
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service";
wants = [
"network-online.target"
@@ -100,6 +105,19 @@ let
wantedBy = [ "multi-user.target" ];
execStart = scripts.startInbounds;
runtimeDirectory = serviceNames.inbounds;
extraServiceConfig = xrayAssetEnv;
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = mkOneshotService {
description = "proxy-suite - add up per-user traffic through the inbounds";
after = [ "${serviceNames.inbounds}.service" ];
execStart = scripts.collectInboundStats;
stateDirectory = "proxy-suite";
# Run by a timer: a unit left "active" would never be started again.
extraServiceConfig.RemainAfterExit = false;
};
}
{
@@ -111,7 +129,7 @@ let
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tun}.service"
@@ -128,7 +146,7 @@ let
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
@@ -202,7 +220,8 @@ let
};
}
{
enable = proxyEnabled && hasSubscriptions;
# Not gated on hasSubscriptions: runtime subscriptions need refreshing too.
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
@@ -221,6 +240,26 @@ let
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-select@";
value = mkOneshotService {
description = "Pin the proxy-suite priority outbound to %i";
execStart = "${scripts.setPriorityOutboundScript} %i";
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-reload";
value = mkOneshotService {
description = "Apply proxy-suite outbounds and subscriptions added at runtime";
execStart = scripts.reloadOutboundsScript;
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
];
userServiceEntries = [
@@ -243,17 +282,31 @@ let
timerEntries = [
{
enable = proxyEnabled && hasSubscriptions;
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "5m";
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = {
description = "proxy-suite per-user inbound traffic collection";
wantedBy = [ "timers.target" ];
timerConfig = {
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = "5m";
};
};
}
];
in
{
+3 -3
View File
@@ -7,7 +7,7 @@
let
s = cfg.sshProxy;
destination = if s.user == null then s.host else "${s.user}@${s.host}";
destination = if s.server.user == null then s.server.host else "${s.server.user}@${s.server.host}";
extraArgs = lib.concatMapStrings (arg: " args+=(${lib.escapeShellArg arg})\n") s.extraArgs;
startScript = pkgs.writeShellScript "proxy-suite-ssh-proxy-start" ''
set -euo pipefail
@@ -20,9 +20,9 @@ let
-o ServerAliveCountMax=3
-o ConnectTimeout=10
-o StrictHostKeyChecking=${lib.escapeShellArg s.strictHostKeyChecking}
-D ${lib.escapeShellArg "${s.listenAddress}:${toString s.listenPort}"}
-D ${lib.escapeShellArg "${s.listener.address}:${toString s.listener.port}"}
)
${lib.optionalString (s.sshPort != 22) "args+=(-p ${toString s.sshPort})"}
${lib.optionalString (s.server.port != 22) "args+=(-p ${toString s.server.port})"}
${lib.optionalString (s.identityFile != null) "args+=(-i ${lib.escapeShellArg s.identityFile})"}
${lib.optionalString (
s.knownHostsFile != null
+13 -13
View File
@@ -27,8 +27,8 @@ let
);
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
args=(
--port=${toString t.port}
--host=${lib.escapeShellArg t.host}
--port=${toString t.listener.port}
--host=${lib.escapeShellArg t.listener.address}
)
${
if t.secretFile != null then
@@ -36,12 +36,12 @@ let
else
"args+=(--secret=${lib.escapeShellArg t.secret})"
}
${dcArgs}${mkFlagArg t.verbose "--verbose"}${
mkOptionalValueArg (t.logFile != null) "--log-file" t.logFile
}${lib.optionalString (t.logFile != null) (mkRawValueArg "--log-max-mb" t.logMaxMb)}${
lib.optionalString (t.logFile != null) (mkRawValueArg "--log-backups" t.logBackups)
}${mkRawValueArg "--buf-kb" t.bufKb}${mkRawValueArg "--pool-size" t.poolSize}${mkRepeatedValueArgs "--cfproxy-domain" t.cfProxyDomains}${mkRepeatedValueArgs "--cfproxy-worker-domain" t.cfProxyWorkerDomains}${
mkFlagArg (!t.cfProxyFallback) "--no-cfproxy"
${dcArgs}${mkFlagArg t.log.verbose "--verbose"}${
mkOptionalValueArg (t.log.file != null) "--log-file" t.log.file
}${lib.optionalString (t.log.file != null) (mkRawValueArg "--log-max-mb" t.log.maxSizeMiB)}${
lib.optionalString (t.log.file != null) (mkRawValueArg "--log-backups" t.log.keep)
}${mkRawValueArg "--buf-kb" t.bufferKiB}${mkRawValueArg "--pool-size" t.poolSize}${mkRepeatedValueArgs "--cfproxy-domain" t.cloudflare.domains}${mkRepeatedValueArgs "--cfproxy-worker-domain" t.cloudflare.workerDomains}${
mkFlagArg (!t.cloudflare.fallback) "--no-cfproxy"
}${
mkOptionalValueArg (t.fakeTlsDomain != null) "--fake-tls-domain" t.fakeTlsDomain
}${mkFlagArg t.proxyProtocol "--proxy-protocol"}
@@ -53,8 +53,8 @@ let
add_bypass_rule() {
local family="$1"
while ${ip} "$family" rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
${ip} "$family" rule add pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null || true
while ${ip} "$family" rule del pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null; do :; done
${ip} "$family" rule add pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null || true
}
add_bypass_rule -4
@@ -64,8 +64,8 @@ let
bypassDownScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-down" ''
set +e
while ${ip} -4 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null; do :; done
'';
in
{
@@ -83,7 +83,7 @@ in
// lib.optionalAttrs transparentBypassEnabled {
ExecStartPre = bypassUpScript;
ExecStopPost = bypassDownScript;
SocketMark = toString t.routingMark;
SocketMark = toString t.fwmark;
};
};
}
+1 -1
View File
@@ -13,7 +13,7 @@ let
inherit (builders) mkOneshotService;
zapretCfg = cfg.zapret;
perAppZapretCfg = zapretCfg.perApp;
perAppZapretCfg = cfg.perAppRouting.zapret;
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
);
@@ -70,8 +70,8 @@ let
{
packageName,
pidDir,
configName ? zapretCfg.configName,
gameFilter ? zapretCfg.gameFilter,
configName ? zapretCfg.zapret-discord-youtube.configName,
gameFilter ? zapretCfg.zapret-discord-youtube.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
+24 -24
View File
@@ -8,10 +8,10 @@
let
zapretCfg = cfg.zapret;
perAppZapretCfg = zapretCfg.perApp;
perAppZapretCfg = cfg.perAppRouting.zapret;
tunInterfaces = lib.unique (
lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface
++ lib.optional (cfg.proxy.enable && cfg.proxy.tun.perApp.enable) cfg.proxy.tun.perApp.interface
++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface
);
zapretDomainGroups = import ../zapret-domain-groups.nix { inherit lib zapret; };
@@ -44,8 +44,8 @@ let
ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule;
protocols = zapretDomainGroups.effectiveRuleProtocolFamilies rule;
}
) zapretCfg.hostlistRules;
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
) zapretCfg.zapret-discord-youtube.hostlistRules;
hostlistRuleNames = map (rule: rule.name) zapretCfg.zapret-discord-youtube.hostlistRules;
baseZapretPackage =
let
@@ -57,14 +57,14 @@ let
fileName: entries:
if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.zapret-discord-youtube.domains;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.zapret-discord-youtube.excludeDomains;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.zapret-discord-youtube.ips;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.zapret-discord-youtube.excludeIps;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
includeExtraUpstreamLists = zapretCfg.zapret-discord-youtube.includeExtraUpstreamLists;
entries = map (rule: {
inherit (rule)
name
@@ -80,7 +80,7 @@ let
}
);
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.zapret-discord-youtube.configName;
patchConfigScriptSrc = builtins.path {
path = ../../../scripts/patch-zapret-config.py;
name = "patch-zapret-config.py";
@@ -110,7 +110,7 @@ let
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = zapretCfg.gameFilter;
gameFilter = zapretCfg.zapret-discord-youtube.gameFilter;
forceDisableFilterMark = true;
customScript =
if perAppZapretCfg.enable || tunInterfaces != [ ] then
@@ -150,15 +150,15 @@ let
assertions = [
{
assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames);
message = "proxy-suite: zapret.hostlistRules names must be unique";
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules names must be unique";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule != [ ]
|| zapretDomainGroups.effectiveRuleIps rule != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps";
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: each zapret.zapret-discord-youtube.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps";
}
{
assertion = builtins.all (
@@ -168,8 +168,8 @@ let
|| rule.ips != [ ]
|| rule.defaultIps != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source";
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: each zapret.zapret-discord-youtube.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source";
}
{
assertion = builtins.all (
@@ -178,20 +178,20 @@ let
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs";
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.preset != null || builtins.length rule.defaultDomains <= 1
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset";
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset";
}
{
assertion = builtins.all (
rule: !(rule.configName != null && rule.nfqwsArgs != [ ])
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName cannot be used together with nfqwsArgs";
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules.*.configName cannot be used together with nfqwsArgs";
}
{
assertion = builtins.all (
@@ -201,8 +201,8 @@ let
|| rule.defaultDomains != [ ]
|| rule.ips != [ ]
|| rule.defaultIps != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps";
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps";
}
];
in
+131
View File
@@ -0,0 +1,131 @@
# zapret2 (nfqws2) services, under the zapret v1 unit and table names.
{
lib,
pkgs,
cfg,
packages,
perAppZapretRulesFile,
nft,
}:
let
builders = import ./service/builders.nix { inherit lib pkgs; };
inherit (builders) mkOneshotService;
zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret;
inherit (import ./derived.nix { inherit lib cfg; }) constants;
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
);
runtime = import ./zapret2/runtime.nix {
inherit
lib
pkgs
cfg
packages
;
};
tunInterfaces = lib.unique (
lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface
++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface
);
globalRuntime = runtime.mkRuntime {
name = "proxy-suite-zapret2";
qnum = constants.zapretGlobalQnum.zapret2;
desyncMark = 1073741824; # 0x40000000
desyncMarkPostnat = 536870912; # 0x20000000
nftTable = "zapret2";
modeFilter = if zapretCfg.zapret2.autoHostlist.enable then "autohostlist" else "hostlist";
customScript =
let
exemptCidrs = lib.optionals zapretCfg.cidrExemption.enable zapretCfg.cidrExemption.cidrs;
in
if perAppZapretCfg.enable || tunInterfaces != [ ] || exemptCidrs != [ ] then
runtime.mkCustomScript {
inherit tunInterfaces exemptCidrs;
excludeMark = if perAppZapretCfg.enable then perAppZapretCfg.filterMark else null;
}
else
null;
};
# Wrapped apps opted in: MODE_FILTER=none applies every profile to all their traffic.
perAppRuntime = runtime.mkRuntime {
name = "proxy-suite-per-app-zapret2";
qnum = perAppZapretCfg.qnum;
desyncMark = 134217728; # 0x8000000
desyncMarkPostnat = 67108864; # 0x4000000
filterMark = perAppZapretCfg.filterMark;
nftTable = "proxy_suite_per_app_zapret";
modeFilter = "none";
customScript =
if tunInterfaces != [ ] then runtime.mkCustomScript { inherit tunInterfaces; } else null;
};
# nfqws2 and proxy-ctl expect the list files to exist.
mkPreStart = ''
${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true
install -d -m 0755 ${runtime.stateDir}
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
'';
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret2-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
${nft} -f ${perAppZapretRulesFile}
'';
perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-per-app-zapret2-mark-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
'';
in
{
environment.systemPackages = lib.mkBefore [ runtime.package ];
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
});
}
+232
View File
@@ -0,0 +1,232 @@
# Per-instance zapret2 runtime: a generated config and custom.d hook, no package copy.
{
lib,
pkgs,
cfg,
packages,
}:
let
zapret2Cfg = cfg.zapret.zapret2;
autoCfg = zapret2Cfg.autoHostlist;
package = packages.zapret2;
zapretBase = "${package}/opt/zapret2";
# Shared by both instances: what the global one learns applies per-app too.
inherit (import ../derived.nix { inherit lib cfg; }) constants;
stateDir = constants.zapret2StateDir;
autoHostlistFile = "${stateDir}/zapret-hosts-auto.txt";
userHostlistFile = "${stateDir}/zapret-hosts-user.txt";
excludeHostlistFile = "${stateDir}/zapret-hosts-user-exclude.txt";
runtimeDeps = lib.attrValues {
inherit (pkgs)
coreutils
findutils
gawk
gnugrep
gnused
iproute2
iptables
ipset
kmod
nftables
procps
util-linux
;
};
toHex = value: "0x" + lib.toHexString value;
blobPath = file: if lib.hasPrefix "/" file then file else "${zapretBase}/files/fake/${file}";
blobArgs = lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs;
hostlistMarkers = [
"<HOSTLIST>"
"<HOSTLIST_NOAUTO>"
];
# Static domain filters join every profile that uses a hostlist marker.
staticListArgs =
lib.optional (
zapret2Cfg.domains != [ ]
) "--hostlist-domains=${lib.concatStringsSep "," zapret2Cfg.domains}"
++ lib.optional (
zapret2Cfg.excludeDomains != [ ]
) "--hostlist-exclude-domains=${lib.concatStringsSep "," zapret2Cfg.excludeDomains}";
renderProfile =
profile:
let
suffix = lib.concatMapStrings (arg: " " + arg) staticListArgs;
in
lib.replaceStrings hostlistMarkers (map (marker: marker + suffix) hostlistMarkers) (
lib.trim profile
);
nfqwsOpt = lib.concatStringsSep " " (
blobArgs ++ [ (lib.concatStringsSep " --new " (map renderProfile zapret2Cfg.profiles)) ]
);
# The NFQUEUE window must exceed the retransmission threshold it counts.
packetWindow = {
tcpOut = 6 + autoCfg.retransThreshold;
tcpIn = 15;
udpOut = 6 + autoCfg.retransThreshold;
udpIn = 3;
};
mkConfig =
{
qnum,
desyncMark,
desyncMarkPostnat,
nftTable,
filterMark ? null,
modeFilter,
}:
pkgs.writeText "proxy-suite-zapret2-config" (
lib.concatStringsSep "\n" (
[
"# Generated by proxy-suite. Do not edit."
"WS_USER=root"
"FWTYPE=nftables"
"INIT_APPLY_FW=1"
"QNUM=${toString qnum}"
"DESYNC_MARK=${toHex desyncMark}"
"DESYNC_MARK_POSTNAT=${toHex desyncMarkPostnat}"
"ZAPRET_NFT_TABLE=${nftTable}"
]
++ lib.optional (filterMark != null) "FILTER_MARK=${toHex filterMark}"
++ lib.optional (!zapret2Cfg.ipv6) "DISABLE_IPV6=1"
++ [
"NFQWS2_ENABLE=1"
"NFQWS2_PORTS_TCP=${zapret2Cfg.ports.tcp}"
"NFQWS2_PORTS_UDP=${zapret2Cfg.ports.udp}"
"NFQWS2_TCP_PKT_OUT=${toString packetWindow.tcpOut}"
"NFQWS2_TCP_PKT_IN=${toString packetWindow.tcpIn}"
"NFQWS2_UDP_PKT_OUT=${toString packetWindow.udpOut}"
"NFQWS2_UDP_PKT_IN=${toString packetWindow.udpIn}"
"MODE_FILTER=${modeFilter}"
"AUTOHOSTLIST_FAIL_THRESHOLD=${toString autoCfg.failThreshold}"
"AUTOHOSTLIST_FAIL_TIME=${toString autoCfg.failTime}"
"AUTOHOSTLIST_RETRANS_THRESHOLD=${toString autoCfg.retransThreshold}"
"AUTOHOSTLIST_RETRANS_RESET=${if autoCfg.retransReset then "1" else "0"}"
"AUTOHOSTLIST_RETRANS_MAXSEQ=${toString autoCfg.retransMaxseq}"
"AUTOHOSTLIST_INCOMING_MAXSEQ=${toString autoCfg.incomingMaxseq}"
"AUTOHOSTLIST_UDP_OUT=${toString autoCfg.udpOut}"
"AUTOHOSTLIST_UDP_IN=${toString autoCfg.udpIn}"
"AUTOHOSTLIST_DEBUGLOG=${if autoCfg.debugLog then "1" else "0"}"
"NFQWS2_OPT=${lib.escapeShellArg nfqwsOpt}"
""
]
)
);
# Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app
# traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break).
mkCustomScript =
{
tunInterfaces ? [ ],
excludeMark ? null,
exemptCidrs ? [ ],
}:
let
chains = [
{
name = "postrouting";
direction = "oifname";
ipMatch = "daddr";
}
{
name = "postnat";
direction = "oifname";
ipMatch = "daddr";
}
{
name = "prerouting";
direction = "iifname";
ipMatch = "saddr";
}
{
name = "prenat";
direction = "iifname";
ipMatch = "saddr";
}
];
nftFamily = cidr: if lib.hasInfix ":" cidr then "ip6" else "ip";
mkRule =
chain: match: comment:
" nft insert rule inet $ZAPRET_NFT_TABLE ${chain} ${match} return comment '\"${comment}\"'";
rules = lib.concatMap (
chain:
lib.optional (excludeMark != null) (
mkRule chain.name "mark and ${toHex excludeMark} != 0" "proxy-suite per-app-zapret bypass"
)
++ map (
interface: mkRule chain.name "${chain.direction} '\"${interface}\"'" "proxy-suite TUN bypass"
) tunInterfaces
++ map (
cidr:
mkRule chain.name "${nftFamily cidr} ${chain.ipMatch} ${cidr}" "proxy-suite CIDR exemption"
) exemptCidrs
) chains;
in
pkgs.writeText "proxy-suite-zapret2-custom.sh" (
lib.concatStringsSep "\n" (
[ "zapret_custom_firewall_nft() {" ]
++ rules
++ [
" return 0"
"}"
""
]
)
);
mkRuntime =
{
name,
customScript ? null,
...
}@args:
pkgs.runCommand name { } ''
mkdir -p "$out/init.d/sysv/custom.d"
cp ${
mkConfig (
builtins.removeAttrs args [
"name"
"customScript"
]
)
} "$out/config"
${lib.optionalString (customScript != null) ''
cp ${customScript} "$out/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
mkEnv =
{ runtime, pidDir }:
[
"ZAPRET_BASE=${zapretBase}"
"ZAPRET_RW=${runtime}"
"HOSTLIST_BASE=${stateDir}"
"PIDDIR=${pidDir}"
"PATH=${lib.makeBinPath runtimeDeps}"
];
in
{
inherit
package
stateDir
autoHostlistFile
userHostlistFile
excludeHostlistFile
mkCustomScript
mkRuntime
mkEnv
;
initScript = "${zapretBase}/init.d/sysv/zapret2";
}
+4 -6
View File
@@ -127,7 +127,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
@@ -137,10 +137,8 @@ let
tun.enable = true;
tproxy.enable = true;
};
zapret = {
enable = true;
perApp.enable = true;
};
zapret.enable = true;
perAppRouting.zapret.enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
@@ -329,7 +327,7 @@ in
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
+7 -7
View File
@@ -33,7 +33,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
@@ -58,7 +58,7 @@ let
ruDisabledFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.routing.enableRuDirect = false;
services.proxy-suite.proxy.routing.directRu = false;
}
];
ruDisabledRules = mkRoutingRules ruDisabledFixture;
@@ -68,7 +68,7 @@ let
baseModule
{
services.proxy-suite.proxy.routing = {
enableRuDirect = false;
directRu = false;
direct.geosites = [ "category-ru" ];
};
}
@@ -99,7 +99,7 @@ let
proxyDirectConfig = mkTProxyConfig (evalProxySuite [
baseModule
{
services.proxy-suite.proxy.proxyByDefault = false;
services.proxy-suite.proxy.routing.default = "direct";
}
]);
@@ -110,7 +110,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "test-proxy";
@@ -121,8 +121,8 @@ let
urlTest = {
url = "https://telegram.org";
interval = "1m";
tolerance = 100;
};
singBox.urlTest.tolerance = 100;
};
};
}
@@ -146,7 +146,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
};
};
}
+1 -1
View File
@@ -43,7 +43,7 @@
in
assert cfg.url == "https://www.gstatic.com/generate_204";
assert cfg.interval == "3m";
assert minimal.config.services.proxy-suite.proxy.singBox.urlTest.tolerance == 50;
assert minimal.config.services.proxy-suite.proxy.urlTest.tolerance == 50;
true
)
+2 -2
View File
@@ -41,7 +41,7 @@ in
true
)
(
assert tproxyManualFixture.config.services.proxy-suite.proxy.tproxy.autostart == false;
assert tproxyManualFixture.config.services.proxy-suite.proxy.autostart == null;
assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ];
true
)
@@ -60,7 +60,7 @@ in
true
)
(
assert tunManualFixture.config.services.proxy-suite.proxy.tun.autostart == false;
assert tunManualFixture.config.services.proxy-suite.proxy.autostart == null;
assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ];
true
)
+8 -22
View File
@@ -17,7 +17,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
tproxy.enable = true;
outbounds = [
{
@@ -44,9 +44,9 @@ let
tproxyAutostartFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.tproxy = {
enable = true;
autostart = true;
services.proxy-suite.proxy = {
tproxy.enable = true;
autostart = "tproxy";
};
}
];
@@ -61,29 +61,15 @@ let
tunAutostartFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.tun = {
enable = true;
autostart = true;
services.proxy-suite.proxy = {
tun.enable = true;
autostart = "tun";
};
}
];
invalidGlobalProxyModeAssertions = mkFailingAssertions mkBadFixture [
# TUN and TProxy cannot both autostart globally.
[
{
services.proxy-suite.proxy = {
tproxy = {
enable = true;
autostart = true;
};
tun = {
enable = true;
autostart = true;
};
};
}
]
# TUN and TProxy can no longer both autostart: proxy.autostart holds one mode.
# Transparent proxy backends require proxy.enable.
[
+2 -2
View File
@@ -10,6 +10,7 @@
let
fixtures = import ./hybrid-backend/fixtures.nix {
inherit
pkgs
evalProxySuite
mkTProxyConfig
mkTunConfig
@@ -54,8 +55,7 @@ in
) hybridTproxyConfig.route.rules
);
in
assert hybridFixture.config.services.proxy-suite.proxy.singBox.enable;
assert hybridFixture.config.services.proxy-suite.proxy.xray.enable;
assert hybridFixture.config.services.proxy-suite.proxy.backend == "hybrid";
assert hybridTproxyConfig ? route;
assert !(hybridTproxyConfig ? routing);
assert dnsBridgeInbound.type == "direct";
+7 -7
View File
@@ -1,4 +1,5 @@
{
pkgs,
evalProxySuite,
mkTProxyConfig,
mkTunConfig,
@@ -14,8 +15,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
xray.enable = true;
backend = "hybrid";
selection = "selector";
outbounds = [
{
@@ -29,8 +29,8 @@ let
];
tproxy.enable = true;
tun.enable = true;
tun.perApp.enable = true;
};
perAppRouting.tun.enable = true;
};
};
hybridFixture = evalProxySuite [ hybridModule ];
@@ -48,6 +48,8 @@ let
hybridBackendJqFilter =
import ../../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix
{
lib = pkgs.lib;
proxyInboundsGuardPrivate = false;
pureXrayEnabled = false;
selectionMode = hybridFixture.config.services.proxy-suite.proxy.selection;
};
@@ -59,8 +61,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
xray.enable = true;
backend = "hybrid";
outbounds = [
{
tag = "raw-xray";
@@ -85,8 +86,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
xray.enable = true;
backend = "hybrid";
subscriptions = [
{
tag = "community";
+2 -2
View File
@@ -166,7 +166,7 @@ let
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
@@ -214,7 +214,7 @@ let
script = wrapper + "\n" + metadata.script;
profiles = builtins.fromJSON (generated.readDerivation metadata.perAppRoutingProfilesFile);
subscriptionTags = builtins.fromJSON (generated.readDerivation metadata.subscriptionTagsFile);
inherit (metadata) proxychainsConfigFile;
inherit (metadata) proxychainsConfigFile wrapperEnv;
awgProfiles = builtins.fromJSON (generated.readDerivation metadata.amneziaWgProfileNamesFile);
};
in
+7 -5
View File
@@ -15,7 +15,7 @@ let
localProxyAuthFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.auth = {
services.proxy-suite.proxy.listener.auth = {
username = "local-user";
password = "local-pass";
};
@@ -27,7 +27,9 @@ let
localProxyAuthBackendJqFilter =
import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix
{
lib = pkgs.lib;
pureXrayEnabled = false;
proxyInboundsGuardPrivate = false;
selectionMode = localProxyAuthFixture.config.services.proxy-suite.proxy.selection;
};
@@ -35,7 +37,7 @@ let
baseModule
{
services.proxy-suite = {
proxy.auth = {
proxy.listener.auth = {
username = "local-user";
passwordFile = "/run/secrets/local-proxy-password";
};
@@ -62,16 +64,16 @@ let
invalidLocalProxyAuthAssertions = mkFailingAssertions mkBadFixture [
# Auth requires both username and a password source.
[
{ services.proxy-suite.proxy.auth.username = "local-user"; }
{ services.proxy-suite.proxy.listener.auth.username = "local-user"; }
]
[
{ services.proxy-suite.proxy.auth.password = "local-pass"; }
{ services.proxy-suite.proxy.listener.auth.password = "local-pass"; }
]
# Inline password and passwordFile are mutually exclusive.
[
{
services.proxy-suite.proxy.auth = {
services.proxy-suite.proxy.listener.auth = {
username = "local-user";
password = "local-pass";
passwordFile = "/run/secrets/local-proxy-password";
+14 -1
View File
@@ -186,6 +186,17 @@ let
;
};
zapret2Checks = import ./zapret2.nix {
inherit
pkgs
evalProxySuite
baseModule
mkProxyCtlDerived
mkBadFixture
mkFailingAssertions
;
};
tgWsProxyChecks = import ./tg-ws-proxy.nix {
inherit
pkgs
@@ -220,7 +231,7 @@ let
validated = builtins.all (x: x) (
[
(
assert minimal.config.services.proxy-suite.proxy.listenAddress == "127.0.0.1";
assert minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1";
true
)
]
@@ -233,6 +244,7 @@ let
++ outboundValidationChecks.assertions
++ amneziaWgChecks.assertions
++ zapretChecks.assertions
++ zapret2Checks.assertions
++ globalProxyModeChecks.assertions
++ trayChecks.assertions
++ subscriptionChecks.assertions
@@ -246,4 +258,5 @@ in
xray-jq-filter-runtime = xrayBackendChecks.runtime;
per-app-zapret-runtime = perAppRoutingChecks.runtime;
zapret-hostlist-rules = zapretChecks.rules;
zapret2-config = zapret2Checks.runtime;
}
+3 -3
View File
@@ -10,7 +10,7 @@
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "dup";
@@ -29,7 +29,7 @@
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "proxy";
@@ -44,7 +44,7 @@
enable = true;
proxy = {
enable = true;
singBox.enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
+9 -13
View File
@@ -50,18 +50,14 @@ let
baseModule
{
services.proxy-suite = {
proxy = {
tun.perApp.enable = true;
tproxy.perApp.enable = true;
};
zapret = {
enable = true;
perApp.enable = true;
};
zapret.enable = true;
perAppRouting = {
enable = true;
createDefaultProfiles = false;
proxychains.enable = true;
tun.enable = true;
tproxy.enable = true;
zapret.enable = true;
};
};
}
@@ -102,12 +98,12 @@ in
# -- perAppRouting: proxy-ctl script embeds wrap/apps commands --
(
assert pkgs.lib.hasInfix "help)" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "show this help message" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "enable/disable the proxy backend stack" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "restart active global proxy-suite services"
assert pkgs.lib.hasInfix "help | -h | --help)" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "Usage: proxy-ctl <group>" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "local proxy backend" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "restart active services"
perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "wrap <profile> -- <cmd>" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "apps run <profile> -- <cmd>" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript;
true
)
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more