Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22ebfa171d | ||
|
|
190ba24ce6 | ||
|
|
1f5e050cb2 | ||
|
|
5b5598d12e | ||
|
|
ce86e5669b | ||
|
|
759bde8b29 | ||
|
|
433a13ccad | ||
|
|
f060c4cd5e | ||
|
|
39ce4d6be2 | ||
|
|
377d974a18 | ||
|
|
32bf2266c0 | ||
|
|
334755fd0e | ||
|
|
6025e463a5 | ||
|
|
110e33bc27 | ||
|
|
86e229ff4c | ||
|
|
70c0454446 | ||
|
|
1198a63f3e | ||
|
|
fc95f71292 | ||
|
|
148f2bf2a2 | ||
|
|
bcc64b3a1b | ||
|
|
43935daeb1 | ||
|
|
b696821d8c | ||
|
|
65e815e6dc | ||
|
|
676fa65747 | ||
|
|
4d6802e194 | ||
|
|
744a769e73 | ||
|
|
078367d919 | ||
|
|
716fe4b18d | ||
|
|
189cf4412d | ||
|
|
af2121412b | ||
|
|
d6cbea79bf | ||
|
|
93e792f2e5 | ||
|
|
ba7560bfac | ||
|
|
b6bde24d2d | ||
|
|
1860928c9c | ||
|
|
415336e618 | ||
|
|
f77f306acb | ||
|
|
476b3fc21e | ||
|
|
5e69502382 | ||
|
|
d3ef8257ab | ||
|
|
f54ae974ef |
No files matched your search
@@ -0,0 +1,89 @@
|
|||||||
|
name: Dependency updates
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 6 * * 1"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: dependency-updates
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
update-dependencies:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Install Nix
|
||||||
|
uses: DeterminateSystems/nix-installer-action@v22
|
||||||
|
|
||||||
|
- name: Decide whether nixpkgs should be updated
|
||||||
|
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
|
||||||
|
else
|
||||||
|
echo "Skipping nixpkgs update: watched package versions on nixos-unstable are unchanged."
|
||||||
|
fi
|
||||||
|
nix flake lock --update-input zapret
|
||||||
|
|
||||||
|
- name: Update tg-ws-proxy pin
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
chmod +x scripts/update-tg-ws-proxy.sh
|
||||||
|
scripts/update-tg-ws-proxy.sh
|
||||||
|
|
||||||
|
- name: Detect dependency file changes
|
||||||
|
id: changes
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if git diff --quiet -- flake.lock pkgs/tg-ws-proxy.nix; then
|
||||||
|
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Run flake checks
|
||||||
|
if: steps.changes.outputs.has_changes == 'true'
|
||||||
|
run: nix flake check
|
||||||
|
|
||||||
|
- name: Create or update pull request
|
||||||
|
if: steps.changes.outputs.has_changes == 'true'
|
||||||
|
uses: peter-evans/create-pull-request@v8
|
||||||
|
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"
|
||||||
|
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'
|
||||||
|
run: echo "No dependency updates detected."
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 FUFSoB
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Declarative proxy stack for NixOS.
|
Declarative proxy stack for NixOS.
|
||||||
|
|
||||||
Bundles [sing-box](https://github.com/SagerNet/sing-box), [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), [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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -10,14 +10,15 @@ The goal is to replace GUI clients like v2rayN and throne – you configure your
|
|||||||
|
|
||||||
## What it gives you
|
## What it gives you
|
||||||
|
|
||||||
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` by default – always running, always available to apps
|
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` when `proxy.enable = true`
|
||||||
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand or autostart at boot
|
- **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
|
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart
|
||||||
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
|
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
|
||||||
- **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer
|
- **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
|
- **Multiple outbounds** with automatic latency-based switching or manual selection
|
||||||
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
|
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
|
||||||
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, TUIC v5, socks5, socks4, http/https proxy
|
- **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
|
- **`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
|
- **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
|
- **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy
|
||||||
@@ -40,20 +41,115 @@ Add the module to your NixOS configuration:
|
|||||||
modules = [ inputs.proxy-suite.nixosModules.default ];
|
modules = [ inputs.proxy-suite.nixosModules.default ];
|
||||||
```
|
```
|
||||||
|
|
||||||
Enable the service with all defaults:
|
Feature-complete starter config:
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
services.proxy-suite = {
|
services.proxy-suite = {
|
||||||
enable = true;
|
enable = true;
|
||||||
|
|
||||||
|
proxy = {
|
||||||
|
enable = true;
|
||||||
|
singBox.enable = true;
|
||||||
|
# Or use XRay instead:
|
||||||
|
# xray.enable = true;
|
||||||
|
|
||||||
|
port = 1080;
|
||||||
|
|
||||||
|
# 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;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
zapret = {
|
||||||
|
enable = true;
|
||||||
|
perApp.enable = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
perAppRouting = {
|
||||||
|
enable = true;
|
||||||
|
createDefaultProfiles = true;
|
||||||
|
proxychains.enable = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
tray = {
|
||||||
|
enable = true;
|
||||||
|
autostart = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
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";
|
||||||
|
};
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
By default, `zapret` and `tgWsProxy` stay disabled until you enable them explicitly.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Options
|
## Options
|
||||||
|
|
||||||
To see options and documentation, check out the [options reference](./docs/options.md).
|
To see options and documentation, check out the [options reference](./docs/options.md).
|
||||||
|
|
||||||
Options are autogenerated from [options.nix](./modules/proxy-suite/options.nix) using `nix run .#update-options-doc`.
|
Options and generated README help are refreshed with `nix run .#update-docs`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `proxy-ctl help`
|
||||||
|
|
||||||
|
Generated from current `proxy-ctl help` output.
|
||||||
|
|
||||||
|
<!-- proxy-ctl-help:start -->
|
||||||
|
```text
|
||||||
|
Usage: proxy-ctl <command> [args]
|
||||||
|
|
||||||
|
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
|
||||||
|
route-mode default|whitelist|blacklist|all-proxy|all-bypass|status
|
||||||
|
set temporary routing override
|
||||||
|
zapret on|off enable/disable zapret-discord-youtube
|
||||||
|
restart restart active global proxy-suite services
|
||||||
|
logs [service] follow service logs (default: proxy-suite-socks)
|
||||||
|
outbounds list outbounds and current selection
|
||||||
|
select <tag> switch to a specific outbound (selector mode)
|
||||||
|
apps list configured per-app routing profiles
|
||||||
|
wrap <profile> -- <cmd> run a command via a perAppRouting profile
|
||||||
|
subscription list show subscriptions, cache age, and proxy count
|
||||||
|
subscription update force-refresh all subscription caches and restart active proxy services
|
||||||
|
```
|
||||||
|
<!-- proxy-ctl-help:end -->
|
||||||
+2050
-1118
File diff suppressed because it is too large.
Load diff
Generated
+9
-9
@@ -20,11 +20,11 @@
|
|||||||
},
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1775710090,
|
"lastModified": 1779560665,
|
||||||
"narHash": "sha256-ar3rofg+awPB8QXDaFJhJ2jJhu+KqN/PRCXeyuXR76E=",
|
"narHash": "sha256-tpyBcxPpcQb8ukyNF7DoCwfSY3VPsxHoYwj00Cayv5o=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "4c1018dae018162ec878d42fec712642d214fdfa",
|
"rev": "64c08a7ca051951c8eae34e3e3cb1e202fe36786",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -64,11 +64,11 @@
|
|||||||
"zapret-flowseal": "zapret-flowseal"
|
"zapret-flowseal": "zapret-flowseal"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1775231936,
|
"lastModified": 1780265315,
|
||||||
"narHash": "sha256-jvyi6D2Ps0zicpIcn24tacIymQOyUVY6lr6B5RLQkx8=",
|
"narHash": "sha256-akozC33JwGQM1S5R5dS2sG/Wsh9k0AVfHgszBySiY/o=",
|
||||||
"owner": "kartavkun",
|
"owner": "kartavkun",
|
||||||
"repo": "zapret-discord-youtube",
|
"repo": "zapret-discord-youtube",
|
||||||
"rev": "b3e3f854f8d9cf35ddbcbfa7a03cb0a1334dd7eb",
|
"rev": "9d8c3110075117a7d9c0f73395fc3eafa6b76222",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -80,11 +80,11 @@
|
|||||||
"zapret-flowseal": {
|
"zapret-flowseal": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1775228068,
|
"lastModified": 1780149029,
|
||||||
"narHash": "sha256-LAbCZRwoGxQcgO1nio33NlxBXIdsTQJxHQxu1RWctIA=",
|
"narHash": "sha256-mXBl6jYku2zXaiSlzzmf1WhhsDYKEvqltLlebxU6kgA=",
|
||||||
"owner": "Flowseal",
|
"owner": "Flowseal",
|
||||||
"repo": "zapret-discord-youtube",
|
"repo": "zapret-discord-youtube",
|
||||||
"rev": "22a9ca3bc067441789c83bd80c00d38e54be51c4",
|
"rev": "7e9b42a00b4c1c3bb5370401b9befcb8565b3ac6",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
description = "NixOS proxy suite – sing-box, zapret, tg-ws-proxy";
|
description = "NixOS proxy suite - SingBox, XRay, zapret, tg-ws-proxy";
|
||||||
|
|
||||||
inputs = {
|
inputs = {
|
||||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
@@ -26,6 +26,14 @@
|
|||||||
mkOptionsDoc = import ./nix/options-doc.nix {
|
mkOptionsDoc = import ./nix/options-doc.nix {
|
||||||
inherit nixpkgs pkgsFor proxySuiteModule;
|
inherit nixpkgs pkgsFor proxySuiteModule;
|
||||||
};
|
};
|
||||||
|
mkReadmeDoc = import ./nix/readme-doc.nix {
|
||||||
|
inherit
|
||||||
|
nixpkgs
|
||||||
|
pkgsFor
|
||||||
|
proxySuiteModule
|
||||||
|
zapret
|
||||||
|
;
|
||||||
|
};
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
# Main module – bakes in the zapret flake so consumers don't need it as a separate input.
|
# Main module – bakes in the zapret flake so consumers don't need it as a separate input.
|
||||||
@@ -35,21 +43,22 @@
|
|||||||
nixosModules.zapret = zapret.nixosModules.default;
|
nixosModules.zapret = zapret.nixosModules.default;
|
||||||
|
|
||||||
overlays.default = final: prev: {
|
overlays.default = final: prev: {
|
||||||
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = final; };
|
inherit (import ./pkgs/default.nix { pkgs = final; })
|
||||||
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = final; };
|
mkProxyCtl
|
||||||
|
mkProxySuiteTray
|
||||||
|
mkTgWsProxy
|
||||||
|
tg-ws-proxy
|
||||||
|
proxy-suite-tray
|
||||||
|
;
|
||||||
};
|
};
|
||||||
|
|
||||||
packages = forAll (
|
packages = forAll (
|
||||||
system:
|
system:
|
||||||
let
|
let
|
||||||
pkgs = pkgsFor system;
|
pkgs = pkgsFor system;
|
||||||
in
|
suitePkgs = import ./pkgs/default.nix { inherit pkgs; };
|
||||||
{
|
updateDocs = pkgs.writeShellApplication {
|
||||||
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { inherit pkgs; };
|
name = "update-docs";
|
||||||
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { inherit pkgs; };
|
|
||||||
optionsDoc = mkOptionsDoc system;
|
|
||||||
update-options-doc = pkgs.writeShellApplication {
|
|
||||||
name = "update-options-doc";
|
|
||||||
runtimeInputs = [
|
runtimeInputs = [
|
||||||
pkgs.coreutils
|
pkgs.coreutils
|
||||||
pkgs.git
|
pkgs.git
|
||||||
@@ -65,20 +74,45 @@
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
|
options_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
|
||||||
target_path="''${repo_root}/docs/options.md"
|
readme_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#readmeDoc")"
|
||||||
|
|
||||||
install -Dm644 "''${output_path}" "''${target_path}"
|
install -Dm644 "''${options_output_path}" "''${repo_root}/docs/options.md"
|
||||||
echo "updated ''${target_path}"
|
install -Dm644 "''${readme_output_path}" "''${repo_root}/README.md"
|
||||||
|
|
||||||
|
echo "updated ''${repo_root}/docs/options.md"
|
||||||
|
echo "updated ''${repo_root}/README.md"
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit (suitePkgs)
|
||||||
|
tg-ws-proxy
|
||||||
|
proxy-suite-tray
|
||||||
|
;
|
||||||
|
optionsDoc = mkOptionsDoc system;
|
||||||
|
readmeDoc = mkReadmeDoc system;
|
||||||
|
update-docs = updateDocs;
|
||||||
|
update-options-doc = pkgs.writeShellApplication {
|
||||||
|
name = "update-options-doc";
|
||||||
|
runtimeInputs = [ updateDocs ];
|
||||||
|
text = ''
|
||||||
|
exec ${updateDocs}/bin/update-docs "$@"
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
apps = forAll (system: {
|
apps = forAll (system: {
|
||||||
|
update-docs = {
|
||||||
|
type = "app";
|
||||||
|
program = "${self.packages.${system}.update-docs}/bin/update-docs";
|
||||||
|
meta.description = "Update generated docs and README help from current NixOS module outputs";
|
||||||
|
};
|
||||||
update-options-doc = {
|
update-options-doc = {
|
||||||
type = "app";
|
type = "app";
|
||||||
program = "${self.packages.${system}.update-options-doc}/bin/update-options-doc";
|
program = "${self.packages.${system}.update-options-doc}/bin/update-options-doc";
|
||||||
|
meta.description = "Compatibility alias for update-docs";
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -92,6 +126,7 @@
|
|||||||
zapret
|
zapret
|
||||||
;
|
;
|
||||||
generatedOptionsDoc = mkOptionsDoc system;
|
generatedOptionsDoc = mkOptionsDoc system;
|
||||||
|
generatedReadmeDoc = mkReadmeDoc system;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+376
-58
@@ -1,5 +1,5 @@
|
|||||||
# Build-time sing-box configuration templates.
|
# Build-time proxy backend configuration templates.
|
||||||
# The proxy outbound(s) are injected at service start time, not here.
|
# Proxy outbounds are injected at service start time, not here.
|
||||||
{
|
{
|
||||||
lib,
|
lib,
|
||||||
pkgs,
|
pkgs,
|
||||||
@@ -8,11 +8,34 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
sb = cfg.singBox;
|
derived = import ./derived.nix { inherit lib cfg; };
|
||||||
art = cfg.appRouting.backends.tun;
|
inherit (derived)
|
||||||
|
proxyCfg
|
||||||
|
singBoxCfg
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
globalTun
|
||||||
|
globalTproxy
|
||||||
|
clashApiEnabled
|
||||||
|
;
|
||||||
|
perAppTun = derived.perAppRoutingTun;
|
||||||
direct = rules.direct;
|
direct = rules.direct;
|
||||||
|
xrayGlobalTunIPv6Address = "fd66:19::1/64";
|
||||||
|
xrayPerAppTunIPv6Address = "fd66:20::1/64";
|
||||||
|
xrayFakeDnsPools = [
|
||||||
|
{
|
||||||
|
ipPool = "198.18.0.0/15";
|
||||||
|
poolSize = 32768;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
ipPool = "fc00::/18";
|
||||||
|
poolSize = 32768;
|
||||||
|
}
|
||||||
|
];
|
||||||
|
stripCidr = cidr: builtins.head (lib.splitString "/" cidr);
|
||||||
|
|
||||||
mkDnsServer =
|
mkSingBoxDnsServer =
|
||||||
tag: upstream: detour:
|
tag: upstream: detour:
|
||||||
{
|
{
|
||||||
inherit tag;
|
inherit tag;
|
||||||
@@ -22,15 +45,17 @@ let
|
|||||||
}
|
}
|
||||||
// lib.optionalAttrs (detour != null) { inherit detour; };
|
// lib.optionalAttrs (detour != null) { inherit detour; };
|
||||||
|
|
||||||
mkDnsConfig =
|
mkSingBoxDnsConfig =
|
||||||
{ localDetour ? null }:
|
{
|
||||||
|
localDetour ? null,
|
||||||
|
}:
|
||||||
{
|
{
|
||||||
servers = [
|
servers = [
|
||||||
(mkDnsServer "remote" sb.dns.remote "proxy")
|
(mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy")
|
||||||
(mkDnsServer "local" sb.dns.local localDetour)
|
(mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour)
|
||||||
];
|
];
|
||||||
rules =
|
rules =
|
||||||
lib.optional (builtins.elem "google" sb.routing.proxy.geosites) {
|
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
|
||||||
rule_set = [ "geosite-google" ];
|
rule_set = [ "geosite-google" ];
|
||||||
server = "remote";
|
server = "remote";
|
||||||
}
|
}
|
||||||
@@ -38,75 +63,96 @@ let
|
|||||||
rule_set = map (s: "geosite-${s}") direct.geosites;
|
rule_set = map (s: "geosite-${s}") direct.geosites;
|
||||||
server = "local";
|
server = "local";
|
||||||
};
|
};
|
||||||
final = if sb.proxyByDefault then "remote" else "local";
|
final = if proxyCfg.proxyByDefault then "remote" else "local";
|
||||||
};
|
};
|
||||||
|
|
||||||
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
|
xrayDnsBridgeHijackRule = {
|
||||||
|
inbound = [ "xray-dns-in" ];
|
||||||
|
network = [
|
||||||
|
"tcp"
|
||||||
|
"udp"
|
||||||
|
];
|
||||||
|
action = "hijack-dns";
|
||||||
|
};
|
||||||
|
|
||||||
|
clashApiBlock = lib.optionalAttrs clashApiEnabled {
|
||||||
experimental = {
|
experimental = {
|
||||||
clash_api = {
|
clash_api = {
|
||||||
external_controller = "127.0.0.1:${toString sb.clashApiPort}";
|
external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
mkConfig =
|
mkSingBoxConfig =
|
||||||
{
|
{
|
||||||
enableMixed ? false,
|
enableMixed ? false,
|
||||||
enableTProxy ? false,
|
enableTProxy ? false,
|
||||||
enableTun ? false,
|
enableTun ? false,
|
||||||
tunInterface ? sb.tun.interface,
|
tunInterface ? globalTun.interface,
|
||||||
tunAddress ? sb.tun.address,
|
tunAddress ? globalTun.address,
|
||||||
tunMtu ? sb.tun.mtu,
|
tunMtu ? globalTun.mtu,
|
||||||
tunAutoRoute ? true,
|
tunAutoRoute ? true,
|
||||||
|
tunAutoRouteTableIndex ? 2022,
|
||||||
|
tunAutoRouteRuleIndex ? 9000,
|
||||||
tunAutoRedirect ? true,
|
tunAutoRedirect ? true,
|
||||||
tunStrictRoute ? true,
|
tunStrictRoute ? true,
|
||||||
forceLocalDnsViaProxy ? false,
|
forceLocalDnsViaProxy ? false,
|
||||||
useOutboundRoutingMark ? false,
|
useOutboundRoutingMark ? false,
|
||||||
enableClashApi ? true,
|
enableClashApi ? clashApiEnabled,
|
||||||
|
enableXrayDnsBridge ? hybridEnabled,
|
||||||
|
xrayDnsBridgePort ? 18533,
|
||||||
}:
|
}:
|
||||||
{
|
{
|
||||||
log.level = "warn";
|
log.level = "warn";
|
||||||
|
|
||||||
# Keep "local" DNS on the direct path by default, but avoid explicit
|
dns = mkSingBoxDnsConfig {
|
||||||
# detour="direct" because sing-box rejects detouring to an empty
|
|
||||||
# direct outbound. Global TUN can force local DNS through proxy.
|
|
||||||
dns = mkDnsConfig {
|
|
||||||
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
|
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
|
||||||
};
|
};
|
||||||
|
|
||||||
inbounds =
|
inbounds =
|
||||||
lib.optional enableMixed {
|
lib.optional enableXrayDnsBridge {
|
||||||
|
type = "direct";
|
||||||
|
tag = "xray-dns-in";
|
||||||
|
listen = "127.0.0.1";
|
||||||
|
listen_port = xrayDnsBridgePort;
|
||||||
|
}
|
||||||
|
++ lib.optional enableMixed {
|
||||||
type = "mixed";
|
type = "mixed";
|
||||||
tag = "mixed-in";
|
tag = "mixed-in";
|
||||||
listen = sb.listenAddress;
|
listen = proxyCfg.listenAddress;
|
||||||
listen_port = sb.port;
|
listen_port = proxyCfg.port;
|
||||||
}
|
}
|
||||||
++ lib.optional enableTProxy {
|
++ lib.optional enableTProxy {
|
||||||
type = "tproxy";
|
type = "tproxy";
|
||||||
tag = "tproxy-in";
|
tag = "tproxy-in";
|
||||||
listen = "127.0.0.1";
|
listen = "127.0.0.1";
|
||||||
listen_port = sb.tproxyPort;
|
listen_port = globalTproxy.port;
|
||||||
}
|
}
|
||||||
++ lib.optional enableTun {
|
++ lib.optional enableTun (
|
||||||
type = "tun";
|
{
|
||||||
tag = "tun-in";
|
type = "tun";
|
||||||
interface_name = tunInterface;
|
tag = "tun-in";
|
||||||
address = [ tunAddress ];
|
interface_name = tunInterface;
|
||||||
mtu = tunMtu;
|
address = [ tunAddress ];
|
||||||
auto_route = tunAutoRoute;
|
mtu = tunMtu;
|
||||||
auto_redirect = tunAutoRedirect;
|
auto_route = tunAutoRoute;
|
||||||
strict_route = tunStrictRoute;
|
auto_redirect = tunAutoRedirect;
|
||||||
stack = "mixed";
|
strict_route = tunStrictRoute;
|
||||||
};
|
stack = "mixed";
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs tunAutoRoute {
|
||||||
|
iproute2_table_index = tunAutoRouteTableIndex;
|
||||||
|
iproute2_rule_index = tunAutoRouteRuleIndex;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
# proxy outbound(s) are prepended at runtime by the start script
|
|
||||||
outbounds = [
|
outbounds = [
|
||||||
(
|
(
|
||||||
{
|
{
|
||||||
type = "direct";
|
type = "direct";
|
||||||
tag = "direct";
|
tag = "direct";
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = sb.proxyMark; }
|
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
type = "block";
|
type = "block";
|
||||||
@@ -117,52 +163,324 @@ let
|
|||||||
route = {
|
route = {
|
||||||
default_domain_resolver = "local";
|
default_domain_resolver = "local";
|
||||||
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
||||||
rules = rules.routingRules;
|
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
|
||||||
final = if sb.proxyByDefault then "proxy" else "direct";
|
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
|
// lib.optionalAttrs (enableTun && tunAutoRoute) {
|
||||||
|
auto_detect_interface = true;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs enableClashApi clashApiBlock;
|
// lib.optionalAttrs enableClashApi clashApiBlock;
|
||||||
|
|
||||||
tproxyTemplate = mkConfig {
|
xrayDnsAddress =
|
||||||
|
upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
|
||||||
|
|
||||||
|
mkXrayDnsServer = tag: upstream: {
|
||||||
|
address = xrayDnsAddress upstream;
|
||||||
|
inherit tag;
|
||||||
|
port = upstream.port;
|
||||||
|
queryStrategy = "UseIP";
|
||||||
|
};
|
||||||
|
|
||||||
|
mkXraySniffing =
|
||||||
|
{
|
||||||
|
fakeDnsOnly ? false,
|
||||||
|
}:
|
||||||
|
if fakeDnsOnly then
|
||||||
|
{
|
||||||
|
enabled = true;
|
||||||
|
destOverride = [ "fakedns" ];
|
||||||
|
metadataOnly = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
enabled = true;
|
||||||
|
destOverride = [
|
||||||
|
"http"
|
||||||
|
"tls"
|
||||||
|
"quic"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
xraySniffing = mkXraySniffing { };
|
||||||
|
|
||||||
|
mkXrayTunDnsConfig =
|
||||||
|
{
|
||||||
|
preferRemote ? proxyCfg.proxyByDefault,
|
||||||
|
}:
|
||||||
|
let
|
||||||
|
primaryTag = if preferRemote then "remote" else "local";
|
||||||
|
secondaryTag = if preferRemote then "local" else "remote";
|
||||||
|
primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local;
|
||||||
|
secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote;
|
||||||
|
in
|
||||||
|
{
|
||||||
|
queryStrategy = "UseIP";
|
||||||
|
tag = "dns-in";
|
||||||
|
servers = [
|
||||||
|
{
|
||||||
|
address = "fakedns";
|
||||||
|
tag = "fakedns";
|
||||||
|
}
|
||||||
|
(mkXrayDnsServer primaryTag primaryUpstream)
|
||||||
|
(mkXrayDnsServer secondaryTag secondaryUpstream)
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
xrayTunDnsHijackRule = {
|
||||||
|
type = "field";
|
||||||
|
inboundTag = [ "tun-in" ];
|
||||||
|
network = "tcp,udp";
|
||||||
|
port = 53;
|
||||||
|
outboundTag = "dns-out";
|
||||||
|
ruleTag = "dns-hijack";
|
||||||
|
};
|
||||||
|
|
||||||
|
xrayTunDnsUpstreamRule = {
|
||||||
|
type = "field";
|
||||||
|
inboundTag = [ "dns-in" ];
|
||||||
|
network = "tcp,udp";
|
||||||
|
outboundTag = "direct";
|
||||||
|
ruleTag = "dns-upstream-direct";
|
||||||
|
};
|
||||||
|
|
||||||
|
xrayFinalRule =
|
||||||
|
tag:
|
||||||
|
{
|
||||||
|
type = "field";
|
||||||
|
network = "tcp,udp";
|
||||||
|
ruleTag = "final-default";
|
||||||
|
}
|
||||||
|
// (
|
||||||
|
if tag == "proxy" && proxyCfg.selection == "urltest" then
|
||||||
|
{ balancerTag = "proxy"; }
|
||||||
|
else
|
||||||
|
{ outboundTag = tag; }
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayRouteRules = rules.xrayRoutingRules ++ [
|
||||||
|
(xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct"))
|
||||||
|
];
|
||||||
|
|
||||||
|
xrayDirectOutbound =
|
||||||
|
useOutboundRoutingMark:
|
||||||
|
{
|
||||||
|
protocol = "freedom";
|
||||||
|
tag = "direct";
|
||||||
|
settings = { };
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs useOutboundRoutingMark {
|
||||||
|
streamSettings.sockopt.mark = globalTproxy.proxyMark;
|
||||||
|
};
|
||||||
|
|
||||||
|
mkXrayConfig =
|
||||||
|
{
|
||||||
|
enableMixed ? false,
|
||||||
|
enableTProxy ? false,
|
||||||
|
enableTun ? false,
|
||||||
|
tunInterface ? globalTun.interface,
|
||||||
|
tunAddress ? globalTun.address,
|
||||||
|
tunIPv6Address ? null,
|
||||||
|
tunMtu ? globalTun.mtu,
|
||||||
|
useOutboundRoutingMark ? false,
|
||||||
|
enableUrlTest ? proxyCfg.selection == "urltest",
|
||||||
|
domainStrategy ? "IPIfNonMatch",
|
||||||
|
enableTunFakeDns ? false,
|
||||||
|
}:
|
||||||
|
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)
|
||||||
|
];
|
||||||
|
xrayTunSniffing = mkXraySniffing { fakeDnsOnly = enableTunFakeDns; };
|
||||||
|
xrayDnsConfig =
|
||||||
|
if enableTunFakeDns then
|
||||||
|
mkXrayTunDnsConfig { }
|
||||||
|
else
|
||||||
|
{
|
||||||
|
servers = [
|
||||||
|
(mkXrayDnsServer "remote" proxyCfg.dns.remote)
|
||||||
|
(mkXrayDnsServer "local" proxyCfg.dns.local)
|
||||||
|
];
|
||||||
|
};
|
||||||
|
xrayTunOutbounds = lib.optionals enableTunFakeDns [
|
||||||
|
{
|
||||||
|
protocol = "dns";
|
||||||
|
tag = "dns-out";
|
||||||
|
settings = {
|
||||||
|
userLevel = 0;
|
||||||
|
rules = [
|
||||||
|
{
|
||||||
|
action = "direct";
|
||||||
|
qType = "2-27,29-65535";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
xrayRoutingRules =
|
||||||
|
lib.optionals enableTunFakeDns [
|
||||||
|
xrayTunDnsUpstreamRule
|
||||||
|
xrayTunDnsHijackRule
|
||||||
|
]
|
||||||
|
++ rules.xrayRoutingRules
|
||||||
|
++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ];
|
||||||
|
in
|
||||||
|
{
|
||||||
|
log.loglevel = "warning";
|
||||||
|
dns = xrayDnsConfig;
|
||||||
|
inbounds =
|
||||||
|
lib.optional enableMixed {
|
||||||
|
tag = "mixed-in";
|
||||||
|
protocol = "socks";
|
||||||
|
listen = proxyCfg.listenAddress;
|
||||||
|
port = proxyCfg.port;
|
||||||
|
settings = {
|
||||||
|
auth = "noauth";
|
||||||
|
udp = true;
|
||||||
|
ip = proxyCfg.listenAddress;
|
||||||
|
};
|
||||||
|
sniffing = xraySniffing;
|
||||||
|
}
|
||||||
|
++ lib.optional enableTProxy {
|
||||||
|
tag = "tproxy-in";
|
||||||
|
protocol = "tunnel";
|
||||||
|
listen = "127.0.0.1";
|
||||||
|
port = globalTproxy.port;
|
||||||
|
settings = {
|
||||||
|
allowedNetwork = "tcp,udp";
|
||||||
|
followRedirect = true;
|
||||||
|
};
|
||||||
|
streamSettings.sockopt.tproxy = "tproxy";
|
||||||
|
sniffing = xraySniffing;
|
||||||
|
}
|
||||||
|
++ lib.optional enableTun {
|
||||||
|
tag = "tun-in";
|
||||||
|
protocol = "tun";
|
||||||
|
settings = {
|
||||||
|
name = tunInterface;
|
||||||
|
mtu = tunMtu;
|
||||||
|
gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ];
|
||||||
|
dns = tunDnsServers;
|
||||||
|
userLevel = 0;
|
||||||
|
autoOutboundsInterface = "auto";
|
||||||
|
};
|
||||||
|
sniffing = xrayTunSniffing;
|
||||||
|
};
|
||||||
|
outbounds = xrayTunOutbounds ++ [
|
||||||
|
(xrayDirectOutbound useOutboundRoutingMark)
|
||||||
|
{
|
||||||
|
protocol = "blackhole";
|
||||||
|
tag = "block";
|
||||||
|
settings = { };
|
||||||
|
}
|
||||||
|
];
|
||||||
|
routing = {
|
||||||
|
domainStrategy = domainStrategy;
|
||||||
|
domainMatcher = "hybrid";
|
||||||
|
rules = xrayRoutingRules;
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs enableUrlTest {
|
||||||
|
balancers = [
|
||||||
|
{
|
||||||
|
tag = "proxy";
|
||||||
|
selector = [ "proxy-suite-ob-" ];
|
||||||
|
strategy = {
|
||||||
|
type = "leastPing";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs enableUrlTest {
|
||||||
|
observatory = {
|
||||||
|
subjectSelector = [ "proxy-suite-ob-" ];
|
||||||
|
probeUrl = proxyCfg.urlTest.url;
|
||||||
|
probeInterval = proxyCfg.urlTest.interval;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs enableTunFakeDns { fakedns = xrayFakeDnsPools; };
|
||||||
|
|
||||||
|
singBoxTproxyTemplate = mkSingBoxConfig {
|
||||||
enableMixed = true;
|
enableMixed = true;
|
||||||
enableTProxy = true;
|
enableTProxy = true;
|
||||||
useOutboundRoutingMark = true;
|
useOutboundRoutingMark = true;
|
||||||
enableClashApi = true;
|
xrayDnsBridgePort = 18533;
|
||||||
};
|
};
|
||||||
|
|
||||||
tunTemplate = mkConfig {
|
singBoxTunTemplate = mkSingBoxConfig {
|
||||||
enableTun = true;
|
enableTun = true;
|
||||||
tunInterface = sb.tun.interface;
|
tunInterface = globalTun.interface;
|
||||||
tunAddress = sb.tun.address;
|
tunAddress = globalTun.address;
|
||||||
tunMtu = sb.tun.mtu;
|
tunMtu = globalTun.mtu;
|
||||||
tunAutoRoute = true;
|
tunAutoRoute = true;
|
||||||
tunAutoRedirect = true;
|
tunAutoRedirect = true;
|
||||||
tunStrictRoute = true;
|
tunStrictRoute = true;
|
||||||
forceLocalDnsViaProxy = true;
|
forceLocalDnsViaProxy = false;
|
||||||
enableClashApi = false;
|
enableClashApi = false;
|
||||||
|
xrayDnsBridgePort = 18534;
|
||||||
};
|
};
|
||||||
|
|
||||||
appTunTemplate = mkConfig {
|
singBoxPerAppTunTemplate = mkSingBoxConfig {
|
||||||
enableTun = true;
|
enableTun = true;
|
||||||
tunInterface = art.interface;
|
tunInterface = perAppTun.interface;
|
||||||
tunAddress = art.address;
|
tunAddress = perAppTun.address;
|
||||||
tunMtu = art.mtu;
|
tunMtu = perAppTun.mtu;
|
||||||
tunAutoRoute = false;
|
tunAutoRoute = false;
|
||||||
tunAutoRedirect = false;
|
tunAutoRedirect = false;
|
||||||
tunStrictRoute = false;
|
tunStrictRoute = false;
|
||||||
forceLocalDnsViaProxy = false;
|
forceLocalDnsViaProxy = false;
|
||||||
# App TUN can be used alongside TProxy; mark direct egress so TProxy output
|
useOutboundRoutingMark = globalTproxy.enable;
|
||||||
# rules do not re-intercept sing-box's own packets.
|
|
||||||
useOutboundRoutingMark = sb.tproxy.enable;
|
|
||||||
enableClashApi = false;
|
enableClashApi = false;
|
||||||
|
xrayDnsBridgePort = 18535;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
xrayTproxyTemplate = mkXrayConfig {
|
||||||
|
enableMixed = true;
|
||||||
|
enableTProxy = true;
|
||||||
|
useOutboundRoutingMark = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
xrayTunTemplate = mkXrayConfig {
|
||||||
|
enableTun = true;
|
||||||
|
tunInterface = globalTun.interface;
|
||||||
|
tunAddress = globalTun.address;
|
||||||
|
tunIPv6Address = xrayGlobalTunIPv6Address;
|
||||||
|
tunMtu = globalTun.mtu;
|
||||||
|
useOutboundRoutingMark = true;
|
||||||
|
enableTunFakeDns = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
xrayPerAppTunTemplate = mkXrayConfig {
|
||||||
|
enableTun = true;
|
||||||
|
tunInterface = perAppTun.interface;
|
||||||
|
tunAddress = perAppTun.address;
|
||||||
|
tunIPv6Address = xrayPerAppTunIPv6Address;
|
||||||
|
tunMtu = perAppTun.mtu;
|
||||||
|
useOutboundRoutingMark = true;
|
||||||
|
enableTunFakeDns = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
tproxyTemplate = if pureXrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate;
|
||||||
|
tunTemplate = if pureXrayEnabled then xrayTunTemplate else singBoxTunTemplate;
|
||||||
|
perAppTunTemplate = if pureXrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate;
|
||||||
|
routeModeRules = if pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
|
||||||
|
|
||||||
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
|
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
|
||||||
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
|
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
|
||||||
appTunFile = pkgs.writeText "proxy-suite-app-tun-template.json" (builtins.toJSON appTunTemplate);
|
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
|
||||||
|
builtins.toJSON perAppTunTemplate
|
||||||
|
);
|
||||||
|
routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" (
|
||||||
|
builtins.toJSON routeModeRules
|
||||||
|
);
|
||||||
|
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
inherit tproxyFile tunFile appTunFile;
|
inherit
|
||||||
|
tproxyFile
|
||||||
|
tunFile
|
||||||
|
perAppTunFile
|
||||||
|
routeModeRulesFile
|
||||||
|
;
|
||||||
}
|
}
|
||||||
@@ -11,47 +11,54 @@
|
|||||||
|
|
||||||
let
|
let
|
||||||
cfg = config.services.proxy-suite;
|
cfg = config.services.proxy-suite;
|
||||||
|
packages = import ../../pkgs/default.nix { inherit pkgs; };
|
||||||
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
|
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
imports = [
|
imports = [
|
||||||
./options.nix
|
./options
|
||||||
];
|
];
|
||||||
|
|
||||||
config = lib.mkIf cfg.enable (
|
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 [
|
lib.mkMerge [
|
||||||
(lib.mkIf cfg.singBox.enable (
|
(import ./service {
|
||||||
let
|
inherit
|
||||||
rules = import ./rules.nix {
|
config
|
||||||
inherit
|
lib
|
||||||
lib
|
pkgs
|
||||||
pkgs
|
packages
|
||||||
cfg
|
cfg
|
||||||
zapret
|
;
|
||||||
;
|
inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile;
|
||||||
};
|
inherit (nftr)
|
||||||
configs = import ./config.nix {
|
nftablesRulesFile
|
||||||
inherit
|
perAppTproxyRulesFile
|
||||||
lib
|
perAppZapretRulesFile
|
||||||
pkgs
|
perAppTunChainFile
|
||||||
cfg
|
ip
|
||||||
rules
|
nft
|
||||||
;
|
;
|
||||||
};
|
})
|
||||||
in
|
|
||||||
import ./service.nix {
|
|
||||||
inherit
|
|
||||||
config
|
|
||||||
lib
|
|
||||||
pkgs
|
|
||||||
cfg
|
|
||||||
;
|
|
||||||
inherit (configs) tproxyFile tunFile appTunFile;
|
|
||||||
inherit (nftr) nftablesRulesFile appTproxyRulesFile appZapretRulesFile appTunChainFile ip nft;
|
|
||||||
}
|
|
||||||
))
|
|
||||||
|
|
||||||
(lib.mkIf cfg.zapret.enable (
|
(lib.mkIf (cfg.zapret.enable || cfg.zapret.perApp.enable) (
|
||||||
import ./zapret.nix {
|
import ./zapret.nix {
|
||||||
inherit
|
inherit
|
||||||
lib
|
lib
|
||||||
@@ -59,11 +66,20 @@ in
|
|||||||
cfg
|
cfg
|
||||||
zapret
|
zapret
|
||||||
;
|
;
|
||||||
inherit (nftr) appZapretRulesFile nft;
|
inherit (nftr) perAppZapretRulesFile nft;
|
||||||
}
|
}
|
||||||
))
|
))
|
||||||
|
|
||||||
(lib.mkIf cfg.tgWsProxy.enable (import ./tg-ws-proxy.nix { inherit lib pkgs cfg; }))
|
(lib.mkIf cfg.tgWsProxy.enable (
|
||||||
|
import ./tg-ws-proxy.nix {
|
||||||
|
inherit
|
||||||
|
lib
|
||||||
|
pkgs
|
||||||
|
packages
|
||||||
|
cfg
|
||||||
|
;
|
||||||
|
}
|
||||||
|
))
|
||||||
|
|
||||||
(lib.mkIf cfg.tray.enable (
|
(lib.mkIf cfg.tray.enable (
|
||||||
import ./tray.nix {
|
import ./tray.nix {
|
||||||
@@ -71,6 +87,7 @@ in
|
|||||||
config
|
config
|
||||||
lib
|
lib
|
||||||
pkgs
|
pkgs
|
||||||
|
packages
|
||||||
cfg
|
cfg
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
{
|
||||||
|
lib,
|
||||||
|
cfg,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
proxyCfg = cfg.proxy;
|
||||||
|
singBoxCfg = proxyCfg // {
|
||||||
|
enable = proxyCfg.enable && proxyCfg.singBox.enable;
|
||||||
|
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;
|
||||||
|
perAppRoutingCfg = cfg.perAppRouting;
|
||||||
|
globalTun = proxyCfg.tun;
|
||||||
|
globalTproxy = proxyCfg.tproxy;
|
||||||
|
perAppRoutingTun = proxyCfg.tun.perApp;
|
||||||
|
perAppRoutingTproxy = proxyCfg.tproxy.perApp;
|
||||||
|
perAppZapretCfg = cfg.zapret.perApp;
|
||||||
|
userControlCfg = cfg.userControl;
|
||||||
|
|
||||||
|
selectionMode = proxyCfg.selection;
|
||||||
|
builtinTags = [
|
||||||
|
"proxy"
|
||||||
|
"direct"
|
||||||
|
"block"
|
||||||
|
];
|
||||||
|
outboundTags = map (ob: ob.tag) proxyCfg.outbounds;
|
||||||
|
subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions;
|
||||||
|
|
||||||
|
hasStaticOutbounds = proxyCfg.outbounds != [ ];
|
||||||
|
hasSubscriptions = proxyCfg.subscriptions != [ ];
|
||||||
|
collapseNamedOutbounds = selectionMode == "first";
|
||||||
|
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
|
||||||
|
perAppZapretEnabled = perAppZapretCfg.enable;
|
||||||
|
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
|
||||||
|
|
||||||
|
invalidRoutingTargets = lib.unique (
|
||||||
|
map (rule: rule.outbound) (
|
||||||
|
builtins.filter (
|
||||||
|
rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)
|
||||||
|
) proxyCfg.routing.rules
|
||||||
|
)
|
||||||
|
);
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit
|
||||||
|
proxyCfg
|
||||||
|
singBoxCfg
|
||||||
|
xrayCfg
|
||||||
|
proxyEnabled
|
||||||
|
singBoxEnabled
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureSingBoxEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
activeBackend
|
||||||
|
perAppRoutingCfg
|
||||||
|
globalTun
|
||||||
|
globalTproxy
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
perAppZapretCfg
|
||||||
|
perAppZapretEnabled
|
||||||
|
userControlCfg
|
||||||
|
userControlEnabled
|
||||||
|
selectionMode
|
||||||
|
builtinTags
|
||||||
|
outboundTags
|
||||||
|
subscriptionTags
|
||||||
|
hasStaticOutbounds
|
||||||
|
hasSubscriptions
|
||||||
|
collapseNamedOutbounds
|
||||||
|
clashApiEnabled
|
||||||
|
invalidRoutingTargets
|
||||||
|
;
|
||||||
|
}
|
||||||
@@ -6,110 +6,118 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
sb = cfg.singBox;
|
proxyCfg = cfg.proxy;
|
||||||
art = cfg.appRouting.backends.tun;
|
globalTproxy = proxyCfg.tproxy;
|
||||||
artp = cfg.appRouting.backends.tproxy;
|
perAppTun = proxyCfg.tun.perApp;
|
||||||
arz = cfg.appRouting.backends.zapret;
|
perAppTproxy = proxyCfg.tproxy.perApp;
|
||||||
|
zapretApp = cfg.zapret.perApp;
|
||||||
|
tgWsProxyCfg = cfg.tgWsProxy;
|
||||||
|
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
|
||||||
|
tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled ''
|
||||||
|
meta mark ${toString tgWsProxyCfg.routingMark} return
|
||||||
|
'';
|
||||||
|
|
||||||
# Shared across all three nftables rule files that do IPv4 routing.
|
# Shared across all three nftables rule files that do IPv4 routing.
|
||||||
reservedIpBlock = ''
|
reservedIpBlock = ''
|
||||||
define RESERVED_IP = {
|
define RESERVED_IP = {
|
||||||
10.0.0.0/8,
|
10.0.0.0/8,
|
||||||
100.64.0.0/10,
|
100.64.0.0/10,
|
||||||
127.0.0.0/8,
|
127.0.0.0/8,
|
||||||
169.254.0.0/16,
|
169.254.0.0/16,
|
||||||
172.16.0.0/12,
|
172.16.0.0/12,
|
||||||
192.0.0.0/24,
|
192.0.0.0/24,
|
||||||
224.0.0.0/4,
|
224.0.0.0/4,
|
||||||
240.0.0.0/4,
|
240.0.0.0/4,
|
||||||
255.255.255.255/32
|
255.255.255.255/32
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
|
|
||||||
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: ''
|
mkLocalSubnetLines =
|
||||||
ip daddr ${cidr} tcp dport != 53 return
|
subnets:
|
||||||
ip daddr ${cidr} udp dport != 53 return
|
lib.concatMapStrings (cidr: ''
|
||||||
'') subnets;
|
ip daddr ${cidr} tcp dport != 53 return
|
||||||
|
ip daddr ${cidr} udp dport != 53 return
|
||||||
|
'') subnets;
|
||||||
|
|
||||||
tproxyLocalSubnetLines = mkLocalSubnetLines sb.tproxy.localSubnets;
|
tproxyLocalSubnetLines = mkLocalSubnetLines globalTproxy.localSubnets;
|
||||||
appTproxyLocalSubnetLines = mkLocalSubnetLines artp.localSubnets;
|
perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets;
|
||||||
|
|
||||||
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
|
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
|
||||||
${reservedIpBlock}
|
${reservedIpBlock}
|
||||||
table ip singbox {
|
table ip singbox {
|
||||||
chain prerouting {
|
chain prerouting {
|
||||||
type filter hook prerouting priority mangle; policy accept;
|
type filter hook prerouting priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
# Packets re-entering via loopback after output marking should not
|
# Packets re-entering via loopback after output marking should not
|
||||||
# be skipped just because the host has an RFC1918 source address.
|
# be skipped just because the host has an RFC1918 source address.
|
||||||
iifname != "lo" ip saddr $RESERVED_IP return
|
iifname != "lo" ip saddr $RESERVED_IP return
|
||||||
${tproxyLocalSubnetLines}
|
${tproxyLocalSubnetLines}
|
||||||
ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
|
ip protocol tcp tproxy to 127.0.0.1:${toString globalTproxy.port} meta mark set ${toString globalTproxy.fwmark}
|
||||||
ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
|
ip protocol udp tproxy to 127.0.0.1:${toString globalTproxy.port} meta mark set ${toString globalTproxy.fwmark}
|
||||||
|
}
|
||||||
|
chain output {
|
||||||
|
type route hook output priority mangle; policy accept;
|
||||||
|
ip daddr $RESERVED_IP return
|
||||||
|
${tproxyLocalSubnetLines}
|
||||||
|
meta mark ${toString globalTproxy.proxyMark} return
|
||||||
|
${tgWsProxyBypassMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
|
||||||
|
ip protocol udp meta mark set ${toString globalTproxy.fwmark}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
chain output {
|
|
||||||
type route hook output priority mangle; policy accept;
|
|
||||||
ip daddr $RESERVED_IP return
|
|
||||||
${tproxyLocalSubnetLines}
|
|
||||||
meta mark ${toString sb.proxyMark} return
|
|
||||||
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"}${lib.optionalString artp.enable " meta mark ${toString artp.fwmark} return\n"} ip protocol tcp meta mark set ${toString sb.fwmark}
|
|
||||||
ip protocol udp meta mark set ${toString sb.fwmark}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
'';
|
'';
|
||||||
|
|
||||||
appTproxyRulesFile = pkgs.writeText "proxy-suite-app-tproxy.nft" ''
|
perAppTproxyRulesFile = pkgs.writeText "proxy-suite-per-app-tproxy.nft" ''
|
||||||
${reservedIpBlock}
|
${reservedIpBlock}
|
||||||
table ip proxy_suite_app_tproxy {
|
table ip proxy_suite_per_app_tproxy {
|
||||||
chain prerouting {
|
chain prerouting {
|
||||||
type filter hook prerouting priority mangle; policy accept;
|
type filter hook prerouting priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
iifname != "lo" ip saddr $RESERVED_IP return
|
iifname != "lo" ip saddr $RESERVED_IP return
|
||||||
${appTproxyLocalSubnetLines}
|
${perAppTproxyLocalSubnetLines}
|
||||||
ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
|
ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark}
|
||||||
meta mark ${toString artp.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort}
|
meta mark ${toString perAppTproxy.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString globalTproxy.port}
|
||||||
meta mark ${toString artp.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort}
|
meta mark ${toString perAppTproxy.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString globalTproxy.port}
|
||||||
}
|
}
|
||||||
|
|
||||||
chain output {
|
chain output {
|
||||||
type route hook output priority mangle; policy accept;
|
type route hook output priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
${appTproxyLocalSubnetLines}
|
${perAppTproxyLocalSubnetLines}
|
||||||
meta mark ${toString sb.proxyMark} return
|
meta mark ${toString globalTproxy.proxyMark} return
|
||||||
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"} ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
|
${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"} ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark}
|
||||||
meta mark ${toString artp.fwmark} return
|
meta mark ${toString perAppTproxy.fwmark} return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
'';
|
'';
|
||||||
|
|
||||||
appZapretRulesFile = pkgs.writeText "proxy-suite-app-zapret.nft" ''
|
perAppZapretRulesFile = pkgs.writeText "proxy-suite-per-app-zapret.nft" ''
|
||||||
table inet proxy_suite_app_zapret_mark {
|
table inet proxy_suite_per_app_zapret_mark {
|
||||||
chain prerouting {
|
chain prerouting {
|
||||||
type filter hook prerouting priority -103; policy accept;
|
type filter hook prerouting priority -103; policy accept;
|
||||||
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
|
ct mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} meta mark set meta mark or ${toString zapretApp.filterMark}
|
||||||
}
|
}
|
||||||
|
|
||||||
chain output {
|
chain output {
|
||||||
type route hook output priority -103; policy accept;
|
type route hook output priority -103; policy accept;
|
||||||
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
|
ct mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} meta mark set meta mark or ${toString zapretApp.filterMark}
|
||||||
meta mark and ${toString arz.filterMark} == ${toString arz.filterMark} return
|
meta mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
|
|
||||||
appTunChainFile = pkgs.writeText "proxy-suite-app-tun-chain.nft" ''
|
perAppTunChainFile = pkgs.writeText "proxy-suite-per-app-tun-chain.nft" ''
|
||||||
${reservedIpBlock}
|
${reservedIpBlock}
|
||||||
table inet proxy_suite_app_tun {
|
table inet proxy_suite_per_app_tun {
|
||||||
chain output {
|
chain output {
|
||||||
type route hook output priority mangle; policy accept;
|
type route hook output priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
${lib.concatMapStrings (cidr: ''
|
${lib.concatMapStrings (cidr: ''
|
||||||
ip daddr ${cidr} return
|
ip daddr ${cidr} return
|
||||||
'') art.localSubnets}
|
'') perAppTun.localSubnets}
|
||||||
ct mark ${toString art.fwmark} meta mark set ${toString art.fwmark}
|
ct mark ${toString perAppTun.fwmark} meta mark set ${toString perAppTun.fwmark}
|
||||||
meta mark ${toString art.fwmark} return
|
meta mark ${toString perAppTun.fwmark} return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
'';
|
'';
|
||||||
|
|
||||||
ip = "${pkgs.iproute2}/bin/ip";
|
ip = "${pkgs.iproute2}/bin/ip";
|
||||||
@@ -117,5 +125,12 @@ ${lib.concatMapStrings (cidr: ''
|
|||||||
|
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
inherit nftablesRulesFile appTproxyRulesFile appZapretRulesFile appTunChainFile ip nft;
|
inherit
|
||||||
|
nftablesRulesFile
|
||||||
|
perAppTproxyRulesFile
|
||||||
|
perAppZapretRulesFile
|
||||||
|
perAppTunChainFile
|
||||||
|
ip
|
||||||
|
nft
|
||||||
|
;
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
|||||||
|
# All option declarations for services.proxy-suite, split by feature area.
|
||||||
|
{ ... }:
|
||||||
|
{
|
||||||
|
imports = [
|
||||||
|
./other.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
|
||||||
|
./per-app-routing.nix
|
||||||
|
./zapret.nix
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
{ 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; })
|
||||||
|
];
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
# Top-level, userControl, tray, and tgWsProxy options.
|
||||||
|
{ lib, ... }:
|
||||||
|
|
||||||
|
let
|
||||||
|
inherit (lib) mkOption mkEnableOption types;
|
||||||
|
in
|
||||||
|
{
|
||||||
|
options.services.proxy-suite = {
|
||||||
|
enable = mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)";
|
||||||
|
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
wsKeepalive = mkOption {
|
||||||
|
type = types.numbers.nonnegative;
|
||||||
|
default = 30.0;
|
||||||
|
description = ''
|
||||||
|
Seconds between upstream WebSocket keepalive pings.
|
||||||
|
Set to 0 to disable keepalive pings.
|
||||||
|
'';
|
||||||
|
example = 15.0;
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# Per-app routing options (backends and profiles).
|
||||||
|
{ lib, ... }:
|
||||||
|
|
||||||
|
let
|
||||||
|
inherit (lib) mkOption mkEnableOption types;
|
||||||
|
t = import ./types.nix { inherit lib; };
|
||||||
|
in
|
||||||
|
{
|
||||||
|
options.services.proxy-suite.perAppRouting = {
|
||||||
|
enable = mkEnableOption "per-app routing helpers via proxy-ctl wrap";
|
||||||
|
|
||||||
|
createDefaultProfiles = mkOption {
|
||||||
|
type = types.bool;
|
||||||
|
default = false;
|
||||||
|
description = ''
|
||||||
|
Whether to automatically add curated perAppRouting profiles.
|
||||||
|
|
||||||
|
This is opt-in. Generated defaults are appended only when no
|
||||||
|
user-defined profile with the same name already exists.
|
||||||
|
|
||||||
|
Current curated defaults:
|
||||||
|
- `proxychains`: route = "proxychains"
|
||||||
|
- `tun`: route = "tun" when proxy.tun.perApp.enable = true
|
||||||
|
- `tproxy`: route = "tproxy" when proxy.tproxy.perApp.enable = true
|
||||||
|
- `zapret`: route = "zapret" when zapret.perApp.enable = true
|
||||||
|
|
||||||
|
This makes `proxy-ctl wrap proxychains -- <command>` available
|
||||||
|
without defining the profile manually, and similarly exposes
|
||||||
|
`proxy-ctl wrap tun -- <command>` or
|
||||||
|
`proxy-ctl wrap tproxy -- <command>` or
|
||||||
|
`proxy-ctl wrap zapret -- <command>` when the corresponding backend
|
||||||
|
is enabled.
|
||||||
|
'';
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
example = [
|
||||||
|
{
|
||||||
|
name = "steam-browser";
|
||||||
|
route = "proxychains";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
name = "native-direct";
|
||||||
|
route = "direct";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
proxychains = {
|
||||||
|
enable = mkEnableOption "proxychains-backed perAppRouting profiles";
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
{ 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;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
{ lib, ... }:
|
||||||
|
|
||||||
|
let
|
||||||
|
inherit (lib) mkOption types;
|
||||||
|
t = import ./types.nix { inherit lib; };
|
||||||
|
in
|
||||||
|
{
|
||||||
|
options.services.proxy-suite.proxy = {
|
||||||
|
outbounds = mkOption {
|
||||||
|
type = types.listOf t.outboundType;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
List of static proxy outbounds.
|
||||||
|
Set exactly one of urlFile, url, singBoxJson, xrayJson, or the
|
||||||
|
deprecated json field per entry. Backend-specific raw JSON fields are
|
||||||
|
only valid with their matching backend.
|
||||||
|
|
||||||
|
At least one outbound or one subscription is required when
|
||||||
|
proxy.enable = true.
|
||||||
|
'';
|
||||||
|
example = [
|
||||||
|
{
|
||||||
|
tag = "de-vps";
|
||||||
|
urlFile = "/run/secrets/proxy-de-url";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
tag = "nl-vps";
|
||||||
|
url = "hy2://password@example.com:443?sni=example.com";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
subscriptions = mkOption {
|
||||||
|
type = types.listOf t.subscriptionType;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Subscription URLs that provide dynamic lists of proxy outbounds.
|
||||||
|
Each URL must return a base64-encoded newline-separated list of proxy URIs
|
||||||
|
(standard v2rayN / Clash subscription format) or plain text of the same.
|
||||||
|
|
||||||
|
On first service start, each subscription is fetched live and cached
|
||||||
|
under /var/lib/proxy-suite/subscriptions/<backend>/<tag>.json. Later restarts
|
||||||
|
reuse the cache, so ordinary service restarts do not need network access.
|
||||||
|
|
||||||
|
A systemd timer (proxy-suite-subscription-update) refreshes all caches
|
||||||
|
on the interval set by subscriptionUpdateInterval and restarts the
|
||||||
|
running proxy services after a successful refresh.
|
||||||
|
'';
|
||||||
|
example = [
|
||||||
|
{
|
||||||
|
tag = "community";
|
||||||
|
url = "https://example.com/sub/token";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
tag = "private";
|
||||||
|
urlFile = "/run/secrets/private-sub-url";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
subscriptionUpdateInterval = mkOption {
|
||||||
|
type = types.str;
|
||||||
|
default = "1d";
|
||||||
|
description = ''
|
||||||
|
How often the proxy-suite-subscription-update timer fires and refreshes
|
||||||
|
all subscription caches. Accepts any systemd time span string
|
||||||
|
(e.g. "1h", "6h", "1d", "12h").
|
||||||
|
|
||||||
|
Only used when proxy.subscriptions is non-empty. The timer also runs
|
||||||
|
once shortly after boot.
|
||||||
|
'';
|
||||||
|
example = "6h";
|
||||||
|
};
|
||||||
|
|
||||||
|
selection = mkOption {
|
||||||
|
type = types.enum [
|
||||||
|
"first"
|
||||||
|
"selector"
|
||||||
|
"urltest"
|
||||||
|
];
|
||||||
|
default = "first";
|
||||||
|
description = ''
|
||||||
|
How to pick between multiple proxy outbounds:
|
||||||
|
|
||||||
|
- "first": route through a single active outbound tagged "proxy".
|
||||||
|
The first static outbound is used, or the first subscription
|
||||||
|
outbound if only subscriptions are configured.
|
||||||
|
- "selector": create a Clash-compatible selector outbound tagged
|
||||||
|
"proxy" and keep all configured outbounds available for manual
|
||||||
|
switching via the Clash API.
|
||||||
|
- "urltest": create automatic latency testing tagged "proxy" and
|
||||||
|
keep all configured outbounds available so the active backend can
|
||||||
|
periodically probe and switch to a faster one.
|
||||||
|
|
||||||
|
proxy.singBox.clashApiPort is only used with "selector" or "urltest"
|
||||||
|
on the SingBox backend. "selector" is SingBox-only. "urltest" maps to
|
||||||
|
SingBox urltest or XRay observatory/balancer depending on backend.
|
||||||
|
urlTest.* options are only used with "urltest".
|
||||||
|
Per-outbound tags are only individually meaningful with "selector"
|
||||||
|
or "urltest".
|
||||||
|
'';
|
||||||
|
example = "urltest";
|
||||||
|
};
|
||||||
|
|
||||||
|
urlTest = {
|
||||||
|
url = mkOption {
|
||||||
|
type = types.str;
|
||||||
|
default = "https://www.gstatic.com/generate_204";
|
||||||
|
description = ''
|
||||||
|
URL that the active backend fetches through each proxy to measure latency.
|
||||||
|
Only used when selection = "urltest".
|
||||||
|
|
||||||
|
Set this to a URL that is actually blocked in your region (e.g.
|
||||||
|
"https://telegram.org") so that only proxies that bypass the
|
||||||
|
blocking get selected. If left at the default, any responding proxy
|
||||||
|
wins – including ones that might not unblock your target site.
|
||||||
|
'';
|
||||||
|
example = "https://telegram.org";
|
||||||
|
};
|
||||||
|
|
||||||
|
interval = mkOption {
|
||||||
|
type = types.str;
|
||||||
|
default = "3m";
|
||||||
|
description = ''
|
||||||
|
How often the active backend re-tests all outbounds. Accepts a Go
|
||||||
|
duration string (e.g. "1m", "3m", "10m").
|
||||||
|
Only used when selection = "urltest".
|
||||||
|
'';
|
||||||
|
example = "1m";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
{ 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" ];
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
{ 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 = 1081;
|
||||||
|
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 = 1081;
|
||||||
|
};
|
||||||
|
|
||||||
|
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"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
{ 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.";
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
# 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.
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
# Type submodule definitions shared across options sub-files.
|
||||||
|
{ lib }:
|
||||||
|
|
||||||
|
let
|
||||||
|
inherit (lib) mkOption types;
|
||||||
|
|
||||||
|
# Shared routing-rule fields (reused in both outboundType.routing and routing.rules entries)
|
||||||
|
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"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
# An explicit routing rule – associates traffic patterns with a named outbound.
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
example = "vps-de";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// routingFields;
|
||||||
|
};
|
||||||
|
|
||||||
|
subscriptionType = types.submodule {
|
||||||
|
options = {
|
||||||
|
tag = mkOption {
|
||||||
|
type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$";
|
||||||
|
description = ''
|
||||||
|
Unique identifier for this subscription.
|
||||||
|
Used as a prefix for all outbound tags generated from its proxy list,
|
||||||
|
e.g. "my-sub" -> tags like "my-sub-Server-DE".
|
||||||
|
|
||||||
|
This value is also used as the subscription cache filename stem under
|
||||||
|
/var/lib/proxy-suite/subscriptions/<backend>/, so it must be a safe
|
||||||
|
identifier.
|
||||||
|
'';
|
||||||
|
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";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
outboundType = types.submodule {
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
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.
|
||||||
|
|
||||||
|
Set exactly one of urlFile, url, or json for each outbound.
|
||||||
|
'';
|
||||||
|
example = "/run/secrets/my-proxy-url";
|
||||||
|
};
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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";
|
||||||
|
};
|
||||||
|
|
||||||
|
backend = mkOption {
|
||||||
|
type = types.enum [
|
||||||
|
"auto"
|
||||||
|
"sing-box"
|
||||||
|
"xray"
|
||||||
|
];
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
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).
|
||||||
|
routing = routingFields;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
dnsUpstreamType = types.submodule {
|
||||||
|
options = {
|
||||||
|
type = mkOption {
|
||||||
|
type = types.enum [
|
||||||
|
"udp"
|
||||||
|
"tcp"
|
||||||
|
"tls"
|
||||||
|
];
|
||||||
|
default = "udp";
|
||||||
|
description = ''
|
||||||
|
DNS transport type for this upstream resolver.
|
||||||
|
'';
|
||||||
|
example = "tls";
|
||||||
|
};
|
||||||
|
|
||||||
|
address = mkOption {
|
||||||
|
type = types.strMatching ".+";
|
||||||
|
description = ''
|
||||||
|
Resolver address or hostname used for this DNS upstream.
|
||||||
|
'';
|
||||||
|
example = "1.1.1.1";
|
||||||
|
};
|
||||||
|
|
||||||
|
port = mkOption {
|
||||||
|
type = types.port;
|
||||||
|
default = 53;
|
||||||
|
description = ''
|
||||||
|
Destination port for this DNS upstream.
|
||||||
|
'';
|
||||||
|
example = 853;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
zapretPresetType = types.enum [
|
||||||
|
"general"
|
||||||
|
"google"
|
||||||
|
"instagram"
|
||||||
|
"soundcloud"
|
||||||
|
"twitter"
|
||||||
|
];
|
||||||
|
|
||||||
|
zapretHostlistRuleType = types.submodule {
|
||||||
|
options = {
|
||||||
|
name = mkOption {
|
||||||
|
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
|
||||||
|
description = ''
|
||||||
|
Custom hostlist name. Used to generate hostlists/list-<name>.txt
|
||||||
|
inside the derived zapret config directory.
|
||||||
|
'';
|
||||||
|
example = "cloudflare";
|
||||||
|
};
|
||||||
|
|
||||||
|
domains = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Domains written into the generated custom zapret hostlist file.
|
||||||
|
Must be non-empty for every hostlistRules entry.
|
||||||
|
'';
|
||||||
|
example = [
|
||||||
|
"example.com"
|
||||||
|
"example.de"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
preset = mkOption {
|
||||||
|
type = types.nullOr zapretPresetType;
|
||||||
|
default = null;
|
||||||
|
description = ''
|
||||||
|
Clone the active zapret config's built-in NFQWS rule family for this
|
||||||
|
hostlist. Can be combined with nfqwsArgs for additional custom rules.
|
||||||
|
'';
|
||||||
|
example = "google";
|
||||||
|
};
|
||||||
|
|
||||||
|
nfqwsArgs = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Additional NFQWS argument fragments for this hostlist.
|
||||||
|
The module injects --hostlist=... and trailing --new automatically.
|
||||||
|
|
||||||
|
Each hostlistRules entry must define preset, nfqwsArgs, or both.
|
||||||
|
'';
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
perAppRoutingProfileType = types.submodule {
|
||||||
|
options = {
|
||||||
|
name = mkOption {
|
||||||
|
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
|
||||||
|
description = ''
|
||||||
|
Profile name used by `proxy-ctl wrap <name> -- <command>`.
|
||||||
|
Must be unique within perAppRouting.profiles.
|
||||||
|
'';
|
||||||
|
example = "steam-browser";
|
||||||
|
};
|
||||||
|
|
||||||
|
route = mkOption {
|
||||||
|
type = types.enum [
|
||||||
|
"direct"
|
||||||
|
"proxychains"
|
||||||
|
"tun"
|
||||||
|
"tproxy"
|
||||||
|
"zapret"
|
||||||
|
];
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
example = "proxychains";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit
|
||||||
|
routingFields
|
||||||
|
routingRuleType
|
||||||
|
subscriptionType
|
||||||
|
outboundType
|
||||||
|
dnsUpstreamType
|
||||||
|
zapretPresetType
|
||||||
|
zapretHostlistRuleType
|
||||||
|
perAppRoutingProfileType
|
||||||
|
;
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
# zapret DPI bypass options.
|
||||||
|
{ lib, ... }:
|
||||||
|
|
||||||
|
let
|
||||||
|
inherit (lib) mkOption mkEnableOption types;
|
||||||
|
t = import ./types.nix { inherit lib; };
|
||||||
|
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 passed through to the generated zapret configuration.";
|
||||||
|
example = "general(ALT)";
|
||||||
|
};
|
||||||
|
|
||||||
|
gameFilter = mkOption {
|
||||||
|
type = types.str;
|
||||||
|
default = "null";
|
||||||
|
description = ''zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.'';
|
||||||
|
example = "null";
|
||||||
|
};
|
||||||
|
|
||||||
|
listGeneral = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Extra domains to include in zapret's interception list.
|
||||||
|
When syncDirectRouting = true, these domains are also mirrored into
|
||||||
|
proxy direct routing.
|
||||||
|
'';
|
||||||
|
example = [ "youtube.com" ];
|
||||||
|
};
|
||||||
|
|
||||||
|
listExclude = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Domains to exclude from zapret interception.
|
||||||
|
When syncDirectRouting = true, these exclusions also remove matching
|
||||||
|
domains from the zapret-derived proxy direct-routing set.
|
||||||
|
'';
|
||||||
|
example = [ "music.youtube.com" ];
|
||||||
|
};
|
||||||
|
|
||||||
|
ipsetAll = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Extra IPs/CIDRs to add to zapret's ipset.
|
||||||
|
Mirrored into proxy direct IP routing when
|
||||||
|
syncDirectRoutingUserIps = true.
|
||||||
|
'';
|
||||||
|
example = [ "203.0.113.0/24" ];
|
||||||
|
};
|
||||||
|
|
||||||
|
ipsetExclude = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
IPs/CIDRs to exclude from zapret's ipset.
|
||||||
|
Also excluded from zapret-derived proxy direct IP routing when
|
||||||
|
syncDirectRoutingUserIps = true.
|
||||||
|
'';
|
||||||
|
example = [ "203.0.113.10/32" ];
|
||||||
|
};
|
||||||
|
|
||||||
|
includeExtraUpstreamLists = mkOption {
|
||||||
|
type = types.bool;
|
||||||
|
default = false;
|
||||||
|
description = ''
|
||||||
|
Automatically activate upstream list-instagram.txt, list-soundcloud.txt,
|
||||||
|
and list-twitter.txt in the generated zapret config when the selected
|
||||||
|
upstream preset does not already reference them.
|
||||||
|
|
||||||
|
When syncDirectRouting = true, domains from these extra lists are also
|
||||||
|
mirrored into proxy direct routing.
|
||||||
|
'';
|
||||||
|
example = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
hostlistRules = mkOption {
|
||||||
|
type = types.listOf t.zapretHostlistRuleType;
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Additional named zapret hostlists with per-list DPI mitigation rules.
|
||||||
|
Each entry generates hostlists/list-<name>.txt and can clone a built-in
|
||||||
|
zapret family, add custom NFQWS rule fragments, or both.
|
||||||
|
|
||||||
|
Each entry must define at least one domain and at least one of preset
|
||||||
|
or nfqwsArgs.
|
||||||
|
'';
|
||||||
|
example = [
|
||||||
|
{
|
||||||
|
name = "googlevideo";
|
||||||
|
domains = [
|
||||||
|
"googlevideo.com"
|
||||||
|
"ggpht.com"
|
||||||
|
];
|
||||||
|
preset = "google";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
name = "example";
|
||||||
|
domains = [
|
||||||
|
"example.com"
|
||||||
|
"example.de"
|
||||||
|
];
|
||||||
|
preset = "general";
|
||||||
|
nfqwsArgs = [
|
||||||
|
"--filter-tcp=443 --dpi-desync=fake,multisplit"
|
||||||
|
];
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
cidrExemption = {
|
||||||
|
enable = mkEnableOption "CIDR exemption from zapret NFQUEUE";
|
||||||
|
|
||||||
|
cidrs = mkOption {
|
||||||
|
type = types.listOf types.str;
|
||||||
|
default = [ ];
|
||||||
|
example = [
|
||||||
|
"192.168.123.0/24"
|
||||||
|
"10.0.0.0/8"
|
||||||
|
];
|
||||||
|
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.
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
+224
-54
@@ -7,9 +7,11 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
r = cfg.singBox.routing;
|
derived = import ./derived.nix { inherit lib cfg; };
|
||||||
sb = cfg.singBox;
|
r = cfg.proxy.routing;
|
||||||
z = cfg.zapret;
|
proxyCfg = derived.proxyCfg;
|
||||||
|
zapretCfg = cfg.zapret;
|
||||||
|
tgWsProxyCfg = cfg.tgWsProxy;
|
||||||
|
|
||||||
trim = lib.strings.trim;
|
trim = lib.strings.trim;
|
||||||
hasPrefix = lib.strings.hasPrefix;
|
hasPrefix = lib.strings.hasPrefix;
|
||||||
@@ -27,16 +29,16 @@ let
|
|||||||
|
|
||||||
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
|
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
|
||||||
|
|
||||||
syncZapretDirectDomains = z.enable && z.syncDirectRouting;
|
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
|
||||||
syncZapretDirectUpstreamIps = z.enable && z.syncDirectRoutingUpstreamIps;
|
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
|
||||||
syncZapretDirectUserIps = z.enable && z.syncDirectRoutingUserIps;
|
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
|
||||||
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
|
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
|
||||||
|
|
||||||
zapretDefaultDomainFiles = [
|
zapretDefaultDomainFiles = [
|
||||||
"list-general.txt"
|
"list-general.txt"
|
||||||
"list-google.txt"
|
"list-google.txt"
|
||||||
]
|
]
|
||||||
++ lib.optionals z.includeExtraUpstreamLists [
|
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
|
||||||
"list-instagram.txt"
|
"list-instagram.txt"
|
||||||
"list-soundcloud.txt"
|
"list-soundcloud.txt"
|
||||||
"list-twitter.txt"
|
"list-twitter.txt"
|
||||||
@@ -51,10 +53,12 @@ let
|
|||||||
[ ];
|
[ ];
|
||||||
zapretDefaultIps =
|
zapretDefaultIps =
|
||||||
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
|
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
|
||||||
zapretUserIps = if syncZapretDirectUserIps then z.ipsetAll else [ ];
|
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
|
||||||
zapretCustomDomains =
|
zapretCustomDomains =
|
||||||
if syncZapretDirectDomains then
|
if syncZapretDirectDomains then
|
||||||
lib.unique (lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) z.hostlistRules)
|
lib.unique (
|
||||||
|
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) zapretCfg.hostlistRules
|
||||||
|
)
|
||||||
else
|
else
|
||||||
[ ];
|
[ ];
|
||||||
zapretExcludedDomains =
|
zapretExcludedDomains =
|
||||||
@@ -66,13 +70,13 @@ let
|
|||||||
else
|
else
|
||||||
[ ]
|
[ ]
|
||||||
)
|
)
|
||||||
++ (if syncZapretDirectUserIps then z.ipsetExclude else [ ])
|
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
|
||||||
);
|
);
|
||||||
|
|
||||||
zapretDirectDomains =
|
zapretDirectDomains =
|
||||||
if syncZapretDirectDomains then
|
if syncZapretDirectDomains then
|
||||||
subtractItems (lib.unique (zapretDefaultDomains ++ z.listGeneral ++ zapretCustomDomains)) (
|
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
|
||||||
lib.unique (zapretExcludedDomains ++ z.listExclude)
|
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
[ ];
|
[ ];
|
||||||
@@ -89,37 +93,39 @@ let
|
|||||||
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
|
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
|
||||||
};
|
};
|
||||||
|
|
||||||
mkDomainRule =
|
mkRule =
|
||||||
tag: domains:
|
field: tag: items:
|
||||||
lib.optional (domains != [ ]) {
|
lib.optional (items != [ ]) {
|
||||||
domain_suffix = domains;
|
${field} = items;
|
||||||
outbound = tag;
|
|
||||||
};
|
|
||||||
|
|
||||||
mkIPRule =
|
|
||||||
tag: ips:
|
|
||||||
lib.optional (ips != [ ]) {
|
|
||||||
ip_cidr = ips;
|
|
||||||
outbound = tag;
|
|
||||||
};
|
|
||||||
|
|
||||||
mkRulesetRule =
|
|
||||||
tag: tags:
|
|
||||||
lib.optional (tags != [ ]) {
|
|
||||||
rule_set = tags;
|
|
||||||
outbound = tag;
|
outbound = tag;
|
||||||
};
|
};
|
||||||
|
mkDomainRule = mkRule "domain_suffix";
|
||||||
|
mkIPRule = mkRule "ip_cidr";
|
||||||
|
mkRulesetRule = mkRule "rule_set";
|
||||||
|
customRuleCategory =
|
||||||
|
outbound:
|
||||||
|
if outbound == "direct" then
|
||||||
|
"direct"
|
||||||
|
else if outbound == "block" then
|
||||||
|
"block"
|
||||||
|
else
|
||||||
|
"proxy";
|
||||||
|
|
||||||
# In "first" mode the start script renames the first outbound to "proxy",
|
# In "first" mode the start script renames the first outbound to "proxy",
|
||||||
# so any per-outbound routing tag that isn't direct/block/proxy must map
|
# so any per-outbound routing tag that isn't direct/block/proxy must map
|
||||||
# to "proxy" instead of the original tag (which won't exist in sing-box).
|
# to "proxy" instead of the original tag (which won't exist in sing-box).
|
||||||
builtinTags = [
|
|
||||||
"proxy"
|
|
||||||
"direct"
|
|
||||||
"block"
|
|
||||||
];
|
|
||||||
resolveTag =
|
resolveTag =
|
||||||
tag: if sb.selection == "first" && !builtins.elem tag builtinTags then "proxy" else tag;
|
tag:
|
||||||
|
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then
|
||||||
|
"proxy"
|
||||||
|
else if
|
||||||
|
derived.pureXrayEnabled
|
||||||
|
&& derived.selectionMode == "urltest"
|
||||||
|
&& !builtins.elem tag derived.builtinTags
|
||||||
|
then
|
||||||
|
"proxy-suite-ob-${tag}"
|
||||||
|
else
|
||||||
|
tag;
|
||||||
|
|
||||||
# Collect per-outbound routing attached directly to outbound definitions.
|
# Collect per-outbound routing attached directly to outbound definitions.
|
||||||
perOutboundRules = lib.concatMap (
|
perOutboundRules = lib.concatMap (
|
||||||
@@ -137,7 +143,7 @@ let
|
|||||||
geoips
|
geoips
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
) sb.outbounds;
|
) proxyCfg.outbounds;
|
||||||
|
|
||||||
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
||||||
customRules =
|
customRules =
|
||||||
@@ -166,21 +172,17 @@ let
|
|||||||
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
|
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
|
||||||
);
|
);
|
||||||
|
|
||||||
geositeRuleSets = map (name: {
|
mkRuleSet = kind: pkg: name: {
|
||||||
tag = "geosite-${name}";
|
tag = "${kind}-${name}";
|
||||||
type = "local";
|
type = "local";
|
||||||
format = "binary";
|
format = "binary";
|
||||||
path = "${pkgs.sing-geosite}/share/sing-box/rule-set/geosite-${name}.srs";
|
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
|
||||||
}) allGeositeNames;
|
};
|
||||||
|
|
||||||
geoIPRuleSets = map (name: {
|
geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames;
|
||||||
tag = "geoip-${name}";
|
geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames;
|
||||||
type = "local";
|
|
||||||
format = "binary";
|
|
||||||
path = "${pkgs.sing-geoip}/share/sing-box/rule-set/geoip-${name}.srs";
|
|
||||||
}) allGeoIPNames;
|
|
||||||
|
|
||||||
routingRules = lib.flatten [
|
commonRules = [
|
||||||
{
|
{
|
||||||
network = [
|
network = [
|
||||||
"tcp"
|
"tcp"
|
||||||
@@ -190,42 +192,210 @@ let
|
|||||||
action = "hijack-dns";
|
action = "hijack-dns";
|
||||||
}
|
}
|
||||||
{ action = "sniff"; }
|
{ action = "sniff"; }
|
||||||
|
];
|
||||||
|
|
||||||
# Per-outbound and explicit rules come first – they take priority.
|
customRouteRules = map (rule: {
|
||||||
(lib.concatMap mkCustomRuleEntries customRules)
|
category = customRuleCategory rule.outbound;
|
||||||
|
entries = mkCustomRuleEntries rule;
|
||||||
|
}) customRules;
|
||||||
|
|
||||||
# Global proxy lists
|
proxyPrimaryRules = lib.flatten [
|
||||||
(mkDomainRule "proxy" r.proxy.domains)
|
(mkDomainRule "proxy" r.proxy.domains)
|
||||||
(mkIPRule "proxy" r.proxy.ips)
|
(mkIPRule "proxy" r.proxy.ips)
|
||||||
|
];
|
||||||
|
|
||||||
# Global direct lists
|
directRules = lib.flatten [
|
||||||
(mkDomainRule "direct" direct.domains)
|
(mkDomainRule "direct" direct.domains)
|
||||||
(mkIPRule "direct" direct.ips)
|
(mkIPRule "direct" direct.ips)
|
||||||
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
|
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
|
||||||
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
|
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
|
||||||
|
];
|
||||||
|
|
||||||
|
tgWsProxyRelayDirectRules =
|
||||||
|
lib.optional
|
||||||
|
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
|
||||||
|
{
|
||||||
|
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
|
||||||
|
outbound = "direct";
|
||||||
|
};
|
||||||
|
|
||||||
|
safetyDirectRules = [
|
||||||
{
|
{
|
||||||
ip_is_private = true;
|
ip_is_private = true;
|
||||||
outbound = "direct";
|
outbound = "direct";
|
||||||
}
|
}
|
||||||
|
]
|
||||||
|
++ tgWsProxyRelayDirectRules;
|
||||||
|
|
||||||
# Block (before proxy geosets so block can override them)
|
blockRules = lib.flatten [
|
||||||
(mkDomainRule "block" r.block.domains)
|
(mkDomainRule "block" r.block.domains)
|
||||||
(mkIPRule "block" r.block.ips)
|
(mkIPRule "block" r.block.ips)
|
||||||
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
|
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
|
||||||
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
|
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
|
||||||
|
];
|
||||||
|
|
||||||
# Global proxy geo lists
|
proxyGeoRules = lib.flatten [
|
||||||
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
|
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
|
||||||
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
|
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
|
||||||
];
|
];
|
||||||
|
|
||||||
|
singBoxRoutingRules =
|
||||||
|
commonRules
|
||||||
|
++ lib.concatMap (item: item.entries) customRouteRules
|
||||||
|
++ proxyPrimaryRules
|
||||||
|
++ directRules
|
||||||
|
++ safetyDirectRules
|
||||||
|
++ blockRules
|
||||||
|
++ proxyGeoRules;
|
||||||
|
|
||||||
|
singBoxRouteModeRules = {
|
||||||
|
common = commonRules;
|
||||||
|
custom = customRouteRules;
|
||||||
|
proxyPrimary = proxyPrimaryRules;
|
||||||
|
direct = directRules;
|
||||||
|
safetyDirect = safetyDirectRules;
|
||||||
|
block = blockRules;
|
||||||
|
proxyGeo = proxyGeoRules;
|
||||||
|
};
|
||||||
|
|
||||||
|
xrayTarget =
|
||||||
|
tag:
|
||||||
|
if tag == "proxy" && derived.selectionMode == "urltest" then
|
||||||
|
{ balancerTag = "proxy"; }
|
||||||
|
else
|
||||||
|
{ outboundTag = tag; };
|
||||||
|
|
||||||
|
mkXrayRule =
|
||||||
|
ruleTag: fields: tag:
|
||||||
|
(
|
||||||
|
{
|
||||||
|
type = "field";
|
||||||
|
inherit ruleTag;
|
||||||
|
}
|
||||||
|
// fields
|
||||||
|
// (xrayTarget tag)
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayDomainRules =
|
||||||
|
ruleTag: tag: domains:
|
||||||
|
lib.optional (domains != [ ]) (
|
||||||
|
mkXrayRule ruleTag {
|
||||||
|
domain = map (domain: "domain:${domain}") domains;
|
||||||
|
} tag
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayIPRules =
|
||||||
|
ruleTag: tag: ips:
|
||||||
|
lib.optional (ips != [ ]) (
|
||||||
|
mkXrayRule ruleTag {
|
||||||
|
ip = ips;
|
||||||
|
} tag
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayGeositeRules =
|
||||||
|
ruleTag: tag: geosites:
|
||||||
|
lib.optional (geosites != [ ]) (
|
||||||
|
mkXrayRule ruleTag {
|
||||||
|
domain = map (name: "geosite:${name}") geosites;
|
||||||
|
} tag
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayGeoIPRules =
|
||||||
|
ruleTag: tag: geoips:
|
||||||
|
lib.optional (geoips != [ ]) (
|
||||||
|
mkXrayRule ruleTag {
|
||||||
|
ip = map (name: "geoip:${name}") geoips;
|
||||||
|
} tag
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
|
||||||
|
|
||||||
|
mkXrayCustomRuleEntries =
|
||||||
|
rule:
|
||||||
|
lib.flatten [
|
||||||
|
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
|
||||||
|
rule.domains
|
||||||
|
)
|
||||||
|
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
|
||||||
|
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
|
||||||
|
rule.geosites
|
||||||
|
)
|
||||||
|
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
|
||||||
|
rule.geoips
|
||||||
|
)
|
||||||
|
];
|
||||||
|
|
||||||
|
xrayCustomRouteRules = map (rule: {
|
||||||
|
category = customRuleCategory rule.outbound;
|
||||||
|
entries = mkXrayCustomRuleEntries rule;
|
||||||
|
}) customRules;
|
||||||
|
|
||||||
|
xrayProxyPrimaryRules = lib.flatten [
|
||||||
|
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
|
||||||
|
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
|
||||||
|
];
|
||||||
|
|
||||||
|
xrayDirectRules = lib.flatten [
|
||||||
|
(xrayDomainRules "direct-domain" "direct" direct.domains)
|
||||||
|
(xrayIPRules "direct-ip" "direct" direct.ips)
|
||||||
|
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
|
||||||
|
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
|
||||||
|
];
|
||||||
|
|
||||||
|
xraySafetyDirectRules = [
|
||||||
|
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
|
||||||
|
]
|
||||||
|
++
|
||||||
|
lib.optional
|
||||||
|
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
|
||||||
|
(
|
||||||
|
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
|
||||||
|
);
|
||||||
|
|
||||||
|
xrayBlockRules = lib.flatten [
|
||||||
|
(xrayDomainRules "block-domain" "block" r.block.domains)
|
||||||
|
(xrayIPRules "block-ip" "block" r.block.ips)
|
||||||
|
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
|
||||||
|
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
|
||||||
|
];
|
||||||
|
|
||||||
|
xrayProxyGeoRules = lib.flatten [
|
||||||
|
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
|
||||||
|
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
|
||||||
|
];
|
||||||
|
|
||||||
|
xrayRoutingRules =
|
||||||
|
lib.concatMap (item: item.entries) xrayCustomRouteRules
|
||||||
|
++ xrayProxyPrimaryRules
|
||||||
|
++ xrayDirectRules
|
||||||
|
++ xraySafetyDirectRules
|
||||||
|
++ xrayProxyGeoRules
|
||||||
|
++ xrayBlockRules;
|
||||||
|
|
||||||
|
xrayRouteModeRules = {
|
||||||
|
common = [ ];
|
||||||
|
custom = xrayCustomRouteRules;
|
||||||
|
proxyPrimary = xrayProxyPrimaryRules;
|
||||||
|
direct = xrayDirectRules;
|
||||||
|
safetyDirect = xraySafetyDirectRules;
|
||||||
|
block = xrayBlockRules;
|
||||||
|
proxyGeo = xrayProxyGeoRules;
|
||||||
|
};
|
||||||
|
|
||||||
|
routingRules = singBoxRoutingRules;
|
||||||
|
routeModeRules = singBoxRouteModeRules;
|
||||||
|
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
inherit
|
inherit
|
||||||
direct
|
direct
|
||||||
geositeRuleSets
|
geositeRuleSets
|
||||||
geoIPRuleSets
|
geoIPRuleSets
|
||||||
|
singBoxRoutingRules
|
||||||
|
singBoxRouteModeRules
|
||||||
|
xrayRoutingRules
|
||||||
|
xrayRouteModeRules
|
||||||
|
routeModeRules
|
||||||
routingRules
|
routingRules
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,452 @@
|
|||||||
|
{
|
||||||
|
lib,
|
||||||
|
cfg,
|
||||||
|
derived,
|
||||||
|
tgWsProxyCfg,
|
||||||
|
builtinTags,
|
||||||
|
outboundTags,
|
||||||
|
subscriptionTags,
|
||||||
|
invalidRoutingTargets,
|
||||||
|
effectivePerAppRoutingProfileNames,
|
||||||
|
hasProxychainsProfiles,
|
||||||
|
hasTunProfiles,
|
||||||
|
hasTproxyProfiles,
|
||||||
|
hasZapretProfiles,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
assertions = import ./service/assertions-lib.nix { inherit lib; };
|
||||||
|
inherit (assertions)
|
||||||
|
mkAssertion
|
||||||
|
requireEnabled
|
||||||
|
requireAvailable
|
||||||
|
uniqueValues
|
||||||
|
notEqualWhen
|
||||||
|
forbiddenValues
|
||||||
|
exactlyOneOf
|
||||||
|
;
|
||||||
|
|
||||||
|
inherit (derived)
|
||||||
|
proxyCfg
|
||||||
|
singBoxCfg
|
||||||
|
proxyEnabled
|
||||||
|
singBoxEnabled
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
perAppRoutingCfg
|
||||||
|
globalTun
|
||||||
|
globalTproxy
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
perAppZapretCfg
|
||||||
|
;
|
||||||
|
|
||||||
|
globalTunAutoRouteTable = 2022;
|
||||||
|
|
||||||
|
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 (
|
||||||
|
proxyCfg.outbounds != [ ] || proxyCfg.subscriptions != [ ]
|
||||||
|
) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true")
|
||||||
|
(uniqueValues proxyEnabled outboundTags "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"
|
||||||
|
)
|
||||||
|
(mkAssertion (
|
||||||
|
!proxyEnabled || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags
|
||||||
|
) "proxy-suite: outbound tags must not use reserved names: proxy, direct, block")
|
||||||
|
(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")
|
||||||
|
(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"
|
||||||
|
)
|
||||||
|
(requireEnabled globalTun.enable proxyEnabled
|
||||||
|
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
|
||||||
|
)
|
||||||
|
(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 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"
|
||||||
|
)
|
||||||
|
];
|
||||||
|
|
||||||
|
perAppRoutingAssertions = [
|
||||||
|
(requireAvailable (perAppRoutingCfg.profiles != [ ]) perAppRoutingCfg.enable
|
||||||
|
"proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true"
|
||||||
|
)
|
||||||
|
(requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable
|
||||||
|
"proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true"
|
||||||
|
)
|
||||||
|
(requireEnabled perAppRoutingCfg.proxychains.enable proxyEnabled
|
||||||
|
"proxy-suite: perAppRouting.proxychains.enable requires proxy.enable = true"
|
||||||
|
)
|
||||||
|
(uniqueValues true effectivePerAppRoutingProfileNames
|
||||||
|
"proxy-suite: perAppRouting profile names must be unique"
|
||||||
|
)
|
||||||
|
(requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable
|
||||||
|
"proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true"
|
||||||
|
)
|
||||||
|
(requireAvailable hasProxychainsProfiles proxyEnabled
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
(requireEnabled perAppRoutingTun.enable proxyEnabled
|
||||||
|
"proxy-suite: proxy.tun.perApp.enable requires proxy.enable = true"
|
||||||
|
)
|
||||||
|
(requireAvailable hasTunProfiles perAppRoutingTun.enable
|
||||||
|
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.tun.perApp.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"
|
||||||
|
)
|
||||||
|
(requireEnabled perAppRoutingTproxy.enable proxyEnabled
|
||||||
|
"proxy-suite: proxy.tproxy.perApp.enable requires proxy.enable = true"
|
||||||
|
)
|
||||||
|
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
|
||||||
|
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.tproxy.perApp.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"
|
||||||
|
)
|
||||||
|
(requireAvailable hasZapretProfiles perAppZapretCfg.enable
|
||||||
|
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true"
|
||||||
|
)
|
||||||
|
];
|
||||||
|
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = globalTun.enable && perAppRoutingTun.enable;
|
||||||
|
left = globalTun.address;
|
||||||
|
right = perAppRoutingTun.address;
|
||||||
|
message = "proxy-suite: proxy.tun.address and proxy.tun.perApp.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 2022";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTproxy.enable;
|
||||||
|
left = perAppRoutingTproxy.fwmark;
|
||||||
|
right = globalTproxy.fwmark;
|
||||||
|
message = "proxy-suite: proxy.tproxy.perApp.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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTproxy.enable;
|
||||||
|
left = perAppRoutingTproxy.routeTable;
|
||||||
|
right = globalTproxy.routeTable;
|
||||||
|
message = "proxy-suite: proxy.tproxy.perApp.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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
left = perAppZapretCfg.filterMark;
|
||||||
|
right = globalTproxy.fwmark;
|
||||||
|
message = "proxy-suite: zapret.perApp.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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||||
|
left = perAppRoutingTun.fwmark;
|
||||||
|
right = perAppZapretCfg.filterMark;
|
||||||
|
message = "proxy-suite: proxy.tun.perApp.fwmark and zapret.perApp.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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
|
||||||
|
left = tgWsProxyCfg.routingMark;
|
||||||
|
right = globalTproxy.fwmark;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.fwmark";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
|
||||||
|
left = tgWsProxyCfg.routingMark;
|
||||||
|
right = globalTproxy.proxyMark;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.proxyMark";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
|
||||||
|
left = tgWsProxyCfg.routingMark;
|
||||||
|
right = perAppRoutingTun.fwmark;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition =
|
||||||
|
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
|
||||||
|
left = tgWsProxyCfg.routingMark;
|
||||||
|
right = perAppRoutingTproxy.fwmark;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
|
||||||
|
left = tgWsProxyCfg.routingMark;
|
||||||
|
right = perAppZapretCfg.filterMark;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must differ from zapret.perApp.filterMark";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
perAppZapretDesyncMarks = [
|
||||||
|
67108864
|
||||||
|
134217728
|
||||||
|
];
|
||||||
|
|
||||||
|
positiveNumberAssertions =
|
||||||
|
map (item: mkAssertion (!item.condition || item.value > 0) item.message)
|
||||||
|
[
|
||||||
|
{
|
||||||
|
condition = globalTun.enable;
|
||||||
|
value = globalTun.mtu;
|
||||||
|
message = "proxy-suite: proxy.tun.mtu must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTun.enable;
|
||||||
|
value = perAppRoutingTun.mtu;
|
||||||
|
message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = globalTproxy.enable;
|
||||||
|
value = globalTproxy.fwmark;
|
||||||
|
message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = globalTproxy.enable;
|
||||||
|
value = globalTproxy.proxyMark;
|
||||||
|
message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = globalTproxy.enable;
|
||||||
|
value = globalTproxy.routeTable;
|
||||||
|
message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTun.enable;
|
||||||
|
value = perAppRoutingTun.fwmark;
|
||||||
|
message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTun.enable;
|
||||||
|
value = perAppRoutingTun.routeTable;
|
||||||
|
message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTproxy.enable;
|
||||||
|
value = perAppRoutingTproxy.fwmark;
|
||||||
|
message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppRoutingTproxy.enable;
|
||||||
|
value = perAppRoutingTproxy.routeTable;
|
||||||
|
message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
value = perAppZapretCfg.filterMark;
|
||||||
|
message = "proxy-suite: zapret.perApp.filterMark must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
value = perAppZapretCfg.qnum;
|
||||||
|
message = "proxy-suite: zapret.perApp.qnum must be greater than zero";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
|
||||||
|
value = tgWsProxyCfg.routingMark;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must be greater than zero";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
localProxyAuthCfg = proxyCfg.auth;
|
||||||
|
localProxyAuthUsed =
|
||||||
|
localProxyAuthCfg.username != null
|
||||||
|
|| localProxyAuthCfg.password != null
|
||||||
|
|| localProxyAuthCfg.passwordFile != null;
|
||||||
|
localProxyAuthAssertions = [
|
||||||
|
(mkAssertion (
|
||||||
|
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
|
||||||
|
) "proxy-suite: proxy.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")
|
||||||
|
];
|
||||||
|
|
||||||
|
forbiddenValueAssertions =
|
||||||
|
map (item: forbiddenValues item.condition item.value item.disallowed item.message)
|
||||||
|
[
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
value = perAppZapretCfg.filterMark;
|
||||||
|
disallowed = [
|
||||||
|
536870912
|
||||||
|
1073741824
|
||||||
|
];
|
||||||
|
message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
value = globalTproxy.fwmark;
|
||||||
|
disallowed = perAppZapretDesyncMarks;
|
||||||
|
message = "proxy-suite: proxy.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
value = globalTproxy.proxyMark;
|
||||||
|
disallowed = perAppZapretDesyncMarks;
|
||||||
|
message = "proxy-suite: proxy.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = perAppZapretCfg.enable;
|
||||||
|
value = perAppZapretCfg.filterMark;
|
||||||
|
disallowed = perAppZapretDesyncMarks;
|
||||||
|
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
|
||||||
|
value = tgWsProxyCfg.routingMark;
|
||||||
|
disallowed = perAppZapretDesyncMarks;
|
||||||
|
message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
secretAssertions = [
|
||||||
|
(exactlyOneOf tgWsProxyCfg.enable [
|
||||||
|
tgWsProxyCfg.secret
|
||||||
|
tgWsProxyCfg.secretFile
|
||||||
|
] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
|
||||||
|
];
|
||||||
|
|
||||||
|
outboundAssertions = lib.concatMap (ob: [
|
||||||
|
(exactlyOneOf proxyEnabled
|
||||||
|
[
|
||||||
|
ob.urlFile
|
||||||
|
ob.url
|
||||||
|
ob.singBoxJson
|
||||||
|
ob.xrayJson
|
||||||
|
ob.json
|
||||||
|
]
|
||||||
|
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
|
||||||
|
)
|
||||||
|
(mkAssertion (
|
||||||
|
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
|
||||||
|
) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true")
|
||||||
|
(mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null))
|
||||||
|
"proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true"
|
||||||
|
)
|
||||||
|
(mkAssertion (
|
||||||
|
!(ob.backend == "xray") || xrayEnabled
|
||||||
|
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true")
|
||||||
|
(mkAssertion (
|
||||||
|
!(ob.backend == "sing-box") || singBoxEnabled
|
||||||
|
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
|
||||||
|
]) proxyCfg.outbounds;
|
||||||
|
|
||||||
|
subscriptionAssertions = lib.concatMap (sub: [
|
||||||
|
(exactlyOneOf proxyEnabled [
|
||||||
|
sub.urlFile
|
||||||
|
sub.url
|
||||||
|
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
|
||||||
|
]) proxyCfg.subscriptions;
|
||||||
|
in
|
||||||
|
featureAssertions
|
||||||
|
++ perAppRoutingAssertions
|
||||||
|
++ collisionAssertions
|
||||||
|
++ positiveNumberAssertions
|
||||||
|
++ localProxyAuthAssertions
|
||||||
|
++ forbiddenValueAssertions
|
||||||
|
++ secretAssertions
|
||||||
|
++ outboundAssertions
|
||||||
|
++ subscriptionAssertions
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,31 @@
|
|||||||
|
{ lib }:
|
||||||
|
|
||||||
|
rec {
|
||||||
|
mkAssertion = assertion: message: { inherit assertion message; };
|
||||||
|
|
||||||
|
requireEnabled =
|
||||||
|
featureEnabled: dependencyEnabled: message:
|
||||||
|
mkAssertion (!featureEnabled || dependencyEnabled) message;
|
||||||
|
|
||||||
|
requireAvailable =
|
||||||
|
featureUsed: dependencyEnabled: message:
|
||||||
|
mkAssertion (!featureUsed || dependencyEnabled) message;
|
||||||
|
|
||||||
|
uniqueValues =
|
||||||
|
condition: values: message:
|
||||||
|
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
|
||||||
|
|
||||||
|
notEqualWhen =
|
||||||
|
condition: left: right: message:
|
||||||
|
mkAssertion (!(condition && left == right)) message;
|
||||||
|
|
||||||
|
forbiddenValues =
|
||||||
|
condition: value: disallowed: message:
|
||||||
|
mkAssertion (!(condition && builtins.elem value disallowed)) message;
|
||||||
|
|
||||||
|
exactlyOneOf =
|
||||||
|
condition: values: message:
|
||||||
|
mkAssertion (
|
||||||
|
!condition || builtins.length (builtins.filter (value: value != null) values) == 1
|
||||||
|
) message;
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
mkOptionalTopLevel =
|
||||||
|
{
|
||||||
|
description,
|
||||||
|
after ? [ ],
|
||||||
|
wantedBy ? [ ],
|
||||||
|
wants ? [ ],
|
||||||
|
requires ? [ ],
|
||||||
|
conflicts ? [ ],
|
||||||
|
preStart ? null,
|
||||||
|
}:
|
||||||
|
{
|
||||||
|
inherit
|
||||||
|
description
|
||||||
|
after
|
||||||
|
wantedBy
|
||||||
|
wants
|
||||||
|
requires
|
||||||
|
conflicts
|
||||||
|
;
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs (preStart != null) { inherit preStart; };
|
||||||
|
in
|
||||||
|
rec {
|
||||||
|
mkNamedUnits =
|
||||||
|
entries:
|
||||||
|
lib.listToAttrs (
|
||||||
|
map (entry: lib.nameValuePair entry.name entry.value) (
|
||||||
|
builtins.filter (entry: entry.enable) entries
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
mkRestartingService =
|
||||||
|
{
|
||||||
|
description,
|
||||||
|
execStart,
|
||||||
|
runtimeDirectory,
|
||||||
|
stateDirectory ? null,
|
||||||
|
after ? [ ],
|
||||||
|
wantedBy ? [ ],
|
||||||
|
wants ? [ ],
|
||||||
|
requires ? [ ],
|
||||||
|
conflicts ? [ ],
|
||||||
|
execStartPre ? null,
|
||||||
|
execStartPost ? null,
|
||||||
|
execStopPost ? null,
|
||||||
|
extraServiceConfig ? { },
|
||||||
|
preStart ? null,
|
||||||
|
}:
|
||||||
|
(mkOptionalTopLevel {
|
||||||
|
inherit
|
||||||
|
description
|
||||||
|
after
|
||||||
|
wantedBy
|
||||||
|
wants
|
||||||
|
requires
|
||||||
|
conflicts
|
||||||
|
preStart
|
||||||
|
;
|
||||||
|
})
|
||||||
|
// {
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = execStart;
|
||||||
|
Restart = "on-failure";
|
||||||
|
RestartSec = 5;
|
||||||
|
RuntimeDirectory = runtimeDirectory;
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
|
||||||
|
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
|
||||||
|
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
|
||||||
|
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
|
||||||
|
// extraServiceConfig;
|
||||||
|
};
|
||||||
|
|
||||||
|
mkOneshotService =
|
||||||
|
{
|
||||||
|
description,
|
||||||
|
execStart,
|
||||||
|
execStop ? null,
|
||||||
|
execStartPre ? null,
|
||||||
|
execStartPost ? null,
|
||||||
|
execStopPost ? null,
|
||||||
|
runtimeDirectory ? null,
|
||||||
|
stateDirectory ? null,
|
||||||
|
after ? [ ],
|
||||||
|
wantedBy ? [ ],
|
||||||
|
wants ? [ ],
|
||||||
|
requires ? [ ],
|
||||||
|
conflicts ? [ ],
|
||||||
|
extraServiceConfig ? { },
|
||||||
|
preStart ? null,
|
||||||
|
}:
|
||||||
|
(mkOptionalTopLevel {
|
||||||
|
inherit
|
||||||
|
description
|
||||||
|
after
|
||||||
|
wantedBy
|
||||||
|
wants
|
||||||
|
requires
|
||||||
|
conflicts
|
||||||
|
preStart
|
||||||
|
;
|
||||||
|
})
|
||||||
|
// {
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
ExecStart = execStart;
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs (execStop != null) { ExecStop = execStop; }
|
||||||
|
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
|
||||||
|
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
|
||||||
|
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
|
||||||
|
// lib.optionalAttrs (runtimeDirectory != null) { RuntimeDirectory = runtimeDirectory; }
|
||||||
|
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
|
||||||
|
// extraServiceConfig;
|
||||||
|
};
|
||||||
|
|
||||||
|
mkUserRuleService =
|
||||||
|
{
|
||||||
|
description,
|
||||||
|
backendService,
|
||||||
|
execStart,
|
||||||
|
execStop,
|
||||||
|
}:
|
||||||
|
mkOneshotService {
|
||||||
|
inherit description execStart execStop;
|
||||||
|
requires = [ "${backendService}.service" ];
|
||||||
|
after = [ "${backendService}.service" ];
|
||||||
|
};
|
||||||
|
|
||||||
|
mkAnchorService =
|
||||||
|
sliceName: description:
|
||||||
|
mkOneshotService {
|
||||||
|
inherit description;
|
||||||
|
execStart = "${pkgs.coreutils}/bin/true";
|
||||||
|
execStop = "${pkgs.coreutils}/bin/true";
|
||||||
|
extraServiceConfig.Slice = sliceName;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
# Shared service-layer assembly used by runtime module and docs generation.
|
||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
packages,
|
||||||
|
cfg,
|
||||||
|
tproxyFile,
|
||||||
|
tunFile,
|
||||||
|
perAppTunFile,
|
||||||
|
routeModeRulesFile,
|
||||||
|
perAppTunChainFile,
|
||||||
|
perAppTproxyRulesFile,
|
||||||
|
perAppZapretRulesFile,
|
||||||
|
ip,
|
||||||
|
nft,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
derived = import ../derived.nix { inherit lib cfg; };
|
||||||
|
inherit (derived)
|
||||||
|
singBoxCfg
|
||||||
|
proxyCfg
|
||||||
|
xrayCfg
|
||||||
|
proxyEnabled
|
||||||
|
singBoxEnabled
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
activeBackend
|
||||||
|
perAppRoutingCfg
|
||||||
|
globalTun
|
||||||
|
globalTproxy
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
perAppZapretCfg
|
||||||
|
userControlCfg
|
||||||
|
selectionMode
|
||||||
|
builtinTags
|
||||||
|
outboundTags
|
||||||
|
subscriptionTags
|
||||||
|
invalidRoutingTargets
|
||||||
|
collapseNamedOutbounds
|
||||||
|
hasSubscriptions
|
||||||
|
;
|
||||||
|
|
||||||
|
# Tool paths – defined once here and passed into sub-modules as needed.
|
||||||
|
jq = "${pkgs.jq}/bin/jq";
|
||||||
|
python3 = "${pkgs.python3}/bin/python3";
|
||||||
|
singBox = "${singBoxCfg.package}/bin/sing-box";
|
||||||
|
xray = "${xrayCfg.package}/bin/xray";
|
||||||
|
grepBin = "${pkgs.gnugrep}/bin/grep";
|
||||||
|
awk = "${pkgs.gawk}/bin/awk";
|
||||||
|
sleepBin = "${pkgs.coreutils}/bin/sleep";
|
||||||
|
headBin = "${pkgs.coreutils}/bin/head";
|
||||||
|
seqBin = "${pkgs.coreutils}/bin/seq";
|
||||||
|
findBin = "${pkgs.findutils}/bin/find";
|
||||||
|
|
||||||
|
proxySuiteScriptsDir = ../../../scripts;
|
||||||
|
parserScriptsPythonPath = proxySuiteScriptsDir;
|
||||||
|
buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py";
|
||||||
|
fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py";
|
||||||
|
|
||||||
|
polkit = import ./polkit.nix {
|
||||||
|
inherit lib cfg userControlCfg;
|
||||||
|
};
|
||||||
|
|
||||||
|
scripts = import ./scripts.nix {
|
||||||
|
inherit
|
||||||
|
lib
|
||||||
|
pkgs
|
||||||
|
singBoxCfg
|
||||||
|
proxyCfg
|
||||||
|
proxyEnabled
|
||||||
|
singBoxEnabled
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
activeBackend
|
||||||
|
perAppRoutingCfg
|
||||||
|
userControlCfg
|
||||||
|
perAppRoutingTun
|
||||||
|
selectionMode
|
||||||
|
collapseNamedOutbounds
|
||||||
|
hasSubscriptions
|
||||||
|
;
|
||||||
|
inherit
|
||||||
|
jq
|
||||||
|
python3
|
||||||
|
singBox
|
||||||
|
xray
|
||||||
|
parserScriptsPythonPath
|
||||||
|
buildOutboundPy
|
||||||
|
fetchSubscriptionPy
|
||||||
|
;
|
||||||
|
inherit
|
||||||
|
tproxyFile
|
||||||
|
tunFile
|
||||||
|
perAppTunFile
|
||||||
|
routeModeRulesFile
|
||||||
|
;
|
||||||
|
};
|
||||||
|
|
||||||
|
perAppRouting = import ./per-app-routing.nix {
|
||||||
|
inherit
|
||||||
|
lib
|
||||||
|
pkgs
|
||||||
|
cfg
|
||||||
|
singBoxCfg
|
||||||
|
proxyCfg
|
||||||
|
pureXrayEnabled
|
||||||
|
perAppRoutingCfg
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
;
|
||||||
|
perAppZapretCfg = perAppZapretCfg;
|
||||||
|
inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile;
|
||||||
|
inherit ip nft;
|
||||||
|
inherit
|
||||||
|
awk
|
||||||
|
grepBin
|
||||||
|
findBin
|
||||||
|
headBin
|
||||||
|
seqBin
|
||||||
|
sleepBin
|
||||||
|
;
|
||||||
|
};
|
||||||
|
|
||||||
|
control = import ./control.nix {
|
||||||
|
inherit
|
||||||
|
packages
|
||||||
|
singBoxCfg
|
||||||
|
proxyCfg
|
||||||
|
perAppRoutingCfg
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
perAppZapretCfg
|
||||||
|
selectionMode
|
||||||
|
;
|
||||||
|
inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
|
||||||
|
inherit (scripts) routeModeStateFile;
|
||||||
|
inherit (perAppRouting)
|
||||||
|
perAppRoutingProfilesFile
|
||||||
|
proxychainsConfigFile
|
||||||
|
proxychainsQuietArg
|
||||||
|
;
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit
|
||||||
|
derived
|
||||||
|
singBoxCfg
|
||||||
|
proxyCfg
|
||||||
|
xrayCfg
|
||||||
|
proxyEnabled
|
||||||
|
singBoxEnabled
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
activeBackend
|
||||||
|
perAppRoutingCfg
|
||||||
|
globalTun
|
||||||
|
globalTproxy
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
perAppZapretCfg
|
||||||
|
userControlCfg
|
||||||
|
builtinTags
|
||||||
|
outboundTags
|
||||||
|
subscriptionTags
|
||||||
|
invalidRoutingTargets
|
||||||
|
polkit
|
||||||
|
scripts
|
||||||
|
perAppRouting
|
||||||
|
control
|
||||||
|
;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Builds proxy-ctl from global proxy-suite state and per-app routing metadata.
|
||||||
|
{
|
||||||
|
packages,
|
||||||
|
singBoxCfg,
|
||||||
|
proxyCfg,
|
||||||
|
perAppRoutingCfg,
|
||||||
|
perAppRoutingTun,
|
||||||
|
perAppRoutingTproxy,
|
||||||
|
perAppZapretCfg,
|
||||||
|
selectionMode,
|
||||||
|
subscriptionTagsFile,
|
||||||
|
subscriptionCacheDir,
|
||||||
|
perAppRoutingProfilesFile,
|
||||||
|
proxychainsConfigFile,
|
||||||
|
proxychainsQuietArg,
|
||||||
|
routeModeStateFile,
|
||||||
|
}:
|
||||||
|
{
|
||||||
|
proxyCtl = packages.mkProxyCtl {
|
||||||
|
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||||
|
selection = selectionMode;
|
||||||
|
inherit
|
||||||
|
subscriptionTagsFile
|
||||||
|
subscriptionCacheDir
|
||||||
|
perAppRoutingProfilesFile
|
||||||
|
proxychainsConfigFile
|
||||||
|
proxychainsQuietArg
|
||||||
|
routeModeStateFile
|
||||||
|
;
|
||||||
|
defaultRouteMode = if proxyCfg.proxyByDefault 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";
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
# Assembles proxy-suite systemd services from the sub-modules.
|
||||||
|
{
|
||||||
|
config,
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
packages,
|
||||||
|
cfg,
|
||||||
|
tproxyFile,
|
||||||
|
tunFile,
|
||||||
|
perAppTunFile,
|
||||||
|
routeModeRulesFile,
|
||||||
|
nftablesRulesFile,
|
||||||
|
perAppTproxyRulesFile,
|
||||||
|
perAppZapretRulesFile,
|
||||||
|
perAppTunChainFile,
|
||||||
|
ip,
|
||||||
|
nft,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
context = import ./context.nix {
|
||||||
|
inherit
|
||||||
|
lib
|
||||||
|
pkgs
|
||||||
|
packages
|
||||||
|
cfg
|
||||||
|
tproxyFile
|
||||||
|
tunFile
|
||||||
|
perAppTunFile
|
||||||
|
routeModeRulesFile
|
||||||
|
perAppTunChainFile
|
||||||
|
perAppTproxyRulesFile
|
||||||
|
perAppZapretRulesFile
|
||||||
|
ip
|
||||||
|
nft
|
||||||
|
;
|
||||||
|
};
|
||||||
|
|
||||||
|
builders = import ./builders.nix { inherit lib pkgs; };
|
||||||
|
inherit (builders)
|
||||||
|
mkNamedUnits
|
||||||
|
mkRestartingService
|
||||||
|
mkOneshotService
|
||||||
|
mkUserRuleService
|
||||||
|
mkAnchorService
|
||||||
|
;
|
||||||
|
|
||||||
|
inherit (context)
|
||||||
|
derived
|
||||||
|
polkit
|
||||||
|
scripts
|
||||||
|
perAppRouting
|
||||||
|
control
|
||||||
|
;
|
||||||
|
|
||||||
|
inherit (derived)
|
||||||
|
singBoxCfg
|
||||||
|
proxyCfg
|
||||||
|
proxyEnabled
|
||||||
|
xrayEnabled
|
||||||
|
hybridEnabled
|
||||||
|
pureXrayEnabled
|
||||||
|
activeBackend
|
||||||
|
perAppRoutingCfg
|
||||||
|
globalTun
|
||||||
|
globalTproxy
|
||||||
|
perAppRoutingTun
|
||||||
|
perAppRoutingTproxy
|
||||||
|
perAppZapretCfg
|
||||||
|
userControlCfg
|
||||||
|
userControlEnabled
|
||||||
|
perAppZapretEnabled
|
||||||
|
hasSubscriptions
|
||||||
|
outboundTags
|
||||||
|
subscriptionTags
|
||||||
|
invalidRoutingTargets
|
||||||
|
builtinTags
|
||||||
|
;
|
||||||
|
|
||||||
|
serviceNames = {
|
||||||
|
socks = "proxy-suite-socks";
|
||||||
|
tproxy = "proxy-suite-tproxy";
|
||||||
|
tun = "proxy-suite-tun";
|
||||||
|
perAppTun = "proxy-suite-per-app-tun";
|
||||||
|
perAppTproxy = "proxy-suite-per-app-tproxy";
|
||||||
|
perAppZapret = "proxy-suite-per-app-zapret";
|
||||||
|
subscriptionUpdate = "proxy-suite-subscription-update";
|
||||||
|
};
|
||||||
|
|
||||||
|
localProxyAuthEnabled =
|
||||||
|
proxyCfg.auth.username != null
|
||||||
|
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
|
||||||
|
|
||||||
|
# Must match the explicit iproute2_* indexes written to the global SingBox TUN
|
||||||
|
# template in config.nix. XRay uses the same table for manual Linux
|
||||||
|
# policy routing because XRay's autoSystemRoutingTable is not Linux-ready.
|
||||||
|
tunAutoRouteTableIndex = 2022;
|
||||||
|
tunAutoRouteRulePriority = 9000;
|
||||||
|
# Keep app-scoped marks ahead of the global XRay TUN catch-all. Without
|
||||||
|
# these priorities, iproute2's default priority lets global TUN capture
|
||||||
|
# packets intended for per-app routing tables.
|
||||||
|
xrayTunPerAppTproxyRulePriority = 8996;
|
||||||
|
xrayTunPerAppTunRulePriority = 8997;
|
||||||
|
xrayGlobalTunIPv6Address = "fd66:19::1/64";
|
||||||
|
xrayGlobalTunIPv6RoutePrefix = "fd66:19::/64";
|
||||||
|
|
||||||
|
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
tun_cidr=${lib.escapeShellArg globalTun.address}
|
||||||
|
tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address}
|
||||||
|
tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix}
|
||||||
|
tun_addr=""
|
||||||
|
tun_route_prefix=""
|
||||||
|
uplink_addr=""
|
||||||
|
|
||||||
|
cidr_network() {
|
||||||
|
local cidr="$1"
|
||||||
|
local addr="''${cidr%/*}"
|
||||||
|
local prefix="''${cidr#*/}"
|
||||||
|
local o1 o2 o3 o4 ip mask net
|
||||||
|
|
||||||
|
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
|
||||||
|
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
|
||||||
|
if [ "$prefix" -eq 0 ]; then
|
||||||
|
mask=0
|
||||||
|
else
|
||||||
|
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
|
||||||
|
fi
|
||||||
|
net=$((ip & mask))
|
||||||
|
|
||||||
|
printf '%d.%d.%d.%d/%s' \
|
||||||
|
$(((net >> 24) & 255)) \
|
||||||
|
$(((net >> 16) & 255)) \
|
||||||
|
$(((net >> 8) & 255)) \
|
||||||
|
$((net & 255)) \
|
||||||
|
"$prefix"
|
||||||
|
}
|
||||||
|
|
||||||
|
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
|
||||||
|
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
${pkgs.coreutils}/bin/sleep 0.1
|
||||||
|
done
|
||||||
|
|
||||||
|
if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
|
||||||
|
echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${pkgs.gawk}/bin/awk '
|
||||||
|
/src/ {
|
||||||
|
for (i = 1; i <= NF; i++) {
|
||||||
|
if ($i == "src" && i + 1 <= NF) {
|
||||||
|
print $(i + 1)
|
||||||
|
exit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
')"
|
||||||
|
if [ -z "$uplink_addr" ]; then
|
||||||
|
echo "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
|
||||||
|
|
||||||
|
tun_addr="''${tun_cidr%%/*}"
|
||||||
|
tun_route_prefix="$(cidr_network "$tun_cidr")"
|
||||||
|
|
||||||
|
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
|
||||||
|
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}
|
||||||
|
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
|
||||||
|
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex}
|
||||||
|
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||||
|
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||||
|
${lib.optionalString perAppRoutingTproxy.enable ''
|
||||||
|
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
|
||||||
|
''}
|
||||||
|
${lib.optionalString perAppRoutingTun.enable ''
|
||||||
|
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||||
|
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||||
|
''}
|
||||||
|
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||||
|
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||||
|
'';
|
||||||
|
|
||||||
|
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Start from a clean policy-routing state. `ip rule add` permits duplicate
|
||||||
|
# rules on some iproute2 versions, and a stale rule can keep packets routed
|
||||||
|
# into a dead local table after a failed restart.
|
||||||
|
${nft} delete table ip singbox 2>/dev/null || true
|
||||||
|
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
|
||||||
|
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||||
|
|
||||||
|
${nft} -f ${nftablesRulesFile}
|
||||||
|
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
|
||||||
|
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
|
||||||
|
'';
|
||||||
|
|
||||||
|
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
|
||||||
|
set +e
|
||||||
|
|
||||||
|
${nft} delete table ip singbox 2>/dev/null || true
|
||||||
|
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
|
||||||
|
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
|
||||||
|
set +e
|
||||||
|
|
||||||
|
# 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.
|
||||||
|
${nft} delete table inet sing-box 2>/dev/null || true
|
||||||
|
|
||||||
|
while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||||
|
${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
|
||||||
|
${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
|
||||||
|
|
||||||
|
${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true
|
||||||
|
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
systemServiceEntries = [
|
||||||
|
{
|
||||||
|
enable = proxyEnabled;
|
||||||
|
name = serviceNames.socks;
|
||||||
|
value = mkRestartingService {
|
||||||
|
description = "${
|
||||||
|
if pureXrayEnabled then
|
||||||
|
"XRay"
|
||||||
|
else if hybridEnabled then
|
||||||
|
"sing-box + XRay sidecar"
|
||||||
|
else
|
||||||
|
"sing-box"
|
||||||
|
} proxy client (SOCKS + TProxy-ready)";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
wantedBy = [ "multi-user.target" ];
|
||||||
|
execStart = scripts.startSocks;
|
||||||
|
runtimeDirectory = serviceNames.socks;
|
||||||
|
stateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && globalTproxy.enable;
|
||||||
|
name = serviceNames.tproxy;
|
||||||
|
value = mkOneshotService {
|
||||||
|
description = "proxy-suite TProxy - nftables rules and policy routing";
|
||||||
|
after = [
|
||||||
|
"network.target"
|
||||||
|
"${serviceNames.socks}.service"
|
||||||
|
];
|
||||||
|
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
|
||||||
|
requires = [ "${serviceNames.socks}.service" ];
|
||||||
|
conflicts = [
|
||||||
|
"${serviceNames.tun}.service"
|
||||||
|
"${serviceNames.perAppTproxy}.service"
|
||||||
|
];
|
||||||
|
execStart = tproxyUpScript;
|
||||||
|
execStop = tproxyDownScript;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && globalTun.enable;
|
||||||
|
name = serviceNames.tun;
|
||||||
|
value = mkRestartingService {
|
||||||
|
description = "${
|
||||||
|
if pureXrayEnabled then
|
||||||
|
"XRay"
|
||||||
|
else if hybridEnabled then
|
||||||
|
"sing-box + XRay sidecar"
|
||||||
|
else
|
||||||
|
"sing-box"
|
||||||
|
} TUN proxy client";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
|
||||||
|
conflicts = [ "${serviceNames.tproxy}.service" ];
|
||||||
|
execStartPre = tunCleanupScript;
|
||||||
|
execStart = scripts.startTun;
|
||||||
|
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
|
||||||
|
execStopPost = tunCleanupScript;
|
||||||
|
runtimeDirectory = serviceNames.tun;
|
||||||
|
stateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||||
|
name = serviceNames.perAppTun;
|
||||||
|
value = mkRestartingService {
|
||||||
|
description = "proxy-suite per-app-routing TUN backend";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
execStartPre = perAppRouting.perAppTunDownScript;
|
||||||
|
execStart = scripts.startPerAppTun;
|
||||||
|
execStartPost = perAppRouting.perAppTunUpScript;
|
||||||
|
execStopPost = perAppRouting.perAppTunDownScript;
|
||||||
|
runtimeDirectory = serviceNames.perAppTun;
|
||||||
|
stateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||||
|
name = "${serviceNames.perAppTun}-user@";
|
||||||
|
value = mkUserRuleService {
|
||||||
|
description = "Enable proxy-suite app TUN marking for user %i";
|
||||||
|
backendService = serviceNames.perAppTun;
|
||||||
|
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
|
||||||
|
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||||
|
name = serviceNames.perAppTproxy;
|
||||||
|
value = mkOneshotService {
|
||||||
|
description = "proxy-suite per-app-routing TProxy backend";
|
||||||
|
after = [
|
||||||
|
"network.target"
|
||||||
|
"${serviceNames.socks}.service"
|
||||||
|
];
|
||||||
|
requires = [ "${serviceNames.socks}.service" ];
|
||||||
|
conflicts = [
|
||||||
|
"${serviceNames.tproxy}.service"
|
||||||
|
"${serviceNames.tun}.service"
|
||||||
|
];
|
||||||
|
execStart = perAppRouting.perAppTproxyUpScript;
|
||||||
|
execStop = perAppRouting.perAppTproxyDownScript;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||||
|
name = "${serviceNames.perAppTproxy}-user@";
|
||||||
|
value = mkUserRuleService {
|
||||||
|
description = "Enable proxy-suite app TProxy marking for user %i";
|
||||||
|
backendService = serviceNames.perAppTproxy;
|
||||||
|
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
|
||||||
|
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = perAppZapretEnabled;
|
||||||
|
name = "${serviceNames.perAppZapret}-user@";
|
||||||
|
value = mkUserRuleService {
|
||||||
|
description = "Enable proxy-suite app zapret marking for user %i";
|
||||||
|
backendService = serviceNames.perAppZapret;
|
||||||
|
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
|
||||||
|
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && hasSubscriptions;
|
||||||
|
name = serviceNames.subscriptionUpdate;
|
||||||
|
value = mkOneshotService {
|
||||||
|
description = "Refresh proxy-suite subscription caches";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
execStart = scripts.subscriptionUpdateScript;
|
||||||
|
stateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = proxyEnabled;
|
||||||
|
name = "proxy-suite-route-mode@";
|
||||||
|
value = mkOneshotService {
|
||||||
|
description = "Set proxy-suite route mode to %i";
|
||||||
|
execStart = "${scripts.setRouteModeScript} %i";
|
||||||
|
extraServiceConfig.RemainAfterExit = false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
userServiceEntries = [
|
||||||
|
{
|
||||||
|
enable = perAppRoutingTun.enable;
|
||||||
|
name = "${serviceNames.perAppTun}-anchor";
|
||||||
|
value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = perAppRoutingTproxy.enable;
|
||||||
|
name = "${serviceNames.perAppTproxy}-anchor";
|
||||||
|
value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = perAppZapretEnabled;
|
||||||
|
name = "${serviceNames.perAppZapret}-anchor";
|
||||||
|
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
timerEntries = [
|
||||||
|
{
|
||||||
|
enable = proxyEnabled && hasSubscriptions;
|
||||||
|
name = serviceNames.subscriptionUpdate;
|
||||||
|
value = {
|
||||||
|
description = "Periodic proxy-suite subscription refresh";
|
||||||
|
wantedBy = [ "timers.target" ];
|
||||||
|
timerConfig = {
|
||||||
|
OnBootSec = "5m";
|
||||||
|
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
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);
|
||||||
|
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
''
|
||||||
|
);
|
||||||
|
|
||||||
|
systemd.user.services = mkNamedUnits userServiceEntries;
|
||||||
|
|
||||||
|
assertions = import ../service-assertions.nix {
|
||||||
|
inherit lib cfg derived;
|
||||||
|
tgWsProxyCfg = cfg.tgWsProxy;
|
||||||
|
inherit
|
||||||
|
builtinTags
|
||||||
|
outboundTags
|
||||||
|
subscriptionTags
|
||||||
|
invalidRoutingTargets
|
||||||
|
;
|
||||||
|
inherit (perAppRouting)
|
||||||
|
effectivePerAppRoutingProfileNames
|
||||||
|
hasProxychainsProfiles
|
||||||
|
hasTunProfiles
|
||||||
|
hasTproxyProfiles
|
||||||
|
hasZapretProfiles
|
||||||
|
;
|
||||||
|
};
|
||||||
|
|
||||||
|
systemd.services = mkNamedUnits systemServiceEntries;
|
||||||
|
|
||||||
|
systemd.timers = mkNamedUnits timerEntries;
|
||||||
|
}
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
# App routing backend infrastructure (TUN, TProxy, zapret).
|
||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
cfg,
|
||||||
|
singBoxCfg,
|
||||||
|
proxyCfg,
|
||||||
|
pureXrayEnabled,
|
||||||
|
perAppRoutingCfg,
|
||||||
|
perAppRoutingTun,
|
||||||
|
perAppRoutingTproxy,
|
||||||
|
perAppZapretCfg,
|
||||||
|
perAppTunChainFile,
|
||||||
|
perAppTproxyRulesFile,
|
||||||
|
perAppZapretRulesFile,
|
||||||
|
ip,
|
||||||
|
nft,
|
||||||
|
awk,
|
||||||
|
grepBin,
|
||||||
|
findBin,
|
||||||
|
headBin,
|
||||||
|
seqBin,
|
||||||
|
sleepBin,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
builders = import ./builders.nix { inherit lib pkgs; };
|
||||||
|
inherit (builders) mkAnchorService;
|
||||||
|
|
||||||
|
perAppTunSliceName = "proxy-suite-per-app-tun.slice";
|
||||||
|
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
|
||||||
|
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
|
||||||
|
|
||||||
|
perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles;
|
||||||
|
defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles (
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name = "proxychains";
|
||||||
|
route = "proxychains";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
++ lib.optionals perAppRoutingTun.enable [
|
||||||
|
{
|
||||||
|
name = "tun";
|
||||||
|
route = "tun";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
++ lib.optionals perAppRoutingTproxy.enable [
|
||||||
|
{
|
||||||
|
name = "tproxy";
|
||||||
|
route = "tproxy";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
++ lib.optionals perAppZapretCfg.enable [
|
||||||
|
{
|
||||||
|
name = "zapret";
|
||||||
|
route = "zapret";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
);
|
||||||
|
effectivePerAppRoutingProfiles =
|
||||||
|
perAppRoutingCfg.profiles
|
||||||
|
++ builtins.filter (
|
||||||
|
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
|
||||||
|
) defaultPerAppRoutingProfiles;
|
||||||
|
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
|
||||||
|
localProxyAuth = proxyCfg.auth;
|
||||||
|
localProxyAuthEnabled =
|
||||||
|
localProxyAuth.username != null
|
||||||
|
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
|
||||||
|
|
||||||
|
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
|
||||||
|
builtins.toJSON effectivePerAppRoutingProfiles
|
||||||
|
);
|
||||||
|
|
||||||
|
proxychainsConfigFile =
|
||||||
|
if localProxyAuthEnabled then
|
||||||
|
"/run/proxy-suite-socks/proxychains.conf"
|
||||||
|
else
|
||||||
|
pkgs.writeText "proxy-suite-proxychains.conf" ''
|
||||||
|
strict_chain
|
||||||
|
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
|
||||||
|
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
|
||||||
|
tcp_read_time_out 15000
|
||||||
|
tcp_connect_time_out 8000
|
||||||
|
|
||||||
|
[ProxyList]
|
||||||
|
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
|
||||||
|
'';
|
||||||
|
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
|
||||||
|
|
||||||
|
hasProxychainsProfiles = builtins.any (
|
||||||
|
profile: profile.route == "proxychains"
|
||||||
|
) effectivePerAppRoutingProfiles;
|
||||||
|
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
|
||||||
|
hasTproxyProfiles = builtins.any (
|
||||||
|
profile: profile.route == "tproxy"
|
||||||
|
) effectivePerAppRoutingProfiles;
|
||||||
|
hasZapretProfiles = builtins.any (
|
||||||
|
profile: profile.route == "zapret"
|
||||||
|
) effectivePerAppRoutingProfiles;
|
||||||
|
xrayPerAppTunIPv6Address = "fd66:20::1/64";
|
||||||
|
xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64";
|
||||||
|
|
||||||
|
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
|
||||||
|
set -euo pipefail
|
||||||
|
for _ in $(${seqBin} 1 50); do
|
||||||
|
if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
${sleepBin} 0.1
|
||||||
|
done
|
||||||
|
echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2
|
||||||
|
exit 1
|
||||||
|
'';
|
||||||
|
|
||||||
|
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
|
||||||
|
tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address}
|
||||||
|
tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix}
|
||||||
|
tun_addr=""
|
||||||
|
tun_route_prefix=""
|
||||||
|
uplink_addr=""
|
||||||
|
|
||||||
|
cidr_network() {
|
||||||
|
local cidr="$1"
|
||||||
|
local addr="''${cidr%/*}"
|
||||||
|
local prefix="''${cidr#*/}"
|
||||||
|
local o1 o2 o3 o4 ip mask net
|
||||||
|
|
||||||
|
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
|
||||||
|
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
|
||||||
|
if [ "$prefix" -eq 0 ]; then
|
||||||
|
mask=0
|
||||||
|
else
|
||||||
|
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
|
||||||
|
fi
|
||||||
|
net=$((ip & mask))
|
||||||
|
|
||||||
|
printf '%d.%d.%d.%d/%s' \
|
||||||
|
$(((net >> 24) & 255)) \
|
||||||
|
$(((net >> 16) & 255)) \
|
||||||
|
$(((net >> 8) & 255)) \
|
||||||
|
$((net & 255)) \
|
||||||
|
"$prefix"
|
||||||
|
}
|
||||||
|
|
||||||
|
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
|
||||||
|
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||||
|
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
${nft} -f ${perAppTunChainFile}
|
||||||
|
${perAppTunWaitForInterface}
|
||||||
|
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
|
||||||
|
/src/ {
|
||||||
|
for (i = 1; i <= NF; i++) {
|
||||||
|
if ($i == "src" && i + 1 <= NF) {
|
||||||
|
print $(i + 1)
|
||||||
|
exit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
')"
|
||||||
|
if [ -z "$uplink_addr" ]; then
|
||||||
|
echo "proxy-suite: could not determine the default uplink IPv4 address for app TUN" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
tun_addr="''${tun_cidr%%/*}"
|
||||||
|
tun_route_prefix="$(cidr_network "$tun_cidr")"
|
||||||
|
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
|
||||||
|
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
|
||||||
|
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable}
|
||||||
|
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
${lib.optionalString pureXrayEnabled ''
|
||||||
|
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
|
||||||
|
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||||
|
${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||||
|
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
''}
|
||||||
|
'';
|
||||||
|
|
||||||
|
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
|
||||||
|
set +e
|
||||||
|
|
||||||
|
# Best-effort cleanup for graceful stops and for unclean previous exits.
|
||||||
|
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
|
||||||
|
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||||
|
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||||
|
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true
|
||||||
|
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
|
||||||
|
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
|
||||||
|
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||||
|
|
||||||
|
${nft} -f ${perAppTproxyRulesFile}
|
||||||
|
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
|
||||||
|
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
|
||||||
|
'';
|
||||||
|
|
||||||
|
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
|
||||||
|
set +e
|
||||||
|
|
||||||
|
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
|
||||||
|
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
|
||||||
|
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Generate a "start" script that adds a per-user cgroup nftables mark rule.
|
||||||
|
mkUserRuleStart =
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
nftFamily,
|
||||||
|
nftTable,
|
||||||
|
nftChain,
|
||||||
|
sliceName,
|
||||||
|
sliceLabel,
|
||||||
|
markRule,
|
||||||
|
}:
|
||||||
|
pkgs.writeShellScript "proxy-suite-${name}-user-start" ''
|
||||||
|
set -euo pipefail
|
||||||
|
uid="$1"
|
||||||
|
rule_comment_prefix="proxy-suite-${name}-user-$uid"
|
||||||
|
mark_comment="$rule_comment_prefix-mark"
|
||||||
|
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
|
||||||
|
if ! [ -d "$cgroup_root" ]; then
|
||||||
|
echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true)
|
||||||
|
if [ -z "$cgroup_dir" ]; then
|
||||||
|
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
|
||||||
|
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
|
||||||
|
|
||||||
|
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
|
||||||
|
| ${grepBin} -F "comment \"$rule_comment_prefix" \
|
||||||
|
| ${awk} '{ print $NF }' || true)
|
||||||
|
if [ -n "$handles" ]; then
|
||||||
|
while IFS= read -r handle; do
|
||||||
|
[ -n "$handle" ] || continue
|
||||||
|
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
|
||||||
|
done <<< "$handles"
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '%s\n' \
|
||||||
|
"add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \
|
||||||
|
| ${nft} -f -
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Generate a "stop" script that removes all per-user cgroup nftables mark rules.
|
||||||
|
mkUserRuleStop =
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
nftFamily,
|
||||||
|
nftTable,
|
||||||
|
nftChain,
|
||||||
|
}:
|
||||||
|
pkgs.writeShellScript "proxy-suite-${name}-user-stop" ''
|
||||||
|
set -euo pipefail
|
||||||
|
uid="$1"
|
||||||
|
rule_comment_prefix="proxy-suite-${name}-user-$uid"
|
||||||
|
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
|
||||||
|
| ${grepBin} -F "comment \"$rule_comment_prefix" \
|
||||||
|
| ${awk} '{ print $NF }' || true)
|
||||||
|
if [ -n "$handles" ]; then
|
||||||
|
while IFS= read -r handle; do
|
||||||
|
[ -n "$handle" ] || continue
|
||||||
|
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
|
||||||
|
done <<< "$handles"
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
perAppTunUserRuleStart = mkUserRuleStart {
|
||||||
|
name = "per-app-tun";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_per_app_tun";
|
||||||
|
nftChain = "output";
|
||||||
|
sliceName = perAppTunSliceName;
|
||||||
|
sliceLabel = "app TUN";
|
||||||
|
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
|
||||||
|
};
|
||||||
|
perAppTunUserRuleStop = mkUserRuleStop {
|
||||||
|
name = "per-app-tun";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_per_app_tun";
|
||||||
|
nftChain = "output";
|
||||||
|
};
|
||||||
|
|
||||||
|
perAppTproxyUserRuleStart = mkUserRuleStart {
|
||||||
|
name = "per-app-tproxy";
|
||||||
|
nftFamily = "ip";
|
||||||
|
nftTable = "proxy_suite_per_app_tproxy";
|
||||||
|
nftChain = "output";
|
||||||
|
sliceName = perAppTproxySliceName;
|
||||||
|
sliceLabel = "app TProxy";
|
||||||
|
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
|
||||||
|
};
|
||||||
|
perAppTproxyUserRuleStop = mkUserRuleStop {
|
||||||
|
name = "per-app-tproxy";
|
||||||
|
nftFamily = "ip";
|
||||||
|
nftTable = "proxy_suite_per_app_tproxy";
|
||||||
|
nftChain = "output";
|
||||||
|
};
|
||||||
|
|
||||||
|
perAppZapretUserRuleStart = mkUserRuleStart {
|
||||||
|
name = "per-app-zapret";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_per_app_zapret_mark";
|
||||||
|
nftChain = "output";
|
||||||
|
sliceName = perAppZapretSliceName;
|
||||||
|
sliceLabel = "app zapret";
|
||||||
|
markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}";
|
||||||
|
};
|
||||||
|
perAppZapretUserRuleStop = mkUserRuleStop {
|
||||||
|
name = "per-app-zapret";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_per_app_zapret_mark";
|
||||||
|
nftChain = "output";
|
||||||
|
};
|
||||||
|
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit
|
||||||
|
perAppTunSliceName
|
||||||
|
perAppTproxySliceName
|
||||||
|
perAppZapretSliceName
|
||||||
|
perAppTunUpScript
|
||||||
|
perAppTunDownScript
|
||||||
|
perAppTproxyUpScript
|
||||||
|
perAppTproxyDownScript
|
||||||
|
perAppTunUserRuleStart
|
||||||
|
perAppTunUserRuleStop
|
||||||
|
perAppTproxyUserRuleStart
|
||||||
|
perAppTproxyUserRuleStop
|
||||||
|
perAppZapretUserRuleStart
|
||||||
|
perAppZapretUserRuleStop
|
||||||
|
mkAnchorService
|
||||||
|
effectivePerAppRoutingProfiles
|
||||||
|
effectivePerAppRoutingProfileNames
|
||||||
|
perAppRoutingProfilesFile
|
||||||
|
proxychainsConfigFile
|
||||||
|
proxychainsQuietArg
|
||||||
|
hasProxychainsProfiles
|
||||||
|
hasTunProfiles
|
||||||
|
hasTproxyProfiles
|
||||||
|
hasZapretProfiles
|
||||||
|
;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Polkit rules granting proxy-suite group members passwordless control over services.
|
||||||
|
{
|
||||||
|
lib,
|
||||||
|
cfg,
|
||||||
|
userControlCfg,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
|
||||||
|
|
||||||
|
userControlPolkitRules =
|
||||||
|
lib.optionalString userControlCfg.perApp.enable ''
|
||||||
|
if (unit.indexOf("proxy-suite-per-app-") === 0) {
|
||||||
|
return polkit.Result.YES;
|
||||||
|
}
|
||||||
|
''
|
||||||
|
+ lib.optionalString userControlCfg.global.enable ''
|
||||||
|
if ((unit.indexOf("proxy-suite-") === 0 &&
|
||||||
|
unit.indexOf("proxy-suite-per-app-") !== 0) ||
|
||||||
|
unit === "zapret-discord-youtube.service") {
|
||||||
|
return polkit.Result.YES;
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit userControlEnabled userControlPolkitRules;
|
||||||
|
}
|
||||||
@@ -0,0 +1,923 @@
|
|||||||
|
# Generates proxy backend startup scripts and subscription management scripts.
|
||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
singBoxCfg,
|
||||||
|
proxyCfg,
|
||||||
|
proxyEnabled,
|
||||||
|
singBoxEnabled,
|
||||||
|
xrayEnabled,
|
||||||
|
hybridEnabled,
|
||||||
|
pureXrayEnabled,
|
||||||
|
activeBackend,
|
||||||
|
perAppRoutingCfg,
|
||||||
|
userControlCfg,
|
||||||
|
perAppRoutingTun,
|
||||||
|
selectionMode,
|
||||||
|
collapseNamedOutbounds,
|
||||||
|
hasSubscriptions,
|
||||||
|
jq,
|
||||||
|
python3,
|
||||||
|
singBox,
|
||||||
|
xray,
|
||||||
|
parserScriptsPythonPath,
|
||||||
|
buildOutboundPy,
|
||||||
|
fetchSubscriptionPy,
|
||||||
|
tproxyFile,
|
||||||
|
tunFile,
|
||||||
|
perAppTunFile,
|
||||||
|
routeModeRulesFile,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
globalTproxy = proxyCfg.tproxy;
|
||||||
|
systemctl = "${pkgs.systemd}/bin/systemctl";
|
||||||
|
backend = if activeBackend == null then "sing-box" else activeBackend;
|
||||||
|
mainBackend = if pureXrayEnabled then "xray" else "sing-box";
|
||||||
|
subscriptionBackend =
|
||||||
|
if hybridEnabled then
|
||||||
|
"hybrid"
|
||||||
|
else
|
||||||
|
mainBackend;
|
||||||
|
backendArg = "--backend ${mainBackend}";
|
||||||
|
subscriptionBackendArg = "--backend ${subscriptionBackend}";
|
||||||
|
backendBin = if pureXrayEnabled then xray else singBox;
|
||||||
|
localProxyAuth = proxyCfg.auth;
|
||||||
|
localProxyAuthEnabled =
|
||||||
|
localProxyAuth.username != null
|
||||||
|
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
|
||||||
|
localProxyAuthPasswordSource =
|
||||||
|
if localProxyAuth.passwordFile != null then
|
||||||
|
localProxyAuth.passwordFile
|
||||||
|
else if localProxyAuth.password != null then
|
||||||
|
pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password
|
||||||
|
else
|
||||||
|
null;
|
||||||
|
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
|
||||||
|
routeModeStateFile = "/run/proxy-suite/route-mode";
|
||||||
|
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
|
||||||
|
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
|
||||||
|
xraySidecarRoutingMark = globalTproxy.proxyMark;
|
||||||
|
|
||||||
|
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
|
||||||
|
|
||||||
|
mkSubscriptionUrlSource =
|
||||||
|
sub:
|
||||||
|
if sub.urlFile != null then
|
||||||
|
sub.urlFile
|
||||||
|
else
|
||||||
|
pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url;
|
||||||
|
|
||||||
|
mkSubscriptionFetchCommand =
|
||||||
|
sub:
|
||||||
|
let
|
||||||
|
urlSource = mkSubscriptionUrlSource sub;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
printf '%s' "$(cat "${urlSource}")" \
|
||||||
|
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
|
||||||
|
'';
|
||||||
|
|
||||||
|
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
|
||||||
|
_proxy_suite_valid_subscription_cache() {
|
||||||
|
[ -s "$1" ] && ${jq} -e ${
|
||||||
|
lib.escapeShellArg (
|
||||||
|
if hybridEnabled then
|
||||||
|
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
|
||||||
|
else
|
||||||
|
''type == "array"''
|
||||||
|
)
|
||||||
|
} "$1" >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
_proxy_suite_commit_subscription_cache() {
|
||||||
|
local tmp="$1" target="$2" tag="$3"
|
||||||
|
if _proxy_suite_valid_subscription_cache "$tmp"; then
|
||||||
|
mv "$tmp" "$target"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
_proxy_suite_drop_invalid_subscription_cache() {
|
||||||
|
local target="$1" tag="$2"
|
||||||
|
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
|
||||||
|
rm -f "$target"
|
||||||
|
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
|
||||||
|
routingMarkJq =
|
||||||
|
routingMark:
|
||||||
|
if routingMark == null then
|
||||||
|
""
|
||||||
|
else if pureXrayEnabled then
|
||||||
|
" | .streamSettings.sockopt.mark = ${toString routingMark}"
|
||||||
|
else
|
||||||
|
" | .routing_mark = ${toString routingMark}";
|
||||||
|
|
||||||
|
rawOutboundJson =
|
||||||
|
ob: tag: routingMark:
|
||||||
|
let
|
||||||
|
backendRaw =
|
||||||
|
if pureXrayEnabled then
|
||||||
|
ob.xrayJson
|
||||||
|
else if ob.singBoxJson != null then
|
||||||
|
ob.singBoxJson
|
||||||
|
else
|
||||||
|
ob.json;
|
||||||
|
markAttrs =
|
||||||
|
if routingMark == null then
|
||||||
|
{ }
|
||||||
|
else if pureXrayEnabled then
|
||||||
|
{ streamSettings.sockopt.mark = routingMark; }
|
||||||
|
else
|
||||||
|
{ routing_mark = routingMark; };
|
||||||
|
taggedRaw = backendRaw // {
|
||||||
|
inherit tag;
|
||||||
|
};
|
||||||
|
in
|
||||||
|
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
|
||||||
|
|
||||||
|
mkOutboundBlock =
|
||||||
|
ob: routingMark: tag:
|
||||||
|
let
|
||||||
|
backendRaw =
|
||||||
|
if pureXrayEnabled then
|
||||||
|
ob.xrayJson
|
||||||
|
else if ob.singBoxJson != null then
|
||||||
|
ob.singBoxJson
|
||||||
|
else
|
||||||
|
ob.json;
|
||||||
|
in
|
||||||
|
if backendRaw != null then
|
||||||
|
let
|
||||||
|
outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
|
||||||
|
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
# outbound: ${tag} (static ${backend} json)
|
||||||
|
OB_JSON=$(cat "${jsonFile}")
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
''
|
||||||
|
else
|
||||||
|
let
|
||||||
|
urlSource =
|
||||||
|
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
|
||||||
|
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")
|
||||||
|
'';
|
||||||
|
|
||||||
|
singBoxRawOutboundJson =
|
||||||
|
ob: tag: routingMark:
|
||||||
|
let
|
||||||
|
backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json;
|
||||||
|
markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
|
||||||
|
in
|
||||||
|
backendRaw // { inherit tag; } // markAttrs;
|
||||||
|
|
||||||
|
xrayRawOutboundJson =
|
||||||
|
ob: tag:
|
||||||
|
lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) {
|
||||||
|
streamSettings.sockopt = {
|
||||||
|
mark = xraySidecarRoutingMark;
|
||||||
|
domainStrategy = "UseIP";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
mkHybridOutboundBlock =
|
||||||
|
ob: routingMark: tag:
|
||||||
|
if ob.xrayJson != null then
|
||||||
|
let
|
||||||
|
outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag);
|
||||||
|
jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
# outbound: ${tag} (hybrid XRay json sidecar)
|
||||||
|
OB_JSON=$(cat "${jsonFile}")
|
||||||
|
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
|
||||||
|
''
|
||||||
|
else if ob.singBoxJson != null || ob.json != null then
|
||||||
|
let
|
||||||
|
outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark);
|
||||||
|
jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
# outbound: ${tag} (hybrid SingBox json)
|
||||||
|
OB_JSON=$(cat "${jsonFile}")
|
||||||
|
_proxy_suite_add_sing_box_ob "$OB_JSON"
|
||||||
|
''
|
||||||
|
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
|
||||||
|
'';
|
||||||
|
|
||||||
|
mkSubscriptionBlock =
|
||||||
|
sub: 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
|
||||||
|
${
|
||||||
|
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
|
||||||
|
''
|
||||||
|
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
|
||||||
|
''
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
|
||||||
|
xrayUrltestTagFilter = ''
|
||||||
|
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
|
||||||
|
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
|
||||||
|
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
hybridRuntimeHelpersBlock =
|
||||||
|
routingMark: xraySidecarBasePort: xrayDnsBridgePort:
|
||||||
|
lib.optionalString hybridEnabled ''
|
||||||
|
XRAY_OUTBOUNDS_JSON='[]'
|
||||||
|
XRAY_INBOUNDS_JSON='[]'
|
||||||
|
XRAY_ROUTE_RULES_JSON='[]'
|
||||||
|
XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort}
|
||||||
|
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
|
||||||
|
|
||||||
|
_proxy_suite_add_sing_box_ob() {
|
||||||
|
local ob="$1"
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
}
|
||||||
|
|
||||||
|
_proxy_suite_next_xray_sidecar_port() {
|
||||||
|
local port="$XRAY_SIDECAR_NEXT_PORT"
|
||||||
|
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1))
|
||||||
|
printf '%s\n' "$port"
|
||||||
|
}
|
||||||
|
|
||||||
|
_proxy_suite_add_xray_sidecar_ob() {
|
||||||
|
local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule
|
||||||
|
port="$(_proxy_suite_next_xray_sidecar_port)"
|
||||||
|
auth="proxy-suite-xray-$port"
|
||||||
|
inbound_tag="$tag-inbound"
|
||||||
|
ob=$(${jq} \
|
||||||
|
--arg tag "$tag" \
|
||||||
|
--argjson mark ${toString xraySidecarRoutingMark} \
|
||||||
|
'.tag = $tag
|
||||||
|
| .streamSettings = (.streamSettings // {})
|
||||||
|
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
|
||||||
|
| .streamSettings.sockopt.mark = $mark
|
||||||
|
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \
|
||||||
|
<<< "$ob")
|
||||||
|
XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON")
|
||||||
|
inbound=$(${jq} -n \
|
||||||
|
--arg tag "$inbound_tag" \
|
||||||
|
--arg auth "$auth" \
|
||||||
|
--argjson port "$port" \
|
||||||
|
'{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}')
|
||||||
|
XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON")
|
||||||
|
route_rule=$(${jq} -n \
|
||||||
|
--arg inbound "$inbound_tag" \
|
||||||
|
--arg outbound "$tag" \
|
||||||
|
'{type:"field",inboundTag:[$inbound],outboundTag:$outbound}')
|
||||||
|
XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON")
|
||||||
|
sing_ob=$(${jq} -n \
|
||||||
|
--arg tag "$tag" \
|
||||||
|
--arg auth "$auth" \
|
||||||
|
--argjson port "$port" \
|
||||||
|
'{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${
|
||||||
|
lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}"
|
||||||
|
}}')
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
}
|
||||||
|
|
||||||
|
_proxy_suite_write_xray_sidecar_config() {
|
||||||
|
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
${jq} -n \
|
||||||
|
--arg loglevel "$XRAY_LOGLEVEL" \
|
||||||
|
--arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \
|
||||||
|
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
|
||||||
|
--argjson inbounds "$XRAY_INBOUNDS_JSON" \
|
||||||
|
--argjson outbounds "$XRAY_OUTBOUNDS_JSON" \
|
||||||
|
--argjson route_rules "$XRAY_ROUTE_RULES_JSON" \
|
||||||
|
'
|
||||||
|
def bind_xray_sidecar($interface):
|
||||||
|
if $interface == "" then
|
||||||
|
.
|
||||||
|
else
|
||||||
|
.streamSettings = (.streamSettings // {})
|
||||||
|
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
|
||||||
|
| if (.streamSettings.sockopt.interface? // "") == "" then
|
||||||
|
.streamSettings.sockopt.interface = $interface
|
||||||
|
else
|
||||||
|
.
|
||||||
|
end
|
||||||
|
end;
|
||||||
|
{
|
||||||
|
log: {
|
||||||
|
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
|
||||||
|
access: "none"
|
||||||
|
},
|
||||||
|
dns: {
|
||||||
|
servers: [
|
||||||
|
{
|
||||||
|
address: "127.0.0.1",
|
||||||
|
port: $dns_port,
|
||||||
|
queryStrategy: "UseIP",
|
||||||
|
skipFallBack: true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
inbounds: $inbounds,
|
||||||
|
outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]),
|
||||||
|
routing: {
|
||||||
|
domainStrategy: "AsIs",
|
||||||
|
rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
|
||||||
|
}
|
||||||
|
}' > "$RUNTIME_DIR/xray-sidecar.json"
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
|
||||||
|
mkOutboundScript =
|
||||||
|
routingMark:
|
||||||
|
let
|
||||||
|
outboundBlocks =
|
||||||
|
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
|
||||||
|
(if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock)
|
||||||
|
(builtins.head proxyCfg.outbounds)
|
||||||
|
routingMark
|
||||||
|
"proxy"
|
||||||
|
else
|
||||||
|
lib.concatMapStrings (
|
||||||
|
ob: (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock) ob routingMark ob.tag
|
||||||
|
) proxyCfg.outbounds;
|
||||||
|
|
||||||
|
subscriptionBlocks = lib.concatMapStrings (
|
||||||
|
sub: mkSubscriptionBlock sub routingMark
|
||||||
|
) proxyCfg.subscriptions;
|
||||||
|
|
||||||
|
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
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
wrapperBlock =
|
||||||
|
if pureXrayEnabled && selectionMode == "urltest" then
|
||||||
|
xrayUrltestTagFilter
|
||||||
|
else if collapseNamedOutbounds then
|
||||||
|
lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) ''
|
||||||
|
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
|
||||||
|
''
|
||||||
|
else if selectionMode == "selector" then
|
||||||
|
''
|
||||||
|
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
|
||||||
|
WRAPPER=$(${jq} -n \
|
||||||
|
--argjson tags "$TAGS" \
|
||||||
|
--arg default "$FIRST" \
|
||||||
|
'{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}')
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||||
|
'';
|
||||||
|
in
|
||||||
|
outboundBlocks + subscriptionBlocks + requireOutboundsBlock + wrapperBlock;
|
||||||
|
|
||||||
|
writeProxychainsConfigBlock = ''
|
||||||
|
{
|
||||||
|
printf '%s\n' 'strict_chain'
|
||||||
|
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
|
||||||
|
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"}
|
||||||
|
printf '%s\n' 'tcp_read_time_out 15000'
|
||||||
|
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 localProxyAuth.username} \
|
||||||
|
"$LOCAL_PROXY_PASSWORD"
|
||||||
|
} > "${runtimeProxychainsConfig}"
|
||||||
|
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
|
||||||
|
chmod 640 "${runtimeProxychainsConfig}"
|
||||||
|
'';
|
||||||
|
|
||||||
|
restartActiveConfigConsumersBlock =
|
||||||
|
lib.concatMapStrings
|
||||||
|
(svc: ''
|
||||||
|
if ${systemctl} is-active --quiet ${svc}; then
|
||||||
|
${systemctl} restart ${svc}
|
||||||
|
fi
|
||||||
|
'')
|
||||||
|
[
|
||||||
|
"proxy-suite-socks"
|
||||||
|
"proxy-suite-tun"
|
||||||
|
"proxy-suite-per-app-tun"
|
||||||
|
];
|
||||||
|
|
||||||
|
routeModeBlacklistTail =
|
||||||
|
if pureXrayEnabled then
|
||||||
|
''
|
||||||
|
+ .proxyGeo
|
||||||
|
+ .block
|
||||||
|
''
|
||||||
|
else
|
||||||
|
''
|
||||||
|
+ .block
|
||||||
|
+ .proxyGeo
|
||||||
|
'';
|
||||||
|
|
||||||
|
routeModeCaseBlock = ''
|
||||||
|
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then
|
||||||
|
ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)"
|
||||||
|
fi
|
||||||
|
case "$ROUTE_MODE" in
|
||||||
|
blacklist)
|
||||||
|
ROUTE_FINAL="proxy"
|
||||||
|
DNS_FINAL="remote"
|
||||||
|
ROUTE_MODE_ACTIVE=true
|
||||||
|
ROUTE_RULES_JSON=$(${jq} -c '
|
||||||
|
.common
|
||||||
|
+ (.custom | map(.entries) | add // [])
|
||||||
|
+ .proxyPrimary
|
||||||
|
+ .direct
|
||||||
|
+ .safetyDirect
|
||||||
|
${routeModeBlacklistTail}
|
||||||
|
' "${routeModeRulesFile}")
|
||||||
|
;;
|
||||||
|
whitelist)
|
||||||
|
ROUTE_FINAL="direct"
|
||||||
|
DNS_FINAL="local"
|
||||||
|
ROUTE_MODE_ACTIVE=true
|
||||||
|
ROUTE_RULES_JSON=$(${jq} -c '
|
||||||
|
.common
|
||||||
|
+ (.custom | map(.entries) | add // [])
|
||||||
|
+ .proxyPrimary
|
||||||
|
+ .direct
|
||||||
|
+ .safetyDirect
|
||||||
|
${routeModeBlacklistTail}
|
||||||
|
' "${routeModeRulesFile}")
|
||||||
|
;;
|
||||||
|
all-proxy)
|
||||||
|
ROUTE_FINAL="proxy"
|
||||||
|
DNS_FINAL="remote"
|
||||||
|
ROUTE_MODE_ACTIVE=true
|
||||||
|
CLEAR_DNS_RULES=true
|
||||||
|
ROUTE_RULES_JSON=$(${jq} -c '
|
||||||
|
.common
|
||||||
|
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
|
||||||
|
+ .proxyPrimary
|
||||||
|
+ .safetyDirect
|
||||||
|
${routeModeBlacklistTail}
|
||||||
|
' "${routeModeRulesFile}")
|
||||||
|
;;
|
||||||
|
all-bypass)
|
||||||
|
ROUTE_FINAL="direct"
|
||||||
|
DNS_FINAL="local"
|
||||||
|
ROUTE_MODE_ACTIVE=true
|
||||||
|
CLEAR_DNS_RULES=true
|
||||||
|
ROUTE_RULES_JSON=$(${jq} -c '
|
||||||
|
.common
|
||||||
|
+ (.custom | map(select(.category == "block") | .entries) | add // [])
|
||||||
|
+ .safetyDirect
|
||||||
|
+ .block
|
||||||
|
' "${routeModeRulesFile}")
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
ROUTE_MODE=""
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
'';
|
||||||
|
|
||||||
|
mkBackendJqFilter =
|
||||||
|
if pureXrayEnabled then
|
||||||
|
''
|
||||||
|
def xray_bind_outbound($interface):
|
||||||
|
if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then
|
||||||
|
.
|
||||||
|
else
|
||||||
|
.streamSettings = (.streamSettings // {})
|
||||||
|
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
|
||||||
|
| if (.streamSettings.sockopt.interface? // "") == "" then
|
||||||
|
.streamSettings.sockopt.interface = $interface
|
||||||
|
else
|
||||||
|
.
|
||||||
|
end
|
||||||
|
end;
|
||||||
|
def xray_proxy_rule_target($single_tag):
|
||||||
|
if $single_tag != "" then
|
||||||
|
{outboundTag:$single_tag}
|
||||||
|
else
|
||||||
|
{balancerTag:"proxy"}
|
||||||
|
end;
|
||||||
|
def xray_rewrite_proxy_rule($single_tag):
|
||||||
|
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
|
||||||
|
.outboundTag = $single_tag | del(.balancerTag)
|
||||||
|
else
|
||||||
|
.
|
||||||
|
end;
|
||||||
|
def xray_preserved_rules:
|
||||||
|
[.routing.rules[]
|
||||||
|
| select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))];
|
||||||
|
def xray_final_rule($tag; $single_tag):
|
||||||
|
if $tag == "proxy" and "${selectionMode}" == "urltest" then
|
||||||
|
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
|
||||||
|
else
|
||||||
|
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
|
||||||
|
end;
|
||||||
|
def xray_dns_server_order($dns_final):
|
||||||
|
if $dns_final == "" then
|
||||||
|
.dns.servers
|
||||||
|
else
|
||||||
|
([.dns.servers[] | select((.tag? // "") == "fakedns")]
|
||||||
|
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
|
||||||
|
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
|
||||||
|
end;
|
||||||
|
def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr):
|
||||||
|
if $dns_final == "local" then
|
||||||
|
[$local_addr, $remote_addr]
|
||||||
|
elif $dns_final == "remote" then
|
||||||
|
[$remote_addr, $local_addr]
|
||||||
|
else
|
||||||
|
[$remote_addr, $local_addr]
|
||||||
|
end;
|
||||||
|
.outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface)))
|
||||||
|
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
|
||||||
|
| if $auth_enabled then
|
||||||
|
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
|
||||||
|
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
|
||||||
|
else . end
|
||||||
|
| if $xray_tun_dns_runtime then
|
||||||
|
.dns.servers = xray_dns_server_order($dns_final)
|
||||||
|
| if $dns_final == "" then
|
||||||
|
.
|
||||||
|
else
|
||||||
|
(.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client)
|
||||||
|
end
|
||||||
|
else . end
|
||||||
|
| if $route_enabled then
|
||||||
|
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
|
||||||
|
else . end
|
||||||
|
| if $xray_single_proxy_tag == "" then
|
||||||
|
.
|
||||||
|
else
|
||||||
|
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
|
||||||
|
| del(.routing.balancers)
|
||||||
|
| del(.observatory)
|
||||||
|
end
|
||||||
|
''
|
||||||
|
else
|
||||||
|
''
|
||||||
|
def sing_box_preserved_rules:
|
||||||
|
[.route.rules[]
|
||||||
|
| select(((.action? // "") == "hijack-dns")
|
||||||
|
and (((.inbound? // []) | index("xray-dns-in")) != null))];
|
||||||
|
.outbounds = $obs + .outbounds
|
||||||
|
| if $auth_enabled then
|
||||||
|
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
|
||||||
|
else . end
|
||||||
|
| if $route_enabled then
|
||||||
|
.route.rules = (sing_box_preserved_rules + $route_rules)
|
||||||
|
| .route.final = $route_final
|
||||||
|
| .dns.final = $dns_final
|
||||||
|
| if $clear_dns_rules then .dns.rules = [] else . end
|
||||||
|
else . end
|
||||||
|
'';
|
||||||
|
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" mkBackendJqFilter;
|
||||||
|
|
||||||
|
mkStartScript =
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
runtimeDir,
|
||||||
|
configFile,
|
||||||
|
routingMark ? null,
|
||||||
|
enableLocalProxyAuth ? false,
|
||||||
|
xrayTunEgressBinding ? false,
|
||||||
|
xrayTunDnsRuntime ? false,
|
||||||
|
xraySidecarBasePort ? 33080,
|
||||||
|
xrayDnsBridgePort ? 18533,
|
||||||
|
}:
|
||||||
|
pkgs.writeShellScript name ''
|
||||||
|
set -euo pipefail
|
||||||
|
RUNTIME_DIR="${runtimeDir}"
|
||||||
|
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
|
||||||
|
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
|
||||||
|
XRAY_LOGLEVEL=""
|
||||||
|
XRAY_TUN_BIND_INTERFACE=""
|
||||||
|
XRAY_SINGLE_PROXY_TAG=""
|
||||||
|
mkdir -p "$RUNTIME_DIR"
|
||||||
|
OUTBOUNDS_JSON='[]'
|
||||||
|
ROUTE_MODE=""
|
||||||
|
ROUTE_FINAL=""
|
||||||
|
DNS_FINAL=""
|
||||||
|
ROUTE_RULES_JSON='[]'
|
||||||
|
ROUTE_MODE_ACTIVE=false
|
||||||
|
CLEAR_DNS_RULES=false
|
||||||
|
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
|
||||||
|
${subscriptionCacheHelpersBlock}
|
||||||
|
${lib.optionalString enableLocalProxyAuth ''
|
||||||
|
umask 077
|
||||||
|
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
|
||||||
|
${writeProxychainsConfigBlock}
|
||||||
|
''}
|
||||||
|
${lib.optionalString xrayEnabled ''
|
||||||
|
if [ -r "${xrayLoglevelFile}" ]; then
|
||||||
|
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
|
||||||
|
fi
|
||||||
|
''}
|
||||||
|
${lib.optionalString xrayTunEgressBinding ''
|
||||||
|
XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk '
|
||||||
|
/dev/ {
|
||||||
|
for (i = 1; i <= NF; i++) {
|
||||||
|
if ($i == "dev" && i + 1 <= NF) {
|
||||||
|
print $(i + 1)
|
||||||
|
exit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
')"
|
||||||
|
if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then
|
||||||
|
echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
''}
|
||||||
|
|
||||||
|
${routeModeCaseBlock}
|
||||||
|
|
||||||
|
${mkOutboundScript routingMark}
|
||||||
|
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
|
||||||
|
|
||||||
|
${jq} \
|
||||||
|
--argjson obs "$OUTBOUNDS_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 "''"} \
|
||||||
|
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
|
||||||
|
--argjson route_rules "$ROUTE_RULES_JSON" \
|
||||||
|
--arg route_final "$ROUTE_FINAL" \
|
||||||
|
--arg dns_final "$DNS_FINAL" \
|
||||||
|
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
|
||||||
|
--arg xray_loglevel "$XRAY_LOGLEVEL" \
|
||||||
|
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
|
||||||
|
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
|
||||||
|
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
|
||||||
|
--arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \
|
||||||
|
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
|
||||||
|
-f "$BACKEND_JQ_FILTER" \
|
||||||
|
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||||
|
${lib.optionalString enableLocalProxyAuth ''
|
||||||
|
chmod 600 "$RUNTIME_DIR/config.json"
|
||||||
|
''}
|
||||||
|
|
||||||
|
${
|
||||||
|
if hybridEnabled then
|
||||||
|
''
|
||||||
|
if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then
|
||||||
|
XRAY_SIDECAR_PID=""
|
||||||
|
_proxy_suite_cleanup_xray_sidecar() {
|
||||||
|
if [ -n "$XRAY_SIDECAR_PID" ]; then
|
||||||
|
kill "$XRAY_SIDECAR_PID" 2>/dev/null || true
|
||||||
|
wait "$XRAY_SIDECAR_PID" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
trap _proxy_suite_cleanup_xray_sidecar EXIT
|
||||||
|
trap 'exit 143' INT TERM
|
||||||
|
|
||||||
|
${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
|
||||||
|
XRAY_SIDECAR_PID="$!"
|
||||||
|
${pkgs.coreutils}/bin/sleep 0.2
|
||||||
|
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
|
||||||
|
XRAY_SIDECAR_STATUS=1
|
||||||
|
wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?"
|
||||||
|
exit "$XRAY_SIDECAR_STATUS"
|
||||||
|
fi
|
||||||
|
|
||||||
|
${singBox} run -c "$RUNTIME_DIR/config.json" &
|
||||||
|
SING_BOX_PID="$!"
|
||||||
|
SING_BOX_STATUS=0
|
||||||
|
wait "$SING_BOX_PID" || SING_BOX_STATUS="$?"
|
||||||
|
exit "$SING_BOX_STATUS"
|
||||||
|
fi
|
||||||
|
|
||||||
|
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||||
|
''
|
||||||
|
else
|
||||||
|
''
|
||||||
|
exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
|
||||||
|
''
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
|
||||||
|
startSocks = mkStartScript {
|
||||||
|
name = "proxy-suite-start-socks";
|
||||||
|
runtimeDir = "/run/proxy-suite-socks";
|
||||||
|
configFile = tproxyFile;
|
||||||
|
routingMark = globalTproxy.proxyMark;
|
||||||
|
enableLocalProxyAuth = localProxyAuthEnabled;
|
||||||
|
xraySidecarBasePort = 33080;
|
||||||
|
xrayDnsBridgePort = 18533;
|
||||||
|
};
|
||||||
|
|
||||||
|
startTun = mkStartScript {
|
||||||
|
name = "proxy-suite-start-tun";
|
||||||
|
runtimeDir = "/run/proxy-suite-tun";
|
||||||
|
configFile = tunFile;
|
||||||
|
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
|
||||||
|
xrayTunEgressBinding = xrayEnabled;
|
||||||
|
xrayTunDnsRuntime = pureXrayEnabled;
|
||||||
|
xraySidecarBasePort = 33180;
|
||||||
|
xrayDnsBridgePort = 18534;
|
||||||
|
};
|
||||||
|
|
||||||
|
startPerAppTun = mkStartScript {
|
||||||
|
name = "proxy-suite-start-per-app-tun";
|
||||||
|
runtimeDir = "/run/proxy-suite-per-app-tun";
|
||||||
|
configFile = perAppTunFile;
|
||||||
|
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
|
||||||
|
xrayTunEgressBinding = xrayEnabled;
|
||||||
|
xrayTunDnsRuntime = pureXrayEnabled;
|
||||||
|
xraySidecarBasePort = 33280;
|
||||||
|
xrayDnsBridgePort = 18535;
|
||||||
|
};
|
||||||
|
|
||||||
|
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
|
||||||
|
else
|
||||||
|
rm -f "${cacheFile}.tmp"
|
||||||
|
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
|
||||||
|
FAILED=1
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" ''
|
||||||
|
set -euo pipefail
|
||||||
|
CACHE_DIR="${subscriptionCacheDir}"
|
||||||
|
mkdir -p "$CACHE_DIR"
|
||||||
|
FAILED=0
|
||||||
|
${subscriptionCacheHelpersBlock}
|
||||||
|
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
|
||||||
|
|
||||||
|
if [ "$FAILED" -eq 0 ]; then
|
||||||
|
${restartActiveConfigConsumersBlock}
|
||||||
|
fi
|
||||||
|
exit "$FAILED"
|
||||||
|
'';
|
||||||
|
|
||||||
|
setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" ''
|
||||||
|
set -euo pipefail
|
||||||
|
mode="''${1:-}"
|
||||||
|
|
||||||
|
case "$mode" in
|
||||||
|
default)
|
||||||
|
;;
|
||||||
|
whitelist)
|
||||||
|
;;
|
||||||
|
blacklist)
|
||||||
|
;;
|
||||||
|
all-proxy)
|
||||||
|
;;
|
||||||
|
all-bypass)
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
mkdir -p "$(dirname "${routeModeStateFile}")"
|
||||||
|
if [ "$mode" = "default" ]; then
|
||||||
|
rm -f "${routeModeStateFile}"
|
||||||
|
else
|
||||||
|
printf '%s\n' "$mode" > "${routeModeStateFile}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
${restartActiveConfigConsumersBlock}
|
||||||
|
'';
|
||||||
|
|
||||||
|
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
|
||||||
|
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
|
||||||
|
);
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit startSocks startTun startPerAppTun;
|
||||||
|
inherit
|
||||||
|
routeModeStateFile
|
||||||
|
setRouteModeScript
|
||||||
|
subscriptionUpdateScript
|
||||||
|
hasSubscriptions
|
||||||
|
subscriptionTagsFile
|
||||||
|
subscriptionCacheDir
|
||||||
|
runtimeProxychainsConfig
|
||||||
|
;
|
||||||
|
}
|
||||||
@@ -2,36 +2,88 @@
|
|||||||
{
|
{
|
||||||
lib,
|
lib,
|
||||||
pkgs,
|
pkgs,
|
||||||
|
packages,
|
||||||
cfg,
|
cfg,
|
||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
t = cfg.tgWsProxy;
|
t = cfg.tgWsProxy;
|
||||||
tgPkg = import ../../pkgs/tg-ws-proxy.nix { inherit pkgs; };
|
tgPkg = packages.tg-ws-proxy;
|
||||||
|
ip = "${pkgs.iproute2}/bin/ip";
|
||||||
|
|
||||||
dcArgs = lib.concatMapStrings (id: " --dc-ip=${id}:${t.dcIps.${id}}") (builtins.attrNames t.dcIps);
|
transparentBypassEnabled =
|
||||||
|
t.bypassTransparentProxy && cfg.proxy.enable && (cfg.proxy.tun.enable || cfg.proxy.tproxy.enable);
|
||||||
|
bypassRulePriority = 8999;
|
||||||
|
|
||||||
|
mkValueArg = name: value: " args+=(${name}=${lib.escapeShellArg value})\n";
|
||||||
|
mkRawValueArg = name: value: " args+=(${name}=${toString value})\n";
|
||||||
|
mkFlagArg = condition: name: lib.optionalString condition " args+=(${name})\n";
|
||||||
|
mkOptionalValueArg =
|
||||||
|
condition: name: value:
|
||||||
|
lib.optionalString condition (mkValueArg name value);
|
||||||
|
mkRepeatedValueArgs = name: values: lib.concatMapStrings (value: mkValueArg name value) values;
|
||||||
|
dcArgs = lib.concatMapStrings (id: mkValueArg "--dc-ip" "${id}:${t.dcIps.${id}}") (
|
||||||
|
builtins.attrNames t.dcIps
|
||||||
|
);
|
||||||
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
|
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
|
||||||
exec ${tgPkg}/bin/tg-ws-proxy \
|
args=(
|
||||||
--port=${toString t.port} \
|
--port=${toString t.port}
|
||||||
--host=${t.host} \
|
--host=${lib.escapeShellArg t.host}
|
||||||
${
|
)
|
||||||
if t.secretFile != null then
|
${
|
||||||
"--secret-file=$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret"
|
if t.secretFile != null then
|
||||||
else
|
''args+=(--secret-file="$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret")''
|
||||||
"--secret=${t.secret}"
|
else
|
||||||
}${dcArgs}
|
"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"
|
||||||
|
}${
|
||||||
|
mkOptionalValueArg (t.fakeTlsDomain != null) "--fake-tls-domain" t.fakeTlsDomain
|
||||||
|
}${mkFlagArg t.proxyProtocol "--proxy-protocol"}${mkRawValueArg "--ws-keepalive" t.wsKeepalive}
|
||||||
|
exec ${tgPkg}/bin/tg-ws-proxy "''${args[@]}"
|
||||||
|
'';
|
||||||
|
|
||||||
|
bypassUpScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
add_bypass_rule -4
|
||||||
|
add_bypass_rule -6
|
||||||
|
'';
|
||||||
|
|
||||||
|
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
|
||||||
'';
|
'';
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
systemd.services.proxy-suite-tg-ws-proxy = {
|
systemd.services.proxy-suite-tg-ws-proxy = {
|
||||||
description = "Telegram MTProto WebSocket proxy";
|
description = "Telegram MTProto WebSocket proxy";
|
||||||
after = [ "network.target" ];
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
wantedBy = [ "multi-user.target" ];
|
wantedBy = [ "multi-user.target" ];
|
||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
ExecStart = "${startScript}";
|
ExecStart = "${startScript}";
|
||||||
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
|
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
|
||||||
Restart = "on-failure";
|
Restart = "on-failure";
|
||||||
RestartSec = 5;
|
RestartSec = 5;
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs transparentBypassEnabled {
|
||||||
|
ExecStartPre = bypassUpScript;
|
||||||
|
ExecStopPost = bypassDownScript;
|
||||||
|
SocketMark = toString t.routingMark;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -3,14 +3,14 @@
|
|||||||
config,
|
config,
|
||||||
lib,
|
lib,
|
||||||
pkgs,
|
pkgs,
|
||||||
|
packages,
|
||||||
cfg,
|
cfg,
|
||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
tray = cfg.tray;
|
tray = cfg.tray;
|
||||||
|
|
||||||
proxyTray = import ../../pkgs/proxy-suite-tray.nix {
|
proxyTray = packages.mkProxySuiteTray {
|
||||||
inherit pkgs;
|
|
||||||
pollInterval = tray.pollInterval;
|
pollInterval = tray.pollInterval;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+144
-139
@@ -4,13 +4,16 @@
|
|||||||
pkgs,
|
pkgs,
|
||||||
cfg,
|
cfg,
|
||||||
zapret,
|
zapret,
|
||||||
appZapretRulesFile,
|
perAppZapretRulesFile,
|
||||||
nft,
|
nft,
|
||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
z = cfg.zapret;
|
builders = import ./service/builders.nix { inherit lib pkgs; };
|
||||||
arz = cfg.appRouting.backends.zapret;
|
inherit (builders) mkOneshotService;
|
||||||
|
|
||||||
|
zapretCfg = cfg.zapret;
|
||||||
|
perAppZapretCfg = zapretCfg.perApp;
|
||||||
|
|
||||||
iptables = "${pkgs.iptables}/bin/iptables";
|
iptables = "${pkgs.iptables}/bin/iptables";
|
||||||
|
|
||||||
@@ -33,58 +36,36 @@ let
|
|||||||
;
|
;
|
||||||
};
|
};
|
||||||
|
|
||||||
hostlistRuleNames = map (rule: rule.name) z.hostlistRules;
|
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
|
||||||
|
|
||||||
baseZapretPackage =
|
baseZapretPackage =
|
||||||
let
|
let
|
||||||
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
|
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
|
||||||
in
|
in
|
||||||
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
|
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
|
||||||
|
mkOptionalHostlistFile =
|
||||||
|
fileName: entries:
|
||||||
|
if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
|
||||||
|
|
||||||
listGeneralFile =
|
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
|
||||||
if z.listGeneral != [ ] then
|
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
|
||||||
pkgs.writeText "proxy-suite-zapret-list-general-user.txt" (
|
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
|
||||||
lib.concatStringsSep "\n" z.listGeneral + "\n"
|
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
|
||||||
)
|
|
||||||
else
|
|
||||||
null;
|
|
||||||
|
|
||||||
listExcludeFile =
|
|
||||||
if z.listExclude != [ ] then
|
|
||||||
pkgs.writeText "proxy-suite-zapret-list-exclude-user.txt" (
|
|
||||||
lib.concatStringsSep "\n" z.listExclude + "\n"
|
|
||||||
)
|
|
||||||
else
|
|
||||||
null;
|
|
||||||
|
|
||||||
ipsetAllFile =
|
|
||||||
if z.ipsetAll != [ ] then
|
|
||||||
pkgs.writeText "proxy-suite-zapret-ipset-all.txt" (lib.concatStringsSep "\n" z.ipsetAll + "\n")
|
|
||||||
else
|
|
||||||
null;
|
|
||||||
|
|
||||||
ipsetExcludeFile =
|
|
||||||
if z.ipsetExclude != [ ] then
|
|
||||||
pkgs.writeText "proxy-suite-zapret-ipset-exclude-user.txt" (
|
|
||||||
lib.concatStringsSep "\n" z.ipsetExclude + "\n"
|
|
||||||
)
|
|
||||||
else
|
|
||||||
null;
|
|
||||||
|
|
||||||
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
|
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
|
||||||
builtins.toJSON {
|
builtins.toJSON {
|
||||||
includeExtraUpstreamLists = z.includeExtraUpstreamLists;
|
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
|
||||||
entries = map (rule: {
|
entries = map (rule: {
|
||||||
inherit (rule)
|
inherit (rule)
|
||||||
name
|
name
|
||||||
preset
|
preset
|
||||||
nfqwsArgs
|
nfqwsArgs
|
||||||
;
|
;
|
||||||
}) z.hostlistRules;
|
}) zapretCfg.hostlistRules;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
selectedConfigName = lib.strings.sanitizeDerivationName z.configName;
|
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
|
||||||
patchConfigScriptSrc = builtins.path {
|
patchConfigScriptSrc = builtins.path {
|
||||||
path = ../../scripts/patch-zapret-config.py;
|
path = ../../scripts/patch-zapret-config.py;
|
||||||
name = "patch-zapret-config.py";
|
name = "patch-zapret-config.py";
|
||||||
@@ -95,10 +76,10 @@ let
|
|||||||
filterMark:
|
filterMark:
|
||||||
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
|
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
|
||||||
zapret_custom_firewall_nft() {
|
zapret_custom_firewall_nft() {
|
||||||
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
|
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
|
||||||
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
|
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
|
||||||
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
|
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
|
||||||
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
|
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
|
|
||||||
@@ -106,8 +87,8 @@ let
|
|||||||
{
|
{
|
||||||
packageName,
|
packageName,
|
||||||
pidDir,
|
pidDir,
|
||||||
configName ? z.configName,
|
configName ? zapretCfg.configName,
|
||||||
gameFilter ? z.gameFilter,
|
gameFilter ? zapretCfg.gameFilter,
|
||||||
forceDisableFilterMark ? false,
|
forceDisableFilterMark ? false,
|
||||||
filterMark ? null,
|
filterMark ? null,
|
||||||
qnum ? null,
|
qnum ? null,
|
||||||
@@ -175,21 +156,32 @@ let
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
${lib.optionalString (listGeneralFile != null) ''
|
${lib.concatMapStrings
|
||||||
append_list_file list-general-user.txt ${listGeneralFile}
|
(
|
||||||
''}
|
{ name, file }:
|
||||||
|
lib.optionalString (file != null) ''
|
||||||
${lib.optionalString (listExcludeFile != null) ''
|
append_list_file ${name} ${file}
|
||||||
append_list_file list-exclude-user.txt ${listExcludeFile}
|
''
|
||||||
''}
|
)
|
||||||
|
[
|
||||||
${lib.optionalString (ipsetAllFile != null) ''
|
{
|
||||||
append_list_file ipset-all.txt ${ipsetAllFile}
|
name = "list-general-user.txt";
|
||||||
''}
|
file = listGeneralFile;
|
||||||
|
}
|
||||||
${lib.optionalString (ipsetExcludeFile != null) ''
|
{
|
||||||
append_list_file ipset-exclude-user.txt ${ipsetExcludeFile}
|
name = "list-exclude-user.txt";
|
||||||
''}
|
file = listExcludeFile;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
name = "ipset-all.txt";
|
||||||
|
file = ipsetAllFile;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
name = "ipset-exclude-user.txt";
|
||||||
|
file = ipsetExcludeFile;
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
|
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
|
||||||
${lib.optionalString (gameFilter != "null") ''
|
${lib.optionalString (gameFilter != "null") ''
|
||||||
@@ -206,31 +198,42 @@ let
|
|||||||
''
|
''
|
||||||
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
|
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
|
||||||
''
|
''
|
||||||
) z.hostlistRules}
|
) zapretCfg.hostlistRules}
|
||||||
|
|
||||||
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
|
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
|
||||||
|
|
||||||
${lib.optionalString forceDisableFilterMark ''
|
${lib.optionalString forceDisableFilterMark ''
|
||||||
set_config_var FILTER_MARK ""
|
set_config_var FILTER_MARK ""
|
||||||
''}
|
''}
|
||||||
${lib.optionalString (filterMark != null) ''
|
${lib.concatMapStrings
|
||||||
filter_mark_hex=$(printf '0x%x' ${toString filterMark})
|
(
|
||||||
set_config_var FILTER_MARK "$filter_mark_hex"
|
{ var, value }:
|
||||||
''}
|
lib.optionalString (value != null) ''
|
||||||
|
hex=$(printf '0x%x' ${toString value})
|
||||||
|
set_config_var ${var} "$hex"
|
||||||
|
''
|
||||||
|
)
|
||||||
|
[
|
||||||
|
{
|
||||||
|
var = "FILTER_MARK";
|
||||||
|
value = filterMark;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
var = "DESYNC_MARK";
|
||||||
|
value = desyncMark;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
var = "DESYNC_MARK_POSTNAT";
|
||||||
|
value = desyncMarkPostnat;
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
${lib.optionalString (qnum != null) ''
|
${lib.optionalString (qnum != null) ''
|
||||||
set_config_var QNUM ${toString qnum}
|
set_config_var QNUM ${toString qnum}
|
||||||
''}
|
''}
|
||||||
${lib.optionalString (modeFilter != null) ''
|
${lib.optionalString (modeFilter != null) ''
|
||||||
set_config_var MODE_FILTER ${modeFilter}
|
set_config_var MODE_FILTER ${modeFilter}
|
||||||
''}
|
''}
|
||||||
${lib.optionalString (desyncMark != null) ''
|
|
||||||
desync_mark_hex=$(printf '0x%x' ${toString desyncMark})
|
|
||||||
set_config_var DESYNC_MARK "$desync_mark_hex"
|
|
||||||
''}
|
|
||||||
${lib.optionalString (desyncMarkPostnat != null) ''
|
|
||||||
desync_mark_postnat_hex=$(printf '0x%x' ${toString desyncMarkPostnat})
|
|
||||||
set_config_var DESYNC_MARK_POSTNAT "$desync_mark_postnat_hex"
|
|
||||||
''}
|
|
||||||
${lib.optionalString (nftTable != null) ''
|
${lib.optionalString (nftTable != null) ''
|
||||||
set_config_var ZAPRET_NFT_TABLE ${nftTable}
|
set_config_var ZAPRET_NFT_TABLE ${nftTable}
|
||||||
''}
|
''}
|
||||||
@@ -245,21 +248,22 @@ let
|
|||||||
globalZapretPackage = mkDerivedZapretPackage {
|
globalZapretPackage = mkDerivedZapretPackage {
|
||||||
packageName = "proxy-suite-zapret-${selectedConfigName}";
|
packageName = "proxy-suite-zapret-${selectedConfigName}";
|
||||||
pidDir = "/run/proxy-suite-zapret";
|
pidDir = "/run/proxy-suite-zapret";
|
||||||
gameFilter = z.gameFilter;
|
gameFilter = zapretCfg.gameFilter;
|
||||||
forceDisableFilterMark = true;
|
forceDisableFilterMark = true;
|
||||||
customScript = if arz.enable then mkGlobalBypassScript (toString arz.filterMark) else null;
|
customScript =
|
||||||
|
if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null;
|
||||||
};
|
};
|
||||||
|
|
||||||
appZapretPackage = mkDerivedZapretPackage {
|
perAppZapretPackage = mkDerivedZapretPackage {
|
||||||
packageName = "proxy-suite-app-zapret-${selectedConfigName}";
|
packageName = "proxy-suite-per-app-zapret-${selectedConfigName}";
|
||||||
pidDir = "/run/proxy-suite-app-zapret";
|
pidDir = "/run/proxy-suite-per-app-zapret";
|
||||||
gameFilter = "all";
|
gameFilter = "all";
|
||||||
filterMark = arz.filterMark;
|
filterMark = perAppZapretCfg.filterMark;
|
||||||
qnum = arz.qnum;
|
qnum = perAppZapretCfg.qnum;
|
||||||
modeFilter = "none";
|
modeFilter = "none";
|
||||||
desyncMark = 134217728;
|
desyncMark = 134217728;
|
||||||
desyncMarkPostnat = 67108864;
|
desyncMarkPostnat = 67108864;
|
||||||
nftTable = "proxy_suite_app_zapret";
|
nftTable = "proxy_suite_per_app_zapret";
|
||||||
};
|
};
|
||||||
|
|
||||||
zapretCommonPreStart = package: ''
|
zapretCommonPreStart = package: ''
|
||||||
@@ -274,36 +278,41 @@ let
|
|||||||
fi
|
fi
|
||||||
'';
|
'';
|
||||||
|
|
||||||
globalZapretEnv = [
|
mkZapretEnv = package: [
|
||||||
"ZAPRET_BASE=${globalZapretPackage}/opt/zapret"
|
"ZAPRET_BASE=${package}/opt/zapret"
|
||||||
"PATH=${lib.makeBinPath runtimeDeps}"
|
"PATH=${lib.makeBinPath runtimeDeps}"
|
||||||
];
|
];
|
||||||
|
globalZapretEnv = mkZapretEnv globalZapretPackage;
|
||||||
|
perAppZapretEnv = mkZapretEnv perAppZapretPackage;
|
||||||
|
|
||||||
appZapretEnv = [
|
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-up" ''
|
||||||
"ZAPRET_BASE=${appZapretPackage}/opt/zapret"
|
|
||||||
"PATH=${lib.makeBinPath runtimeDeps}"
|
|
||||||
];
|
|
||||||
|
|
||||||
appZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-app-zapret-mark-up" ''
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
${nft} delete table inet proxy_suite_app_zapret_mark 2>/dev/null || true
|
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
|
||||||
${nft} -f ${appZapretRulesFile}
|
${nft} -f ${perAppZapretRulesFile}
|
||||||
'';
|
'';
|
||||||
|
|
||||||
appZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-app-zapret-mark-down" ''
|
perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-down" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
${nft} delete table inet proxy_suite_app_zapret_mark 2>/dev/null || true
|
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
|
||||||
'';
|
'';
|
||||||
|
|
||||||
exemptStart = lib.concatMapStrings (cidr: ''
|
exemptStart = ''
|
||||||
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
set -euo pipefail
|
||||||
|
''
|
||||||
|
+ lib.concatMapStrings (cidr: ''
|
||||||
|
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||||
|
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||||
|
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
||||||
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
|
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
|
||||||
'') z.cidrExemption.cidrs;
|
'') zapretCfg.cidrExemption.cidrs;
|
||||||
|
|
||||||
exemptStop = lib.concatMapStrings (cidr: ''
|
exemptStop = ''
|
||||||
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true
|
set +e
|
||||||
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true
|
''
|
||||||
'') z.cidrExemption.cidrs;
|
+ lib.concatMapStrings (cidr: ''
|
||||||
|
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||||
|
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||||
|
'') zapretCfg.cidrExemption.cidrs;
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
assertions = [
|
assertions = [
|
||||||
@@ -312,66 +321,62 @@ in
|
|||||||
message = "proxy-suite: zapret.hostlistRules names must be unique";
|
message = "proxy-suite: zapret.hostlistRules names must be unique";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = builtins.all (rule: rule.domains != [ ]) z.hostlistRules;
|
assertion = builtins.all (rule: rule.domains != [ ]) zapretCfg.hostlistRules;
|
||||||
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
|
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = builtins.all (rule: rule.preset != null || rule.nfqwsArgs != [ ]) z.hostlistRules;
|
assertion = builtins.all (
|
||||||
|
rule: rule.preset != null || rule.nfqwsArgs != [ ]
|
||||||
|
) zapretCfg.hostlistRules;
|
||||||
message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both";
|
message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both";
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
environment.systemPackages =
|
environment.systemPackages = lib.mkBefore (
|
||||||
lib.mkBefore (
|
lib.optionals zapretCfg.enable [ globalZapretPackage ]
|
||||||
[ globalZapretPackage ] ++ lib.optionals arz.enable [ appZapretPackage ]
|
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
|
||||||
);
|
);
|
||||||
|
|
||||||
systemd.services.zapret-discord-youtube = {
|
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService {
|
||||||
description = "zapret DPI bypass";
|
description = "zapret DPI bypass";
|
||||||
after = [ "network.target" ];
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
wantedBy = [ "multi-user.target" ];
|
wantedBy = [ "multi-user.target" ];
|
||||||
preStart = zapretCommonPreStart globalZapretPackage;
|
preStart = zapretCommonPreStart globalZapretPackage;
|
||||||
serviceConfig = {
|
runtimeDirectory = "proxy-suite-zapret";
|
||||||
Type = "oneshot";
|
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||||
RemainAfterExit = true;
|
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||||
RuntimeDirectory = "proxy-suite-zapret";
|
extraServiceConfig = {
|
||||||
ExecStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
|
||||||
ExecStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
|
||||||
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
|
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
|
||||||
Environment = globalZapretEnv;
|
Environment = globalZapretEnv;
|
||||||
};
|
};
|
||||||
};
|
});
|
||||||
|
|
||||||
systemd.services.proxy-suite-app-zapret = lib.mkIf arz.enable {
|
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
|
||||||
description = "proxy-suite app-routing zapret backend";
|
description = "proxy-suite per-app-routing zapret backend";
|
||||||
after = [ "network.target" ];
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
conflicts = [
|
conflicts = [
|
||||||
"proxy-suite-tproxy.service"
|
"proxy-suite-tproxy.service"
|
||||||
"proxy-suite-tun.service"
|
"proxy-suite-tun.service"
|
||||||
];
|
];
|
||||||
preStart = zapretCommonPreStart appZapretPackage;
|
preStart = zapretCommonPreStart perAppZapretPackage;
|
||||||
serviceConfig = {
|
runtimeDirectory = "proxy-suite-per-app-zapret";
|
||||||
Type = "oneshot";
|
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||||
RemainAfterExit = true;
|
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||||
RuntimeDirectory = "proxy-suite-app-zapret";
|
execStartPre = "${perAppZapretMarkUpScript}";
|
||||||
ExecStartPre = "${appZapretMarkUpScript}";
|
execStopPost = "${perAppZapretMarkDownScript}";
|
||||||
ExecStart = "${appZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
extraServiceConfig.Environment = perAppZapretEnv;
|
||||||
ExecStop = "${appZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
});
|
||||||
ExecStopPost = "${appZapretMarkDownScript}";
|
|
||||||
Environment = appZapretEnv;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf z.cidrExemption.enable {
|
systemd.services.proxy-suite-zapret-vm-exempt =
|
||||||
description = "Exempt CIDRs from zapret NFQUEUE";
|
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable)
|
||||||
after = [ "zapret-discord-youtube.service" ];
|
(mkOneshotService {
|
||||||
wants = [ "zapret-discord-youtube.service" ];
|
description = "Exempt CIDRs from zapret NFQUEUE";
|
||||||
wantedBy = [ "multi-user.target" ];
|
after = [ "zapret-discord-youtube.service" ];
|
||||||
serviceConfig = {
|
wants = [ "zapret-discord-youtube.service" ];
|
||||||
Type = "oneshot";
|
wantedBy = [ "multi-user.target" ];
|
||||||
RemainAfterExit = true;
|
execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
|
||||||
ExecStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
|
execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
|
||||||
ExecStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
|
});
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
+2225
-710
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
|||||||
|
{ pkgs }:
|
||||||
|
|
||||||
|
{
|
||||||
|
build-outbound-parser =
|
||||||
|
pkgs.runCommand "build-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||||
|
''
|
||||||
|
export PYTHONDONTWRITEBYTECODE=1
|
||||||
|
export PYTHONPATH=${../../scripts}:$PYTHONPATH
|
||||||
|
python ${../../scripts/test-build-outbound.py}
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
|
||||||
|
fetch-subscription-parser =
|
||||||
|
pkgs.runCommand "fetch-subscription-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||||
|
''
|
||||||
|
export PYTHONDONTWRITEBYTECODE=1
|
||||||
|
export PYTHONPATH=${../../scripts}:$PYTHONPATH
|
||||||
|
python ${../../scripts/test-fetch-subscription.py}
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
pkgs,
|
||||||
|
rg,
|
||||||
|
generatedOptionsDoc,
|
||||||
|
generatedReadmeDoc,
|
||||||
|
readmeDocSource,
|
||||||
|
trayModuleSource,
|
||||||
|
tgWsProxyModuleSource,
|
||||||
|
controlModuleSource,
|
||||||
|
}:
|
||||||
|
|
||||||
|
{
|
||||||
|
no-secrets = pkgs.runCommand "proxy-suite-no-secrets-check" { } ''
|
||||||
|
repo_root=${../../.}
|
||||||
|
if ${rg} --pcre2 -n -I -H -S \
|
||||||
|
-e '-----BEGIN (RSA|DSA|EC|OPENSSH|PGP) PRIVATE KEY-----' \
|
||||||
|
-e 'ghp_[A-Za-z0-9]{36}' \
|
||||||
|
-e 'github_pat_[A-Za-z0-9_]{20,}' \
|
||||||
|
-e 'glpat-[A-Za-z0-9_-]{20,}' \
|
||||||
|
-e 'xox[baprs]-[A-Za-z0-9-]{10,}' \
|
||||||
|
-e 'AKIA[0-9A-Z]{16}' \
|
||||||
|
-e 'AIza[0-9A-Za-z_-]{35}' \
|
||||||
|
-e 'sk-(proj-)?[A-Za-z0-9_-]{20,}' \
|
||||||
|
"$repo_root"; then
|
||||||
|
echo "secret-like content detected in source tree" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
|
||||||
|
options-doc = pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||||
|
diff -u ${../../docs/options.md} ${generatedOptionsDoc}
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
|
||||||
|
readme-doc = pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||||
|
diff -u ${../../README.md} ${generatedReadmeDoc}
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
|
||||||
|
readme-doc-source = builtins.seq
|
||||||
|
(
|
||||||
|
assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource);
|
||||||
|
assert !(pkgs.lib.hasInfix "packageByPattern" readmeDocSource);
|
||||||
|
true
|
||||||
|
)
|
||||||
|
(pkgs.writeText "proxy-suite-readme-doc-source-check" "ok");
|
||||||
|
|
||||||
|
package-source = builtins.seq
|
||||||
|
(
|
||||||
|
assert !(pkgs.lib.hasInfix "../../pkgs/proxy-suite-tray.nix" trayModuleSource);
|
||||||
|
assert !(pkgs.lib.hasInfix "../../pkgs/tg-ws-proxy.nix" tgWsProxyModuleSource);
|
||||||
|
assert !(pkgs.lib.hasInfix "../../../pkgs/proxy-ctl.nix" controlModuleSource);
|
||||||
|
true
|
||||||
|
)
|
||||||
|
(pkgs.writeText "proxy-suite-package-source-check" "ok");
|
||||||
|
}
|
||||||
+61
-9
@@ -19,6 +19,41 @@ let
|
|||||||
];
|
];
|
||||||
};
|
};
|
||||||
filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module");
|
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" ]
|
||||||
|
// {
|
||||||
|
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 =
|
mkGeneratedExampleValue =
|
||||||
option:
|
option:
|
||||||
if (option ? _type) && option._type == "option" then
|
if (option ? _type) && option._type == "option" then
|
||||||
@@ -32,10 +67,10 @@ let
|
|||||||
throw "Cannot generate example value for option ${lib.showOption option.loc}"
|
throw "Cannot generate example value for option ${lib.showOption option.loc}"
|
||||||
else
|
else
|
||||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option);
|
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option);
|
||||||
defaultConfigText = lib.generators.toPretty { } eval.config.services.proxy-suite;
|
defaultConfigText = renderConfigText eval.config.services.proxy-suite;
|
||||||
exampleConfigText = lib.generators.toPretty { } (
|
generatedExampleConfig =
|
||||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite)
|
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite);
|
||||||
);
|
exampleConfigText = renderConfigText (builtins.removeAttrs generatedExampleConfig [ "singBox" ]);
|
||||||
repoRoot = toString ../.;
|
repoRoot = toString ../.;
|
||||||
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
|
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
|
||||||
transformDeclaration =
|
transformDeclaration =
|
||||||
@@ -73,7 +108,7 @@ pkgs.runCommand "proxy-suite-options.md" { } ''
|
|||||||
cat >"$preamble" <<'EOF'
|
cat >"$preamble" <<'EOF'
|
||||||
# proxy-suite options
|
# proxy-suite options
|
||||||
|
|
||||||
This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options.nix`](modules/proxy-suite/options.nix).
|
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.
|
Update module option docs there instead of editing this file by hand.
|
||||||
|
|
||||||
## Table of contents
|
## Table of contents
|
||||||
@@ -227,8 +262,25 @@ pkgs.runCommand "proxy-suite-options.md" { } ''
|
|||||||
}
|
}
|
||||||
' "$section_index"
|
' "$section_index"
|
||||||
|
|
||||||
cat "$preamble" >"$out"
|
raw="$TMPDIR/options.md.raw"
|
||||||
cat "$toc" >>"$out"
|
|
||||||
printf '\n' >>"$out"
|
cat "$preamble" >"$raw"
|
||||||
cat "$sections_with_anchors" >>"$out"
|
cat "$toc" >>"$raw"
|
||||||
|
printf '\n' >>"$raw"
|
||||||
|
cat "$sections_with_anchors" >>"$raw"
|
||||||
|
|
||||||
|
awk '
|
||||||
|
NF {
|
||||||
|
for (i = 0; i < blanks; i++) {
|
||||||
|
print ""
|
||||||
|
}
|
||||||
|
blanks = 0
|
||||||
|
print
|
||||||
|
next
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
blanks++
|
||||||
|
}
|
||||||
|
' "$raw" >"$out"
|
||||||
''
|
''
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
system.stateVersion = "26.05";
|
||||||
|
|
||||||
|
services.proxy-suite = {
|
||||||
|
enable = true;
|
||||||
|
|
||||||
|
proxy = {
|
||||||
|
enable = true;
|
||||||
|
singBox.enable = true;
|
||||||
|
outbounds = [
|
||||||
|
{
|
||||||
|
tag = "primary";
|
||||||
|
url = "http://proxy.example.com:8080";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
{
|
||||||
|
nixpkgs,
|
||||||
|
pkgsFor,
|
||||||
|
proxySuiteModule,
|
||||||
|
zapret,
|
||||||
|
}:
|
||||||
|
|
||||||
|
system:
|
||||||
|
|
||||||
|
let
|
||||||
|
pkgs = pkgsFor system;
|
||||||
|
packages = import ../pkgs/default.nix { inherit pkgs; };
|
||||||
|
fixture = import ./readme-doc-fixture.nix;
|
||||||
|
eval = import "${nixpkgs}/nixos/lib/eval-config.nix" {
|
||||||
|
inherit system;
|
||||||
|
modules = [
|
||||||
|
proxySuiteModule
|
||||||
|
fixture
|
||||||
|
];
|
||||||
|
};
|
||||||
|
cfg = eval.config.services.proxy-suite;
|
||||||
|
rules = import ../modules/proxy-suite/rules.nix {
|
||||||
|
lib = pkgs.lib;
|
||||||
|
inherit pkgs cfg zapret;
|
||||||
|
};
|
||||||
|
configs = import ../modules/proxy-suite/config.nix {
|
||||||
|
lib = pkgs.lib;
|
||||||
|
inherit pkgs cfg rules;
|
||||||
|
};
|
||||||
|
nftr = import ../modules/proxy-suite/nftables.nix {
|
||||||
|
lib = pkgs.lib;
|
||||||
|
inherit pkgs cfg;
|
||||||
|
};
|
||||||
|
context = import ../modules/proxy-suite/service/context.nix {
|
||||||
|
lib = pkgs.lib;
|
||||||
|
inherit
|
||||||
|
pkgs
|
||||||
|
packages
|
||||||
|
cfg
|
||||||
|
;
|
||||||
|
inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile;
|
||||||
|
inherit (nftr) perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile ip nft;
|
||||||
|
};
|
||||||
|
in
|
||||||
|
pkgs.runCommand "proxy-suite-README.md" { nativeBuildInputs = [ pkgs.python3 ]; } ''
|
||||||
|
src=${../README.md}
|
||||||
|
help_file="$TMPDIR/proxy-ctl-help.txt"
|
||||||
|
export src help_file
|
||||||
|
|
||||||
|
${context.control.proxyCtl}/bin/proxy-ctl help > "$help_file"
|
||||||
|
|
||||||
|
python <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
|
||||||
|
src = Path(os.environ["src"])
|
||||||
|
help_file = Path(os.environ["help_file"])
|
||||||
|
out = Path(os.environ["out"])
|
||||||
|
|
||||||
|
start_marker = "<!-- proxy-ctl-help:start -->"
|
||||||
|
end_marker = "<!-- proxy-ctl-help:end -->"
|
||||||
|
|
||||||
|
readme = src.read_text()
|
||||||
|
help_text = help_file.read_text().rstrip("\n")
|
||||||
|
replacement = f"{start_marker}\n```text\n{help_text}\n```\n{end_marker}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
start = readme.index(start_marker)
|
||||||
|
end = readme.index(end_marker) + len(end_marker)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise SystemExit(f"README markers missing: {exc}")
|
||||||
|
|
||||||
|
out.write_text(readme[:start] + replacement + readme[end:])
|
||||||
|
PY
|
||||||
|
''
|
||||||
+15
-1
@@ -1,4 +1,18 @@
|
|||||||
{ pkgs }:
|
{ pkgs }:
|
||||||
|
let
|
||||||
|
mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; };
|
||||||
|
mkProxySuiteTray = args: import ./proxy-suite-tray.nix ({ inherit pkgs; } // args);
|
||||||
|
mkProxyCtl = import ./proxy-ctl.nix {
|
||||||
|
lib = pkgs.lib;
|
||||||
|
inherit pkgs;
|
||||||
|
};
|
||||||
|
in
|
||||||
{
|
{
|
||||||
tg-ws-proxy = import ./tg-ws-proxy.nix { inherit pkgs; };
|
inherit
|
||||||
|
mkTgWsProxy
|
||||||
|
mkProxySuiteTray
|
||||||
|
mkProxyCtl
|
||||||
|
;
|
||||||
|
tg-ws-proxy = mkTgWsProxy { };
|
||||||
|
proxy-suite-tray = mkProxySuiteTray { };
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
ALL_SERVICES=(
|
||||||
|
proxy-suite-socks
|
||||||
|
proxy-suite-tproxy
|
||||||
|
proxy-suite-tun
|
||||||
|
proxy-suite-tg-ws-proxy
|
||||||
|
proxy-suite-zapret-vm-exempt
|
||||||
|
zapret-discord-youtube
|
||||||
|
)
|
||||||
|
|
||||||
|
_usage() {
|
||||||
|
local status="${1:-1}"
|
||||||
|
echo "Usage: proxy-ctl <command> [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 " 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 <tag> switch to a specific outbound (selector mode)"
|
||||||
|
echo " apps list configured per-app routing profiles"
|
||||||
|
echo " wrap <profile> -- <cmd> 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"
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
|
||||||
|
_bool() {
|
||||||
|
if "$@"; then
|
||||||
|
printf true
|
||||||
|
else
|
||||||
|
printf false
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_svc_exists() {
|
||||||
|
systemctl cat "$1" &>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
_svc_active() {
|
||||||
|
systemctl is-active --quiet "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
_require_service() {
|
||||||
|
local svc="$1" message="$2"
|
||||||
|
if ! _svc_exists "$svc"; then
|
||||||
|
echo "$message"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_stop_if_exists() {
|
||||||
|
local svc="$1"
|
||||||
|
if _svc_exists "$svc"; then
|
||||||
|
systemctl stop "$svc" || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_route_mode_default() {
|
||||||
|
printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}"
|
||||||
|
}
|
||||||
|
|
||||||
|
_route_mode_effective() {
|
||||||
|
local mode=""
|
||||||
|
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
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
_route_mode_current() {
|
||||||
|
if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then
|
||||||
|
_route_mode_effective
|
||||||
|
else
|
||||||
|
printf 'default'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_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'
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
_status_tray() {
|
||||||
|
local pair key svc
|
||||||
|
for pair in \
|
||||||
|
socks:proxy-suite-socks \
|
||||||
|
tproxy:proxy-suite-tproxy \
|
||||||
|
tun:proxy-suite-tun \
|
||||||
|
zapret:zapret-discord-youtube; do
|
||||||
|
key="${pair%%:*}"
|
||||||
|
svc="${pair##*:}"
|
||||||
|
printf '%s_available=%s\n' "$key" "$(_bool _svc_exists "$svc")"
|
||||||
|
printf '%s_active=%s\n' "$key" "$(_bool _svc_active "$svc")"
|
||||||
|
done
|
||||||
|
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
|
||||||
|
printf 'route_mode_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||||
|
printf 'route_mode=%s\n' "$(_route_mode_current)"
|
||||||
|
printf 'default_route_mode=%s\n' "$(_route_mode_default)"
|
||||||
|
}
|
||||||
|
|
||||||
|
_ensure_app_routing() {
|
||||||
|
if [ "$PER_APP_ROUTING_ENABLED" != "1" ]; then
|
||||||
|
echo "perAppRouting is not enabled in services.proxy-suite.perAppRouting."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_profile_route() {
|
||||||
|
local profile="$1"
|
||||||
|
jq -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$PER_APP_ROUTING_PROFILES_FILE"
|
||||||
|
}
|
||||||
|
|
||||||
|
_scope_running() {
|
||||||
|
systemctl --user list-units --type=scope --state=running --plain --no-legend "$1-*" \
|
||||||
|
| grep -q .
|
||||||
|
}
|
||||||
|
|
||||||
|
_any_user_active() {
|
||||||
|
systemctl list-units --type=service --state=active --plain --no-legend "$1*.service" \
|
||||||
|
| grep -q .
|
||||||
|
}
|
||||||
|
|
||||||
|
_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
|
||||||
|
}
|
||||||
|
|
||||||
|
_cleanup_slice_if_idle() {
|
||||||
|
local slice_base="$1" anchor_unit="$2" user_svc="$3" backend_svc="$4"
|
||||||
|
|
||||||
|
if ! _scope_running "$slice_base"; then
|
||||||
|
systemctl stop "$user_svc" || true
|
||||||
|
systemctl --user stop "$anchor_unit" || true
|
||||||
|
if ! _any_user_active "$slice_base-user@"; then
|
||||||
|
systemctl stop "$backend_svc" || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
|
||||||
|
_wrap_slice() {
|
||||||
|
local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
|
||||||
|
shift 4
|
||||||
|
if [ "$enabled" != "1" ]; then
|
||||||
|
echo "$disabled_msg"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
local uid; uid="$(id -u)"
|
||||||
|
local scope_unit="$slice_base-${profile}-$$"
|
||||||
|
local anchor_unit="$slice_base-anchor.service"
|
||||||
|
local user_svc="$slice_base-user@$uid.service"
|
||||||
|
local status=0
|
||||||
|
|
||||||
|
cleanup_slice() {
|
||||||
|
_cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc"
|
||||||
|
}
|
||||||
|
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
|
||||||
|
if [ "$status" -eq 0 ]; then
|
||||||
|
systemd-run --user --scope --quiet --collect --same-dir \
|
||||||
|
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd_status() {
|
||||||
|
if [ "${1:-}" = "--tray" ]; then
|
||||||
|
_status_tray
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "proxy-suite services:"
|
||||||
|
for svc in "${ALL_SERVICES[@]}"; do
|
||||||
|
_svc_status "$svc"
|
||||||
|
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-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
|
||||||
|
}
|
||||||
|
|
||||||
|
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 <outbound-tag>}"
|
||||||
|
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 <profile> -- <command> [args...]}"
|
||||||
|
shift || true
|
||||||
|
if [ "${1:-}" = "--" ]; then
|
||||||
|
shift
|
||||||
|
fi
|
||||||
|
if [ "$#" -eq 0 ]; then
|
||||||
|
echo "Usage: proxy-ctl wrap <profile> -- <command> [args...]"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
_ensure_app_routing
|
||||||
|
route="$(_profile_route "$profile")"
|
||||||
|
if [ -z "$route" ] || [ "$route" = "null" ]; then
|
||||||
|
echo "Unknown perAppRouting profile: $profile"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "$route" in
|
||||||
|
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
|
||||||
|
exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@"
|
||||||
|
;;
|
||||||
|
tun)
|
||||||
|
_check_no_global_proxy tun
|
||||||
|
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \
|
||||||
|
"Profile '$profile' uses route=tun, but proxy.tun.perApp.enable is false." \
|
||||||
|
"proxy-suite-per-app-tun.service" "$@"
|
||||||
|
;;
|
||||||
|
tproxy)
|
||||||
|
_check_no_global_proxy tproxy
|
||||||
|
_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \
|
||||||
|
"Profile '$profile' uses route=tproxy, but proxy.tproxy.perApp.enable is false." \
|
||||||
|
"proxy-suite-per-app-tproxy.service" "$@"
|
||||||
|
;;
|
||||||
|
zapret)
|
||||||
|
_check_no_global_proxy zapret
|
||||||
|
_wrap_slice "proxy-suite-per-app-zapret" "$PER_APP_ROUTING_ZAPRET_ENABLED" \
|
||||||
|
"Profile '$profile' uses route=zapret, but zapret.perApp.enable is false." \
|
||||||
|
"proxy-suite-per-app-zapret.service" "$@"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Route backend '$route' is not implemented in this build."
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd_subscription() {
|
||||||
|
local subcmd cache age count t
|
||||||
|
subcmd="${1:-list}"
|
||||||
|
shift || true
|
||||||
|
|
||||||
|
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=$(jq 'length' "$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
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
}:
|
||||||
|
|
||||||
|
{
|
||||||
|
clashApi,
|
||||||
|
selection,
|
||||||
|
subscriptionTagsFile,
|
||||||
|
subscriptionCacheDir,
|
||||||
|
perAppRoutingEnabled,
|
||||||
|
perAppRoutingProxychainsEnabled,
|
||||||
|
perAppRoutingTunEnabled,
|
||||||
|
perAppRoutingTproxyEnabled,
|
||||||
|
perAppRoutingZapretEnabled,
|
||||||
|
perAppRoutingProfilesFile,
|
||||||
|
proxychainsConfigFile,
|
||||||
|
proxychainsQuietArg,
|
||||||
|
routeModeStateFile,
|
||||||
|
defaultRouteMode,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
unwrapped = pkgs.writeShellScriptBin "proxy-ctl" (
|
||||||
|
builtins.readFile ./proxy-ctl-lib.sh + "\n" + builtins.readFile ./proxy-ctl.sh
|
||||||
|
);
|
||||||
|
in
|
||||||
|
pkgs.symlinkJoin {
|
||||||
|
name = "proxy-ctl";
|
||||||
|
paths = [ unwrapped ];
|
||||||
|
nativeBuildInputs = [ pkgs.makeWrapper ];
|
||||||
|
postBuild = ''
|
||||||
|
wrapProgram "$out/bin/proxy-ctl" \
|
||||||
|
--prefix PATH : "${
|
||||||
|
lib.makeBinPath [
|
||||||
|
pkgs.coreutils
|
||||||
|
pkgs.curl
|
||||||
|
pkgs.gawk
|
||||||
|
pkgs.gnugrep
|
||||||
|
pkgs.jq
|
||||||
|
pkgs.proxychains-ng
|
||||||
|
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}
|
||||||
|
'';
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Wrapped binary provides runtime config through env vars.
|
||||||
|
SUB_TAGS_FILE="${SUB_TAGS_FILE:-}"
|
||||||
|
PROXYCHAINS_QUIET_ARG="${PROXYCHAINS_QUIET_ARG:-}"
|
||||||
|
SUB_TAGS=()
|
||||||
|
|
||||||
|
if [ -n "$SUB_TAGS_FILE" ] && [ -f "$SUB_TAGS_FILE" ]; then
|
||||||
|
mapfile -t SUB_TAGS < <(jq -r '.[]' "$SUB_TAGS_FILE")
|
||||||
|
fi
|
||||||
|
|
||||||
|
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:-}"
|
||||||
|
;;
|
||||||
|
|
||||||
|
route-mode)
|
||||||
|
cmd_route_mode "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
zapret)
|
||||||
|
cmd_zapret "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
restart)
|
||||||
|
cmd_restart
|
||||||
|
;;
|
||||||
|
|
||||||
|
logs)
|
||||||
|
svc="${1:-proxy-suite-socks}"
|
||||||
|
shift || true
|
||||||
|
exec journalctl -fu "$svc" "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
outbounds)
|
||||||
|
cmd_outbounds
|
||||||
|
;;
|
||||||
|
|
||||||
|
select)
|
||||||
|
cmd_select "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
apps)
|
||||||
|
cmd_apps
|
||||||
|
;;
|
||||||
|
|
||||||
|
wrap)
|
||||||
|
cmd_wrap "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
subscription)
|
||||||
|
cmd_subscription "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
*)
|
||||||
|
_usage 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
@@ -21,7 +21,7 @@ pkgs.stdenv.mkDerivation {
|
|||||||
-DSYSTEMCTL_BIN='"${pkgs.systemd}/bin/systemctl"' \
|
-DSYSTEMCTL_BIN='"${pkgs.systemd}/bin/systemctl"' \
|
||||||
-DPKEXEC_BIN='"/run/wrappers/bin/pkexec"' \
|
-DPKEXEC_BIN='"/run/wrappers/bin/pkexec"' \
|
||||||
-DPOLL_INTERVAL=${toString pollInterval} \
|
-DPOLL_INTERVAL=${toString pollInterval} \
|
||||||
-O2 -Wall
|
-O2 -Wall -Werror=discarded-qualifiers
|
||||||
'';
|
'';
|
||||||
|
|
||||||
installPhase = ''
|
installPhase = ''
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||||
<!-- Gold shield: TUN/TProxy active -->
|
<!-- Purple shield: TUN/TProxy active -->
|
||||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||||
fill="#FFC107" stroke="#F57F17" stroke-width="0.8"/>
|
fill="#9C27B0" stroke="#4A148C" stroke-width="0.8"/>
|
||||||
<!-- Up arrow: traffic routed through tunnel -->
|
<!-- Up arrow: traffic routed through tunnel -->
|
||||||
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
|
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
|
||||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 497 B After Width: | Height: | Size: 499 B |
+536
-197
File diff suppressed because it is too large.
Load diff
@@ -4,8 +4,8 @@ let
|
|||||||
src = pkgs.fetchFromGitHub {
|
src = pkgs.fetchFromGitHub {
|
||||||
owner = "Flowseal";
|
owner = "Flowseal";
|
||||||
repo = "tg-ws-proxy";
|
repo = "tg-ws-proxy";
|
||||||
rev = "v1.6.1";
|
rev = "v1.7.3";
|
||||||
hash = "sha256-7dFHrD8lrxzQsjGanCWao5zEIIx+swcKRKo+mI/fMlQ=";
|
hash = "sha256-b9Dmh41PEC3LZDhaSILUDrLApDgP0IiKXn//cvLfm9o=";
|
||||||
};
|
};
|
||||||
|
|
||||||
pythonEnv = pkgs.python3.withPackages (
|
pythonEnv = pkgs.python3.withPackages (
|
||||||
|
|||||||
+12
-357
@@ -1,379 +1,34 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""Read a proxy URL from stdin and emit a backend outbound JSON object."""
|
||||||
Read a proxy URL from stdin, emit a sing-box outbound JSON object to stdout.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
echo "vless://..." | build-outbound.py --tag my-server [--routing-mark 2]
|
|
||||||
|
|
||||||
Supported schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
|
|
||||||
socks5, socks5h, socks4, socks4a, http, https
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import base64
|
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
import urllib.parse
|
|
||||||
|
|
||||||
|
from proxy_parsing import build_outbound
|
||||||
def _qs(query: str) -> dict:
|
|
||||||
return dict(urllib.parse.parse_qsl(query))
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
|
|
||||||
"""Strip scheme+fragment, return (userinfo, host, port_str, params).
|
|
||||||
userinfo is "" when no '@' is present."""
|
|
||||||
rest = url[len(f"{scheme}://"):]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
if "@" in rest:
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
else:
|
|
||||||
userinfo = ""
|
|
||||||
hostpart, _, query = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
return userinfo, host, port, _qs(query)
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_transport(
|
|
||||||
transport_type: str,
|
|
||||||
path: str = "/",
|
|
||||||
host_header: str = "",
|
|
||||||
service_name: str = "",
|
|
||||||
) -> "dict | None":
|
|
||||||
"""Build a sing-box transport dict for ws/grpc/h2. Returns None for tcp."""
|
|
||||||
if transport_type == "ws":
|
|
||||||
return {
|
|
||||||
"type": "ws",
|
|
||||||
"path": urllib.parse.unquote(path),
|
|
||||||
"headers": {"Host": host_header},
|
|
||||||
}
|
|
||||||
elif transport_type == "grpc":
|
|
||||||
return {
|
|
||||||
"type": "grpc",
|
|
||||||
"service_name": urllib.parse.unquote(service_name),
|
|
||||||
}
|
|
||||||
elif transport_type == "h2":
|
|
||||||
return {
|
|
||||||
"type": "http",
|
|
||||||
"host": [host_header],
|
|
||||||
"path": urllib.parse.unquote(path),
|
|
||||||
}
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def parse_vless(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
vless://UUID@HOST:PORT?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=SID&flow=FLOW&type=tcp
|
|
||||||
vless://UUID@HOST:PORT?security=tls&sni=SNI&fp=chrome&type=ws&path=/path&host=HOST
|
|
||||||
"""
|
|
||||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
|
||||||
security = params.get("security", "none")
|
|
||||||
transport = params.get("type", "tcp")
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "vless",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"uuid": userinfo,
|
|
||||||
"packet_encoding": "xudp",
|
|
||||||
}
|
|
||||||
|
|
||||||
if security == "reality":
|
|
||||||
ob["tls"] = {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
|
|
||||||
"reality": {
|
|
||||||
"enabled": True,
|
|
||||||
"public_key": params["pbk"],
|
|
||||||
"short_id": params.get("sid", ""),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
elif security == "tls":
|
|
||||||
ob["tls"] = {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
}
|
|
||||||
if params.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
|
|
||||||
if params.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = params["alpn"].split(",")
|
|
||||||
|
|
||||||
tr = _mk_transport(
|
|
||||||
transport,
|
|
||||||
path=params.get("path", "/"),
|
|
||||||
host_header=params.get("host", host),
|
|
||||||
service_name=params.get("serviceName", ""),
|
|
||||||
)
|
|
||||||
if tr is not None:
|
|
||||||
ob["transport"] = tr
|
|
||||||
|
|
||||||
flow = urllib.parse.unquote(params.get("flow", ""))
|
|
||||||
if flow:
|
|
||||||
ob["flow"] = flow
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_vmess(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
vmess://BASE64 where BASE64 decodes to a JSON object (V2 link format).
|
|
||||||
Fields: v, ps, add, port, id, aid, scy, net, type, host, path, tls, sni, alpn, fp
|
|
||||||
"""
|
|
||||||
b64 = url[len("vmess://"):]
|
|
||||||
pad = "=" * (-len(b64) % 4)
|
|
||||||
try:
|
|
||||||
data = json.loads(base64.b64decode(b64 + pad))
|
|
||||||
except Exception:
|
|
||||||
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
|
|
||||||
|
|
||||||
host = str(data["add"])
|
|
||||||
port = int(data["port"])
|
|
||||||
net = data.get("net", "tcp")
|
|
||||||
tls_field = str(data.get("tls", ""))
|
|
||||||
sni = str(data.get("sni") or data.get("host") or host)
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "vmess",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": port,
|
|
||||||
"uuid": data["id"],
|
|
||||||
"security": data.get("scy", "auto"),
|
|
||||||
"alter_id": int(data.get("aid", 0)),
|
|
||||||
}
|
|
||||||
|
|
||||||
if tls_field in ("tls", "reality"):
|
|
||||||
ob["tls"] = {"enabled": True, "server_name": sni}
|
|
||||||
if data.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
|
|
||||||
if data.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
|
|
||||||
|
|
||||||
path = str(data.get("path") or "/")
|
|
||||||
h_host = str(data.get("host") or host)
|
|
||||||
|
|
||||||
# vmess grpc uses path as service_name; other transports use path/h_host directly
|
|
||||||
tr = _mk_transport(
|
|
||||||
net if net != "http" else "h2",
|
|
||||||
path=path,
|
|
||||||
host_header=h_host,
|
|
||||||
service_name=path.lstrip("/"),
|
|
||||||
)
|
|
||||||
if tr is not None:
|
|
||||||
ob["transport"] = tr
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_trojan(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
trojan://PASSWORD@HOST:PORT?sni=SNI&fp=chrome&security=tls&type=tcp|ws|grpc&path=...
|
|
||||||
"""
|
|
||||||
userinfo, host, port, params = _parse_url_parts(url, "trojan")
|
|
||||||
transport = params.get("type", "tcp")
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "trojan",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"password": urllib.parse.unquote(userinfo),
|
|
||||||
"tls": {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if params.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
|
|
||||||
if params.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = params["alpn"].split(",")
|
|
||||||
|
|
||||||
tr = _mk_transport(
|
|
||||||
transport,
|
|
||||||
path=params.get("path", "/"),
|
|
||||||
host_header=params.get("host", host),
|
|
||||||
service_name=params.get("serviceName", ""),
|
|
||||||
)
|
|
||||||
if tr is not None:
|
|
||||||
ob["transport"] = tr
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_shadowsocks(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
SIP002: ss://BASE64(method:password)@HOST:PORT[?plugin=...]#remark
|
|
||||||
plain: ss://method:password@HOST:PORT#remark
|
|
||||||
"""
|
|
||||||
rest = url[len("ss://"):]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
hostpart, _, _ = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
|
|
||||||
# Try SIP002 base64 decode first
|
|
||||||
pad = "=" * (-len(userinfo) % 4)
|
|
||||||
try:
|
|
||||||
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
|
|
||||||
if ":" not in decoded:
|
|
||||||
raise ValueError
|
|
||||||
method, password = decoded.split(":", 1)
|
|
||||||
except Exception:
|
|
||||||
plain = urllib.parse.unquote(userinfo)
|
|
||||||
method, password = plain.split(":", 1)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"type": "shadowsocks",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"method": method,
|
|
||||||
"password": password,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def parse_hysteria2(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
hysteria2://PASSWORD@HOST:PORT?sni=SNI&insecure=1&obfs=salamander&obfs-password=PASS
|
|
||||||
hy2://... (same, shorter alias)
|
|
||||||
"""
|
|
||||||
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
|
|
||||||
userinfo, host, port, params = _parse_url_parts(url, scheme)
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "hysteria2",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"password": urllib.parse.unquote(userinfo),
|
|
||||||
"tls": {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
"insecure": params.get("insecure", "0") == "1",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if params.get("obfs") == "salamander":
|
|
||||||
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_tuic(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
tuic://UUID:PASSWORD@HOST:PORT?congestion_control=bbr&udp_relay_mode=native&alpn=h3&sni=SNI
|
|
||||||
"""
|
|
||||||
userinfo, host, port, params = _parse_url_parts(url, "tuic")
|
|
||||||
uuid, _, password = userinfo.partition(":")
|
|
||||||
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"type": "tuic",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"uuid": uuid,
|
|
||||||
"password": urllib.parse.unquote(password),
|
|
||||||
"congestion_control": params.get("congestion_control", "bbr"),
|
|
||||||
"udp_relay_mode": params.get("udp_relay_mode", "native"),
|
|
||||||
"tls": {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
"alpn": alpn,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def parse_socks(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
socks5://[user:pass@]host:port[#remark]
|
|
||||||
socks5h://... (socks5 with remote DNS resolution – same wire format)
|
|
||||||
socks4://host:port[#remark]
|
|
||||||
socks4a://host:port[#remark]
|
|
||||||
"""
|
|
||||||
scheme = url.split("://")[0].lower()
|
|
||||||
version = "4" if scheme.startswith("socks4") else "5"
|
|
||||||
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
|
||||||
|
|
||||||
ob: dict = {"type": "socks", "tag": tag, "version": version}
|
|
||||||
if userinfo and ":" in userinfo:
|
|
||||||
username, _, password = userinfo.partition(":")
|
|
||||||
ob["username"] = urllib.parse.unquote(username)
|
|
||||||
ob["password"] = urllib.parse.unquote(password)
|
|
||||||
ob["server"] = host
|
|
||||||
ob["server_port"] = int(port)
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_http_proxy(url: str, tag: str) -> dict:
|
|
||||||
"""
|
|
||||||
http://[user:pass@]host:port[#remark] – plain HTTP CONNECT proxy
|
|
||||||
https://[user:pass@]host:port[#remark] – HTTP CONNECT proxy over TLS
|
|
||||||
"""
|
|
||||||
scheme = url.split("://")[0].lower()
|
|
||||||
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
|
||||||
|
|
||||||
ob: dict = {"type": "http", "tag": tag}
|
|
||||||
if userinfo and ":" in userinfo:
|
|
||||||
username, _, password = userinfo.partition(":")
|
|
||||||
ob["username"] = urllib.parse.unquote(username)
|
|
||||||
ob["password"] = urllib.parse.unquote(password)
|
|
||||||
ob["server"] = host
|
|
||||||
ob["server_port"] = int(port)
|
|
||||||
|
|
||||||
if scheme == "https":
|
|
||||||
ob["tls"] = {"enabled": True, "server_name": host}
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
PARSERS = {
|
|
||||||
"vless": parse_vless,
|
|
||||||
"vmess": parse_vmess,
|
|
||||||
"trojan": parse_trojan,
|
|
||||||
"ss": parse_shadowsocks,
|
|
||||||
"hysteria2": parse_hysteria2,
|
|
||||||
"hy2": parse_hysteria2,
|
|
||||||
"tuic": parse_tuic,
|
|
||||||
"socks5": parse_socks,
|
|
||||||
"socks5h": parse_socks,
|
|
||||||
"socks4": parse_socks,
|
|
||||||
"socks4a": parse_socks,
|
|
||||||
"http": parse_http_proxy,
|
|
||||||
"https": parse_http_proxy,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
ap = argparse.ArgumentParser(
|
ap = argparse.ArgumentParser(
|
||||||
description="Convert a proxy URL from stdin into a sing-box outbound JSON object."
|
description="Convert a proxy URL from stdin into a backend outbound JSON object."
|
||||||
)
|
)
|
||||||
ap.add_argument("--tag", required=True)
|
ap.add_argument("--tag", required=True)
|
||||||
|
ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box")
|
||||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||||
args = ap.parse_args()
|
args = ap.parse_args()
|
||||||
|
|
||||||
url = sys.stdin.read().strip()
|
url = sys.stdin.read().strip()
|
||||||
scheme = url.split("://")[0].lower()
|
|
||||||
|
|
||||||
if scheme not in PARSERS:
|
|
||||||
print(f"error: unsupported scheme '{scheme}'", file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ob = PARSERS[scheme](url, args.tag)
|
outbound = build_outbound(url, args.tag, args.routing_mark, args.backend)
|
||||||
except Exception as e:
|
except ValueError as exc:
|
||||||
print(f"error: failed to parse {scheme} URL: {e}", file=sys.stderr)
|
print(f"error: {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
except Exception as exc:
|
||||||
|
scheme = url.split("://", 1)[0].lower()
|
||||||
|
print(f"error: failed to parse {scheme} URL: {exc}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
if args.routing_mark is not None:
|
print(json.dumps(outbound))
|
||||||
ob["routing_mark"] = args.routing_mark
|
|
||||||
|
|
||||||
print(json.dumps(ob))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Executable
+93
@@ -0,0 +1,93 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
if [[ ! -f flake.nix ]]; then
|
||||||
|
echo "flake.nix not found at repository root" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! command -v nix >/dev/null 2>&1; then
|
||||||
|
echo "nix 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
|
||||||
|
|
||||||
|
system="${NIXPKGS_WATCH_SYSTEM:-x86_64-linux}"
|
||||||
|
default_watch_attrs="sing-box,proxychains-ng,sing-geosite,sing-geoip,nftables,iproute2,iptables,ipset,python3,python3Packages.requests,python3Packages.websockets,python3Packages.cryptography,gtk3,libayatana-appindicator"
|
||||||
|
watch_attrs_csv="${NIXPKGS_WATCH_ATTRS:-$default_watch_attrs}"
|
||||||
|
|
||||||
|
IFS=',' read -r -a watch_attrs <<< "$watch_attrs_csv"
|
||||||
|
watch_attrs_json="$(
|
||||||
|
printf '%s\n' "${watch_attrs[@]}" |
|
||||||
|
sed '/^[[:space:]]*$/d' |
|
||||||
|
jq -R . |
|
||||||
|
jq -s .
|
||||||
|
)"
|
||||||
|
|
||||||
|
if [[ "$(jq 'length' <<< "$watch_attrs_json")" -eq 0 ]]; then
|
||||||
|
echo "watch attribute list is empty" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
eval_versions() {
|
||||||
|
local ref="$1"
|
||||||
|
|
||||||
|
REF="$ref" SYSTEM="$system" WATCH_ATTRS_JSON="$watch_attrs_json" nix eval --json --impure --expr '
|
||||||
|
let
|
||||||
|
flake = builtins.getFlake (builtins.getEnv "REF");
|
||||||
|
watched = builtins.fromJSON (builtins.getEnv "WATCH_ATTRS_JSON");
|
||||||
|
system = builtins.getEnv "SYSTEM";
|
||||||
|
pkgs =
|
||||||
|
if flake ? legacyPackages then
|
||||||
|
flake.legacyPackages.${system}
|
||||||
|
else if flake ? inputs && flake.inputs ? nixpkgs then
|
||||||
|
import flake.inputs.nixpkgs { inherit system; }
|
||||||
|
else
|
||||||
|
throw "Cannot evaluate watched nixpkgs attrs: flake has neither legacyPackages nor inputs.nixpkgs";
|
||||||
|
lib = pkgs.lib;
|
||||||
|
versionOf = attrPath:
|
||||||
|
let value = lib.attrByPath (lib.splitString "." attrPath) null pkgs;
|
||||||
|
in
|
||||||
|
if value == null then null
|
||||||
|
else if builtins.isAttrs value && value ? version then value.version
|
||||||
|
else null;
|
||||||
|
in
|
||||||
|
lib.genAttrs watched versionOf
|
||||||
|
'
|
||||||
|
}
|
||||||
|
|
||||||
|
current_versions="$(eval_versions "path:${repo_root}")"
|
||||||
|
latest_versions="$(eval_versions "github:NixOS/nixpkgs/nixos-unstable")"
|
||||||
|
|
||||||
|
changes_json="$(
|
||||||
|
jq -n \
|
||||||
|
--argjson current "$current_versions" \
|
||||||
|
--argjson latest "$latest_versions" \
|
||||||
|
'
|
||||||
|
[($latest | keys[]) as $k
|
||||||
|
| select(($current[$k] // null) != ($latest[$k] // null))
|
||||||
|
| {
|
||||||
|
attr: $k,
|
||||||
|
current: ($current[$k] // null),
|
||||||
|
latest: ($latest[$k] // null)
|
||||||
|
}]
|
||||||
|
'
|
||||||
|
)"
|
||||||
|
|
||||||
|
if jq -e 'length > 0' <<< "$changes_json" >/dev/null; then
|
||||||
|
changed_attrs="$(jq -r '[.[].attr] | join(",")' <<< "$changes_json")"
|
||||||
|
echo "Detected nixpkgs updates for watched attrs: ${changed_attrs}" >&2
|
||||||
|
echo "should_update_nixpkgs=true"
|
||||||
|
echo "nixpkgs_changed_watch_attrs=${changed_attrs}"
|
||||||
|
else
|
||||||
|
echo "No watched nixpkgs package version changes detected on nixos-unstable." >&2
|
||||||
|
echo "should_update_nixpkgs=false"
|
||||||
|
echo "nixpkgs_changed_watch_attrs="
|
||||||
|
fi
|
||||||
Executable
+253
@@ -0,0 +1,253 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PROXY_CTL="${PROXY_CTL:-proxy-ctl}"
|
||||||
|
SYSTEMCTL="${SYSTEMCTL:-systemctl}"
|
||||||
|
JOURNALCTL="${JOURNALCTL:-journalctl}"
|
||||||
|
IP_BIN="${IP_BIN:-ip}"
|
||||||
|
NFT_BIN="${NFT_BIN:-nft}"
|
||||||
|
CURL_BIN="${CURL_BIN:-curl}"
|
||||||
|
TARGET_URL="${TARGET_URL:-https://whatismyipaddress.com/}"
|
||||||
|
PER_APP_TUN_PROFILE="${PER_APP_TUN_PROFILE:-tun}"
|
||||||
|
PER_APP_TPROXY_PROFILE="${PER_APP_TPROXY_PROFILE:-tproxy}"
|
||||||
|
XRAY_LOGLEVEL_FILE="${XRAY_LOGLEVEL_FILE:-/run/proxy-suite/xray-loglevel}"
|
||||||
|
ROUTE_MODE_FILE="${ROUTE_MODE_FILE:-/run/proxy-suite/route-mode}"
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
cat <<'EOF'
|
||||||
|
Usage: check-xray-tun.sh [output-dir]
|
||||||
|
|
||||||
|
Runs four native XRay regression probes:
|
||||||
|
- global TUN
|
||||||
|
- per-app TUN
|
||||||
|
- global TProxy
|
||||||
|
- per-app TProxy
|
||||||
|
|
||||||
|
The script toggles proxy-suite modes while it runs and writes captures under the
|
||||||
|
chosen output directory.
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
require_cmd() {
|
||||||
|
command -v "$1" >/dev/null 2>&1 || {
|
||||||
|
echo "missing required command: $1" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
capture_cmd() {
|
||||||
|
local output="$1"
|
||||||
|
local status=0
|
||||||
|
shift
|
||||||
|
|
||||||
|
if "$@" >"$output" 2>&1; then
|
||||||
|
return 0
|
||||||
|
else
|
||||||
|
status=$?
|
||||||
|
fi
|
||||||
|
|
||||||
|
{
|
||||||
|
echo
|
||||||
|
echo "[exit=$status] $*"
|
||||||
|
} >>"$output"
|
||||||
|
}
|
||||||
|
|
||||||
|
capture_path() {
|
||||||
|
local source="$1"
|
||||||
|
local target="$2"
|
||||||
|
|
||||||
|
if [ -e "$source" ]; then
|
||||||
|
cp -a "$source" "$target"
|
||||||
|
else
|
||||||
|
printf 'missing: %s\n' "$source" >"$target"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
service_active() {
|
||||||
|
"$SYSTEMCTL" is-active --quiet "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
set_global_mode() {
|
||||||
|
local mode="$1"
|
||||||
|
|
||||||
|
case "$mode" in
|
||||||
|
tun)
|
||||||
|
"$PROXY_CTL" proxy on
|
||||||
|
"$PROXY_CTL" tproxy off || true
|
||||||
|
"$PROXY_CTL" tun on
|
||||||
|
;;
|
||||||
|
tproxy)
|
||||||
|
"$PROXY_CTL" proxy on
|
||||||
|
"$PROXY_CTL" tun off || true
|
||||||
|
"$PROXY_CTL" tproxy on
|
||||||
|
;;
|
||||||
|
off)
|
||||||
|
"$PROXY_CTL" tun off || true
|
||||||
|
"$PROXY_CTL" tproxy off || true
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unsupported global mode: $mode" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
capture_state() {
|
||||||
|
local probe_dir="$1"
|
||||||
|
local since="$2"
|
||||||
|
local config_path="$3"
|
||||||
|
shift 3
|
||||||
|
local services=("$@")
|
||||||
|
|
||||||
|
capture_path "$config_path" "$probe_dir/config.json"
|
||||||
|
capture_path "$ROUTE_MODE_FILE" "$probe_dir/route-mode.txt"
|
||||||
|
capture_path "$XRAY_LOGLEVEL_FILE" "$probe_dir/xray-loglevel.txt"
|
||||||
|
|
||||||
|
capture_cmd "$probe_dir/ip-rule.txt" "$IP_BIN" rule show
|
||||||
|
capture_cmd "$probe_dir/ip-route-all.txt" "$IP_BIN" -4 route show table all
|
||||||
|
capture_cmd "$probe_dir/ip-addr.txt" "$IP_BIN" -4 addr show
|
||||||
|
capture_cmd "$probe_dir/nft-ruleset.txt" "$NFT_BIN" list ruleset
|
||||||
|
|
||||||
|
for svc in "${services[@]}"; do
|
||||||
|
capture_cmd "$probe_dir/journal-${svc}.log" "$JOURNALCTL" -u "$svc" --since "$since" --no-pager
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
run_global_probe() {
|
||||||
|
local mode="$1"
|
||||||
|
local probe_dir="$OUTPUT_DIR/$mode"
|
||||||
|
local config_path="$2"
|
||||||
|
shift 2
|
||||||
|
local services=("$@")
|
||||||
|
local since=""
|
||||||
|
local curl_status=0
|
||||||
|
|
||||||
|
mkdir -p "$probe_dir"
|
||||||
|
|
||||||
|
set_global_mode "${mode#global-}"
|
||||||
|
sleep 2
|
||||||
|
since="$(date --iso-8601=seconds)"
|
||||||
|
if "$CURL_BIN" -4 -L -sS --max-time 20 -D "$probe_dir/headers.txt" -o "$probe_dir/body.html" "$TARGET_URL" >"$probe_dir/stdout.txt" 2>"$probe_dir/stderr.txt"; then
|
||||||
|
:
|
||||||
|
else
|
||||||
|
curl_status=$?
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$curl_status" >"$probe_dir/curl-exit-code.txt"
|
||||||
|
capture_state "$probe_dir" "$since" "$config_path" "${services[@]}"
|
||||||
|
set_global_mode off
|
||||||
|
}
|
||||||
|
|
||||||
|
make_wrapped_probe_script() {
|
||||||
|
local probe_dir="$1"
|
||||||
|
local script_path="$probe_dir/run-probe.sh"
|
||||||
|
|
||||||
|
cat >"$script_path" <<EOF
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
status=0
|
||||||
|
if ${CURL_BIN@Q} -4 -L -sS --max-time 20 -D ${probe_dir@Q}/headers.txt -o ${probe_dir@Q}/body.html ${TARGET_URL@Q} >${probe_dir@Q}/stdout.txt 2>${probe_dir@Q}/stderr.txt; then
|
||||||
|
:
|
||||||
|
else
|
||||||
|
status=\$?
|
||||||
|
fi
|
||||||
|
printf '%s\n' "\$status" >${probe_dir@Q}/curl-exit-code.txt
|
||||||
|
sleep 5
|
||||||
|
exit "\$status"
|
||||||
|
EOF
|
||||||
|
chmod 755 "$script_path"
|
||||||
|
printf '%s\n' "$script_path"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_per_app_probe() {
|
||||||
|
local mode="$1"
|
||||||
|
local profile="$2"
|
||||||
|
local config_path="$3"
|
||||||
|
shift 3
|
||||||
|
local services=("$@")
|
||||||
|
local probe_dir="$OUTPUT_DIR/$mode"
|
||||||
|
local probe_script=""
|
||||||
|
local wrapped_pid=""
|
||||||
|
local wrapped_status=0
|
||||||
|
local since=""
|
||||||
|
|
||||||
|
mkdir -p "$probe_dir"
|
||||||
|
set_global_mode off
|
||||||
|
"$PROXY_CTL" proxy on
|
||||||
|
probe_script="$(make_wrapped_probe_script "$probe_dir")"
|
||||||
|
since="$(date --iso-8601=seconds)"
|
||||||
|
"$PROXY_CTL" wrap "$profile" -- "$probe_script" &
|
||||||
|
wrapped_pid=$!
|
||||||
|
sleep 2
|
||||||
|
capture_state "$probe_dir" "$since" "$config_path" "${services[@]}"
|
||||||
|
if wait "$wrapped_pid"; then
|
||||||
|
:
|
||||||
|
else
|
||||||
|
wrapped_status=$?
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$wrapped_status" >"$probe_dir/wrap-exit-code.txt"
|
||||||
|
}
|
||||||
|
|
||||||
|
restore_state() {
|
||||||
|
if [ -n "${ORIG_XRAY_LOGLEVEL+x}" ]; then
|
||||||
|
if [ -n "$ORIG_XRAY_LOGLEVEL" ]; then
|
||||||
|
printf '%s\n' "$ORIG_XRAY_LOGLEVEL" >"$XRAY_LOGLEVEL_FILE"
|
||||||
|
else
|
||||||
|
rm -f "$XRAY_LOGLEVEL_FILE"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$ORIG_TUN_ACTIVE" = 1 ]; then
|
||||||
|
set_global_mode tun || true
|
||||||
|
elif [ "$ORIG_TPROXY_ACTIVE" = 1 ]; then
|
||||||
|
set_global_mode tproxy || true
|
||||||
|
else
|
||||||
|
set_global_mode off || true
|
||||||
|
if [ "$ORIG_PROXY_ACTIVE" = 0 ]; then
|
||||||
|
"$PROXY_CTL" proxy off || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
|
||||||
|
usage
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
require_cmd "$PROXY_CTL"
|
||||||
|
require_cmd "$SYSTEMCTL"
|
||||||
|
require_cmd "$JOURNALCTL"
|
||||||
|
require_cmd "$IP_BIN"
|
||||||
|
require_cmd "$NFT_BIN"
|
||||||
|
require_cmd "$CURL_BIN"
|
||||||
|
|
||||||
|
OUTPUT_DIR="${1:-/tmp/proxy-suite-xray-tun-$(date +%Y%m%d-%H%M%S)}"
|
||||||
|
mkdir -p "$OUTPUT_DIR"
|
||||||
|
|
||||||
|
ORIG_PROXY_ACTIVE=0
|
||||||
|
ORIG_TUN_ACTIVE=0
|
||||||
|
ORIG_TPROXY_ACTIVE=0
|
||||||
|
ORIG_XRAY_LOGLEVEL=""
|
||||||
|
|
||||||
|
if service_active proxy-suite-socks; then
|
||||||
|
ORIG_PROXY_ACTIVE=1
|
||||||
|
fi
|
||||||
|
if service_active proxy-suite-tun; then
|
||||||
|
ORIG_TUN_ACTIVE=1
|
||||||
|
fi
|
||||||
|
if service_active proxy-suite-tproxy; then
|
||||||
|
ORIG_TPROXY_ACTIVE=1
|
||||||
|
fi
|
||||||
|
if [ -r "$XRAY_LOGLEVEL_FILE" ]; then
|
||||||
|
ORIG_XRAY_LOGLEVEL="$(tr -d '\r\n' < "$XRAY_LOGLEVEL_FILE")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
trap restore_state EXIT
|
||||||
|
|
||||||
|
printf 'info\n' >"$XRAY_LOGLEVEL_FILE"
|
||||||
|
|
||||||
|
run_global_probe global-tun /run/proxy-suite-tun/config.json proxy-suite-tun
|
||||||
|
run_per_app_probe per-app-tun "$PER_APP_TUN_PROFILE" /run/proxy-suite-per-app-tun/config.json proxy-suite-per-app-tun
|
||||||
|
run_global_probe global-tproxy /run/proxy-suite-socks/config.json proxy-suite-socks proxy-suite-tproxy
|
||||||
|
run_per_app_probe per-app-tproxy "$PER_APP_TPROXY_PROFILE" /run/proxy-suite-socks/config.json proxy-suite-socks proxy-suite-per-app-tproxy
|
||||||
|
|
||||||
|
printf '%s\n' "$OUTPUT_DIR"
|
||||||
+17
-452
@@ -1,464 +1,24 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""Read a subscription URL from stdin and emit a JSON array of backend outbounds."""
|
||||||
Read a subscription URL from stdin, fetch it, decode it, and emit a JSON array
|
|
||||||
of sing-box outbound objects to stdout.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
echo "https://example.com/sub" | fetch-subscription.py --tag-prefix my-sub
|
|
||||||
echo "https://example.com/sub" | fetch-subscription.py --tag-prefix my-sub --routing-mark 2
|
|
||||||
|
|
||||||
The subscription endpoint must return either:
|
|
||||||
- A base64-encoded blob that decodes to newline-separated proxy URIs, or
|
|
||||||
- Plain newline-separated proxy URIs directly.
|
|
||||||
|
|
||||||
Supported URI schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
|
|
||||||
socks5, socks5h, socks4, socks4a, http, https
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import base64
|
|
||||||
import json
|
import json
|
||||||
import re
|
|
||||||
import sys
|
import sys
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
|
from proxy_parsing import decode_subscription, fetch_raw, parse_hybrid_subscription, parse_subscription
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Proxy URL parsers (identical to build-outbound.py)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _qs(query: str) -> dict:
|
|
||||||
return dict(urllib.parse.parse_qsl(query))
|
|
||||||
|
|
||||||
|
|
||||||
def parse_vless(url: str, tag: str) -> dict:
|
|
||||||
rest = url[len("vless://"):]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
hostpart, _, query = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
params = _qs(query)
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "vless",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"uuid": userinfo,
|
|
||||||
"packet_encoding": "xudp",
|
|
||||||
}
|
|
||||||
|
|
||||||
security = params.get("security", "none")
|
|
||||||
transport = params.get("type", "tcp")
|
|
||||||
|
|
||||||
if security == "reality":
|
|
||||||
ob["tls"] = {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
|
|
||||||
"reality": {
|
|
||||||
"enabled": True,
|
|
||||||
"public_key": params["pbk"],
|
|
||||||
"short_id": params.get("sid", ""),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
elif security == "tls":
|
|
||||||
ob["tls"] = {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
}
|
|
||||||
if params.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
|
|
||||||
if params.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = params["alpn"].split(",")
|
|
||||||
|
|
||||||
if transport == "ws":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "ws",
|
|
||||||
"path": urllib.parse.unquote(params.get("path", "/")),
|
|
||||||
"headers": {"Host": params.get("host", host)},
|
|
||||||
}
|
|
||||||
elif transport == "grpc":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "grpc",
|
|
||||||
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
|
|
||||||
}
|
|
||||||
elif transport == "h2":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "http",
|
|
||||||
"host": [params.get("host", host)],
|
|
||||||
"path": urllib.parse.unquote(params.get("path", "/")),
|
|
||||||
}
|
|
||||||
|
|
||||||
flow = urllib.parse.unquote(params.get("flow", ""))
|
|
||||||
if flow:
|
|
||||||
ob["flow"] = flow
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_vmess(url: str, tag: str) -> dict:
|
|
||||||
b64 = url[len("vmess://"):]
|
|
||||||
pad = "=" * (-len(b64) % 4)
|
|
||||||
try:
|
|
||||||
data = json.loads(base64.b64decode(b64 + pad))
|
|
||||||
except Exception:
|
|
||||||
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
|
|
||||||
|
|
||||||
host = str(data["add"])
|
|
||||||
port = int(data["port"])
|
|
||||||
net = data.get("net", "tcp")
|
|
||||||
tls_field = str(data.get("tls", ""))
|
|
||||||
sni = str(data.get("sni") or data.get("host") or host)
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "vmess",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": port,
|
|
||||||
"uuid": data["id"],
|
|
||||||
"security": data.get("scy", "auto"),
|
|
||||||
"alter_id": int(data.get("aid", 0)),
|
|
||||||
}
|
|
||||||
|
|
||||||
if tls_field in ("tls", "reality"):
|
|
||||||
ob["tls"] = {"enabled": True, "server_name": sni}
|
|
||||||
if data.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
|
|
||||||
if data.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
|
|
||||||
|
|
||||||
path = str(data.get("path") or "/")
|
|
||||||
h_host = str(data.get("host") or host)
|
|
||||||
|
|
||||||
if net == "ws":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "ws",
|
|
||||||
"path": path,
|
|
||||||
"headers": {"Host": h_host},
|
|
||||||
}
|
|
||||||
elif net == "grpc":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "grpc",
|
|
||||||
"service_name": path.lstrip("/"),
|
|
||||||
}
|
|
||||||
elif net in ("h2", "http"):
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "http",
|
|
||||||
"host": [h_host],
|
|
||||||
"path": path,
|
|
||||||
}
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_trojan(url: str, tag: str) -> dict:
|
|
||||||
rest = url[len("trojan://"):]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
password = urllib.parse.unquote(userinfo)
|
|
||||||
|
|
||||||
hostpart, _, query = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
params = _qs(query)
|
|
||||||
transport = params.get("type", "tcp")
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "trojan",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"password": password,
|
|
||||||
"tls": {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if params.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
|
|
||||||
if params.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = params["alpn"].split(",")
|
|
||||||
|
|
||||||
if transport == "ws":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "ws",
|
|
||||||
"path": urllib.parse.unquote(params.get("path", "/")),
|
|
||||||
"headers": {"Host": params.get("host", host)},
|
|
||||||
}
|
|
||||||
elif transport == "grpc":
|
|
||||||
ob["transport"] = {
|
|
||||||
"type": "grpc",
|
|
||||||
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
|
|
||||||
}
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_shadowsocks(url: str, tag: str) -> dict:
|
|
||||||
rest = url[len("ss://"):]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
hostpart, _, _ = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
|
|
||||||
pad = "=" * (-len(userinfo) % 4)
|
|
||||||
try:
|
|
||||||
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
|
|
||||||
if ":" not in decoded:
|
|
||||||
raise ValueError
|
|
||||||
method, password = decoded.split(":", 1)
|
|
||||||
except Exception:
|
|
||||||
plain = urllib.parse.unquote(userinfo)
|
|
||||||
method, password = plain.split(":", 1)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"type": "shadowsocks",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"method": method,
|
|
||||||
"password": password,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def parse_hysteria2(url: str, tag: str) -> dict:
|
|
||||||
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
|
|
||||||
rest = url[len(scheme) + 3:]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
hostpart, _, query = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
params = _qs(query)
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "hysteria2",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"password": urllib.parse.unquote(userinfo),
|
|
||||||
"tls": {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
"insecure": params.get("insecure", "0") == "1",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if params.get("obfs") == "salamander":
|
|
||||||
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_tuic(url: str, tag: str) -> dict:
|
|
||||||
rest = url[len("tuic://"):]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
uuid, _, password = userinfo.partition(":")
|
|
||||||
|
|
||||||
hostpart, _, query = rest.partition("?")
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
params = _qs(query)
|
|
||||||
|
|
||||||
alpn_raw = params.get("alpn", "h3")
|
|
||||||
alpn = [a for a in alpn_raw.split(",") if a]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"type": "tuic",
|
|
||||||
"tag": tag,
|
|
||||||
"server": host,
|
|
||||||
"server_port": int(port),
|
|
||||||
"uuid": uuid,
|
|
||||||
"password": urllib.parse.unquote(password),
|
|
||||||
"congestion_control": params.get("congestion_control", "bbr"),
|
|
||||||
"udp_relay_mode": params.get("udp_relay_mode", "native"),
|
|
||||||
"tls": {
|
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
"alpn": alpn,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def parse_socks(url: str, tag: str) -> dict:
|
|
||||||
scheme = url.split("://")[0].lower()
|
|
||||||
version = "4" if scheme.startswith("socks4") else "5"
|
|
||||||
|
|
||||||
rest = url[len(scheme) + 3:]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "socks",
|
|
||||||
"tag": tag,
|
|
||||||
"version": version,
|
|
||||||
}
|
|
||||||
|
|
||||||
if "@" in rest:
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
if ":" in userinfo:
|
|
||||||
username, _, password = userinfo.partition(":")
|
|
||||||
ob["username"] = urllib.parse.unquote(username)
|
|
||||||
ob["password"] = urllib.parse.unquote(password)
|
|
||||||
|
|
||||||
hostpart = rest.split("?")[0]
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
ob["server"] = host
|
|
||||||
ob["server_port"] = int(port)
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
def parse_http_proxy(url: str, tag: str) -> dict:
|
|
||||||
scheme = url.split("://")[0].lower()
|
|
||||||
rest = url[len(scheme) + 3:]
|
|
||||||
rest, _, _ = rest.partition("#")
|
|
||||||
|
|
||||||
ob: dict = {
|
|
||||||
"type": "http",
|
|
||||||
"tag": tag,
|
|
||||||
}
|
|
||||||
|
|
||||||
if "@" in rest:
|
|
||||||
userinfo, _, rest = rest.partition("@")
|
|
||||||
if ":" in userinfo:
|
|
||||||
username, _, password = userinfo.partition(":")
|
|
||||||
ob["username"] = urllib.parse.unquote(username)
|
|
||||||
ob["password"] = urllib.parse.unquote(password)
|
|
||||||
|
|
||||||
hostpart = rest.split("?")[0]
|
|
||||||
host, _, port = hostpart.rpartition(":")
|
|
||||||
ob["server"] = host
|
|
||||||
ob["server_port"] = int(port)
|
|
||||||
|
|
||||||
if scheme == "https":
|
|
||||||
ob["tls"] = {"enabled": True, "server_name": host}
|
|
||||||
|
|
||||||
return ob
|
|
||||||
|
|
||||||
|
|
||||||
PARSERS = {
|
|
||||||
"vless": parse_vless,
|
|
||||||
"vmess": parse_vmess,
|
|
||||||
"trojan": parse_trojan,
|
|
||||||
"ss": parse_shadowsocks,
|
|
||||||
"hysteria2": parse_hysteria2,
|
|
||||||
"hy2": parse_hysteria2,
|
|
||||||
"tuic": parse_tuic,
|
|
||||||
"socks5": parse_socks,
|
|
||||||
"socks5h": parse_socks,
|
|
||||||
"socks4": parse_socks,
|
|
||||||
"socks4a": parse_socks,
|
|
||||||
"http": parse_http_proxy,
|
|
||||||
"https": parse_http_proxy,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Subscription fetching & parsing
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def fetch_raw(url: str) -> bytes:
|
|
||||||
req = urllib.request.Request(
|
|
||||||
url,
|
|
||||||
headers={"User-Agent": "v2rayN/6.0"},
|
|
||||||
)
|
|
||||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
||||||
return resp.read()
|
|
||||||
|
|
||||||
|
|
||||||
def decode_subscription(data: bytes) -> list[str]:
|
|
||||||
"""
|
|
||||||
Return a list of proxy URI strings from a raw subscription response.
|
|
||||||
Tries base64 decode first (standard v2rayN format), falls back to UTF-8 plain text.
|
|
||||||
"""
|
|
||||||
# Standard format: response is base64-encoded, decodes to newline-separated URIs.
|
|
||||||
text = None
|
|
||||||
stripped = data.strip()
|
|
||||||
try:
|
|
||||||
# Pad to a multiple of 4 before decoding.
|
|
||||||
pad = b"=" * (-len(stripped) % 4)
|
|
||||||
decoded = base64.b64decode(stripped + pad).decode("utf-8")
|
|
||||||
# Sanity-check: decoded content should contain at least one known scheme.
|
|
||||||
if any(f"{scheme}://" in decoded for scheme in PARSERS):
|
|
||||||
text = decoded
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
if text is None:
|
|
||||||
text = data.decode("utf-8", errors="replace")
|
|
||||||
|
|
||||||
return [line.strip() for line in text.splitlines() if line.strip()]
|
|
||||||
|
|
||||||
|
|
||||||
def slugify(remark: str) -> str:
|
|
||||||
"""Convert a free-form remark into a tag-safe slug (max 60 chars)."""
|
|
||||||
slug = re.sub(r"[^a-zA-Z0-9_-]", "-", remark)
|
|
||||||
slug = re.sub(r"-{2,}", "-", slug).strip("-")
|
|
||||||
return slug[:60] or "proxy"
|
|
||||||
|
|
||||||
|
|
||||||
def make_tag(prefix: str, remark: str, index: int) -> str:
|
|
||||||
if remark:
|
|
||||||
slug = slugify(urllib.parse.unquote(remark))
|
|
||||||
return f"{prefix}-{slug}"
|
|
||||||
return f"{prefix}-{index}"
|
|
||||||
|
|
||||||
|
|
||||||
def parse_subscription(lines: list[str], tag_prefix: str, routing_mark: int | None) -> list[dict]:
|
|
||||||
outbounds = []
|
|
||||||
seen_tags: set[str] = set()
|
|
||||||
|
|
||||||
for i, line in enumerate(lines):
|
|
||||||
scheme = line.split("://")[0].lower()
|
|
||||||
if scheme not in PARSERS:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Extract remark from the #fragment at the end of the URI.
|
|
||||||
remark = ""
|
|
||||||
if "#" in line:
|
|
||||||
remark = line.split("#", 1)[1]
|
|
||||||
|
|
||||||
base_tag = make_tag(tag_prefix, remark, i)
|
|
||||||
|
|
||||||
# Deduplicate: append -<index> until unique.
|
|
||||||
tag = base_tag
|
|
||||||
if tag in seen_tags:
|
|
||||||
n = 2
|
|
||||||
while f"{base_tag}-{n}" in seen_tags:
|
|
||||||
n += 1
|
|
||||||
tag = f"{base_tag}-{n}"
|
|
||||||
seen_tags.add(tag)
|
|
||||||
|
|
||||||
try:
|
|
||||||
ob = PARSERS[scheme](line, tag)
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"warning: skipping entry {i} ({scheme}): {exc}", file=sys.stderr)
|
|
||||||
continue
|
|
||||||
|
|
||||||
if routing_mark is not None:
|
|
||||||
ob["routing_mark"] = routing_mark
|
|
||||||
|
|
||||||
outbounds.append(ob)
|
|
||||||
|
|
||||||
return outbounds
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# CLI
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
ap = argparse.ArgumentParser(
|
ap = argparse.ArgumentParser(
|
||||||
description="Fetch a proxy subscription URL from stdin and emit a sing-box outbound JSON array."
|
description="Fetch a proxy subscription URL from stdin and emit a backend outbound JSON array."
|
||||||
)
|
)
|
||||||
ap.add_argument("--tag-prefix", required=True, dest="tag_prefix",
|
ap.add_argument(
|
||||||
help="Prefix for outbound tags, e.g. 'my-sub'.")
|
"--tag-prefix",
|
||||||
|
required=True,
|
||||||
|
dest="tag_prefix",
|
||||||
|
help="Prefix for outbound tags, e.g. 'my-sub'.",
|
||||||
|
)
|
||||||
|
ap.add_argument("--backend", choices=["sing-box", "xray", "hybrid"], default="sing-box")
|
||||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||||
args = ap.parse_args()
|
args = ap.parse_args()
|
||||||
|
|
||||||
@@ -474,9 +34,14 @@ def main() -> None:
|
|||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
lines = decode_subscription(raw)
|
lines = decode_subscription(raw)
|
||||||
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark)
|
if args.backend == "hybrid":
|
||||||
|
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark)
|
||||||
|
has_outbounds = bool(outbounds["singBox"] or outbounds["xray"])
|
||||||
|
else:
|
||||||
|
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
|
||||||
|
has_outbounds = bool(outbounds)
|
||||||
|
|
||||||
if not outbounds:
|
if not has_outbounds:
|
||||||
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
|
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|||||||
@@ -12,38 +12,25 @@ BUILTIN_ACTIVATION_FALLBACKS = {
|
|||||||
"list-twitter.txt": "general",
|
"list-twitter.txt": "general",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _hostlist_remove_pattern(stem: str) -> str:
|
||||||
|
escaped = re.escape(stem)
|
||||||
|
return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
|
||||||
|
|
||||||
|
|
||||||
|
def _mk_family(match_stems: list[str], remove_stems: list[str]) -> dict:
|
||||||
|
return {
|
||||||
|
"match": [f"list-{s}.txt" for s in match_stems],
|
||||||
|
"remove": [_hostlist_remove_pattern(f"list-{s}") for s in remove_stems],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
FAMILY_PATTERNS = {
|
FAMILY_PATTERNS = {
|
||||||
"general": {
|
"general": _mk_family(["general", "general-user"], ["general", "general-user"]),
|
||||||
"match": ["list-general.txt", "list-general-user.txt"],
|
"google": _mk_family(["google"], ["google"]),
|
||||||
"remove": [
|
"instagram": _mk_family(["instagram"], ["instagram"]),
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-general\.txt"|[^ ]*/hostlists/list-general\.txt)',
|
"soundcloud": _mk_family(["soundcloud"], ["soundcloud"]),
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-general-user\.txt"|[^ ]*/hostlists/list-general-user\.txt)',
|
"twitter": _mk_family(["twitter"], ["twitter"]),
|
||||||
],
|
|
||||||
},
|
|
||||||
"google": {
|
|
||||||
"match": ["list-google.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-google\.txt"|[^ ]*/hostlists/list-google\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"instagram": {
|
|
||||||
"match": ["list-instagram.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-instagram\.txt"|[^ ]*/hostlists/list-instagram\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"soundcloud": {
|
|
||||||
"match": ["list-soundcloud.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-soundcloud\.txt"|[^ ]*/hostlists/list-soundcloud\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"twitter": {
|
|
||||||
"match": ["list-twitter.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-twitter\.txt"|[^ ]*/hostlists/list-twitter\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -78,19 +65,32 @@ def add_standard_excludes(line: str, standard_excludes: list[str]) -> str:
|
|||||||
return line
|
return line
|
||||||
|
|
||||||
|
|
||||||
|
def _render_args(
|
||||||
|
line: str,
|
||||||
|
hostlist_path: str,
|
||||||
|
standard_excludes: list[str],
|
||||||
|
*,
|
||||||
|
preset_family: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
rendered = strip_trailing_new(line)
|
||||||
|
if preset_family is not None:
|
||||||
|
for pattern in FAMILY_PATTERNS[preset_family]["remove"]:
|
||||||
|
rendered = re.sub(pattern, "", rendered)
|
||||||
|
else:
|
||||||
|
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered)
|
||||||
|
rendered = normalize_spaces(rendered)
|
||||||
|
rendered = f'{rendered} --hostlist="{hostlist_path}"'
|
||||||
|
rendered = add_standard_excludes(rendered, standard_excludes)
|
||||||
|
return f"{normalize_spaces(rendered)} --new"
|
||||||
|
|
||||||
|
|
||||||
def render_preset_clone(
|
def render_preset_clone(
|
||||||
line: str,
|
line: str,
|
||||||
family: str,
|
family: str,
|
||||||
hostlist_path: str,
|
hostlist_path: str,
|
||||||
standard_excludes: list[str],
|
standard_excludes: list[str],
|
||||||
) -> str:
|
) -> str:
|
||||||
rendered = strip_trailing_new(line)
|
return _render_args(line, hostlist_path, standard_excludes, preset_family=family)
|
||||||
for pattern in FAMILY_PATTERNS[family]["remove"]:
|
|
||||||
rendered = re.sub(pattern, "", rendered)
|
|
||||||
rendered = normalize_spaces(rendered)
|
|
||||||
rendered = f'{rendered} --hostlist="{hostlist_path}"'
|
|
||||||
rendered = add_standard_excludes(rendered, standard_excludes)
|
|
||||||
return f"{normalize_spaces(rendered)} --new"
|
|
||||||
|
|
||||||
|
|
||||||
def render_custom_args(
|
def render_custom_args(
|
||||||
@@ -98,12 +98,7 @@ def render_custom_args(
|
|||||||
hostlist_path: str,
|
hostlist_path: str,
|
||||||
standard_excludes: list[str],
|
standard_excludes: list[str],
|
||||||
) -> str:
|
) -> str:
|
||||||
rendered = strip_trailing_new(fragment)
|
return _render_args(fragment, hostlist_path, standard_excludes)
|
||||||
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered)
|
|
||||||
rendered = normalize_spaces(rendered)
|
|
||||||
rendered = f'{rendered} --hostlist="{hostlist_path}"'
|
|
||||||
rendered = add_standard_excludes(rendered, standard_excludes)
|
|
||||||
return f"{normalize_spaces(rendered)} --new"
|
|
||||||
|
|
||||||
|
|
||||||
def clone_family_lines(
|
def clone_family_lines(
|
||||||
@@ -118,8 +113,13 @@ def clone_family_lines(
|
|||||||
if any(marker in line for marker in FAMILY_PATTERNS[family]["match"])
|
if any(marker in line for marker in FAMILY_PATTERNS[family]["match"])
|
||||||
]
|
]
|
||||||
if not matches:
|
if not matches:
|
||||||
raise ValueError(f"Preset family '{family}' is not present in the selected zapret config")
|
raise ValueError(
|
||||||
return [render_preset_clone(line, family, hostlist_path, standard_excludes) for line in matches]
|
f"Preset family '{family}' is not present in the selected zapret config"
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
render_preset_clone(line, family, hostlist_path, standard_excludes)
|
||||||
|
for line in matches
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def activate_builtin_hostlists(
|
def activate_builtin_hostlists(
|
||||||
@@ -145,8 +145,12 @@ def main() -> int:
|
|||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description="Append proxy-suite custom hostlist rules to a zapret config."
|
description="Append proxy-suite custom hostlist rules to a zapret config."
|
||||||
)
|
)
|
||||||
parser.add_argument("--config", required=True, help="Path to the selected zapret config file")
|
parser.add_argument(
|
||||||
parser.add_argument("--spec", required=True, help="JSON file describing custom hostlist rules")
|
"--config", required=True, help="Path to the selected zapret config file"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--spec", required=True, help="JSON file describing custom hostlist rules"
|
||||||
|
)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
config_path = Path(args.config)
|
config_path = Path(args.config)
|
||||||
@@ -177,10 +181,14 @@ def main() -> int:
|
|||||||
preset = entry.get("preset")
|
preset = entry.get("preset")
|
||||||
if preset:
|
if preset:
|
||||||
generated_lines.extend(
|
generated_lines.extend(
|
||||||
clone_family_lines(nfqws_lines, preset, hostlist_path, standard_excludes)
|
clone_family_lines(
|
||||||
|
nfqws_lines, preset, hostlist_path, standard_excludes
|
||||||
|
)
|
||||||
)
|
)
|
||||||
for fragment in entry.get("nfqwsArgs", []):
|
for fragment in entry.get("nfqwsArgs", []):
|
||||||
generated_lines.append(render_custom_args(fragment, hostlist_path, standard_excludes))
|
generated_lines.append(
|
||||||
|
render_custom_args(fragment, hostlist_path, standard_excludes)
|
||||||
|
)
|
||||||
|
|
||||||
updated_lines = lines[:end] + generated_lines + lines[end:]
|
updated_lines = lines[:end] + generated_lines + lines[end:]
|
||||||
config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
|
config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
|
||||||
|
|||||||
@@ -0,0 +1,328 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from proxy_url_parsers import PARSERS
|
||||||
|
|
||||||
|
|
||||||
|
def detect_scheme(url: str) -> str:
|
||||||
|
return url.split("://", 1)[0].lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_url(url: str, tag: str, backend: str) -> dict:
|
||||||
|
scheme = detect_scheme(url)
|
||||||
|
if scheme not in PARSERS:
|
||||||
|
raise ValueError(f"unsupported scheme '{scheme}'")
|
||||||
|
|
||||||
|
parser = PARSERS[scheme]
|
||||||
|
try:
|
||||||
|
return parser(url, tag, backend)
|
||||||
|
except TypeError:
|
||||||
|
return parser(url, tag)
|
||||||
|
|
||||||
|
|
||||||
|
def _xray_sockopt(routing_mark: int | None) -> dict:
|
||||||
|
if routing_mark is None:
|
||||||
|
return {}
|
||||||
|
return {"streamSettings": {"sockopt": {"mark": routing_mark}}}
|
||||||
|
|
||||||
|
|
||||||
|
def _xray_tls(tls: dict | None) -> tuple[str, dict]:
|
||||||
|
if not tls or not tls.get("enabled"):
|
||||||
|
return "none", {}
|
||||||
|
|
||||||
|
if tls.get("reality", {}).get("enabled"):
|
||||||
|
reality = tls["reality"]
|
||||||
|
settings = {
|
||||||
|
"serverName": tls.get("server_name", ""),
|
||||||
|
"publicKey": reality["public_key"],
|
||||||
|
"shortId": reality.get("short_id", ""),
|
||||||
|
}
|
||||||
|
utls = tls.get("utls", {})
|
||||||
|
if reality.get("spider_x"):
|
||||||
|
settings["spiderX"] = reality["spider_x"]
|
||||||
|
if utls.get("enabled") and utls.get("fingerprint"):
|
||||||
|
settings["fingerprint"] = utls["fingerprint"]
|
||||||
|
return "reality", {"realitySettings": settings}
|
||||||
|
|
||||||
|
settings = {"serverName": tls.get("server_name", "")}
|
||||||
|
if tls.get("alpn"):
|
||||||
|
settings["alpn"] = tls["alpn"]
|
||||||
|
if tls.get("insecure"):
|
||||||
|
raise ValueError(
|
||||||
|
"XRay no longer supports tlsSettings.allowInsecure; "
|
||||||
|
"remove insecure=1 or use a supported certificate verification option"
|
||||||
|
)
|
||||||
|
if tls.get("ech_config_list"):
|
||||||
|
settings["echConfigList"] = tls["ech_config_list"]
|
||||||
|
utls = tls.get("utls", {})
|
||||||
|
if utls.get("enabled") and utls.get("fingerprint"):
|
||||||
|
settings["fingerprint"] = utls["fingerprint"]
|
||||||
|
return "tls", {"tlsSettings": settings}
|
||||||
|
|
||||||
|
|
||||||
|
def _xray_transport(transport: dict | None) -> tuple[str, dict]:
|
||||||
|
if not transport:
|
||||||
|
return "raw", {}
|
||||||
|
|
||||||
|
t = transport["type"]
|
||||||
|
if t == "ws":
|
||||||
|
return "ws", {"wsSettings": {"path": transport.get("path", "/"), "headers": transport.get("headers", {})}}
|
||||||
|
if t == "grpc":
|
||||||
|
return "grpc", {"grpcSettings": {"serviceName": transport.get("service_name", "")}}
|
||||||
|
if t == "http":
|
||||||
|
return "http", {"httpSettings": {"host": transport.get("host", []), "path": transport.get("path", "/")}}
|
||||||
|
if t == "httpupgrade":
|
||||||
|
return "httpupgrade", {
|
||||||
|
"httpupgradeSettings": {
|
||||||
|
"host": transport.get("host", ""),
|
||||||
|
"path": transport.get("path", "/"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if t == "quic":
|
||||||
|
return "quic", {}
|
||||||
|
if t == "xhttp":
|
||||||
|
settings = {"path": transport.get("path", "/")}
|
||||||
|
if transport.get("host"):
|
||||||
|
settings["host"] = transport["host"]
|
||||||
|
if transport.get("mode"):
|
||||||
|
settings["mode"] = transport["mode"]
|
||||||
|
if transport.get("extra") is not None:
|
||||||
|
settings["extra"] = transport["extra"]
|
||||||
|
return "xhttp", {"xhttpSettings": settings}
|
||||||
|
return t, {}
|
||||||
|
|
||||||
|
|
||||||
|
def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict:
|
||||||
|
typ = ob["type"]
|
||||||
|
tag = ob["tag"]
|
||||||
|
|
||||||
|
def stream_settings() -> dict:
|
||||||
|
security, sec = _xray_tls(ob.get("tls"))
|
||||||
|
network, net = _xray_transport(ob.get("transport"))
|
||||||
|
stream = {"network": network, "security": security}
|
||||||
|
stream.update(sec)
|
||||||
|
stream.update(net)
|
||||||
|
stream.setdefault("sockopt", {})["domainStrategy"] = "UseIP"
|
||||||
|
if routing_mark is not None:
|
||||||
|
stream.setdefault("sockopt", {})["mark"] = routing_mark
|
||||||
|
return stream
|
||||||
|
|
||||||
|
if typ == "vless":
|
||||||
|
settings = {
|
||||||
|
"address": ob["server"],
|
||||||
|
"port": ob["server_port"],
|
||||||
|
"id": ob["uuid"],
|
||||||
|
"encryption": "none",
|
||||||
|
}
|
||||||
|
if ob.get("flow"):
|
||||||
|
settings["flow"] = ob["flow"]
|
||||||
|
return {"protocol": "vless", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||||
|
|
||||||
|
if typ == "vmess":
|
||||||
|
settings = {
|
||||||
|
"address": ob["server"],
|
||||||
|
"port": ob["server_port"],
|
||||||
|
"id": ob["uuid"],
|
||||||
|
"security": ob.get("security", "auto"),
|
||||||
|
"alterId": ob.get("alter_id", 0),
|
||||||
|
}
|
||||||
|
return {"protocol": "vmess", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||||
|
|
||||||
|
if typ == "trojan":
|
||||||
|
settings = {
|
||||||
|
"address": ob["server"],
|
||||||
|
"port": ob["server_port"],
|
||||||
|
"password": ob["password"],
|
||||||
|
}
|
||||||
|
return {"protocol": "trojan", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||||
|
|
||||||
|
if typ == "shadowsocks":
|
||||||
|
settings = {
|
||||||
|
"address": ob["server"],
|
||||||
|
"port": ob["server_port"],
|
||||||
|
"method": ob["method"],
|
||||||
|
"password": ob["password"],
|
||||||
|
}
|
||||||
|
return {"protocol": "shadowsocks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)}
|
||||||
|
|
||||||
|
if typ == "hysteria2":
|
||||||
|
stream = stream_settings()
|
||||||
|
stream["network"] = "hysteria"
|
||||||
|
stream["security"] = "tls"
|
||||||
|
stream["hysteriaSettings"] = {"version": 2}
|
||||||
|
settings = {
|
||||||
|
"version": 2,
|
||||||
|
"address": ob["server"],
|
||||||
|
"port": ob["server_port"],
|
||||||
|
}
|
||||||
|
if ob.get("password"):
|
||||||
|
stream["hysteriaSettings"]["auth"] = ob["password"]
|
||||||
|
if ob.get("obfs", {}).get("type") == "salamander":
|
||||||
|
stream.setdefault("finalmask", {}).setdefault("udp", []).append(
|
||||||
|
{
|
||||||
|
"type": "salamander",
|
||||||
|
"settings": {"password": ob["obfs"].get("password", "")},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"protocol": "hysteria", "tag": tag, "settings": settings, "streamSettings": stream}
|
||||||
|
|
||||||
|
if typ == "socks":
|
||||||
|
settings = {"address": ob["server"], "port": ob["server_port"]}
|
||||||
|
if ob.get("username"):
|
||||||
|
settings["user"] = ob["username"]
|
||||||
|
settings["pass"] = ob.get("password", "")
|
||||||
|
return {"protocol": "socks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)}
|
||||||
|
|
||||||
|
if typ == "http":
|
||||||
|
settings = {"address": ob["server"], "port": ob["server_port"]}
|
||||||
|
if ob.get("username"):
|
||||||
|
settings["user"] = ob["username"]
|
||||||
|
settings["pass"] = ob.get("password", "")
|
||||||
|
outbound = {"protocol": "http", "tag": tag, "settings": settings}
|
||||||
|
if ob.get("tls"):
|
||||||
|
security, sec = _xray_tls(ob.get("tls"))
|
||||||
|
outbound["streamSettings"] = {"security": security, **sec}
|
||||||
|
if routing_mark is not None:
|
||||||
|
outbound["streamSettings"].setdefault("sockopt", {})["mark"] = routing_mark
|
||||||
|
elif routing_mark is not None:
|
||||||
|
outbound.update(_xray_sockopt(routing_mark))
|
||||||
|
return outbound
|
||||||
|
|
||||||
|
raise ValueError(f"unsupported XRay outbound type '{typ}'")
|
||||||
|
|
||||||
|
|
||||||
|
def build_outbound(
|
||||||
|
url: str, tag: str, routing_mark: int | None = None, backend: str = "sing-box"
|
||||||
|
) -> dict:
|
||||||
|
if backend not in {"sing-box", "xray"}:
|
||||||
|
raise ValueError(f"unsupported backend '{backend}'")
|
||||||
|
|
||||||
|
outbound = _parse_url(url, tag, backend)
|
||||||
|
if routing_mark is not None:
|
||||||
|
if backend == "xray":
|
||||||
|
return render_xray_outbound(outbound, routing_mark)
|
||||||
|
outbound["routing_mark"] = routing_mark
|
||||||
|
elif backend == "xray":
|
||||||
|
return render_xray_outbound(outbound)
|
||||||
|
return outbound
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_raw(url: str) -> bytes:
|
||||||
|
request = urllib.request.Request(
|
||||||
|
url,
|
||||||
|
headers={"User-Agent": "v2rayN/6.0"},
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(request, timeout=30) as response:
|
||||||
|
return response.read()
|
||||||
|
|
||||||
|
|
||||||
|
def decode_subscription(data: bytes) -> list[str]:
|
||||||
|
text = None
|
||||||
|
stripped = data.strip()
|
||||||
|
try:
|
||||||
|
pad = b"=" * (-len(stripped) % 4)
|
||||||
|
decoded = base64.b64decode(stripped + pad).decode("utf-8")
|
||||||
|
if any(f"{scheme}://" in decoded for scheme in PARSERS):
|
||||||
|
text = decoded
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if text is None:
|
||||||
|
text = data.decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
return [line.strip() for line in text.splitlines() if line.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def slugify_tag(remark: str) -> str:
|
||||||
|
slug = re.sub(r"[^a-zA-Z0-9_-]", "-", remark)
|
||||||
|
slug = re.sub(r"-{2,}", "-", slug).strip("-")
|
||||||
|
return slug[:60] or "proxy"
|
||||||
|
|
||||||
|
|
||||||
|
def make_tag(prefix: str, remark: str, index: int) -> str:
|
||||||
|
if remark:
|
||||||
|
return f"{prefix}-{slugify_tag(urllib.parse.unquote(remark))}"
|
||||||
|
return f"{prefix}-{index}"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_subscription(
|
||||||
|
lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box"
|
||||||
|
) -> list[dict]:
|
||||||
|
outbounds = []
|
||||||
|
seen_tags: set[str] = set()
|
||||||
|
|
||||||
|
for index, line in enumerate(lines):
|
||||||
|
scheme = detect_scheme(line)
|
||||||
|
if scheme not in PARSERS:
|
||||||
|
continue
|
||||||
|
|
||||||
|
remark = line.split("#", 1)[1] if "#" in line else ""
|
||||||
|
base_tag = make_tag(tag_prefix, remark, index)
|
||||||
|
tag = base_tag
|
||||||
|
|
||||||
|
if tag in seen_tags:
|
||||||
|
suffix = 2
|
||||||
|
while f"{base_tag}-{suffix}" in seen_tags:
|
||||||
|
suffix += 1
|
||||||
|
tag = f"{base_tag}-{suffix}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
outbound = build_outbound(line, tag, routing_mark, backend)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
|
||||||
|
continue
|
||||||
|
|
||||||
|
seen_tags.add(tag)
|
||||||
|
outbounds.append(outbound)
|
||||||
|
|
||||||
|
return outbounds
|
||||||
|
|
||||||
|
|
||||||
|
def parse_hybrid_subscription(
|
||||||
|
lines: list[str], tag_prefix: str, routing_mark: int | None = None
|
||||||
|
) -> dict[str, list[dict]]:
|
||||||
|
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
|
||||||
|
seen_tags: set[str] = set()
|
||||||
|
|
||||||
|
for index, line in enumerate(lines):
|
||||||
|
scheme = detect_scheme(line)
|
||||||
|
if scheme not in PARSERS:
|
||||||
|
continue
|
||||||
|
|
||||||
|
remark = line.split("#", 1)[1] if "#" in line else ""
|
||||||
|
base_tag = make_tag(tag_prefix, remark, index)
|
||||||
|
tag = base_tag
|
||||||
|
|
||||||
|
if tag in seen_tags:
|
||||||
|
suffix = 2
|
||||||
|
while f"{base_tag}-{suffix}" in seen_tags:
|
||||||
|
suffix += 1
|
||||||
|
tag = f"{base_tag}-{suffix}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
outbound = build_outbound(line, tag, routing_mark, "sing-box")
|
||||||
|
outbounds["singBox"].append(outbound)
|
||||||
|
seen_tags.add(tag)
|
||||||
|
continue
|
||||||
|
except Exception as sing_box_exc:
|
||||||
|
sing_box_error = sing_box_exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
outbound = build_outbound(line, tag, routing_mark, "xray")
|
||||||
|
except Exception as xray_exc:
|
||||||
|
print(
|
||||||
|
f"warning: skipping entry {index} ({scheme}): "
|
||||||
|
f"sing-box: {sing_box_error}; xray: {xray_exc}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
outbounds["xray"].append(outbound)
|
||||||
|
seen_tags.add(tag)
|
||||||
|
|
||||||
|
return outbounds
|
||||||
@@ -0,0 +1,418 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import json
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
SUPPORTED_VLESS_TRANSPORTS = {
|
||||||
|
"",
|
||||||
|
"tcp",
|
||||||
|
"ws",
|
||||||
|
"grpc",
|
||||||
|
"h2",
|
||||||
|
"http",
|
||||||
|
"httpupgrade",
|
||||||
|
"quic",
|
||||||
|
}
|
||||||
|
|
||||||
|
SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS | {
|
||||||
|
"xhttp",
|
||||||
|
"splithttp",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _qs(query: str) -> dict:
|
||||||
|
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
|
||||||
|
|
||||||
|
|
||||||
|
def _split_host_port(hostpart: str) -> tuple[str, str]:
|
||||||
|
host, separator, port = hostpart.rpartition(":")
|
||||||
|
if not separator or not host or not port:
|
||||||
|
raise ValueError("URL must include host and port")
|
||||||
|
if host.startswith("[") and host.endswith("]"):
|
||||||
|
host = host[1:-1]
|
||||||
|
return host, port
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
|
||||||
|
rest = url[len(f"{scheme}://") :]
|
||||||
|
rest, _, _ = rest.partition("#")
|
||||||
|
if "@" in rest:
|
||||||
|
userinfo, _, rest = rest.rpartition("@")
|
||||||
|
else:
|
||||||
|
userinfo = ""
|
||||||
|
hostpart, _, query = rest.partition("?")
|
||||||
|
host, port = _split_host_port(hostpart)
|
||||||
|
return userinfo, host, port, _qs(query)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_json_param(value: str, name: str) -> dict:
|
||||||
|
try:
|
||||||
|
parsed = json.loads(value)
|
||||||
|
except json.JSONDecodeError as exc:
|
||||||
|
raise ValueError(f"invalid {name} JSON: {exc}") from exc
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise ValueError(f"invalid {name} JSON: expected object")
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
|
def _mk_transport(
|
||||||
|
transport_type: str,
|
||||||
|
path: str = "/",
|
||||||
|
host_header: str = "",
|
||||||
|
service_name: str = "",
|
||||||
|
mode: str = "",
|
||||||
|
extra: str = "",
|
||||||
|
x_padding_bytes: str = "",
|
||||||
|
) -> "dict | None":
|
||||||
|
normalized = transport_type.lower()
|
||||||
|
|
||||||
|
if normalized in ("", "tcp"):
|
||||||
|
return None
|
||||||
|
if normalized == "ws":
|
||||||
|
return {
|
||||||
|
"type": "ws",
|
||||||
|
"path": urllib.parse.unquote(path),
|
||||||
|
"headers": {"Host": host_header},
|
||||||
|
}
|
||||||
|
if normalized == "grpc":
|
||||||
|
return {
|
||||||
|
"type": "grpc",
|
||||||
|
"service_name": urllib.parse.unquote(service_name),
|
||||||
|
}
|
||||||
|
if normalized in ("h2", "http"):
|
||||||
|
return {
|
||||||
|
"type": "http",
|
||||||
|
"host": [host_header],
|
||||||
|
"path": urllib.parse.unquote(path),
|
||||||
|
}
|
||||||
|
if normalized == "httpupgrade":
|
||||||
|
return {
|
||||||
|
"type": "httpupgrade",
|
||||||
|
"host": host_header,
|
||||||
|
"path": urllib.parse.unquote(path),
|
||||||
|
}
|
||||||
|
if normalized == "quic":
|
||||||
|
return {
|
||||||
|
"type": "quic",
|
||||||
|
}
|
||||||
|
if normalized in ("xhttp", "splithttp"):
|
||||||
|
transport = {
|
||||||
|
"type": "xhttp",
|
||||||
|
"path": urllib.parse.unquote(path),
|
||||||
|
}
|
||||||
|
if host_header:
|
||||||
|
transport["host"] = host_header
|
||||||
|
if mode:
|
||||||
|
transport["mode"] = mode
|
||||||
|
if extra:
|
||||||
|
transport["extra"] = _parse_json_param(extra, "xhttp extra")
|
||||||
|
elif x_padding_bytes:
|
||||||
|
transport["extra"] = {"xPaddingBytes": x_padding_bytes}
|
||||||
|
return transport
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _mk_tls(
|
||||||
|
server_name: str, fp: "str | None" = None, alpn: "str | None" = None
|
||||||
|
) -> dict:
|
||||||
|
tls: dict = {"enabled": True, "server_name": server_name}
|
||||||
|
if fp:
|
||||||
|
tls["utls"] = {"enabled": True, "fingerprint": fp}
|
||||||
|
if alpn:
|
||||||
|
tls["alpn"] = alpn.split(",")
|
||||||
|
return tls
|
||||||
|
|
||||||
|
|
||||||
|
def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||||
|
if userinfo and ":" in userinfo:
|
||||||
|
username, _, password = userinfo.partition(":")
|
||||||
|
return urllib.parse.unquote(username), urllib.parse.unquote(password)
|
||||||
|
return None, 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(
|
||||||
|
"unsupported VLESS parameter 'ech': proxy-suite does not translate "
|
||||||
|
"share-link ECH blobs into sing-box TLS config"
|
||||||
|
)
|
||||||
|
|
||||||
|
supported_transports = (
|
||||||
|
SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS
|
||||||
|
)
|
||||||
|
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",
|
||||||
|
"tag": tag,
|
||||||
|
"server": host,
|
||||||
|
"server_port": int(port),
|
||||||
|
"uuid": userinfo,
|
||||||
|
"packet_encoding": "xudp",
|
||||||
|
}
|
||||||
|
|
||||||
|
if security == "reality":
|
||||||
|
ob["tls"] = _mk_tls(params.get("sni", host), fp=params.get("fp", "chrome"))
|
||||||
|
ob["tls"]["reality"] = {
|
||||||
|
"enabled": True,
|
||||||
|
"public_key": params["pbk"],
|
||||||
|
"short_id": params.get("sid", ""),
|
||||||
|
}
|
||||||
|
if backend == "xray" and params.get("spx"):
|
||||||
|
ob["tls"]["reality"]["spider_x"] = params["spx"]
|
||||||
|
elif security == "tls":
|
||||||
|
ob["tls"] = _mk_tls(
|
||||||
|
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
|
||||||
|
)
|
||||||
|
if backend == "xray" and "ech" in params:
|
||||||
|
ob["tls"]["ech_config_list"] = urllib.parse.unquote(params["ech"])
|
||||||
|
|
||||||
|
tr = _mk_transport(
|
||||||
|
normalized_transport,
|
||||||
|
path=params.get("path", "/"),
|
||||||
|
host_header=params.get("host", host),
|
||||||
|
service_name=params.get("serviceName", ""),
|
||||||
|
mode=params.get("mode", ""),
|
||||||
|
extra=params.get("extra", ""),
|
||||||
|
x_padding_bytes=params.get("x_padding_bytes", ""),
|
||||||
|
)
|
||||||
|
if tr is not None:
|
||||||
|
ob["transport"] = tr
|
||||||
|
|
||||||
|
flow = urllib.parse.unquote(params.get("flow", ""))
|
||||||
|
if flow:
|
||||||
|
ob["flow"] = flow
|
||||||
|
|
||||||
|
return ob
|
||||||
|
|
||||||
|
|
||||||
|
def parse_vmess(url: str, tag: str) -> dict:
|
||||||
|
b64 = url[len("vmess://") :]
|
||||||
|
b64, _, _ = b64.partition("#")
|
||||||
|
b64, _, _ = b64.partition("?")
|
||||||
|
b64 = urllib.parse.unquote(b64)
|
||||||
|
pad = "=" * (-len(b64) % 4)
|
||||||
|
try:
|
||||||
|
data = json.loads(base64.b64decode(b64 + pad))
|
||||||
|
except (binascii.Error, ValueError):
|
||||||
|
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
|
||||||
|
|
||||||
|
host = str(data["add"])
|
||||||
|
port = int(data["port"])
|
||||||
|
net = data.get("net", "tcp")
|
||||||
|
tls_field = str(data.get("tls", ""))
|
||||||
|
sni = str(data.get("sni") or data.get("host") or host)
|
||||||
|
|
||||||
|
ob: dict = {
|
||||||
|
"type": "vmess",
|
||||||
|
"tag": tag,
|
||||||
|
"server": host,
|
||||||
|
"server_port": port,
|
||||||
|
"uuid": data["id"],
|
||||||
|
"security": data.get("scy", "auto"),
|
||||||
|
"alter_id": int(data.get("aid", 0)),
|
||||||
|
}
|
||||||
|
|
||||||
|
if tls_field in ("tls", "reality"):
|
||||||
|
ob["tls"] = _mk_tls(
|
||||||
|
sni,
|
||||||
|
fp=str(data["fp"]) if data.get("fp") else None,
|
||||||
|
alpn=str(data["alpn"]) if data.get("alpn") else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
path = str(data.get("path") or "/")
|
||||||
|
h_host = str(data.get("host") or host)
|
||||||
|
|
||||||
|
tr = _mk_transport(
|
||||||
|
net if net != "http" else "h2",
|
||||||
|
path=path,
|
||||||
|
host_header=h_host,
|
||||||
|
service_name=path.lstrip("/"),
|
||||||
|
)
|
||||||
|
if tr is not None:
|
||||||
|
ob["transport"] = tr
|
||||||
|
|
||||||
|
return ob
|
||||||
|
|
||||||
|
|
||||||
|
def parse_trojan(url: str, tag: str) -> dict:
|
||||||
|
userinfo, host, port, params = _parse_url_parts(url, "trojan")
|
||||||
|
transport = params.get("type", "tcp")
|
||||||
|
|
||||||
|
ob: dict = {
|
||||||
|
"type": "trojan",
|
||||||
|
"tag": tag,
|
||||||
|
"server": host,
|
||||||
|
"server_port": int(port),
|
||||||
|
"password": urllib.parse.unquote(userinfo),
|
||||||
|
"tls": _mk_tls(
|
||||||
|
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
tr = _mk_transport(
|
||||||
|
transport,
|
||||||
|
path=params.get("path", "/"),
|
||||||
|
host_header=params.get("host", host),
|
||||||
|
service_name=params.get("serviceName", ""),
|
||||||
|
)
|
||||||
|
if tr is not None:
|
||||||
|
ob["transport"] = tr
|
||||||
|
|
||||||
|
return ob
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_ss_userinfo(userinfo: str) -> tuple[str, str]:
|
||||||
|
plain = urllib.parse.unquote(userinfo)
|
||||||
|
if ":" in plain:
|
||||||
|
return tuple(plain.split(":", 1))
|
||||||
|
|
||||||
|
pad = "=" * (-len(userinfo) % 4)
|
||||||
|
try:
|
||||||
|
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
|
||||||
|
if ":" not in decoded:
|
||||||
|
raise ValueError
|
||||||
|
return tuple(decoded.split(":", 1))
|
||||||
|
except (binascii.Error, UnicodeDecodeError, ValueError) as exc:
|
||||||
|
raise ValueError("invalid shadowsocks userinfo") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def parse_shadowsocks(url: str, tag: str) -> dict:
|
||||||
|
# Support both SIP002 form:
|
||||||
|
# ss://base64(method:password)@host:port#name
|
||||||
|
# and legacy subscriptions that base64-encode the whole endpoint:
|
||||||
|
# ss://base64(method:password@host:port)#name
|
||||||
|
rest = url[len("ss://") :]
|
||||||
|
rest, _, _ = rest.partition("#")
|
||||||
|
endpoint, _, _ = rest.partition("?")
|
||||||
|
|
||||||
|
if "@" in endpoint:
|
||||||
|
userinfo, host, port, _ = _parse_url_parts(url, "ss")
|
||||||
|
else:
|
||||||
|
pad = "=" * (-len(endpoint) % 4)
|
||||||
|
try:
|
||||||
|
decoded = base64.urlsafe_b64decode(endpoint + pad).decode()
|
||||||
|
except (binascii.Error, UnicodeDecodeError) as exc:
|
||||||
|
raise ValueError("invalid shadowsocks URL") from exc
|
||||||
|
userinfo, separator, hostpart = decoded.rpartition("@")
|
||||||
|
if not separator:
|
||||||
|
raise ValueError("invalid legacy shadowsocks URL")
|
||||||
|
host, port = _split_host_port(hostpart)
|
||||||
|
|
||||||
|
method, password = _decode_ss_userinfo(userinfo)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "shadowsocks",
|
||||||
|
"tag": tag,
|
||||||
|
"server": host,
|
||||||
|
"server_port": int(port),
|
||||||
|
"method": method,
|
||||||
|
"password": password,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_hysteria2(url: str, tag: str) -> dict:
|
||||||
|
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
|
||||||
|
userinfo, host, port, params = _parse_url_parts(url, scheme)
|
||||||
|
|
||||||
|
ob: dict = {
|
||||||
|
"type": "hysteria2",
|
||||||
|
"tag": tag,
|
||||||
|
"server": host,
|
||||||
|
"server_port": int(port),
|
||||||
|
"password": urllib.parse.unquote(userinfo),
|
||||||
|
"tls": {
|
||||||
|
"enabled": True,
|
||||||
|
"server_name": params.get("sni", host),
|
||||||
|
"insecure": params.get("insecure", "0") == "1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if params.get("obfs") == "salamander":
|
||||||
|
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
|
||||||
|
|
||||||
|
return ob
|
||||||
|
|
||||||
|
|
||||||
|
def parse_tuic(url: str, tag: str) -> dict:
|
||||||
|
userinfo, host, port, params = _parse_url_parts(url, "tuic")
|
||||||
|
uuid, _, password = userinfo.partition(":")
|
||||||
|
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "tuic",
|
||||||
|
"tag": tag,
|
||||||
|
"server": host,
|
||||||
|
"server_port": int(port),
|
||||||
|
"uuid": uuid,
|
||||||
|
"password": urllib.parse.unquote(password),
|
||||||
|
"congestion_control": params.get("congestion_control", "bbr"),
|
||||||
|
"udp_relay_mode": params.get("udp_relay_mode", "native"),
|
||||||
|
"tls": {
|
||||||
|
"enabled": True,
|
||||||
|
"server_name": params.get("sni", host),
|
||||||
|
"alpn": alpn,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_socks(url: str, tag: str) -> dict:
|
||||||
|
scheme = url.split("://")[0].lower()
|
||||||
|
version = "4" if scheme.startswith("socks4") else "5"
|
||||||
|
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
||||||
|
|
||||||
|
ob: dict = {"type": "socks", "tag": tag, "version": version}
|
||||||
|
username, password = _mk_auth(userinfo)
|
||||||
|
if username is not None:
|
||||||
|
ob["username"] = username
|
||||||
|
ob["password"] = password
|
||||||
|
ob["server"] = host
|
||||||
|
ob["server_port"] = int(port)
|
||||||
|
|
||||||
|
return ob
|
||||||
|
|
||||||
|
|
||||||
|
def parse_http_proxy(url: str, tag: str) -> dict:
|
||||||
|
scheme = url.split("://")[0].lower()
|
||||||
|
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
||||||
|
|
||||||
|
ob: dict = {"type": "http", "tag": tag}
|
||||||
|
username, password = _mk_auth(userinfo)
|
||||||
|
if username is not None:
|
||||||
|
ob["username"] = username
|
||||||
|
ob["password"] = password
|
||||||
|
ob["server"] = host
|
||||||
|
ob["server_port"] = int(port)
|
||||||
|
|
||||||
|
if scheme == "https":
|
||||||
|
ob["tls"] = {"enabled": True, "server_name": host}
|
||||||
|
|
||||||
|
return ob
|
||||||
|
|
||||||
|
|
||||||
|
PARSERS = {
|
||||||
|
"vless": parse_vless,
|
||||||
|
"vmess": parse_vmess,
|
||||||
|
"trojan": parse_trojan,
|
||||||
|
"ss": parse_shadowsocks,
|
||||||
|
"hysteria2": parse_hysteria2,
|
||||||
|
"hy2": parse_hysteria2,
|
||||||
|
"tuic": parse_tuic,
|
||||||
|
"socks5": parse_socks,
|
||||||
|
"socks5h": parse_socks,
|
||||||
|
"socks4": parse_socks,
|
||||||
|
"socks4a": parse_socks,
|
||||||
|
"http": parse_http_proxy,
|
||||||
|
"https": parse_http_proxy,
|
||||||
|
}
|
||||||
+169
-25
@@ -2,32 +2,17 @@
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
|
||||||
|
from proxy_parsing import build_outbound
|
||||||
|
|
||||||
|
|
||||||
SCRIPT = Path(os.environ.get("BUILD_OUTBOUND_SCRIPT", Path(__file__).with_name("build-outbound.py")))
|
def run_parser(url: str):
|
||||||
|
return build_outbound(url, "test-outbound")
|
||||||
|
|
||||||
|
|
||||||
def run_parser(url: str, *, expect_ok: bool = True):
|
def run_xray_parser(url: str):
|
||||||
env = dict(os.environ)
|
return build_outbound(url, "test-outbound", backend="xray")
|
||||||
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
|
||||||
proc = subprocess.run(
|
|
||||||
[sys.executable, str(SCRIPT), "--tag", "test-outbound"],
|
|
||||||
input=url,
|
|
||||||
text=True,
|
|
||||||
capture_output=True,
|
|
||||||
check=False,
|
|
||||||
env=env,
|
|
||||||
)
|
|
||||||
if expect_ok:
|
|
||||||
if proc.returncode != 0:
|
|
||||||
raise AssertionError(proc.stderr)
|
|
||||||
return json.loads(proc.stdout)
|
|
||||||
return proc
|
|
||||||
|
|
||||||
|
|
||||||
class BuildOutboundTests(unittest.TestCase):
|
class BuildOutboundTests(unittest.TestCase):
|
||||||
@@ -39,6 +24,93 @@ class BuildOutboundTests(unittest.TestCase):
|
|||||||
self.assertEqual(ob["server"], "example.com")
|
self.assertEqual(ob["server"], "example.com")
|
||||||
self.assertEqual(ob["tls"]["reality"]["public_key"], "pubkey")
|
self.assertEqual(ob["tls"]["reality"]["public_key"], "pubkey")
|
||||||
|
|
||||||
|
def test_vless_reality_germany_main_shape(self):
|
||||||
|
ob = run_parser(
|
||||||
|
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
|
||||||
|
)
|
||||||
|
self.assertEqual(ob["type"], "vless")
|
||||||
|
self.assertEqual(ob["server_port"], 443)
|
||||||
|
self.assertEqual(ob["flow"], "xtls-rprx-vision")
|
||||||
|
self.assertEqual(ob["tls"]["server_name"], "last.fm")
|
||||||
|
self.assertEqual(ob["tls"]["utls"]["fingerprint"], "qq")
|
||||||
|
self.assertEqual(ob["tls"]["reality"]["short_id"], "8a54")
|
||||||
|
self.assertNotIn("spider_x", ob["tls"]["reality"])
|
||||||
|
self.assertNotIn("transport", ob)
|
||||||
|
|
||||||
|
def test_xray_vless_reality_germany_main_shape(self):
|
||||||
|
ob = run_xray_parser(
|
||||||
|
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
|
||||||
|
)
|
||||||
|
self.assertEqual(ob["protocol"], "vless")
|
||||||
|
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||||
|
self.assertEqual(ob["settings"]["flow"], "xtls-rprx-vision")
|
||||||
|
self.assertEqual(ob["streamSettings"]["network"], "raw")
|
||||||
|
self.assertEqual(ob["streamSettings"]["sockopt"]["domainStrategy"], "UseIP")
|
||||||
|
self.assertEqual(ob["streamSettings"]["realitySettings"]["serverName"], "last.fm")
|
||||||
|
self.assertEqual(ob["streamSettings"]["realitySettings"]["fingerprint"], "qq")
|
||||||
|
self.assertEqual(
|
||||||
|
ob["streamSettings"]["realitySettings"]["spiderX"], "/-/en/gp/bestsellers"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_vless_httpupgrade_transport(self):
|
||||||
|
ob = run_parser(
|
||||||
|
"vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade"
|
||||||
|
)
|
||||||
|
self.assertEqual(ob["transport"]["type"], "httpupgrade")
|
||||||
|
self.assertEqual(ob["transport"]["host"], "cdn.example.com")
|
||||||
|
self.assertEqual(ob["transport"]["path"], "/upgrade")
|
||||||
|
|
||||||
|
def test_vless_quic_transport(self):
|
||||||
|
ob = run_parser("vless://uuid@example.com:443?type=quic&security=tls&sni=cdn.example.com")
|
||||||
|
self.assertEqual(ob["transport"]["type"], "quic")
|
||||||
|
|
||||||
|
def test_vless_xhttp_fails_loudly(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, "unsupported VLESS transport 'xhttp'"):
|
||||||
|
run_parser(
|
||||||
|
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_xray_vless_xhttp(self):
|
||||||
|
ob = run_xray_parser(
|
||||||
|
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
|
||||||
|
)
|
||||||
|
self.assertEqual(ob["protocol"], "vless")
|
||||||
|
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||||
|
self.assertEqual(ob["settings"]["id"], "uuid")
|
||||||
|
self.assertEqual(ob["streamSettings"]["network"], "xhttp")
|
||||||
|
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x")
|
||||||
|
|
||||||
|
def test_xray_vless_ech(self):
|
||||||
|
ob = run_xray_parser(
|
||||||
|
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
|
||||||
|
)
|
||||||
|
self.assertEqual(ob["streamSettings"]["tlsSettings"]["echConfigList"], "udp://1.1.1.1")
|
||||||
|
|
||||||
|
def test_xray_socks_uses_current_flat_settings_shape(self):
|
||||||
|
ob = run_xray_parser("socks5://user:pass@example.com:1080")
|
||||||
|
self.assertEqual(ob["protocol"], "socks")
|
||||||
|
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||||
|
self.assertEqual(ob["settings"]["user"], "user")
|
||||||
|
self.assertNotIn("servers", ob["settings"])
|
||||||
|
|
||||||
|
def test_xray_shadowsocks_uses_current_flat_settings_shape(self):
|
||||||
|
credentials = (
|
||||||
|
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd")
|
||||||
|
.decode()
|
||||||
|
.rstrip("=")
|
||||||
|
)
|
||||||
|
ob = run_xray_parser(f"ss://{credentials}@ss.example.com:8388")
|
||||||
|
self.assertEqual(ob["protocol"], "shadowsocks")
|
||||||
|
self.assertEqual(ob["settings"]["address"], "ss.example.com")
|
||||||
|
self.assertEqual(ob["settings"]["method"], "chacha20-ietf-poly1305")
|
||||||
|
self.assertNotIn("servers", ob["settings"])
|
||||||
|
|
||||||
|
def test_vless_ech_fails_loudly(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, "unsupported VLESS parameter 'ech'"):
|
||||||
|
run_parser(
|
||||||
|
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=blob"
|
||||||
|
)
|
||||||
|
|
||||||
def test_vmess(self):
|
def test_vmess(self):
|
||||||
payload = {
|
payload = {
|
||||||
"add": "vmess.example.com",
|
"add": "vmess.example.com",
|
||||||
@@ -58,6 +130,19 @@ class BuildOutboundTests(unittest.TestCase):
|
|||||||
self.assertEqual(ob["transport"]["type"], "ws")
|
self.assertEqual(ob["transport"]["type"], "ws")
|
||||||
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
|
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
|
||||||
|
|
||||||
|
def test_vmess_with_external_remark(self):
|
||||||
|
payload = {
|
||||||
|
"add": "vmess.example.com",
|
||||||
|
"port": "443",
|
||||||
|
"id": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"aid": "0",
|
||||||
|
"scy": "auto",
|
||||||
|
}
|
||||||
|
encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||||
|
ob = run_parser(f"vmess://{encoded}#Subscription Remark")
|
||||||
|
self.assertEqual(ob["type"], "vmess")
|
||||||
|
self.assertEqual(ob["server"], "vmess.example.com")
|
||||||
|
|
||||||
def test_trojan(self):
|
def test_trojan(self):
|
||||||
ob = run_parser("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome")
|
ob = run_parser("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome")
|
||||||
self.assertEqual(ob["type"], "trojan")
|
self.assertEqual(ob["type"], "trojan")
|
||||||
@@ -65,11 +150,46 @@ class BuildOutboundTests(unittest.TestCase):
|
|||||||
self.assertEqual(ob["tls"]["server_name"], "tls.example.com")
|
self.assertEqual(ob["tls"]["server_name"], "tls.example.com")
|
||||||
|
|
||||||
def test_shadowsocks(self):
|
def test_shadowsocks(self):
|
||||||
credentials = base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
|
credentials = (
|
||||||
|
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd")
|
||||||
|
.decode()
|
||||||
|
.rstrip("=")
|
||||||
|
)
|
||||||
ob = run_parser(f"ss://{credentials}@ss.example.com:8388")
|
ob = run_parser(f"ss://{credentials}@ss.example.com:8388")
|
||||||
self.assertEqual(ob["type"], "shadowsocks")
|
self.assertEqual(ob["type"], "shadowsocks")
|
||||||
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
|
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
|
||||||
|
|
||||||
|
def test_shadowsocks_legacy_full_base64(self):
|
||||||
|
legacy = (
|
||||||
|
base64.urlsafe_b64encode(
|
||||||
|
b"chacha20-ietf-poly1305:passw0rd@legacy.example.com:8388"
|
||||||
|
)
|
||||||
|
.decode()
|
||||||
|
.rstrip("=")
|
||||||
|
)
|
||||||
|
ob = run_parser(f"ss://{legacy}#Legacy Server")
|
||||||
|
self.assertEqual(ob["type"], "shadowsocks")
|
||||||
|
self.assertEqual(ob["server"], "legacy.example.com")
|
||||||
|
self.assertEqual(ob["server_port"], 8388)
|
||||||
|
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
|
||||||
|
self.assertEqual(ob["password"], "passw0rd")
|
||||||
|
|
||||||
|
def test_shadowsocks_plain_userinfo(self):
|
||||||
|
ob = run_parser("ss://none:plain%20pass@plain.example.com:8388")
|
||||||
|
self.assertEqual(ob["type"], "shadowsocks")
|
||||||
|
self.assertEqual(ob["method"], "none")
|
||||||
|
self.assertEqual(ob["password"], "plain pass")
|
||||||
|
|
||||||
|
def test_shadowsocks_legacy_ipv6_strips_brackets(self):
|
||||||
|
legacy = (
|
||||||
|
base64.urlsafe_b64encode(b"none:pass@[2001:db8::1]:8388")
|
||||||
|
.decode()
|
||||||
|
.rstrip("=")
|
||||||
|
)
|
||||||
|
ob = run_parser(f"ss://{legacy}#Legacy IPv6")
|
||||||
|
self.assertEqual(ob["server"], "2001:db8::1")
|
||||||
|
self.assertEqual(ob["server_port"], 8388)
|
||||||
|
|
||||||
def test_hysteria2(self):
|
def test_hysteria2(self):
|
||||||
ob = run_parser(
|
ob = run_parser(
|
||||||
"hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask"
|
"hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask"
|
||||||
@@ -78,6 +198,25 @@ class BuildOutboundTests(unittest.TestCase):
|
|||||||
self.assertTrue(ob["tls"]["insecure"])
|
self.assertTrue(ob["tls"]["insecure"])
|
||||||
self.assertEqual(ob["obfs"]["password"], "mask")
|
self.assertEqual(ob["obfs"]["password"], "mask")
|
||||||
|
|
||||||
|
def test_xray_hysteria2(self):
|
||||||
|
ob = run_xray_parser(
|
||||||
|
"hy2://secret@example.com:443?sni=hy.example.com&obfs=salamander&obfs-password=mask"
|
||||||
|
)
|
||||||
|
self.assertEqual(ob["protocol"], "hysteria")
|
||||||
|
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||||
|
self.assertNotIn("password", ob["settings"])
|
||||||
|
self.assertEqual(ob["streamSettings"]["network"], "hysteria")
|
||||||
|
self.assertEqual(ob["streamSettings"]["tlsSettings"]["serverName"], "hy.example.com")
|
||||||
|
self.assertEqual(ob["streamSettings"]["hysteriaSettings"]["auth"], "secret")
|
||||||
|
self.assertEqual(
|
||||||
|
ob["streamSettings"]["finalmask"]["udp"],
|
||||||
|
[{"type": "salamander", "settings": {"password": "mask"}}],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_xray_hysteria2_insecure_fails_loudly(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, "allowInsecure"):
|
||||||
|
run_xray_parser("hy2://secret@example.com:443?sni=hy.example.com&insecure=1")
|
||||||
|
|
||||||
def test_tuic(self):
|
def test_tuic(self):
|
||||||
ob = run_parser(
|
ob = run_parser(
|
||||||
"tuic://00000000-0000-0000-0000-000000000000:secret@example.com:443?sni=tuic.example.com&alpn=h3,hq-29"
|
"tuic://00000000-0000-0000-0000-000000000000:secret@example.com:443?sni=tuic.example.com&alpn=h3,hq-29"
|
||||||
@@ -91,15 +230,20 @@ class BuildOutboundTests(unittest.TestCase):
|
|||||||
self.assertEqual(ob["version"], "5")
|
self.assertEqual(ob["version"], "5")
|
||||||
self.assertEqual(ob["username"], "user")
|
self.assertEqual(ob["username"], "user")
|
||||||
|
|
||||||
|
def test_proxy_userinfo_allows_at_in_password(self):
|
||||||
|
ob = run_parser("socks5://user:p@ss@example.com:1080")
|
||||||
|
self.assertEqual(ob["username"], "user")
|
||||||
|
self.assertEqual(ob["password"], "p@ss")
|
||||||
|
self.assertEqual(ob["server"], "example.com")
|
||||||
|
|
||||||
def test_https_proxy(self):
|
def test_https_proxy(self):
|
||||||
ob = run_parser("https://proxy.example.com:8443")
|
ob = run_parser("https://proxy.example.com:8443")
|
||||||
self.assertEqual(ob["type"], "http")
|
self.assertEqual(ob["type"], "http")
|
||||||
self.assertEqual(ob["tls"]["server_name"], "proxy.example.com")
|
self.assertEqual(ob["tls"]["server_name"], "proxy.example.com")
|
||||||
|
|
||||||
def test_invalid_scheme_fails(self):
|
def test_invalid_scheme_fails(self):
|
||||||
proc = run_parser("wireguard://example.com", expect_ok=False)
|
with self.assertRaisesRegex(ValueError, "unsupported scheme"):
|
||||||
self.assertNotEqual(proc.returncode, 0)
|
run_parser("wireguard://example.com")
|
||||||
self.assertIn("unsupported scheme", proc.stderr)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -1,53 +1,12 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
import unittest
|
import unittest
|
||||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
from proxy_parsing import decode_subscription, parse_hybrid_subscription, parse_subscription
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
SCRIPT = Path(os.environ.get("FETCH_SUBSCRIPTION_SCRIPT", Path(__file__).with_name("fetch-subscription.py")))
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Tiny embedded HTTP server for test fixtures
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
class _FixtureHandler(BaseHTTPRequestHandler):
|
|
||||||
def do_GET(self):
|
|
||||||
body = self.server.response_data
|
|
||||||
self.send_response(200)
|
|
||||||
self.send_header("Content-Type", "text/plain")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass # silence access log during tests
|
|
||||||
|
|
||||||
|
|
||||||
def _start_server(data: bytes):
|
|
||||||
"""Start an ephemeral HTTP server on a random port. Returns (server, port)."""
|
|
||||||
srv = HTTPServer(("127.0.0.1", 0), _FixtureHandler)
|
|
||||||
srv.response_data = data
|
|
||||||
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
|
||||||
thread.start()
|
|
||||||
# Give the server a moment to enter its accept loop.
|
|
||||||
time.sleep(0.05)
|
|
||||||
return srv, srv.server_address[1]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Helpers
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
|
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"
|
||||||
|
VLESS_ECH_URI = "vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
|
||||||
SS_URI = "ss://{}@ss.example.com:8388".format(
|
SS_URI = "ss://{}@ss.example.com:8388".format(
|
||||||
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
|
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
|
||||||
)
|
)
|
||||||
@@ -60,32 +19,19 @@ def _make_b64_payload(*uris: str) -> bytes:
|
|||||||
return base64.b64encode(text.encode())
|
return base64.b64encode(text.encode())
|
||||||
|
|
||||||
|
|
||||||
def run_fetcher(server_data: bytes, tag_prefix: str = "test", *, expect_ok: bool = True, extra_args: list = None):
|
def run_fetcher(
|
||||||
srv, port = _start_server(server_data)
|
server_data: bytes,
|
||||||
url = f"http://127.0.0.1:{port}/sub"
|
tag_prefix: str = "test",
|
||||||
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
|
*,
|
||||||
cmd = [sys.executable, str(SCRIPT), "--tag-prefix", tag_prefix] + (extra_args or [])
|
routing_mark: int | None = None,
|
||||||
proc = subprocess.run(
|
backend: str = "sing-box",
|
||||||
cmd,
|
):
|
||||||
input=url,
|
lines = decode_subscription(server_data)
|
||||||
text=True,
|
if backend == "hybrid":
|
||||||
capture_output=True,
|
return parse_hybrid_subscription(lines, tag_prefix, routing_mark)
|
||||||
check=False,
|
return parse_subscription(lines, tag_prefix, routing_mark, backend)
|
||||||
env=env,
|
|
||||||
)
|
|
||||||
srv.shutdown()
|
|
||||||
srv.server_close()
|
|
||||||
if expect_ok:
|
|
||||||
if proc.returncode != 0:
|
|
||||||
raise AssertionError(f"Expected success, got:\n{proc.stderr}")
|
|
||||||
return json.loads(proc.stdout)
|
|
||||||
return proc
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Tests
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
class FetchSubscriptionTests(unittest.TestCase):
|
class FetchSubscriptionTests(unittest.TestCase):
|
||||||
|
|
||||||
def test_base64_payload_mixed_protocols(self):
|
def test_base64_payload_mixed_protocols(self):
|
||||||
@@ -119,6 +65,7 @@ class FetchSubscriptionTests(unittest.TestCase):
|
|||||||
tag = obs[0]["tag"]
|
tag = obs[0]["tag"]
|
||||||
# Tag must contain only safe characters
|
# Tag must contain only safe characters
|
||||||
import re
|
import re
|
||||||
|
|
||||||
self.assertRegex(tag, r"^[a-zA-Z0-9_/\-]+$")
|
self.assertRegex(tag, r"^[a-zA-Z0-9_/\-]+$")
|
||||||
|
|
||||||
def test_tag_deduplication(self):
|
def test_tag_deduplication(self):
|
||||||
@@ -145,15 +92,13 @@ class FetchSubscriptionTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_routing_mark_applied(self):
|
def test_routing_mark_applied(self):
|
||||||
payload = _make_b64_payload(VLESS_URI, SS_URI)
|
payload = _make_b64_payload(VLESS_URI, SS_URI)
|
||||||
obs = run_fetcher(payload, extra_args=["--routing-mark", "2"])
|
obs = run_fetcher(payload, routing_mark=2)
|
||||||
for ob in obs:
|
for ob in obs:
|
||||||
self.assertEqual(ob["routing_mark"], 2)
|
self.assertEqual(ob["routing_mark"], 2)
|
||||||
|
|
||||||
def test_all_invalid_fails(self):
|
def test_all_invalid_fails(self):
|
||||||
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
|
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
|
||||||
proc = run_fetcher(payload, expect_ok=False)
|
self.assertEqual(run_fetcher(payload), [])
|
||||||
self.assertNotEqual(proc.returncode, 0)
|
|
||||||
self.assertIn("no parseable proxy URIs", proc.stderr)
|
|
||||||
|
|
||||||
def test_index_tag_fallback_when_no_remark(self):
|
def test_index_tag_fallback_when_no_remark(self):
|
||||||
# URIs without a remark should get index-based tags
|
# URIs without a remark should get index-based tags
|
||||||
@@ -175,6 +120,23 @@ class FetchSubscriptionTests(unittest.TestCase):
|
|||||||
obs = run_fetcher(payload)
|
obs = run_fetcher(payload)
|
||||||
self.assertEqual(len(obs), 2)
|
self.assertEqual(len(obs), 2)
|
||||||
|
|
||||||
|
def test_hybrid_subscription_preserves_xray_only_entries(self):
|
||||||
|
payload = _make_b64_payload(VLESS_URI, VLESS_XHTTP_URI, VLESS_ECH_URI)
|
||||||
|
obs = run_fetcher(payload, backend="hybrid")
|
||||||
|
self.assertEqual(len(obs["singBox"]), 1)
|
||||||
|
self.assertEqual(len(obs["xray"]), 2)
|
||||||
|
self.assertEqual(obs["singBox"][0]["type"], "vless")
|
||||||
|
self.assertEqual(obs["xray"][0]["streamSettings"]["network"], "xhttp")
|
||||||
|
self.assertEqual(
|
||||||
|
obs["xray"][1]["streamSettings"]["tlsSettings"]["echConfigList"],
|
||||||
|
"udp://1.1.1.1",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_hybrid_subscription_all_invalid_returns_empty_backend_lists(self):
|
||||||
|
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
|
||||||
|
obs = run_fetcher(payload, backend="hybrid")
|
||||||
|
self.assertEqual(obs, {"singBox": [], "xray": []})
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Executable
+73
@@ -0,0 +1,73 @@
|
|||||||
|
#!/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}"
|
||||||
Reference in new issue
Block a user