diff --git a/.github/workflows/dependency-updates.yml b/.github/workflows/dependency-updates.yml index da7138b..f55552f 100644 --- a/.github/workflows/dependency-updates.yml +++ b/.github/workflows/dependency-updates.yml @@ -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' diff --git a/README.md b/README.md index 4bd7722..cb77201 100644 --- a/README.md +++ b/README.md @@ -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 -- `, 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 -- ` 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. - ```text -Usage: proxy-ctl [args] +Usage: proxy-ctl [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 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 switch to a specific outbound (selector mode) - apps list configured per-app routing profiles - wrap -- 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 [user] print the client share link for an inbound - inbounds qr [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 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 add an outbound at runtime + proxy outbounds rm remove a runtime outbound + proxy select [|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 add a subscription at runtime + proxy subs rm 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 [/path] [--json] [--exits a,b | --via tag] + find an exit that reaches a domain + proxy auto learn 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 + 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 | off [profile] | restart [profile] + + ssh [status|on|off] SSH SOCKS5 tunnel + + apps [list] per-app routing profiles + apps run -- [args] run a command through a profile + + inbounds [list] server inbounds + inbounds link [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) ``` diff --git a/docs/options.md b/docs/options.md deleted file mode 100644 index 6c87b53..0000000 --- a/docs/options.md +++ /dev/null @@ -1,9592 +0,0 @@ -# proxy-suite options - -This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options/default.nix`](/modules/proxy-suite/options/default.nix). -Update module option docs there instead of editing this file by hand. - -## Table of contents - -- Config samples - - [Complete default config](#complete-default-config) - - [Complete example config](#complete-example-config) -- services.proxy-suite - - [enable](#services-proxy-suite-enable) - - amneziaWg - - [enable](#services-proxy-suite-amneziawg-enable) - - [kernelModulePackage](#services-proxy-suite-amneziawg-kernelmodulepackage) - - [profiles](#services-proxy-suite-amneziawg-profiles) - - `` - - [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) - - 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) - - proxy - - [enable](#services-proxy-suite-proxy-enable) - - auth - - [password](#services-proxy-suite-proxy-auth-password) - - [passwordFile](#services-proxy-suite-proxy-auth-passwordfile) - - [username](#services-proxy-suite-proxy-auth-username) - - dns - - [local](#services-proxy-suite-proxy-dns-local) - - [address](#services-proxy-suite-proxy-dns-local-address) - - [port](#services-proxy-suite-proxy-dns-local-port) - - [type](#services-proxy-suite-proxy-dns-local-type) - - [remote](#services-proxy-suite-proxy-dns-remote) - - [address](#services-proxy-suite-proxy-dns-remote-address) - - [port](#services-proxy-suite-proxy-dns-remote-port) - - [type](#services-proxy-suite-proxy-dns-remote-type) - - [listenAddress](#services-proxy-suite-proxy-listenaddress) - - [outbounds](#services-proxy-suite-proxy-outbounds) - - item - - [backend](#services-proxy-suite-proxy-outbounds-backend) - - routing - - [domains](#services-proxy-suite-proxy-outbounds-routing-domains) - - [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips) - - [geosites](#services-proxy-suite-proxy-outbounds-routing-geosites) - - [ips](#services-proxy-suite-proxy-outbounds-routing-ips) - - [singBoxJson](#services-proxy-suite-proxy-outbounds-singboxjson) - - [tag](#services-proxy-suite-proxy-outbounds-tag) - - [url](#services-proxy-suite-proxy-outbounds-url) - - [urlFile](#services-proxy-suite-proxy-outbounds-urlfile) - - [xrayJson](#services-proxy-suite-proxy-outbounds-xrayjson) - - [port](#services-proxy-suite-proxy-port) - - [proxyByDefault](#services-proxy-suite-proxy-proxybydefault) - - routing - - [enableRuDirect](#services-proxy-suite-proxy-routing-enablerudirect) - - block - - [domains](#services-proxy-suite-proxy-routing-block-domains) - - [geoips](#services-proxy-suite-proxy-routing-block-geoips) - - [geosites](#services-proxy-suite-proxy-routing-block-geosites) - - [ips](#services-proxy-suite-proxy-routing-block-ips) - - direct - - [domains](#services-proxy-suite-proxy-routing-direct-domains) - - [geoips](#services-proxy-suite-proxy-routing-direct-geoips) - - [geosites](#services-proxy-suite-proxy-routing-direct-geosites) - - [ips](#services-proxy-suite-proxy-routing-direct-ips) - - proxy - - [domains](#services-proxy-suite-proxy-routing-proxy-domains) - - [geoips](#services-proxy-suite-proxy-routing-proxy-geoips) - - [geosites](#services-proxy-suite-proxy-routing-proxy-geosites) - - [ips](#services-proxy-suite-proxy-routing-proxy-ips) - - [rules](#services-proxy-suite-proxy-routing-rules) - - item - - [domains](#services-proxy-suite-proxy-routing-rules-domains) - - [geoips](#services-proxy-suite-proxy-routing-rules-geoips) - - [geosites](#services-proxy-suite-proxy-routing-rules-geosites) - - [ips](#services-proxy-suite-proxy-routing-rules-ips) - - [outbound](#services-proxy-suite-proxy-routing-rules-outbound) - - [selection](#services-proxy-suite-proxy-selection) - - singBox - - [enable](#services-proxy-suite-proxy-singbox-enable) - - [package](#services-proxy-suite-proxy-singbox-package) - - [clashApiPort](#services-proxy-suite-proxy-singbox-clashapiport) - - urlTest - - [tolerance](#services-proxy-suite-proxy-singbox-urltest-tolerance) - - [subscriptionUpdateInterval](#services-proxy-suite-proxy-subscriptionupdateinterval) - - [subscriptions](#services-proxy-suite-proxy-subscriptions) - - item - - [tag](#services-proxy-suite-proxy-subscriptions-tag) - - [url](#services-proxy-suite-proxy-subscriptions-url) - - [urlFile](#services-proxy-suite-proxy-subscriptions-urlfile) - - tproxy - - [enable](#services-proxy-suite-proxy-tproxy-enable) - - [autostart](#services-proxy-suite-proxy-tproxy-autostart) - - [fwmark](#services-proxy-suite-proxy-tproxy-fwmark) - - [localSubnets](#services-proxy-suite-proxy-tproxy-localsubnets) - - perApp - - [enable](#services-proxy-suite-proxy-tproxy-perapp-enable) - - [fwmark](#services-proxy-suite-proxy-tproxy-perapp-fwmark) - - [localSubnets](#services-proxy-suite-proxy-tproxy-perapp-localsubnets) - - [routeTable](#services-proxy-suite-proxy-tproxy-perapp-routetable) - - [port](#services-proxy-suite-proxy-tproxy-port) - - [proxyMark](#services-proxy-suite-proxy-tproxy-proxymark) - - [routeTable](#services-proxy-suite-proxy-tproxy-routetable) - - tun - - [enable](#services-proxy-suite-proxy-tun-enable) - - [address](#services-proxy-suite-proxy-tun-address) - - [autostart](#services-proxy-suite-proxy-tun-autostart) - - [interface](#services-proxy-suite-proxy-tun-interface) - - [mtu](#services-proxy-suite-proxy-tun-mtu) - - perApp - - [enable](#services-proxy-suite-proxy-tun-perapp-enable) - - [address](#services-proxy-suite-proxy-tun-perapp-address) - - [fwmark](#services-proxy-suite-proxy-tun-perapp-fwmark) - - [interface](#services-proxy-suite-proxy-tun-perapp-interface) - - [localSubnets](#services-proxy-suite-proxy-tun-perapp-localsubnets) - - [mtu](#services-proxy-suite-proxy-tun-perapp-mtu) - - [routeTable](#services-proxy-suite-proxy-tun-perapp-routetable) - - urlTest - - [interval](#services-proxy-suite-proxy-urltest-interval) - - [url](#services-proxy-suite-proxy-urltest-url) - - xray - - [enable](#services-proxy-suite-proxy-xray-enable) - - [package](#services-proxy-suite-proxy-xray-package) - - proxyInbounds - - [enable](#services-proxy-suite-proxyinbounds-enable) - - [package](#services-proxy-suite-proxyinbounds-package) - - [blockPrivate](#services-proxy-suite-proxyinbounds-blockprivate) - - [blockRu](#services-proxy-suite-proxyinbounds-blockru) - - [listeners](#services-proxy-suite-proxyinbounds-listeners) - - `` - - [flow](#services-proxy-suite-proxyinbounds-listeners-name-flow) - - [jsonFile](#services-proxy-suite-proxyinbounds-listeners-name-jsonfile) - - [listenAddress](#services-proxy-suite-proxyinbounds-listeners-name-listenaddress) - - [method](#services-proxy-suite-proxyinbounds-listeners-name-method) - - [port](#services-proxy-suite-proxyinbounds-listeners-name-port) - - [reality](#services-proxy-suite-proxyinbounds-listeners-name-reality) - - [enable](#services-proxy-suite-proxyinbounds-listeners-name-reality-enable) - - [dest](#services-proxy-suite-proxyinbounds-listeners-name-reality-dest) - - [privateKey](#services-proxy-suite-proxyinbounds-listeners-name-reality-privatekey) - - [privateKeyFile](#services-proxy-suite-proxyinbounds-listeners-name-reality-privatekeyfile) - - [publicKey](#services-proxy-suite-proxyinbounds-listeners-name-reality-publickey) - - [serverNames](#services-proxy-suite-proxyinbounds-listeners-name-reality-servernames) - - [shortIds](#services-proxy-suite-proxyinbounds-listeners-name-reality-shortids) - - [tls](#services-proxy-suite-proxyinbounds-listeners-name-tls) - - [enable](#services-proxy-suite-proxyinbounds-listeners-name-tls-enable) - - [certificateFile](#services-proxy-suite-proxyinbounds-listeners-name-tls-certificatefile) - - [keyFile](#services-proxy-suite-proxyinbounds-listeners-name-tls-keyfile) - - [serverName](#services-proxy-suite-proxyinbounds-listeners-name-tls-servername) - - [transport](#services-proxy-suite-proxyinbounds-listeners-name-transport) - - [host](#services-proxy-suite-proxyinbounds-listeners-name-transport-host) - - [path](#services-proxy-suite-proxyinbounds-listeners-name-transport-path) - - [serviceName](#services-proxy-suite-proxyinbounds-listeners-name-transport-servicename) - - [type](#services-proxy-suite-proxyinbounds-listeners-name-transport-type) - - [type](#services-proxy-suite-proxyinbounds-listeners-name-type) - - [users](#services-proxy-suite-proxyinbounds-listeners-name-users) - - item - - [name](#services-proxy-suite-proxyinbounds-listeners-name-users-name) - - [password](#services-proxy-suite-proxyinbounds-listeners-name-users-password) - - [passwordFile](#services-proxy-suite-proxyinbounds-listeners-name-users-passwordfile) - - [uuid](#services-proxy-suite-proxyinbounds-listeners-name-users-uuid) - - [uuidFile](#services-proxy-suite-proxyinbounds-listeners-name-users-uuidfile) - - [via](#services-proxy-suite-proxyinbounds-listeners-name-via) - - [xrayJson](#services-proxy-suite-proxyinbounds-listeners-name-xrayjson) - - [openFirewall](#services-proxy-suite-proxyinbounds-openfirewall) - - [serverAddress](#services-proxy-suite-proxyinbounds-serveraddress) - - [shareLinks](#services-proxy-suite-proxyinbounds-sharelinks) - - [via](#services-proxy-suite-proxyinbounds-via) - - [zapretDirect](#services-proxy-suite-proxyinbounds-zapretdirect) - - 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) - - [host](#services-proxy-suite-sshproxy-host) - - [hostKey](#services-proxy-suite-sshproxy-hostkey) - - [hostKeyFile](#services-proxy-suite-sshproxy-hostkeyfile) - - [identityFile](#services-proxy-suite-sshproxy-identityfile) - - [knownHostsFile](#services-proxy-suite-sshproxy-knownhostsfile) - - [listenAddress](#services-proxy-suite-sshproxy-listenaddress) - - [listenPort](#services-proxy-suite-sshproxy-listenport) - - [serviceUser](#services-proxy-suite-sshproxy-serviceuser) - - [sshPort](#services-proxy-suite-sshproxy-sshport) - - [strictHostKeyChecking](#services-proxy-suite-sshproxy-stricthostkeychecking) - - [user](#services-proxy-suite-sshproxy-user) - - tgWsProxy - - [enable](#services-proxy-suite-tgwsproxy-enable) - - [bufKb](#services-proxy-suite-tgwsproxy-bufkb) - - [bypassTransparentProxy](#services-proxy-suite-tgwsproxy-bypasstransparentproxy) - - [cfProxyDomains](#services-proxy-suite-tgwsproxy-cfproxydomains) - - [cfProxyFallback](#services-proxy-suite-tgwsproxy-cfproxyfallback) - - [cfProxyWorkerDomains](#services-proxy-suite-tgwsproxy-cfproxyworkerdomains) - - [dcIps](#services-proxy-suite-tgwsproxy-dcips) - - [fakeTlsDomain](#services-proxy-suite-tgwsproxy-faketlsdomain) - - [host](#services-proxy-suite-tgwsproxy-host) - - [logBackups](#services-proxy-suite-tgwsproxy-logbackups) - - [logFile](#services-proxy-suite-tgwsproxy-logfile) - - [logMaxMb](#services-proxy-suite-tgwsproxy-logmaxmb) - - [poolSize](#services-proxy-suite-tgwsproxy-poolsize) - - [port](#services-proxy-suite-tgwsproxy-port) - - [proxyProtocol](#services-proxy-suite-tgwsproxy-proxyprotocol) - - [routingMark](#services-proxy-suite-tgwsproxy-routingmark) - - [secret](#services-proxy-suite-tgwsproxy-secret) - - [secretFile](#services-proxy-suite-tgwsproxy-secretfile) - - [verbose](#services-proxy-suite-tgwsproxy-verbose) - - tray - - [enable](#services-proxy-suite-tray-enable) - - [autostart](#services-proxy-suite-tray-autostart) - - [pollInterval](#services-proxy-suite-tray-pollinterval) - - userControl - - global - - [enable](#services-proxy-suite-usercontrol-global-enable) - - [group](#services-proxy-suite-usercontrol-group) - - perApp - - [enable](#services-proxy-suite-usercontrol-perapp-enable) - - zapret - - [enable](#services-proxy-suite-zapret-enable) - - cidrExemption - - [enable](#services-proxy-suite-zapret-cidrexemption-enable) - - [cidrs](#services-proxy-suite-zapret-cidrexemption-cidrs) - - [configName](#services-proxy-suite-zapret-configname) - - [gameFilter](#services-proxy-suite-zapret-gamefilter) - - [hostlistRules](#services-proxy-suite-zapret-hostlistrules) - - item - - [enableDirectSync](#services-proxy-suite-zapret-hostlistrules-enabledirectsync) - - [configName](#services-proxy-suite-zapret-hostlistrules-configname) - - [defaultDomains](#services-proxy-suite-zapret-hostlistrules-defaultdomains) - - [defaultIps](#services-proxy-suite-zapret-hostlistrules-defaultips) - - [domains](#services-proxy-suite-zapret-hostlistrules-domains) - - [ips](#services-proxy-suite-zapret-hostlistrules-ips) - - [name](#services-proxy-suite-zapret-hostlistrules-name) - - [nfqwsArgs](#services-proxy-suite-zapret-hostlistrules-nfqwsargs) - - [preset](#services-proxy-suite-zapret-hostlistrules-preset) - - [includeExtraUpstreamLists](#services-proxy-suite-zapret-includeextraupstreamlists) - - [ipsetAll](#services-proxy-suite-zapret-ipsetall) - - [ipsetExclude](#services-proxy-suite-zapret-ipsetexclude) - - [listExclude](#services-proxy-suite-zapret-listexclude) - - [listGeneral](#services-proxy-suite-zapret-listgeneral) - - perApp - - [enable](#services-proxy-suite-zapret-perapp-enable) - - [filterMark](#services-proxy-suite-zapret-perapp-filtermark) - - [qnum](#services-proxy-suite-zapret-perapp-qnum) - - [syncDirectRouting](#services-proxy-suite-zapret-syncdirectrouting) - - [syncDirectRoutingUpstreamIps](#services-proxy-suite-zapret-syncdirectroutingupstreamips) - - [syncDirectRoutingUserIps](#services-proxy-suite-zapret-syncdirectroutinguserips) - - -## Complete default config - -```nix -services.proxy-suite = { - amneziaWg = { - enable = false; - kernelModulePackage = ; - profiles = { }; - toolsPackage = ; - userspacePackage = ; - }; - enable = false; - perAppRouting = { - createDefaultProfiles = false; - enable = false; - profiles = [ ]; - proxychains = { - enable = false; - proxyDns = true; - quiet = true; - }; - }; - proxy = { - auth = { - password = null; - passwordFile = null; - username = null; - }; - dns = { - local = { - address = "1.1.1.1"; - port = 53; - type = "udp"; - }; - remote = { - address = "1.1.1.1"; - port = 53; - type = "udp"; - }; - }; - enable = false; - listenAddress = "127.0.0.1"; - outbounds = [ ]; - port = 1080; - proxyByDefault = true; - routing = { - block = { - domains = [ ]; - geoips = [ ]; - geosites = [ ]; - ips = [ ]; - }; - direct = { - domains = [ ]; - geoips = [ ]; - geosites = [ ]; - ips = [ ]; - }; - enableRuDirect = true; - proxy = { - domains = [ ]; - geoips = [ ]; - geosites = [ ]; - ips = [ ]; - }; - rules = [ ]; - }; - selection = "first"; - singBox = { - clashApiPort = 9090; - enable = false; - package = pkgs.sing-box; - urlTest = { - tolerance = 50; - }; - }; - subscriptionUpdateInterval = "1d"; - subscriptions = [ ]; - tproxy = { - autostart = false; - enable = false; - fwmark = 1; - localSubnets = [ - "192.168.0.0/16" - ]; - perApp = { - enable = false; - fwmark = 17; - localSubnets = [ - "192.168.0.0/16" - ]; - routeTable = 102; - }; - port = 1085; - proxyMark = 2; - routeTable = 100; - }; - tun = { - address = "172.19.0.1/30"; - autostart = false; - enable = false; - interface = "singtun0"; - mtu = 1400; - perApp = { - address = "172.20.0.1/30"; - enable = false; - fwmark = 16; - interface = "psperapptun0"; - localSubnets = [ - "192.168.0.0/16" - ]; - mtu = 1400; - routeTable = 101; - }; - }; - urlTest = { - interval = "3m"; - url = "https://www.gstatic.com/generate_204"; - }; - xray = { - enable = false; - package = pkgs.xray; - }; - }; - proxyInbounds = { - blockPrivate = true; - blockRu = true; - enable = false; - listeners = { }; - openFirewall = true; - package = pkgs.xray; - serverAddress = null; - shareLinks = true; - via = "proxy"; - zapretDirect = true; - }; - sshProxy = { - asOutbound = false; - domainStrategy = null; - enable = false; - extraArgs = [ ]; - host = null; - hostKey = [ ]; - hostKeyFile = null; - identityFile = null; - knownHostsFile = null; - listenAddress = "127.0.0.1"; - listenPort = 1091; - serviceUser = null; - sshPort = 22; - strictHostKeyChecking = "accept-new"; - user = null; - }; - tgWsProxy = { - bufKb = 256; - bypassTransparentProxy = true; - cfProxyDomains = [ ]; - cfProxyFallback = true; - cfProxyWorkerDomains = [ ]; - dcIps = { }; - enable = false; - fakeTlsDomain = null; - host = "127.0.0.1"; - logBackups = 1; - logFile = null; - logMaxMb = 5.0; - poolSize = 4; - port = 1443; - proxyProtocol = false; - routingMark = 4; - secret = null; - secretFile = null; - verbose = false; - }; - tray = { - autostart = true; - enable = false; - pollInterval = 5; - }; - userControl = { - global = { - enable = true; - }; - group = "proxy-suite"; - perApp = { - enable = true; - }; - }; - zapret = { - cidrExemption = { - cidrs = [ ]; - enable = false; - }; - configName = "general(ALT)"; - enable = false; - gameFilter = "null"; - hostlistRules = [ ]; - includeExtraUpstreamLists = false; - ipsetAll = [ ]; - ipsetExclude = [ ]; - listExclude = [ ]; - listGeneral = [ ]; - perApp = { - enable = false; - filterMark = 268435456; - qnum = 201; - }; - syncDirectRouting = true; - syncDirectRoutingUpstreamIps = false; - syncDirectRoutingUserIps = true; - }; -}; -``` - - -## Complete example config - -This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options. - -```nix -services.proxy-suite = { - amneziaWg = { - enable = true; - kernelModulePackage = ; - profiles = { }; - toolsPackage = ; - userspacePackage = ; - }; - enable = true; - perAppRouting = { - createDefaultProfiles = true; - enable = true; - profiles = [ - { - name = "steam-browser"; - route = "proxychains"; - } - { - name = "native-direct"; - route = "direct"; - } - ]; - proxychains = { - enable = true; - proxyDns = true; - quiet = true; - }; - }; - proxy = { - auth = { - password = "change-me"; - passwordFile = "/run/secrets/proxy-suite-local-proxy-password"; - username = "proxy-user"; - }; - dns = { - local = { - address = "9.9.9.9"; - port = 53; - type = "tcp"; - }; - remote = { - address = "1.1.1.1"; - port = 853; - type = "tls"; - }; - }; - enable = false; - listenAddress = "127.0.0.1"; - outbounds = [ - { - tag = "de-vps"; - urlFile = "/run/secrets/proxy-de-url"; - } - { - tag = "nl-vps"; - url = "hy2://password@example.com:443?sni=example.com"; - } - ]; - port = 1080; - proxyByDefault = true; - routing = { - block = { - domains = [ - "ads.example.com" - ]; - geoips = [ - "cn" - ]; - geosites = [ - "category-ads-all" - ]; - ips = [ - "203.0.113.0/24" - ]; - }; - direct = { - domains = [ - "internal.example" - ]; - geoips = [ - "ru" - ]; - geosites = [ - "category-ru" - ]; - ips = [ - "10.10.0.0/16" - ]; - }; - enableRuDirect = true; - proxy = { - domains = [ - "youtube.com" - "discord.com" - ]; - geoips = [ - "us" - "de" - ]; - geosites = [ - "netflix" - "google" - ]; - ips = [ - "1.1.1.0/24" - ]; - }; - rules = [ - { - domains = [ - "netflix.com" - ]; - geosites = [ - "netflix" - ]; - outbound = "vps-de"; - } - { - domains = [ - "internal.corp" - ]; - outbound = "direct"; - } - { - domains = [ - "ads.example.com" - ]; - outbound = "block"; - } - ]; - }; - selection = "urltest"; - singBox = { - clashApiPort = 9090; - enable = true; - package = pkgs.sing-box; - urlTest = { - tolerance = 100; - }; - }; - subscriptionUpdateInterval = "6h"; - subscriptions = [ - { - tag = "community"; - url = "https://example.com/sub/token"; - } - { - tag = "private"; - urlFile = "/run/secrets/private-sub-url"; - } - ]; - tproxy = { - autostart = true; - enable = true; - fwmark = 1; - localSubnets = [ - "192.168.0.0/16" - "10.0.0.0/8" - ]; - perApp = { - enable = true; - fwmark = 17; - localSubnets = [ - "192.168.0.0/16" - "10.0.0.0/8" - ]; - routeTable = 102; - }; - port = 1085; - proxyMark = 2; - routeTable = 100; - }; - tun = { - address = "172.19.0.1/30"; - autostart = true; - enable = true; - interface = "singtun0"; - mtu = 1400; - perApp = { - address = "172.20.0.1/30"; - enable = true; - fwmark = 16; - interface = "psperapptun0"; - localSubnets = [ - "192.168.0.0/16" - "10.0.0.0/8" - ]; - mtu = 1400; - routeTable = 101; - }; - }; - urlTest = { - interval = "1m"; - url = "https://telegram.org"; - }; - xray = { - enable = true; - package = pkgs.xray; - }; - }; - proxyInbounds = { - blockPrivate = false; - blockRu = false; - enable = true; - listeners = { - _type = "literalExpression"; - text = '' - { - 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" ]; - }; - }; - } - ''; - }; - openFirewall = false; - package = pkgs.xray; - serverAddress = "vpn.example.com"; - shareLinks = false; - via = "direct"; - zapretDirect = false; - }; - sshProxy = { - asOutbound = true; - domainStrategy = "prefer_ipv4"; - enable = true; - extraArgs = [ - "-o" - "ServerAliveInterval=30" - ]; - host = "ssh.example.com"; - hostKey = [ - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." - ]; - hostKeyFile = "/root/.ssh/known_hosts"; - identityFile = "/run/secrets/proxy-suite-ssh-key"; - knownHostsFile = "/run/secrets/proxy-suite-ssh-known-hosts"; - listenAddress = "127.0.0.1"; - listenPort = 1091; - serviceUser = "proxy"; - sshPort = 22; - strictHostKeyChecking = "yes"; - user = "root"; - }; - tgWsProxy = { - bufKb = 512; - bypassTransparentProxy = true; - cfProxyDomains = [ - "cdn.example.com" - "edge.example.net" - ]; - cfProxyFallback = false; - cfProxyWorkerDomains = [ - "worker.example.com" - ]; - dcIps = { - "2" = "149.154.167.220"; - "203" = "149.154.167.220"; - "4" = "149.154.167.220"; - }; - enable = true; - fakeTlsDomain = "www.example.com"; - host = "127.0.0.1"; - logBackups = 3; - logFile = "/var/log/tg-ws-proxy.log"; - logMaxMb = 10.0; - poolSize = 8; - port = 1076; - proxyProtocol = true; - routingMark = 4; - secret = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - secretFile = "/run/secrets/tg-ws-proxy-secret"; - verbose = true; - }; - tray = { - autostart = true; - enable = true; - pollInterval = 5; - }; - userControl = { - global = { - enable = true; - }; - group = "proxy-suite"; - perApp = { - enable = true; - }; - }; - zapret = { - cidrExemption = { - cidrs = [ - "192.168.123.0/24" - "10.0.0.0/8" - ]; - enable = true; - }; - configName = "general(ALT)"; - enable = true; - gameFilter = "null"; - hostlistRules = [ - { - configName = "general(ALT9)"; - defaultDomains = [ - "youtube" - ]; - name = "youtube-alt9"; - } - { - configName = "general (ALT12)"; - defaultDomains = [ - "discord" - ]; - name = "discord-alt12"; - } - { - configName = "general (SIMPLE FAKE)"; - domains = [ - "example.com" - "example.org" - ]; - ips = [ - "203.0.113.0/24" - ]; - name = "custom-sites"; - preset = "general"; - } - ]; - includeExtraUpstreamLists = false; - ipsetAll = [ - "203.0.113.0/24" - ]; - ipsetExclude = [ - "203.0.113.10/32" - ]; - listExclude = [ - "music.youtube.com" - ]; - listGeneral = [ - "youtube.com" - ]; - perApp = { - enable = true; - filterMark = 268435456; - qnum = 201; - }; - syncDirectRouting = true; - syncDirectRoutingUpstreamIps = false; - syncDirectRoutingUserIps = true; - }; -}; -``` - - -## services\.proxy-suite\.enable - - - -Whether to enable proxy suite (proxy backend + AmneziaWG + zapret + tg-ws-proxy)\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.amneziaWg\.enable - -Whether to enable native AmneziaWG client profiles\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.kernelModulePackage - - - -AWG 3\.1 kernel module package\. Set null to use userspace-only fallback\. - - - -*Type:* -null or package - - - -*Default:* - -```nix - -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles - - - -Named AmneziaWG client profiles\. Only one global profile can be active\. - - - -*Type:* -attribute set of (submodule) - - - -*Default:* - -```nix -{ } -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.allowConfigHooks - - - -Allow trusted imported configs to execute wg-quick hooks or use SaveConfig\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.autostart - - - -Whether to start this profile at boot\. At most one profile may autostart\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.configFile - - - -Runtime path to an AmneziaWG \.conf file\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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›" -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings - - - -Typed declarative AmneziaWG client configuration\. - - - -*Type:* -null or (submodule) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.addresses - - - -IP prefixes assigned to the AWG interface\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "10.8.0.2/32" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.dns - - - -DNS servers installed while this profile is active\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.listenPort - - - -Optional local UDP listen port\. - - - -*Type:* -null or 16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.mtu - - - -Optional interface MTU\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation - - - -AmneziaWG 1\.x through 3\.x obfuscation parameters\. - - - -*Type:* -submodule - - - -*Default:* - -```nix -{ } -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.disableCookies - - - -AWG 3 cookie suppression (DisableCookies)\. - - - -*Type:* -null or boolean - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.headerProtectionKey - - - -Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.headerProtectionKeyFile - - - -Runtime path containing the AWG 3 header-protection key\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i1 - - - -First custom signature packet (I1)\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i2 - - - -Second custom signature packet (I2)\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i3 - - - -Third custom signature packet (I3)\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i4 - - - -Fourth custom signature packet (I4)\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i5 - - - -Fifth custom signature packet (I5)\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jc - - - -Junk packet count (Jc)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jmax - - - -Maximum junk packet size (Jmax)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jmin - - - -Minimum junk packet size (Jmin)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.randomTrailers - - - -AWG 3 random transport trailers (RandomTrailers)\. - - - -*Type:* -null or boolean - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s1 - - - -Handshake-init padding (S1)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s2 - - - -Handshake-response padding (S2)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s3 - - - -Cookie-reply padding (S3)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s4 - - - -Transport-message padding (S4)\. - - - -*Type:* -null or (unsigned integer, meaning >=0) - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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" -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers - - - -AmneziaWG peers\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.advancedSecurity - - - -Optional AWG peer AdvancedSecurity setting\. - - - -*Type:* -null or boolean - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.endpoint - - - -Optional peer endpoint in host:port form\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"vpn.example.com:51820" -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.presharedKey - - - -Inline peer preshared key\. Prefer presharedKeyFile for secrets\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.presharedKeyFile - - - -Runtime path containing the peer preshared key\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.publicKey - - - -AmneziaWG peer public key\. - - - -*Type:* -string matching the pattern \[^\[:space:]]+ - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.privateKey - - - -Inline client private key\. Prefer privateKeyFile\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.privateKeyFile - - - -Runtime path containing the client private key\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.table - - - -wg-quick routing table name/number, auto, or off\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpn - - - -Inline self-contained vpn:// export\. This value is stored in the Nix store\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpnContainer - - - -AWG container/protocol identifier to select when a vpn:// bundle is ambiguous\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpnFile - - - -Runtime path containing a self-contained vpn:// export\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.toolsPackage - - - -AWG 3\.1 package providing awg and awg-quick\. - - - -*Type:* -package - - - -*Default:* - -```nix - -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.amneziaWg\.userspacePackage - - - -AWG 3\.1 userspace implementation used when the kernel interface is unavailable\. - - - -*Type:* -package - - - -*Default:* - -```nix - -``` - -*Declared by:* - - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) - - - - -## services\.proxy-suite\.perAppRouting\.enable - - - -Whether to enable per-app routing helpers via proxy-ctl wrap\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.createDefaultProfiles - - - -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 -- ` available -without defining the profile manually, and similarly exposes -` proxy-ctl wrap tun -- ` or -` proxy-ctl wrap tproxy -- ` or -` proxy-ctl wrap zapret -- ` when the corresponding backend -is enabled\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.profiles - - - -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\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - { - name = "steam-browser"; - route = "proxychains"; - } - { - name = "native-direct"; - route = "direct"; - } -] -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.profiles\.\*\.name - - - -Profile name used by ` proxy-ctl wrap -- `\. -Must be unique within perAppRouting\.profiles\. - - - -*Type:* -string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$ - - - -*Example:* - -```nix -"steam-browser" -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.profiles\.\*\.route - - - -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\. - - - -*Type:* -one of “direct”, “proxychains”, “tun”, “tproxy”, “zapret” - - - -*Default:* - -```nix -"proxychains" -``` - - - -*Example:* - -```nix -"proxychains" -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.proxychains\.enable - - - -Whether to enable proxychains-backed perAppRouting profiles\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.proxychains\.proxyDns - - - -Whether generated proxychains wrappers should resolve DNS through -the proxy instead of the local resolver\. This maps to proxychains-ng -proxy_dns\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.perAppRouting\.proxychains\.quiet - - - -Whether generated proxychains wrappers should suppress their normal -startup chatter\. This maps to proxychains-ng quiet_mode\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/per-app-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/per-app-routing.nix) - - - - -## services\.proxy-suite\.proxy\.enable - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.auth\.password - - - -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\. - - - -*Type:* -null or string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"change-me" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.auth\.passwordFile - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-suite-local-proxy-password" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.auth\.username - - - -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\. - - - -*Type:* -null or string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"proxy-user" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.local - - - -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\. - - - -*Type:* -submodule - - - -*Default:* - -```nix -{ - address = "1.1.1.1"; - port = 53; - type = "udp"; -} -``` - - - -*Example:* - -```nix -{ - address = "9.9.9.9"; - port = 53; - type = "tcp"; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.local\.address - - - -Resolver address or hostname used for this DNS upstream\. - - - -*Type:* -string matching the pattern \.+ - - - -*Example:* - -```nix -"1.1.1.1" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.local\.port - - - -Destination port for this DNS upstream\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -53 -``` - - - -*Example:* - -```nix -853 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.local\.type - - - -DNS transport type for this upstream resolver\. - - - -*Type:* -one of “udp”, “tcp”, “tls” - - - -*Default:* - -```nix -"udp" -``` - - - -*Example:* - -```nix -"tls" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.remote - - - -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\. - - - -*Type:* -submodule - - - -*Default:* - -```nix -{ - address = "1.1.1.1"; - port = 53; - type = "udp"; -} -``` - - - -*Example:* - -```nix -{ - address = "1.1.1.1"; - port = 853; - type = "tls"; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.remote\.address - - - -Resolver address or hostname used for this DNS upstream\. - - - -*Type:* -string matching the pattern \.+ - - - -*Example:* - -```nix -"1.1.1.1" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.remote\.port - - - -Destination port for this DNS upstream\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -53 -``` - - - -*Example:* - -```nix -853 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.dns\.remote\.type - - - -DNS transport type for this upstream resolver\. - - - -*Type:* -one of “udp”, “tcp”, “tls” - - - -*Default:* - -```nix -"udp" -``` - - - -*Example:* - -```nix -"tls" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-dns\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-dns.nix) - - - - -## services\.proxy-suite\.proxy\.listenAddress - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"127.0.0.1" -``` - - - -*Example:* - -```nix -"127.0.0.1" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds - - - -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\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - { - tag = "de-vps"; - urlFile = "/run/secrets/proxy-de-url"; - } - { - tag = "nl-vps"; - url = "hy2://password@example.com:443?sni=example.com"; - } -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.backend - - - -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\. - - - -*Type:* -one of “auto”, “sing-box”, “xray” - - - -*Default:* - -```nix -"auto" -``` - - - -*Example:* - -```nix -"xray" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.domains - - - -Domain suffixes to match in this routing rule\. -Leave empty to skip domain-based matching for this rule entry\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "youtube.com" - "discord.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.geoips - - - -sing-geoip rule-set names to match in this routing rule\. -Each name becomes a backend geoip rule-set reference\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "us" - "de" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.geosites - - - -sing-geosite rule-set names to match in this routing rule\. -Each name becomes a backend geosite rule-set reference\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "netflix" - "google" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.ips - - - -IP CIDRs to match in this routing rule\. -Leave empty to skip IP-based matching for this rule entry\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "1.1.1.0/24" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.singBoxJson - - - -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\. - - - -*Type:* -null or (attribute set) - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -{ - server = "example.com"; - server_port = 443; - type = "vless"; - uuid = "..."; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.tag - - - -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\. - - - -*Type:* -string - - - -*Example:* - -```nix -"vps-de" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.url - - - -Literal proxy URL\. Convenient for non-secret configs, but the URL -will end up in the Nix store\. - -Set exactly one of urlFile, url, or json for each outbound\. -Prefer urlFile for real credentials\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"hy2://password@example.com:443?sni=example.com" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.urlFile - - - -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\. - -Set exactly one of urlFile, url, or json for each outbound\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/my-proxy-url" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.outbounds\.\*\.xrayJson - - - -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\. - - - -*Type:* -null or (attribute set) - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -{ - protocol = "vless"; - settings = { - address = "example.com"; - encryption = "none"; - id = "..."; - port = 443; - }; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.port - - - -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\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -1080 -``` - - - -*Example:* - -```nix -1080 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.proxyByDefault - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.enableRuDirect - - - -Automatically append “category-ru” to routing\.direct\.geosites and -“ru” to routing\.direct\.geoips\. - -This is additive: user-defined routing\.direct\.\* entries still apply\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.block\.domains - - - -Domain suffixes to block entirely\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "ads.example.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.block\.geoips - - - -sing-geoip names to block\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "cn" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.block\.geosites - - - -sing-geosite names to block\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "category-ads-all" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.block\.ips - - - -IP CIDRs to block\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "203.0.113.0/24" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.direct\.domains - - - -Domain suffixes to send direct (bypass proxy)\. -Merged with zapret-synced direct domains when zapret direct sync -options are enabled\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "internal.example" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.direct\.geoips - - - -sing-geoip names to send direct\. -“ru” is added automatically when enableRuDirect = true\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "ru" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.direct\.geosites - - - -sing-geosite names to send direct\. -“category-ru” is added automatically when enableRuDirect = true\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "category-ru" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.direct\.ips - - - -IP CIDRs to send direct\. -Merged with zapret-synced direct IPs when the corresponding zapret -sync options are enabled\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "10.10.0.0/16" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.proxy\.domains - -Domain suffixes to match in this routing rule\. -Leave empty to skip domain-based matching for this rule entry\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "youtube.com" - "discord.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.proxy\.geoips - - - -sing-geoip rule-set names to match in this routing rule\. -Each name becomes a backend geoip rule-set reference\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "us" - "de" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.proxy\.geosites - - - -sing-geosite rule-set names to match in this routing rule\. -Each name becomes a backend geosite rule-set reference\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "netflix" - "google" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.proxy\.ips - - - -IP CIDRs to match in this routing rule\. -Leave empty to skip IP-based matching for this rule entry\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "1.1.1.0/24" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.rules - - - -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\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - { - domains = [ - "netflix.com" - ]; - geosites = [ - "netflix" - ]; - outbound = "vps-de"; - } - { - domains = [ - "internal.corp" - ]; - outbound = "direct"; - } - { - domains = [ - "ads.example.com" - ]; - outbound = "block"; - } -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.rules\.\*\.domains - - - -Domain suffixes to match in this routing rule\. -Leave empty to skip domain-based matching for this rule entry\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "youtube.com" - "discord.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.rules\.\*\.geoips - - - -sing-geoip rule-set names to match in this routing rule\. -Each name becomes a backend geoip rule-set reference\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "us" - "de" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.rules\.\*\.geosites - - - -sing-geosite rule-set names to match in this routing rule\. -Each name becomes a backend geosite rule-set reference\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "netflix" - "google" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.rules\.\*\.ips - - - -IP CIDRs to match in this routing rule\. -Leave empty to skip IP-based matching for this rule entry\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "1.1.1.0/24" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.routing\.rules\.\*\.outbound - - - -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\. - - - -*Type:* -string - - - -*Example:* - -```nix -"vps-de" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-routing\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-routing.nix) - - - - -## services\.proxy-suite\.proxy\.selection - - - -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”\. - - - -*Type:* -one of “first”, “selector”, “urltest” - - - -*Default:* - -```nix -"first" -``` - - - -*Example:* - -```nix -"urltest" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.singBox\.enable - - - -Whether to enable SingBox proxy backend\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.singBox\.package - - - -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\. - - - -*Type:* -package - - - -*Default:* - -```nix -pkgs.sing-box -``` - - - -*Example:* - -```nix -pkgs.sing-box -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.singBox\.clashApiPort - - - -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\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -9090 -``` - - - -*Example:* - -```nix -9090 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.singBox\.urlTest\.tolerance - - - -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\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -50 -``` - - - -*Example:* - -```nix -100 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.subscriptionUpdateInterval - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"1d" -``` - - - -*Example:* - -```nix -"6h" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.subscriptions - - - -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/\/\\.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\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - { - tag = "community"; - url = "https://example.com/sub/token"; - } - { - tag = "private"; - urlFile = "/run/secrets/private-sub-url"; - } -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.subscriptions\.\*\.tag - - - -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/\/, so it must be a safe -identifier\. - - - -*Type:* -string matching the pattern ^\[A-Za-z0-9]\[A-Za-z0-9\._-]\*$ - - - -*Example:* - -```nix -"community-list" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.subscriptions\.\*\.url - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"https://example.com/sub/token123" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.subscriptions\.\*\.urlFile - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-subscription-url" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.enable - - - -Whether to enable global proxy TProxy mode service\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.autostart - - - -Whether to start proxy-suite-tproxy automatically during boot by -attaching it to multi-user\.target\. -Cannot be enabled together with proxy\.tun\.autostart\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.fwmark - - - -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\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -1 -``` - - - -*Example:* - -```nix -1 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.localSubnets - - - -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\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ - "192.168.0.0/16" -] -``` - - - -*Example:* - -```nix -[ - "192.168.0.0/16" - "10.0.0.0/8" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.perApp\.enable - - - -Whether to enable per-app-scoped proxy TProxy backend for perAppRouting profiles\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.perApp\.fwmark - - - -Packet mark used to steer wrapped app traffic into the per-app-scoped -TProxy policy-routing table\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -17 -``` - - - -*Example:* - -```nix -17 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.perApp\.localSubnets - - - -Subnets whose traffic bypasses per-app-scoped TProxy interception, -except DNS (port 53)\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ - "192.168.0.0/16" -] -``` - - - -*Example:* - -```nix -[ - "192.168.0.0/16" - "10.0.0.0/8" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.perApp\.routeTable - - - -Policy-routing table used by the per-app-scoped TProxy backend\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -102 -``` - - - -*Example:* - -```nix -102 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.port - - - -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\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -1085 -``` - - - -*Example:* - -```nix -1085 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.proxyMark - - - -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\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -2 -``` - - - -*Example:* - -```nix -2 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tproxy\.routeTable - - - -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\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -100 -``` - - - -*Example:* - -```nix -100 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tproxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tproxy.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.enable - - - -Whether to enable global proxy TUN mode service\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.address - - - -Address assigned to the global TUN interface in CIDR notation\. - - - -*Type:* -string - - - -*Default:* - -```nix -"172.19.0.1/30" -``` - - - -*Example:* - -```nix -"172.19.0.1/30" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.autostart - - - -Whether to start proxy-suite-tun automatically during boot by -attaching it to multi-user\.target\. -Cannot be enabled together with proxy\.tproxy\.autostart\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.interface - - - -Name of the TUN interface created by proxy-suite-tun\. - - - -*Type:* -string - - - -*Default:* - -```nix -"singtun0" -``` - - - -*Example:* - -```nix -"singtun0" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.mtu - - - -MTU for the global TUN interface created by proxy-suite-tun\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -1400 -``` - - - -*Example:* - -```nix -1400 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.enable - - - -Whether to enable per-app-scoped proxy TUN backend for perAppRouting profiles\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.address - - - -Address assigned to the dedicated per-app-routing TUN interface in CIDR -notation\. - - - -*Type:* -string - - - -*Default:* - -```nix -"172.20.0.1/30" -``` - - - -*Example:* - -```nix -"172.20.0.1/30" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.fwmark - - - -Packet mark used to steer wrapped app traffic into the per-app-scoped -TUN policy-routing table\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -16 -``` - - - -*Example:* - -```nix -16 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.interface - - - -Name of the dedicated per-app-routing TUN interface used by -proxy-suite-per-app-tun\. - - - -*Type:* -string - - - -*Default:* - -```nix -"psperapptun0" -``` - - - -*Example:* - -```nix -"psperapptun0" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.localSubnets - - - -Destination subnets that should bypass the per-app-scoped TUN mark, -so wrapped apps can still reach local LAN resources directly\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ - "192.168.0.0/16" -] -``` - - - -*Example:* - -```nix -[ - "192.168.0.0/16" - "10.0.0.0/8" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.mtu - - - -MTU for the dedicated per-app-routing TUN interface\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -1400 -``` - - - -*Example:* - -```nix -1400 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.tun\.perApp\.routeTable - - - -Policy-routing table used by the per-app-scoped TUN backend\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -101 -``` - - - -*Example:* - -```nix -101 -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-tun\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-tun.nix) - - - - -## services\.proxy-suite\.proxy\.urlTest\.interval - - - -How often the active backend re-tests all outbounds\. Accepts a Go -duration string (e\.g\. “1m”, “3m”, “10m”)\. -Only used when selection = “urltest”\. - - - -*Type:* -string - - - -*Default:* - -```nix -"3m" -``` - - - -*Example:* - -```nix -"1m" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.urlTest\.url - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"https://www.gstatic.com/generate_204" -``` - - - -*Example:* - -```nix -"https://telegram.org" -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box-outbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box-outbounds.nix) - - - - -## services\.proxy-suite\.proxy\.xray\.enable - - - -Whether to enable XRay proxy backend\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxy\.xray\.package - - - -XRay package used by proxy-suite systemd services\. - -Override this to pin or test a specific XRay build when upstream -protocol behavior changes\. - - - -*Type:* -package - - - -*Default:* - -```nix -pkgs.xray -``` - - - -*Example:* - -```nix -pkgs.xray -``` - -*Declared by:* - - [modules/proxy-suite/options/sing-box\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/sing-box.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.enable - - - -Whether to enable server-side proxy inbounds (accept connections from outside)\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.package - - - -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\. - - - -*Type:* -package - - - -*Default:* - -```nix -pkgs.xray -``` - - - -*Example:* - -```nix -pkgs.xray -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.blockPrivate - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.blockRu - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners - - - -Named inbound listeners\. The attribute name becomes the inbound tag -used in routing rules and in ` proxy-ctl inbounds `\. - - - -*Type:* -attribute set of (submodule) - - - -*Default:* - -```nix -{ } -``` - - - -*Example:* - -```nix -{ - 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" ]; - }; - }; -} - -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.flow - - - -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\. - - - -*Type:* -null or value “xtls-rprx-vision” (singular enum) - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"xtls-rprx-vision" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.jsonFile - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-inbound-vless.json" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.listenAddress - - - -Address this listener binds\. The default accepts both IPv4 and IPv6 -connections from anywhere\. - - - -*Type:* -string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -"::" -``` - - - -*Example:* - -```nix -"0.0.0.0" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.method - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"2022-blake3-aes-128-gcm" -``` - - - -*Example:* - -```nix -"aes-128-gcm" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.port - - - -Port this listener binds\. Opened in the firewall automatically unless -proxyInbounds\.openFirewall is disabled\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -443 -``` - - - -*Example:* - -```nix -443 -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality - - - -REALITY settings for this listener\. Mutually exclusive with tls\. - - - -*Type:* -submodule - - - -*Default:* - -```nix -{ } -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.enable - - - -Enable REALITY on this listener\. Mutually exclusive with tls\.enable\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.dest - - - -Real TLS server that unauthenticated probes are proxied to\. Must be a -host:port that serves TLS 1\.3 with HTTP/2\. - - - -*Type:* -string - - - -*Default:* - -```nix -"www.microsoft.com:443" -``` - - - -*Example:* - -```nix -"www.microsoft.com:443" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.privateKey - - - -Literal REALITY x25519 private key\. - -This value is embedded in the Nix store\. Prefer privateKeyFile\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"gG1Yz..." -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.privateKeyFile - - - -Runtime path to the REALITY x25519 private key, as produced by -` xray x25519 `\. Read at service start time; never lands in the Nix -store\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-inbound-reality-key" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.publicKey - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"jNXH..." -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.serverNames - - - -SNI values accepted by this listener\. These must be names the dest -server actually serves\. The first entry is used in share links\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "www.microsoft.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.shortIds - - - -Accepted REALITY short IDs (hex, up to 16 characters)\. The default -accepts the empty short ID\. The first entry is used in share links\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ - "" -] -``` - - - -*Example:* - -```nix -[ - "0123abcd" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls - - - -TLS termination settings for this listener\. Mutually exclusive with -reality\. - - - -*Type:* -submodule - - - -*Default:* - -```nix -{ } -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.enable - - - -Terminate TLS on this listener\. Mutually exclusive with reality\. - -Always on for trojan listeners regardless of this setting\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.certificateFile - - - -Runtime path to the PEM certificate chain\. Compose with -security\.acme to keep it renewed\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/var/lib/acme/example.com/fullchain.pem" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.keyFile - - - -Runtime path to the PEM private key matching certificateFile\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/var/lib/acme/example.com/key.pem" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.serverName - - - -SNI advertised in generated share links\. Defaults to -proxyInbounds\.serverAddress when unset\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"example.com" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport - - - -Stream transport settings for this listener\. - - - -*Type:* -submodule - - - -*Default:* - -```nix -{ } -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.host - - - -Expected Host header for the “ws”, “httpupgrade”, and “xhttp” -transports\. Leave null to accept any host\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"cdn.example.com" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.path - - - -Request path for the “ws”, “httpupgrade”, and “xhttp” transports\. -Ignored by the other transports\. - - - -*Type:* -string - - - -*Default:* - -```nix -"/" -``` - - - -*Example:* - -```nix -"/download" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.serviceName - - - -gRPC service name for the “grpc” transport\. Ignored otherwise\. - - - -*Type:* -string - - - -*Default:* - -```nix -"" -``` - - - -*Example:* - -```nix -"GunService" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.type - - - -Stream transport for this listener\. “raw” is plain TCP and is what -REALITY setups normally use\. - - - -*Type:* -one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp” - - - -*Default:* - -```nix -"raw" -``` - - - -*Example:* - -```nix -"ws" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.type - - - -Proxy protocol served by this listener\. - -Set exactly one of type, xrayJson, or jsonFile for each listener\. - - - -*Type:* -null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http” - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"vless" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users - - - -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\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - { - uuidFile = "/run/secrets/proxy-inbound-uuid"; - } -] -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.name - - - -Optional label for this account\. Used as the share-link fragment so -clients show a readable server name, and as the XRay user email\. - - - -*Type:* -string - - - -*Default:* - -```nix -"" -``` - - - -*Example:* - -```nix -"phone" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.password - - - -Literal password for trojan, shadowsocks, socks, and http listeners\. - -This value is embedded in the Nix store\. Prefer passwordFile for real -credentials\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"hunter2" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.passwordFile - - - -Runtime path to a file containing the account password\. -The file is read at service start time and never lands in the Nix store\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-inbound-password" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.uuid - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"b831381d-6324-4d53-ad4f-8cda48b30811" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.uuidFile - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-inbound-uuid" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.via - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"nl-vps" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.listeners\.\\.xrayJson - - - -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\. - - - -*Type:* -null or (attribute set) - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -{ - protocol = "dokodemo-door"; - settings = { - address = "127.0.0.1"; - port = 8080; - }; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.openFirewall - - - -Add every listener port to networking\.firewall\. Disable to manage the -firewall yourself\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.serverAddress - - - -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\. - - - -*Type:* -null or string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"vpn.example.com" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.shareLinks - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.via - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"proxy" -``` - - - -*Example:* - -```nix -"direct" -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.proxyInbounds\.zapretDirect - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) - - - - -## services\.proxy-suite\.sshProxy\.enable - - - -Whether to enable SSH dynamic SOCKS5 proxy\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.asOutbound - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.domainStrategy - - - -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\. - - - -*Type:* -null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only” - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"prefer_ipv4" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.extraArgs - - - -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\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "-o" - "ServerAliveInterval=30" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.host - - - -SSH server hostname or address\. Required when sshProxy\.enable is true\. - - - -*Type:* -null or string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"ssh.example.com" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.hostKey - - - -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\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." -] -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.hostKeyFile - - - -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\. - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/root/.ssh/known_hosts" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.identityFile - - - -Runtime path to the SSH private key\. Leave unset to use the SSH agent -or OpenSSH’s normal identity-file lookup\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-suite-ssh-key" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.knownHostsFile - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/proxy-suite-ssh-known-hosts" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.listenAddress - - - -Local address for the SSH-created SOCKS5 listener\. - -OpenSSH path only: a SingBox or hybrid backend dials SSH natively and -creates no local listener\. - - - -*Type:* -string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -"127.0.0.1" -``` - - - -*Example:* - -```nix -"127.0.0.1" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.listenPort - - - -Local port for the SSH-created SOCKS5 listener\. - -OpenSSH path only: a SingBox or hybrid backend dials SSH natively and -creates no local listener\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -1091 -``` - - - -*Example:* - -```nix -1091 -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.serviceUser - - - -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\. - - - -*Type:* -null or string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"proxy" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.sshPort - - - -Remote SSH server port\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -22 -``` - - - -*Example:* - -```nix -22 -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.strictHostKeyChecking - - - -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\. - - - -*Type:* -one of “yes”, “accept-new”, “no” - - - -*Default:* - -```nix -"accept-new" -``` - - - -*Example:* - -```nix -"yes" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.sshProxy\.user - - - -SSH login user\. Required when sshProxy\.enable is true\. - - - -*Type:* -null or string matching the pattern \[^\[:space:]]+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"root" -``` - -*Declared by:* - - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.enable - - - -Whether to enable Telegram MTProto WebSocket proxy\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.bufKb - - - -Socket send and receive buffer size for tg-ws-proxy, in KiB\. - - - -*Type:* -integer between 4 and 2147483647 (both inclusive) - - - -*Default:* - -```nix -256 -``` - - - -*Example:* - -```nix -512 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.bypassTransparentProxy - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.cfProxyDomains - - - -User-defined Cloudflare-proxied domains used by tg-ws-proxy for -WebSocket fallback\. Each entry is passed as a separate -–cfproxy-domain argument\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "cdn.example.com" - "edge.example.net" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.cfProxyFallback - - - -Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when -direct WebSocket routing is unavailable\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.cfProxyWorkerDomains - - - -Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback\. -These are tried before other fallback methods\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "worker.example.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.dcIps - - - -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\. - - - -*Type:* -attribute set of string - - - -*Default:* - -```nix -{ } -``` - - - -*Example:* - -```nix -{ - "2" = "149.154.167.220"; - "203" = "149.154.167.220"; - "4" = "149.154.167.220"; -} -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.fakeTlsDomain - - - -Optional SNI domain used to enable tg-ws-proxy Fake TLS masking\. -When set, tg-ws-proxy emits an ee-secret connection link\. - - - -*Type:* -null or string matching the pattern \.+ - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"www.example.com" -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.host - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"127.0.0.1" -``` - - - -*Example:* - -```nix -"127.0.0.1" -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.logBackups - - - -Number of rotated tg-ws-proxy log files to keep\. -Only used when tgWsProxy\.logFile is set\. - - - -*Type:* -positive integer, meaning >0 - - - -*Default:* - -```nix -1 -``` - - - -*Example:* - -```nix -3 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.logFile - - - -Optional path where tg-ws-proxy writes rotating logs\. -When unset, tg-ws-proxy logs to stderr only\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/var/log/tg-ws-proxy.log" -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.logMaxMb - - - -Maximum tg-ws-proxy log file size in MiB before rotation\. -Only used when tgWsProxy\.logFile is set\. - - - -*Type:* -positive integer or floating point number, meaning >0 - - - -*Default:* - -```nix -5.0 -``` - - - -*Example:* - -```nix -10.0 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.poolSize - - - -WebSocket connection pool size per Telegram DC\. -Set to 0 to disable connection pooling\. - - - -*Type:* -unsigned integer, meaning >=0 - - - -*Default:* - -```nix -4 -``` - - - -*Example:* - -```nix -8 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.port - - - -TCP listen port for tg-ws-proxy\. -Telegram clients connect to this endpoint when using the local MTProto -WebSocket proxy\. - - - -*Type:* -16 bit unsigned integer; between 0 and 65535 (both inclusive) - - - -*Default:* - -```nix -1443 -``` - - - -*Example:* - -```nix -1076 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.proxyProtocol - - - -Whether tg-ws-proxy should accept a PROXY protocol v1 header from a -fronting reverse proxy such as nginx or HAProxy\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.routingMark - - - -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\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -4 -``` - - - -*Example:* - -```nix -4 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.secret - - - -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 - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.secretFile - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"/run/secrets/tg-ws-proxy-secret" -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tgWsProxy\.verbose - - - -Whether to enable debug logging in tg-ws-proxy\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tray\.enable - - - -Whether to enable system tray indicator for proxy-suite\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tray\.autostart - - - -Whether to install an XDG autostart entry for the tray application -for graphical users\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.tray\.pollInterval - - - -Tray status refresh interval in seconds\. -Lower values make UI state changes appear faster, while higher values -reduce background polling overhead\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -5 -``` - - - -*Example:* - -```nix -5 -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.userControl\.global\.enable - - - -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 `\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.userControl\.group - - - -Local group allowed to use passwordless polkit-backed ` proxy-ctl ` -commands when userControl\.global\.enable or userControl\.perApp\.enable -is turned on\. - - - -*Type:* -string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$ - - - -*Default:* - -```nix -"proxy-suite" -``` - - - -*Example:* - -```nix -"proxy-suite" -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.userControl\.perApp\.enable - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/other\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/other.nix) - - - - -## services\.proxy-suite\.zapret\.enable - - - -Whether to enable zapret DPI bypass\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.cidrExemption\.enable - - - -Whether to enable CIDR exemption from zapret NFQUEUE\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.cidrExemption\.cidrs - - - -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\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "192.168.123.0/24" - "10.0.0.0/8" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.configName - - - -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\. - - - -*Type:* -string - - - -*Default:* - -```nix -"general(ALT)" -``` - - - -*Example:* - -```nix -"general(ALT)" -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.gameFilter - - - -zapret game traffic filter mode: “all”, “tcp”, “udp”, or “null” to disable\. - - - -*Type:* -string - - - -*Default:* - -```nix -"null" -``` - - - -*Example:* - -```nix -"null" -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules - - - -Additional named zapret hostlists with per-list DPI mitigation rules\. -Each entry generates hostlists/list-\\.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\. - - - -*Type:* -list of (submodule) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - { - configName = "general(ALT9)"; - defaultDomains = [ - "youtube" - ]; - name = "youtube-alt9"; - } - { - configName = "general (ALT12)"; - defaultDomains = [ - "discord" - ]; - name = "discord-alt12"; - } - { - configName = "general (SIMPLE FAKE)"; - domains = [ - "example.com" - "example.org" - ]; - ips = [ - "203.0.113.0/24" - ]; - name = "custom-sites"; - preset = "general"; - } -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.enableDirectSync - - - -Whether this custom hostlist should also be mirrored into proxy -direct domain routing when zapret\.syncDirectRouting = true\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.configName - - - -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\. - - - -*Type:* -null or string - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"general(ALT9)" -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.defaultDomains - - - -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-\\.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\. - - - -*Type:* -list of (one of “general”, “google”, “discord”, “youtube”, “instagram”, “soundcloud”, “twitter”) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "google" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.defaultIps - - - -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\. - - - -*Type:* -list of value “all” (singular enum) - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "all" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.domains - - - -Domains written into the generated custom zapret hostlist file\. -Can be combined with defaultDomains\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "example.com" - "example.de" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.ips - - - -IPs or CIDRs written into the generated custom zapret ipset file\. -Can be combined with defaultIps\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "203.0.113.0/24" - "2001:db8::/32" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.name - - - -Custom hostlist name\. Used to generate hostlists/list-\\.txt -inside the derived zapret config directory\. - - - -*Type:* -string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$ - - - -*Example:* - -```nix -"cloudflare" -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.nfqwsArgs - - - -Additional NFQWS argument fragments for this hostlist\. -The module injects --hostlist=… and trailing --new automatically\. - -This cannot be used together with configName\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "--filter-tcp=443 --dpi-desync=fake,multisplit" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.hostlistRules\.\*\.preset - - - -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\. - - - -*Type:* -null or one of “general”, “google”, “instagram”, “soundcloud”, “twitter” - - - -*Default:* - -```nix -null -``` - - - -*Example:* - -```nix -"google" -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.includeExtraUpstreamLists - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.ipsetAll - - - -Extra IPs/CIDRs to add to zapret’s ipset\. -Mirrored into proxy direct IP routing when -syncDirectRoutingUserIps = true\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "203.0.113.0/24" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.ipsetExclude - - - -IPs/CIDRs to exclude from zapret’s ipset\. -Also excluded from zapret-derived proxy direct IP routing when -syncDirectRoutingUserIps = true\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "203.0.113.10/32" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.listExclude - - - -Domains to exclude from zapret interception\. -When syncDirectRouting = true, these exclusions also remove matching -domains from the zapret-derived proxy direct-routing set\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "music.youtube.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.listGeneral - - - -Extra domains to include in zapret’s interception list\. -When syncDirectRouting = true, these domains are also mirrored into -proxy direct routing\. - - - -*Type:* -list of string - - - -*Default:* - -```nix -[ ] -``` - - - -*Example:* - -```nix -[ - "youtube.com" -] -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.perApp\.enable - - - -Whether to enable per-app-scoped zapret backend for perAppRouting profiles\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.perApp\.filterMark - - - -Packet mark bit used to mark wrapped app traffic for the -dedicated per-app-scoped zapret instance\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -268435456 -``` - - - -*Example:* - -```nix -268435456 -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.perApp\.qnum - - - -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\. - - - -*Type:* -signed integer - - - -*Default:* - -```nix -201 -``` - - - -*Example:* - -```nix -201 -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.syncDirectRouting - - - -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\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.syncDirectRoutingUpstreamIps - - - -When zapret\.enable = true, mirror zapret’s upstream ipset ranges -(such as ipset-all\.txt minus exclusions) into proxy direct IP routing\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -false -``` - - - -*Example:* - -```nix -false -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) - - - - -## services\.proxy-suite\.zapret\.syncDirectRoutingUserIps - - - -When zapret\.enable = true, mirror user-defined zapret\.ipsetAll and -zapret\.ipsetExclude entries into proxy direct IP routing\. - - - -*Type:* -boolean - - - -*Default:* - -```nix -true -``` - - - -*Example:* - -```nix -true -``` - -*Declared by:* - - [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix) diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md new file mode 100644 index 0000000..a6cbaae --- /dev/null +++ b/docs/options/amneziaWg.md @@ -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) + - `` + - [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) + + +## services\.proxy-suite\.amneziaWg\.enable + +Whether to enable native AmneziaWG client profiles\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.amneziaWg\.kernelModulePackage + +AWG 3\.1 kernel module package\. Set null to use userspace-only fallback\. + +*Type:* +null or package + +*Default:* + +```nix + +``` + + +## services\.proxy-suite\.amneziaWg\.profiles + +Named AmneziaWG client profiles\. Only one global profile can be active\. + +*Type:* +attribute set of (submodule) + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.allowConfigHooks + +Allow trusted imported configs to execute wg-quick hooks or use SaveConfig\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.autostart + +Whether to start this profile at boot\. At most one profile may autostart\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.configFile + +Runtime path to an AmneziaWG \.conf file\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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›" +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings + +Typed declarative AmneziaWG client configuration\. + +*Type:* +null or (submodule) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.addresses + +IP prefixes assigned to the AWG interface\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "10.8.0.2/32" +] +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.dns + +DNS servers installed while this profile is active\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.listenPort + +Optional local UDP listen port\. + +*Type:* +null or 16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.mtu + +Optional interface MTU\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation + +AmneziaWG 1\.x through 3\.x obfuscation parameters\. + +*Type:* +submodule + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.disableCookies + +AWG 3 cookie suppression (DisableCookies)\. + +*Type:* +null or boolean + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.headerProtectionKey + +Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.headerProtectionKeyFile + +Runtime path containing the AWG 3 header-protection key\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i1 + +First custom signature packet (I1)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i2 + +Second custom signature packet (I2)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i3 + +Third custom signature packet (I3)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i4 + +Fourth custom signature packet (I4)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i5 + +Fifth custom signature packet (I5)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jc + +Junk packet count (Jc)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jmax + +Maximum junk packet size (Jmax)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jmin + +Minimum junk packet size (Jmin)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.randomTrailers + +AWG 3 random transport trailers (RandomTrailers)\. + +*Type:* +null or boolean + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s1 + +Handshake-init padding (S1)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s2 + +Handshake-response padding (S2)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s3 + +Cookie-reply padding (S3)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s4 + +Transport-message padding (S4)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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" +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers + +AmneziaWG peers\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.advancedSecurity + +Optional AWG peer AdvancedSecurity setting\. + +*Type:* +null or boolean + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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" +] +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.endpoint + +Optional peer endpoint in host:port form\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"vpn.example.com:51820" +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.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 +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.presharedKey + +Inline peer preshared key\. Prefer presharedKeyFile for secrets\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.presharedKeyFile + +Runtime path containing the peer preshared key\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.publicKey + +AmneziaWG peer public key\. + +*Type:* +string matching the pattern \[^\[:space:]]+ + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.privateKey + +Inline client private key\. Prefer privateKeyFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.privateKeyFile + +Runtime path containing the client private key\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.table + +wg-quick routing table name/number, auto, or off\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpn + +Inline self-contained vpn:// export\. This value is stored in the Nix store\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpnContainer + +AWG container/protocol identifier to select when a vpn:// bundle is ambiguous\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpnFile + +Runtime path containing a self-contained vpn:// export\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.amneziaWg\.toolsPackage + +AWG 3\.1 package providing awg and awg-quick\. + +*Type:* +package + +*Default:* + +```nix + +``` + + +## services\.proxy-suite\.amneziaWg\.userspacePackage + +AWG 3\.1 userspace implementation used when the kernel interface is unavailable\. + +*Type:* +package + +*Default:* + +```nix + +``` diff --git a/docs/options/geodata.md b/docs/options/geodata.md new file mode 100644 index 0000000..5c8b708 --- /dev/null +++ b/docs/options/geodata.md @@ -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) + + +## 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 +``` + + +## services\.proxy-suite\.geodata\.singBox\.geosite + +Package with share/sing-box/rule-set/geosite-NAME\.srs\. + +*Type:* +package + +*Default:* + +```nix +pkgs.sing-geosite +``` + + +## 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 +``` diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md new file mode 100644 index 0000000..a451a1d --- /dev/null +++ b/docs/options/inbounds.md @@ -0,0 +1,1077 @@ +# services.proxy-suite.inbounds + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- inbounds + - [enable](#services-proxy-suite-inbounds-enable) + - [package](#services-proxy-suite-inbounds-package) + - [listeners](#services-proxy-suite-inbounds-listeners) + - `` + - [address](#services-proxy-suite-inbounds-listeners-name-address) + - [flow](#services-proxy-suite-inbounds-listeners-name-flow) + - [jsonFile](#services-proxy-suite-inbounds-listeners-name-jsonfile) + - [method](#services-proxy-suite-inbounds-listeners-name-method) + - [port](#services-proxy-suite-inbounds-listeners-name-port) + - [reality](#services-proxy-suite-inbounds-listeners-name-reality) + - [enable](#services-proxy-suite-inbounds-listeners-name-reality-enable) + - [dest](#services-proxy-suite-inbounds-listeners-name-reality-dest) + - [privateKey](#services-proxy-suite-inbounds-listeners-name-reality-privatekey) + - [privateKeyFile](#services-proxy-suite-inbounds-listeners-name-reality-privatekeyfile) + - [publicKey](#services-proxy-suite-inbounds-listeners-name-reality-publickey) + - [serverNames](#services-proxy-suite-inbounds-listeners-name-reality-servernames) + - [shortIds](#services-proxy-suite-inbounds-listeners-name-reality-shortids) + - [sharePort](#services-proxy-suite-inbounds-listeners-name-shareport) + - [tls](#services-proxy-suite-inbounds-listeners-name-tls) + - [enable](#services-proxy-suite-inbounds-listeners-name-tls-enable) + - [alpn](#services-proxy-suite-inbounds-listeners-name-tls-alpn) + - [certificateFile](#services-proxy-suite-inbounds-listeners-name-tls-certificatefile) + - [keyFile](#services-proxy-suite-inbounds-listeners-name-tls-keyfile) + - [serverName](#services-proxy-suite-inbounds-listeners-name-tls-servername) + - [transport](#services-proxy-suite-inbounds-listeners-name-transport) + - [host](#services-proxy-suite-inbounds-listeners-name-transport-host) + - [mode](#services-proxy-suite-inbounds-listeners-name-transport-mode) + - [path](#services-proxy-suite-inbounds-listeners-name-transport-path) + - [serviceName](#services-proxy-suite-inbounds-listeners-name-transport-servicename) + - [type](#services-proxy-suite-inbounds-listeners-name-transport-type) + - [type](#services-proxy-suite-inbounds-listeners-name-type) + - [users](#services-proxy-suite-inbounds-listeners-name-users) + - item + - [name](#services-proxy-suite-inbounds-listeners-name-users-name) + - [password](#services-proxy-suite-inbounds-listeners-name-users-password) + - [passwordFile](#services-proxy-suite-inbounds-listeners-name-users-passwordfile) + - [uuid](#services-proxy-suite-inbounds-listeners-name-users-uuid) + - [uuidFile](#services-proxy-suite-inbounds-listeners-name-users-uuidfile) + - [via](#services-proxy-suite-inbounds-listeners-name-via) + - [xrayJson](#services-proxy-suite-inbounds-listeners-name-xrayjson) + - [openFirewall](#services-proxy-suite-inbounds-openfirewall) + - routing + - [blockPrivate](#services-proxy-suite-inbounds-routing-blockprivate) + - [blockRu](#services-proxy-suite-inbounds-routing-blockru) + - proxy + - [domains](#services-proxy-suite-inbounds-routing-proxy-domains) + - [geoips](#services-proxy-suite-inbounds-routing-proxy-geoips) + - [geosites](#services-proxy-suite-inbounds-routing-proxy-geosites) + - [ips](#services-proxy-suite-inbounds-routing-proxy-ips) + - [via](#services-proxy-suite-inbounds-routing-via) + - [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect) + - [serverAddress](#services-proxy-suite-inbounds-serveraddress) + - [shareLinks](#services-proxy-suite-inbounds-sharelinks) + - subscriptions + - [enable](#services-proxy-suite-inbounds-subscriptions-enable) + - [baseUrl](#services-proxy-suite-inbounds-subscriptions-baseurl) + - [group](#services-proxy-suite-inbounds-subscriptions-group) + + +## services\.proxy-suite\.inbounds\.enable + +Whether to enable server inbounds that accept proxy connections from outside\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.package + +XRay package serving the inbounds, whatever the client-side backend\. + +*Type:* +package + +*Default:* +proxy-suite’s ` xray ` (` pkgs/xray.nix `) + +*Example:* + +```nix +pkgs.xray +``` + + +## services\.proxy-suite\.inbounds\.listeners + +Listeners by tag\. + +*Type:* +attribute set of (submodule) + +*Default:* + +```nix +{ } +``` + +*Example:* + +```nix +{ + 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" ]; + }; + }; +} + +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.address + +Bound address\. A loopback address keeps the port closed in the firewall\. + +*Type:* +string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +"::" +``` + +*Example:* + +```nix +"127.0.0.1" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.flow + +VLESS flow; raw transport only\. + +*Type:* +null or value “xtls-rprx-vision” (singular enum) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"xtls-rprx-vision" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.jsonFile + +Runtime path to a raw XRay inbound (no share link); tag is overridden\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-inbound-vless.json" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.method + +Shadowsocks cipher\. 2022 ciphers take a base64 key of matching length as password\. + +*Type:* +string + +*Default:* + +```nix +"2022-blake3-aes-128-gcm" +``` + +*Example:* + +```nix +"aes-128-gcm" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.port + +Bound port\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +443 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality + +REALITY\. + +*Type:* +submodule + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.enable + +Enable REALITY\. Exclusive with tls\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.dest + +TLS 1\.3 + HTTP/2 server that unauthenticated probes are forwarded to\. + +*Type:* +string + +*Default:* + +```nix +"www.microsoft.com:443" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.privateKey + +x25519 private key\. Ends up in the Nix store; prefer privateKeyFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"gG1Yz..." +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.privateKeyFile + +Runtime path to the x25519 private key (` xray x25519 `)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-inbound-reality-key" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.publicKey + +x25519 public key, required for share links\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"jNXH..." +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.serverNames + +Accepted SNIs, served by dest\. The first goes into share links\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "www.microsoft.com" +] +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.reality\.shortIds + +Accepted short IDs (hex)\. The first goes into share links\. + +*Type:* +list of string + +*Default:* + +```nix +[ + "" +] +``` + +*Example:* + +```nix +[ + "0123abcd" +] +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.sharePort + +Port share links advertise, when something in front owns the public port\. Null uses port\. + +*Type:* +null or 16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +443 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.tls + +TLS termination\. + +*Type:* +submodule + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.tls\.enable + +Terminate TLS (always on for trojan)\. Exclusive with reality\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.tls\.alpn + +ALPN offered and put in share links\. \[ “h3” ] alone makes an xhttp listener UDP-only, so +a web server can keep the TCP port\. + +*Type:* +null or (list of (one of “h3”, “h2”, “http/1\.1”)) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +[ + "h3" +] +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.tls\.certificateFile + +Runtime path to the PEM certificate chain\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/var/lib/acme/example.com/fullchain.pem" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.tls\.keyFile + +Runtime path to the PEM private key\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/var/lib/acme/example.com/key.pem" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.tls\.serverName + +SNI in share links\. Defaults to inbounds\.serverAddress\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"example.com" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.transport + +Stream transport\. + +*Type:* +submodule + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.transport\.host + +Expected Host header (ws, httpupgrade, xhttp)\. Null accepts any\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"cdn.example.com" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.transport\.mode + +xhttp mode\. Null lets the client choose; behind an HTTP/1\.1 proxy use “packet-up”\. + +*Type:* +null or one of “auto”, “packet-up”, “stream-up”, “stream-one” + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"packet-up" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.transport\.path + +Request path (ws, httpupgrade, xhttp)\. + +*Type:* +string + +*Default:* + +```nix +"/" +``` + +*Example:* + +```nix +"/download" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.transport\.serviceName + +gRPC service name\. + +*Type:* +string + +*Default:* + +```nix +"" +``` + +*Example:* + +```nix +"GunService" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.transport\.type + +Stream transport\. “raw” is plain TCP, the usual choice for REALITY\. + +*Type:* +one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp” + +*Default:* + +```nix +"raw" +``` + +*Example:* + +```nix +"ws" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.type + +Protocol\. Set exactly one of type, xrayJson, or jsonFile\. + +*Type:* +null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http” + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"vless" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users + +Accepted accounts\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + { + uuidFile = "/run/secrets/proxy-inbound-uuid"; + } +] +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.name + +Account label: the share link’s name, and what subscriptions and stats group by\. + +*Type:* +string + +*Default:* + +```nix +"" +``` + +*Example:* + +```nix +"phone" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.password + +Password (trojan, shadowsocks, socks, http)\. Ends up in the Nix store; prefer passwordFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"hunter2" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.passwordFile + +Runtime path to the password\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-inbound-password" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.uuid + +UUID (vless, vmess)\. Ends up in the Nix store; prefer uuidFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"b831381d-6324-4d53-ad4f-8cda48b30811" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.uuidFile + +Runtime path to the UUID\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-inbound-uuid" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.via + +Egress, as in inbounds\.routing\.via\. Null inherits it\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"nl-vps" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.xrayJson + +Raw XRay inbound, built into the store; tag is overridden\. + +*Type:* +null or (attribute set) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +{ + protocol = "dokodemo-door"; + settings = { + port = 8080; + }; +} +``` + + +## services\.proxy-suite\.inbounds\.openFirewall + +Open every non-loopback listener port\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.routing\.blockPrivate + +Block private and loopback destinations, so clients cannot reach this host’s LAN or local services\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.routing\.blockRu + +Block Russian destinations (geosite “category-ru”, geoip “ru”)\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.routing\.proxy\.domains + +Domain suffixes to match\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "youtube.com" +] +``` + + +## services\.proxy-suite\.inbounds\.routing\.proxy\.geoips + +Geoip names to match (see geodata; the defaults are country codes only)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "us" +] +``` + + +## services\.proxy-suite\.inbounds\.routing\.proxy\.geosites + +Geosite names to match (see geodata)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "netflix" +] +``` + + +## services\.proxy-suite\.inbounds\.routing\.proxy\.ips + +IP CIDRs to match\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "1.1.1.0/24" +] +``` + + +## services\.proxy-suite\.inbounds\.routing\.via + +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\. + +*Type:* +string + +*Default:* + +```nix +"proxy" +``` + +*Example:* + +```nix +"direct" +``` + + +## services\.proxy-suite\.inbounds\.routing\.zapretDirect + +Send zapret’s hostlist destinations direct, so this host’s zapret unblocks them (default via only)\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.serverAddress + +Public address clients connect to, used in share links\. Null detects the uplink IPv4\. + +*Type:* +null or string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"vpn.example.com" +``` + + +## services\.proxy-suite\.inbounds\.shareLinks + +Write client share links for ` proxy-ctl inbounds link ` (root and userControl\.group only)\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.subscriptions\.enable + +Write one subscription file per user (their links from every listener, base64) to +/run/proxy-suite-inbounds/subscriptions/\\. Serve that directory with a web server; +see the README\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.inbounds\.subscriptions\.baseUrl + +URL the subscription directory is served at, for ` proxy-ctl inbounds sub `\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"https://vpn.example.com/sub" +``` + + +## services\.proxy-suite\.inbounds\.subscriptions\.group + +Group allowed to read the subscription files: the web server serving them\. + +*Type:* +string + +*Default:* + +```nix +"nginx" +``` + +*Example:* + +```nix +"caddy" +``` diff --git a/docs/options/index.md b/docs/options/index.md new file mode 100644 index 0000000..7c5372f --- /dev/null +++ b/docs/options/index.md @@ -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 + --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 + --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= +## services\.proxy-suite\.enable + +Whether to enable proxy-suite\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` diff --git a/docs/options/perAppRouting.md b/docs/options/perAppRouting.md new file mode 100644 index 0000000..caa5828 --- /dev/null +++ b/docs/options/perAppRouting.md @@ -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) + + +## services\.proxy-suite\.perAppRouting\.enable + +Whether to enable per-app routing (` proxy-ctl apps run `)\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## 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 +``` + + +## services\.proxy-suite\.perAppRouting\.profiles + +Profiles for ` proxy-ctl apps run -- `\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + { + name = "steam-browser"; + route = "proxychains"; + } +] +``` + + +## services\.proxy-suite\.perAppRouting\.profiles\.\*\.name + +Profile name, unique\. + +*Type:* +string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$ + +*Example:* + +```nix +"steam-browser" +``` + + +## 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" +``` + + +## 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 +``` + + +## services\.proxy-suite\.perAppRouting\.proxychains\.proxyDns + +Resolve DNS through the proxy (proxy_dns)\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.perAppRouting\.proxychains\.quiet + +Silence proxychains (quiet_mode)\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.perAppRouting\.tproxy\.enable + +Whether to enable the per-app TProxy backend\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.perAppRouting\.tproxy\.fwmark + +Mark that steers wrapped apps into routeTable\. + +*Type:* +signed integer + +*Default:* + +```nix +17 +``` + + +## 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" +] +``` + + +## services\.proxy-suite\.perAppRouting\.tproxy\.routeTable + +Policy-routing table of the per-app TProxy\. + +*Type:* +signed integer + +*Default:* + +```nix +102 +``` + + +## services\.proxy-suite\.perAppRouting\.tun\.enable + +Whether to enable the per-app TUN backend\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.perAppRouting\.tun\.address + +Per-app TUN interface address (CIDR)\. + +*Type:* +string + +*Default:* + +```nix +"172.20.0.1/30" +``` + + +## services\.proxy-suite\.perAppRouting\.tun\.fwmark + +Mark that steers wrapped apps into routeTable\. + +*Type:* +signed integer + +*Default:* + +```nix +16 +``` + + +## services\.proxy-suite\.perAppRouting\.tun\.interface + +Per-app TUN interface name\. + +*Type:* +string + +*Default:* + +```nix +"psperapptun0" +``` + + +## 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" +] +``` + + +## services\.proxy-suite\.perAppRouting\.tun\.mtu + +Per-app TUN interface MTU\. + +*Type:* +signed integer + +*Default:* + +```nix +1400 +``` + + +## services\.proxy-suite\.perAppRouting\.tun\.routeTable + +Policy-routing table of the per-app TUN\. + +*Type:* +signed integer + +*Default:* + +```nix +101 +``` + + +## 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 +``` + + +## services\.proxy-suite\.perAppRouting\.zapret\.filterMark + +Mark bit that selects wrapped app traffic\. + +*Type:* +signed integer + +*Default:* + +```nix +268435456 +``` + + +## services\.proxy-suite\.perAppRouting\.zapret\.qnum + +NFQUEUE number\. Must differ from the global instance’s\. + +*Type:* +signed integer + +*Default:* + +```nix +201 +``` diff --git a/docs/options/proxy.md b/docs/options/proxy.md new file mode 100644 index 0000000..a700f06 --- /dev/null +++ b/docs/options/proxy.md @@ -0,0 +1,1612 @@ +# services.proxy-suite.proxy + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- proxy + - [enable](#services-proxy-suite-proxy-enable) + - autoProxy + - [enable](#services-proxy-suite-proxy-autoproxy-enable) + - [exclude](#services-proxy-suite-proxy-autoproxy-exclude) + - [interval](#services-proxy-suite-proxy-autoproxy-interval) + - [maxExits](#services-proxy-suite-proxy-autoproxy-maxexits) + - [probeBasePort](#services-proxy-suite-proxy-autoproxy-probebaseport) + - [probesPerRun](#services-proxy-suite-proxy-autoproxy-probesperrun) + - [slowBelowKiBps](#services-proxy-suite-proxy-autoproxy-slowbelowkibps) + - [ttlDays](#services-proxy-suite-proxy-autoproxy-ttldays) + - [autostart](#services-proxy-suite-proxy-autostart) + - [backend](#services-proxy-suite-proxy-backend) + - dns + - [local](#services-proxy-suite-proxy-dns-local) + - [address](#services-proxy-suite-proxy-dns-local-address) + - [port](#services-proxy-suite-proxy-dns-local-port) + - [type](#services-proxy-suite-proxy-dns-local-type) + - [remote](#services-proxy-suite-proxy-dns-remote) + - [address](#services-proxy-suite-proxy-dns-remote-address) + - [port](#services-proxy-suite-proxy-dns-remote-port) + - [type](#services-proxy-suite-proxy-dns-remote-type) + - listener + - [address](#services-proxy-suite-proxy-listener-address) + - auth + - [password](#services-proxy-suite-proxy-listener-auth-password) + - [passwordFile](#services-proxy-suite-proxy-listener-auth-passwordfile) + - [username](#services-proxy-suite-proxy-listener-auth-username) + - [port](#services-proxy-suite-proxy-listener-port) + - [outbounds](#services-proxy-suite-proxy-outbounds) + - item + - [backend](#services-proxy-suite-proxy-outbounds-backend) + - routing + - [domains](#services-proxy-suite-proxy-outbounds-routing-domains) + - [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips) + - [geosites](#services-proxy-suite-proxy-outbounds-routing-geosites) + - [ips](#services-proxy-suite-proxy-outbounds-routing-ips) + - [singBoxJson](#services-proxy-suite-proxy-outbounds-singboxjson) + - [tag](#services-proxy-suite-proxy-outbounds-tag) + - [url](#services-proxy-suite-proxy-outbounds-url) + - [urlFile](#services-proxy-suite-proxy-outbounds-urlfile) + - [xrayJson](#services-proxy-suite-proxy-outbounds-xrayjson) + - routing + - block + - [domains](#services-proxy-suite-proxy-routing-block-domains) + - [geoips](#services-proxy-suite-proxy-routing-block-geoips) + - [geosites](#services-proxy-suite-proxy-routing-block-geosites) + - [ips](#services-proxy-suite-proxy-routing-block-ips) + - [default](#services-proxy-suite-proxy-routing-default) + - direct + - [domains](#services-proxy-suite-proxy-routing-direct-domains) + - [geoips](#services-proxy-suite-proxy-routing-direct-geoips) + - [geosites](#services-proxy-suite-proxy-routing-direct-geosites) + - [ips](#services-proxy-suite-proxy-routing-direct-ips) + - [directRu](#services-proxy-suite-proxy-routing-directru) + - proxy + - [domains](#services-proxy-suite-proxy-routing-proxy-domains) + - [geoips](#services-proxy-suite-proxy-routing-proxy-geoips) + - [geosites](#services-proxy-suite-proxy-routing-proxy-geosites) + - [ips](#services-proxy-suite-proxy-routing-proxy-ips) + - [rules](#services-proxy-suite-proxy-routing-rules) + - item + - [domains](#services-proxy-suite-proxy-routing-rules-domains) + - [geoips](#services-proxy-suite-proxy-routing-rules-geoips) + - [geosites](#services-proxy-suite-proxy-routing-rules-geosites) + - [ips](#services-proxy-suite-proxy-routing-rules-ips) + - [outbound](#services-proxy-suite-proxy-routing-rules-outbound) + - [selection](#services-proxy-suite-proxy-selection) + - singBox + - [package](#services-proxy-suite-proxy-singbox-package) + - [clashApiPort](#services-proxy-suite-proxy-singbox-clashapiport) + - [subscriptionUpdateInterval](#services-proxy-suite-proxy-subscriptionupdateinterval) + - [subscriptions](#services-proxy-suite-proxy-subscriptions) + - item + - [tag](#services-proxy-suite-proxy-subscriptions-tag) + - [url](#services-proxy-suite-proxy-subscriptions-url) + - [urlFile](#services-proxy-suite-proxy-subscriptions-urlfile) + - tproxy + - [enable](#services-proxy-suite-proxy-tproxy-enable) + - [fwmark](#services-proxy-suite-proxy-tproxy-fwmark) + - [localSubnets](#services-proxy-suite-proxy-tproxy-localsubnets) + - [port](#services-proxy-suite-proxy-tproxy-port) + - [proxyMark](#services-proxy-suite-proxy-tproxy-proxymark) + - [routeTable](#services-proxy-suite-proxy-tproxy-routetable) + - tun + - [enable](#services-proxy-suite-proxy-tun-enable) + - [address](#services-proxy-suite-proxy-tun-address) + - [interface](#services-proxy-suite-proxy-tun-interface) + - [mtu](#services-proxy-suite-proxy-tun-mtu) + - urlTest + - [interval](#services-proxy-suite-proxy-urltest-interval) + - [tolerance](#services-proxy-suite-proxy-urltest-tolerance) + - [url](#services-proxy-suite-proxy-urltest-url) + - xray + - [package](#services-proxy-suite-proxy-xray-package) + + +## services\.proxy-suite\.proxy\.enable + +Whether to enable the local proxy\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.enable + +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\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.exclude + +Domain suffixes never probed or auto-routed\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "internal.example" +] +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.interval + +Time between probe runs\. ` proxy-ctl proxy auto learn ` does not wait for it\. + +*Type:* +string + +*Default:* + +```nix +"10m" +``` + +*Example:* + +```nix +"30m" +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.maxExits + +Most exits probed, direct included\. The first round tries one exit per network (AS), a +second round the rest\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +12 +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.probeBasePort + +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\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +18540 +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.probesPerRun + +Most destinations probed per run; the rest wait in a backlog, most-dialled first\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +200 +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.slowBelowKiBps + +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”\. + +*Type:* +unsigned integer, meaning >=0 + +*Default:* + +```nix +150 +``` + +*Example:* + +```nix +0 +``` + + +## services\.proxy-suite\.proxy\.autoProxy\.ttlDays + +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 ` re-probes one destination right away\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +30 +``` + + +## services\.proxy-suite\.proxy\.autostart + +Transparent mode started at boot, or null for neither\. The mode named here must +also be enabled (proxy\.tun\.enable or proxy\.tproxy\.enable)\. + +*Type:* +null or one of “tun”, “tproxy” + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"tun" +``` + + +## services\.proxy-suite\.proxy\.backend + +Proxy backend\. “hybrid” runs sing-box in front and hands XRay-only outbounds +(XHTTP, ECH) to XRay\. + +*Type:* +one of “sing-box”, “xray”, “hybrid” + +*Default:* + +```nix +"sing-box" +``` + +*Example:* + +```nix +"hybrid" +``` + + +## services\.proxy-suite\.proxy\.dns\.local + +Resolver for direct traffic and the default domain resolver\. Goes through the proxy in global TUN mode\. + +*Type:* +submodule + +*Default:* + +```nix +{ + address = "1.1.1.1"; + port = 53; + type = "udp"; +} +``` + +*Example:* + +```nix +{ + address = "9.9.9.9"; + type = "tcp"; +} +``` + + +## services\.proxy-suite\.proxy\.dns\.local\.address + +Resolver address\. + +*Type:* +string matching the pattern \.+ + +*Example:* + +```nix +"1.1.1.1" +``` + + +## services\.proxy-suite\.proxy\.dns\.local\.port + +Resolver port\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +53 +``` + + +## services\.proxy-suite\.proxy\.dns\.local\.type + +DNS transport\. + +*Type:* +one of “udp”, “tcp”, “tls” + +*Default:* + +```nix +"udp" +``` + + +## services\.proxy-suite\.proxy\.dns\.remote + +Resolver used through the proxy; the DNS default when proxy\.routing\.default is proxy\. + +*Type:* +submodule + +*Default:* + +```nix +{ + address = "1.1.1.1"; + port = 53; + type = "udp"; +} +``` + +*Example:* + +```nix +{ + address = "1.1.1.1"; + port = 853; + type = "tls"; +} +``` + + +## services\.proxy-suite\.proxy\.dns\.remote\.address + +Resolver address\. + +*Type:* +string matching the pattern \.+ + +*Example:* + +```nix +"1.1.1.1" +``` + + +## services\.proxy-suite\.proxy\.dns\.remote\.port + +Resolver port\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +53 +``` + + +## services\.proxy-suite\.proxy\.dns\.remote\.type + +DNS transport\. + +*Type:* +one of “udp”, “tcp”, “tls” + +*Default:* + +```nix +"udp" +``` + + +## services\.proxy-suite\.proxy\.listener\.address + +Bind address of the local SOCKS5/HTTP proxy\. Use “0\.0\.0\.0” only to expose it to the network\. + +*Type:* +string + +*Default:* + +```nix +"127.0.0.1" +``` + + +## services\.proxy-suite\.proxy\.listener\.auth\.password + +Inline local proxy password\. Ends up in the Nix store; prefer passwordFile\. + +*Type:* +null or string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"change-me" +``` + + +## services\.proxy-suite\.proxy\.listener\.auth\.passwordFile + +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\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-suite-local-proxy-password" +``` + + +## services\.proxy-suite\.proxy\.listener\.auth\.username + +Username the local proxy requires\. Set together with password or passwordFile\. + +*Type:* +null or string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"proxy-user" +``` + + +## services\.proxy-suite\.proxy\.listener\.port + +Port of the local SOCKS5/HTTP proxy\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +1080 +``` + + +## services\.proxy-suite\.proxy\.outbounds + +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\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + { + tag = "de-vps"; + urlFile = "/run/secrets/proxy-de-url"; + } + { + tag = "nl-vps"; + url = "hy2://password@example.com:443?sni=example.com"; + } +] +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.backend + +Backend for this outbound when both run\. “auto” prefers sing-box and falls back to XRay +for XRay-only transports (XHTTP, ECH)\. + +*Type:* +one of “auto”, “sing-box”, “xray” + +*Default:* + +```nix +"auto" +``` + +*Example:* + +```nix +"xray" +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.domains + +Domain suffixes to match\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "youtube.com" +] +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.geoips + +Geoip names to match (see geodata; the defaults are country codes only)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "us" +] +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.geosites + +Geosite names to match (see geodata)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "netflix" +] +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.ips + +IP CIDRs to match\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "1.1.1.0/24" +] +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.singBoxJson + +Raw sing-box outbound (sing-box backend); tag is overridden\. + +*Type:* +null or (attribute set) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +{ + server = "example.com"; + server_port = 443; + type = "vless"; +} +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.tag + +Outbound tag, for routing rules and selection\. + +*Type:* +string + +*Example:* + +```nix +"vps-de" +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.url + +Proxy URL\. Ends up in the Nix store; prefer urlFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"hy2://password@example.com:443?sni=example.com" +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.urlFile + +Runtime path to the proxy URL\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/my-proxy-url" +``` + + +## services\.proxy-suite\.proxy\.outbounds\.\*\.xrayJson + +Raw XRay outbound (XRay backend); tag is overridden\. + +*Type:* +null or (attribute set) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +{ + protocol = "vless"; + settings = { + address = "example.com"; + }; +} +``` + + +## services\.proxy-suite\.proxy\.routing\.block\.domains + +Domain suffixes blocked\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "ads.example.com" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.block\.geoips + +Geoip names blocked\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "cn" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.block\.geosites + +Geosite names blocked\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "category-ads-all" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.block\.ips + +IP CIDRs blocked\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "203.0.113.0/24" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.default + +Where traffic no routing rule matches goes\. + +*Type:* +one of “proxy”, “direct” + +*Default:* + +```nix +"proxy" +``` + +*Example:* + +```nix +"direct" +``` + + +## services\.proxy-suite\.proxy\.routing\.direct\.domains + +Domain suffixes sent direct\. zapret hostlists join them when zapret\.directSync\.enable is on\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "internal.example" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.direct\.geoips + +Geoip names sent direct\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "ru" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.direct\.geosites + +Geosite names sent direct\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "category-ru" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.direct\.ips + +IP CIDRs sent direct\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "10.10.0.0/16" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.directRu + +Send geosite “category-ru” and geoip “ru” direct\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.proxy\.routing\.proxy\.domains + +Domain suffixes sent through the proxy\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "youtube.com" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.proxy\.geoips + +Geoip names sent through the proxy\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "us" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.proxy\.geosites + +Geosite names sent through the proxy\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "netflix" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.proxy\.ips + +IP CIDRs sent through the proxy\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "1.1.1.0/24" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.rules + +Rules checked before the proxy/direct/block lists, in order; the first match wins\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + { + geosites = [ + "netflix" + ]; + outbound = "vps-de"; + } + { + domains = [ + "internal.corp" + ]; + outbound = "direct"; + } +] +``` + + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.domains + +Domain suffixes to match\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "youtube.com" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.geoips + +Geoip names to match (see geodata; the defaults are country codes only)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "us" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.geosites + +Geosite names to match (see geodata)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "netflix" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.ips + +IP CIDRs to match\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "1.1.1.0/24" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.outbound + +Outbound tag, or “proxy”, “direct”, “block”\. With selection = “first” every proxy tag means “proxy”\. + +*Type:* +string + +*Example:* + +```nix +"vps-de" +``` + + +## services\.proxy-suite\.proxy\.selection + +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\. + +*Type:* +one of “first”, “selector”, “urltest” + +*Default:* + +```nix +"first" +``` + +*Example:* + +```nix +"urltest" +``` + + +## services\.proxy-suite\.proxy\.singBox\.package + +sing-box package, used when backend is “sing-box” or “hybrid”\. + +*Type:* +package + +*Default:* +` sing-box ` from proxy-suite’s own ` nixpkgs ` input + +*Example:* + +```nix +pkgs.sing-box +``` + + +## services\.proxy-suite\.proxy\.singBox\.clashApiPort + +Port of sing-box’s Clash API, used with selection “selector” or “urltest”\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +9090 +``` + + +## services\.proxy-suite\.proxy\.subscriptionUpdateInterval + +How often subscriptions are refreshed (systemd time span)\. + +*Type:* +string + +*Default:* + +```nix +"1d" +``` + +*Example:* + +```nix +"6h" +``` + + +## services\.proxy-suite\.proxy\.subscriptions + +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\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + { + tag = "private"; + urlFile = "/run/secrets/private-sub-url"; + } +] +``` + + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.tag + +Unique name; prefixes the tags of its outbounds and names its cache file\. + +*Type:* +string matching the pattern ^\[A-Za-z0-9]\[A-Za-z0-9\._-]\*$ + +*Example:* + +```nix +"community-list" +``` + + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.url + +Subscription URL\. Ends up in the Nix store; prefer urlFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"https://example.com/sub/token123" +``` + + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.urlFile + +Runtime path to the subscription URL\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-subscription-url" +``` + + +## services\.proxy-suite\.proxy\.tproxy\.enable + +Whether to enable global TProxy mode (proxy-suite-tproxy)\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.proxy\.tproxy\.fwmark + +Mark of intercepted packets, routed through routeTable\. + +*Type:* +signed integer + +*Default:* + +```nix +1 +``` + + +## services\.proxy-suite\.proxy\.tproxy\.localSubnets + +Subnets that bypass interception (DNS excepted): your LAN, VM bridges\. + +*Type:* +list of string + +*Default:* + +```nix +[ + "192.168.0.0/16" +] +``` + +*Example:* + +```nix +[ + "192.168.0.0/16" + "10.0.0.0/8" +] +``` + + +## services\.proxy-suite\.proxy\.tproxy\.port + +Port of the TProxy inbound\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +1085 +``` + + +## services\.proxy-suite\.proxy\.tproxy\.proxyMark + +Mark of the backend’s own traffic, so it is not intercepted again\. + +*Type:* +signed integer + +*Default:* + +```nix +2 +``` + + +## services\.proxy-suite\.proxy\.tproxy\.routeTable + +Policy-routing table for intercepted traffic\. + +*Type:* +signed integer + +*Default:* + +```nix +100 +``` + + +## services\.proxy-suite\.proxy\.tun\.enable + +Whether to enable global TUN mode (proxy-suite-tun)\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.proxy\.tun\.address + +TUN interface address (CIDR)\. + +*Type:* +string + +*Default:* + +```nix +"172.19.0.1/30" +``` + + +## services\.proxy-suite\.proxy\.tun\.interface + +TUN interface name\. + +*Type:* +string + +*Default:* + +```nix +"singtun0" +``` + + +## services\.proxy-suite\.proxy\.tun\.mtu + +TUN interface MTU\. + +*Type:* +signed integer + +*Default:* + +```nix +1400 +``` + + +## services\.proxy-suite\.proxy\.urlTest\.interval + +How often outbounds are re-tested (Go duration)\. + +*Type:* +string + +*Default:* + +```nix +"3m" +``` + +*Example:* + +```nix +"1m" +``` + + +## services\.proxy-suite\.proxy\.urlTest\.tolerance + +Milliseconds a faster outbound must win by to replace the current one (sing-box only)\. + +*Type:* +signed integer + +*Default:* + +```nix +50 +``` + +*Example:* + +```nix +100 +``` + + +## services\.proxy-suite\.proxy\.urlTest\.url + +URL fetched through each outbound to rank them\. Pick one blocked in your region\. + +*Type:* +string + +*Default:* + +```nix +"https://www.gstatic.com/generate_204" +``` + +*Example:* + +```nix +"https://telegram.org" +``` + + +## services\.proxy-suite\.proxy\.xray\.package + +XRay package, used when backend is “xray” or “hybrid”\. + +*Type:* +package + +*Default:* +proxy-suite’s ` xray ` (` pkgs/xray.nix `) + +*Example:* + +```nix +pkgs.xray +``` diff --git a/docs/options/sshProxy.md b/docs/options/sshProxy.md new file mode 100644 index 0000000..adfc184 --- /dev/null +++ b/docs/options/sshProxy.md @@ -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) + + +## services\.proxy-suite\.sshProxy\.enable + +Whether to enable an SSH dynamic SOCKS5 tunnel\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## 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 +``` + + +## 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" +``` + + +## services\.proxy-suite\.sshProxy\.extraArgs + +Extra OpenSSH arguments\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "-J" + "jump.example.com" +] +``` + + +## 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..." +] +``` + + +## 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" +``` + + +## 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" +``` + + +## 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" +``` + + +## services\.proxy-suite\.sshProxy\.listener\.address + +Address of the OpenSSH SOCKS5 listener\. + +*Type:* +string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +"127.0.0.1" +``` + + +## 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 +``` + + +## services\.proxy-suite\.sshProxy\.server\.host + +SSH server\. + +*Type:* +null or string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"ssh.example.com" +``` + + +## services\.proxy-suite\.sshProxy\.server\.port + +SSH server port\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +22 +``` + + +## services\.proxy-suite\.sshProxy\.server\.user + +SSH login user\. + +*Type:* +null or string matching the pattern \[^\[:space:]]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"root" +``` + + +## 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" +``` + + +## services\.proxy-suite\.sshProxy\.strictHostKeyChecking + +OpenSSH host key policy\. + +*Type:* +one of “yes”, “accept-new”, “no” + +*Default:* + +```nix +"accept-new" +``` + +*Example:* + +```nix +"yes" +``` diff --git a/docs/options/tgWsProxy.md b/docs/options/tgWsProxy.md new file mode 100644 index 0000000..0343366 --- /dev/null +++ b/docs/options/tgWsProxy.md @@ -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) + + +## services\.proxy-suite\.tgWsProxy\.enable + +Whether to enable the Telegram MTProto WebSocket proxy\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.tgWsProxy\.bufferKiB + +Socket buffer size, in KiB\. + +*Type:* +integer between 4 and 2147483647 (both inclusive) + +*Default:* + +```nix +256 +``` + + +## 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 +``` + + +## services\.proxy-suite\.tgWsProxy\.cloudflare\.domains + +Cloudflare-proxied domains for WebSocket fallback\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "cdn.example.com" +] +``` + + +## services\.proxy-suite\.tgWsProxy\.cloudflare\.fallback + +Fall back to Cloudflare when direct WebSocket fails\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.tgWsProxy\.cloudflare\.workerDomains + +Cloudflare Worker domains, tried first\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "worker.example.com" +] +``` + + +## 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"; +} +``` + + +## 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" +``` + + +## services\.proxy-suite\.tgWsProxy\.fwmark + +Packet mark bypassTransparentProxy uses\. + +*Type:* +signed integer + +*Default:* + +```nix +4 +``` + + +## services\.proxy-suite\.tgWsProxy\.listener\.address + +Bind address\. + +*Type:* +string + +*Default:* + +```nix +"127.0.0.1" +``` + + +## services\.proxy-suite\.tgWsProxy\.listener\.port + +Listen port\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +1443 +``` + + +## 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" +``` + + +## services\.proxy-suite\.tgWsProxy\.log\.keep + +Rotated logs kept\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +1 +``` + + +## 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 +``` + + +## services\.proxy-suite\.tgWsProxy\.log\.verbose + +Debug logging\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.tgWsProxy\.poolSize + +WebSocket pool size per DC; 0 disables pooling\. + +*Type:* +unsigned integer, meaning >=0 + +*Default:* + +```nix +4 +``` + + +## services\.proxy-suite\.tgWsProxy\.proxyProtocol + +Accept a PROXY protocol v1 header from a fronting reverse proxy\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## 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" +``` + + +## 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" +``` diff --git a/docs/options/tray.md b/docs/options/tray.md new file mode 100644 index 0000000..359c1b8 --- /dev/null +++ b/docs/options/tray.md @@ -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) + + +## services\.proxy-suite\.tray\.enable + +Whether to enable the system tray indicator\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.tray\.autostart + +Start the tray in graphical sessions (XDG autostart)\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.tray\.pollInterval + +Status refresh interval, in seconds\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +5 +``` diff --git a/docs/options/userControl.md b/docs/options/userControl.md new file mode 100644 index 0000000..b0d78b5 --- /dev/null +++ b/docs/options/userControl.md @@ -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) + + +## 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" +] +``` + + +## 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" +``` diff --git a/docs/options/zapret.md b/docs/options/zapret.md new file mode 100644 index 0000000..aec923a --- /dev/null +++ b/docs/options/zapret.md @@ -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) + + +## services\.proxy-suite\.zapret\.enable + +Whether to enable zapret DPI bypass\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## 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 +``` + + +## services\.proxy-suite\.zapret\.cidrExemption\.cidrs + +Exempted subnets\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "192.168.123.0/24" +] +``` + + +## services\.proxy-suite\.zapret\.directSync\.enable + +Add zapret’s domain hostlists to proxy\.routing\.direct\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.zapret\.directSync\.upstreamIps + +Add zapret’s upstream ipsets to proxy\.routing\.direct\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## 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 +``` + + +## 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" +``` + + +## 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)" +``` + + +## services\.proxy-suite\.zapret\.zapret-discord-youtube\.domains + +Extra domains to bypass\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "youtube.com" +] +``` + + +## services\.proxy-suite\.zapret\.zapret-discord-youtube\.excludeDomains + +Domains never bypassed\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "music.youtube.com" +] +``` + + +## 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" +] +``` + + +## 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" +``` + + +## 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"; + } +] +``` + + +## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.enableDirectSync + +Include these domains in zapret\.directSync\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## 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)" +``` + + +## 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" +] +``` + + +## 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" +] +``` + + +## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.domains + +Domains in this hostlist\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "example.com" +] +``` + + +## 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" +] +``` + + +## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.name + +Hostlist name (hostlists/list-\\.txt)\. + +*Type:* +string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$ + +*Example:* + +```nix +"cloudflare" +``` + + +## 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" +] +``` + + +## 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" +``` + + +## services\.proxy-suite\.zapret\.zapret-discord-youtube\.includeExtraUpstreamLists + +Also use the upstream instagram, soundcloud and twitter lists\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## 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" +] +``` + + +## 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 +``` + + +## 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 +``` + + +## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failThreshold + +Failures before a host is learned\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +3 +``` + + +## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failTime + +Seconds allowed between two failures before the count resets\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +300 +``` + + +## 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 +``` + + +## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransMaxseq + +Outgoing sequence number past which failure detection stops\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +32768 +``` + + +## 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 +``` + + +## 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 +``` + + +## 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 +``` + + +## 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 +``` + + +## services\.proxy-suite\.zapret\.zapret2\.blobs + +Fake payloads by name (blob=\): 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"; +} +``` + + +## 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" +] +``` + + +## 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" +] +``` + + +## services\.proxy-suite\.zapret\.zapret2\.ipv6 + +Intercept IPv6 as well as IPv4\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## 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" +``` + + +## 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" +``` + + +## services\.proxy-suite\.zapret\.zapret2\.profiles + +nfqws2 profiles, joined with --new; first match wins\. \ expands to the hostlist +arguments, \ 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 + --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 + --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= --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld" +] +``` diff --git a/flake.nix b/flake.nix index 3aea2fb..df841c4 100644 --- a/flake.nix +++ b/flake.nix @@ -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; diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 53ac3e2..f06cd15 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -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"; } ]; } diff --git a/modules/proxy-suite/autoproxy-render.nix b/modules/proxy-suite/autoproxy-render.nix new file mode 100644 index 0000000..b5dba8f --- /dev/null +++ b/modules/proxy-suite/autoproxy-render.nix @@ -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 +'' diff --git a/modules/proxy-suite/autoproxy-slow-judge.jq b/modules/proxy-suite/autoproxy-slow-judge.jq new file mode 100644 index 0000000..fb2c749 --- /dev/null +++ b/modules/proxy-suite/autoproxy-slow-judge.jq @@ -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))) diff --git a/modules/proxy-suite/autoproxy-slow-sample.jq b/modules/proxy-suite/autoproxy-slow-sample.jq new file mode 100644 index 0000000..0d4caaf --- /dev/null +++ b/modules/proxy-suite/autoproxy-slow-sample.jq @@ -0,0 +1,19 @@ +# Slurped Clash API /connections snapshots, a second apart, in; per host and exit that +# moved at least $min bytes: hostexitslow|fastpeak. 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)" diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix new file mode 100644 index 0000000..80628b7 --- /dev/null +++ b/modules/proxy-suite/autoproxy.nix @@ -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". + # 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; + }; + }; +} diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index e5dc58c..9bd0ed3 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -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; }; diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index a8709a5..4a7567a 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -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; diff --git a/modules/proxy-suite/config-templates/xray.nix b/modules/proxy-suite/config-templates/xray.nix index 00970a8..b9a71c5 100644 --- a/modules/proxy-suite/config-templates/xray.nix +++ b/modules/proxy-suite/config-templates/xray.nix @@ -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; } diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 3ee7b76..357b71d 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -55,7 +55,7 @@ let xrayJson jsonFile ; - listen = ib.listener.listenAddress; + listen = ib.listener.address; }) derived.proxyInbounds; }; diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index a99afe0..9250190 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -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 + ; + } + )) + ] + )) + ]; } diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index b0db7fb..579a070 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -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 diff --git a/modules/proxy-suite/inbound-stats-add.jq b/modules/proxy-suite/inbound-stats-add.jq new file mode 100644 index 0000000..00ccf05 --- /dev/null +++ b/modules/proxy-suite/inbound-stats-add.jq @@ -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": {"": {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"))))) diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index 54ed93f..1c2918e 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -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. diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix index dbb6813..4167d27 100644 --- a/modules/proxy-suite/options/amnezia-wg.nix +++ b/modules/proxy-suite/options/amnezia-wg.nix @@ -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."; }; diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index a8e30b2..d0d3d2d 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -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"; } diff --git a/modules/proxy-suite/options/geodata.nix b/modules/proxy-suite/options/geodata.nix new file mode 100644 index 0000000..c18dd44 --- /dev/null +++ b/modules/proxy-suite/options/geodata.nix @@ -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."; + }; + }; + }; +} diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix new file mode 100644 index 0000000..6a5d1d6 --- /dev/null +++ b/modules/proxy-suite/options/inbounds.nix @@ -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/. 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" ]; + }; + }; + } + ''; + }; + }; +} diff --git a/modules/proxy-suite/options/legacy-sing-box.nix b/modules/proxy-suite/options/legacy-sing-box.nix deleted file mode 100644 index bbe67e2..0000000 --- a/modules/proxy-suite/options/legacy-sing-box.nix +++ /dev/null @@ -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; }) - ]; - }; -} diff --git a/modules/proxy-suite/options/other.nix b/modules/proxy-suite/options/other.nix deleted file mode 100644 index 96a5a0c..0000000 --- a/modules/proxy-suite/options/other.nix +++ /dev/null @@ -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; -} diff --git a/modules/proxy-suite/options/other/tg-ws-proxy.nix b/modules/proxy-suite/options/other/tg-ws-proxy.nix deleted file mode 100644 index 5390a6c..0000000 --- a/modules/proxy-suite/options/other/tg-ws-proxy.nix +++ /dev/null @@ -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; - }; - }; -} diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index ae41b27..be5d0b7 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -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 -- ` available - without defining the profile manually, and similarly exposes - `proxy-ctl wrap tun -- ` or - `proxy-ctl wrap tproxy -- ` or - `proxy-ctl wrap zapret -- ` 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 -- `."; 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."; + }; }; } diff --git a/modules/proxy-suite/options/proxy-dns.nix b/modules/proxy-suite/options/proxy-dns.nix new file mode 100644 index 0000000..513cbd1 --- /dev/null +++ b/modules/proxy-suite/options/proxy-dns.nix @@ -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; + }; + }; + }; +} diff --git a/modules/proxy-suite/options/proxy-inbounds.nix b/modules/proxy-suite/options/proxy-inbounds.nix deleted file mode 100644 index c5e1fc9..0000000 --- a/modules/proxy-suite/options/proxy-inbounds.nix +++ /dev/null @@ -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" ]; - }; - }; - } - ''; - }; - }; -} diff --git a/modules/proxy-suite/options/proxy-outbounds.nix b/modules/proxy-suite/options/proxy-outbounds.nix new file mode 100644 index 0000000..fed1949 --- /dev/null +++ b/modules/proxy-suite/options/proxy-outbounds.nix @@ -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; + }; + }; + }; +} diff --git a/modules/proxy-suite/options/proxy-routing.nix b/modules/proxy-suite/options/proxy-routing.nix new file mode 100644 index 0000000..afe627a --- /dev/null +++ b/modules/proxy-suite/options/proxy-routing.nix @@ -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" ]; + } + ]; + }; + }; +} diff --git a/modules/proxy-suite/options/proxy-tproxy.nix b/modules/proxy-suite/options/proxy-tproxy.nix new file mode 100644 index 0000000..121545b --- /dev/null +++ b/modules/proxy-suite/options/proxy-tproxy.nix @@ -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" + ]; + }; + }; +} diff --git a/modules/proxy-suite/options/proxy-tun.nix b/modules/proxy-suite/options/proxy-tun.nix new file mode 100644 index 0000000..4873b2c --- /dev/null +++ b/modules/proxy-suite/options/proxy-tun.nix @@ -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."; + }; + }; +} diff --git a/modules/proxy-suite/options/proxy.nix b/modules/proxy-suite/options/proxy.nix new file mode 100644 index 0000000..fbbba3d --- /dev/null +++ b/modules/proxy-suite/options/proxy.nix @@ -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 ` 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".''; + }; + }; + }; +} diff --git a/modules/proxy-suite/options/removed.nix b/modules/proxy-suite/options/removed.nix new file mode 100644 index 0000000..821ce2b --- /dev/null +++ b/modules/proxy-suite/options/removed.nix @@ -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; +} diff --git a/modules/proxy-suite/options/sing-box-dns.nix b/modules/proxy-suite/options/sing-box-dns.nix deleted file mode 100644 index 0818b5c..0000000 --- a/modules/proxy-suite/options/sing-box-dns.nix +++ /dev/null @@ -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; - }; - }; - }; -} diff --git a/modules/proxy-suite/options/sing-box-outbounds.nix b/modules/proxy-suite/options/sing-box-outbounds.nix deleted file mode 100644 index 9c77608..0000000 --- a/modules/proxy-suite/options/sing-box-outbounds.nix +++ /dev/null @@ -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//.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"; - }; - }; - }; -} diff --git a/modules/proxy-suite/options/sing-box-routing.nix b/modules/proxy-suite/options/sing-box-routing.nix deleted file mode 100644 index a8cfbc1..0000000 --- a/modules/proxy-suite/options/sing-box-routing.nix +++ /dev/null @@ -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" ]; - } - ]; - }; - }; -} diff --git a/modules/proxy-suite/options/sing-box-tproxy.nix b/modules/proxy-suite/options/sing-box-tproxy.nix deleted file mode 100644 index 91ca132..0000000 --- a/modules/proxy-suite/options/sing-box-tproxy.nix +++ /dev/null @@ -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" - ]; - }; - }; - }; -} diff --git a/modules/proxy-suite/options/sing-box-tun.nix b/modules/proxy-suite/options/sing-box-tun.nix deleted file mode 100644 index bb0e8b9..0000000 --- a/modules/proxy-suite/options/sing-box-tun.nix +++ /dev/null @@ -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."; - }; -} diff --git a/modules/proxy-suite/options/sing-box.nix b/modules/proxy-suite/options/sing-box.nix deleted file mode 100644 index 76f053c..0000000 --- a/modules/proxy-suite/options/sing-box.nix +++ /dev/null @@ -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. - ''; - }; - }; - }; -} diff --git a/modules/proxy-suite/options/ssh-proxy.nix b/modules/proxy-suite/options/ssh-proxy.nix index 93e409b..f6ce61b 100644 --- a/modules/proxy-suite/options/ssh-proxy.nix +++ b/modules/proxy-suite/options/ssh-proxy.nix @@ -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; - }; }; } diff --git a/modules/proxy-suite/options/tg-ws-proxy.nix b/modules/proxy-suite/options/tg-ws-proxy.nix new file mode 100644 index 0000000..6d9e0b2 --- /dev/null +++ b/modules/proxy-suite/options/tg-ws-proxy.nix @@ -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."; + }; + }; + }; +} diff --git a/modules/proxy-suite/options/tray.nix b/modules/proxy-suite/options/tray.nix new file mode 100644 index 0000000..2ccdd74 --- /dev/null +++ b/modules/proxy-suite/options/tray.nix @@ -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."; + }; + }; +} diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index 749788a..682645a 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -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 -- `. - 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; } diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index 3bad731..a1f4c5b 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -304,11 +304,5 @@ let ); in { - inherit - profileType - settingsType - peerType - obfuscationType - rangeValue - ; + inherit profileType; } diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix new file mode 100644 index 0000000..d01ae82 --- /dev/null +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -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; +} diff --git a/modules/proxy-suite/options/types/outbounds.nix b/modules/proxy-suite/options/types/outbounds.nix index 6e0c8f4..0a21229 100644 --- a/modules/proxy-suite/options/types/outbounds.nix +++ b/modules/proxy-suite/options/types/outbounds.nix @@ -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//, 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; }; }; diff --git a/modules/proxy-suite/options/types/proxy-inbounds.nix b/modules/proxy-suite/options/types/proxy-inbounds.nix deleted file mode 100644 index adcb9f5..0000000 --- a/modules/proxy-suite/options/types/proxy-inbounds.nix +++ /dev/null @@ -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; -} diff --git a/modules/proxy-suite/options/types/zapret.nix b/modules/proxy-suite/options/types/zapret.nix index 5e84a7b..6ef6253 100644 --- a/modules/proxy-suite/options/types/zapret.nix +++ b/modules/proxy-suite/options/types/zapret.nix @@ -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-.txt - inside the derived zapret config directory. - ''; + description = "Hostlist name (hostlists/list-.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-.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; } diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix new file mode 100644 index 0000000..1ce63b2 --- /dev/null +++ b/modules/proxy-suite/options/user-control.nix @@ -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" ]; + }; + }; +} diff --git a/modules/proxy-suite/options/zapret.nix b/modules/proxy-suite/options/zapret.nix index 0b0329c..82c8f2d 100644 --- a/modules/proxy-suite/options/zapret.nix +++ b/modules/proxy-suite/options/zapret.nix @@ -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-.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"; + } + ]; }; }; }; diff --git a/modules/proxy-suite/options/zapret2.nix b/modules/proxy-suite/options/zapret2.nix new file mode 100644 index 0000000..c1ef4a1 --- /dev/null +++ b/modules/proxy-suite/options/zapret2.nix @@ -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 + --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 + --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= expands to the hostlist + arguments, to the same without learning. --qnum, --fwmark and --lua-init + are added automatically. + ''; + example = [ + "--filter-tcp=443 --filter-l7=tls --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=): 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."; + }; + }; + }; +} diff --git a/modules/proxy-suite/rules-zapret-direct.nix b/modules/proxy-suite/rules-zapret-direct.nix index 4d71008..71efdee 100644 --- a/modules/proxy-suite/rules-zapret-direct.nix +++ b/modules/proxy-suite/rules-zapret-direct.nix @@ -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"); }; } diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index 5fd5573..996b032 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -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 diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index b4f9229..a4fe849 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -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; diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix index 30ceeb9..2943ed1 100644 --- a/modules/proxy-suite/rules/sing-box.nix +++ b/modules/proxy-suite/rules/sing-box.nix @@ -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 = [ { diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index a015023..2208f7a 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -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 ` 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 ` 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 diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 1ccc0d8..452ee15 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -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 diff --git a/modules/proxy-suite/service/control-scripts.nix b/modules/proxy-suite/service/control-scripts.nix index 8c7d6f9..8b50186 100644 --- a/modules/proxy-suite/service/control-scripts.nix +++ b/modules/proxy-suite/service/control-scripts.nix @@ -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 " >&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 ; } diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index ad88402..9f698af 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -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}"; }; } diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 8a3ebe3..325b65e 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -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; + } +] diff --git a/modules/proxy-suite/service/per-app-routing/profiles.nix b/modules/proxy-suite/service/per-app-routing/profiles.nix index 5ae44a0..5c2427e 100644 --- a/modules/proxy-suite/service/per-app-routing/profiles.nix +++ b/modules/proxy-suite/service/per-app-routing/profiles.nix @@ -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 "; diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index 52b0fbf..79b97f3 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -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") { diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 7bca1a4..2b66bc6 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -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 = ""`. 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 = ""`, 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 + ; } diff --git a/modules/proxy-suite/service/routing-scripts.nix b/modules/proxy-suite/service/routing-scripts.nix index 328439b..0ac9471 100644 --- a/modules/proxy-suite/service/routing-scripts.nix +++ b/modules/proxy-suite/service/routing-scripts.nix @@ -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; }} diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index f6d534d..3b1bae6 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -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 '' diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 4972911..10accd8 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -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 "\t" 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; diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix index d53a3cf..850e9d7 100644 --- a/modules/proxy-suite/service/script-blocks/subscriptions.nix +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -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 "\t" 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 ; } diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index b2b4d0d..6e1e09a 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -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 ; } diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 7c32a9b..5213bcc 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -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 { diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index 2691c77..82b5b09 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -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 { diff --git a/modules/proxy-suite/ssh-proxy.nix b/modules/proxy-suite/ssh-proxy.nix index eb3fc4b..3cd7d6c 100644 --- a/modules/proxy-suite/ssh-proxy.nix +++ b/modules/proxy-suite/ssh-proxy.nix @@ -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 diff --git a/modules/proxy-suite/tg-ws-proxy.nix b/modules/proxy-suite/tg-ws-proxy.nix index 89f5a79..f906bfc 100644 --- a/modules/proxy-suite/tg-ws-proxy.nix +++ b/modules/proxy-suite/tg-ws-proxy.nix @@ -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; }; }; } diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 6454429..18ca84e 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -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 ); diff --git a/modules/proxy-suite/zapret/package-builder.nix b/modules/proxy-suite/zapret/package-builder.nix index c5a8ddd..5f99210 100644 --- a/modules/proxy-suite/zapret/package-builder.nix +++ b/modules/proxy-suite/zapret/package-builder.nix @@ -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, diff --git a/modules/proxy-suite/zapret/packages.nix b/modules/proxy-suite/zapret/packages.nix index 2ae7d3b..cee8acd 100644 --- a/modules/proxy-suite/zapret/packages.nix +++ b/modules/proxy-suite/zapret/packages.nix @@ -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 diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix new file mode 100644 index 0000000..f0b0501 --- /dev/null +++ b/modules/proxy-suite/zapret2.nix @@ -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"; + }; + }); +} diff --git a/modules/proxy-suite/zapret2/runtime.nix b/modules/proxy-suite/zapret2/runtime.nix new file mode 100644 index 0000000..e3747a7 --- /dev/null +++ b/modules/proxy-suite/zapret2/runtime.nix @@ -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 = [ + "" + "" + ]; + + # 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"; +} diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index 3f0ca05..fccb229 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -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"; diff --git a/nix/checks/core-proxy/fixtures.nix b/nix/checks/core-proxy/fixtures.nix index 2e9afef..210f9d4 100644 --- a/nix/checks/core-proxy/fixtures.nix +++ b/nix/checks/core-proxy/fixtures.nix @@ -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"; }; }; } diff --git a/nix/checks/core-proxy/service-defaults.nix b/nix/checks/core-proxy/service-defaults.nix index 85986fe..8ca490b 100644 --- a/nix/checks/core-proxy/service-defaults.nix +++ b/nix/checks/core-proxy/service-defaults.nix @@ -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 ) diff --git a/nix/checks/global-proxy-modes.nix b/nix/checks/global-proxy-modes.nix index 4eef149..0a1ef8d 100644 --- a/nix/checks/global-proxy-modes.nix +++ b/nix/checks/global-proxy-modes.nix @@ -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 ) diff --git a/nix/checks/global-proxy-modes/fixtures.nix b/nix/checks/global-proxy-modes/fixtures.nix index e056ca3..522f6c1 100644 --- a/nix/checks/global-proxy-modes/fixtures.nix +++ b/nix/checks/global-proxy-modes/fixtures.nix @@ -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. [ diff --git a/nix/checks/hybrid-backend.nix b/nix/checks/hybrid-backend.nix index 3a7d9bb..e249cad 100644 --- a/nix/checks/hybrid-backend.nix +++ b/nix/checks/hybrid-backend.nix @@ -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"; diff --git a/nix/checks/hybrid-backend/fixtures.nix b/nix/checks/hybrid-backend/fixtures.nix index d95ecb0..3caaa6b 100644 --- a/nix/checks/hybrid-backend/fixtures.nix +++ b/nix/checks/hybrid-backend/fixtures.nix @@ -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"; diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index 772a892..d43ceeb 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -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 diff --git a/nix/checks/local-proxy-auth.nix b/nix/checks/local-proxy-auth.nix index 612a196..7a18300 100644 --- a/nix/checks/local-proxy-auth.nix +++ b/nix/checks/local-proxy-auth.nix @@ -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"; diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index a33b7e2..e2f9f2d 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -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; } diff --git a/nix/checks/outbound-validation.nix b/nix/checks/outbound-validation.nix index abee3bb..f9ce851 100644 --- a/nix/checks/outbound-validation.nix +++ b/nix/checks/outbound-validation.nix @@ -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"; diff --git a/nix/checks/per-app-routing-proxychains.nix b/nix/checks/per-app-routing-proxychains.nix index 9d784a8..3b200b6 100644 --- a/nix/checks/per-app-routing-proxychains.nix +++ b/nix/checks/per-app-routing-proxychains.nix @@ -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 " perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "local proxy backend" perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "restart active services" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix "wrap -- " perAppRoutingProxychainsScript; + assert pkgs.lib.hasInfix "apps run -- " perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript; true ) diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix index 7d1f7b0..5e2b42d 100644 --- a/nix/checks/per-app-routing-tproxy.nix +++ b/nix/checks/per-app-routing-tproxy.nix @@ -13,10 +13,10 @@ let baseModule { services.proxy-suite = { - proxy.tproxy.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; + tproxy.enable = true; }; }; } diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index 29ba2d8..4346309 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -15,10 +15,10 @@ let baseModule { services.proxy-suite = { - proxy.tun.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; + tun.enable = true; }; }; } @@ -43,13 +43,11 @@ let baseModule { services.proxy-suite = { - proxy = { - tproxy.enable = true; - tun.perApp.enable = true; - }; + proxy.tproxy.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; + tun.enable = true; }; }; } diff --git a/nix/checks/per-app-routing-validation-profiles.nix b/nix/checks/per-app-routing-validation-profiles.nix index 55386b1..8e9ac09 100644 --- a/nix/checks/per-app-routing-validation-profiles.nix +++ b/nix/checks/per-app-routing-validation-profiles.nix @@ -48,7 +48,7 @@ } ] - # route=tun requires proxy.tun.perApp.enable. + # route=tun requires perAppRouting.tun.enable. [ { services.proxy-suite.perAppRouting = { @@ -67,11 +67,11 @@ [ { services.proxy-suite = { - proxy = { - enable = false; - tun.perApp.enable = true; + proxy.enable = false; + perAppRouting = { + enable = true; + tun.enable = true; }; - perAppRouting.enable = true; }; } ] @@ -92,7 +92,7 @@ } ] - # route=tproxy requires proxy.tproxy.perApp.enable. + # route=tproxy requires perAppRouting.tproxy.enable. [ { services.proxy-suite.perAppRouting = { @@ -111,11 +111,11 @@ [ { services.proxy-suite = { - proxy = { - enable = false; - tproxy.perApp.enable = true; + proxy.enable = false; + perAppRouting = { + enable = true; + tproxy.enable = true; }; - perAppRouting.enable = true; }; } ] @@ -136,7 +136,7 @@ } ] - # route=zapret requires zapret.perApp.enable. + # route=zapret requires perAppRouting.zapret.enable. [ { services.proxy-suite = { diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix index 1214fe1..293420e 100644 --- a/nix/checks/per-app-routing-zapret.nix +++ b/nix/checks/per-app-routing-zapret.nix @@ -16,14 +16,12 @@ let baseModule { services.proxy-suite = { - zapret = { - enable = true; - perApp.enable = true; - }; + zapret.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; proxychains.enable = true; + zapret.enable = true; }; }; } @@ -44,14 +42,12 @@ let baseModule { services.proxy-suite = { - zapret = { - enable = false; - perApp.enable = true; - }; + zapret.enable = false; perAppRouting = { enable = true; createDefaultProfiles = true; proxychains.enable = true; + zapret.enable = true; }; }; } @@ -69,11 +65,13 @@ let proxy.tun = { enable = true; interface = "test-global0"; - perApp.enable = true; - perApp.interface = "test-app0"; + }; + perAppRouting.tun = { + enable = true; + interface = "test-app0"; }; zapret.enable = true; - zapret.perApp.enable = perAppZapret; + perAppRouting.zapret.enable = perAppZapret; }; } ]; diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index 420ab8d..3b8e17f 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -36,10 +36,10 @@ pkgs.testers.runNixOSTest { services.proxy-suite = { enable = true; proxy.enable = false; - proxyInbounds = { + inbounds = { enable = true; inherit serverAddress; - via = "direct"; + routing.via = "direct"; openFirewall = true; listeners.vless-in = { type = "vless"; @@ -79,8 +79,8 @@ pkgs.testers.runNixOSTest { enable = true; proxy = { enable = true; - xray.enable = true; - port = 1080; + backend = "xray"; + listener.port = 1080; outbounds = [ { tag = "server"; @@ -106,7 +106,7 @@ pkgs.testers.runNixOSTest { server.succeed(f"jq -e '.inbounds[] | select(.tag == \"ss-in\" and .port == 8388)' {cfg}") # Credentials live only in the runtime config, never in the store. server.succeed(f"test $(stat -c %a {cfg}) = 600") - server.fail(f"grep -r '${uuid}' /nix/store/*proxy-suite-inbounds-*.json") + server.fail("grep -r '${uuid}' /nix/store/*proxy-suite-inbounds-*.json") with subtest("safety rules are present and ordered first"): cfg = "/run/proxy-suite-inbounds/config.json" @@ -138,7 +138,7 @@ pkgs.testers.runNixOSTest { assert link.startswith("vless://${uuid}@${serverAddress}:8443"), link assert "#tester" in link, link server.succeed("proxy-ctl inbounds | grep -q vless-in") - server.succeed("proxy-ctl inbounds qr vless-in | head -c 1") + server.succeed("proxy-ctl inbounds link vless-in --qr | head -c 1") server.succeed("proxy-ctl status | grep -q proxy-suite-inbounds") with subtest("a listener keeps serving after a restart"): diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 6c070b6..fd2934c 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -24,10 +24,10 @@ let }; mkInbounds = - proxyInbounds: + inbounds: evalProxySuite [ baseModule - { services.proxy-suite.proxyInbounds = { enable = true; } // proxyInbounds; } + { services.proxy-suite.inbounds = { enable = true; } // inbounds; } ]; relayFixture = mkInbounds { listeners.vless-in = realityListener; }; @@ -35,7 +35,7 @@ let relaySpec = mkInboundsSpec relayFixture; exitFixture = mkInbounds { - via = "direct"; + routing.via = "direct"; listeners.vless-in = realityListener; }; exitConfig = mkInboundsConfig exitFixture; @@ -57,7 +57,7 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; outbounds = [ { tag = "nl-vps"; @@ -75,9 +75,9 @@ let } ]; }; - proxyInbounds = { + inbounds = { enable = true; - via = "nl-vps"; + routing.via = "nl-vps"; listeners.through-nl = realityListener; listeners.through-de = realityListener // { port = 8443; @@ -104,10 +104,10 @@ let ipNamedConfig = mkInboundsConfig ipNamedFixture; unguardedFixture = mkInbounds { - - - blockRu = false; - blockPrivate = false; + routing = { + blockRu = false; + blockPrivate = false; + }; listeners.vless-in = realityListener; }; unguardedConfig = mkInboundsConfig unguardedFixture; @@ -119,13 +119,12 @@ let port = 8388; users = [ { passwordFile = "/run/secrets/ss"; } ]; }; - # Fronted by something else on this host, so its port stays closed even - # though the share link advertises the public one. + # Loopback-bound: the port stays closed though the link advertises the public one. listeners.ws-in = { type = "vless"; port = 10002; sharePort = 443; - listenAddress = "127.0.0.1"; + address = "127.0.0.1"; users = [ { uuidFile = "/run/secrets/ws"; } ]; transport = { type = "ws"; @@ -137,6 +136,22 @@ let keyFile = "/run/acme/key.pem"; }; }; + # h3 only: UDP is opened, the TCP port stays free. + listeners.h3-in = { + type = "vless"; + port = 8443; + users = [ { uuidFile = "/run/secrets/h3"; } ]; + transport = { + type = "xhttp"; + path = "/h3"; + }; + tls = { + enable = true; + certificateFile = "/run/acme/fullchain.pem"; + keyFile = "/run/acme/key.pem"; + alpn = [ "h3" ]; + }; + }; }; firewallSpec = mkInboundsSpec firewallFixture; wsListener = lib.head (builtins.filter (l: l.tag == "ws-in") firewallSpec.listeners); @@ -154,13 +169,28 @@ let service = fixture: fixture.config.systemd.services."proxy-suite-inbounds"; - # Bad configurations are checked by looking at config.assertions directly - # rather than by forcing system.build.toplevel: it is far cheaper, and it - # pins which assertion fired instead of just "something failed". + # `proxy-ctl inbounds stats` reads the collected file, so userControl members need it. + statsScript = + fixture: + (import ./read-generated.nix).readDerivation + fixture.config.systemd.services."proxy-suite-inbound-stats".serviceConfig.ExecStart; + noControlFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + inbounds.enable = true; + inbounds.listeners.vless-in = realityListener; + userControl.allow = [ ]; + }; + } + ]; + + # Checked against config.assertions directly: cheaper than toplevel, and names the + # assertion. baseProxy = { enable = true; proxy.enable = true; - proxy.singBox.enable = true; + proxy.backend = "sing-box"; proxy.outbounds = [ { tag = "primary"; @@ -183,15 +213,13 @@ let if lib.any (a: lib.hasInfix fragment a.message) failed then true else - # Name what was expected and what actually failed, so a regression here - # points at the assertion instead of just "something evaluated wrong". throw "proxy-inbounds check: expected an assertion matching '${fragment}', got: ${builtins.toJSON (map (a: a.message) failed)}"; failing = [ (mkRejects ( baseProxy // { - proxyInbounds = { + inbounds = { enable = true; listeners.bad = { type = "vless"; @@ -204,7 +232,7 @@ let (mkRejects ( baseProxy // { - proxyInbounds = { + inbounds = { enable = true; listeners.a = realityListener; listeners.b = realityListener; @@ -215,9 +243,9 @@ let (mkRejects { enable = true; proxy.enable = false; - proxyInbounds = { + inbounds = { enable = true; - via = "proxy"; + routing.via = "proxy"; listeners.vless-in = realityListener; }; } "requires proxy.enable = true") @@ -225,7 +253,7 @@ let (mkRejects ( baseProxy // { - proxyInbounds = { + inbounds = { enable = true; listeners.vless-in = realityListener // { reality = realityListener.reality // { @@ -239,7 +267,7 @@ let (mkRejects ( baseProxy // { - proxyInbounds = { + inbounds = { enable = true; listeners.tls-in = { type = "vless"; @@ -254,7 +282,7 @@ let (mkRejects ( baseProxy // { - proxyInbounds = { + inbounds = { enable = true; listeners.ws-in = realityListener // { transport.type = "ws"; @@ -266,9 +294,9 @@ let (mkRejects ( baseProxy // { - proxyInbounds = { + inbounds = { enable = true; - via = "no-such-outbound"; + routing.via = "no-such-outbound"; listeners.vless-in = realityListener; }; } @@ -277,46 +305,47 @@ let (mkRejects { enable = true; proxy.enable = true; - proxy.singBox.enable = true; + proxy.backend = "sing-box"; proxy.outbounds = [ { tag = "sb-only"; singBoxJson.type = "tuic"; } ]; - proxyInbounds = { + inbounds = { enable = true; - via = "sb-only"; + routing.via = "sb-only"; listeners.vless-in = realityListener; }; } "targets a sing-box-only outbound") - (mkRejects (baseProxy // { proxyInbounds.enable = true; }) - "requires at least one entry in proxyInbounds.listeners" + (mkRejects (baseProxy // { inbounds.enable = true; }) + "requires at least one entry in inbounds.listeners" ) # recursiveUpdate, not //: this one nests into proxy, which baseProxy sets. (mkRejects (lib.recursiveUpdate baseProxy { - proxy.port = 1080; - proxyInbounds = { + proxy.listener.port = 1080; + inbounds = { enable = true; listeners.clash = realityListener // { port = 1080; }; }; }) - "collides with proxy.port" + "collides with proxy.listener.port" ) ]; assertions = [ - # The template carries no listeners; they are rendered at start time so no - # credential reaches the Nix store. + # Listeners are rendered at start time. (assert relayConfig.inbounds == [ ]; true) - # Relaying goes through the client stack's local SOCKS listener rather than - # a second copy of the outbound machinery. + # AsIs when relayed through sing-box; IPOnDemand when XRay dials (see the template). + (assert relayConfig.routing.domainStrategy == "AsIs"; true) + (assert exitConfig.routing.domainStrategy == "IPOnDemand"; true) + (assert hasOutbound relayConfig "proxy"; true) (assert (ruleByTag relayConfig "inbound-final").outboundTag == "proxy"; true) ( @@ -342,15 +371,13 @@ let (assert !hasOutbound exitConfig "proxy"; true) (assert (ruleByTag exitConfig "inbound-final").outboundTag == "direct"; true) - # Safety rules are on by default and come before anything else, so an - # inbound credential cannot reach the LAN or loopback. + # Safety rules come first. (assert builtins.head (ruleTags relayConfig) == "inbound-block-private"; true) (assert (ruleByTag relayConfig "inbound-block-private").outboundTag == "block"; true) (assert (ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]; true) (assert (ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]; true) (assert !builtins.elem "inbound-block-private" (ruleTags unguardedConfig); true) - # The relay must not blackhole the address clients dial to reach it, and the - # exemption has to sit after blockPrivate but ahead of the country blocks. + # serverAddress is exempt after blockPrivate, before the country blocks. ( assert lib.take 3 (ruleTags namedConfig) == [ @@ -380,12 +407,10 @@ let (assert (ruleByTag mixedConfig "inbound-via-local-exit").inboundTag == [ "local-exit" ]; true) (assert (ruleByTag mixedConfig "inbound-via-local-exit").outboundTag == "direct"; true) - # Two listeners can leave through two different servers: the pinned one - # gets its own rule, the default one rides the final rule. + # The pinned listener gets its own rule; the default one rides the final rule. (assert (ruleByTag pinnedConfig "inbound-via-through-de").outboundTag == "de-vps"; true) (assert (ruleByTag pinnedConfig "inbound-final").outboundTag == "nl-vps"; true) - # Pinned outbounds are injected at start time, not baked into the template, - # and chaining through the local proxy is not needed for either of them. + # Pinned outbounds are injected at start and need no local proxy. (assert !hasOutbound pinnedConfig "proxy"; true) (assert outboundTags pinnedConfig == [ "direct" "block" ]; true) # Only referenced outbounds are rendered, so the sing-box-only one is fine. @@ -427,9 +452,14 @@ let ]; true ) - (assert firewallFixture.config.networking.firewall.allowedUDPPorts == [ 8388 ]; true) - # A loopback-bound listener is fronted on this host; opening its port would - # expose what the arrangement hides. + ( + assert + lib.sort lib.lessThan firewallFixture.config.networking.firewall.allowedUDPPorts == [ + 8388 + 8443 + ]; + true + ) (assert wsListener.port == 10002 && wsListener.sharePort == 443; true) (assert noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ]; true) @@ -440,6 +470,15 @@ let # Not `requires`: direct-routed listeners keep serving if the client is down. (assert (service relayFixture).requires == [ ]; true) + # The collected stats are group-readable with userControl, root-only without. + ( + assert lib.hasInfix "chgrp proxy-suite \"$tmp\"" (statsScript relayFixture); + assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript relayFixture); + assert !lib.hasInfix "chgrp" (statsScript noControlFixture); + assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript noControlFixture); + true + ) + ] ++ failing; in diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 776f035..f2ff760 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -31,7 +31,7 @@ options-doc = pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } '' - diff -u ${../../docs/options.md} ${generatedOptionsDoc} + diff -ru ${../../docs/options} ${generatedOptionsDoc} touch "$out" ''; @@ -78,7 +78,10 @@ PROXYCHAINS_QUIET_ARG="" \ ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ DEFAULT_ROUTE_MODE="blacklist" \ - bash "$proxy_ctl" subscription list > output + bash "$proxy_ctl" proxy subs list > output + # The old spelling still dispatches. + env SUB_TAGS_FILE="$PWD/tags.json" SUB_CACHE_DIR="$PWD/cache" \ + bash "$proxy_ctl" subscription list | cmp - output awk '$1 == "plain" { found = 1; if ($NF != "2") exit 1 } END { exit found ? 0 : 1 }' output awk '$1 == "hybrid" { found = 1; if ($NF != "3") exit 1 } END { exit found ? 0 : 1 }' output @@ -87,6 +90,641 @@ touch "$out" ''; + proxy-ctl-outbounds = + pkgs.runCommand "proxy-suite-proxy-ctl-outbounds-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.curl + pkgs.gawk + pkgs.gnugrep + pkgs.jq + ]; + } + '' + proxy_ctl="$TMPDIR/proxy-ctl" + cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + chmod +x "$proxy_ctl" + + # systemd is not in the sandbox. The reload stub stands in for the start + # script, which is what actually republishes the inventory. + mkdir -p stub + { + printf '%s\n' '#!/bin/sh' + printf '%s\n' 'if [ "$1" = start ] && [ "$2" = proxy-suite-outbound-reload.service ]; then' + printf '%s\n' ' ls "$RUNTIME_OUTBOUNDS_DIR" > "$OUTBOUND_INVENTORY_FILE.spool"' + printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'($spool | split("\n") | map(select(endswith(".url")) | rtrimstr(".url"))) as $new | .tags = (.tags + $new | unique) | .sources = reduce $new[] as $t (.sources; .[$t] = "runtime")'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' + printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' + printf '%s\n' 'fi' + printf '%s\n' 'exit 0' + } > stub/systemctl + printf '#!/bin/sh\nprintf %%s "$2"\n' > stub/systemd-escape + chmod +x stub/systemctl stub/systemd-escape + export PATH="$PWD/stub:$PATH" + + mkdir -p obd subd cache + printf '%s\n' '["community"]' > tags.json + jq -n '{tags:["own-vps","community-de"], + sources:{"own-vps":"static","community-de":"sub:community"}, + pinned:"community-de", selection:"urltest"}' > inventory.json + + run() { + env \ + SUB_TAGS_FILE="$PWD/tags.json" \ + SUB_CACHE_DIR="$PWD/cache" \ + OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ + RUNTIME_OUTBOUNDS_DIR="$PWD/obd" \ + RUNTIME_SUBS_DIR="$PWD/subd" \ + USER_CONTROL_GROUP="proxy-suite" \ + CLASH_API="http://127.0.0.1:1" \ + SELECTION="urltest" \ + PER_APP_ROUTING_ENABLED="0" \ + PER_APP_ROUTING_PROXYCHAINS_ENABLED="0" \ + PER_APP_ROUTING_TUN_ENABLED="0" \ + PER_APP_ROUTING_TPROXY_ENABLED="0" \ + PER_APP_ROUTING_ZAPRET_ENABLED="0" \ + PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ + PROXYCHAINS_CONFIG="$PWD/proxychains.conf" \ + PROXYCHAINS_QUIET_ARG="" \ + ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ + DEFAULT_ROUTE_MODE="blacklist" \ + bash "$proxy_ctl" "$@" + } + + # Listing works from the inventory alone, with no Clash API answering. + run proxy outbounds > listing + grep -q 'Selection: urltest' listing + grep -q 'Pinned: community-de' listing + grep -q '\*community-de' listing + grep -q 'own-vps *static' listing + # The old spelling still dispatches. + run outbounds | cmp - listing + + # Reserved and malformed tags are refused before anything is written. + for bad in proxy direct block "has space" "-leading"; do + if run proxy outbounds add "$bad" http://example.com:1 2>/dev/null; then + echo "accepted invalid tag: $bad" >&2 + exit 1 + fi + done + # Tags that already exist are refused too, declared or not. + ! run proxy outbounds add own-vps http://example.com:1 2>/dev/null + ! run proxy subs add community https://example.com/sub 2>/dev/null + # A URL with whitespace is refused. + ! run proxy outbounds add ok-tag "http://example.com:1 x" 2>/dev/null + # Nothing above touched the spool. + [ -z "$(ls -A obd)" ] + + # Removing something that was never added says so. + ! run proxy outbounds rm nope 2>/dev/null + + # A good add lands in the spool group-readable, not world-readable. + run proxy outbounds add spool-one http://example.com:1 | grep -q 'Added outbound: spool-one' + [ "$(cat obd/spool-one.url)" = "http://example.com:1" ] + [ "$(stat -c %a obd/spool-one.url)" = "640" ] + run proxy outbounds | grep -q 'spool-one *runtime' + # Adding it twice is refused. + ! run proxy outbounds add spool-one http://example.com:1 2>/dev/null + run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one' + [ ! -e obd/spool-one.url ] + + # Subscriptions use the same spool machinery, verified by cache file. + printf '%s\n' '[{},{}]' > cache/extra.json + run proxy subs add extra https://example.com/sub | grep -q 'Added subscription: extra (2 proxies)' + run proxy subs list > subs + grep -q 'community .* static' subs + grep -q 'extra .* runtime' subs + + # A spool entry the backend refused is reported, not silently accepted. + run proxy subs add rejected https://example.com/sub > rejected 2>&1 && exit 1 + grep -q 'did not come up' rejected + + # Pinning goes through the unit, including "auto". + run proxy select community-de | grep -q 'Pinned: community-de' + run proxy select auto | grep -q 'Selecting automatically again' + # Without a terminal and without a tag there is nothing to pick from. + ! run proxy select /dev/null + + touch "$out" + ''; + + proxy-ctl-zapret-auto = + pkgs.runCommand "proxy-suite-proxy-ctl-zapret-auto-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.gnugrep + ]; + } + '' + proxy_ctl="$TMPDIR/proxy-ctl" + cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + + state="$PWD/state" + mkdir -p "$state" + printf 'blocked.example\nother.example\n' > "$state/zapret-hosts-auto.txt" + : > "$state/zapret-hosts-user.txt" + : > "$state/zapret-hosts-user-exclude.txt" + + run() { + env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto "$@" + } + + run list | grep -qx blocked.example + + # exclude must also blacklist, or the host is relearned. + run exclude blocked.example > /dev/null + ! grep -qx blocked.example "$state/zapret-hosts-auto.txt" + grep -qx blocked.example "$state/zapret-hosts-user-exclude.txt" + + # Pinning is idempotent, so repeated runs cannot grow the list. + run add pinned.example > /dev/null + run add pinned.example > /dev/null + test "$(grep -c -x pinned.example "$state/zapret-hosts-user.txt")" = 1 + + # The lists stay readable by unprivileged proxy-ctl after a rewrite. + test "$(stat -c %a "$state/zapret-hosts-user.txt")" = 644 + + run clear > /dev/null + run list | grep -q 'No hostnames learned' + + # Without the zapret2 engine there is nothing to inspect. + ! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto list + + touch "$out" + ''; + + proxy-ctl-complete = + pkgs.runCommand "proxy-suite-proxy-ctl-complete-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.gawk + pkgs.gnugrep + pkgs.jq + ]; + } + '' + proxy_ctl="$TMPDIR/proxy-ctl" + cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + + printf '%s\n' '["home","work"]' > awg.json + jq -n '[{name:"torrent",route:"direct"}]' > profiles.json + jq -n '{tags:["own-vps","community-de"]}' > inventory.json + + run() { + env AWG_PROFILES_FILE="$PWD/awg.json" \ + PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ + OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ + bash "$proxy_ctl" __complete "$@" + } + + # Every group the help lists must complete, or the table has drifted. + bash "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups + run > top + while read -r group; do + grep -qx "$group" top || { echo "help lists $group, completion does not" >&2; exit 1; } + done < groups + + # Piping into `grep -q` would race the script against SIGPIPE. + has() { + local want="$1" + shift + run "$@" > words + grep -qx "$want" words + } + + has outbounds proxy + has all-bypass proxy mode + has exclude zapret auto + has proxy-suite-awg-work logs + has work awg on + has torrent apps run + has auto proxy select + has community-de proxy select + + # A shell completing must never die, however unreadable the state is. + run inbounds link | cmp - /dev/null + env AWG_PROFILES_FILE=/nonexistent bash "$proxy_ctl" __complete awg on + + touch "$out" + ''; + + proxy-ctl-where = + pkgs.runCommand "proxy-suite-proxy-ctl-where-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.gnugrep + pkgs.jq + ]; + } + '' + proxy_ctl="$TMPDIR/proxy-ctl" + cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + + mkdir -p ap zap + jq -n '{domains:{"spotify.com":{exit:"community-de",host:"open.spotify.com",at:0}}}' > ap/state.json + printf 'nyt.com\n' > zap/zapret-hosts-auto.txt + printf 'discord.com\n' > zap/zapret-hosts-user.txt + printf 'ok.ru\n' > zap/zapret-hosts-user-exclude.txt + + run() { + env AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$PWD/ap" \ + ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$PWD/zap" \ + bash "$proxy_ctl" where "$@" + } + + # Piping into `grep -q` would race the script against SIGPIPE. + verdict() { + run "$1" > where + grep -q -- "$2" where + } + + # Both stores key on an apex, so a subdomain has to match its parent. + verdict open.spotify.com '-> proxied via community-de' + grep -q 'autoProxy .*routed via community-de' where + # What proxy-ctl cannot see has to be said out loud. + grep -q 'proxy.routing.rules are not visible' where + + verdict discord.com '-> direct, with the zapret2 bypass' + verdict nyt.com '-> direct, with the zapret2 bypass' + # Excluded is not bypassed: it must not read as a zapret2 verdict. + verdict ok.ru '-> nothing runtime matches it' + verdict example.org '-> nothing runtime matches it' + + # A URL is accepted where a hostname is. + verdict https://open.spotify.com/track/x '^ domain *open.spotify.com$' + + ! bash "$proxy_ctl" where 2>/dev/null + + touch "$out" + ''; + + # The verdict table, fed tuples measured on a real censored network. + proxy-ctl-proxy-probe = + pkgs.runCommand "proxy-suite-proxy-ctl-proxy-probe-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.gnugrep + pkgs.jq + ]; + } + '' + cat > "$TMPDIR/test.sh" <<'EOF' + set -euo pipefail + . ${../../pkgs/proxy-ctl-lib.sh} + + expect() { + local want="$1" direct="$2" via="$3" got + got="$(_probe_verdict "$direct" "$via")" + if [ "$got" != "$want" ]; then + echo "FAIL: expected $want, got $got" >&2 + echo " direct=$direct" >&2 + echo " proxy =$via" >&2 + exit 1 + fi + } + + # Origin refuses direct, accepts the proxy: chatgpt.com/robots.txt. + expect destination '0|0.146175|403|6633|' '0|0.230116|200|4302|' + + # The same through a redirect: claude.ai/robots.txt. + expect destination \ + '0|0.141625|302|143|https://claude.com/app-unavailable-in-region' \ + '0|0.181276|200|281|' + + # TLS never completed: censorship, zapret's job. + expect censor '35|0.000000|000|0|' '0|0.119348|200|6258|' + + # Handshake, then silence: the post-handshake throttle. + expect censor '0|0.125029|000|0|' '0|0.143772|200|32881|' + + # Direct works. Nothing to do, whoever else also works. + expect ok '0|0.099546|200|2678|' '0|0.146822|200|2678|' + + # robots.txt legitimately absent is not a failure. + expect ok '0|0.161330|404|559|' '0|0.214667|404|559|' + + # An ordinary redirect must not read as a block. + expect ok \ + '0|0.10|301|0|https://www.example.com/robots.txt' \ + '0|0.20|301|0|https://www.example.com/robots.txt' + + # Refused everywhere: not an egress problem. + expect both-fail '0|0.10|403|100|' '0|0.20|403|100|' + + # Nothing reaches it at all - a dead name, not a blocked one. + expect unreachable '6|0.000000|000|0|' '35|0.000000|000|0|' + + # --- redirect chains --- + # spotify.com: the block is four same-site hops in. + curl() { + local url + for url; do :; done + echo x >> "$TMPDIR/curl-calls" + case "$url" in + https://spotify.test/) printf '0|0.1|301|0|https://www.spotify.test/' ;; + https://www.spotify.test/) printf '0|0.1|301|0|https://open.spotify.test/' ;; + https://open.spotify.test/) printf '0|0.1|302|93|https://accounts.spotify.test/login' ;; + https://accounts.spotify.test/login) + printf '0|0.1|301|0|https://www.spotify.test/int/why-not-available/' ;; + https://redir.test/) printf '0|0.1|301|0|https://elsewhere.example/' ;; + https://loop.test/) printf '0|0.1|301|0|https://loop.test/' ;; + *) printf '0|0.1|200|10|' ;; + esac + } + test "$(_probe_exit_verdict "$(_probe_fetch spotify.test / --noproxy '*')")" = blocked + # Leaving the site ends the walk. + test "$(_probe_exit_verdict "$(_probe_fetch redir.test / --noproxy '*')")" = ok + # A redirect loop inside the site still stops. + : > "$TMPDIR/curl-calls" + _probe_fetch loop.test / --noproxy '*' > /dev/null + test "$(wc -l < "$TMPDIR/curl-calls")" -le 6 + unset -f curl + + # --- which path decides: the apex, robots.txt only breaks ties --- + _svc_active() { return 0; } + # No listener index: only this host and the local proxy. + PROBE_EXITS_FILE=/nonexistent + + # A curl that cannot start is an error, not a dead site. + ! (PROBE_CURL=/nonexistent cmd_proxy_probe --json x.test) 2> "$TMPDIR/curl-err" + grep -q 'Cannot run /nonexistent' "$TMPDIR/curl-err" + + probe_with() { + # $1 apex-direct $2 apex-proxy $3 robots-direct $4 robots-proxy + _probe_fetch() { + case "$2" in + /) [ "$3" = --noproxy ] && printf '%s' "$APEX_DIRECT" || printf '%s' "$APEX_PROXY" ;; + *) [ "$3" = --noproxy ] && printf '%s' "$ROBOTS_DIRECT" || printf '%s' "$ROBOTS_PROXY" ;; + esac + } + APEX_DIRECT="$1" APEX_PROXY="$2" ROBOTS_DIRECT="$3" ROBOTS_PROXY="$4" \ + cmd_proxy_probe --json example.test + } + + # last.fm: apex geo-blocked, robots.txt served everywhere. + out="$(probe_with '0|0.11|403|424|' '0|0.17|200|59809|' '0|0.11|200|400|' '0|0.17|200|400|')" + grep -q '"verdict":"destination"' <<<"$out" + grep -q '"url":"https://example.test/"' <<<"$out" + + # chatgpt.com: apex 403 everywhere, robots.txt separates. + out="$(probe_with '0|0.14|403|6633|' '0|0.23|403|8442|' '0|0.14|403|6633|' '0|0.23|200|4302|')" + grep -q '"verdict":"destination"' <<<"$out" + grep -q '"url":"https://example.test/robots.txt"' <<<"$out" + + # A working apex is never second-guessed by the fallback path. + out="$(probe_with '0|0.10|200|500|' '0|0.20|200|500|' '0|0.10|403|10|' '0|0.20|200|10|')" + grep -q '"verdict":"ok"' <<<"$out" + + # --- walking more than two exits --- + # Direct and the first proxy share a WAF; only the third exit gets through. + printf '%s' '[{"i":0,"tag":"direct","port":18540}, + {"i":1,"tag":"fi","port":18541},{"i":2,"tag":"de","port":18542}]' \ + > "$TMPDIR/exits.json" + PROBE_EXITS_FILE="$TMPDIR/exits.json" + _probe_fetch() { + # every exit, direct included, goes through its pinned listener + case "$4" in + *:18540 | *:18541) printf '0|0.10|403|919|' ;; + *:18542) printf '0|0.10|200|500|' ;; + esac + } + out="$(cmd_proxy_probe --json sekai.test)" + jq -e '.verdict == "destination" and .exit == "de"' <<<"$out" > /dev/null + + # --exits restricts and orders the walk; direct is always tried first. + out="$(cmd_proxy_probe --json --exits de sekai.test)" + jq -e '[.exits[].tag] == ["direct", "de"]' <<<"$out" > /dev/null + + # An empty list probes direct only (every exit shares one network). + out="$(cmd_proxy_probe --json --exits "" sekai.test)" + jq -e '([.exits[].tag] | unique) == ["direct"] and .exit == null' <<<"$out" > /dev/null + + # --via: can this exit carry what direct reaches? + out="$(cmd_proxy_probe --json --via de sekai.test)" + jq -e '.verdict == "ok" and ([.exits[].tag] | unique) == ["de", "direct"]' <<<"$out" > /dev/null + out="$(cmd_proxy_probe --json --via fi sekai.test)" + jq -e '.verdict == "blocked"' <<<"$out" > /dev/null + ! (cmd_proxy_probe --json --via nowhere sekai.test) 2> /dev/null + # A given path is probed as is, for that probe only. + out="$(cmd_proxy_probe --json --via de sekai.test/robots.txt)" + jq -e '.url == "https://sekai.test/robots.txt" and ([.exits[].path] | unique) == ["/robots.txt"]' \ + <<<"$out" > /dev/null + out="$(cmd_proxy_probe --json --via fi sekai.test)" + jq -e '([.exits[].path] | unique) == ["/", "/robots.txt"]' <<<"$out" > /dev/null + + # Refused a front page direct gets: not a stand-in (www.reddit.com). + _probe_fetch() { + case "$4:$2" in + *:18541:/) printf '0|0.10|403|190240|' ;; + *) printf '0|0.10|200|500|' ;; + esac + } + out="$(cmd_proxy_probe --json --via fi geo.test)" + jq -e '.verdict == "blocked"' <<<"$out" > /dev/null + # i.pximg.net: the front page is 400 everywhere, so robots.txt decides. + _probe_fetch() { + case "$2" in + /) printf '0|0.10|400|0|' ;; + *) printf '0|0.10|200|43|' ;; + esac + } + out="$(cmd_proxy_probe --json --via fi cdn.test)" + jq -e '.verdict == "ok"' <<<"$out" > /dev/null + + # --- proxy-ctl proxy auto learn --- + learn_dir="$TMPDIR/learn" + mkdir -p "$learn_dir" + systemctl() { + # stands in for the requests-only run + printf '%s' '{"domains":{"last.fm":{"verdict":"destination","exit":"primary","host":"www.last.fm"}}, + "hosts":{"www.last.fm":{"domain":"last.fm","verdict":"destination","exit":"primary"}}}' \ + > "$learn_dir/state.json" + } + ! (AUTOPROXY_ENABLED=0 cmd_proxy_learn www.last.fm) 2> /dev/null + # It lands in a root-owned file and then in a URL: hostnames only. + ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn 'x;rm -rf /') 2> /dev/null + ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn '-evil.test/path') 2> /dev/null + out="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn www.last.fm)" + test "$(cat "$learn_dir/requests")" = www.last.fm + grep -q 'last.fm: destination - routed via primary' <<<"$out" + + # A verdict that routes nothing is kept for its host and reported. + systemctl() { + printf '%s' '{"domains":{}, + "hosts":{"api.example.test":{"domain":"example.test","verdict":"ok","exit":null}}}' \ + > "$learn_dir/state.json" + } + out="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn api.example.test)" + grep -q 'api.example.test: ok - nothing to route' <<<"$out" + + # A failed run is reported in plain words, and the request is not lost. + systemctl() { return 1; } + : > "$learn_dir/requests" + ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn www.last.fm) 2> "$TMPDIR/learn-err" + grep -q 'still queued' "$TMPDIR/learn-err" + grep -qx www.last.fm "$learn_dir/requests" + + # --- queue and learned ---------------------------------------------- + systemctl() { return 0; } + printf '%s' '{"domains":{"spotify.com":{"verdict":"destination","exit":"primary","host":"www.spotify.com","at":0}}, + "hosts":{"www.spotify.com":{"domain":"spotify.com","verdict":"destination","exit":"primary"}, + "gew1-spclient.spotify.com":{"domain":"spotify.com","verdict":"ok","exit":null}}, + "backlog":{"a.example":{"domain":"example","hits":2},"b.example":{"domain":"example","hits":9}}}' \ + > "$learn_dir/state.json" + q="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_queue)" + grep -qx ' www.last.fm' <<<"$q" + # Most-dialled first. + test "$(grep -oE '[ab]\.example' <<<"$q" | head -n 1)" = b.example + l="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learned)" + grep -q 'spotify.com .*-> primary' <<<"$l" + grep -q 'ok=1' <<<"$l" + # An unreadable state directory asks for sudo. + chmod 000 "$learn_dir" + ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_queue) 2> "$TMPDIR/q-err" + chmod 755 "$learn_dir" + grep -q 'enable userControl, or run with sudo' "$TMPDIR/q-err" + EOF + bash "$TMPDIR/test.sh" + touch "$out" + ''; + + # autoProxy slowness routing: sampler and judge. + autoproxy-slowness = + pkgs.runCommand "proxy-suite-autoproxy-slowness-check" + { nativeBuildInputs = [ pkgs.jq ]; } + '' + sample=${../../modules/proxy-suite/autoproxy-slow-sample.jq} + judge=${../../modules/proxy-suite/autoproxy-slow-judge.jq} + + # A steady crawl, a burst, probe traffic, and a tiny flow. + res="$(jq -n -c '[range(0; 11) as $t | {connections: [ + {id: "a", metadata: {host: "i.pximg.net", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 50000)}, + {id: "b", metadata: {host: "audio.example", type: "mixed/mixed-in"}, chains: ["direct"], download: (if $t >= 5 then 2000000 else 0 end)}, + {id: "c", metadata: {host: "probe.example", type: "mixed/probe-in-0"}, chains: ["direct"], download: ($t * 50000)}, + {id: "d", metadata: {host: "tiny.example", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 1000)}, + {id: "e", metadata: {host: "far.example", type: "mixed/mixed-in"}, chains: ["primary", "proxy"], download: ($t * 50000)} + ]}][]' | jq -s -r --argjson min 307200 --argjson below 153600 -f "$sample")" + printf '%s\n' "$res" + test "$(wc -l <<<"$res")" = 3 + grep -qx "$(printf 'i.pximg.net\tdirect\tslow\t50000')" <<<"$res" + grep -qx "$(printf 'audio.example\tdirect\tfast\t2000000')" <<<"$res" + # chains[0] is the exit that carried it, not the selector. + grep -qx "$(printf 'far.example\tprimary\tslow\t50000')" <<<"$res" + + j() { + jq -c --argjson o "$1" --argjson now 1000 --argjson ttl 100 --argjson hits 3 -f "$judge" <<<"$2" + } + slow='[{"d":"pximg.net","h":"i.pximg.net","exit":"direct","slow":true,"peak":50000}]' + onExitSlow='[{"d":"pximg.net","h":"i.pximg.net","exit":"primary","slow":true,"peak":1}]' + onExitFast='[{"d":"pximg.net","h":"i.pximg.net","exit":"primary","slow":false,"peak":900000}]' + s='{"domains":{},"hosts":{"x.twimg.com":{"verdict":"censor"}},"exits":{},"backlog":{}}' + + # Three crawls within a day make the domain owed an exit; two do not. + s="$(j "$slow" "$s")"; s="$(j "$slow" "$s")" + jq -e '.slowWant == {}' <<<"$s" > /dev/null + s="$(j "$slow" "$s")" + jq -e '.slowWant["pximg.net"] == {host: "i.pximg.net", tried: []}' <<<"$s" > /dev/null + + # Left to zapret: never moved, however slow. + z='[{"d":"twimg.com","h":"x.twimg.com","exit":"direct","slow":true,"peak":1}]' + t="$(j "$z" "$s")"; t="$(j "$z" "$t")"; t="$(j "$z" "$t")" + jq -e '.slowWant["twimg.com"] == null' <<<"$t" > /dev/null + + # Once routed -- the prober picks the exit -- judged on that exit alone. + r='{"domains":{"pximg.net":{"verdict":"slow","exit":"primary","host":"i.pximg.net","at":0,"tried":["primary"]}}, + "hosts":{},"exits":{},"backlog":{}}' + # Fast there: kept, and a strike against it forgotten. + k="$(j "$onExitSlow" "$r")"; k="$(j "$onExitFast" "$k")" + jq -e '.domains["pximg.net"] | .bad == 0 and .at == 1000' <<<"$k" > /dev/null + # Crawling there too, twice: owed the next exit, the ones tried remembered. + u="$(j "$onExitSlow" "$r")"; u="$(j "$onExitSlow" "$u")" + jq -e '.domains["pximg.net"] == null and .slowWant["pximg.net"].tried == ["primary"]' <<<"$u" > /dev/null + + # Every exit failed it: left direct until slowSkip expires, however slow. + w='{"domains":{},"hosts":{},"exits":{},"backlog":{},"slowSkip":{"pximg.net":1100}}' + w="$(j "$slow" "$w")"; w="$(j "$slow" "$w")"; w="$(j "$slow" "$w")" + jq -e '.slowWant == {} and .slowSkip["pximg.net"] == 1100' <<<"$w" > /dev/null + + touch "$out" + ''; + + # Per-user inbound traffic: collection and `proxy-ctl inbounds stats`. + inbound-stats = + pkgs.runCommand "proxy-suite-inbound-stats-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.gawk + pkgs.gnugrep + pkgs.jq + ]; + } + '' + add=${../../modules/proxy-suite/inbound-stats-add.jq} + now=1789135690 # 2026-09-11 + a() { jq -c --argjson q "$1" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; } + + # XRay gives values as strings and leaves a zero counter without one. + r='{"stat":[{"name":"user>>>fufsob>>>traffic>>>downlink","value":"3000000"}, + {"name":"user>>>fufsob>>>traffic>>>uplink","value":"2000"}, + {"name":"user>>>phone>>>traffic>>>uplink"}]}' + s="$(a "$r" '{}')" + s="$(a "$r" "$s")" + jq -e '.days["2026-09-11"].fufsob == {down: 6000000, up: 4000} + and .days["2026-09-11"].phone.up == 0 and .at == 1789135690' <<<"$s" > /dev/null + # Nothing counted since the last reading: nothing changes. + jq -e --argjson s "$s" '.days == $s.days' <<<"$(a '{}' "$s")" > /dev/null + # Days more than a year old are let go. + old="$(jq -c '.days["2024-01-01"] = {fufsob: {up: 1}}' <<<"$s")" + jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null + + jq -c '.days["2026-09-10"] = {fufsob: {down: 1073741824, up: 1048576}}' <<<"$s" > "$TMPDIR/stats.json" + cat > "$TMPDIR/test.sh" <<'EOF' + set -euo pipefail + . ${../../pkgs/proxy-ctl-lib.sh} + id() { echo 1000; } + date() { echo 2026-09-10; } + export INBOUNDS_STATS_FILE="$TMPDIR/stats.json" + out="$(_inbound_stats 2)" + printf '%s\n' "$out" + # Newest day first, sizes readable, then totals over the period. + test "$(grep -oE '^ 2026-09-1[01]' <<<"$out" | head -n 1)" = " 2026-09-11" + grep -qE '^ 2026-09-11 +fufsob +5\.7 MiB +4 KiB$' <<<"$out" + grep -qE '^ 2026-09-11 +phone +0 B +0 B$' <<<"$out" + grep -qE '^ 2026-09-10 +fufsob +1\.0 GiB +1\.0 MiB$' <<<"$out" + grep -qE '^ fufsob +1\.0 GiB +1\.0 MiB$' <<<"$out" + ! (_inbound_stats 0) 2> /dev/null + # Nothing collected yet says so, rather than printing an empty table. + ! (INBOUNDS_STATS_FILE="$TMPDIR/none.json" _inbound_stats 7) 2> "$TMPDIR/err" + grep -q 'No traffic recorded yet' "$TMPDIR/err" + + # --- proxy-ctl inbounds sub ----------------------------------------- + printf '%s' '[{"user":"fufsob","token":"aaa"},{"user":"teri","token":"bbb"}]' > "$TMPDIR/subs.json" + export INBOUNDS_SUBS_FILE="$TMPDIR/subs.json" + test "$(INBOUNDS_SUB_BASE_URL=https://vpn.example/sub/ _inbound_subscriptions teri)" = https://vpn.example/sub/bbb + # Without a user: names only, never a token. + out="$(INBOUNDS_SUB_BASE_URL=https://vpn.example/sub _inbound_subscriptions 2> /dev/null)" + test "$(wc -l <<<"$out")" = 2 + ! grep -qE 'aaa|bbb' <<<"$out" + ! (_inbound_subscriptions nobody) 2> /dev/null + # Without a base URL: the file path, and no QR code. + test "$(INBOUNDS_SUB_BASE_URL= _inbound_subscriptions fufsob 2> /dev/null)" = "$TMPDIR/subs/aaa" + ! (INBOUNDS_SUB_BASE_URL= _inbound_subscriptions fufsob --qr) 2> /dev/null + EOF + bash "$TMPDIR/test.sh" + touch "$out" + ''; + proxy-ctl-amneziawg = pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check" { @@ -134,7 +772,6 @@ bash "$proxy_ctl" awg list > list-output grep -q 'home.*active' list-output grep -q 'work.*inactive' list-output - test "$(bash "$proxy_ctl" awg status)" = home bash "$proxy_ctl" awg on work bash "$proxy_ctl" awg off home bash "$proxy_ctl" awg restart home diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index 1a39b31..1fcf47b 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -44,20 +44,27 @@ let routeModeBackendJqFilter = import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { + lib = pkgs.lib; pureXrayEnabled = false; + proxyInboundsGuardPrivate = false; selectionMode = routeModeFixture.config.services.proxy-suite.proxy.selection; }; - routeModeSetterScript = generated.readDerivation ( - (import ../../modules/proxy-suite/service/control-scripts.nix { - inherit pkgs; - lib = pkgs.lib; - proxyCfg = routeModeFixture.config.services.proxy-suite.proxy; - routeModeStateFile = "/run/proxy-suite/route-mode"; - subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/sing-box"; - subscriptionCacheHelpersBlock = ""; - mkSubscriptionFetchBlock = _: ""; - }).setRouteModeScript - ); + routeModeControlScripts = import ../../modules/proxy-suite/service/control-scripts.nix { + inherit pkgs; + lib = pkgs.lib; + proxyCfg = routeModeFixture.config.services.proxy-suite.proxy; + clashApi = "http://127.0.0.1:9090"; + routeModeStateFile = "/run/proxy-suite/route-mode"; + priorityOutboundFile = "/var/lib/proxy-suite/priority-outbound"; + outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json"; + subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/sing-box"; + subscriptionCacheHelpersBlock = ""; + mkSubscriptionFetchBlock = _: ""; + runtimeSubscriptionsFetchBlock = ""; + jq = "${pkgs.jq}/bin/jq"; + }; + routeModeSetterScript = generated.readDerivation routeModeControlScripts.setRouteModeScript; + prioritySetterScript = generated.readDerivation routeModeControlScripts.setPriorityOutboundScript; routeModeRules = mkRouteModeRules routeModeFixture; in { @@ -73,7 +80,7 @@ in # proxy-ctl help/status exposes default plus the explicit route modes. ( - assert pkgs.lib.hasInfix "route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" + assert pkgs.lib.hasInfix "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]" minimalProxyCtlScript; assert pkgs.lib.hasInfix ''printf 'route_mode=%s\n' "$(_route_mode_current)"'' minimalProxyCtlScript; @@ -119,5 +126,38 @@ in assert pkgs.lib.hasInfix "all-bypass)" routeModeSetterScript; true ) + + # The outbound pin reuses the same unit-plus-state-file shape, but persists + # across a reboot and prefers a live Clash switch over a restart. + ( + let + selectSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-select@"; + reloadSvc = routeModeFixture.config.systemd.services."proxy-suite-outbound-reload"; + in + assert selectSvc.serviceConfig.RemainAfterExit == false; + assert selectSvc.serviceConfig.StateDirectory == "proxy-suite"; + assert reloadSvc.serviceConfig.RemainAfterExit == false; + assert pkgs.lib.hasInfix "/var/lib/proxy-suite/priority-outbound" prioritySetterScript; + assert pkgs.lib.hasInfix ''rm -f "/var/lib/proxy-suite/priority-outbound"'' prioritySetterScript; + assert pkgs.lib.hasInfix "/proxies/proxy" prioritySetterScript; + assert pkgs.lib.hasInfix "systemctl restart proxy-suite-socks" prioritySetterScript; + true + ) + + # proxy-ctl reaches both through the wrapper environment. + ( + assert + shellValueByPrefix minimalProxyCtlWrapper "export OUTBOUND_INVENTORY_FILE=" + == "/run/proxy-suite-socks/outbounds.json"; + assert + shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_OUTBOUNDS_DIR=" + == "/var/lib/proxy-suite/outbounds.d"; + assert + shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR=" + == "/var/lib/proxy-suite/subscriptions.d"; + assert pkgs.lib.hasInfix "proxy select [|auto]" minimalProxyCtlScript; + assert pkgs.lib.hasInfix "proxy outbounds add " minimalProxyCtlScript; + true + ) ]; } diff --git a/nix/checks/ssh-proxy.nix b/nix/checks/ssh-proxy.nix index 5d59eeb..05eddbd 100644 --- a/nix/checks/ssh-proxy.nix +++ b/nix/checks/ssh-proxy.nix @@ -12,13 +12,11 @@ let testHostKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - # The socks start script always passes proxy.tproxy.proxyMark as the routing - # mark, so an expected outbound has to carry it to match byte for byte. + # Expected outbounds carry proxy.tproxy.proxyMark, as the start script sets it. markOf = fixture: fixture.config.services.proxy-suite.proxy.tproxy.proxyMark; - # writeText paths are content-addressed, so asserting the store path appears - # in the start script pins the exact generated JSON without reading it back. - # The context has to go, or the check derivation refuses to mention the path. + # writeText paths are content-addressed: finding one in the start script pins the + # JSON. The context is dropped so the check may mention it. expectedOutboundFile = backend: value: builtins.unsafeDiscardStringContext "${ @@ -33,15 +31,15 @@ let enable = true; sshProxy = { enable = true; - user = "root"; - host = "ssh.example.com"; + server.user = "root"; + server.host = "ssh.example.com"; asOutbound = true; identityFile = "/run/secrets/ssh-key"; hostKey = [ testHostKey ]; }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; }; }; } @@ -60,8 +58,7 @@ let routing_mark = markOf sshNativeSingBox; }; - # hostKeyFile is read at start time, so the keys must be injected by the - # start script rather than baked into the outbound JSON. + # hostKeyFile keys are injected at start, not baked into the JSON. sshHostKeyFile = evalProxySuite [ { system.stateVersion = "26.05"; @@ -69,15 +66,15 @@ let enable = true; sshProxy = { enable = true; - user = "root"; - host = "ssh.example.com"; - sshPort = 2222; + server.user = "root"; + server.host = "ssh.example.com"; + server.port = 2222; asOutbound = true; hostKeyFile = "/run/secrets/ssh-known-hosts"; }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; }; }; } @@ -86,8 +83,7 @@ let sshHostKeyFile.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); - # asOutbound = false is a standalone tunnel no backend knows about, so the - # OpenSSH unit is still created even on SingBox. + # asOutbound = false: a standalone tunnel, so the OpenSSH unit exists even on SingBox. sshStandalone = evalProxySuite [ { system.stateVersion = "26.05"; @@ -95,8 +91,8 @@ let enable = true; sshProxy = { enable = true; - user = "root"; - host = "ssh.example.com"; + server.user = "root"; + server.host = "ssh.example.com"; asOutbound = false; serviceUser = "proxy"; identityFile = "/run/secrets/ssh-key"; @@ -108,7 +104,7 @@ let }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; outbounds = [ { tag = "static"; @@ -130,8 +126,7 @@ let unchanged.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); - # XRay has no SSH outbound, so it keeps the unit and proxies through its - # local SOCKS5 listener, with domainStrategy mapped onto sockopt. + # XRay keeps the unit and proxies through its listener, domainStrategy on sockopt. sshXray = evalProxySuite [ { system.stateVersion = "26.05"; @@ -139,14 +134,14 @@ let enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; domainStrategy = "prefer_ipv4"; }; proxy = { enable = true; - xray.enable = true; + backend = "xray"; }; }; } @@ -176,15 +171,14 @@ let enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; hostKey = [ testHostKey ]; }; proxy = { enable = true; - singBox.enable = true; - xray.enable = true; + backend = "hybrid"; }; }; } @@ -209,14 +203,14 @@ let enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; hostKey = [ testHostKey ]; }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; selection = "selector"; outbounds = [ { @@ -239,13 +233,13 @@ let enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; }; proxy = { enable = true; - xray.enable = true; + backend = "xray"; selection = "urltest"; outbounds = [ { @@ -268,14 +262,14 @@ let enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; hostKey = [ testHostKey ]; }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; selection = "selector"; routing.rules = [ { @@ -293,8 +287,8 @@ let enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; hostKey = [ testHostKey ]; }; @@ -308,21 +302,21 @@ let }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; }; } { enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; hostKey = [ testHostKey ]; }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; outbounds = [ { tag = "ssh-proxy"; @@ -331,19 +325,18 @@ let ]; }; } - # SingBox verifies host keys by value, so an empty hostKey would silently - # accept any key. + # An empty hostKey would accept any key on SingBox. { enable = true; sshProxy = { enable = true; - user = "proxy"; - host = "ssh.example.com"; + server.user = "proxy"; + server.host = "ssh.example.com"; asOutbound = true; }; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; }; } ]; diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix index fab149e..bb90fc1 100644 --- a/nix/checks/subscriptions-runtime.nix +++ b/nix/checks/subscriptions-runtime.nix @@ -67,9 +67,37 @@ in true ) - # selection=first renames the first subscription outbound to "proxy". + # selection=first renames the pinned outbound - or the first one, absent a + # pin - to "proxy" at start, rather than collapsing at eval time. ( - assert builtins.match ".*proxy.*" subscriptionFirstSelectionStartScript != null; + assert pkgs.lib.hasInfix ''PROXY_TAG="$PRIORITY_OUTBOUND"'' subscriptionFirstSelectionStartScript; + assert + pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end)'' + subscriptionFirstSelectionStartScript; + true + ) + + # The pin is read from state, and one that names nothing is dropped. + ( + assert + pkgs.lib.hasInfix "/var/lib/proxy-suite/priority-outbound" subscriptionOnlyStartScript; + assert + pkgs.lib.hasInfix "pinned outbound '$PRIORITY_OUTBOUND' is not available" + subscriptionOnlyStartScript; + true + ) + + # proxy-ctl reads the inventory the start script leaves behind. + ( + assert pkgs.lib.hasInfix ''> "$RUNTIME_DIR/outbounds.json"'' subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix ''chmod 644 "$RUNTIME_DIR/outbounds.json"'' subscriptionOnlyStartScript; + true + ) + + # Outbounds added at runtime share the URL path with the declared ones. + ( + assert pkgs.lib.hasInfix "_proxy_suite_runtime_outbounds" subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_add_url_outbound" subscriptionWithStaticStartScript; true ) @@ -85,26 +113,36 @@ in true ) - # Generated cache paths use the raw validated tag, not shell-escaped quotes. + # Cache paths are built from the tag argument, so a tag never reaches the + # filename shell-quoted. ( - assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/sing-box/community.json"'' + assert pkgs.lib.hasInfix ''SUB_CACHE_DIR="/var/lib/proxy-suite/subscriptions/sing-box"'' subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix "/var/lib/proxy-suite/subscriptions/sing-box/community.json.tmp" - subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''cache="$SUB_CACHE_DIR/$1.json"'' subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix ''cache="$SUB_CACHE_DIR/$1.json"'' subscriptionOnlyUpdateScript; assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyStartScript); assert !(pkgs.lib.hasInfix "subscriptions/'community'.json" subscriptionOnlyUpdateScript); true ) - # The fetcher's stdout has to land in the cache file. A newline between the - # pipeline and the redirect closes the pipeline, leaving a bare redirect - # that truncates the cache to zero bytes while the JSON goes to the journal. + # Declared and runtime subscriptions both go through the same two entry + # points, with the tag passed raw. ( - assert pkgs.lib.hasInfix ''--tag-prefix community > "$CACHE_FILE.tmp"'' + assert pkgs.lib.hasInfix "_proxy_suite_load_subscription community " subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix - ''--tag-prefix community > "/var/lib/proxy-suite/subscriptions/sing-box/community.json.tmp"'' + assert pkgs.lib.hasInfix "_proxy_suite_fetch_subscription community " subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''_proxy_suite_load_subscription "$RUNTIME_SUB_TAG"'' + subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix ''_proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG"'' + subscriptionOnlyUpdateScript; + true + ) + + # The fetcher's output must land in the cache, not after a stray newline. + ( + assert pkgs.lib.hasInfix ''--tag-prefix "$tag" > "$cache.tmp"'' subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix ''--tag-prefix "$tag" > "$cache.tmp"'' subscriptionOnlyUpdateScript; true ) @@ -133,13 +171,36 @@ in true ) - # No update service or timer exists without subscriptions. + # The update service and timer exist whenever the proxy does, because a + # subscription can be added at runtime after the rebuild. ( - assert !(minimal.config.systemd.services ? "proxy-suite-subscription-update"); + assert minimal.config.systemd.services ? "proxy-suite-subscription-update"; true ) ( - assert !(minimal.config.systemd.timers ? "proxy-suite-subscription-update"); + assert minimal.config.systemd.timers ? "proxy-suite-subscription-update"; + true + ) + + # Runtime spool dirs are group-writable and setgid, so proxy-ctl needs no sudo. + ( + assert + builtins.any ( + rule: builtins.match "d /var/lib/proxy-suite/outbounds\\.d 2770 root .*" rule != null + ) minimal.config.systemd.tmpfiles.rules; + assert + builtins.any ( + rule: builtins.match "d /var/lib/proxy-suite/subscriptions\\.d 2770 root .*" rule != null + ) minimal.config.systemd.tmpfiles.rules; + true + ) + + # Both kinds of subscription go through one loader, and the runtime spool is + # walked at start and on refresh. + ( + assert pkgs.lib.hasInfix "_proxy_suite_load_subscription" subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_runtime_subscriptions" subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_runtime_subscriptions" subscriptionOnlyUpdateScript; true ) ]; diff --git a/nix/checks/subscriptions-runtime/fixtures.nix b/nix/checks/subscriptions-runtime/fixtures.nix index 906b574..88bf8ca 100644 --- a/nix/checks/subscriptions-runtime/fixtures.nix +++ b/nix/checks/subscriptions-runtime/fixtures.nix @@ -13,7 +13,7 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; subscriptions = [ { tag = "community"; @@ -41,7 +41,7 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; outbounds = [ { tag = "own-vps"; @@ -71,7 +71,7 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; subscriptions = [ { tag = "community"; @@ -94,16 +94,18 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; subscriptions = [ { tag = "community"; url = "https://example.com/sub/token"; } ]; - tun.perApp.enable = true; }; - perAppRouting.enable = true; + perAppRouting = { + enable = true; + tun.enable = true; + }; }; } ]; diff --git a/nix/checks/subscriptions-validation.nix b/nix/checks/subscriptions-validation.nix index 284d341..69111bc 100644 --- a/nix/checks/subscriptions-validation.nix +++ b/nix/checks/subscriptions-validation.nix @@ -13,7 +13,7 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; inherit subscriptions; }; }; diff --git a/nix/checks/tg-ws-proxy.nix b/nix/checks/tg-ws-proxy.nix index 029a429..5698654 100644 --- a/nix/checks/tg-ws-proxy.nix +++ b/nix/checks/tg-ws-proxy.nix @@ -38,11 +38,11 @@ in { assertions = [ ( - assert tgSecretFile.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; + assert tgSecretFile.config.services.proxy-suite.tgWsProxy.listener.address == "127.0.0.1"; true ) ( - assert minimal.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; + assert minimal.config.services.proxy-suite.tgWsProxy.listener.address == "127.0.0.1"; true ) ( diff --git a/nix/checks/tg-ws-proxy/fixtures.nix b/nix/checks/tg-ws-proxy/fixtures.nix index e8eef99..a0ae4d0 100644 --- a/nix/checks/tg-ws-proxy/fixtures.nix +++ b/nix/checks/tg-ws-proxy/fixtures.nix @@ -15,7 +15,7 @@ let { services.proxy-suite.tgWsProxy = { enable = true; - host = "127.0.0.1"; + listener.address = "127.0.0.1"; secretFile = "/run/secrets/tg-ws-proxy"; }; } @@ -27,21 +27,21 @@ let { services.proxy-suite.tgWsProxy = { enable = true; - port = 2443; - host = "0.0.0.0"; + listener.port = 2443; + listener.address = "0.0.0.0"; secretFile = "/run/secrets/tg-ws-proxy"; - verbose = true; - logFile = "/var/log/tg-ws-proxy.log"; - logMaxMb = 2.5; - logBackups = 3; - bufKb = 512; + log.verbose = true; + log.file = "/var/log/tg-ws-proxy.log"; + log.maxSizeMiB = 2.5; + log.keep = 3; + bufferKiB = 512; poolSize = 8; - cfProxyDomains = [ + cloudflare.domains = [ "cdn.example.com" "edge.example.net" ]; - cfProxyWorkerDomains = [ "worker.example.com" ]; - cfProxyFallback = false; + cloudflare.workerDomains = [ "worker.example.com" ]; + cloudflare.fallback = false; fakeTlsDomain = "mask.example.com"; proxyProtocol = true; }; @@ -92,7 +92,7 @@ let tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; - routingMark = 1; + fwmark = 1; }; }; } @@ -102,7 +102,7 @@ let services.proxy-suite.tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; - bufKb = 3; + bufferKiB = 3; }; } ] @@ -120,7 +120,7 @@ let services.proxy-suite.tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; - logBackups = 0; + log.keep = 0; }; } ] diff --git a/nix/checks/user-control.nix b/nix/checks/user-control.nix index 1166b3e..905fa97 100644 --- a/nix/checks/user-control.nix +++ b/nix/checks/user-control.nix @@ -9,10 +9,10 @@ let baseModule { services.proxy-suite = { - proxy.tun.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; + tun.enable = true; }; }; } @@ -22,10 +22,7 @@ let userControlGlobalOnlyFixture = evalProxySuite [ baseModule { - services.proxy-suite.userControl = { - global.enable = true; - perApp.enable = false; - }; + services.proxy-suite.userControl.allow = [ "global" ]; } ]; userControlGlobalOnlyPolkitConfig = userControlGlobalOnlyFixture.config.security.polkit.extraConfig; @@ -34,15 +31,12 @@ let baseModule { services.proxy-suite = { - proxy.tun.perApp.enable = true; perAppRouting = { enable = true; createDefaultProfiles = true; + tun.enable = true; }; - userControl = { - global.enable = false; - perApp.enable = true; - }; + userControl.allow = [ "perApp" ]; }; } ]; @@ -51,12 +45,30 @@ let userControlDisabledFixture = evalProxySuite [ baseModule { - services.proxy-suite.userControl = { - global.enable = false; - perApp.enable = false; - }; + services.proxy-suite.userControl.allow = [ ]; } ]; + + # Every unit declaring the autoProxy state directory must carry the group, or + # the next start chowns it back and `proxy auto list|queue` loses its read. + mkAutoProxyFixture = + extra: + evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.autoProxy.enable = true; + } + // extra; + } + ]; + autoProxyGroups = + fixture: + map (unit: fixture.config.systemd.services.${unit}.serviceConfig.Group or null) [ + "proxy-suite-autoproxy" + "proxy-suite-autoproxy-learn" + "proxy-suite-autoproxy-sample" + ]; in { assertions = [ @@ -100,6 +112,33 @@ in true ) + # -- userControl: the autoProxy state directory is group-owned, and only then -- + ( + assert + autoProxyGroups (mkAutoProxyFixture { }) == [ + "proxy-suite" + "proxy-suite" + "proxy-suite" + ]; + assert + autoProxyGroups (mkAutoProxyFixture { + userControl.group = "vpnops"; + }) == [ + "vpnops" + "vpnops" + "vpnops" + ]; + assert + autoProxyGroups (mkAutoProxyFixture { + userControl.allow = [ ]; + }) == [ + null + null + null + ]; + true + ) + # -- userControl: disabling both scopes removes group and polkit wiring -- ( assert !(userControlDisabledFixture.config.users.groups ? "proxy-suite"); diff --git a/nix/checks/xray-backend-features.nix b/nix/checks/xray-backend-features.nix index 6cf1802..37fdc64 100644 --- a/nix/checks/xray-backend-features.nix +++ b/nix/checks/xray-backend-features.nix @@ -27,8 +27,9 @@ in { assertions = [ ( - assert pkgs.lib.hasInfix ''CACHE_FILE="/var/lib/proxy-suite/subscriptions/xray/xray-sub.json"'' + assert pkgs.lib.hasInfix ''SUB_CACHE_DIR="/var/lib/proxy-suite/subscriptions/xray"'' xraySubscriptionStartScript; + assert pkgs.lib.hasInfix "_proxy_suite_load_subscription xray-sub" xraySubscriptionStartScript; assert pkgs.lib.hasInfix "--backend xray" xraySubscriptionStartScript; true ) diff --git a/nix/checks/xray-backend-features/fixtures.nix b/nix/checks/xray-backend-features/fixtures.nix index d48120f..3c6df6e 100644 --- a/nix/checks/xray-backend-features/fixtures.nix +++ b/nix/checks/xray-backend-features/fixtures.nix @@ -22,11 +22,15 @@ let backend = null; backendArg = null; xraySidecarRoutingMark = null; + priorityOutboundFile = null; + runtimeOutboundsDir = null; jq = null; python3 = null; parserScriptsPythonPath = null; buildOutboundPy = null; mkSubscriptionBlock = null; + mkSubscriptionLoadHelperBlock = null; + runtimeSubscriptionsBlock = null; }).rawOutboundJson; xrayRawStreamDefinition = { @@ -56,7 +60,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; subscriptions = [ { tag = "xray-sub"; @@ -78,7 +82,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; outbounds = [ xrayRawStreamDefinition ]; }; }; @@ -96,7 +100,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; dns.local = { type = "tcp"; address = "9.9.9.9"; @@ -118,7 +122,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; dns.remote = { type = "tls"; address = "1.1.1.1"; @@ -148,7 +152,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; selection = "selector"; outbounds = [ { @@ -162,7 +166,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; outbounds = [ { tag = "raw"; @@ -177,7 +181,7 @@ let enable = true; proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; outbounds = [ { tag = "raw"; diff --git a/nix/checks/xray-backend-runtime/fixtures.nix b/nix/checks/xray-backend-runtime/fixtures.nix index 71a2d9f..0498bae 100644 --- a/nix/checks/xray-backend-runtime/fixtures.nix +++ b/nix/checks/xray-backend-runtime/fixtures.nix @@ -16,7 +16,7 @@ let enable = true; proxy = { enable = true; - xray.enable = true; + backend = "xray"; selection = "urltest"; outbounds = [ { @@ -34,15 +34,13 @@ let block.domains = [ "block.example" ]; }; tproxy.enable = true; - tproxy.perApp.enable = true; - tun = { - enable = true; - perApp.enable = true; - }; + tun.enable = true; }; perAppRouting = { enable = true; createDefaultProfiles = true; + tun.enable = true; + tproxy.enable = true; }; }; }; @@ -81,6 +79,8 @@ let xrayBackendJqFilter = import ../../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { + lib = pkgs.lib; + proxyInboundsGuardPrivate = false; pureXrayEnabled = true; selectionMode = xrayFixture.config.services.proxy-suite.proxy.selection; }; diff --git a/nix/checks/xray-backend-runtime/service-shape.nix b/nix/checks/xray-backend-runtime/service-shape.nix index 588c23d..030f704 100644 --- a/nix/checks/xray-backend-runtime/service-shape.nix +++ b/nix/checks/xray-backend-runtime/service-shape.nix @@ -23,7 +23,7 @@ ); balancer = builtins.head xrayTproxyConfig.routing.balancers; in - assert xrayFixture.config.services.proxy-suite.proxy.xray.enable; + assert xrayFixture.config.services.proxy-suite.proxy.backend == "xray"; assert xrayFixture.config.systemd.services ? "proxy-suite-socks"; assert xrayFixture.config.systemd.services ? "proxy-suite-tproxy"; assert xrayFixture.config.systemd.services ? "proxy-suite-tun"; diff --git a/nix/checks/zapret-hostlist-routing/fixtures.nix b/nix/checks/zapret-hostlist-routing/fixtures.nix index 67f78d6..c3078a2 100644 --- a/nix/checks/zapret-hostlist-routing/fixtures.nix +++ b/nix/checks/zapret-hostlist-routing/fixtures.nix @@ -13,7 +13,7 @@ let { services.proxy-suite.zapret = { enable = true; - hostlistRules = [ + zapret-discord-youtube.hostlistRules = [ { name = "googlevideo"; domains = [ @@ -81,7 +81,7 @@ let { services.proxy-suite.zapret = { enable = true; - hostlistRules = [ + zapret-discord-youtube.hostlistRules = [ { name = "dup"; domains = [ "one.example" ]; @@ -100,7 +100,7 @@ let { services.proxy-suite.zapret = { enable = true; - hostlistRules = [ + zapret-discord-youtube.hostlistRules = [ { name = "empty"; domains = [ ]; @@ -114,7 +114,7 @@ let { services.proxy-suite.zapret = { enable = true; - hostlistRules = [ + zapret-discord-youtube.hostlistRules = [ { name = "missing"; domains = [ "missing.example" ]; @@ -127,7 +127,7 @@ let { services.proxy-suite.zapret = { enable = true; - hostlistRules = [ + zapret-discord-youtube.hostlistRules = [ { name = "conflict"; defaultDomains = [ "google" ]; @@ -142,7 +142,7 @@ let { services.proxy-suite.zapret = { enable = true; - hostlistRules = [ + zapret-discord-youtube.hostlistRules = [ { name = "missing-family"; domains = [ "example.com" ]; diff --git a/nix/checks/zapret/fixtures.nix b/nix/checks/zapret/fixtures.nix index fd4aae9..afe5303 100644 --- a/nix/checks/zapret/fixtures.nix +++ b/nix/checks/zapret/fixtures.nix @@ -24,58 +24,60 @@ let zapretSyncBase = mkZapretBase zapretSyncFixture; zapretSpacedConfigAliasBase = mkZapretBase (evalZapret { - configName = "general(ALT12)"; + zapret-discord-youtube.configName = "general(ALT12)"; }); zapretUnspacedConfigAliasBase = mkZapretBase (evalZapret { - configName = "general (ALT)"; + zapret-discord-youtube.configName = "general (ALT)"; }); zapretSyncNoExtraListsFixture = evalZapret { - includeExtraUpstreamLists = false; + zapret-discord-youtube.includeExtraUpstreamLists = false; }; zapretSyncNoExtraListsBase = mkZapretBase zapretSyncNoExtraListsFixture; zapretSyncNoExtraListsRules = mkRoutingRules zapretSyncNoExtraListsFixture; zapretSyncExtraListsFixture = evalZapret { - includeExtraUpstreamLists = true; + zapret-discord-youtube.includeExtraUpstreamLists = true; }; zapretSyncExtraListsBase = mkZapretBase zapretSyncExtraListsFixture; zapretSyncExtraListsRules = mkRoutingRules zapretSyncExtraListsFixture; zapretSyncIpsRules = mkRoutingRules (evalZapret { - syncDirectRoutingUpstreamIps = true; + directSync.upstreamIps = true; }); zapretSyncUserIpsDisabledRules = mkRoutingRules (evalZapret { - syncDirectRoutingUserIps = false; - ipsetAll = [ "203.0.113.0/24" ]; + directSync.userIps = false; + zapret-discord-youtube.ips = [ "203.0.113.0/24" ]; }); zapretSyncDisabledRules = mkRoutingRules (evalZapret { - syncDirectRouting = false; + directSync.enable = false; }); zapretSyncDomainsOnlyRules = mkRoutingRules (evalZapret { - syncDirectRouting = true; - syncDirectRoutingUpstreamIps = false; + directSync = { + enable = true; + upstreamIps = false; + }; }); zapretExtrasRules = mkRoutingRules (evalZapret { - listGeneral = [ "pixiv.net" ]; + zapret-discord-youtube.domains = [ "pixiv.net" ]; }); zapretIpExtrasRules = mkRoutingRules (evalZapret { - ipsetAll = [ "203.0.113.0/24" ]; + zapret-discord-youtube.ips = [ "203.0.113.0/24" ]; }); zapretExcludesRules = mkRoutingRules (evalZapret { - listExclude = [ "discord.com" ]; + zapret-discord-youtube.excludeDomains = [ "discord.com" ]; }); zapretIpExcludesRules = mkRoutingRules (evalZapret { - ipsetExclude = [ "1.1.1.0/24" ]; - ipsetAll = [ "1.1.1.0/24" ]; + zapret-discord-youtube.excludeIps = [ "1.1.1.0/24" ]; + zapret-discord-youtube.ips = [ "1.1.1.0/24" ]; }); in { diff --git a/nix/checks/zapret2.nix b/nix/checks/zapret2.nix new file mode 100644 index 0000000..a9d4ef1 --- /dev/null +++ b/nix/checks/zapret2.nix @@ -0,0 +1,163 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkProxyCtlDerived, + mkBadFixture, + mkFailingAssertions, +}: + +let + inherit (pkgs) lib; + + fixtures = import ./zapret2/fixtures.nix { inherit evalProxySuite baseModule; }; + inherit (fixtures) + zapretDiscordYoutubeGlobal + zapret2Global + zapret2PerApp + zapret2Tuned + zapret2NoAuto + ; + + envValue = + fixture: serviceName: prefix: + lib.removePrefix prefix ( + builtins.head ( + builtins.filter ( + value: lib.hasPrefix prefix value + ) fixture.config.systemd.services.${serviceName}.serviceConfig.Environment + ) + ); + + globalService = "zapret-discord-youtube"; + perAppService = "proxy-suite-per-app-zapret"; + + zapretBase = fixture: envValue fixture globalService "ZAPRET_BASE="; + runtimeDir = fixture: serviceName: envValue fixture serviceName "ZAPRET_RW="; + + globalRuntime = runtimeDir zapret2Global globalService; + perAppGlobalRuntime = runtimeDir zapret2PerApp globalService; + perAppRuntime = runtimeDir zapret2PerApp perAppService; + tunedRuntime = runtimeDir zapret2Tuned globalService; + noAutoRuntime = runtimeDir zapret2NoAuto globalService; + + proxyCtlEnv = fixture: (mkProxyCtlDerived fixture).wrapperEnv; +in +{ + assertions = [ + # The engine changes the implementation, not the unit names. + ( + assert lib.hasInfix "zapret2" (zapretBase zapret2Global); + assert !(lib.hasInfix "zapret2" (zapretBase zapretDiscordYoutubeGlobal)); + assert zapret2Global.config.systemd.services ? ${globalService}; + assert !(zapret2Global.config.systemd.services ? ${perAppService}); + true + ) + + # Both instances share the state directory. + ( + assert envValue zapret2Global globalService "HOSTLIST_BASE=" == "/var/lib/proxy-suite/zapret2"; + assert + zapret2Global.config.systemd.services.${globalService}.serviceConfig.StateDirectory + == "proxy-suite"; + assert envValue zapret2PerApp perAppService "HOSTLIST_BASE=" == "/var/lib/proxy-suite/zapret2"; + true + ) + + # Two nfqws2 processes must not share a pidfile or a config. + ( + assert envValue zapret2PerApp globalService "PIDDIR=" == "/run/proxy-suite-zapret"; + assert envValue zapret2PerApp perAppService "PIDDIR=" == "/run/proxy-suite-per-app-zapret"; + assert perAppGlobalRuntime != perAppRuntime; + true + ) + + # `proxy-ctl zapret auto` only makes sense when something is learning. + ( + assert (proxyCtlEnv zapret2Global).ZAPRET_AUTO_ENABLED == "1"; + assert (proxyCtlEnv zapretDiscordYoutubeGlobal).ZAPRET_AUTO_ENABLED == "0"; + assert (proxyCtlEnv zapret2Global).ZAPRET_STATE_DIR == "/var/lib/proxy-suite/zapret2"; + true + ) + ]; + + runtime = + pkgs.runCommand "proxy-suite-zapret2-config-check" + { + nativeBuildInputs = [ pkgs.gnugrep ]; + } + '' + base=${zapretBase zapret2Global} + + # --- generated config ------------------------------------------------- + grep -qx 'MODE_FILTER=autohostlist' "${globalRuntime}/config" + grep -qx 'AUTOHOSTLIST_FAIL_THRESHOLD=3' "${globalRuntime}/config" + grep -qx 'AUTOHOSTLIST_FAIL_TIME=300' "${globalRuntime}/config" + grep -qx 'AUTOHOSTLIST_RETRANS_THRESHOLD=3' "${globalRuntime}/config" + grep -qx 'QNUM=300' "${globalRuntime}/config" + grep -qx 'FWTYPE=nftables' "${globalRuntime}/config" + grep -qx 'WS_USER=root' "${globalRuntime}/config" + grep -qx 'DISABLE_IPV6=1' "${globalRuntime}/config" + + # The NFQUEUE window must exceed the retransmission threshold. + grep -qx 'NFQWS2_TCP_PKT_OUT=9' "${globalRuntime}/config" + grep -qx 'NFQWS2_TCP_PKT_IN=15' "${globalRuntime}/config" + + # Learning off means list mode, not "no lists". + grep -qx 'MODE_FILTER=hostlist' "${noAutoRuntime}/config" + + # Tuned knobs reach the config, including the wider packet window. + grep -qx 'AUTOHOSTLIST_FAIL_THRESHOLD=5' "${tunedRuntime}/config" + grep -qx 'AUTOHOSTLIST_FAIL_TIME=120' "${tunedRuntime}/config" + grep -qx 'AUTOHOSTLIST_DEBUGLOG=1' "${tunedRuntime}/config" + grep -qx 'NFQWS2_TCP_PKT_OUT=10' "${tunedRuntime}/config" + + # Static filters only on hostlist profiles; the UDP profile stays list-free. + grep -qF -- ' --hostlist-domains=pinned.example --hostlist-exclude-domains=excluded.example' "${tunedRuntime}/config" + grep -qF -- ' --hostlist-domains=pinned.example --hostlist-exclude-domains=excluded.example' "${tunedRuntime}/config" + test "$(grep -oF -- '--hostlist-domains=pinned.example' "${tunedRuntime}/config" | wc -l)" = 2 + + # --- per-app instance ------------------------------------------------- + # Wrapped apps opted in explicitly, so no hostlist gates them. + grep -qx 'MODE_FILTER=none' "${perAppRuntime}/config" + grep -qx 'FILTER_MARK=0x10000000' "${perAppRuntime}/config" + grep -qx 'QNUM=201' "${perAppRuntime}/config" + grep -qx 'DESYNC_MARK=0x8000000' "${perAppRuntime}/config" + grep -qx 'DESYNC_MARK_POSTNAT=0x4000000' "${perAppRuntime}/config" + grep -qx 'ZAPRET_NFT_TABLE=proxy_suite_per_app_zapret' "${perAppRuntime}/config" + + # The global instance must keep its hands off per-app traffic. + hook="${perAppGlobalRuntime}/init.d/sysv/custom.d/50-proxy-suite-custom.sh" + test "$(grep -c 'mark and 0x10000000 != 0 return' "$hook")" = 4 + grep -q 'nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and 0x10000000 != 0 return' "$hook" + + # --- the command line nfqws2 receives --- + # Expand with zapret2's list.sh and let nfqws2 validate the result. + export HOSTLIST_BASE="$PWD/lists" + export ZAPRET_BASE="$base" + mkdir -p "$HOSTLIST_BASE" + touch "$HOSTLIST_BASE/zapret-hosts-auto.txt" \ + "$HOSTLIST_BASE/zapret-hosts-user.txt" \ + "$HOSTLIST_BASE/zapret-hosts-user-exclude.txt" + + . "${globalRuntime}/config" + . "$base/common/base.sh" + . "$base/common/list.sh" + + opt="--qnum=$QNUM $NFQWS2_OPT" + filter_apply_hostlist_target opt + + printf '%s\n' "$opt" | tr ' ' '\n' | grep -qx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" + printf '%s\n' "$opt" | tr ' ' '\n' | grep -qx -- '--hostlist-auto-fail-threshold=3' + printf '%s\n' "$opt" | tr ' ' '\n' | grep -qx -- '--hostlist-auto-fail-time=300' + + # --user is deliberately omitted: the sandbox is not root. + "$base/nfq2/nfqws2" --dry-run --fwmark="$DESYNC_MARK" \ + --lua-init=@"$base/lua/zapret-lib.lua" \ + --lua-init=@"$base/lua/zapret-antidpi.lua" \ + --lua-init=@"$base/lua/zapret-auto.lua" \ + $opt + + touch "$out" + ''; +} diff --git a/nix/checks/zapret2/fixtures.nix b/nix/checks/zapret2/fixtures.nix new file mode 100644 index 0000000..c8ae49c --- /dev/null +++ b/nix/checks/zapret2/fixtures.nix @@ -0,0 +1,61 @@ +{ + evalProxySuite, + baseModule, +}: + +let + mkZapret2 = + zapret: + evalProxySuite [ + baseModule + { + services.proxy-suite.zapret = { + engine = "zapret2"; + } + // zapret; + } + ]; +in +{ + zapretDiscordYoutubeGlobal = evalProxySuite [ + baseModule + { services.proxy-suite.zapret.enable = true; } + ]; + + zapret2Global = mkZapret2 { enable = true; }; + + zapret2PerApp = evalProxySuite [ + baseModule + { + services.proxy-suite = { + perAppRouting = { + enable = true; + zapret.enable = true; + }; + zapret = { + engine = "zapret2"; + enable = true; + }; + }; + } + ]; + + zapret2Tuned = mkZapret2 { + enable = true; + zapret2 = { + domains = [ "pinned.example" ]; + excludeDomains = [ "excluded.example" ]; + autoHostlist = { + failThreshold = 5; + failTime = 120; + retransThreshold = 4; + debugLog = true; + }; + }; + }; + + zapret2NoAuto = mkZapret2 { + enable = true; + zapret2.autoHostlist.enable = false; + }; +} diff --git a/nix/options-doc.nix b/nix/options-doc.nix index 0da6eef..91881e8 100644 --- a/nix/options-doc.nix +++ b/nix/options-doc.nix @@ -13,98 +13,37 @@ let inherit system; modules = [ proxySuiteModule - { - system.stateVersion = lib.trivial.release; - } + { system.stateVersion = lib.trivial.release; } ]; }; - filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module"); - singBoxPackagePlaceholder = "__proxy_suite_doc_pkg_sing_box__"; - xrayPackagePlaceholder = "__proxy_suite_doc_pkg_xray__"; - sanitizeConfigForDocs = - config: - builtins.removeAttrs config [ "singBox" ] - // lib.optionalAttrs ((config.proxyInbounds or { }) ? package) { - proxyInbounds = config.proxyInbounds // { - package = xrayPackagePlaceholder; - }; - } - // { - proxy = (config.proxy or { }) // { - singBox = - ((config.proxy or { }).singBox or { }) - // lib.optionalAttrs (((config.proxy or { }).singBox or { }) ? package) { - package = singBoxPackagePlaceholder; - }; - xray = - ((config.proxy or { }).xray or { }) - // lib.optionalAttrs (((config.proxy or { }).xray or { }) ? package) { - package = xrayPackagePlaceholder; - }; - }; - }; - renderConfigText = - config: - lib.replaceStrings - [ - "\"${singBoxPackagePlaceholder}\"" - "\"${xrayPackagePlaceholder}\"" - ] - [ - "pkgs.sing-box" - "pkgs.xray" - ] - (lib.generators.toPretty { } (sanitizeConfigForDocs config)); - mkGeneratedExampleValue = - option: - if (option ? _type) && option._type == "option" then - if option ? example then - option.example - else if (option ? type) && ((option.type.name or null) == "submodule") then - lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions (option.type.getSubOptions [ ])) - else if option ? default then - option.default + + # Visible options only (renamed aliases are hidden), packages shown by name. + visibleConfig = + opts: cfg: + lib.mapAttrs ( + name: opt: + if !lib.isOption opt then + visibleConfig opt cfg.${name} + else if lib.isDerivation cfg.${name} then + { + __pretty = _: "pkgs.${lib.getName cfg.${name}}"; + val = null; + } else - throw "Cannot generate example value for option ${lib.showOption option.loc}" - else - lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option); - defaultConfigText = renderConfigText eval.config.services.proxy-suite; - generatedExampleConfig = lib.mapAttrs (_: mkGeneratedExampleValue) ( - filterGeneratedOptions eval.options.services.proxy-suite - ); - exampleConfigText = renderConfigText (builtins.removeAttrs generatedExampleConfig [ "singBox" ]); - repoRoot = toString ../.; - repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main"; - transformDeclaration = - decl: - let - declStr = toString decl; - subpath = lib.removePrefix "/" (lib.removePrefix repoRoot declStr); - in - if lib.hasPrefix repoRoot declStr then - { - url = "${repoUrl}/${subpath}"; - name = subpath; - } - else - decl; + cfg.${name} + ) (lib.filterAttrs (name: opt: name != "_module" && (opt.visible or true) != false) opts); + optionDocs = pkgs.nixosOptionsDoc { - options = { - services = { - "proxy-suite" = eval.options.services.proxy-suite; - }; - }; + options.services.proxy-suite = eval.options.services.proxy-suite; documentType = "none"; variablelistId = "proxy-suite-options"; optionIdPrefix = "proxy-suite-opt-"; - transformOptions = opt: opt // { declarations = map transformDeclaration opt.declarations; }; + transformOptions = opt: opt // { declarations = [ ]; }; }; in import ./options-doc/render-options-markdown.nix { - inherit - pkgs - optionDocs - defaultConfigText - exampleConfigText - ; + inherit pkgs optionDocs; + defaultConfigText = lib.generators.toPretty { allowPrettyValues = true; } ( + visibleConfig eval.options.services.proxy-suite eval.config.services.proxy-suite + ); } diff --git a/nix/options-doc/render-options-markdown.nix b/nix/options-doc/render-options-markdown.nix index b8e8c29..2540e9e 100644 --- a/nix/options-doc/render-options-markdown.nix +++ b/nix/options-doc/render-options-markdown.nix @@ -2,48 +2,21 @@ pkgs, optionDocs, defaultConfigText, - exampleConfigText, }: -pkgs.runCommand "proxy-suite-options.md" { } '' - preamble="$TMPDIR/preamble.md" - sections="$TMPDIR/sections.md" - sections_with_anchors="$TMPDIR/sections-with-anchors.md" - section_index="$TMPDIR/sections-index.tsv" - toc="$TMPDIR/toc.md" +# One file per top-level option group, plus an index. The single 6k-line page was +# not navigable. +pkgs.runCommand "proxy-suite-options-doc" { } '' + mkdir -p "$out" "$TMPDIR/bodies" + all="$TMPDIR/all.md" + index_tsv="$TMPDIR/sections-index.tsv" - cat >"$preamble" <<'EOF' - # proxy-suite options + cat ${optionDocs.optionsCommonMark} >"$all" - This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options/default.nix`](/modules/proxy-suite/options/default.nix). - Update module option docs there instead of editing this file by hand. - - ## Table of contents - - EOF - - cat >"$sections" <<'EOF' - ## Complete default config - - ```nix - services.proxy-suite = ${defaultConfigText}; - ``` - - ## Complete example config - - This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options. - - ```nix - services.proxy-suite = ${exampleConfigText}; - ``` - - EOF - - cat ${optionDocs.optionsCommonMark} >>"$sections" - - : >"$section_index" - : >"$sections_with_anchors" - awk -v section_index="$section_index" -v out="$sections_with_anchors" ' + # Anchor every section and file it under its top-level group. Options directly + # under services.proxy-suite (only `enable`) stay on the index. + : >"$index_tsv" + awk -v outdir="$TMPDIR/bodies" -v index_tsv="$index_tsv" ' function slugify(text, slug) { slug = text gsub(/\\/, "", slug) @@ -56,141 +29,121 @@ pkgs.runCommand "proxy-suite-options.md" { } '' /^## / { title = substr($0, 4) - base = slugify(title) - count = seen[base] - seen[base]++ - slug = count == 0 ? base : base "-" count - - print title "\t" slug >> section_index - print "" >> out - } - - { - print >> out - } - ' "$sections" - - : >"$toc" - awk -F '\t' -v toc="$toc" ' - function addChild(parent, child, key) { - key = parent SUBSEP child - if (!(key in seenChild)) { - seenChild[key] = 1 - childCount[parent]++ - childOrder[parent, childCount[parent]] = child - } - } - - function indent(depth, i, prefix) { - prefix = "" - for (i = 0; i < depth; i++) { - prefix = prefix " " - } - return prefix - } - - function displayLabel(label) { - if (label == "*") { - return "item" - } - if (label ~ /^<.*>$/) { - return "`" label "`" - } - return label - } - - function printNode(path, label, depth, i, child, childPath, text) { - text = displayLabel(label) - if (path in slugByPath) { - text = "[" text "](#" slugByPath[path] ")" - } - - print indent(depth) "- " text >> toc - - for (i = 1; i <= childCount[path]; i++) { - child = childOrder[path, i] - childPath = path "." child - printNode(childPath, child, depth + 1) - } - } - - { - title = $1 - slug = $2 normalized = title gsub(/\\/, "", normalized) + count = split(normalized, parts, /\./) + group = (count <= 3) ? "index" : parts[3] + slug = slugify(title) + current = outdir "/" group ".md" - if (normalized ~ /^Complete /) { - sampleCount++ - sampleTitle[sampleCount] = title - sampleSlug[sampleCount] = slug - next + print title "\t" slug "\t" group >> index_tsv + print "" >> current + print $0 >> current + next + } + + { if (current != "") print >> current } + ' "$all" + + groups="$(cut -f3 "$index_tsv" | grep -v '^index$' | awk '!seen[$0]++')" + + # Per-group table of contents, nested by option path. + mkToc() { + awk -F '\t' -v want="$1" ' + function indent(depth, i, prefix) { + prefix = "" + for (i = 0; i < depth; i++) { + prefix = prefix " " + } + return prefix } - if (index(normalized, "services.proxy-suite") == 1) { - optionRootSeen = 1 - slugByPath[normalized] = slug + function displayLabel(label) { + if (label == "*") { + return "item" + } + if (label ~ /^<.*>$/) { + return "`" label "`" + } + return label + } + + function addChild(parent, child, key) { + key = parent SUBSEP child + if (!(key in seenChild)) { + seenChild[key] = 1 + childCount[parent]++ + childOrder[parent, childCount[parent]] = child + } + } + + function printNode(path, label, depth, i, child, childPath, text) { + text = displayLabel(label) + if (path in slugByPath) { + text = "[" text "](#" slugByPath[path] ")" + } + print indent(depth) "- " text + for (i = 1; i <= childCount[path]; i++) { + child = childOrder[path, i] + childPath = path "." child + printNode(childPath, child, depth + 1) + } + } + + $3 == want { + normalized = $1 + gsub(/\\/, "", normalized) + slugByPath[normalized] = $2 count = split(normalized, parts, /\./) - if (count < 3) { - next - } - parent = "services.proxy-suite" for (i = 3; i <= count; i++) { child = parts[i] addChild(parent, child) parent = parent "." child } - next } - otherCount++ - otherTitle[otherCount] = title - otherSlug[otherCount] = slug - } - - END { - if (sampleCount > 0) { - print "- Config samples" >> toc - for (i = 1; i <= sampleCount; i++) { - print " - [" sampleTitle[i] "](#" sampleSlug[i] ")" >> toc - } - } - - if (optionRootSeen) { - print "- services.proxy-suite" >> toc - for (i = 1; i <= childCount["services.proxy-suite"]; i++) { - child = childOrder["services.proxy-suite", i] - printNode("services.proxy-suite." child, child, 1) - } - } - - for (i = 1; i <= otherCount; i++) { - print "- [" otherTitle[i] "](#" otherSlug[i] ")" >> toc - } - } - ' "$section_index" - - raw="$TMPDIR/options.md.raw" - - cat "$preamble" >"$raw" - cat "$toc" >>"$raw" - printf '\n' >>"$raw" - cat "$sections_with_anchors" >>"$raw" - - awk ' - NF { - for (i = 0; i < blanks; i++) { - print "" - } - blanks = 0 - print - next - } + END { printNode("services.proxy-suite." want, want, 0) } + ' "$index_tsv" + } + for group in $groups; do { - blanks++ - } - ' "$raw" >"$out" + printf '# services.proxy-suite.%s\n\n' "$group" + printf 'Part of the [proxy-suite options reference](./index.md).\n\n' + printf '## Options\n\n' + mkToc "$group" + printf '\n' + cat "$TMPDIR/bodies/$group.md" + } >"$TMPDIR/$group.out" + done + + { + printf '# proxy-suite options\n\n' + printf 'Generated from the `services.proxy-suite` option descriptions under\n' + printf '[`modules/proxy-suite/options/`](/modules/proxy-suite/options/).\n' + printf 'Update the module option docs there instead of editing these files by hand.\n\n' + + printf '## Option groups\n\n' + for group in $groups; do + printf -- '- [%s](./%s.md)\n' "$group" "$group" + done + printf '\n' + + printf '## Complete default config\n\n' + printf '```nix\n' + printf 'services.proxy-suite = %s;\n' ${pkgs.lib.escapeShellArg defaultConfigText} + printf '```\n\n' + + if [ -f "$TMPDIR/bodies/index.md" ]; then + cat "$TMPDIR/bodies/index.md" + fi + } >"$TMPDIR/index.out" + + # Collapse runs of blank lines, drop trailing ones. + for group in $groups index; do + awk 'NF { if (blank) print ""; blank = 0; print; next } { blank = 1 }' \ + "$TMPDIR/$group.out" >"$out/$group.md" + done '' diff --git a/nix/readme-doc-fixture.nix b/nix/readme-doc-fixture.nix index df815e8..581a403 100644 --- a/nix/readme-doc-fixture.nix +++ b/nix/readme-doc-fixture.nix @@ -6,7 +6,7 @@ proxy = { enable = true; - singBox.enable = true; + backend = "sing-box"; outbounds = [ { tag = "primary"; diff --git a/pkgs/default.nix b/pkgs/default.nix index be791b6..99f202f 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -3,6 +3,7 @@ let amneziaWg = import ./amneziawg.nix { inherit pkgs; }; mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; }; mkProxySuiteTray = args: import ./proxy-suite-tray.nix ({ inherit pkgs; } // args); + zapret2 = import ./zapret2.nix { inherit pkgs; }; mkProxyCtl = import ./proxy-ctl.nix { lib = pkgs.lib; inherit pkgs; @@ -16,6 +17,7 @@ in mkTgWsProxy mkProxySuiteTray mkProxyCtl + zapret2 ; tg-ws-proxy = mkTgWsProxy { }; proxy-suite-tray = mkProxySuiteTray { }; diff --git a/pkgs/proxy-ctl-completion.bash b/pkgs/proxy-ctl-completion.bash new file mode 100644 index 0000000..832a4f3 --- /dev/null +++ b/pkgs/proxy-ctl-completion.bash @@ -0,0 +1,7 @@ +# proxy-ctl knows its own verbs, tags, profiles and units: ask it. +_proxy_ctl() { + mapfile -t COMPREPLY < <( + compgen -W "$(proxy-ctl __complete "${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null)" \ + -- "${COMP_WORDS[COMP_CWORD]}") +} +complete -F _proxy_ctl proxy-ctl diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index 6153c14..5827043 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -9,86 +9,116 @@ ALL_SERVICES=( zapret-discord-youtube ) -_awg_service() { - printf 'proxy-suite-awg-%s' "$1" +RESTART_SERVICES=( + proxy-suite-tproxy + proxy-suite-tun + proxy-suite-inbounds + proxy-suite-ssh-proxy + proxy-suite-tg-ws-proxy + zapret-discord-youtube +) + +_help() { + cat <<'EOF' +Usage: proxy-ctl [verb] [args] +A group without a verb shows its status or list. + + status [--tray] services and routing mode + restart restart active services + logs [unit] follow logs (default: every proxy-suite unit) + where 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 add an outbound at runtime + proxy outbounds rm remove a runtime outbound + proxy select [|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 add a subscription at runtime + proxy subs rm 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 [/path] [--json] [--exits a,b | --via tag] + find an exit that reaches a domain + proxy auto learn 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 + 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 | off [profile] | restart [profile] + + ssh [status|on|off] SSH SOCKS5 tunnel + + apps [list] per-app routing profiles + apps run -- [args] run a command through a profile + + inbounds [list] server inbounds + inbounds link [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) +EOF } -_awg_profile_exists() { - local wanted="$1" profile - for profile in "${AWG_PROFILES[@]}"; do - if [ "$profile" = "$wanted" ]; then - return 0 - fi - done - return 1 +# Completion candidates for the words already typed, one per line. The tree +# lives here, next to _help, not in the completion file. +_complete_tree() { + local profile + case "$*" in + "") printf '%s\n' status restart logs where proxy zapret awg ssh apps inbounds help ;; + proxy) printf '%s\n' status on off outbounds select mode subs tun tproxy auto ;; + "proxy outbounds") printf '%s\n' list add rm ;; + "proxy outbounds rm") _runtime_tags outbound ;; + "proxy subs") printf '%s\n' list update add rm ;; + "proxy subs rm") _runtime_tags subscription ;; + "proxy select") printf 'auto\n'; _outbound_tags ;; + "proxy mode") printf '%s\n' default whitelist blacklist all-proxy all-bypass ;; + "proxy tun" | "proxy tproxy" | zapret | ssh) printf '%s\n' status on off ;; + "proxy auto") printf '%s\n' list probe learn queue ;; + "zapret auto") printf '%s\n' list add forget exclude clear ;; + "zapret auto forget" | "zapret auto exclude") cat "$(_zapret_auto_file zapret-hosts-auto.txt)" ;; + awg) printf '%s\n' list on off restart ;; + "awg on" | "awg off" | "awg restart") printf '%s\n' "${AWG_PROFILES[@]}" ;; + apps) printf '%s\n' list run ;; + "apps run") jq -r '.[].name' "$PER_APP_ROUTING_PROFILES_FILE" ;; + inbounds) printf '%s\n' list link sub stats ;; + "inbounds link") jq -r '.[].tag' "$INBOUNDS_LINKS_FILE" | sort -u ;; + "inbounds sub") jq -r '.[].user' "$INBOUNDS_SUBS_FILE" ;; + logs) + printf '%s\n' "${ALL_SERVICES[@]}" + for profile in "${AWG_PROFILES[@]}"; do + _awg_service "$profile" + echo + done + ;; + where) jq -r '(.domains // {}) | keys[]' "$(_autoproxy_dir)/state.json" ;; + esac } -_require_awg_profile() { - local profile="$1" - if ! _awg_profile_exists "$profile"; then - echo "Unknown AmneziaWG profile: $profile" >&2 - exit 1 - fi +# The hidden verb the installed bash completion calls. Completing must never +# die or say anything, however unreadable the state behind an arm is. +cmd_complete() { + _complete_tree "$@" 2>/dev/null || true } -_active_awg_profiles() { - local profile service - for profile in "${AWG_PROFILES[@]}"; do - service="$(_awg_service "$profile")" - if _svc_active "$service"; then - printf '%s\n' "$profile" - fi - done +_die() { + echo "$*" >&2 + exit 1 } _usage() { - local status="${1:-1}" - echo "Usage: proxy-ctl [args]" - echo "" - echo "Commands:" - echo " help show this help message" - echo " status [--tray] show status of all proxy-suite services" - echo " proxy on|off enable/disable the proxy backend stack" - echo " tproxy on|off enable/disable TProxy transparent mode" - echo " tun on|off enable/disable TUN mode" - echo " ssh on|off enable/disable the SSH SOCKS5 proxy" - echo " awg list|status [profile] list profiles or show AmneziaWG status" - echo " awg on start an AmneziaWG profile" - echo " awg off [profile] stop one or all active AmneziaWG profiles" - echo " awg restart [profile] restart one or all active AmneziaWG profiles" - echo " route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" - echo " set temporary routing override" - echo " zapret on|off enable/disable zapret-discord-youtube" - echo " restart restart active global proxy-suite services" - echo " logs [service] follow service logs (default: proxy-suite-socks)" - echo " outbounds list outbounds and current selection" - echo " select switch to a specific outbound (selector mode)" - echo " apps list configured per-app routing profiles" - echo " wrap -- run a command via a perAppRouting profile" - echo " subscription list show subscriptions, cache age, and proxy count" - echo " subscription update force-refresh all subscription caches and restart active proxy services" - echo " inbounds [list] list server inbounds and their state" - echo " inbounds link [user] print the client share link for an inbound" - echo " inbounds qr [user] print the client share link as a QR code" - exit "$status" -} - -_svc_status() { - local svc="$1" - if ! systemctl cat "$svc" &>/dev/null; then - return - fi - local state - state=$(systemctl is-active "$svc" 2>/dev/null || true) - printf " %-44s %s\n" "$svc" "$state" + _die "Usage: proxy-ctl $*" } _bool() { - if "$@"; then - printf true - else - printf false - fi + if "$@"; then printf true; else printf false; fi } _svc_exists() { @@ -99,21 +129,37 @@ _svc_active() { systemctl is-active --quiet "$1" } -_require_service() { - local svc="$1" message="$2" - if ! _svc_exists "$svc"; then - echo "$message" - exit 1 - fi +_svc_status() { + _svc_exists "$1" || return 0 + printf " %-44s %s\n" "$1" "$(systemctl is-active "$1" 2>/dev/null || true)" } _stop_if_exists() { - local svc="$1" - if _svc_exists "$svc"; then - systemctl stop "$svc" || true + if _svc_exists "$1"; then systemctl stop "$1" || true; fi +} + +_toggle() { + local unit="$1" name="$2" verb="${3:-status}" + _svc_exists "$unit" || _die "$name is not enabled in this configuration." + case "$verb" in + status) systemctl is-active "$unit" || true ;; + on) systemctl start "$unit" ;; + off) systemctl stop "$unit" ;; + *) _usage "$name [status|on|off]" ;; + esac +} + +# Prints the QR code instead when $2 is 1. +_emit() { + if [ "$2" = 1 ]; then + printf '%s' "$1" | qrencode -t ANSIUTF8 + else + printf '%s\n' "$1" fi } +# --- status ------------------------------------------------------------------ + _route_mode_default() { printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}" } @@ -123,14 +169,9 @@ _route_mode_effective() { if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then mode=$(tr -d '\r\n[:space:]' < "${ROUTE_MODE_STATE_FILE}" 2>/dev/null || true) fi - case "$mode" in - whitelist|blacklist|all-proxy|all-bypass) - printf '%s' "$mode" - ;; - *) - _route_mode_default - ;; + whitelist|blacklist|all-proxy|all-bypass) printf '%s' "$mode" ;; + *) _route_mode_default ;; esac } @@ -144,24 +185,12 @@ _route_mode_current() { _route_mode_label() { case "$1" in - default) - printf 'Default (%s)' "$(_route_mode_label "$(_route_mode_default)")" - ;; - whitelist) - printf 'Whitelist (direct by default)' - ;; - blacklist) - printf 'Blacklist (proxy by default)' - ;; - all-proxy) - printf 'All Proxy (override)' - ;; - all-bypass) - printf 'All Bypass (override)' - ;; - *) - printf 'Unknown' - ;; + default) printf 'Default (%s)' "$(_route_mode_label "$(_route_mode_default)")" ;; + whitelist) printf 'Whitelist (direct by default)' ;; + blacklist) printf 'Blacklist (proxy by default)' ;; + all-proxy) printf 'All Proxy (override)' ;; + all-bypass) printf 'All Bypass (override)' ;; + *) printf 'Unknown' ;; esac } @@ -186,59 +215,1114 @@ _status_tray() { printf 'awg_profiles=%s\n' "$(IFS=,; echo "${AWG_PROFILES[*]}")" } -_ensure_app_routing() { - if [ "$PER_APP_ROUTING_ENABLED" != "1" ]; then - echo "perAppRouting is not enabled in services.proxy-suite.perAppRouting." - exit 1 +_status_row() { + printf " %-44s %s\n" "$1" "$2" +} + +# Nothing to say about a state that is absent or unreadable. +_status_row_if() { + [ -z "$2" ] || _status_row "$1" "$2" +} + +# The pin when there is one, otherwise whatever the backend is dialling. +_status_outbound() { + local pinned current + pinned="$(_outbound_inventory | jq -r '.pinned // ""' 2>/dev/null || true)" + if [ -n "$pinned" ]; then + printf '%s (pinned)' "$pinned" + return + fi + current="$(_outbound_current)" + if [ -n "$current" ]; then printf '%s' "$current"; fi +} + +_status_autoproxy() { + local state next + [ "${AUTOPROXY_ENABLED:-0}" = 1 ] || return 0 + state="$(_autoproxy_dir)/state.json" + [ -r "$state" ] || return 0 + printf '%s routed, %s queued' \ + "$(jq '(.domains // {}) | length' "$state" 2>/dev/null || echo '?')" \ + "$(jq '(.backlog // {}) | length' "$state" 2>/dev/null || echo '?')" + next="$(_autoproxy_next_run)" + if [ -n "$next" ]; then printf ', next run %s' "$(_in_time "$next")"; fi +} + +_status_zapret() { + local auto + [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ] || return 0 + auto="$(_zapret_auto_file zapret-hosts-auto.txt)" + [ -r "$auto" ] || return 0 + printf '%s learned' "$(grep -c . "$auto" || true)" +} + +cmd_status() { + if [ "${1:-}" = "--tray" ]; then + _status_tray + return + fi + local svc profile + echo "proxy-suite services:" + for svc in "${ALL_SERVICES[@]}"; do + _svc_status "$svc" + done + for profile in "${AWG_PROFILES[@]}"; do + _svc_status "$(_awg_service "$profile")" + done + if _svc_exists proxy-suite-socks || [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ]; then + echo "" + echo "routing:" + if _svc_exists proxy-suite-socks; then + _status_row "active mode" "$(_route_mode_label "$(_route_mode_current)")" + _status_row_if "outbound" "$(_status_outbound)" + _status_row_if "autoProxy" "$(_status_autoproxy)" + fi + _status_row_if "zapret2" "$(_status_zapret)" fi } -_profile_route() { - local profile="$1" - jq -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$PER_APP_ROUTING_PROFILES_FILE" +# Restarts what is running; starting something that was stopped on purpose is +# what `proxy on` is for. +cmd_restart() { + local svc profile + if _svc_exists proxy-suite-socks && _svc_active proxy-suite-socks; then + systemctl restart proxy-suite-socks + fi + for svc in "${RESTART_SERVICES[@]}"; do + if _svc_exists "$svc" && _svc_active "$svc"; then + systemctl restart "$svc" + fi + done + for profile in "${AWG_PROFILES[@]}"; do + if _svc_active "$(_awg_service "$profile")"; then + systemctl restart "$(_awg_service "$profile")" + fi + done } -_scope_running() { - systemctl --user list-units --type=scope --state=running --plain --no-legend "$1-*" \ - | grep -q . +# --- proxy ------------------------------------------------------------------- + +cmd_proxy() { + local verb="${1:-status}" + shift || true + case "$verb" in + status | on) _toggle proxy-suite-socks proxy "$verb" ;; + off) + _svc_exists proxy-suite-socks || _die "proxy is not enabled in this configuration." + _stop_if_exists proxy-suite-tproxy + _stop_if_exists proxy-suite-tun + systemctl stop proxy-suite-socks + ;; + outbounds) cmd_outbounds "$@" ;; + select) cmd_select "$@" ;; + mode) cmd_route_mode "$@" ;; + subs) cmd_subscription "$@" ;; + tun) _toggle proxy-suite-tun "proxy tun" "$@" ;; + tproxy) _toggle proxy-suite-tproxy "proxy tproxy" "$@" ;; + auto) cmd_proxy_auto "$@" ;; + probe | learn | queue | learned) cmd_proxy_auto "$verb" "$@" ;; + *) _usage "proxy [status|on|off|outbounds|select|mode|subs|tun|tproxy|auto]" ;; + esac } -_any_user_active() { - systemctl list-units --type=service --state=active --plain --no-legend "$1*.service" \ - | grep -q . +cmd_outbounds() { + local verb="${1:-list}" + shift || true + case "$verb" in + list) _outbounds_list ;; + add) _runtime_entry_add outbound "$@" ;; + rm | remove | del) _runtime_entry_rm outbound "$@" ;; + *) _usage "proxy outbounds [list|add |rm ]" ;; + esac +} + +# The inventory the running backend wrote: tags, where each came from, and the +# pin. Absent until the proxy has started once. +_outbound_inventory() { + if [ -r "${OUTBOUND_INVENTORY_FILE:-}" ]; then + cat "$OUTBOUND_INVENTORY_FILE" + else + printf '%s' '{}' + fi +} + +_outbound_tags() { + _outbound_inventory | jq -r '(.tags // [])[]' +} + +_require_outbound_inventory() { + if [ "$(_outbound_inventory | jq -r '(.tags // []) | length')" = 0 ]; then + _die "No outbounds are available yet - is proxy-suite-socks running?" + fi +} + +# What the backend is dialling right now, when it exposes a selector. Empty +# otherwise, which is the normal case for selection = "first" and for XRay. +_outbound_current() { + curl -sf "$CLASH_API/proxies/proxy" 2>/dev/null | jq -r '.now // empty' 2>/dev/null || true +} + +_outbounds_list() { + local inv pinned current selection mark tag source + _require_outbound_inventory + inv=$(_outbound_inventory) + pinned=$(jq -r '.pinned // ""' <<<"$inv") + selection=$(jq -r '.selection // "first"' <<<"$inv") + current=$(_outbound_current) + + echo "Selection: $selection" + if [ -n "$pinned" ]; then + echo "Pinned: $pinned" + else + echo "Pinned: (auto)" + fi + if [ -n "$current" ]; then + echo "Current: $current" + fi + echo "" + printf " %-34s %s\n" "TAG" "SOURCE" + while IFS=$'\t' read -r tag source; do + mark=" " + if [ "$tag" = "$pinned" ]; then + mark="*" + elif [ -z "$pinned" ] && [ "$tag" = "$current" ]; then + mark=">" + fi + printf " %s%-34s %s\n" "$mark" "$tag" "$source" + done < <(jq -r '. as $i | (.tags // [])[] | [., (($i.sources // {})[.] // "-")] | @tsv' <<<"$inv") +} + +# Runs in a command substitution, so anything fatal has to be checked by the +# caller first: an exit here would only leave the subshell. +_select_outbound_menu() { + local inv pinned + inv=$(_outbound_inventory) + pinned=$(jq -r '.pinned // ""' <<<"$inv") + { printf 'auto\n'; jq -r '(.tags // [])[]' <<<"$inv"; } | + fzf --prompt='outbound> ' --height=40% --reverse \ + --header="pinned: ${pinned:-auto} (auto = let the configured selection decide)" +} + +cmd_select() { + local tag="${1:-}" escaped + if [ -z "$tag" ]; then + if [ ! -t 0 ] || [ ! -t 1 ]; then + _usage "proxy select |auto" + fi + _require_outbound_inventory + # Empty when the menu was dismissed. + tag="$(_select_outbound_menu)" || return 0 + [ -n "$tag" ] || return 0 + fi + [ -n "$tag" ] || _usage "proxy select [|auto]" + escaped="$(systemd-escape -- "$tag")" + systemctl start "proxy-suite-outbound-select@${escaped}.service" || + _die "Failed - see: proxy-ctl logs proxy-suite-outbound-select@${escaped}" + if [ "$tag" = auto ]; then + echo "Selecting automatically again." + else + echo "Pinned: $tag" + fi +} + +# --- runtime outbounds and subscriptions ------------------------------------- +# +# One URL per file in a spool directory the userControl group may write. The +# backend reads them at start, which the reload unit triggers. + +_runtime_dir() { + if [ "$1" = outbound ]; then + printf '%s' "${RUNTIME_OUTBOUNDS_DIR:-/var/lib/proxy-suite/outbounds.d}" + else + printf '%s' "${RUNTIME_SUBS_DIR:-/var/lib/proxy-suite/subscriptions.d}" + fi +} + +_runtime_noun() { + if [ "$1" = outbound ]; then printf 'outbounds'; else printf 'subs'; fi +} + +_runtime_tags() { + local dir f tag + dir="$(_runtime_dir "$1")" + [ -d "$dir" ] || return 0 + for f in "$dir"/*.url; do + [ -e "$f" ] || continue + tag="${f##*/}" + printf '%s\n' "${tag%.url}" + done +} + +_check_runtime_tag() { + local kind="$1" tag="$2" t + case "$tag" in + proxy | direct | block) + _die "'$tag' is reserved; pick another $kind tag." + ;; + esac + if ! [[ "$tag" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + _die "Invalid $kind tag '$tag': letters, digits, dot, dash and underscore only." + fi + if _runtime_tags "$kind" | grep -qxF "$tag"; then + _die "A runtime $kind named '$tag' already exists; remove it first." + fi + if [ "$kind" = outbound ]; then + if _outbound_tags | grep -qxF "$tag"; then + _die "An outbound named '$tag' already exists." + fi + else + for t in "${SUB_TAGS[@]}"; do + if [ "$t" = "$tag" ]; then + _die "A subscription named '$tag' is declared in the configuration." + fi + done + fi +} + +_runtime_entry_add() { + local kind="$1" tag="${2:-}" url="${3:-}" file + if [ -z "$tag" ] || [ -z "$url" ]; then + _usage "proxy $(_runtime_noun "$kind") add " + fi + _check_runtime_tag "$kind" "$tag" + case "$url" in + *[[:space:]]*) _die "A URL cannot contain whitespace." ;; + esac + file="$(_runtime_dir "$kind")/$tag.url" + ( umask 027; printf '%s\n' "$url" > "$file" ) 2>/dev/null || + _die "Cannot write $file - join the ${USER_CONTROL_GROUP:-proxy-suite} group, or re-run with sudo." + _runtime_reload + _runtime_entry_verify "$kind" "$tag" +} + +_runtime_entry_rm() { + local kind="$1" tag="${2:-}" file + [ -n "$tag" ] || _usage "proxy $(_runtime_noun "$kind") rm " + file="$(_runtime_dir "$kind")/$tag.url" + if [ ! -e "$file" ]; then + _die "No runtime $kind named '$tag'. Ones declared in the NixOS configuration are removed there." + fi + rm -f "$file" 2>/dev/null || + _die "Cannot remove $file - join the ${USER_CONTROL_GROUP:-proxy-suite} group, or re-run with sudo." + _runtime_reload + echo "Removed $kind: $tag" +} + +_runtime_reload() { + systemctl start proxy-suite-outbound-reload.service || + _die "Saved, but applying it failed - see: proxy-ctl logs proxy-suite-outbound-reload" +} + +# Only the backend parses the URL, so confirm the entry actually came up. +_runtime_entry_verify() { + local kind="$1" tag="$2" cache + if [ "$kind" = outbound ]; then + if _outbound_tags | grep -qxF "$tag"; then + echo "Added outbound: $tag" + return + fi + else + cache="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}/$tag.json" + if [ -f "$cache" ]; then + echo "Added subscription: $tag ($(_subscription_proxy_count "$cache" 2>/dev/null || echo '?') proxies)" + return + fi + fi + echo "Saved $kind '$tag', but it did not come up. Check: proxy-ctl logs" >&2 + echo "Remove it again with: proxy-ctl proxy $(_runtime_noun "$kind") rm $tag" >&2 + exit 1 +} + +cmd_route_mode() { + local action="${1:-status}" + _svc_exists proxy-suite-socks || _die "proxy is not enabled in this configuration." + case "$action" in + status) _route_mode_current; echo ;; + default|whitelist|blacklist|all-proxy|all-bypass) + systemctl start "proxy-suite-route-mode@${action}.service" + echo "Switched to: $(_route_mode_label "$action")" + ;; + *) _usage "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]" ;; + esac +} + +_subscription_proxy_count() { + jq ' + if type == "array" then length + elif type == "object" and (.singBox | type == "array") and (.xray | type == "array") + then (.singBox | length) + (.xray | length) + else error("unsupported subscription cache shape") + end + ' "$1" +} + +_subscription_row() { + local tag="$1" source="$2" dir="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}" + local cache="$dir/$tag.json" age count + if [ -f "$cache" ]; then + age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown") + count=$(_subscription_proxy_count "$cache" 2>/dev/null || echo "?") + else + age="(no cache)" + count="-" + fi + printf " %-30s %-22s %-9s %s\n" "$tag" "$age" "$count" "$source" +} + +_subscription_list() { + local t runtime + runtime="$(_runtime_tags subscription)" + if [ ${#SUB_TAGS[@]} -eq 0 ] && [ -z "$runtime" ]; then + echo "No subscriptions configured." + return + fi + printf " %-30s %-22s %-9s %s\n" "TAG" "LAST UPDATED" "PROXIES" "SOURCE" + for t in "${SUB_TAGS[@]}"; do + _subscription_row "$t" static + done + while IFS= read -r t; do + [ -n "$t" ] || continue + _subscription_row "$t" runtime + done <<<"$runtime" +} + +cmd_subscription() { + local verb="${1:-list}" + shift || true + case "$verb" in + list) _subscription_list ;; + add) _runtime_entry_add subscription "$@" ;; + rm | remove | del) _runtime_entry_rm subscription "$@" ;; + update) + _svc_exists proxy-suite-subscription-update || _die "The proxy is not enabled in this configuration." + systemctl start proxy-suite-subscription-update + echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update" + ;; + *) _usage "proxy subs [list|update|add |rm ]" ;; + esac +} + +# --- proxy auto: reachability probe ------------------------------------------ +# +# Fetches a URL through one exit after another (direct first) and finds one +# whose origin answers. The exits are the per-exit loopback listeners +# proxy-suite-socks opens for autoProxy (PROBE_EXITS_FILE); without them, only +# this host and the local proxy. The apex decides when any exit gets content +# from it; robots.txt breaks ties when the apex is refused everywhere. + +PROBE_PATH="${PROBE_PATH:-/}" +PROBE_PATH_FALLBACK="${PROBE_PATH_FALLBACK:-/robots.txt}" +PROBE_UA="${PROBE_UA:-Mozilla/5.0 (X11; Linux x86_64) proxy-suite-probe}" +PROBE_EXITS_FILE="${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}" +PROBE_BLOCK_REDIRECT='unavailable|not-available|blocked|geo|region|restricted' + +# Last two labels: only used to keep redirect following on one site. +_probe_site() { + local host="${1#*://}" + host="${host%%[/:?#]*}" + printf '%s' "$host" | awk -F. '{ print $(NF - 1) "." $NF }' +} + +# $1 domain, $2 path, rest: curl egress selector. Echoes +# "||||" for the +# first hop that is not a same-site redirect: a block can sit at the end of a +# chain (spotify.com -> www -> open -> accounts -> why-not-available). +_probe_fetch() { + local domain="$1" path="$2" url site result hop rc + local -a ua=() + shift 2 + url="https://${domain}${path}" + site="$(_probe_site "$url")" + # An impersonating curl must keep its browser's own User-Agent. + [ -n "${PROBE_CURL:-}" ] || ua=(-A "$PROBE_UA") + for hop in 1 2 3 4 5 6; do + rc=0 + result="$("${PROBE_CURL:-curl}" -sS -o /dev/null \ + "${ua[@]}" \ + --connect-timeout "${PROBE_CONNECT_TIMEOUT:-8}" \ + --max-time "${PROBE_MAX_TIME:-15}" \ + -w '%{exitcode}|%{time_appconnect}|%{http_code}|%{size_download}|%{redirect_url}' \ + "$@" "$url" 2>/dev/null)" || rc=$? + # Not a dead site: curl itself did not start. + if [ -z "$result" ] && [ "$rc" -ge 126 ]; then + _die "Cannot run ${PROBE_CURL:-curl} (exit $rc)." + fi + [ -n "$result" ] || result='99|0|000|0|' + case "$(_probe_field "$result" 3)" in + 3??) ;; + *) break ;; + esac + _probe_redirect_is_block "$result" && break + url="$(_probe_field "$result" 5)" + { [ -n "$url" ] && [ "$(_probe_site "$url")" = "$site" ]; } || break + : "$hop" + done + printf '%s' "$result" +} + +_probe_field() { + printf '%s' "$1" | cut -d'|' -f"$2" +} + +# curl reports appconnect 0 when TLS never finished. +_probe_tls_ok() { + case "$(_probe_field "$1" 2)" in + "" | 0 | 0.000000) return 1 ;; + *) return 0 ;; + esac +} + +_probe_http_ok() { + case "$(_probe_field "$1" 3)" in + 2?? | 401 | 404) return 0 ;; + 3??) ! _probe_redirect_is_block "$1" ;; + *) return 1 ;; + esac +} + +_probe_redirect_is_block() { + printf '%s' "$(_probe_field "$1" 5)" | grep -qiE "$PROBE_BLOCK_REDIRECT" +} + +# dead: failed before the origin spoke (the censor's doing, zapret's job). +# blocked: the origin answered and refused (a proxy hop can fix it). +_probe_exit_verdict() { + if ! _probe_tls_ok "$1" || [ "$(_probe_field "$1" 3)" = "000" ]; then + printf 'dead' + elif _probe_http_ok "$1"; then + printf 'ok' + else + printf 'blocked' + fi +} + +_probe_verdict() { + local direct via + direct="$(_probe_exit_verdict "$1")" + via="$(_probe_exit_verdict "$2")" + if [ "$direct" = ok ]; then + printf 'ok' + elif [ "$via" = ok ]; then + if [ "$direct" = dead ]; then printf 'censor'; else printf 'destination'; fi + elif [ "$direct" = dead ]; then + printf 'unreachable' + else + printf 'both-fail' + fi +} + +_probe_verdict_text() { + case "$1" in + ok) printf 'reachable directly - nothing to do' ;; + destination) printf 'destination-side block - route via %s' "${2:-proxy}" ;; + censor) printf 'censor-side block - zapret2 territory, do not proxy' ;; + both-fail) printf 'fails through every egress - not an egress problem' ;; + unreachable) printf 'no egress reaches it at all' ;; + *) printf 'inconclusive' ;; + esac +} + +_probe_describe() { + local r="$1" status location + if ! _probe_tls_ok "$r"; then + printf 'no TLS (curl exit %s)' "$(_probe_field "$r" 1)" + return + fi + status="$(_probe_field "$r" 3)" + location="$(_probe_field "$r" 5)" + if [ "$status" = "000" ]; then + printf 'TLS %ss, then no response' "$(_probe_field "$r" 2)" + return + fi + printf 'TLS %ss, %s, %s bytes' "$(_probe_field "$r" 2)" "$status" "$(_probe_field "$r" 4)" + [ -n "$location" ] && printf ' -> %s' "$location" + return 0 +} + +# "tagproxy-url" per exit, in order; an empty url means this host. +_probe_exits() { + if [ -r "$PROBE_EXITS_FILE" ]; then + jq -r '.[] | "\(.tag)\thttp://127.0.0.1:\(.port)"' "$PROBE_EXITS_FILE" + else + printf 'direct\t\n' + printf 'proxy\t%s\n' "${LOCAL_PROXY_URL:-http://127.0.0.1:1080}" + fi +} + +_probe_fetch_exit() { + if [ -n "$3" ]; then + _probe_fetch "$1" "$2" --proxy "$3" + else + _probe_fetch "$1" "$2" --noproxy '*' + fi +} + +# Walks EXIT_TAGS/EXIT_URLS (direct first) and stops at the first exit that +# gets content. Sets WALK_VERDICT, WALK_EXIT, WALK_PATH, WALK_DIRECT, WALK_VIA +# and WALK_ROWS ("tagpathresultjudgement" per request). +_probe_walk() { + local domain="$1" path direct result judgement i first_direct="" + WALK_ROWS=() + WALK_EXIT="" + WALK_VIA="" + for path in "$PROBE_PATH" ${PROBE_PATH_FALLBACK:+"$PROBE_PATH_FALLBACK"}; do + direct="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[0]}")" + judgement="$(_probe_exit_verdict "$direct")" + WALK_ROWS+=("${EXIT_TAGS[0]}"$'\t'"$path"$'\t'"$direct"$'\t'"$judgement") + [ -n "$first_direct" ] || first_direct="$direct" + if [ "$judgement" = ok ]; then + WALK_VERDICT=ok + WALK_PATH="$path" + WALK_DIRECT="$direct" + return + fi + for ((i = 1; i < ${#EXIT_TAGS[@]}; i++)); do + result="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[i]}")" + judgement="$(_probe_exit_verdict "$result")" + WALK_ROWS+=("${EXIT_TAGS[i]}"$'\t'"$path"$'\t'"$result"$'\t'"$judgement") + if [ "$judgement" = ok ]; then + WALK_VERDICT="$(_probe_verdict "$direct" "$result")" + WALK_EXIT="${EXIT_TAGS[i]}" + WALK_PATH="$path" + WALK_DIRECT="$direct" + WALK_VIA="$result" + return + fi + done + done + WALK_PATH="$PROBE_PATH" + WALK_DIRECT="$first_direct" + if [ "$(_probe_exit_verdict "$first_direct")" = dead ]; then + WALK_VERDICT=unreachable + else + WALK_VERDICT=both-fail + fi +} + +# --via: can EXIT_TAGS[1] carry what direct reaches? It must get content on +# some path and fail on none where direct succeeds. Verdict "ok" or "blocked". +_probe_stand_in() { + local domain="$1" path direct via dj vj got=0 + WALK_ROWS=() + WALK_VERDICT=ok + WALK_EXIT="${EXIT_TAGS[1]}" + WALK_PATH="$PROBE_PATH" + for path in "$PROBE_PATH" ${PROBE_PATH_FALLBACK:+"$PROBE_PATH_FALLBACK"}; do + direct="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[0]}")" + via="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[1]}")" + dj="$(_probe_exit_verdict "$direct")" + vj="$(_probe_exit_verdict "$via")" + WALK_ROWS+=("${EXIT_TAGS[0]}"$'\t'"$path"$'\t'"$direct"$'\t'"$dj") + WALK_ROWS+=("${EXIT_TAGS[1]}"$'\t'"$path"$'\t'"$via"$'\t'"$vj") + if [ "$path" = "$PROBE_PATH" ]; then + WALK_DIRECT="$direct" + WALK_VIA="$via" + fi + [ "$vj" != ok ] || got=1 + if [ "$dj" = ok ] && [ "$vj" != ok ]; then WALK_VERDICT=blocked; fi + done + [ "$got" = 1 ] || WALK_VERDICT=blocked +} + +cmd_proxy_probe() { + local json=0 domain="" want="" have_want=0 via="" row tag + local -a rows wanted + while [ $# -gt 0 ]; do + case "$1" in + --json) json=1 ;; + --exits) + want="${2?--exits needs a comma-separated list of exit tags}" + have_want=1 + shift + ;; + --via) + via="${2?--via needs an exit tag}" + want="$via" + have_want=1 + shift + ;; + -*) _die "Unknown option: $1" ;; + *) domain="$1" ;; + esac + shift + done + + [ -n "$domain" ] || _usage "proxy auto probe [/path] [--json] [--exits a,b | --via tag]" + domain="${domain#*://}" + if [[ "$domain" == */* ]]; then + local PROBE_PATH="/${domain#*/}" PROBE_PATH_FALLBACK="" + domain="${domain%%/*}" + fi + + _svc_active proxy-suite-socks || _die "The local proxy (proxy-suite-socks) is not running; a probe needs its exits." + + # direct first, then every exit in order, or the ones asked for in that order. + mapfile -t rows < <(_probe_exits) + EXIT_TAGS=() + EXIT_URLS=() + for row in "${rows[@]}"; do + if [ "${row%%$'\t'*}" = direct ]; then + EXIT_TAGS+=(direct) + EXIT_URLS+=("${row#*$'\t'}") + fi + done + if [ "$have_want" = 1 ]; then + IFS=, read -ra wanted <<<"$want" + else + wanted=() + for row in "${rows[@]}"; do wanted+=("${row%%$'\t'*}"); done + fi + for tag in "${wanted[@]}"; do + [ "$tag" = direct ] && continue + for row in "${rows[@]}"; do + if [ "${row%%$'\t'*}" = "$tag" ]; then + EXIT_TAGS+=("$tag") + EXIT_URLS+=("${row#*$'\t'}") + break + fi + done + done + if [ "${#EXIT_TAGS[@]}" -eq 0 ] || [ "${EXIT_TAGS[0]}" != direct ]; then + _die "No direct exit to probe from ($PROBE_EXITS_FILE)." + fi + if [ -n "$via" ] && [ "${#EXIT_TAGS[@]}" -ne 2 ]; then + _die "No exit named $via other than direct ($PROBE_EXITS_FILE)." + fi + + if [ -n "$via" ]; then + _probe_stand_in "$domain" + else + _probe_walk "$domain" + fi + + if [ "$json" = 1 ]; then + printf '%s\n' "${WALK_ROWS[@]}" | jq -R -s -c \ + --arg domain "$domain" \ + --arg url "https://${domain}${WALK_PATH}" \ + --arg path "$WALK_PATH" \ + --arg verdict "$WALK_VERDICT" \ + --arg exit "$WALK_EXIT" \ + --arg direct "$WALK_DIRECT" \ + --arg via "$WALK_VIA" ' + (split("\n") | map(select(length > 0) | split("\t") + | {tag: .[0], path: .[1], result: .[2], judgement: .[3]})) as $exits + | {domain: $domain, url: $url, path: $path, verdict: $verdict, + exit: (if $exit == "" then null else $exit end), + direct: $direct, proxy: $via, exits: $exits}' + return + fi + + local t p r j chosen + printf ' domain %s\n' "$domain" + printf ' probe https://%s%s\n' "$domain" "$WALK_PATH" + printf ' exits\n' + for row in "${WALK_ROWS[@]}"; do + IFS=$'\t' read -r t p r j <<<"$row" + chosen="" + [ "$t" = "$WALK_EXIT" ] && [ "$p" = "$WALK_PATH" ] && chosen=" <- chosen" + printf ' %-18s %-12s %-44s %s%s\n' "$t" "$p" "$(_probe_describe "$r")" "$j" "$chosen" + done + if [ -n "$via" ]; then + if [ "$WALK_VERDICT" = ok ]; then + printf ' verdict %s answers it as well as direct does - it can carry it\n' "$via" + else + printf ' verdict %s answers it worse than direct does\n' "$via" + fi + return + fi + printf ' verdict %s\n' "$(_probe_verdict_text "$WALK_VERDICT" "$WALK_EXIT")" + case "$WALK_VERDICT" in + destination) + printf ' pin: proxy.routing.rules = [ { outbound = "%s"; domains = [ "%s" ]; } ]\n' \ + "$WALK_EXIT" "$domain" + ;; + censor) + printf ' try: proxy-ctl zapret auto add %s\n' "$domain" + ;; + esac +} + +_autoproxy_dir() { + printf '%s' "${AUTOPROXY_STATE_DIR:-/var/lib/proxy-suite/autoproxy}" +} + +_require_autoproxy() { + [ "${AUTOPROXY_ENABLED:-0}" = 1 ] || _die "proxy.autoProxy is not enabled in this configuration." +} + +# Root-only without userControl: say so rather than show an empty queue. +_require_autoproxy_readable() { + [ -d "$1" ] || _die "No autoProxy state yet - the prober has not completed a run." + { [ -x "$1" ] && [ -r "$1" ]; } || _die "Cannot read $1 - enable userControl, or run with sudo." +} + +cmd_proxy_auto() { + local verb="${1:-list}" + shift || true + case "$verb" in + list | learned) cmd_proxy_learned ;; + probe) cmd_proxy_probe "$@" ;; + learn) cmd_proxy_learn "$@" ;; + queue) cmd_proxy_queue "$@" ;; + *) _usage "proxy auto [list|probe|learn|queue]" ;; + esac +} + +# The timer is relative, so only list-timers knows the next run. Empty when +# none is armed. +_autoproxy_next_run() { + local next + next="$(systemctl list-timers -o json proxy-suite-autoproxy.timer 2>/dev/null | + jq -r '.[0].next // empty' 2>/dev/null || true)" + if [ -n "$next" ] && [ "$next" != 0 ]; then printf '%s' "$((next / 1000000))"; fi +} + +_in_time() { + local left=$(($1 - $(date +%s))) + if [ "$left" -lt 60 ]; then printf 'under a minute'; else printf 'in %s min' "$((left / 60))"; fi +} + +cmd_proxy_queue() { + local dir top="${1:-20}" waiting next + _require_autoproxy + [[ "$top" =~ ^[0-9]+$ ]] || _usage "proxy auto queue [count]" + dir="$(_autoproxy_dir)" + _require_autoproxy_readable "$dir" + + echo "Requested with proxy-ctl proxy auto learn:" + if [ -s "$dir/requests" ] || [ -s "$dir/requests.taking" ]; then + cat "$dir/requests" "$dir/requests.taking" 2>/dev/null | awk '{ print " " $0 }' + else + echo " (none)" + fi + + waiting="$(jq '(.backlog // {}) | length' "$dir/state.json" 2>/dev/null || echo 0)" + echo "" + echo "Waiting to be probed, most-dialled first ($waiting):" + if [ "$waiting" -gt 0 ]; then + jq -r --argjson top "$top" '(.backlog // {}) | to_entries | sort_by(-.value.hits) + | .[:$top][] | " \(.value.hits)\t\(.key)"' "$dir/state.json" + [ "$waiting" -le "$top" ] || echo " ... and $((waiting - top)) more" + else + echo " (none)" + fi + + next="$(_autoproxy_next_run)" + if [ -n "$next" ]; then + echo "" + echo "Next run: $(date -d "@$next" '+%H:%M:%S'), $(_in_time "$next")" + elif [ "$(systemctl show -p ActiveState --value proxy-suite-autoproxy.service 2>/dev/null)" = activating ]; then + echo "" + echo "Next run: one is running now" + fi +} + +cmd_proxy_learned() { + local dir + _require_autoproxy + dir="$(_autoproxy_dir)" + _require_autoproxy_readable "$dir" + + if ! jq -e '(.domains // {}) | length > 0' "$dir/state.json" > /dev/null 2>&1; then + echo "Nothing routed yet." + else + echo "Routed through an exit:" + jq -r --argjson now "$(date +%s)" ' + .domains | to_entries | sort_by(.key)[] + | ((($now - (.value.at // 0)) / 60) | floor) as $m + | "\(.key)\t\(.value.exit)\t\(.value.host)\(if .value.verdict == "slow" then ", which crawled directly" else "" end)\t\(if $m < 120 then "\($m)m" else "\($m / 60 | floor)h" end)"' \ + "$dir/state.json" | + awk -F'\t' '{ printf " %-28s -> %-12s (learned from %s, checked %s ago)\n", $1, $2, $3, $4 }' + fi + + echo "" + echo "Hosts judged: $(jq -r '[(.hosts // {})[] | .verdict] | group_by(.) + | map("\(.[0])=\(length)") | join(" ") | if . == "" then "none yet" else . end' \ + "$dir/state.json" 2>/dev/null || echo "none yet")" +} + +# Queues the host for the prober's own unit, so it is recorded under the same +# lock as a timer run. +cmd_proxy_learn() { + local host="${1:-}" dir + _require_autoproxy + dir="$(_autoproxy_dir)" + # Lands in a root-owned file and then in a URL: hostnames only. + [[ "$host" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || _usage "proxy auto learn " + printf '%s\n' "$host" >> "$dir/requests" 2>/dev/null || _die "Cannot write $dir/requests - re-run with sudo." + echo "Probing $host through each exit..." + if ! systemctl start proxy-suite-autoproxy-learn.service 2> /dev/null; then + echo "The probe run failed. $host is still queued and will be tried again at the next run." >&2 + _die "Details: journalctl -u proxy-suite-autoproxy-learn -n 20" + fi + jq -r --arg h "$host" ' + (.hosts // {})[$h] + | if . == null then "No verdict recorded; see: journalctl -u proxy-suite-autoproxy-learn" + elif .exit then "\(.domain): \(.verdict) - routed via \(.exit) from now on, no restart needed" + else "\($h): \(.verdict) - nothing to route" end' "$dir/state.json" +} + +# --- zapret ------------------------------------------------------------------ + +cmd_zapret() { + if [ "${1:-}" = auto ]; then + shift + cmd_zapret_auto "$@" + return + fi + _toggle zapret-discord-youtube zapret "$@" +} + +_zapret_auto_file() { + printf '%s/%s' "${ZAPRET_STATE_DIR:-/var/lib/proxy-suite/zapret2}" "$1" +} + +# nfqws2 re-reads a list when its mtime changes; no reload needed. +_zapret_auto_edit() { + local file="$1" domain="$2" action="$3" tmp + if [ ! -e "$file" ] && [ "$action" = drop ]; then + return 0 + fi + tmp=$(mktemp "$file.XXXXXX" 2>/dev/null) || _die "Cannot write $file - re-run with sudo." + grep -v -x -F -- "$domain" "$file" 2>/dev/null >"$tmp" || true + if [ "$action" = add ]; then + printf '%s\n' "$domain" >>"$tmp" + fi + chmod 0644 "$tmp" + if ! mv "$tmp" "$file"; then + rm -f "$tmp" + _die "Cannot replace $file - re-run with sudo." + fi +} + +cmd_zapret_auto() { + local verb="${1:-list}" domain="${2:-}" auto user exclude + [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ] || _die "Learned hostlists need zapret.engine = \"zapret2\"." + auto=$(_zapret_auto_file zapret-hosts-auto.txt) + user=$(_zapret_auto_file zapret-hosts-user.txt) + exclude=$(_zapret_auto_file zapret-hosts-user-exclude.txt) + + case "$verb" in + add | forget | exclude) + [[ "$domain" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || _usage "zapret auto $verb " + ;; + esac + case "$verb" in + list) + if [ -s "$auto" ]; then cat "$auto"; else echo "No hostnames learned yet."; fi + ;; + add) + _zapret_auto_edit "$user" "$domain" add + echo "Pinned $domain (always bypassed)." + ;; + forget) + _zapret_auto_edit "$auto" "$domain" drop + echo "Forgot $domain. It is learned again if it keeps failing; 'exclude' prevents that." + ;; + exclude) + _zapret_auto_edit "$auto" "$domain" drop + _zapret_auto_edit "$exclude" "$domain" add + echo "Excluded $domain. It is no longer touched or learned." + ;; + clear) + : >"$auto" 2>/dev/null || _die "Cannot write $auto - re-run with sudo." + echo "Cleared the learned hostlist." + ;; + *) _usage "zapret auto [list|add|forget|exclude|clear]" ;; + esac +} + +# --- where ------------------------------------------------------------------- +# +# What the runtime state says about one host. Hostlists and autoProxy both key +# on an apex, so a miss on the full name retries each parent label. + +_where_row() { + printf ' %-14s %s\n' "$1" "$2" +} + +_where_parents() { + local d="$1" + while [ -n "$d" ]; do + printf '%s\n' "$d" + case "$d" in + *.*) d="${d#*.}" ;; + *) d="" ;; + esac + done +} + +# The first parent of $2 that file $1 lists, empty when none is. +_where_in_list() { + local file="$1" d + [ -r "$file" ] || return 0 + while IFS= read -r d; do + if grep -qxF -- "$d" "$file" 2>/dev/null; then + printf '%s' "$d" + return 0 + fi + done < <(_where_parents "$2") +} + +_where_in_autoproxy() { + local state="$1" d + while IFS= read -r d; do + if jq -e --arg d "$d" 'has("domains") and (.domains | has($d))' "$state" > /dev/null 2>&1; then + printf '%s' "$d" + return 0 + fi + done < <(_where_parents "$2") +} + +cmd_where() { + local domain="${1:-}" state hit exit_tag outbound excluded pinned learned verdict="" + [ -n "$domain" ] || _usage "where " + domain="${domain#*://}" + domain="${domain%%/*}" + _where_row domain "$domain" + + if _svc_exists proxy-suite-socks; then + _where_row "route mode" "$(_route_mode_label "$(_route_mode_current)")" + outbound="$(_status_outbound)" + [ -z "$outbound" ] || _where_row outbound "$outbound" + fi + + if [ "${AUTOPROXY_ENABLED:-0}" = 1 ]; then + state="$(_autoproxy_dir)/state.json" + if [ ! -r "$state" ]; then + _where_row autoProxy "state is not readable - enable userControl, or run with sudo" + else + hit="$(_where_in_autoproxy "$state" "$domain")" + if [ -z "$hit" ]; then + _where_row autoProxy "not routed" + else + exit_tag="$(jq -r --arg d "$hit" '.domains[$d].exit' "$state")" + _where_row autoProxy "$(jq -r --arg d "$hit" --argjson now "$(date +%s)" ' + .domains[$d] | ((($now - (.at // 0)) / 60) | floor) as $m + | "routed via \(.exit), learned from \(.host), checked \( + if $m < 120 then "\($m)m" else "\($m / 60 | floor)h" end) ago"' "$state")" + verdict="proxied via $exit_tag" + fi + fi + fi + + if [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ]; then + excluded="$(_where_in_list "$(_zapret_auto_file zapret-hosts-user-exclude.txt)" "$domain")" + pinned="$(_where_in_list "$(_zapret_auto_file zapret-hosts-user.txt)" "$domain")" + learned="$(_where_in_list "$(_zapret_auto_file zapret-hosts-auto.txt)" "$domain")" + if [ -n "$excluded" ]; then + _where_row zapret2 "excluded ($excluded) - never bypassed, never learned" + elif [ -n "$pinned" ]; then + _where_row zapret2 "pinned ($pinned) - always bypassed" + [ -n "$verdict" ] || verdict="direct, with the zapret2 bypass" + elif [ -n "$learned" ]; then + _where_row zapret2 "learned ($learned) - bypassed" + [ -n "$verdict" ] || verdict="direct, with the zapret2 bypass" + else + _where_row zapret2 "not learned, not pinned, not excluded" + fi + fi + + echo " -> ${verdict:-nothing runtime matches it; the configured routing decides}" + echo " Declared proxy.routing.rules are not visible here. Test what reaches it:" + echo " proxy-ctl proxy auto probe $domain" +} + +# --- awg --------------------------------------------------------------------- + +_awg_service() { + printf 'proxy-suite-awg-%s' "$1" +} + +_require_awg_profile() { + local profile + for profile in "${AWG_PROFILES[@]}"; do + [ "$profile" = "$1" ] && return 0 + done + _die "Unknown AmneziaWG profile: $1" +} + +_active_awg_profiles() { + local profile + for profile in "${AWG_PROFILES[@]}"; do + if _svc_active "$(_awg_service "$profile")"; then + printf '%s\n' "$profile" + fi + done +} + +cmd_awg() { + local verb="${1:-list}" profile active + shift || true + if [ "$#" -gt 0 ]; then + _require_awg_profile "$1" + fi + case "$verb" in + list | status) + if [ "${#AWG_PROFILES[@]}" -eq 0 ]; then + echo "No AmneziaWG profiles configured." + return + fi + printf " %-24s %s\n" "PROFILE" "STATUS" + for profile in "${AWG_PROFILES[@]}"; do + active="$(systemctl is-active "$(_awg_service "$profile")" 2>/dev/null || true)" + printf " %-24s %s\n" "$profile" "${active:-unknown}" + done + ;; + on) + [ "$#" -gt 0 ] || _usage "awg on " + systemctl start "$(_awg_service "$1")" + ;; + off | restart) + if [ "$#" -gt 0 ]; then + active="$1" + else + active="$(_active_awg_profiles)" + if [ -z "$active" ]; then + [ "$verb" = off ] && return + _die "No AmneziaWG profile is active." + fi + fi + [ "$verb" = off ] && verb=stop + while IFS= read -r profile; do + systemctl "$verb" "$(_awg_service "$profile")" + done <<< "$active" + ;; + *) _usage "awg [list] | on | off [profile] | restart [profile]" ;; + esac +} + +# --- apps -------------------------------------------------------------------- + +_ensure_app_routing() { + [ "${PER_APP_ROUTING_ENABLED:-0}" = "1" ] || _die "perAppRouting is not enabled in this configuration." } _check_no_global_proxy() { - if systemctl is-active --quiet proxy-suite-tun.service; then - echo "Global proxy-suite-tun.service is active. Stop it before using route=$1 profiles." - exit 1 - fi - if systemctl is-active --quiet proxy-suite-tproxy.service; then - echo "Global proxy-suite-tproxy.service is active. Stop it before using route=$1 profiles." - exit 1 - fi + local svc + for svc in proxy-suite-tun proxy-suite-tproxy; do + if _svc_active "$svc.service"; then + _die "Global $svc.service is active. Stop it before using route=$1 profiles." + fi + done } _cleanup_slice_if_idle() { local slice_base="$1" anchor_unit="$2" user_svc="$3" backend_svc="$4" - - if ! _scope_running "$slice_base"; then + if ! systemctl --user list-units --type=scope --state=running --plain --no-legend "$slice_base-*" | grep -q .; then systemctl stop "$user_svc" || true systemctl --user stop "$anchor_unit" || true - if ! _any_user_active "$slice_base-user@"; then + if ! systemctl list-units --type=service --state=active --plain --no-legend "$slice_base-user@*.service" | grep -q .; then systemctl stop "$backend_svc" || true fi fi } -# _wrap_slice [cmd...] +# _wrap_slice _wrap_slice() { local slice_base="$1" profile="$2" enabled="$3" disabled_msg="$4" backend_svc="$5" shift 5 - if [ "$enabled" != "1" ]; then - echo "$disabled_msg" - exit 1 - fi + [ "$enabled" = "1" ] || _die "$disabled_msg" local uid; uid="$(id -u)" local scope_unit="$slice_base-${profile}-$$" local anchor_unit="$slice_base-anchor.service" @@ -251,383 +1335,81 @@ _wrap_slice() { trap cleanup_slice EXIT systemctl --user start "$anchor_unit" || status=$? - if [ "$status" -eq 0 ]; then - systemctl start "$backend_svc" || status=$? - fi - if [ "$status" -eq 0 ]; then - systemctl start "$user_svc" || status=$? - fi + [ "$status" -ne 0 ] || systemctl start "$backend_svc" || status=$? + [ "$status" -ne 0 ] || systemctl start "$user_svc" || status=$? if [ "$status" -eq 0 ]; then systemd-run --user --scope --quiet --collect --same-dir \ --slice="$slice_base" --unit="$scope_unit" "$@" || status=$? fi - exit "$status" } -_subscription_proxy_count() { - local cache="$1" - jq ' - if type == "array" then - length - elif type == "object" - and (.singBox | type == "array") - and (.xray | type == "array") - then - (.singBox | length) + (.xray | length) - else - error("unsupported subscription cache shape") - end - ' "$cache" -} - -cmd_status() { - if [ "${1:-}" = "--tray" ]; then - _status_tray - return - fi - - echo "proxy-suite services:" - for svc in "${ALL_SERVICES[@]}"; do - _svc_status "$svc" - done - for profile in "${AWG_PROFILES[@]}"; do - _svc_status "$(_awg_service "$profile")" - done - if _svc_exists proxy-suite-socks; then - echo "" - echo "routing:" - echo " active mode $(_route_mode_label "$(_route_mode_current)")" - fi -} - -cmd_proxy() { - case "${1:-on}" in - on) - _require_service proxy-suite-socks "SOCKS proxy service is not available because proxy.enable is not enabled." - systemctl start proxy-suite-socks - ;; - off) - _require_service proxy-suite-socks "SOCKS proxy service is not available because proxy.enable is not enabled." - _stop_if_exists proxy-suite-tproxy - _stop_if_exists proxy-suite-tun - systemctl stop proxy-suite-socks - ;; - *) - echo "Usage: proxy-ctl proxy on|off" - exit 1 - ;; - esac -} - -cmd_mode_toggle() { - local name="$1" - local default_action="${2:-on}" - local display="${4:-${name#proxy-suite-}}" - _require_service "$name" "Service '$name' is not available in this proxy-suite configuration." - case "${3:-$default_action}" in - on) - systemctl start "$name" - ;; - off) - systemctl stop "$name" - ;; - *) - echo "Usage: proxy-ctl $display on|off" - exit 1 - ;; - esac -} - -cmd_zapret() { cmd_mode_toggle "zapret-discord-youtube" on "${1:-on}" "zapret"; } - -cmd_route_mode() { - local action - - if ! _svc_exists proxy-suite-socks; then - echo "Route mode is unavailable because proxy services are not enabled." - exit 1 - fi - - action="${1:-status}" - - case "$action" in - status) - echo "$(_route_mode_current)" - ;; - default|whitelist|blacklist|all-proxy|all-bypass) - systemctl start "proxy-suite-route-mode@${action}.service" - echo "Switched to: $(_route_mode_label "$action")" - ;; - *) - echo "Usage: proxy-ctl route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" - exit 1 - ;; - esac -} - -RESTART_SERVICES=( - proxy-suite-tproxy - proxy-suite-tun - proxy-suite-inbounds - proxy-suite-ssh-proxy - proxy-suite-tg-ws-proxy - zapret-discord-youtube -) - -cmd_restart() { - if _svc_exists proxy-suite-socks; then - systemctl restart proxy-suite-socks - fi - - for svc in "${RESTART_SERVICES[@]}"; do - if _svc_exists "$svc" && _svc_active "$svc"; then - systemctl restart "$svc" - fi - done - local profile - for profile in "${AWG_PROFILES[@]}"; do - if _svc_active "$(_awg_service "$profile")"; then - systemctl restart "$(_awg_service "$profile")" - fi - done -} - -cmd_awg() { - local action="${1:-list}" profile service active +cmd_apps() { + local verb="${1:-list}" shift || true - - case "$action" in + _ensure_app_routing + case "$verb" in list) - if [ "${#AWG_PROFILES[@]}" -eq 0 ]; then - echo "No AmneziaWG profiles configured." + if [ "$(jq 'length' "$PER_APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then + echo "No perAppRouting profiles configured." return fi - printf " %-24s %s\n" "PROFILE" "STATUS" - for profile in "${AWG_PROFILES[@]}"; do - service="$(_awg_service "$profile")" - active="$(systemctl is-active "$service" 2>/dev/null || true)" - printf " %-24s %s\n" "$profile" "${active:-unknown}" - done - ;; - status) - if [ "$#" -gt 0 ]; then - profile="$1" - _require_awg_profile "$profile" - systemctl is-active "$(_awg_service "$profile")" - else - _active_awg_profiles - fi - ;; - on) - profile="${1:?Usage: proxy-ctl awg on }" - _require_awg_profile "$profile" - systemctl start "$(_awg_service "$profile")" - ;; - off) - if [ "$#" -gt 0 ]; then - profile="$1" - _require_awg_profile "$profile" - systemctl stop "$(_awg_service "$profile")" - else - for profile in "${AWG_PROFILES[@]}"; do - service="$(_awg_service "$profile")" - if _svc_active "$service"; then - systemctl stop "$service" - fi - done - fi - ;; - restart) - if [ "$#" -gt 0 ]; then - profile="$1" - _require_awg_profile "$profile" - systemctl restart "$(_awg_service "$profile")" - else - active="$(_active_awg_profiles)" - if [ -z "$active" ]; then - echo "No AmneziaWG profile is active." >&2 - exit 1 - fi - while IFS= read -r profile; do - systemctl restart "$(_awg_service "$profile")" - done <<< "$active" - fi - ;; - *) - echo "Usage: proxy-ctl awg list|status [profile]|on |off [profile]|restart [profile]" >&2 - exit 1 + printf " %-24s %s\n" "PROFILE" "ROUTE" + jq -r '.[] | "\(.name)\t\(.route)"' "$PER_APP_ROUTING_PROFILES_FILE" | + awk -F'\t' '{ printf " %-24s %s\n", $1, $2 }' ;; + run) cmd_apps_run "$@" ;; + *) _usage "apps [list] | run -- [args]" ;; esac } -cmd_outbounds() { - local data now ob_type - data=$(curl -sf "$CLASH_API/proxies/proxy" 2>/dev/null) || { - echo "Clash API not available." - echo " - Make sure proxy-suite-socks is running" - echo " - selection must be 'selector' or 'urltest' (currently: $SELECTION)" - exit 1 - } - now=$(echo "$data" | jq -r '.now // "n/a"') - ob_type=$(echo "$data" | jq -r '.type // "n/a"') - echo "Type: $ob_type" - echo "Current: $now" - echo "" - echo "Available:" - echo "$data" | jq -r '.all[]? | " " + .' -} - -cmd_select() { - local tag payload - tag="${1:?Usage: proxy-ctl select }" - if [ "$SELECTION" != "selector" ]; then - echo "selection must be 'selector' (currently: $SELECTION)" - exit 1 - fi - - payload=$(jq -cn --arg name "$tag" '{name:$name}') - if curl -sf -X PUT "$CLASH_API/proxies/proxy" \ - -H "Content-Type: application/json" \ - -d "$payload" >/dev/null; then - echo "Switched to: $tag" - else - echo "Failed – is proxy-suite-socks running with selector mode?" - exit 1 - fi -} - -cmd_apps() { - _ensure_app_routing - if [ "$(jq 'length' "$PER_APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then - echo "No perAppRouting profiles configured." - return - fi - - printf " %-24s %s\n" "PROFILE" "ROUTE" - jq -r '.[] | " " + (.name | tostring) + "\t" + (.route | tostring)' \ - "$PER_APP_ROUTING_PROFILES_FILE" \ - | while IFS=$'\t' read -r profile route; do - printf "%-26s %s\n" "$profile" "$route" - done -} - -cmd_wrap() { - local route - local profile="${1:?Usage: proxy-ctl wrap -- [args...]}" +cmd_apps_run() { + local profile="${1:-}" route shift || true - if [ "${1:-}" = "--" ]; then - shift - fi - if [ "$#" -eq 0 ]; then - echo "Usage: proxy-ctl wrap -- [args...]" - exit 1 - fi + [ "${1:-}" != "--" ] || shift + { [ -n "$profile" ] && [ "$#" -gt 0 ]; } || _usage "apps run -- [args]" - _ensure_app_routing - route="$(_profile_route "$profile")" - if [ -z "$route" ] || [ "$route" = "null" ]; then - echo "Unknown perAppRouting profile: $profile" - exit 1 - fi + route="$(jq -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$PER_APP_ROUTING_PROFILES_FILE")" + [ -n "$route" ] || _die "Unknown perAppRouting profile: $profile" case "$route" in - direct) - exec "$@" - ;; + direct) exec "$@" ;; proxychains) - if [ "$PER_APP_ROUTING_PROXYCHAINS_ENABLED" != "1" ]; then - echo "Profile '$profile' uses route=proxychains, but perAppRouting.proxychains.enable is false." - exit 1 - fi - if [ ! -r "$PROXYCHAINS_CONFIG" ]; then - echo "Proxychains config is not readable: $PROXYCHAINS_CONFIG" - echo "Make sure proxy-suite-socks.service is running." - exit 1 - fi + [ "$PER_APP_ROUTING_PROXYCHAINS_ENABLED" = "1" ] || + _die "Profile '$profile' uses route=proxychains, but perAppRouting.proxychains.enable is false." + [ -r "$PROXYCHAINS_CONFIG" ] || + _die "Proxychains config is not readable: $PROXYCHAINS_CONFIG (is proxy-suite-socks running?)" exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@" ;; tun) _check_no_global_proxy tun _wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED" \ - "Profile '$profile' uses route=tun, but proxy.tun.perApp.enable is false." \ + "Profile '$profile' uses route=tun, but perAppRouting.tun.enable is false." \ "proxy-suite-per-app-tun.service" "$@" ;; tproxy) _check_no_global_proxy tproxy _wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED" \ - "Profile '$profile' uses route=tproxy, but proxy.tproxy.perApp.enable is false." \ + "Profile '$profile' uses route=tproxy, but perAppRouting.tproxy.enable is false." \ "proxy-suite-per-app-tproxy.service" "$@" ;; zapret) _check_no_global_proxy zapret _wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED" \ - "Profile '$profile' uses route=zapret, but zapret.perApp.enable is false." \ + "Profile '$profile' uses route=zapret, but perAppRouting.zapret.enable is false." \ "proxy-suite-per-app-zapret.service" "$@" ;; - *) - echo "Route backend '$route' is not implemented in this build." - exit 1 - ;; + *) _die "Route backend '$route' is not implemented." ;; esac } -cmd_subscription() { - local subcmd cache age count t - subcmd="${1:-list}" - shift || true +# --- inbounds ---------------------------------------------------------------- - case "$subcmd" in - list) - CACHE_DIR="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}" - if [ ${#SUB_TAGS[@]} -eq 0 ]; then - echo "No subscriptions configured." - return - fi - - printf " %-30s %-22s %s\n" "TAG" "LAST UPDATED" "PROXIES" - for t in "${SUB_TAGS[@]}"; do - cache="$CACHE_DIR/$t.json" - if [ -f "$cache" ]; then - age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown") - count=$(_subscription_proxy_count "$cache" 2>/dev/null || echo "?") - else - age="(no cache)" - count="-" - fi - printf " %-30s %-22s %s\n" "$t" "$age" "$count" - done - ;; - update) - _require_service proxy-suite-subscription-update "Subscription updates are unavailable because no subscriptions are configured." - systemctl start proxy-suite-subscription-update - echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update" - ;; - *) - echo "Usage: proxy-ctl subscription list|update" - exit 1 - ;; - esac -} - -_ensure_inbounds() { - if [ "${INBOUNDS_ENABLED:-0}" != "1" ]; then - echo "proxyInbounds is not enabled in services.proxy-suite.proxyInbounds." - exit 1 - fi -} - -# Links carry listener credentials, so the file is root/group-only. Say so -# rather than leaking a bare permission error. +# Links carry listener credentials, so the file is root/group-only. _inbound_links() { - if [ ! -f "$INBOUNDS_LINKS_FILE" ]; then - echo "No share links available. Is proxy-suite-inbounds running, and is proxyInbounds.shareLinks enabled?" >&2 - exit 1 - fi - if [ ! -r "$INBOUNDS_LINKS_FILE" ]; then - echo "Share links are not readable by this user. Enable userControl, or run as root." >&2 - exit 1 - fi + [ -f "$INBOUNDS_LINKS_FILE" ] || + _die "No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?" + [ -r "$INBOUNDS_LINKS_FILE" ] || _die "Share links are not readable by this user. Enable userControl, or run as root." cat "$INBOUNDS_LINKS_FILE" } @@ -635,10 +1417,7 @@ _inbound_link_for() { local tag="$1" user="${2:-}" matches count matches="$(_inbound_links | jq -c --arg tag "$tag" --arg user "$user" '[.[] | select(.tag == $tag) | select($user == "" or .user == $user)]')" count="$(jq 'length' <<< "$matches")" - if [ "$count" -eq 0 ]; then - echo "Unknown inbound, or no share link for it: $tag" >&2 - exit 1 - fi + [ "$count" -ne 0 ] || _die "Unknown inbound, or no share link for it: $tag" if [ "$count" -ne 1 ]; then echo "Multiple users match '$tag'; specify one of:" >&2 jq -r '.[].user' <<< "$matches" | sed 's/^/ /' >&2 @@ -647,35 +1426,94 @@ _inbound_link_for() { jq -r '.[0].link' <<< "$matches" } +# Per-user traffic over the last $1 days, newest first, then totals. +_inbound_stats() { + local days="$1" file="${INBOUNDS_STATS_FILE:-/var/lib/proxy-suite/inbound-stats.json}" since + [[ "$days" =~ ^[1-9][0-9]*$ ]] || _usage "inbounds stats [days]" + # Collect what XRay counted since the last run first; root and userControl + # members may, anyone else reads what the timer last wrote. + systemctl --no-ask-password start proxy-suite-inbound-stats.service 2>/dev/null || true + [ -e "$file" ] || _die "No traffic recorded yet - the collector runs every 5 minutes." + [ -r "$file" ] || _die "Cannot read $file - enable userControl, or run with sudo." + since="$(date -d "-$((days - 1)) days" +%F)" + echo "Traffic through the inbounds since $since, by user:" + jq -r --arg since "$since" ' + [(.days // {}) | to_entries[] | select(.key >= $since) | .key as $d + | .value | to_entries[] | [$d, .key, (.value.down // 0), (.value.up // 0)]] + | (group_by(.[0]) | reverse | .[] | sort_by(.[1])[] | "day\t" + (map(tostring) | join("\t"))), + (group_by(.[1])[] | "total\t\t\(.[0][1])\t\(map(.[2]) | add)\t\(map(.[3]) | add)")' "$file" | + awk -F'\t' ' + function h(b) { + if (b >= 1073741824) return sprintf("%.1f GiB", b / 1073741824) + if (b >= 1048576) return sprintf("%.1f MiB", b / 1048576) + if (b >= 1024) return sprintf("%.0f KiB", b / 1024) + return b " B" + } + $1 == "day" { + if (!d++) printf " %-12s %-20s %10s %10s\n", "DAY", "USER", "DOWN", "UP" + printf " %-12s %-20s %10s %10s\n", $2, $3, h($4), h($5) + } + $1 == "total" { + if (!t++) printf "\n %-33s %10s %10s\n", "TOTAL", "DOWN", "UP" + printf " %-33s %10s %10s\n", $3, h($4), h($5) + } + END { if (!d) print " (nothing recorded)" }' +} + +# Without a user: user names only, since each URL is its user's secret. +_inbound_subscriptions() { + local user="" qr=0 file="${INBOUNDS_SUBS_FILE:-/run/proxy-suite-inbounds/subscriptions.json}" + local base="${INBOUNDS_SUB_BASE_URL:-}" arg token + for arg; do + case "$arg" in + --qr) qr=1 ;; + *) user="$arg" ;; + esac + done + [ -f "$file" ] || + _die "No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?" + [ -r "$file" ] || _die "Subscriptions are not readable by this user. Enable userControl, or run as root." + if [ -z "$user" ]; then + [ "$qr" = 0 ] || _usage "inbounds sub --qr" + jq -r '.[] | " " + .user' "$file" + echo "Show one with: proxy-ctl inbounds sub [--qr]" >&2 + return + fi + token="$(jq -r --arg u "$user" 'first(.[] | select(.user == $u) | .token) // empty' "$file")" + [ -n "$token" ] || _die "No subscription for user: $user" + if [ -n "$base" ]; then + _emit "${base%/}/$token" "$qr" + else + [ "$qr" = 0 ] || _die "A QR code needs inbounds.subscriptions.baseUrl." + echo "${file%.json}/$token" + echo "Set inbounds.subscriptions.baseUrl to get a URL instead of a path." >&2 + fi +} + cmd_inbounds() { - _ensure_inbounds - case "${1:-list}" in + local verb="${1:-list}" qr=0 arg link state + local -a args=() + shift || true + [ "${INBOUNDS_ENABLED:-0}" = 1 ] || _die "inbounds is not enabled in this configuration." + case "$verb" in list) - echo "proxy-suite inbounds:" - printf " %-24s %-16s %-14s %-8s %s\n" TAG USER TYPE PORT STATE - local state state="$(systemctl is-active proxy-suite-inbounds 2>/dev/null || true)" + printf " %-24s %-16s %-14s %-8s %s\n" TAG USER TYPE PORT STATE _inbound_links \ | jq -r --arg state "$state" '.[] | "\(.tag)\t\(.user)\t\(.type)\t\(.port)\t\($state)"' \ | awk -F'\t' '{printf " %-24s %-16s %-14s %-8s %s\n", $1, $2, $3, $4, $5}' ;; - link) - if [ -z "${2:-}" ]; then - echo "Usage: proxy-ctl inbounds link [user]" >&2 - exit 1 - fi - _inbound_link_for "$2" "${3:-}" - ;; - qr) - if [ -z "${2:-}" ]; then - echo "Usage: proxy-ctl inbounds qr [user]" >&2 - exit 1 - fi - _inbound_link_for "$2" "${3:-}" | qrencode -t ANSIUTF8 - ;; - *) - echo "Usage: proxy-ctl inbounds [list|link [user]|qr [user]]" >&2 - exit 1 + link | qr) + [ "$verb" = link ] || qr=1 + for arg; do + if [ "$arg" = --qr ]; then qr=1; else args+=("$arg"); fi + done + [ "${#args[@]}" -gt 0 ] || _usage "inbounds link [user] [--qr]" + link="$(_inbound_link_for "${args[@]}")" + _emit "$link" "$qr" ;; + stats) _inbound_stats "${1:-7}" ;; + sub) _inbound_subscriptions "$@" ;; + *) _usage "inbounds [list] | link [user] [--qr] | sub [user] [--qr] | stats [days]" ;; esac } diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index ffe7c76..f15f5ed 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -21,6 +21,19 @@ amneziaWgProfileNamesFile, inboundsEnabled, inboundsLinksFile, + inboundsStatsFile, + inboundsSubscriptionsFile, + inboundsSubscriptionsBaseUrl, + zapretAutoEnabled, + zapretStateDir, + priorityOutboundFile, + outboundInventoryFile, + runtimeOutboundsDir, + runtimeSubscriptionsDir, + userControlGroup, + localProxyUrl, + autoProxyEnabled, + autoProxyStateDir, }: let @@ -45,6 +58,19 @@ let AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; INBOUNDS_ENABLED = inboundsEnabled; INBOUNDS_LINKS_FILE = inboundsLinksFile; + INBOUNDS_STATS_FILE = inboundsStatsFile; + INBOUNDS_SUBS_FILE = inboundsSubscriptionsFile; + INBOUNDS_SUB_BASE_URL = inboundsSubscriptionsBaseUrl; + ZAPRET_AUTO_ENABLED = zapretAutoEnabled; + ZAPRET_STATE_DIR = zapretStateDir; + PRIORITY_OUTBOUND_FILE = priorityOutboundFile; + OUTBOUND_INVENTORY_FILE = outboundInventoryFile; + RUNTIME_OUTBOUNDS_DIR = runtimeOutboundsDir; + RUNTIME_SUBS_DIR = runtimeSubscriptionsDir; + USER_CONTROL_GROUP = userControlGroup; + LOCAL_PROXY_URL = localProxyUrl; + AUTOPROXY_ENABLED = autoProxyEnabled; + AUTOPROXY_STATE_DIR = autoProxyStateDir; }; in pkgs.symlinkJoin { @@ -61,12 +87,23 @@ pkgs.symlinkJoin { ; script = unwrapped.drvAttrs.text; }; + # Probes present a browser's TLS fingerprint: bot protection refuses plain + # curl. The newest Chrome profile the package ships, since the set varies by + # version; the build fails if there is none. postBuild = '' + install -Dm644 ${./proxy-ctl-completion.bash} \ + "$out/share/bash-completion/completions/proxy-ctl" + probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1) + [ -x "$probe_curl" ] wrapProgram "$out/bin/proxy-ctl" \ + --set PROBE_CURL "$probe_curl" \ --prefix PATH : "${ lib.makeBinPath [ + # curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`. + pkgs.bash pkgs.coreutils pkgs.curl + pkgs.fzf pkgs.gawk pkgs.gnugrep pkgs.jq @@ -74,23 +111,10 @@ pkgs.symlinkJoin { pkgs.qrencode pkgs.systemd ] - }" \ - --set CLASH_API ${lib.escapeShellArg clashApi} \ - --set SELECTION ${lib.escapeShellArg selection} \ - --set SUB_TAGS_FILE ${lib.escapeShellArg (toString subscriptionTagsFile)} \ - --set SUB_CACHE_DIR ${lib.escapeShellArg subscriptionCacheDir} \ - --set PER_APP_ROUTING_ENABLED ${lib.escapeShellArg perAppRoutingEnabled} \ - --set PER_APP_ROUTING_PROXYCHAINS_ENABLED ${lib.escapeShellArg perAppRoutingProxychainsEnabled} \ - --set PER_APP_ROUTING_TUN_ENABLED ${lib.escapeShellArg perAppRoutingTunEnabled} \ - --set PER_APP_ROUTING_TPROXY_ENABLED ${lib.escapeShellArg perAppRoutingTproxyEnabled} \ - --set PER_APP_ROUTING_ZAPRET_ENABLED ${lib.escapeShellArg perAppRoutingZapretEnabled} \ - --set PER_APP_ROUTING_PROFILES_FILE ${lib.escapeShellArg (toString perAppRoutingProfilesFile)} \ - --set PROXYCHAINS_CONFIG ${lib.escapeShellArg (toString proxychainsConfigFile)} \ - --set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)} \ - --set ROUTE_MODE_STATE_FILE ${lib.escapeShellArg routeModeStateFile} \ - --set DEFAULT_ROUTE_MODE ${lib.escapeShellArg defaultRouteMode} \ - --set AWG_PROFILES_FILE ${lib.escapeShellArg (toString amneziaWgProfileNamesFile)} \ - --set INBOUNDS_ENABLED ${lib.escapeShellArg inboundsEnabled} \ - --set INBOUNDS_LINKS_FILE ${lib.escapeShellArg inboundsLinksFile} + }" ${ + lib.concatStringsSep " " ( + lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv + ) + } ''; } diff --git a/pkgs/proxy-ctl.sh b/pkgs/proxy-ctl.sh index aa4cfd7..28faed4 100644 --- a/pkgs/proxy-ctl.sh +++ b/pkgs/proxy-ctl.sh @@ -1,95 +1,45 @@ set -euo pipefail -# Wrapped binary provides runtime config through env vars. -SUB_TAGS_FILE="${SUB_TAGS_FILE:-}" -AWG_PROFILES_FILE="${AWG_PROFILES_FILE:-}" PROXYCHAINS_QUIET_ARG="${PROXYCHAINS_QUIET_ARG:-}" SUB_TAGS=() AWG_PROFILES=() - -if [ -n "$SUB_TAGS_FILE" ] && [ -f "$SUB_TAGS_FILE" ]; then +if [ -f "${SUB_TAGS_FILE:-}" ]; then mapfile -t SUB_TAGS < <(jq -r '.[]' "$SUB_TAGS_FILE") fi - -if [ -n "$AWG_PROFILES_FILE" ] && [ -f "$AWG_PROFILES_FILE" ]; then +if [ -f "${AWG_PROFILES_FILE:-}" ]; then mapfile -t AWG_PROFILES < <(jq -r '.[]' "$AWG_PROFILES_FILE") fi +# Old spellings: still accepted, not in the help. +case "${1:-}" in + tun | tproxy | outbounds | select) set -- proxy "$@" ;; + route-mode) shift; set -- proxy mode "$@" ;; + subscription) shift; set -- proxy subs "$@" ;; + wrap) shift; set -- apps run "$@" ;; +esac + cmd="${1:-status}" shift || true case "$cmd" in - help) - _usage 0 - ;; - - status) - cmd_status "$@" - ;; - - proxy) - cmd_proxy "$@" - ;; - - tproxy) - cmd_mode_toggle proxy-suite-tproxy on "${1:-}" - ;; - - tun) - cmd_mode_toggle proxy-suite-tun on "${1:-}" - ;; - - ssh) - cmd_mode_toggle proxy-suite-ssh-proxy on "${1:-}" ssh - ;; - - awg) - cmd_awg "$@" - ;; - - route-mode) - cmd_route_mode "$@" - ;; - - zapret) - cmd_zapret "$@" - ;; - - restart) - cmd_restart - ;; - + help | -h | --help) _help ;; + status) cmd_status "$@" ;; + restart) cmd_restart ;; logs) - svc="${1:-proxy-suite-socks}" - shift || true - exec journalctl -fu "$svc" "$@" + if [ "$#" -gt 0 ]; then exec journalctl -fu "$@"; fi + # journalctl takes unit globs, so the default needs no unit list of its own. + exec journalctl -f -u 'proxy-suite-*' -u zapret-discord-youtube ;; - - outbounds) - cmd_outbounds - ;; - - select) - cmd_select "$@" - ;; - - apps) - cmd_apps - ;; - - wrap) - cmd_wrap "$@" - ;; - - inbounds) - cmd_inbounds "$@" - ;; - - subscription) - cmd_subscription "$@" - ;; - + proxy) cmd_proxy "$@" ;; + zapret) cmd_zapret "$@" ;; + awg) cmd_awg "$@" ;; + ssh) _toggle proxy-suite-ssh-proxy ssh "$@" ;; + apps) cmd_apps "$@" ;; + inbounds) cmd_inbounds "$@" ;; + where) cmd_where "$@" ;; + __complete) cmd_complete "$@" ;; *) - _usage 1 + _help >&2 + exit 1 ;; esac diff --git a/pkgs/proxy-suite-tray/main.c b/pkgs/proxy-suite-tray/main.c index 66c556b..353b243 100644 --- a/pkgs/proxy-suite-tray/main.c +++ b/pkgs/proxy-suite-tray/main.c @@ -753,11 +753,11 @@ static void on_tproxy_toggle(GtkWidget *item, gpointer data) ServiceState state = get_service_state(); if (state.tproxy) { - run_proxy_ctl("tproxy", "off"); + run_proxy_ctl3("proxy", "tproxy", "off"); } else { - run_proxy_ctl("tproxy", "on"); + run_proxy_ctl3("proxy", "tproxy", "on"); } update_status(); } @@ -774,7 +774,7 @@ static void on_route_mode_menu_toggled(GtkCheckMenuItem *item, gpointer data) { return; } - run_proxy_ctl("route-mode", mode); + run_proxy_ctl3("proxy", "mode", mode); update_status(); } @@ -798,7 +798,7 @@ static void on_route_mode_combo_changed(GtkComboBox *combo, gpointer data) { return; } - run_proxy_ctl("route-mode", mode); + run_proxy_ctl3("proxy", "mode", mode); update_status(); } @@ -809,11 +809,11 @@ static void on_tun_toggle(GtkWidget *item, gpointer data) ServiceState state = get_service_state(); if (state.tun) { - run_proxy_ctl("tun", "off"); + run_proxy_ctl3("proxy", "tun", "off"); } else { - run_proxy_ctl("tun", "on"); + run_proxy_ctl3("proxy", "tun", "on"); } update_status(); } @@ -884,7 +884,7 @@ static void on_subscription_update(GtkWidget *item, gpointer data) { (void)item; (void)data; - run_proxy_ctl("subscription", "update"); + run_proxy_ctl3("proxy", "subs", "update"); } static void on_open_controls(GtkWidget *item, gpointer data) diff --git a/pkgs/tg-ws-proxy.nix b/pkgs/tg-ws-proxy.nix index 919ad33..ef7b9a6 100644 --- a/pkgs/tg-ws-proxy.nix +++ b/pkgs/tg-ws-proxy.nix @@ -4,8 +4,8 @@ let src = pkgs.fetchFromGitHub { owner = "Flowseal"; repo = "tg-ws-proxy"; - rev = "v1.10.1"; - hash = "sha256-/X0dGXnyxVSQOgpETzvw+jBEjSSgj5tMHzwPxVenKII="; + rev = "v1.10.2"; + hash = "sha256-XpO0Hmi0Hotu5TdOZ6+Cg/YBaF31RHJ5MfPJ1JKpPr8="; }; pythonEnv = pkgs.python3.withPackages ( diff --git a/pkgs/xray.nix b/pkgs/xray.nix new file mode 100644 index 0000000..139049e --- /dev/null +++ b/pkgs/xray.nix @@ -0,0 +1,27 @@ +# Xray-core ahead of nixpkgs, which still ships 26.3.27. From 26.9.8 its go.mod +# asks for Go 1.27, so the builder is swapped along with the source. Steps +# aside once nixpkgs has caught up. +{ pkgs }: + +let + inherit (pkgs) lib; + version = "26.9.9"; +in +if lib.versionAtLeast pkgs.xray.version version then + pkgs.xray +else + (pkgs.xray.override ( + args: lib.optionalAttrs (args ? buildGo126Module) { buildGo126Module = pkgs.buildGo127Module; } + )).overrideAttrs + ( + finalAttrs: _: { + inherit version; + src = pkgs.fetchFromGitHub { + owner = "XTLS"; + repo = "Xray-core"; + rev = "v${finalAttrs.version}"; + hash = "sha256-GqPEAgWM9Wx19uxMj0LGeOyHreLbU0IMSmalwLe/SIc="; + }; + vendorHash = "sha256-6Qa05hFdvfLlH8WQd426IU7MScmeevIgrgP5037pNek="; + } + ) diff --git a/pkgs/zapret2.nix b/pkgs/zapret2.nix new file mode 100644 index 0000000..f3b2f77 --- /dev/null +++ b/pkgs/zapret2.nix @@ -0,0 +1,68 @@ +# zapret2 / nfqws2 - the Lua-strategy successor to zapret's nfqws. +# +# Unlike the zapret v1 packaging, nothing here is patched for NixOS beyond making +# PIDDIR overridable: the init scripts already take ZAPRET_BASE, ZAPRET_RW, +# ZAPRET_CONFIG and HOSTLIST_BASE from the environment, and the unit supplies PATH. +{ pkgs }: + +let + version = "1.0.5.1"; +in +pkgs.stdenv.mkDerivation { + pname = "zapret2"; + inherit version; + + src = pkgs.fetchFromGitHub { + owner = "bol-van"; + repo = "zapret2"; + tag = "v${version}"; + hash = "sha256-cb83DXeHExdLPjB283i1sU+GtqrwVtUXBbTloXsnvlA="; + }; + + nativeBuildInputs = [ pkgs.pkg-config ]; + + buildInputs = [ + pkgs.libcap + pkgs.libmnl + pkgs.libnetfilter_queue + pkgs.libnfnetlink + pkgs.luajit + pkgs.systemdLibs + pkgs.zlib + ]; + + # "systemd" is the plain linux target plus -DUSE_SYSTEMD; ip2net and mdig are + # only used by the ipset list-download scripts, which this suite does not run. + buildPhase = '' + runHook preBuild + make -C nfq2 systemd + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + + mkdir -p "$out/opt/zapret2" "$out/bin" + cp -r common init.d ipset lua files config.default "$out/opt/zapret2/" + install -Dm755 nfq2/nfqws2 "$out/opt/zapret2/nfq2/nfqws2" + ln -s "$out/opt/zapret2/nfq2/nfqws2" "$out/bin/nfqws2" + + chmod +x "$out/opt/zapret2/init.d/sysv/zapret2" + find "$out/opt/zapret2" -name '*.sh' -exec chmod +x {} + + + # Everything else the init scripts need is already env-overridable; PIDDIR is + # not, and two instances (global + per-app) must not share a pidfile. + substituteInPlace "$out/opt/zapret2/init.d/sysv/functions" \ + --replace-fail 'PIDDIR=/var/run' 'PIDDIR=''${PIDDIR:-/var/run}' + + runHook postInstall + ''; + + meta = with pkgs.lib; { + description = "DPI bypass utility with Lua-scripted desync strategies (nfqws2)"; + homepage = "https://github.com/bol-van/zapret2"; + license = licenses.mit; + platforms = platforms.linux; + mainProgram = "nfqws2"; + }; +} diff --git a/scripts/build-inbound.py b/scripts/build-inbound.py index d953a1b..d44d3b3 100644 --- a/scripts/build-inbound.py +++ b/scripts/build-inbound.py @@ -10,7 +10,7 @@ from proxy_inbound import build_inbounds def main() -> None: ap = argparse.ArgumentParser( - description="Render services.proxy-suite.proxyInbounds into XRay inbounds." + description="Render services.proxy-suite.inbounds into XRay inbounds." ) ap.add_argument("--spec", required=True, help="path to the generated inbound spec JSON") ap.add_argument( diff --git a/scripts/proxy_inbound.py b/scripts/proxy_inbound.py index beeb0b8..98e6120 100644 --- a/scripts/proxy_inbound.py +++ b/scripts/proxy_inbound.py @@ -2,13 +2,14 @@ """Render server-side proxy inbounds and their client share links. The input spec is backend-neutral: it mirrors the -services.proxy-suite.proxyInbounds option tree, with secrets given as file +services.proxy-suite.inbounds option tree, with secrets given as file paths that are read here rather than at Nix evaluation time. Only XRay is rendered today; a render_sing_box_inbound would sit beside render_xray_inbound without changing the spec or the link generator. """ import base64 +import hashlib import json import urllib.parse @@ -122,6 +123,9 @@ def _xray_stream(listener: dict, tag: str) -> dict: stream["tlsSettings"] = {"certificates": [certificate]} if tls.get("serverName"): stream["tlsSettings"]["serverName"] = tls["serverName"] + # ["h3"] alone is what makes an xhttp listener serve HTTP/3, on UDP. + if tls.get("alpn"): + stream["tlsSettings"]["alpn"] = tls["alpn"] else: stream["security"] = "none" @@ -209,11 +213,16 @@ def _link_security_params(listener: dict, server_address: str) -> dict: params["sid"] = short_ids[0] return params if tls["enable"] or listener["type"] == "trojan": - return { + params = { "security": "tls", "sni": tls.get("serverName") or server_address, "fp": "chrome", } + # A client left to its own ALPN offers h2 and http/1.1, and so never + # reaches an HTTP/3-only listener at all. + if tls.get("alpn"): + params["alpn"] = ",".join(tls["alpn"]) + return params return {"security": "none"} @@ -304,22 +313,52 @@ def build_listener(listener: dict, server_address: str, share_links: bool) -> di return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links} +def subscription_token(name: str, secrets: list[str]) -> str: + """Name of a user's subscription file, and so the secret part of its URL. + + Derived from the user's own credentials rather than stored: there is no + second secret to manage, it stays put for as long as they do, and rotating + the user's uuid rotates the URL with it. + """ + material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets))]) + return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32] + + def build_inbounds(spec: dict, server_address: str) -> dict: - """Render a whole spec into {"inbounds": [...], "links": [...]}.""" + """Render a whole spec into {"inbounds": [...], "links": [...], + "subscriptions": [...]}. + + A subscription gathers one user's links from every listener -- users are + matched by name -- as base64 of the newline-joined links, which is what + v2rayNG, Hiddify and NekoBox import. + """ inbounds = [] links = [] + by_user: dict[str, dict] = {} for listener in spec["listeners"]: rendered = build_listener(listener, server_address, spec.get("shareLinks", True)) inbounds.append(rendered["inbound"]) for index, link in enumerate(rendered["links"]): user = listener["users"][index] + name = user.get("name") or f"{rendered['tag']}-{index}" links.append( { "tag": rendered["tag"], - "user": user.get("name") or f"{rendered['tag']}-{index}", + "user": name, "type": rendered.get("type", ""), "port": rendered.get("port", 0), "link": link, } ) - return {"inbounds": inbounds, "links": links} + entry = by_user.setdefault(name, {"links": [], "secrets": []}) + entry["links"].append(link) + entry["secrets"].append(_user_secret(user, listener["type"], rendered["tag"])) + subscriptions = [ + { + "user": name, + "token": subscription_token(name, entry["secrets"]), + "body": base64.b64encode("\n".join(entry["links"]).encode("utf-8")).decode("ascii"), + } + for name, entry in by_user.items() + ] + return {"inbounds": inbounds, "links": links, "subscriptions": subscriptions} diff --git a/scripts/proxy_parsing.py b/scripts/proxy_parsing.py index 9d3ace0..b74f77e 100644 --- a/scripts/proxy_parsing.py +++ b/scripts/proxy_parsing.py @@ -212,6 +212,11 @@ def build_outbound( def fetch_raw(url: str) -> bytes: + # urlopen also speaks file:, ftp: and data:. This runs as root over a URL that + # reaches it from a group-writable spool, so only the two a subscription is + # ever served over. + if urllib.parse.urlsplit(url).scheme not in ("http", "https"): + raise ValueError("subscription URL must be http:// or https://") request = urllib.request.Request( url, headers={"User-Agent": "v2rayN/6.0"}, diff --git a/scripts/proxy_url_parsers.py b/scripts/proxy_url_parsers.py index 5c5c5ba..3d92ae5 100644 --- a/scripts/proxy_url_parsers.py +++ b/scripts/proxy_url_parsers.py @@ -117,6 +117,21 @@ def _mk_transport( return None +# sing-box refuses to start on a transport it does not know, so one bad share +# link would otherwise take the whole config down with it. +def _check_transport(transport: str, backend: str, protocol: str) -> str: + normalized = transport.lower() + supported = ( + SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS + ) + if normalized not in supported: + raise ValueError( + f"unsupported {protocol} transport '{transport}': proxy-suite only maps " + f"{backend}-documented transports; use raw JSON or another client/core" + ) + return normalized + + def _require(params: dict, name: str, security: str) -> str: if name not in params: raise ValueError(f"{security} link is missing the '{name}' parameter") @@ -168,8 +183,6 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]": def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict: userinfo, host, port, params = _parse_url_parts(url, "vless") security = params.get("security", "none") - transport = params.get("type", "tcp") - normalized_transport = transport.lower() if "ech" in params and backend != "xray": raise ValueError( @@ -177,14 +190,9 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict: "share-link ECH blobs into sing-box TLS config" ) - supported_transports = ( - SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS + normalized_transport = _check_transport( + params.get("type", "tcp"), backend, "VLESS" ) - if normalized_transport not in supported_transports: - raise ValueError( - f"unsupported VLESS transport '{transport}': proxy-suite only maps " - f"{backend}-documented transports; use raw JSON or another client/core" - ) ob: dict = { "type": "vless", @@ -237,7 +245,7 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict: return ob -def parse_vmess(url: str, tag: str) -> dict: +def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict: b64 = url[len("vmess://") :] b64, _, _ = b64.partition("#") b64, _, _ = b64.partition("?") @@ -250,7 +258,7 @@ def parse_vmess(url: str, tag: str) -> dict: host = str(data["add"]) port = int(data["port"]) - net = data.get("net", "tcp") + net = _check_transport(str(data.get("net", "tcp")), backend, "VMess") tls_field = str(data.get("tls", "")) sni = str(data.get("sni") or data.get("host") or host) @@ -269,6 +277,7 @@ def parse_vmess(url: str, tag: str) -> dict: sni, fp=str(data["fp"]) if data.get("fp") else None, alpn=str(data["alpn"]) if data.get("alpn") else None, + backend=backend, ) path = str(data.get("path") or "/") @@ -286,9 +295,9 @@ def parse_vmess(url: str, tag: str) -> dict: return ob -def parse_trojan(url: str, tag: str) -> dict: +def parse_trojan(url: str, tag: str, backend: str = "sing-box") -> dict: userinfo, host, port, params = _parse_url_parts(url, "trojan") - transport = params.get("type", "tcp") + transport = _check_transport(params.get("type", "tcp"), backend, "Trojan") ob: dict = { "type": "trojan", @@ -297,7 +306,10 @@ def parse_trojan(url: str, tag: str) -> dict: "server_port": int(port), "password": urllib.parse.unquote(userinfo), "tls": _mk_tls( - params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn") + params.get("sni", host), + fp=params.get("fp"), + alpn=params.get("alpn"), + backend=backend, ), } @@ -459,4 +471,6 @@ PARSERS = { BACKEND_AWARE_PARSERS = { "vless", + "vmess", + "trojan", } diff --git a/scripts/test-build-inbound.py b/scripts/test-build-inbound.py index 9b9f208..e789d75 100644 --- a/scripts/test-build-inbound.py +++ b/scripts/test-build-inbound.py @@ -7,7 +7,7 @@ import tempfile import unittest import urllib.parse -from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound +from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound, subscription_token from proxy_parsing import build_outbound @@ -368,6 +368,56 @@ class BuildInboundsTests(unittest.TestCase): # what breaks XHTTP behind an HTTP/1.1 reverse proxy. self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["mode"], "packet-up") + def test_alpn_reaches_the_inbound_and_the_link(self): + spec = listener( + transport={"type": "xhttp", "path": "/h3", "host": None, "mode": None, "serviceName": ""}, + tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None, "alpn": ["h3"]}, + ) + # h3 alone is what makes XRay serve the listener as HTTP/3, on UDP. + self.assertEqual(render_xray_inbound(spec)["streamSettings"]["tlsSettings"]["alpn"], ["h3"]) + # A client left to its own ALPN offers h2 and http/1.1 and never gets in. + self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["alpn"], "h3") + plain = listener(tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}) + self.assertNotIn("alpn", render_xray_inbound(plain)["streamSettings"]["tlsSettings"]) + self.assertNotIn("alpn", link_params(build_share_link(plain, "vpn.example.com"))) + + def test_subscriptions_gather_each_users_links(self): + def users(uuid_a): + return [ + {"name": "fufsob", "uuid": uuid_a, "password": None, "passwordFile": None}, + {"name": "teri", "uuid": "uuid-teri", "password": None, "passwordFile": None}, + ] + + def spec(uuid_a="uuid-fufsob", share=True): + return { + "serverAddress": "vpn.example.com", + "shareLinks": share, + "listeners": [ + listener(tag="ws", users=users(uuid_a)), + listener(tag="h3", port=8443, users=users(uuid_a)), + ], + } + + result = build_inbounds(spec(), "vpn.example.com") + subs = {s["user"]: s for s in result["subscriptions"]} + self.assertEqual(sorted(subs), ["fufsob", "teri"]) + # Every listener's link for that user, as clients import them. + body = base64.b64decode(subs["fufsob"]["body"]).decode() + self.assertEqual( + body.split("\n"), + [entry["link"] for entry in result["links"] if entry["user"] == "fufsob"], + ) + self.assertEqual(len(body.split("\n")), 2) + # Stable while the credentials are, rotated with them, never shared. + token = subs["fufsob"]["token"] + self.assertRegex(token, "^[0-9a-f]{32}$") + self.assertEqual(token, subscription_token("fufsob", ["uuid-fufsob"])) + self.assertNotEqual(token, subs["teri"]["token"]) + rotated = build_inbounds(spec(uuid_a="uuid-new"), "vpn.example.com")["subscriptions"] + self.assertNotEqual(token, next(s["token"] for s in rotated if s["user"] == "fufsob")) + # No links, nothing to subscribe to. + self.assertEqual(build_inbounds(spec(share=False), "vpn.example.com")["subscriptions"], []) + def test_share_port_overrides_the_bound_port(self): spec = { "serverAddress": "vpn.example.com", diff --git a/scripts/test-build-outbound.py b/scripts/test-build-outbound.py index 1dca71d..a5ecdcc 100644 --- a/scripts/test-build-outbound.py +++ b/scripts/test-build-outbound.py @@ -16,6 +16,11 @@ def run_xray_parser(url: str): return build_outbound(url, "test-outbound", backend="xray") +def vmess_url(extra: dict) -> str: + body = {"add": "example.com", "port": 443, "id": "uuid", "net": "tcp", **extra} + return "vmess://" + base64.b64encode(json.dumps(body).encode()).decode() + + class BuildOutboundTests(unittest.TestCase): def test_vless_reality(self): ob = run_parser( @@ -290,6 +295,34 @@ class BuildOutboundTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, "unsupported scheme"): run_parser("wireguard://example.com") + def test_trojan_xhttp_fails_loudly_on_sing_box(self): + url = "trojan://pw@example.com:443?security=tls&type=xhttp&path=/p" + with self.assertRaisesRegex(ValueError, "unsupported Trojan transport 'xhttp'"): + run_parser(url) + self.assertEqual( + run_xray_parser(url)["streamSettings"]["network"], "xhttp" + ) + + def test_vmess_kcp_fails_loudly(self): + with self.assertRaisesRegex(ValueError, "unsupported VMess transport 'kcp'"): + run_parser(vmess_url({"net": "kcp"})) + + def test_xray_only_fingerprint_rejected_for_sing_box_trojan_and_vmess(self): + trojan = "trojan://pw@example.com:443?security=tls&fp=unsafe" + with self.assertRaises(ValueError): + run_parser(trojan) + self.assertEqual( + run_xray_parser(trojan)["streamSettings"]["tlsSettings"]["fingerprint"], + "unsafe", + ) + vmess = vmess_url({"tls": "tls", "fp": "unsafe"}) + with self.assertRaises(ValueError): + run_parser(vmess) + self.assertEqual( + run_xray_parser(vmess)["streamSettings"]["tlsSettings"]["fingerprint"], + "unsafe", + ) + def test_backend_aware_parser_type_error_is_not_arity_fallback(self): def broken_parser(url: str, tag: str, backend: str): raise TypeError("real parser bug") diff --git a/scripts/test-fetch-subscription.py b/scripts/test-fetch-subscription.py index 66d6418..8c1cb87 100644 --- a/scripts/test-fetch-subscription.py +++ b/scripts/test-fetch-subscription.py @@ -2,7 +2,12 @@ import base64 import unittest -from proxy_parsing import decode_subscription, parse_hybrid_subscription, parse_subscription +from proxy_parsing import ( + decode_subscription, + fetch_raw, + parse_hybrid_subscription, + parse_subscription, +) VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd" VLESS_XHTTP_URI = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx" @@ -33,6 +38,11 @@ def run_fetcher( class FetchSubscriptionTests(unittest.TestCase): + def test_fetch_rejects_non_http_schemes(self): + for url in ("file:///etc/shadow", "ftp://example.com/sub", "data:text/plain,x"): + with self.assertRaisesRegex(ValueError, "http"): + fetch_raw(url) + def test_base64_payload_mixed_protocols(self): payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI) diff --git a/scripts/update-pins.sh b/scripts/update-pins.sh new file mode 100755 index 0000000..f5f1999 --- /dev/null +++ b/scripts/update-pins.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +# Refresh every hand-pinned GitHub source under pkgs/ to its latest release tag, +# including the Go vendorHash where the package has one. +# +# Table columns: nix-file|owner|repo|version-key|flake-attr +# version-key the ` = "...";` line holding the tag. A leading "=" means +# "do not query GitHub, reuse the value of that key" - for sources +# that must stay in lockstep (AWG kernel module follows tools). +# flake-attr package built to recompute vendorHash; "-" when there is none. +# +# Prints one "updated : -> " line per change on stdout; progress +# and errors go to stderr. `--attrs` lists the flake attrs instead. +set -euo pipefail + +PINS=( + "pkgs/tg-ws-proxy.nix|Flowseal|tg-ws-proxy|rev|tg-ws-proxy" + "pkgs/zapret2.nix|bol-van|zapret2|version|zapret2" + "pkgs/xray.nix|XTLS|Xray-core|version|xray" + "pkgs/amneziawg.nix|amnezia-vpn|amneziawg-tools|version|amneziawg-tools" + "pkgs/amneziawg.nix|amnezia-vpn|amneziawg-go|userspaceVersion|amneziawg-go" + "pkgs/amneziawg.nix|amnezia-vpn|amneziawg-linux-kernel-module|=version|-" +) + +FAKE_HASH="sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" + +if [[ "${1:-}" == "--attrs" ]]; then + for pin in "${PINS[@]}"; do + IFS='|' read -r _ _ _ _ attr <<<"$pin" + [[ "$attr" == "-" ]] || printf '.#%s\n' "$attr" + done | sort -u + exit 0 +fi + +cd "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" + +for cmd in curl jq nix awk; do + command -v "$cmd" >/dev/null || { echo "$cmd is required" >&2; exit 1; } +done + +gh_api() { + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + curl -fsSL -H "Authorization: Bearer ${GITHUB_TOKEN}" "$1" + else + curl -fsSL "$1" + fi +} + +# The tags list, not releases/latest: some of these repos cut prereleases or no +# releases at all, and releases/latest skips both (it reported v26.3.27 while +# Xray-core was already on v26.9.9, and 404s for amneziawg-go). +latest_tag() { + local owner=$1 repo=$2 tag + tag=$(gh_api "https://api.github.com/repos/${owner}/${repo}/tags?per_page=100" | + jq -r '.[].name' | grep -E '^v?[0-9]' | sort -V | tail -n1) + [[ -n "$tag" ]] || { echo "unable to resolve latest tag for ${owner}/${repo}" >&2; return 1; } + printf '%s\n' "$tag" +} + +newest() { printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1; } + +get_key() { + sed -n -E "s/^[[:space:]]*$2 = \"([^\"]+)\";.*/\1/p" "$1" | head -n1 +} + +# Replace ` = "...";` with val. When repo is non-empty the search is scoped +# to the fetchFromGitHub block of that repo, so sibling pins in the same file +# (amneziawg.nix holds three) never clobber each other. Returns 1 if not found. +set_attr() { + local file=$1 repo=$2 attr=$3 val=$4 tmp + tmp=$(mktemp) + if awk -v repo="$repo" -v attr="$attr" -v val="$val" ' + BEGIN { region = (repo == "") } + { + if (repo != "" && $0 ~ ("repo = \"" repo "\";")) { region = 1 } + else if (repo != "" && region && $0 ~ /repo = "/) { region = 0 } + else if (region && !done && $0 ~ ("^[ \t]*" attr " = \"")) { + sub(/"[^"]*"/, "\"" val "\""); done = 1 + } + print + } + END { exit(done ? 0 : 1) } + ' "$file" >"$tmp"; then + mv "$tmp" "$file" + else + rm -f "$tmp" + return 1 + fi +} + +# Go packages pin a vendorHash that a source bump invalidates: poison it and let +# the failing build report the real one. +refresh_vendor_hash() { + local file=$1 repo=$2 attr=$3 log got + [[ "$attr" != "-" ]] || return 0 + set_attr "$file" "$repo" vendorHash "$FAKE_HASH" || return 0 + echo "recomputing vendorHash for ${attr}" >&2 + if log=$(nix build --no-link ".#${attr}" 2>&1); then + echo "build of ${attr} succeeded with a placeholder vendorHash" >&2 + return 1 + fi + got=$(grep -oE 'sha256-[A-Za-z0-9+/]{43}=' <<<"$log" | grep -vxF "$FAKE_HASH" | tail -n1) + if [[ -z "$got" ]]; then + echo "could not extract vendorHash for ${attr}:" >&2 + tail -n 30 <<<"$log" >&2 + return 1 + fi + set_attr "$file" "$repo" vendorHash "$got" + echo "updated ${repo} vendorHash: ${got}" +} + + +# `--self-test`: the one thing that must not break is set_attr's block scoping - +# amneziawg.nix holds three fetchFromGitHub blocks and a vendorHash that belongs +# to exactly one of them. +self_test() { + local d f + d=$(mktemp -d) + trap 'rm -rf "$d"' RETURN + f="$d/fixture.nix" + cat >"$f" <<'FIXTURE' + version = "1.0"; + other = pkgs.a.overrideAttrs (_: { + src = pkgs.fetchFromGitHub { + repo = "alpha"; + hash = "sha256-ALPHA"; + }; + }); + more = pkgs.b.overrideAttrs (_: { + src = pkgs.fetchFromGitHub { + repo = "beta"; + hash = "sha256-BETA"; + }; + vendorHash = "sha256-VENDOR"; + }); +FIXTURE + set_attr "$f" "" version 2.0 + set_attr "$f" alpha hash sha256-NEW + set_attr "$f" alpha vendorHash sha256-WRONG && { echo "self-test: vendorHash leaked out of the alpha block" >&2; return 1; } + set_attr "$f" beta vendorHash sha256-OK + [[ "$(get_key "$f" version)" == "2.0" ]] || { echo "self-test: version not written" >&2; return 1; } + grep -q 'hash = "sha256-NEW";' "$f" || { echo "self-test: alpha hash not written" >&2; return 1; } + grep -q 'hash = "sha256-BETA";' "$f" || { echo "self-test: beta hash was clobbered" >&2; return 1; } + grep -q 'vendorHash = "sha256-OK";' "$f" || { echo "self-test: beta vendorHash not written" >&2; return 1; } + echo "self-test ok" +} + +if [[ "${1:-}" == "--self-test" ]]; then + self_test + exit 0 +fi + +declare -A BUMPED=() + +for pin in "${PINS[@]}"; do + IFS='|' read -r file owner repo key attr <<<"$pin" + [[ -f "$file" ]] || { echo "missing ${file}" >&2; exit 1; } + + if [[ "$key" == =* ]]; then + # Lockstep source: refetch only when the key it follows actually moved. + key=${key#=} + [[ -n "${BUMPED[$key]:-}" ]] || { echo "${repo}: follows ${key}, unchanged" >&2; continue; } + new=$(get_key "$file" "$key") + current=$new + else + current=$(get_key "$file" "$key") + [[ -n "$current" ]] || { echo "could not read ${key} from ${file}" >&2; exit 1; } + tag=$(latest_tag "$owner" "$repo") + # Keep whatever "v" convention the file already uses. + if [[ "$current" == v* ]]; then new=$tag; else new=${tag#v}; fi + if [[ "$current" == "$new" ]]; then + echo "${repo}: already at ${current}" >&2 + continue + fi + # These pins exist because they are ahead of nixpkgs; never walk one back. + if [[ "$(newest "$current" "$new")" != "$new" ]]; then + echo "${repo}: pinned ${current} is newer than upstream ${new}, keeping it" >&2 + continue + fi + fi + + tag_ref=$new + [[ "$tag_ref" == v* ]] || tag_ref="v${tag_ref}" + hash=$(nix store prefetch-file --json --unpack \ + "https://github.com/${owner}/${repo}/archive/refs/tags/${tag_ref}.tar.gz" | jq -r '.hash') + [[ -n "$hash" && "$hash" != "null" ]] || { echo "could not hash ${repo} ${tag_ref}" >&2; exit 1; } + + if [[ "$current" != "$new" ]]; then + set_attr "$file" "" "$key" "$new" || { echo "could not write ${key} in ${file}" >&2; exit 1; } + BUMPED[$key]=1 + echo "updated ${repo}: ${current} -> ${new}" + fi + set_attr "$file" "$repo" hash "$hash" || { echo "could not write hash for ${repo}" >&2; exit 1; } + refresh_vendor_hash "$file" "$repo" "$attr" +done diff --git a/scripts/update-tg-ws-proxy.sh b/scripts/update-tg-ws-proxy.sh deleted file mode 100755 index dda8a78..0000000 --- a/scripts/update-tg-ws-proxy.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" -cd "$repo_root" - -target_file="pkgs/tg-ws-proxy.nix" - -if [[ ! -f "$target_file" ]]; then - echo "Cannot find ${target_file}" >&2 - exit 1 -fi - -if ! command -v curl >/dev/null 2>&1; then - echo "curl command is required" >&2 - exit 1 -fi - -if ! command -v jq >/dev/null 2>&1; then - echo "jq command is required" >&2 - exit 1 -fi - -if ! command -v nix >/dev/null 2>&1; then - echo "nix command is required" >&2 - exit 1 -fi - -latest_tag="$( - curl -fsSL "https://api.github.com/repos/Flowseal/tg-ws-proxy/releases/latest" | - jq -r '.tag_name // empty' -)" - -if [[ -z "$latest_tag" ]]; then - latest_tag="$( - curl -fsSL "https://api.github.com/repos/Flowseal/tg-ws-proxy/tags?per_page=1" | - jq -r '.[0].name // empty' - )" -fi - -if [[ -z "$latest_tag" ]]; then - echo "Unable to resolve latest tg-ws-proxy tag" >&2 - exit 1 -fi - -archive_url="https://github.com/Flowseal/tg-ws-proxy/archive/refs/tags/${latest_tag}.tar.gz" -latest_hash="$( - nix store prefetch-file --json --unpack "$archive_url" | jq -r '.hash' -)" - -if [[ -z "$latest_hash" || "$latest_hash" == "null" ]]; then - echo "Unable to compute tg-ws-proxy source hash for ${latest_tag}" >&2 - exit 1 -fi - -current_rev="$(sed -n -E 's/^[[:space:]]*rev = "([^"]+)";/\1/p' "$target_file" | head -n1)" -current_hash="$(sed -n -E 's/^[[:space:]]*hash = "([^"]+)";/\1/p' "$target_file" | head -n1)" - -if [[ -z "$current_rev" || -z "$current_hash" ]]; then - echo "Could not parse current rev/hash from ${target_file}" >&2 - exit 1 -fi - -if [[ "$current_rev" == "$latest_tag" && "$current_hash" == "$latest_hash" ]]; then - echo "tg-ws-proxy is already up to date (${latest_tag})" - exit 0 -fi - -sed -i -E "s|(^[[:space:]]*rev = \").*(\";)|\1${latest_tag}\2|" "$target_file" -sed -i -E "s|(^[[:space:]]*hash = \").*(\";)|\1${latest_hash}\2|" "$target_file" - -echo "Updated tg-ws-proxy pin: ${current_rev} -> ${latest_tag}" -echo "Updated tg-ws-proxy hash: ${current_hash} -> ${latest_hash}"