Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
676fa65747 | ||
|
|
4d6802e194 | ||
|
|
744a769e73 | ||
|
|
078367d919 | ||
|
|
716fe4b18d | ||
|
|
189cf4412d | ||
|
|
af2121412b | ||
|
|
d6cbea79bf | ||
|
|
93e792f2e5 | ||
|
|
ba7560bfac | ||
|
|
b6bde24d2d | ||
|
|
1860928c9c | ||
|
|
415336e618 | ||
|
|
f77f306acb | ||
|
|
476b3fc21e | ||
|
|
5e69502382 | ||
|
|
d3ef8257ab | ||
|
|
f54ae974ef | ||
|
|
d3c68f7a9a | ||
|
|
fe41f56cc5 | ||
|
|
eeea6c161d | ||
|
|
8d4779481c | ||
|
|
de33512c88 | ||
|
|
435c908663 | ||
|
|
c3f4088458 | ||
|
|
14557eba82 | ||
|
|
181f3355c1 | ||
|
|
e6c7b1a817 | ||
|
|
981745bafb | ||
|
|
215958b367 | ||
|
|
5f45041e4c | ||
|
|
2ba1167d69 | ||
|
|
b8496a5737 | ||
|
|
aac8e8d17d | ||
|
|
1eebbfdc21 |
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."
|
||||
@@ -1,25 +1,26 @@
|
||||
# proxy-suite-flake
|
||||
|
||||
Declarative proxy stack for NixOS. One flake, one module, done.
|
||||
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.
|
||||
|
||||
The goal is to replace GUI clients like v2rayN, throne and their ilk – 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.
|
||||
|
||||
---
|
||||
|
||||
## What it gives you
|
||||
|
||||
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` by default – always running, always available to apps
|
||||
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand
|
||||
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something
|
||||
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box 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
|
||||
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
|
||||
- **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer
|
||||
- **Multiple outbounds** with automatic latency-based switching or manual selection
|
||||
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
|
||||
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, TUIC v5, socks5, socks4, http/https proxy
|
||||
- **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs
|
||||
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites that are blocked by packet inspection rather than IP
|
||||
- **Telegram proxy** – local MTProto WebSocket proxy using tg-ws-proxy
|
||||
- **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
|
||||
|
||||
---
|
||||
|
||||
@@ -36,496 +37,112 @@ No need to add zapret separately – it comes along as a transitive input.
|
||||
Add the module to your NixOS configuration:
|
||||
|
||||
```nix
|
||||
imports = [ inputs.proxy-suite.nixosModules.default ];
|
||||
modules = [ inputs.proxy-suite.nixosModules.default ];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Basic configuration
|
||||
Feature-complete starter config:
|
||||
|
||||
```nix
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
|
||||
singBox = {
|
||||
enable = true;
|
||||
port = 1080;
|
||||
|
||||
# Individual proxy example
|
||||
outbounds = [
|
||||
{
|
||||
tag = "vps";
|
||||
# Runtime secret – not in the nix store.
|
||||
# Works with sops-nix, agenix, or anything that gives you a file path.
|
||||
urlFile = config.sops.secrets.proxy_url.path;
|
||||
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";
|
||||
}
|
||||
];
|
||||
|
||||
routing = {
|
||||
# Default: send RU geosite/geoip traffic direct.
|
||||
enableRuDirect = true;
|
||||
direct.domains = [ "reddit.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;
|
||||
};
|
||||
routing.proxy.geosites = [ "google" ];
|
||||
};
|
||||
|
||||
zapret = {
|
||||
enable = true;
|
||||
# Default: mirror zapret domain lists into sing-box direct routing.
|
||||
syncDirectRouting = true;
|
||||
# Upstream zapret IP ranges are much broader, so keep them opt-in.
|
||||
syncDirectRoutingUpstreamIps = false;
|
||||
# User-defined ipsetAll/ipsetExclude still map into sing-box by default.
|
||||
syncDirectRoutingUserIps = true;
|
||||
perApp.enable = true;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
After `nixos-rebuild switch`, you have a SOCKS proxy at `localhost:1080`.
|
||||
|
||||
If you intentionally want to expose it on another interface, set:
|
||||
|
||||
```nix
|
||||
services.proxy-suite.singBox.listenAddress = "0.0.0.0";
|
||||
```
|
||||
|
||||
To also start transparent proxying:
|
||||
|
||||
```bash
|
||||
systemctl start proxy-suite-tproxy
|
||||
```
|
||||
|
||||
TProxy installs its own nftables interception rules and can coexist with the NixOS firewall.
|
||||
|
||||
---
|
||||
|
||||
## Outbound formats
|
||||
|
||||
Each outbound needs exactly one of `urlFile`, `url`, or `json`.
|
||||
|
||||
### urlFile (recommended for real credentials)
|
||||
|
||||
```nix
|
||||
outbounds = [{
|
||||
tag = "vps";
|
||||
urlFile = config.sops.secrets.my_vps_url.path;
|
||||
}];
|
||||
```
|
||||
|
||||
The URL is read at service start time. Never touches the nix store.
|
||||
|
||||
### url (convenient, not secret)
|
||||
|
||||
```nix
|
||||
outbounds = [{
|
||||
tag = "vps";
|
||||
url = "hy2://yourpassword@your-server.com:443?sni=your-server.com";
|
||||
}];
|
||||
```
|
||||
|
||||
The URL string ends up in `/nix/store`. Fine for non-sensitive configs or testing.
|
||||
|
||||
### json (full sing-box outbound attrset)
|
||||
|
||||
```nix
|
||||
outbounds = [{
|
||||
tag = "vps";
|
||||
json = {
|
||||
type = "vless";
|
||||
server = "your-server.com";
|
||||
server_port = 443;
|
||||
uuid = "your-uuid";
|
||||
tls = {
|
||||
enabled = true;
|
||||
server_name = "your-server.com";
|
||||
reality = {
|
||||
enabled = true;
|
||||
public_key = "your-public-key";
|
||||
short_id = "abc123";
|
||||
};
|
||||
};
|
||||
perAppRouting = {
|
||||
enable = true;
|
||||
createDefaultProfiles = true;
|
||||
proxychains.enable = true;
|
||||
};
|
||||
}];
|
||||
```
|
||||
|
||||
Embedded at build time. Good when you generate the config programmatically.
|
||||
|
||||
---
|
||||
|
||||
## Multiple outbounds
|
||||
|
||||
```nix
|
||||
singBox = {
|
||||
outbounds = [
|
||||
{ tag = "de"; urlFile = config.sops.secrets.vps_de.path; }
|
||||
{ tag = "nl"; urlFile = config.sops.secrets.vps_nl.path; }
|
||||
];
|
||||
|
||||
# Auto-select the fastest (checks every 3 minutes)
|
||||
selection = "urltest";
|
||||
|
||||
# Or expose a Clash-compatible API for manual switching:
|
||||
# selection = "selector";
|
||||
# clashApiPort = 9090; # then use a Clash controller UI
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Subscription URLs
|
||||
|
||||
A subscription URL is an HTTP endpoint that returns a base64-encoded newline-separated list of proxy URIs — the standard format used by v2rayN, Clash, and similar clients. All supported proxy schemes (VLESS, VMess, Trojan, Shadowsocks, Hysteria2, TUIC, SOCKS5, HTTP…) can appear in the same subscription.
|
||||
|
||||
```nix
|
||||
singBox = {
|
||||
subscriptions = [
|
||||
{
|
||||
tag = "community";
|
||||
url = "https://example.com/sub/your-token";
|
||||
}
|
||||
];
|
||||
|
||||
# urltest is strongly recommended for subscriptions: sing-box probes all proxies
|
||||
# concurrently and routes through the fastest working one. With selection = "first"
|
||||
# a single dead server in position 0 breaks everything.
|
||||
selection = "urltest";
|
||||
subscriptionUpdateInterval = "6h"; # refresh every 6 hours (default: 1d)
|
||||
|
||||
# Optional: test against a URL that is actually blocked in your region.
|
||||
# Only proxies that bypass the block will win — not just any reachable server.
|
||||
# Defaults to https://www.gstatic.com/generate_204 (reachability check only).
|
||||
urlTest.url = "https://telegram.org/";
|
||||
};
|
||||
```
|
||||
|
||||
Use `urlFile` instead of `url` to keep the subscription URL out of the nix store:
|
||||
|
||||
```nix
|
||||
subscriptions = [{
|
||||
tag = "private";
|
||||
urlFile = config.sops.secrets.sub_url.path;
|
||||
}];
|
||||
```
|
||||
|
||||
### How it works
|
||||
|
||||
**First start:** the service fetches the subscription URL live and writes the parsed outbounds to `/var/lib/proxy-suite/subscriptions/<tag>.json`.
|
||||
|
||||
**Subsequent starts:** the cache file is used directly — no network access on restart.
|
||||
|
||||
**Periodic refresh:** a systemd timer (`proxy-suite-subscription-update`) fires on boot (after 5 minutes) and then every `subscriptionUpdateInterval`. On success it updates the cache files and restarts `proxy-suite-socks` (and `proxy-suite-tun` if it is active).
|
||||
|
||||
### urltest startup behavior
|
||||
|
||||
When `selection = "urltest"`, sing-box starts probing all proxies **concurrently** the moment the service comes up. Until the first test result arrives (typically within a few seconds), traffic uses the first proxy in the list. As tests complete, sing-box progressively switches to faster winners. Dead proxies are skipped as their tests time out.
|
||||
|
||||
**Practical consequence:** the first few requests after a (re)start may go through a slow or unreachable proxy. This resolves quickly — usually within 5–20 seconds — without any manual action.
|
||||
|
||||
To minimize this window, set `urlTest.url` to a URL that must actually be reachable through a working proxy (e.g. a blocked site in your region). This way the first working test result corresponds to a proxy that genuinely serves your traffic, not just any reachable server.
|
||||
|
||||
### Tag generation
|
||||
|
||||
Each proxy URI in the subscription gets a sing-box outbound tag derived from its `#remark` fragment:
|
||||
|
||||
```
|
||||
<subscription-tag>-<slugified-remark>
|
||||
```
|
||||
|
||||
For example, a subscription with `tag = "sub"` and a proxy remarked `Server DE #1` becomes `sub-Server-DE--1`. URIs without a remark get `sub-0`, `sub-1`, etc. Duplicate tags are suffixed with `-2`, `-3`, and so on.
|
||||
|
||||
### Routing domains through subscription proxies
|
||||
|
||||
Routing rules that point to `"proxy"` automatically use whatever subscription proxy is currently active. With `selection = "urltest"`, the fastest subscription proxy handles those domains. With `selection = "selector"`, the manually chosen one does.
|
||||
|
||||
```nix
|
||||
singBox = {
|
||||
subscriptions = [{ tag = "community"; url = "https://example.com/sub/token"; }];
|
||||
selection = "urltest";
|
||||
|
||||
# These domains go through whichever community proxy wins the latency test.
|
||||
routing.proxy.domains = [ "telegram.org" "twitter.com" ];
|
||||
};
|
||||
```
|
||||
|
||||
You **cannot** route specific domains to "a named group of proxies from subscription X" — subscription tags are generated at runtime and are unknown at Nix eval time. If you need to pin a domain to a specific proxy, use `selection = "selector"`, switch to that proxy via `proxy-ctl select <tag>`, and all routing rules pointing to `"proxy"` will follow.
|
||||
|
||||
### Mixing subscriptions with static outbounds
|
||||
|
||||
Subscriptions and static outbound declarations can coexist. Subscription outbounds are appended after static ones, so with `selection = "selector"` or `"urltest"` all of them are available:
|
||||
|
||||
```nix
|
||||
singBox = {
|
||||
outbounds = [
|
||||
{ tag = "own-vps"; urlFile = config.sops.secrets.vps.path; }
|
||||
];
|
||||
subscriptions = [
|
||||
{ tag = "backup"; url = "https://example.com/sub/token"; }
|
||||
];
|
||||
selection = "urltest";
|
||||
};
|
||||
```
|
||||
|
||||
### `selection = "first"` with subscriptions
|
||||
|
||||
With `selection = "first"` and static outbounds, the first static outbound is used (as usual). With `selection = "first"` and **subscriptions only**, the first proxy from the first subscription is used as `proxy`.
|
||||
|
||||
---
|
||||
|
||||
## Per-outbound routing
|
||||
|
||||
By default all proxied traffic goes to whatever the active outbound is (the selector, urltest winner, or single "first" outbound). You can override this per-outbound or with explicit rules to send specific traffic to a specific server.
|
||||
|
||||
Global direct routing also has two built-in behaviors:
|
||||
|
||||
- `singBox.routing.enableRuDirect = true` sends `geosite-category-ru` and `geoip-ru` direct by default.
|
||||
- If `zapret.enable = true`, then `zapret.syncDirectRouting = true` mirrors zapret's upstream domain hostlists into sing-box direct rules. `zapret.syncDirectRoutingUpstreamIps = false` by default, so upstream zapret IP ranges are not mirrored unless you opt in, while `zapret.syncDirectRoutingUserIps = true` keeps user `ipsetAll`/`ipsetExclude` mirrored by default.
|
||||
|
||||
**Attached to an outbound:**
|
||||
|
||||
```nix
|
||||
outbounds = [
|
||||
{
|
||||
tag = "de";
|
||||
urlFile = config.sops.secrets.vps_de.path;
|
||||
# Only meaningful with selection = "selector" or "urltest"
|
||||
routing.geosites = [ "netflix" ];
|
||||
routing.geoips = [ "us" ];
|
||||
routing.domains = [ "hulu.com" "peacocktv.com" ];
|
||||
}
|
||||
{
|
||||
tag = "nl";
|
||||
urlFile = config.sops.secrets.vps_nl.path;
|
||||
routing.domains = [ "discord.com" "discordapp.com" ];
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
**Explicit rules list** – also works for `direct` and `block`, in any selection mode:
|
||||
|
||||
```nix
|
||||
singBox.routing.rules = [
|
||||
# Block ad networks before anything else
|
||||
{ outbound = "block"; geosites = [ "category-ads-all" ]; }
|
||||
# Internal traffic goes direct
|
||||
{ outbound = "direct"; domains = [ "corp.internal" ]; ips = [ "10.0.0.0/8" ]; }
|
||||
# Route US ips and Netflix to a specific server
|
||||
{ outbound = "de"; geoips = [ "us" ]; geosites = [ "netflix" ]; }
|
||||
];
|
||||
```
|
||||
|
||||
Rules from `outbound.routing` and `routing.rules` are evaluated **before** the global `routing.proxy` / `routing.direct` / `routing.block` lists, so they always take priority.
|
||||
|
||||
Within a single rule, `domains`, `ips`, `geosites`, and `geoips` are treated as independent matches. In practice that means one rule with multiple fields behaves like OR, not AND.
|
||||
|
||||
In `first` selection mode, per-outbound tags are resolved to `"proxy"` automatically (there's only one proxy outbound in that mode, so routing to a specific tag doesn't make sense).
|
||||
|
||||
---
|
||||
|
||||
## proxy-ctl
|
||||
|
||||
A control script is installed into your system packages automatically. Run it as root or with the right polkit permissions.
|
||||
|
||||
```
|
||||
proxy-ctl status show status of all proxy-suite services
|
||||
proxy-ctl tproxy on|off enable/disable TProxy transparent mode
|
||||
proxy-ctl tun on|off enable/disable TUN mode
|
||||
proxy-ctl restart restart proxy-suite-socks, and proxy-suite-tun if it is active
|
||||
proxy-ctl logs [service] follow logs (default: proxy-suite-socks)
|
||||
proxy-ctl outbounds list outbounds and current selection (needs Clash API)
|
||||
proxy-ctl select <tag> switch to a specific outbound (selector mode)
|
||||
proxy-ctl subscription list show subscriptions, cache age, and proxy count
|
||||
proxy-ctl subscription update force-refresh all subscription caches and restart
|
||||
```
|
||||
|
||||
`outbounds` works with `selection = "selector"` or `"urltest"`. `select` requires `selection = "selector"` and talks to the Clash-compatible REST API embedded in sing-box.
|
||||
|
||||
`subscription list` and `subscription update` are only meaningful when `singBox.subscriptions` is non-empty.
|
||||
|
||||
---
|
||||
|
||||
## Protocol URL formats
|
||||
|
||||
| Protocol | Example URL |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| VLESS + Reality | `vless://uuid@host:443?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=abc&flow=xtls-rprx-vision` |
|
||||
| VLESS + TLS | `vless://uuid@host:443?security=tls&sni=SNI&type=ws&path=/path` |
|
||||
| VMess | `vmess://BASE64_JSON` (standard V2 link format) |
|
||||
| Trojan | `trojan://password@host:443?sni=SNI&fp=chrome` |
|
||||
| Shadowsocks | `ss://BASE64(method:password)@host:port` or `ss://method:password@host:port` |
|
||||
| Hysteria2 | `hy2://password@host:443?sni=SNI` |
|
||||
| TUIC v5 | `tuic://uuid:password@host:443?sni=SNI&congestion_control=bbr` |
|
||||
| SOCKS5 | `socks5://user:pass@host:1080` or `socks5://host:1080` |
|
||||
| SOCKS4 | `socks4://host:1080` |
|
||||
| HTTP proxy | `http://user:pass@host:8080` |
|
||||
| HTTPS proxy | `https://host:8080` (HTTP CONNECT over TLS) |
|
||||
|
||||
---
|
||||
|
||||
## Zapret
|
||||
|
||||
zapret handles DPI-based blocking by mangling packets at the netfilter level. It's separate from the proxy, but by default this module also mirrors zapret-covered domains into sing-box direct routing so the proxy does not fight zapret for the same traffic.
|
||||
|
||||
```nix
|
||||
zapret = {
|
||||
enable = true;
|
||||
configName = "general(ALT)";
|
||||
syncDirectRouting = true; # default: sync upstream domain lists
|
||||
syncDirectRoutingUpstreamIps = false; # default: do not sync upstream IP ranges
|
||||
syncDirectRoutingUserIps = true; # default: do sync user ipsetAll/ipsetExclude
|
||||
|
||||
# Extra domains beyond zapret's built-in list
|
||||
listGeneral = [ "pixiv.net" "pximg.net" ];
|
||||
};
|
||||
```
|
||||
|
||||
When `syncDirectRouting = true`, the module always reuses zapret's upstream `hostlists/list-general.txt` and `list-google.txt`, adds your `listGeneral`, and subtracts both upstream and user domain exclusions before generating sing-box direct rules. If `zapret.includeExtraUpstreamLists = true`, it also includes upstream `list-instagram.txt`, `list-soundcloud.txt`, and `list-twitter.txt` in both zapret handling and sing-box direct sync.
|
||||
|
||||
Custom `zapret.hostlistRules` domains also join this direct-domain sync by default. Set `enableDirectSync = false` on a custom hostlist if you want zapret to handle it but do not want sing-box direct-routing rules generated from it.
|
||||
|
||||
The generated zapret config can also auto-activate upstream `list-instagram.txt`, `list-soundcloud.txt`, and `list-twitter.txt` when the selected upstream preset does not already reference them. They are attached using the active config's `general` rule family so those hostlists are actually handled by zapret instead of just existing on disk. This is disabled by default; set `zapret.includeExtraUpstreamLists = true;` to opt in.
|
||||
|
||||
When `syncDirectRoutingUpstreamIps = true`, the module also mirrors zapret's upstream `ipset-all.txt`. This is disabled by default because the upstream IP set is intentionally broad.
|
||||
|
||||
When `syncDirectRoutingUserIps = true`, the module mirrors your `ipsetAll` and `ipsetExclude` values into sing-box direct routing even if upstream IP sync stays disabled. This is enabled by default.
|
||||
|
||||
If zapret corrupts traffic for some subnet (e.g. a VM behind a libvirt bridge):
|
||||
|
||||
```nix
|
||||
zapret.cidrExemption = {
|
||||
enable = true;
|
||||
cidrs = [ "192.168.123.0/24" ]; # your VM's bridge network(s)
|
||||
};
|
||||
```
|
||||
|
||||
You can also define custom zapret hostlists with per-list rules:
|
||||
|
||||
```nix
|
||||
zapret.hostlistRules = [
|
||||
{
|
||||
name = "googlevideo";
|
||||
domains = [ "googlevideo.com" "ggpht.com" ];
|
||||
preset = "google";
|
||||
}
|
||||
{
|
||||
name = "example";
|
||||
domains = [ "example.com" "example.de" ];
|
||||
nfqwsArgs = [
|
||||
"--filter-tcp=443 --dpi-desync=fake,multisplit"
|
||||
];
|
||||
}
|
||||
{
|
||||
name = "social-extra";
|
||||
domains = [ "x.example" ];
|
||||
preset = "twitter";
|
||||
nfqwsArgs = [
|
||||
"--filter-udp=443 --dpi-desync=fake --dpi-desync-repeats=6"
|
||||
];
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
Each entry generates `hostlists/list-<name>.txt`. `preset` clones the active zapret config's matching family rules for that hostlist, while `nfqwsArgs` appends custom NFQWS rule fragments. The module injects the generated `--hostlist=...`, standard zapret exclude files, and trailing `--new` automatically.
|
||||
|
||||
---
|
||||
|
||||
## Telegram proxy
|
||||
|
||||
Runs a WebSocket MTProto relay. Useful for sharing with others on mobile or for clients that need a dedicated Telegram proxy.
|
||||
|
||||
```nix
|
||||
tgWsProxy = {
|
||||
enable = true;
|
||||
# Generate a secret: openssl rand -hex 16
|
||||
secretFile = config.sops.secrets.tg_ws_proxy_secret.path;
|
||||
port = 1076;
|
||||
host = "0.0.0.0"; # configurable bind address
|
||||
};
|
||||
```
|
||||
|
||||
`secretFile` is the recommended form because it keeps the secret out of the nix store. The legacy inline `secret = "...";` form still works for testing.
|
||||
|
||||
---
|
||||
|
||||
## Services
|
||||
|
||||
| Service | Auto-starts | Description |
|
||||
| --------------------------------- | ------------------ | ------------------------------------------------ |
|
||||
| `proxy-suite-socks` | yes | SOCKS5/HTTP proxy, always running |
|
||||
| `proxy-suite-tproxy` | no | TProxy transparent mode (start manually) |
|
||||
| `proxy-suite-tun` | no | TUN mode (start manually, conflicts with tproxy) |
|
||||
| `proxy-suite-tg-ws-proxy` | yes (if enabled) | Telegram proxy |
|
||||
| `proxy-suite-zapret-vm-exempt` | yes (if enabled) | VM subnet exemption |
|
||||
| `proxy-suite-subscription-update` | timer (if sub set) | Refresh subscription caches and restart |
|
||||
|
||||
TProxy and TUN are mutually exclusive. Start one, the other refuses to start.
|
||||
|
||||
---
|
||||
|
||||
## Secret management
|
||||
|
||||
This module doesn't care how you manage secrets. Anything that gives you a file path works:
|
||||
|
||||
**sops-nix:**
|
||||
|
||||
```nix
|
||||
sops.secrets.proxy_url.sopsFile = ./secrets/proxy.yaml;
|
||||
|
||||
services.proxy-suite.singBox.outbounds = [{
|
||||
tag = "vps";
|
||||
urlFile = config.sops.secrets.proxy_url.path;
|
||||
}];
|
||||
```
|
||||
|
||||
**agenix:**
|
||||
|
||||
```nix
|
||||
age.secrets.proxy_url.file = ./secrets/proxy_url.age;
|
||||
|
||||
services.proxy-suite.singBox.outbounds = [{
|
||||
tag = "vps";
|
||||
urlFile = config.age.secrets.proxy_url.path;
|
||||
}];
|
||||
```
|
||||
|
||||
**Plain file (not recommended but works):**
|
||||
|
||||
```nix
|
||||
# Create /run/proxy-url with your URL, ensure it's readable by root
|
||||
urlFile = "/run/proxy-url";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## System tray
|
||||
|
||||
Optional tray indicator for desktop environments. Shows proxy status and provides quick toggles.
|
||||
|
||||
```nix
|
||||
services.proxy-suite = {
|
||||
tray = {
|
||||
enable = true;
|
||||
autostart = true; # Install XDG autostart for all graphical users (default)
|
||||
pollInterval = 5; # Status refresh interval in seconds
|
||||
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";
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Features:
|
||||
---
|
||||
|
||||
- **Status icon**: `network-vpn` (active), `network-vpn-acquiring` (partial), `network-vpn-disconnected` (stopped)
|
||||
- **Quick controls window**: Opens on secondary activation and on hosts that emit StatusNotifier `Activate` on left-click (including niri)
|
||||
- **Enable/Disable Proxy**: Toggles `proxy-suite-socks`; disabling proxy also stops active TProxy/TUN first
|
||||
- **Toggle TProxy/TUN**: Only shown if the service is enabled in your config
|
||||
- **Close window**: Hides the floating controls window without exiting the tray
|
||||
- **Update Subscriptions**: Triggers `proxy-suite-subscription-update` to re-fetch all subscription caches; only shown when subscriptions are configured
|
||||
- **Restart services**: Restarts `proxy-suite-socks`, and `proxy-suite-tun` if it is active
|
||||
- **Polkit authentication**: Prompts for password when toggling services
|
||||
## Options
|
||||
|
||||
When enabled, the tray app is installed system-wide and autostarts for all graphical users via XDG autostart unless you set `tray.autostart = false;`.
|
||||
To see options and documentation, check out the [options reference](./docs/options.md).
|
||||
|
||||
The tray uses libayatana-appindicator and requires StatusNotifier/AppIndicator support. KDE generally works out of the box; GNOME may need shell support or an extension that exposes AppIndicators.
|
||||
Options and generated README help are refreshed with `nix run .#update-docs`.
|
||||
|
||||
To enable TProxy/TUN toggles in the tray, you need to enable the services in your config:
|
||||
---
|
||||
|
||||
```nix
|
||||
services.proxy-suite.singBox = {
|
||||
tproxy.enable = true; # Show TProxy toggle
|
||||
tun.enable = true; # Show TUN toggle
|
||||
};
|
||||
## `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 sing-box proxy stack
|
||||
tproxy on|off enable/disable TProxy transparent mode
|
||||
tun on|off enable/disable TUN mode
|
||||
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 sing-box services
|
||||
```
|
||||
<!-- proxy-ctl-help:end -->
|
||||
@@ -23,6 +23,17 @@
|
||||
forAll = nixpkgs.lib.genAttrs systems;
|
||||
pkgsFor = system: import nixpkgs { inherit system; };
|
||||
proxySuiteModule = import ./modules/proxy-suite { inherit zapret; };
|
||||
mkOptionsDoc = import ./nix/options-doc.nix {
|
||||
inherit nixpkgs pkgsFor proxySuiteModule;
|
||||
};
|
||||
mkReadmeDoc = import ./nix/readme-doc.nix {
|
||||
inherit
|
||||
nixpkgs
|
||||
pkgsFor
|
||||
proxySuiteModule
|
||||
zapret
|
||||
;
|
||||
};
|
||||
in
|
||||
{
|
||||
# Main module – bakes in the zapret flake so consumers don't need it as a separate input.
|
||||
@@ -32,13 +43,77 @@
|
||||
nixosModules.zapret = zapret.nixosModules.default;
|
||||
|
||||
overlays.default = final: prev: {
|
||||
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = final; };
|
||||
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = final; };
|
||||
inherit (import ./pkgs/default.nix { pkgs = final; })
|
||||
mkProxyCtl
|
||||
mkProxySuiteTray
|
||||
mkTgWsProxy
|
||||
tg-ws-proxy
|
||||
proxy-suite-tray
|
||||
;
|
||||
};
|
||||
|
||||
packages = forAll (system: {
|
||||
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = pkgsFor system; };
|
||||
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = pkgsFor system; };
|
||||
packages = forAll (
|
||||
system:
|
||||
let
|
||||
pkgs = pkgsFor system;
|
||||
suitePkgs = import ./pkgs/default.nix { inherit pkgs; };
|
||||
updateDocs = pkgs.writeShellApplication {
|
||||
name = "update-docs";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.git
|
||||
pkgs.nix
|
||||
];
|
||||
text = ''
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
|
||||
|
||||
if [[ -z "''${repo_root}" || ! -f "''${repo_root}/flake.nix" ]]; then
|
||||
echo "run this helper from inside the proxy-suite-flake repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
options_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
|
||||
readme_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#readmeDoc")"
|
||||
|
||||
install -Dm644 "''${options_output_path}" "''${repo_root}/docs/options.md"
|
||||
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: {
|
||||
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 = {
|
||||
type = "app";
|
||||
program = "${self.packages.${system}.update-options-doc}/bin/update-options-doc";
|
||||
meta.description = "Compatibility alias for update-docs";
|
||||
};
|
||||
});
|
||||
|
||||
checks = forAll (
|
||||
@@ -50,6 +125,8 @@
|
||||
proxySuiteModule
|
||||
zapret
|
||||
;
|
||||
generatedOptionsDoc = mkOptionsDoc system;
|
||||
generatedReadmeDoc = mkReadmeDoc system;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -8,84 +8,102 @@
|
||||
}:
|
||||
|
||||
let
|
||||
sb = cfg.singBox;
|
||||
derived = import ./derived.nix { inherit lib cfg; };
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
clashApiEnabled
|
||||
;
|
||||
perAppTun = derived.perAppRoutingTun;
|
||||
direct = rules.direct;
|
||||
|
||||
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
|
||||
mkDnsServer =
|
||||
tag: upstream: detour:
|
||||
{
|
||||
inherit tag;
|
||||
type = upstream.type;
|
||||
server = upstream.address;
|
||||
server_port = upstream.port;
|
||||
}
|
||||
// lib.optionalAttrs (detour != null) { inherit detour; };
|
||||
|
||||
mkDnsConfig =
|
||||
{
|
||||
localDetour ? null,
|
||||
}:
|
||||
{
|
||||
servers = [
|
||||
(mkDnsServer "remote" singBoxCfg.dns.remote "proxy")
|
||||
(mkDnsServer "local" singBoxCfg.dns.local localDetour)
|
||||
];
|
||||
rules =
|
||||
lib.optional (builtins.elem "google" singBoxCfg.routing.proxy.geosites) {
|
||||
rule_set = [ "geosite-google" ];
|
||||
server = "remote";
|
||||
}
|
||||
++ lib.optional (direct.geosites != [ ]) {
|
||||
rule_set = map (s: "geosite-${s}") direct.geosites;
|
||||
server = "local";
|
||||
};
|
||||
final = if singBoxCfg.proxyByDefault then "remote" else "local";
|
||||
};
|
||||
|
||||
clashApiBlock = lib.optionalAttrs clashApiEnabled {
|
||||
experimental = {
|
||||
clash_api = {
|
||||
external_controller = "127.0.0.1:${toString sb.clashApiPort}";
|
||||
external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
dnsConfig = {
|
||||
servers = [
|
||||
{
|
||||
tag = "remote";
|
||||
type = "udp";
|
||||
server = "1.1.1.1";
|
||||
detour = "proxy";
|
||||
}
|
||||
{
|
||||
tag = "local";
|
||||
type = "udp";
|
||||
server = "1.1.1.1";
|
||||
# In TUN mode, routing DNS through direct can conflict with auto_redirect.
|
||||
# In TProxy/mixed mode, direct is fine for local traffic.
|
||||
detour = "direct";
|
||||
}
|
||||
];
|
||||
rules =
|
||||
lib.optional (builtins.elem "google" sb.routing.proxy.geosites) {
|
||||
rule_set = [ "geosite-google" ];
|
||||
server = "remote";
|
||||
}
|
||||
++ lib.optional (direct.geosites != [ ]) {
|
||||
rule_set = map (s: "geosite-${s}") direct.geosites;
|
||||
server = "local";
|
||||
};
|
||||
final = if sb.proxyByDefault then "remote" else "local";
|
||||
};
|
||||
|
||||
dnsConfigTun = dnsConfig // {
|
||||
servers = map (s: if s.tag == "local" then s // { detour = "proxy"; } else s) dnsConfig.servers;
|
||||
};
|
||||
|
||||
mkConfig =
|
||||
{
|
||||
enableMixed ? false,
|
||||
enableTProxy ? false,
|
||||
enableTun ? false,
|
||||
tunInterface ? globalTun.interface,
|
||||
tunAddress ? globalTun.address,
|
||||
tunMtu ? globalTun.mtu,
|
||||
tunAutoRoute ? true,
|
||||
tunAutoRedirect ? true,
|
||||
tunStrictRoute ? true,
|
||||
forceLocalDnsViaProxy ? false,
|
||||
useOutboundRoutingMark ? false,
|
||||
enableClashApi ? clashApiEnabled,
|
||||
}:
|
||||
{
|
||||
log.level = "warn";
|
||||
|
||||
dns = if enableTun then dnsConfigTun else dnsConfig;
|
||||
# Keep "local" DNS on the direct path by default, but avoid explicit
|
||||
# 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;
|
||||
};
|
||||
|
||||
inbounds =
|
||||
lib.optional enableMixed {
|
||||
type = "mixed";
|
||||
tag = "mixed-in";
|
||||
listen = sb.listenAddress;
|
||||
listen_port = sb.port;
|
||||
listen = singBoxCfg.listenAddress;
|
||||
listen_port = singBoxCfg.port;
|
||||
}
|
||||
++ lib.optional enableTProxy {
|
||||
type = "tproxy";
|
||||
tag = "tproxy-in";
|
||||
listen = "127.0.0.1";
|
||||
listen_port = sb.tproxyPort;
|
||||
listen_port = globalTproxy.port;
|
||||
}
|
||||
++ lib.optional enableTun {
|
||||
type = "tun";
|
||||
tag = "tun-in";
|
||||
interface_name = sb.tun.interface;
|
||||
address = [ sb.tun.address ];
|
||||
mtu = sb.tun.mtu;
|
||||
auto_route = true;
|
||||
auto_redirect = true;
|
||||
strict_route = true;
|
||||
interface_name = tunInterface;
|
||||
address = [ tunAddress ];
|
||||
mtu = tunMtu;
|
||||
auto_route = tunAutoRoute;
|
||||
auto_redirect = tunAutoRedirect;
|
||||
strict_route = tunStrictRoute;
|
||||
stack = "mixed";
|
||||
};
|
||||
|
||||
@@ -96,7 +114,7 @@ let
|
||||
type = "direct";
|
||||
tag = "direct";
|
||||
}
|
||||
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = sb.proxyMark; }
|
||||
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
|
||||
)
|
||||
{
|
||||
type = "block";
|
||||
@@ -108,11 +126,11 @@ let
|
||||
default_domain_resolver = "local";
|
||||
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
||||
rules = rules.routingRules;
|
||||
final = if sb.proxyByDefault then "proxy" else "direct";
|
||||
final = if singBoxCfg.proxyByDefault then "proxy" else "direct";
|
||||
}
|
||||
// lib.optionalAttrs enableTun { auto_detect_interface = true; };
|
||||
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
|
||||
}
|
||||
// clashApiBlock;
|
||||
// lib.optionalAttrs enableClashApi clashApiBlock;
|
||||
|
||||
tproxyTemplate = mkConfig {
|
||||
enableMixed = true;
|
||||
@@ -122,12 +140,38 @@ let
|
||||
|
||||
tunTemplate = mkConfig {
|
||||
enableTun = true;
|
||||
tunInterface = globalTun.interface;
|
||||
tunAddress = globalTun.address;
|
||||
tunMtu = globalTun.mtu;
|
||||
tunAutoRoute = true;
|
||||
tunAutoRedirect = true;
|
||||
tunStrictRoute = true;
|
||||
forceLocalDnsViaProxy = true;
|
||||
enableClashApi = false;
|
||||
};
|
||||
|
||||
perAppTunTemplate = mkConfig {
|
||||
enableTun = true;
|
||||
tunInterface = perAppTun.interface;
|
||||
tunAddress = perAppTun.address;
|
||||
tunMtu = perAppTun.mtu;
|
||||
tunAutoRoute = false;
|
||||
tunAutoRedirect = false;
|
||||
tunStrictRoute = false;
|
||||
forceLocalDnsViaProxy = false;
|
||||
# App TUN can be used alongside TProxy; mark direct egress so TProxy output
|
||||
# rules do not re-intercept sing-box's own packets.
|
||||
useOutboundRoutingMark = globalTproxy.enable;
|
||||
enableClashApi = false;
|
||||
};
|
||||
|
||||
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
|
||||
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
|
||||
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
|
||||
builtins.toJSON perAppTunTemplate
|
||||
);
|
||||
|
||||
in
|
||||
{
|
||||
inherit tproxyFile tunFile;
|
||||
inherit tproxyFile tunFile perAppTunFile;
|
||||
}
|
||||
@@ -11,48 +11,52 @@
|
||||
|
||||
let
|
||||
cfg = config.services.proxy-suite;
|
||||
packages = import ../../pkgs/default.nix { inherit pkgs; };
|
||||
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
|
||||
in
|
||||
{
|
||||
imports = [
|
||||
./options.nix
|
||||
# Always import the zapret module so its options are available,
|
||||
# but we only activate services when cfg.zapret.enable = true.
|
||||
zapret.nixosModules.default
|
||||
./options
|
||||
];
|
||||
|
||||
config = lib.mkIf cfg.enable (
|
||||
let
|
||||
rules = import ./rules.nix {
|
||||
inherit
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
zapret
|
||||
;
|
||||
};
|
||||
configs = import ./config.nix {
|
||||
inherit
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
rules
|
||||
;
|
||||
};
|
||||
in
|
||||
lib.mkMerge [
|
||||
(lib.mkIf cfg.singBox.enable (
|
||||
let
|
||||
rules = import ./rules.nix {
|
||||
inherit
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
zapret
|
||||
;
|
||||
};
|
||||
configs = import ./config.nix {
|
||||
inherit
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
rules
|
||||
;
|
||||
};
|
||||
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
|
||||
in
|
||||
import ./service.nix {
|
||||
inherit
|
||||
config
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
;
|
||||
inherit (configs) tproxyFile tunFile;
|
||||
inherit (nftr) nftablesRulesFile ip nft;
|
||||
}
|
||||
))
|
||||
(import ./service {
|
||||
inherit
|
||||
config
|
||||
lib
|
||||
pkgs
|
||||
packages
|
||||
cfg
|
||||
;
|
||||
inherit (configs) tproxyFile tunFile perAppTunFile;
|
||||
inherit (nftr)
|
||||
nftablesRulesFile
|
||||
perAppTproxyRulesFile
|
||||
perAppZapretRulesFile
|
||||
perAppTunChainFile
|
||||
ip
|
||||
nft
|
||||
;
|
||||
})
|
||||
|
||||
(lib.mkIf cfg.zapret.enable (
|
||||
import ./zapret.nix {
|
||||
@@ -62,10 +66,20 @@ in
|
||||
cfg
|
||||
zapret
|
||||
;
|
||||
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 (
|
||||
import ./tray.nix {
|
||||
@@ -73,6 +87,7 @@ in
|
||||
config
|
||||
lib
|
||||
pkgs
|
||||
packages
|
||||
cfg
|
||||
;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
lib,
|
||||
cfg,
|
||||
}:
|
||||
|
||||
let
|
||||
singBoxCfg = cfg.singBox;
|
||||
perAppRoutingCfg = cfg.perAppRouting;
|
||||
globalTun = singBoxCfg.tun;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppRoutingTun = singBoxCfg.tun.perApp;
|
||||
perAppRoutingTproxy = singBoxCfg.tproxy.perApp;
|
||||
perAppZapretCfg = cfg.zapret.perApp;
|
||||
userControlCfg = cfg.userControl;
|
||||
|
||||
selectionMode = singBoxCfg.selection;
|
||||
builtinTags = [
|
||||
"proxy"
|
||||
"direct"
|
||||
"block"
|
||||
];
|
||||
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds;
|
||||
subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions;
|
||||
|
||||
hasStaticOutbounds = singBoxCfg.outbounds != [ ];
|
||||
hasSubscriptions = singBoxCfg.subscriptions != [ ];
|
||||
collapseNamedOutbounds = selectionMode == "first";
|
||||
clashApiEnabled = selectionMode != "first";
|
||||
perAppZapretEnabled = cfg.zapret.enable && 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)
|
||||
) singBoxCfg.routing.rules
|
||||
)
|
||||
);
|
||||
in
|
||||
{
|
||||
inherit
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
perAppZapretEnabled
|
||||
userControlCfg
|
||||
userControlEnabled
|
||||
selectionMode
|
||||
builtinTags
|
||||
outboundTags
|
||||
subscriptionTags
|
||||
hasStaticOutbounds
|
||||
hasSubscriptions
|
||||
collapseNamedOutbounds
|
||||
clashApiEnabled
|
||||
invalidRoutingTargets
|
||||
;
|
||||
}
|
||||
@@ -6,46 +6,113 @@
|
||||
}:
|
||||
|
||||
let
|
||||
sb = cfg.singBox;
|
||||
singBoxCfg = cfg.singBox;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppTun = singBoxCfg.tun.perApp;
|
||||
perAppTproxy = singBoxCfg.tproxy.perApp;
|
||||
zapretApp = cfg.zapret.perApp;
|
||||
|
||||
localSubnetLines = lib.concatMapStrings (cidr: ''
|
||||
ip daddr ${cidr} tcp dport != 53 return
|
||||
ip daddr ${cidr} udp dport != 53 return
|
||||
'') sb.tproxy.localSubnets;
|
||||
# Shared across all three nftables rule files that do IPv4 routing.
|
||||
reservedIpBlock = ''
|
||||
define RESERVED_IP = {
|
||||
10.0.0.0/8,
|
||||
100.64.0.0/10,
|
||||
127.0.0.0/8,
|
||||
169.254.0.0/16,
|
||||
172.16.0.0/12,
|
||||
192.0.0.0/24,
|
||||
224.0.0.0/4,
|
||||
240.0.0.0/4,
|
||||
255.255.255.255/32
|
||||
}
|
||||
'';
|
||||
|
||||
mkLocalSubnetLines =
|
||||
subnets:
|
||||
lib.concatMapStrings (cidr: ''
|
||||
ip daddr ${cidr} tcp dport != 53 return
|
||||
ip daddr ${cidr} udp dport != 53 return
|
||||
'') subnets;
|
||||
|
||||
tproxyLocalSubnetLines = mkLocalSubnetLines globalTproxy.localSubnets;
|
||||
perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets;
|
||||
|
||||
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
|
||||
define RESERVED_IP = {
|
||||
10.0.0.0/8,
|
||||
100.64.0.0/10,
|
||||
127.0.0.0/8,
|
||||
169.254.0.0/16,
|
||||
172.16.0.0/12,
|
||||
192.0.0.0/24,
|
||||
224.0.0.0/4,
|
||||
240.0.0.0/4,
|
||||
255.255.255.255/32
|
||||
}
|
||||
${reservedIpBlock}
|
||||
table ip singbox {
|
||||
chain prerouting {
|
||||
type filter hook prerouting priority mangle; policy accept;
|
||||
ip daddr $RESERVED_IP return
|
||||
# Packets re-entering via loopback after output marking should not
|
||||
# be skipped just because the host has an RFC1918 source address.
|
||||
iifname != "lo" ip saddr $RESERVED_IP return
|
||||
${tproxyLocalSubnetLines}
|
||||
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 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
|
||||
${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}
|
||||
}
|
||||
}
|
||||
'';
|
||||
|
||||
table ip singbox {
|
||||
chain prerouting {
|
||||
type filter hook prerouting priority mangle; policy accept;
|
||||
ip daddr $RESERVED_IP return
|
||||
# Packets re-entering via loopback after output marking should not
|
||||
# be skipped just because the host has an RFC1918 source address.
|
||||
iifname != "lo" ip saddr $RESERVED_IP return
|
||||
${localSubnetLines}
|
||||
ip protocol tcp 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 sb.tproxyPort} meta mark set ${toString sb.fwmark}
|
||||
perAppTproxyRulesFile = pkgs.writeText "proxy-suite-per-app-tproxy.nft" ''
|
||||
${reservedIpBlock}
|
||||
table ip proxy_suite_per_app_tproxy {
|
||||
chain prerouting {
|
||||
type filter hook prerouting priority mangle; policy accept;
|
||||
ip daddr $RESERVED_IP return
|
||||
iifname != "lo" ip saddr $RESERVED_IP return
|
||||
${perAppTproxyLocalSubnetLines}
|
||||
ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark}
|
||||
meta mark ${toString perAppTproxy.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString globalTproxy.port}
|
||||
meta mark ${toString perAppTproxy.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString globalTproxy.port}
|
||||
}
|
||||
|
||||
chain output {
|
||||
type route hook output priority mangle; policy accept;
|
||||
ip daddr $RESERVED_IP return
|
||||
${perAppTproxyLocalSubnetLines}
|
||||
meta mark ${toString globalTproxy.proxyMark} return
|
||||
${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 perAppTproxy.fwmark} return
|
||||
}
|
||||
}
|
||||
chain output {
|
||||
type route hook output priority mangle; policy accept;
|
||||
ip daddr $RESERVED_IP return
|
||||
${localSubnetLines}
|
||||
meta mark ${toString sb.proxyMark} return
|
||||
ip protocol tcp meta mark set ${toString sb.fwmark}
|
||||
ip protocol udp meta mark set ${toString sb.fwmark}
|
||||
'';
|
||||
|
||||
perAppZapretRulesFile = pkgs.writeText "proxy-suite-per-app-zapret.nft" ''
|
||||
table inet proxy_suite_per_app_zapret_mark {
|
||||
chain prerouting {
|
||||
type filter hook prerouting priority -103; policy accept;
|
||||
ct mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} meta mark set meta mark or ${toString zapretApp.filterMark}
|
||||
}
|
||||
|
||||
chain output {
|
||||
type route hook output priority -103; policy accept;
|
||||
ct mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} meta mark set meta mark or ${toString zapretApp.filterMark}
|
||||
meta mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} return
|
||||
}
|
||||
}
|
||||
'';
|
||||
|
||||
perAppTunChainFile = pkgs.writeText "proxy-suite-per-app-tun-chain.nft" ''
|
||||
${reservedIpBlock}
|
||||
table inet proxy_suite_per_app_tun {
|
||||
chain output {
|
||||
type route hook output priority mangle; policy accept;
|
||||
ip daddr $RESERVED_IP return
|
||||
${lib.concatMapStrings (cidr: ''
|
||||
ip daddr ${cidr} return
|
||||
'') perAppTun.localSubnets}
|
||||
ct mark ${toString perAppTun.fwmark} meta mark set ${toString perAppTun.fwmark}
|
||||
meta mark ${toString perAppTun.fwmark} return
|
||||
}
|
||||
}
|
||||
}
|
||||
'';
|
||||
|
||||
ip = "${pkgs.iproute2}/bin/ip";
|
||||
@@ -53,5 +120,12 @@ let
|
||||
|
||||
in
|
||||
{
|
||||
inherit nftablesRulesFile ip nft;
|
||||
inherit
|
||||
nftablesRulesFile
|
||||
perAppTproxyRulesFile
|
||||
perAppZapretRulesFile
|
||||
perAppTunChainFile
|
||||
ip
|
||||
nft
|
||||
;
|
||||
}
|
||||
@@ -1,686 +0,0 @@
|
||||
# All option declarations for services.proxy-suite
|
||||
{ config, lib, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkOption mkEnableOption 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.";
|
||||
example = [
|
||||
"youtube.com"
|
||||
"discord.com"
|
||||
];
|
||||
};
|
||||
ips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "IP CIDRs to match.";
|
||||
example = [ "1.1.1.0/24" ];
|
||||
};
|
||||
geosites = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "sing-geosite rule-set names to match.";
|
||||
example = [
|
||||
"netflix"
|
||||
"google"
|
||||
];
|
||||
};
|
||||
geoips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "sing-geoip rule-set names to match.";
|
||||
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".
|
||||
'';
|
||||
example = "vps-de";
|
||||
};
|
||||
}
|
||||
// routingFields;
|
||||
};
|
||||
|
||||
subscriptionType = types.submodule {
|
||||
options = {
|
||||
tag = mkOption {
|
||||
type = types.str;
|
||||
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".
|
||||
'';
|
||||
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.
|
||||
The URL will end up in the nix store. Use urlFile for actual secrets.
|
||||
'';
|
||||
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.
|
||||
'';
|
||||
example = "/run/secrets/my-sub-url";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
outboundType = types.submodule {
|
||||
options = {
|
||||
tag = mkOption {
|
||||
type = types.str;
|
||||
description = "Outbound tag. Used in routing rules and multi-outbound selection.";
|
||||
example = "vps-de";
|
||||
};
|
||||
|
||||
urlFile = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = ''
|
||||
Runtime path to a file containing the proxy URL.
|
||||
Intended for use with secret managers (sops-nix, agenix, etc.).
|
||||
The file is read at service start time and never lands in the nix store.
|
||||
|
||||
Example with sops-nix:
|
||||
urlFile = config.sops.secrets.my_proxy_url.path;
|
||||
'';
|
||||
};
|
||||
|
||||
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. Use urlFile for actual credentials.
|
||||
'';
|
||||
example = "hy2://password@example.com:443?sni=example.com";
|
||||
};
|
||||
|
||||
json = 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.
|
||||
'';
|
||||
example = {
|
||||
type = "vless";
|
||||
server = "example.com";
|
||||
server_port = 443;
|
||||
uuid = "...";
|
||||
};
|
||||
};
|
||||
|
||||
# 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;
|
||||
};
|
||||
};
|
||||
|
||||
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 list-<name>.txt.";
|
||||
example = "cloudflare";
|
||||
};
|
||||
|
||||
domains = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Domains written into the generated custom zapret hostlist.";
|
||||
example = [
|
||||
"example.com"
|
||||
"example.de"
|
||||
];
|
||||
};
|
||||
|
||||
preset = mkOption {
|
||||
type = types.nullOr zapretPresetType;
|
||||
default = null;
|
||||
description = "Clone the active zapret config's built-in rule family for this hostlist.";
|
||||
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.
|
||||
'';
|
||||
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 sing-box direct domain routing.";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite = {
|
||||
enable = mkEnableOption "proxy suite (sing-box + zapret + tg-ws-proxy)";
|
||||
|
||||
singBox = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Whether to configure and run sing-box.";
|
||||
};
|
||||
|
||||
outbounds = mkOption {
|
||||
type = types.listOf outboundType;
|
||||
default = [ ];
|
||||
description = ''
|
||||
List of proxy outbounds. Set exactly one of urlFile, url, or json per entry.
|
||||
At least one outbound (or one subscription) is required when singBox.enable = true.
|
||||
'';
|
||||
};
|
||||
|
||||
subscriptions = mkOption {
|
||||
type = types.listOf 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 the subscription is fetched live. Subsequent starts
|
||||
use the on-disk cache under /var/lib/proxy-suite/subscriptions/.
|
||||
|
||||
A systemd timer (proxy-suite-subscription-update) refreshes all caches on
|
||||
the interval set by subscriptionUpdateInterval and restarts the service.
|
||||
'';
|
||||
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 subscriptions is non-empty.
|
||||
'';
|
||||
example = "6h";
|
||||
};
|
||||
|
||||
selection = mkOption {
|
||||
type = types.enum [
|
||||
"first"
|
||||
"selector"
|
||||
"urltest"
|
||||
];
|
||||
default = "first";
|
||||
description = ''
|
||||
How to pick between multiple outbounds:
|
||||
- "first": use the first outbound only (no overhead, simplest)
|
||||
- "selector": expose a Clash-compatible API for manual switching
|
||||
- "urltest": measure latency periodically and auto-switch to the fastest
|
||||
'';
|
||||
};
|
||||
|
||||
urlTest = {
|
||||
url = mkOption {
|
||||
type = types.str;
|
||||
default = "https://www.gstatic.com/generate_204";
|
||||
description = ''
|
||||
URL that sing-box 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 sing-box re-tests all outbounds. Accepts a Go duration
|
||||
string (e.g. "1m", "3m", "10m"). Only used when selection = "urltest".
|
||||
'';
|
||||
example = "1m";
|
||||
};
|
||||
|
||||
tolerance = mkOption {
|
||||
type = types.int;
|
||||
default = 50;
|
||||
description = ''
|
||||
Latency tolerance in milliseconds. The current proxy is only replaced
|
||||
when a competing one is faster by more than this value.
|
||||
Only used when selection = "urltest".
|
||||
'';
|
||||
example = 100;
|
||||
};
|
||||
};
|
||||
|
||||
clashApiPort = mkOption {
|
||||
type = types.port;
|
||||
default = 9090;
|
||||
description = "Port for the Clash-compatible REST API. Only used when selection is selector or urltest.";
|
||||
};
|
||||
|
||||
listenAddress = mkOption {
|
||||
type = types.str;
|
||||
default = "127.0.0.1";
|
||||
description = ''
|
||||
Address for the SOCKS5/HTTP mixed inbound to bind to.
|
||||
Use "0.0.0.0" only if you intentionally want to expose the proxy.
|
||||
'';
|
||||
};
|
||||
|
||||
port = mkOption {
|
||||
type = types.port;
|
||||
default = 1080;
|
||||
description = "SOCKS5/HTTP mixed inbound listen port.";
|
||||
};
|
||||
|
||||
tproxyPort = mkOption {
|
||||
type = types.port;
|
||||
default = 1081;
|
||||
description = "Transparent proxy (TProxy) inbound listen port.";
|
||||
};
|
||||
|
||||
fwmark = mkOption {
|
||||
type = types.int;
|
||||
default = 1;
|
||||
description = "Netfilter mark set on packets intercepted by TProxy for policy routing.";
|
||||
};
|
||||
|
||||
proxyMark = mkOption {
|
||||
type = types.int;
|
||||
default = 2;
|
||||
description = "Netfilter mark set on sing-box's own outbound packets so they bypass TProxy re-interception.";
|
||||
};
|
||||
|
||||
routeTable = mkOption {
|
||||
type = types.int;
|
||||
default = 100;
|
||||
description = "Policy routing table used to redirect TProxy-marked packets to the loopback interface.";
|
||||
};
|
||||
|
||||
proxyByDefault = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "If true, traffic not matching any routing rule goes through the proxy. If false, it goes direct.";
|
||||
};
|
||||
|
||||
tun = {
|
||||
enable = mkEnableOption "TUN mode service (opt-in, mutually exclusive with proxy-suite-tproxy)";
|
||||
|
||||
interface = mkOption {
|
||||
type = types.str;
|
||||
default = "singtun0";
|
||||
description = "TUN interface name.";
|
||||
};
|
||||
|
||||
address = mkOption {
|
||||
type = types.str;
|
||||
default = "172.19.0.1/30";
|
||||
description = "TUN interface address (CIDR).";
|
||||
};
|
||||
|
||||
mtu = mkOption {
|
||||
type = types.int;
|
||||
default = 1400;
|
||||
description = "TUN interface MTU.";
|
||||
};
|
||||
};
|
||||
|
||||
tproxy = {
|
||||
enable = mkEnableOption "TProxy mode service (opt-in, transparent proxy via nftables)";
|
||||
|
||||
localSubnets = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ "192.168.0.0/16" ];
|
||||
description = ''
|
||||
Subnets whose traffic bypasses TProxy interception, except DNS (port 53).
|
||||
Typically your LAN subnet(s). VM bridge networks should go here too,
|
||||
or use zapret.cidrExemption for subnet-specific NFQUEUE exemption.
|
||||
'';
|
||||
example = [
|
||||
"192.168.0.0/16"
|
||||
"10.0.0.0/8"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
routing = {
|
||||
enableRuDirect = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Automatically send sing-geosite category-ru and sing-geoip ru traffic direct.";
|
||||
};
|
||||
|
||||
proxy = routingFields;
|
||||
|
||||
direct = {
|
||||
domains = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Domain suffixes to send direct (bypass proxy).";
|
||||
};
|
||||
ips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "IP CIDRs to send direct.";
|
||||
};
|
||||
geosites = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "sing-geosite names to send direct.";
|
||||
};
|
||||
geoips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "sing-geoip names to send direct.";
|
||||
};
|
||||
};
|
||||
|
||||
block = {
|
||||
domains = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Domain suffixes to block entirely.";
|
||||
};
|
||||
ips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "IP CIDRs to block.";
|
||||
};
|
||||
geosites = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "sing-geosite names to block.";
|
||||
};
|
||||
geoips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "sing-geoip names to block.";
|
||||
};
|
||||
};
|
||||
|
||||
# Per-outbound and per-action routing rules.
|
||||
# These are evaluated before the global proxy/direct/block lists above.
|
||||
# Use this for fine-grained control: route specific services to specific
|
||||
# servers, or override the default for particular domains/IPs/geos.
|
||||
#
|
||||
# Alternatively, attach routing directly to an outbound via outbound.routing.*
|
||||
# which is equivalent to adding an entry here with outbound = <that tag>.
|
||||
#
|
||||
# Order within this list is preserved (first matching rule wins in sing-box).
|
||||
rules = mkOption {
|
||||
type = types.listOf 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".
|
||||
'';
|
||||
example = [
|
||||
{
|
||||
outbound = "vps-de";
|
||||
geosites = [ "netflix" ];
|
||||
geoips = [ "us" ];
|
||||
}
|
||||
{
|
||||
outbound = "direct";
|
||||
domains = [ "internal.corp" ];
|
||||
}
|
||||
{
|
||||
outbound = "block";
|
||||
domains = [ "ads.example.com" ];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
zapret = {
|
||||
enable = mkEnableOption "zapret DPI bypass";
|
||||
|
||||
syncDirectRouting = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "When zapret is enabled, mirror its upstream domain hostlists into sing-box direct routing.";
|
||||
};
|
||||
|
||||
syncDirectRoutingUpstreamIps = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
description = "When zapret is enabled, mirror its upstream ipset ranges into sing-box direct routing.";
|
||||
};
|
||||
|
||||
syncDirectRoutingUserIps = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "When zapret is enabled, mirror user-defined ipsetAll/ipsetExclude entries into sing-box direct routing.";
|
||||
};
|
||||
|
||||
configName = mkOption {
|
||||
type = types.str;
|
||||
default = "general(ALT)";
|
||||
description = "zapret strategy preset name.";
|
||||
};
|
||||
|
||||
gameFilter = mkOption {
|
||||
type = types.str;
|
||||
default = "null";
|
||||
description = ''zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.'';
|
||||
};
|
||||
|
||||
listGeneral = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Extra domains to include in zapret's interception list.";
|
||||
};
|
||||
|
||||
listExclude = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Domains to exclude from zapret interception.";
|
||||
};
|
||||
|
||||
ipsetAll = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Extra IPs/CIDRs to add to zapret's ipset.";
|
||||
};
|
||||
|
||||
ipsetExclude = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "IPs/CIDRs to exclude from zapret's ipset.";
|
||||
};
|
||||
|
||||
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.
|
||||
'';
|
||||
};
|
||||
|
||||
hostlistRules = mkOption {
|
||||
type = types.listOf 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.
|
||||
'';
|
||||
example = [
|
||||
{
|
||||
name = "googlevideo";
|
||||
domains = [
|
||||
"googlevideo.com"
|
||||
"ggpht.com"
|
||||
];
|
||||
preset = "google";
|
||||
}
|
||||
{
|
||||
name = "example";
|
||||
domains = [
|
||||
"example.com"
|
||||
"example.de"
|
||||
];
|
||||
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.
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
tray = {
|
||||
enable = mkEnableOption "system tray indicator for proxy-suite";
|
||||
|
||||
pollInterval = mkOption {
|
||||
type = types.int;
|
||||
default = 5;
|
||||
description = "Status polling interval in seconds.";
|
||||
};
|
||||
|
||||
autostart = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Whether to autostart the tray application for all graphical users via XDG desktop autostart.";
|
||||
};
|
||||
};
|
||||
|
||||
tgWsProxy = {
|
||||
enable = mkEnableOption "Telegram MTProto WebSocket proxy";
|
||||
|
||||
port = mkOption {
|
||||
type = types.port;
|
||||
default = 1076;
|
||||
description = "Port to listen on.";
|
||||
};
|
||||
|
||||
host = mkOption {
|
||||
type = types.str;
|
||||
default = "0.0.0.0";
|
||||
description = "Address to bind to.";
|
||||
};
|
||||
|
||||
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.
|
||||
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.
|
||||
'';
|
||||
example = "/run/secrets/tg-ws-proxy-secret";
|
||||
};
|
||||
|
||||
dcIps = mkOption {
|
||||
type = types.attrsOf types.str;
|
||||
default = {
|
||||
"2" = "149.154.167.220";
|
||||
"4" = "149.154.167.220";
|
||||
};
|
||||
description = "Map of Telegram DC ID to IP address for relay.";
|
||||
example = {
|
||||
"1" = "149.154.175.50";
|
||||
"2" = "149.154.167.51";
|
||||
"3" = "149.154.175.100";
|
||||
"4" = "149.154.167.91";
|
||||
"5" = "91.108.56.130";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# All option declarations for services.proxy-suite, split by feature area.
|
||||
{ ... }:
|
||||
{
|
||||
imports = [
|
||||
./other.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,135 @@
|
||||
# Top-level, userControl, tray, and tgWsProxy options.
|
||||
{ lib, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkOption mkEnableOption types;
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite = {
|
||||
enable = mkEnableOption "proxy suite (sing-box + 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";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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 singBox.tun.perApp.enable = true
|
||||
- `tproxy`: route = "tproxy" when singBox.tproxy.perApp.enable = true
|
||||
- `zapret`: route = "zapret" when zapret.perApp.enable = true and
|
||||
zapret.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 singBox.enable = true and the
|
||||
local proxy-suite mixed proxy listener provided by sing-box. The
|
||||
"tun" route depends on singBox.tun.perApp.enable = true. The "tproxy"
|
||||
route depends on singBox.tproxy.perApp.enable = true. The "zapret"
|
||||
route depends on zapret.perApp.enable = true and zapret.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.singBox.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 sing-box route.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 singBox.proxyByDefault = true.
|
||||
'';
|
||||
example = {
|
||||
type = "tls";
|
||||
address = "1.1.1.1";
|
||||
port = 853;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
{ lib, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkOption types;
|
||||
t = import ./types.nix { inherit lib; };
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox = {
|
||||
outbounds = mkOption {
|
||||
type = types.listOf t.outboundType;
|
||||
default = [ ];
|
||||
description = ''
|
||||
List of static proxy outbounds.
|
||||
Set exactly one of urlFile, url, or json per entry.
|
||||
|
||||
At least one outbound or one subscription is required when
|
||||
singBox.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/<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
|
||||
sing-box 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 singBox.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 an automatic latency-testing outbound tagged
|
||||
"proxy" and keep all configured outbounds available so sing-box
|
||||
can periodically probe and switch to a faster one.
|
||||
|
||||
clashApiPort is only used with "selector" or "urltest".
|
||||
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 sing-box 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 sing-box re-tests all outbounds. Accepts a Go duration
|
||||
string (e.g. "1m", "3m", "10m").
|
||||
Only used when selection = "urltest".
|
||||
'';
|
||||
example = "1m";
|
||||
};
|
||||
|
||||
tolerance = mkOption {
|
||||
type = types.int;
|
||||
default = 50;
|
||||
description = ''
|
||||
Latency tolerance in milliseconds. The current proxy is only replaced
|
||||
when a competing one is faster by more than this value.
|
||||
|
||||
Only used when selection = "urltest".
|
||||
'';
|
||||
example = 100;
|
||||
};
|
||||
};
|
||||
|
||||
clashApiPort = mkOption {
|
||||
type = types.port;
|
||||
default = 9090;
|
||||
description = ''
|
||||
Port for the Clash-compatible REST API exposed by sing-box.
|
||||
Only used when selection is "selector" or "urltest". Ignored in
|
||||
"first" mode because there is no selector-style outbound to control.
|
||||
'';
|
||||
example = 9090;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
{ lib, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkOption types;
|
||||
t = import ./types.nix { inherit lib; };
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox.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 sing-box.
|
||||
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.singBox.tproxy = {
|
||||
enable = mkEnableOption "global sing-box 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 singBox.tun.autostart.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
port = mkOption {
|
||||
type = types.port;
|
||||
default = 1081;
|
||||
description = ''
|
||||
Local listen port for sing-box'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
|
||||
singBox.tproxy.routeTable, which points traffic to
|
||||
loopback for local proxy processing.
|
||||
'';
|
||||
example = 1;
|
||||
};
|
||||
|
||||
proxyMark = mkOption {
|
||||
type = types.int;
|
||||
default = 2;
|
||||
description = ''
|
||||
Mark applied to sing-box 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 singBox.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 sing-box 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.singBox.tun = {
|
||||
enable = mkEnableOption "global sing-box 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 singBox.tproxy.autostart.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
perApp = {
|
||||
enable = mkEnableOption "per-app-scoped sing-box 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,55 @@
|
||||
# Core sing-box options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix.
|
||||
{ lib, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkOption mkEnableOption types;
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Whether to configure and run sing-box services for proxy-suite.
|
||||
When disabled, sing-box services and generated sing-box configs are
|
||||
skipped even if proxy-suite itself is enabled.
|
||||
'';
|
||||
};
|
||||
|
||||
listenAddress = mkOption {
|
||||
type = types.str;
|
||||
default = "127.0.0.1";
|
||||
description = ''
|
||||
Address for the SOCKS5/HTTP mixed inbound to bind to.
|
||||
This affects the always-on 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 always-on SOCKS5/HTTP mixed inbound provided by
|
||||
proxy-suite-socks.
|
||||
'';
|
||||
example = 1080;
|
||||
};
|
||||
|
||||
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 sing-box route.final and dns.final in the generated
|
||||
config.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
# 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 sing-box 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 sing-box 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/, 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", sing-box
|
||||
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";
|
||||
};
|
||||
|
||||
json = 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, or json for each outbound.
|
||||
Use this when the proxy definition is easier to generate as native Nix
|
||||
than as a single URL string.
|
||||
'';
|
||||
example = {
|
||||
type = "vless";
|
||||
server = "example.com";
|
||||
server_port = 443;
|
||||
uuid = "...";
|
||||
};
|
||||
};
|
||||
|
||||
# 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 = ''
|
||||
sing-box 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 sing-box
|
||||
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 sing-box 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 sing-box 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 sing-box 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 sing-box 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
|
||||
sing-box 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 sing-box 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 sing-box 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 sing-box 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 sing-box 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.
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -7,9 +7,10 @@
|
||||
}:
|
||||
|
||||
let
|
||||
derived = import ./derived.nix { inherit lib cfg; };
|
||||
r = cfg.singBox.routing;
|
||||
sb = cfg.singBox;
|
||||
z = cfg.zapret;
|
||||
singBoxCfg = derived.singBoxCfg;
|
||||
zapretCfg = cfg.zapret;
|
||||
|
||||
trim = lib.strings.trim;
|
||||
hasPrefix = lib.strings.hasPrefix;
|
||||
@@ -27,16 +28,16 @@ let
|
||||
|
||||
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
|
||||
|
||||
syncZapretDirectDomains = z.enable && z.syncDirectRouting;
|
||||
syncZapretDirectUpstreamIps = z.enable && z.syncDirectRoutingUpstreamIps;
|
||||
syncZapretDirectUserIps = z.enable && z.syncDirectRoutingUserIps;
|
||||
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
|
||||
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
|
||||
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
|
||||
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
|
||||
|
||||
zapretDefaultDomainFiles = [
|
||||
"list-general.txt"
|
||||
"list-google.txt"
|
||||
]
|
||||
++ lib.optionals z.includeExtraUpstreamLists [
|
||||
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
|
||||
"list-instagram.txt"
|
||||
"list-soundcloud.txt"
|
||||
"list-twitter.txt"
|
||||
@@ -51,10 +52,12 @@ let
|
||||
[ ];
|
||||
zapretDefaultIps =
|
||||
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 =
|
||||
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
|
||||
[ ];
|
||||
zapretExcludedDomains =
|
||||
@@ -66,13 +69,13 @@ let
|
||||
else
|
||||
[ ]
|
||||
)
|
||||
++ (if syncZapretDirectUserIps then z.ipsetExclude else [ ])
|
||||
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
|
||||
);
|
||||
|
||||
zapretDirectDomains =
|
||||
if syncZapretDirectDomains then
|
||||
subtractItems (lib.unique (zapretDefaultDomains ++ z.listGeneral ++ zapretCustomDomains)) (
|
||||
lib.unique (zapretExcludedDomains ++ z.listExclude)
|
||||
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
|
||||
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
|
||||
)
|
||||
else
|
||||
[ ];
|
||||
@@ -89,37 +92,22 @@ let
|
||||
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
|
||||
};
|
||||
|
||||
mkDomainRule =
|
||||
tag: domains:
|
||||
lib.optional (domains != [ ]) {
|
||||
domain_suffix = domains;
|
||||
outbound = tag;
|
||||
};
|
||||
|
||||
mkIPRule =
|
||||
tag: ips:
|
||||
lib.optional (ips != [ ]) {
|
||||
ip_cidr = ips;
|
||||
outbound = tag;
|
||||
};
|
||||
|
||||
mkRulesetRule =
|
||||
tag: tags:
|
||||
lib.optional (tags != [ ]) {
|
||||
rule_set = tags;
|
||||
mkRule =
|
||||
field: tag: items:
|
||||
lib.optional (items != [ ]) {
|
||||
${field} = items;
|
||||
outbound = tag;
|
||||
};
|
||||
mkDomainRule = mkRule "domain_suffix";
|
||||
mkIPRule = mkRule "ip_cidr";
|
||||
mkRulesetRule = mkRule "rule_set";
|
||||
|
||||
# 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
|
||||
# to "proxy" instead of the original tag (which won't exist in sing-box).
|
||||
builtinTags = [
|
||||
"proxy"
|
||||
"direct"
|
||||
"block"
|
||||
];
|
||||
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 tag;
|
||||
|
||||
# Collect per-outbound routing attached directly to outbound definitions.
|
||||
perOutboundRules = lib.concatMap (
|
||||
@@ -137,7 +125,7 @@ let
|
||||
geoips
|
||||
;
|
||||
}
|
||||
) sb.outbounds;
|
||||
) singBoxCfg.outbounds;
|
||||
|
||||
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
||||
customRules =
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
{
|
||||
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)
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
;
|
||||
|
||||
featureAssertions = [
|
||||
(requireAvailable singBoxCfg.enable (
|
||||
singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]
|
||||
) "proxy-suite: at least one outbound or subscription is required when singBox.enable = true")
|
||||
(uniqueValues singBoxCfg.enable outboundTags "proxy-suite: outbound tags must be unique")
|
||||
(uniqueValues singBoxCfg.enable subscriptionTags
|
||||
"proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes"
|
||||
)
|
||||
(mkAssertion (
|
||||
!singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags
|
||||
) "proxy-suite: outbound tags must not use reserved names: proxy, direct, block")
|
||||
(mkAssertion (!singBoxCfg.enable || invalidRoutingTargets == [ ])
|
||||
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
|
||||
)
|
||||
(requireEnabled globalTun.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tun.enable requires singBox.enable = true"
|
||||
)
|
||||
(requireEnabled globalTproxy.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tproxy.enable requires singBox.enable = true"
|
||||
)
|
||||
(requireEnabled globalTun.autostart globalTun.enable
|
||||
"proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true"
|
||||
)
|
||||
(requireEnabled globalTproxy.autostart globalTproxy.enable
|
||||
"proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true"
|
||||
)
|
||||
(mkAssertion
|
||||
(!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart))
|
||||
"proxy-suite: singBox.tproxy.autostart and singBox.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 singBoxCfg.enable
|
||||
"proxy-suite: perAppRouting.proxychains.enable requires singBox.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 singBoxCfg.enable
|
||||
"proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTun.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true"
|
||||
)
|
||||
(requireAvailable hasTunProfiles perAppRoutingTun.enable
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true"
|
||||
)
|
||||
(requireAvailable hasTunProfiles singBoxCfg.enable
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTproxy.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true"
|
||||
)
|
||||
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true"
|
||||
)
|
||||
(requireAvailable hasTproxyProfiles singBoxCfg.enable
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true"
|
||||
)
|
||||
(requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppZapretCfg.enable cfg.zapret.enable
|
||||
"proxy-suite: zapret.perApp.enable requires zapret.enable = true"
|
||||
)
|
||||
(requireAvailable hasZapretProfiles (perAppZapretCfg.enable && cfg.zapret.enable)
|
||||
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true and zapret.enable = true"
|
||||
)
|
||||
];
|
||||
|
||||
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = globalTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.routeTable;
|
||||
right = globalTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.routeTable must differ from singBox.tproxy.routeTable";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = perAppRoutingTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and singBox.tproxy.perApp.fwmark must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = perAppRoutingTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tun.perApp.routeTable and singBox.tproxy.perApp.routeTable must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
left = perAppZapretCfg.filterMark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
left = perAppZapretCfg.filterMark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
];
|
||||
|
||||
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 = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = globalTproxy.proxyMark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||
value = perAppRoutingTun.fwmark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
|
||||
value = perAppRoutingTproxy.fwmark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = perAppZapretCfg.filterMark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: zapret.perApp.filterMark 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 singBoxCfg.enable [
|
||||
ob.urlFile
|
||||
ob.url
|
||||
ob.json
|
||||
] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json")
|
||||
]) singBoxCfg.outbounds;
|
||||
|
||||
subscriptionAssertions = lib.concatMap (sub: [
|
||||
(exactlyOneOf singBoxCfg.enable [
|
||||
sub.urlFile
|
||||
sub.url
|
||||
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
|
||||
]) singBoxCfg.subscriptions;
|
||||
in
|
||||
featureAssertions
|
||||
++ perAppRoutingAssertions
|
||||
++ collisionAssertions
|
||||
++ forbiddenValueAssertions
|
||||
++ secretAssertions
|
||||
++ outboundAssertions
|
||||
++ subscriptionAssertions
|
||||
@@ -1,547 +0,0 @@
|
||||
# Systemd services for sing-box
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
cfg,
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
nftablesRulesFile,
|
||||
ip,
|
||||
nft,
|
||||
}:
|
||||
|
||||
let
|
||||
sb = cfg.singBox;
|
||||
t = cfg.tgWsProxy;
|
||||
builtinTags = [
|
||||
"proxy"
|
||||
"direct"
|
||||
"block"
|
||||
];
|
||||
outboundTags = map (ob: ob.tag) sb.outbounds;
|
||||
invalidRoutingTargets = lib.unique (
|
||||
map (rule: rule.outbound) (
|
||||
builtins.filter (rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)) sb.routing.rules
|
||||
)
|
||||
);
|
||||
|
||||
jq = "${pkgs.jq}/bin/jq";
|
||||
python3 = "${pkgs.python3}/bin/python3";
|
||||
singBox = "${pkgs.sing-box}/bin/sing-box";
|
||||
|
||||
fetchSubscriptionPy = ../../scripts/fetch-subscription.py;
|
||||
|
||||
# Build the shell code block for a single outbound entry.
|
||||
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
|
||||
# routingMark is null or an int; added to outbound JSON if set.
|
||||
mkOutboundBlock =
|
||||
ob: routingMark: tag:
|
||||
let
|
||||
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
|
||||
in
|
||||
if ob.json != null then
|
||||
let
|
||||
outboundJson = builtins.toJSON (
|
||||
ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
|
||||
);
|
||||
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (static json)
|
||||
OB_JSON=$(cat ${lib.escapeShellArg jsonFile})
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else
|
||||
let
|
||||
urlSource =
|
||||
if ob.urlFile != null then
|
||||
ob.urlFile
|
||||
else
|
||||
# Literal URL – write to nix store so the script can cat it.
|
||||
# Less secret than urlFile, but convenient for non-sensitive configs.
|
||||
"${pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url}";
|
||||
in
|
||||
''
|
||||
# outbound: ${tag}
|
||||
URL=$(cat ${lib.escapeShellArg urlSource})
|
||||
OB_JSON=$(printf '%s' "$URL" | ${python3} ${../../scripts/build-outbound.py} --tag ${lib.escapeShellArg tag}${markArg})
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
|
||||
# Build the shell code block for a single subscription entry.
|
||||
# Fetches subscription into the cache on first run; subsequent starts use the cache.
|
||||
mkSubscriptionBlock =
|
||||
sub: routingMark:
|
||||
let
|
||||
urlSource =
|
||||
if sub.urlFile != null then
|
||||
sub.urlFile
|
||||
else
|
||||
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
|
||||
in
|
||||
''
|
||||
# subscription: ${sub.tag}
|
||||
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||
CACHE_FILE="$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
|
||||
if [ ! -f "$CACHE_FILE" ]; then
|
||||
mkdir -p "$CACHE_DIR"
|
||||
SUB_URL=$(cat ${lib.escapeShellArg urlSource})
|
||||
if printf '%s' "$SUB_URL" \
|
||||
| ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} \
|
||||
> "$CACHE_FILE.tmp"; then
|
||||
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
|
||||
else
|
||||
rm -f "$CACHE_FILE.tmp"
|
||||
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
|
||||
fi
|
||||
fi
|
||||
if [ -f "$CACHE_FILE" ]; then
|
||||
SUB_JSON=$(cat "$CACHE_FILE")
|
||||
${lib.optionalString (routingMark != null) ''
|
||||
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON")
|
||||
''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
fi
|
||||
'';
|
||||
|
||||
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
|
||||
mkOutboundScript =
|
||||
routingMark:
|
||||
let
|
||||
outboundBlocks =
|
||||
if sb.selection == "first" && sb.outbounds != [ ] then
|
||||
# Only the first static outbound, tagged "proxy" so sing-box routes to it.
|
||||
mkOutboundBlock (builtins.head sb.outbounds) routingMark "proxy"
|
||||
else
|
||||
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) sb.outbounds;
|
||||
|
||||
subscriptionBlocks =
|
||||
lib.concatMapStrings (sub: mkSubscriptionBlock sub routingMark) sb.subscriptions;
|
||||
|
||||
wrapperBlock =
|
||||
if sb.selection == "first" then
|
||||
# When there are no static outbounds, subscription outbounds keep their
|
||||
# real tags. Rename the first one to "proxy" so routing rules resolve.
|
||||
lib.optionalString (sb.outbounds == [ ] && sb.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 sb.selection == "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
|
||||
# urltest
|
||||
''
|
||||
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--arg url ${lib.escapeShellArg sb.urlTest.url} \
|
||||
--arg interval ${lib.escapeShellArg sb.urlTest.interval} \
|
||||
--argjson tolerance ${toString sb.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 + wrapperBlock;
|
||||
|
||||
mkStartScript =
|
||||
{
|
||||
name,
|
||||
runtimeDir,
|
||||
configFile,
|
||||
routingMark ? null,
|
||||
}:
|
||||
pkgs.writeShellScript name ''
|
||||
set -euo pipefail
|
||||
RUNTIME_DIR="${runtimeDir}"
|
||||
mkdir -p "$RUNTIME_DIR"
|
||||
OUTBOUNDS_JSON='[]'
|
||||
|
||||
${mkOutboundScript routingMark}
|
||||
|
||||
${jq} --argjson obs "$OUTBOUNDS_JSON" \
|
||||
'.outbounds = $obs + .outbounds' \
|
||||
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||
|
||||
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||
'';
|
||||
|
||||
startSocks = mkStartScript {
|
||||
name = "proxy-suite-start-socks";
|
||||
runtimeDir = "/run/proxy-suite-socks";
|
||||
configFile = tproxyFile;
|
||||
routingMark = sb.proxyMark;
|
||||
};
|
||||
|
||||
startTun = mkStartScript {
|
||||
name = "proxy-suite-start-tun";
|
||||
runtimeDir = "/run/proxy-suite-tun";
|
||||
configFile = tunFile;
|
||||
routingMark = null;
|
||||
};
|
||||
|
||||
clashApi = "http://127.0.0.1:${toString sb.clashApiPort}";
|
||||
selection = sb.selection;
|
||||
|
||||
# Shell code to fetch a single subscription into the cache (used in update service).
|
||||
mkSubscriptionFetchBlock =
|
||||
sub:
|
||||
let
|
||||
urlSource =
|
||||
if sub.urlFile != null then
|
||||
sub.urlFile
|
||||
else
|
||||
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
|
||||
in
|
||||
''
|
||||
SUB_URL=$(cat ${lib.escapeShellArg urlSource})
|
||||
if printf '%s' "$SUB_URL" \
|
||||
| ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} \
|
||||
> "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"; then
|
||||
mv "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp" \
|
||||
"$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
|
||||
echo "Updated subscription: ${sub.tag}"
|
||||
else
|
||||
rm -f "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.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="/var/lib/proxy-suite/subscriptions"
|
||||
mkdir -p "$CACHE_DIR"
|
||||
FAILED=0
|
||||
|
||||
${lib.concatMapStrings mkSubscriptionFetchBlock sb.subscriptions}
|
||||
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
systemctl restart proxy-suite-socks
|
||||
systemctl is-active --quiet proxy-suite-tun && systemctl restart proxy-suite-tun || true
|
||||
fi
|
||||
exit "$FAILED"
|
||||
'';
|
||||
|
||||
# Subscription tags embedded at build time for proxy-ctl.
|
||||
subscriptionTagsList = lib.concatStringsSep " " (map (sub: lib.escapeShellArg sub.tag) sb.subscriptions);
|
||||
hasSubscriptions = sb.subscriptions != [ ];
|
||||
|
||||
proxyCtl = pkgs.writeShellApplication {
|
||||
name = "proxy-ctl";
|
||||
runtimeInputs = with pkgs; [
|
||||
curl
|
||||
jq
|
||||
];
|
||||
text = ''
|
||||
# Embedded at build time from module config
|
||||
CLASH_API="${clashApi}"
|
||||
SELECTION="${selection}"
|
||||
SUB_TAGS=(${subscriptionTagsList})
|
||||
|
||||
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() {
|
||||
echo "Usage: proxy-ctl <command> [args]"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " status show status of all proxy-suite services"
|
||||
echo " tproxy on|off enable/disable TProxy transparent mode"
|
||||
echo " tun on|off enable/disable TUN mode"
|
||||
echo " restart restart proxy-suite-socks and proxy-suite-tun if active"
|
||||
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 " subscription list show subscriptions, cache age, and proxy count"
|
||||
echo " subscription update force-refresh all subscription caches and restart"
|
||||
exit 1
|
||||
}
|
||||
|
||||
_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"
|
||||
}
|
||||
|
||||
cmd="''${1:-status}"
|
||||
shift || true
|
||||
|
||||
case "$cmd" in
|
||||
status)
|
||||
echo "proxy-suite services:"
|
||||
for svc in "''${ALL_SERVICES[@]}"; do
|
||||
_svc_status "$svc"
|
||||
done
|
||||
;;
|
||||
|
||||
tproxy)
|
||||
case "''${1:-on}" in
|
||||
on) systemctl start proxy-suite-tproxy ;;
|
||||
off) systemctl stop proxy-suite-tproxy ;;
|
||||
*) echo "Usage: proxy-ctl tproxy on|off"; exit 1 ;;
|
||||
esac
|
||||
;;
|
||||
|
||||
tun)
|
||||
case "''${1:-on}" in
|
||||
on) systemctl start proxy-suite-tun ;;
|
||||
off) systemctl stop proxy-suite-tun ;;
|
||||
*) echo "Usage: proxy-ctl tun on|off"; exit 1 ;;
|
||||
esac
|
||||
;;
|
||||
|
||||
restart)
|
||||
systemctl restart proxy-suite-socks
|
||||
if systemctl is-active --quiet proxy-suite-tun; then
|
||||
systemctl restart proxy-suite-tun
|
||||
fi
|
||||
;;
|
||||
|
||||
logs)
|
||||
svc="''${1:-proxy-suite-socks}"
|
||||
shift || true
|
||||
exec journalctl -fu "$svc" "$@"
|
||||
;;
|
||||
|
||||
outbounds)
|
||||
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[]? | " " + .'
|
||||
;;
|
||||
|
||||
select)
|
||||
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
|
||||
;;
|
||||
|
||||
subscription)
|
||||
subcmd="''${1:-list}"
|
||||
shift || true
|
||||
case "$subcmd" in
|
||||
list)
|
||||
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||
if [ ''${#SUB_TAGS[@]} -eq 0 ]; then
|
||||
echo "No subscriptions configured."
|
||||
else
|
||||
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
|
||||
fi
|
||||
;;
|
||||
update)
|
||||
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
|
||||
;;
|
||||
|
||||
*)
|
||||
_usage
|
||||
;;
|
||||
esac
|
||||
'';
|
||||
};
|
||||
|
||||
in
|
||||
{
|
||||
environment.systemPackages = [ proxyCtl ];
|
||||
|
||||
# nftables must be on for TProxy to work.
|
||||
networking.nftables.enable = lib.mkIf sb.tproxy.enable (lib.mkDefault true);
|
||||
|
||||
assertions = [
|
||||
{
|
||||
assertion = !sb.enable || (sb.outbounds != [ ] || sb.subscriptions != [ ]);
|
||||
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = builtins.length outboundTags == builtins.length (lib.unique outboundTags);
|
||||
message = "proxy-suite: outbound tags must be unique";
|
||||
}
|
||||
{
|
||||
assertion = builtins.all (tag: !builtins.elem tag builtinTags) outboundTags;
|
||||
message = "proxy-suite: outbound tags must not use reserved names: proxy, direct, block";
|
||||
}
|
||||
{
|
||||
assertion = invalidRoutingTargets == [ ];
|
||||
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
|
||||
}
|
||||
{
|
||||
assertion =
|
||||
!t.enable
|
||||
||
|
||||
builtins.length (
|
||||
builtins.filter (x: x != null) [
|
||||
t.secret
|
||||
t.secretFile
|
||||
]
|
||||
) == 1;
|
||||
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
|
||||
}
|
||||
]
|
||||
++ lib.concatMap (ob: [
|
||||
{
|
||||
assertion =
|
||||
builtins.length (
|
||||
builtins.filter (x: x != null) [
|
||||
ob.urlFile
|
||||
ob.url
|
||||
ob.json
|
||||
]
|
||||
) == 1;
|
||||
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
|
||||
}
|
||||
]) sb.outbounds
|
||||
++ lib.concatMap (sub: [
|
||||
{
|
||||
assertion =
|
||||
builtins.length (
|
||||
builtins.filter (x: x != null) [
|
||||
sub.urlFile
|
||||
sub.url
|
||||
]
|
||||
) == 1;
|
||||
message = "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url";
|
||||
}
|
||||
]) sb.subscriptions;
|
||||
|
||||
systemd.services = {
|
||||
# Always-on: SOCKS5/HTTP mixed inbound, also ready for TProxy interception.
|
||||
proxy-suite-socks = {
|
||||
description = "sing-box proxy client (SOCKS + TProxy-ready)";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${startSocks}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = "proxy-suite-socks";
|
||||
StateDirectory = "proxy-suite";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs sb.tproxy.enable {
|
||||
# Opt-in transparent proxy. Start/stop with:
|
||||
# systemctl start proxy-suite-tproxy
|
||||
# systemctl stop proxy-suite-tproxy
|
||||
proxy-suite-tproxy = {
|
||||
description = "sing-box TProxy – nftables rules and policy routing";
|
||||
after = [
|
||||
"network.target"
|
||||
"proxy-suite-socks.service"
|
||||
];
|
||||
requires = [ "proxy-suite-socks.service" ];
|
||||
conflicts = [ "proxy-suite-tun.service" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
${nft} -f ${nftablesRulesFile}
|
||||
${ip} route add local default dev lo table ${toString sb.routeTable}
|
||||
${ip} rule add fwmark ${toString sb.fwmark} table ${toString sb.routeTable}
|
||||
'';
|
||||
ExecStop = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
${ip} route del local default dev lo table ${toString sb.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString sb.fwmark} table ${toString sb.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs sb.tun.enable {
|
||||
# Opt-in TUN mode (full tunnel, no nftables needed). Start/stop with:
|
||||
# systemctl start proxy-suite-tun
|
||||
# systemctl stop proxy-suite-tun
|
||||
proxy-suite-tun = {
|
||||
description = "sing-box TUN proxy client";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
conflicts = [ "proxy-suite-tproxy.service" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${startTun}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = "proxy-suite-tun";
|
||||
StateDirectory = "proxy-suite";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs hasSubscriptions {
|
||||
proxy-suite-subscription-update = {
|
||||
description = "Refresh proxy-suite subscription caches";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
StateDirectory = "proxy-suite";
|
||||
ExecStart = "${subscriptionUpdateScript}";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
systemd.timers = lib.optionalAttrs hasSubscriptions {
|
||||
proxy-suite-subscription-update = {
|
||||
description = "Periodic proxy-suite subscription refresh";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnBootSec = "5m";
|
||||
OnUnitActiveSec = sb.subscriptionUpdateInterval;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -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,143 @@
|
||||
{
|
||||
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 ? [ ],
|
||||
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 (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,140 @@
|
||||
# Shared service-layer assembly used by runtime module and docs generation.
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
packages,
|
||||
cfg,
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
perAppTunFile,
|
||||
perAppTunChainFile,
|
||||
perAppTproxyRulesFile,
|
||||
perAppZapretRulesFile,
|
||||
ip,
|
||||
nft,
|
||||
}:
|
||||
|
||||
let
|
||||
derived = import ../derived.nix { inherit lib cfg; };
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
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 = "${pkgs.sing-box}/bin/sing-box";
|
||||
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
|
||||
perAppRoutingTun
|
||||
selectionMode
|
||||
collapseNamedOutbounds
|
||||
hasSubscriptions
|
||||
;
|
||||
inherit
|
||||
jq
|
||||
python3
|
||||
singBox
|
||||
parserScriptsPythonPath
|
||||
buildOutboundPy
|
||||
fetchSubscriptionPy
|
||||
;
|
||||
inherit tproxyFile tunFile perAppTunFile;
|
||||
};
|
||||
|
||||
perAppRouting = import ./per-app-routing.nix {
|
||||
inherit
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
singBoxCfg
|
||||
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
|
||||
perAppRoutingCfg
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
selectionMode
|
||||
;
|
||||
zapretEnabled = cfg.zapret.enable;
|
||||
inherit (scripts) subscriptionTagsFile;
|
||||
inherit (perAppRouting)
|
||||
perAppRoutingProfilesFile
|
||||
proxychainsConfigFile
|
||||
proxychainsQuietArg
|
||||
;
|
||||
};
|
||||
in
|
||||
{
|
||||
inherit
|
||||
derived
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
userControlCfg
|
||||
builtinTags
|
||||
outboundTags
|
||||
subscriptionTags
|
||||
invalidRoutingTargets
|
||||
polkit
|
||||
scripts
|
||||
perAppRouting
|
||||
control
|
||||
;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# Builds proxy-ctl from global proxy-suite state and per-app routing metadata.
|
||||
{
|
||||
packages,
|
||||
singBoxCfg,
|
||||
perAppRoutingCfg,
|
||||
perAppRoutingTun,
|
||||
perAppRoutingTproxy,
|
||||
perAppZapretCfg,
|
||||
selectionMode,
|
||||
zapretEnabled,
|
||||
subscriptionTagsFile,
|
||||
perAppRoutingProfilesFile,
|
||||
proxychainsConfigFile,
|
||||
proxychainsQuietArg,
|
||||
}:
|
||||
{
|
||||
proxyCtl = packages.mkProxyCtl {
|
||||
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||
selection = selectionMode;
|
||||
inherit
|
||||
subscriptionTagsFile
|
||||
perAppRoutingProfilesFile
|
||||
proxychainsConfigFile
|
||||
proxychainsQuietArg
|
||||
;
|
||||
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 && zapretEnabled) then "1" else "0";
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
# Assembles all sing-box systemd services from the sub-modules.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
packages,
|
||||
cfg,
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
perAppTunFile,
|
||||
nftablesRulesFile,
|
||||
perAppTproxyRulesFile,
|
||||
perAppZapretRulesFile,
|
||||
perAppTunChainFile,
|
||||
ip,
|
||||
nft,
|
||||
}:
|
||||
|
||||
let
|
||||
context = import ./context.nix {
|
||||
inherit
|
||||
lib
|
||||
pkgs
|
||||
packages
|
||||
cfg
|
||||
tproxyFile
|
||||
tunFile
|
||||
perAppTunFile
|
||||
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
|
||||
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";
|
||||
};
|
||||
|
||||
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
${nft} -f ${nftablesRulesFile}
|
||||
${ip} route add 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" ''
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
systemServiceEntries = [
|
||||
{
|
||||
enable = singBoxCfg.enable;
|
||||
name = serviceNames.socks;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box proxy client (SOCKS + TProxy-ready)";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = scripts.startSocks;
|
||||
runtimeDirectory = serviceNames.socks;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && globalTproxy.enable;
|
||||
name = serviceNames.tproxy;
|
||||
value = mkOneshotService {
|
||||
description = "sing-box 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 = singBoxCfg.enable && globalTun.enable;
|
||||
name = serviceNames.tun;
|
||||
value = mkRestartingService {
|
||||
description = "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" ];
|
||||
execStart = scripts.startTun;
|
||||
runtimeDirectory = serviceNames.tun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTun.enable;
|
||||
name = serviceNames.perAppTun;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box per-app-routing TUN backend";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
execStart = scripts.startPerAppTun;
|
||||
execStartPost = perAppRouting.perAppTunUpScript;
|
||||
execStopPost = perAppRouting.perAppTunDownScript;
|
||||
runtimeDirectory = serviceNames.perAppTun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && 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 = singBoxCfg.enable && 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 = singBoxCfg.enable && 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 = singBoxCfg.enable && 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";
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
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 = singBoxCfg.enable && hasSubscriptions;
|
||||
name = serviceNames.subscriptionUpdate;
|
||||
value = {
|
||||
description = "Periodic proxy-suite subscription refresh";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnBootSec = "5m";
|
||||
OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval;
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
in
|
||||
{
|
||||
environment.systemPackages = [ control.proxyCtl ];
|
||||
|
||||
# nftables must be on for TProxy to work.
|
||||
networking.nftables.enable = lib.mkIf (
|
||||
globalTproxy.enable || perAppRoutingTun.enable || perAppRoutingTproxy.enable || perAppZapretEnabled
|
||||
) (lib.mkDefault true);
|
||||
|
||||
users.groups = lib.mkIf (cfg.enable && userControlEnabled) {
|
||||
"${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,279 @@
|
||||
# App routing backend infrastructure (TUN, TProxy, zapret).
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
cfg,
|
||||
singBoxCfg,
|
||||
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 && cfg.zapret.enable) [
|
||||
{
|
||||
name = "zapret";
|
||||
route = "zapret";
|
||||
}
|
||||
]
|
||||
);
|
||||
effectivePerAppRoutingProfiles =
|
||||
perAppRoutingCfg.profiles
|
||||
++ builtins.filter (
|
||||
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
|
||||
) defaultPerAppRoutingProfiles;
|
||||
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
|
||||
|
||||
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
|
||||
builtins.toJSON effectivePerAppRoutingProfiles
|
||||
);
|
||||
|
||||
proxychainsConfigFile = 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 ${singBoxCfg.listenAddress} ${toString singBoxCfg.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;
|
||||
|
||||
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
|
||||
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
|
||||
${nft} -f ${perAppTunChainFile}
|
||||
${perAppTunWaitForInterface}
|
||||
${ip} route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
|
||||
set -euo pipefail
|
||||
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
|
||||
${ip} route del default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 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
|
||||
${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} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
|
||||
set -euo pipefail
|
||||
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
|
||||
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} 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,260 @@
|
||||
# Generates the sing-box startup scripts and subscription management scripts.
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
singBoxCfg,
|
||||
perAppRoutingTun,
|
||||
selectionMode,
|
||||
collapseNamedOutbounds,
|
||||
hasSubscriptions,
|
||||
jq,
|
||||
python3,
|
||||
singBox,
|
||||
parserScriptsPythonPath,
|
||||
buildOutboundPy,
|
||||
fetchSubscriptionPy,
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
perAppTunFile,
|
||||
}:
|
||||
|
||||
let
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions";
|
||||
|
||||
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} --tag-prefix ${lib.escapeShellArg sub.tag}
|
||||
'';
|
||||
|
||||
# Build the shell code block for a single outbound entry.
|
||||
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
|
||||
# routingMark is null or an int; added to outbound JSON if set.
|
||||
mkOutboundBlock =
|
||||
ob: routingMark: tag:
|
||||
let
|
||||
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
|
||||
in
|
||||
if ob.json != null then
|
||||
let
|
||||
outboundJson = builtins.toJSON (
|
||||
ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
|
||||
);
|
||||
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (static 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
|
||||
# Literal URL – write to nix store so the script can cat it.
|
||||
# Less secret than urlFile, but convenient for non-sensitive configs.
|
||||
pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag}
|
||||
URL=$(cat "${urlSource}")
|
||||
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --tag ${lib.escapeShellArg tag}${markArg})
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
|
||||
# Build the shell code block for a single subscription entry.
|
||||
# Fetches subscription into the cache on first run; subsequent starts use the cache.
|
||||
mkSubscriptionBlock =
|
||||
sub: routingMark:
|
||||
let
|
||||
cacheFile = mkSubscriptionCacheFile sub;
|
||||
in
|
||||
''
|
||||
# subscription: ${sub.tag}
|
||||
CACHE_DIR="${subscriptionCacheDir}"
|
||||
CACHE_FILE="${cacheFile}"
|
||||
if [ ! -f "$CACHE_FILE" ]; then
|
||||
mkdir -p "$CACHE_DIR"
|
||||
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
|
||||
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
|
||||
else
|
||||
rm -f "$CACHE_FILE.tmp"
|
||||
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
|
||||
fi
|
||||
fi
|
||||
if [ -f "$CACHE_FILE" ]; then
|
||||
SUB_JSON=$(cat "$CACHE_FILE")
|
||||
${
|
||||
lib.optionalString (routingMark != null) ''
|
||||
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON")
|
||||
''
|
||||
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
fi
|
||||
'';
|
||||
|
||||
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
|
||||
mkOutboundScript =
|
||||
routingMark:
|
||||
let
|
||||
outboundBlocks =
|
||||
if collapseNamedOutbounds && singBoxCfg.outbounds != [ ] then
|
||||
# Only the first static outbound, tagged "proxy" so sing-box routes to it.
|
||||
mkOutboundBlock (builtins.head singBoxCfg.outbounds) routingMark "proxy"
|
||||
else
|
||||
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds;
|
||||
|
||||
subscriptionBlocks = lib.concatMapStrings (
|
||||
sub: mkSubscriptionBlock sub routingMark
|
||||
) singBoxCfg.subscriptions;
|
||||
|
||||
wrapperBlock =
|
||||
if collapseNamedOutbounds then
|
||||
# When there are no static outbounds, subscription outbounds keep their
|
||||
# real tags. Rename the first one to "proxy" so routing rules resolve.
|
||||
lib.optionalString (singBoxCfg.outbounds == [ ] && singBoxCfg.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
|
||||
# urltest
|
||||
''
|
||||
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--arg url ${lib.escapeShellArg singBoxCfg.urlTest.url} \
|
||||
--arg interval ${lib.escapeShellArg singBoxCfg.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 + wrapperBlock;
|
||||
|
||||
mkStartScript =
|
||||
{
|
||||
name,
|
||||
runtimeDir,
|
||||
configFile,
|
||||
routingMark ? null,
|
||||
}:
|
||||
pkgs.writeShellScript name ''
|
||||
set -euo pipefail
|
||||
RUNTIME_DIR="${runtimeDir}"
|
||||
mkdir -p "$RUNTIME_DIR"
|
||||
OUTBOUNDS_JSON='[]'
|
||||
|
||||
${mkOutboundScript routingMark}
|
||||
|
||||
${jq} --argjson obs "$OUTBOUNDS_JSON" \
|
||||
'.outbounds = $obs + .outbounds' \
|
||||
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||
|
||||
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||
'';
|
||||
|
||||
startSocks = mkStartScript {
|
||||
name = "proxy-suite-start-socks";
|
||||
runtimeDir = "/run/proxy-suite-socks";
|
||||
configFile = tproxyFile;
|
||||
routingMark = globalTproxy.proxyMark;
|
||||
};
|
||||
|
||||
startTun = mkStartScript {
|
||||
name = "proxy-suite-start-tun";
|
||||
runtimeDir = "/run/proxy-suite-tun";
|
||||
configFile = tunFile;
|
||||
routingMark = null;
|
||||
};
|
||||
|
||||
startPerAppTun = mkStartScript {
|
||||
name = "proxy-suite-start-per-app-tun";
|
||||
runtimeDir = "/run/proxy-suite-per-app-tun";
|
||||
configFile = perAppTunFile;
|
||||
# Only needed when TProxy mode is enabled; otherwise avoid tagging app TUN
|
||||
# proxy outbounds with a host-global mark.
|
||||
routingMark = if globalTproxy.enable then globalTproxy.proxyMark else null;
|
||||
};
|
||||
|
||||
# Shell code to fetch a single subscription into the cache (used in update service).
|
||||
mkSubscriptionFetchBlock =
|
||||
sub:
|
||||
let
|
||||
cacheFile = mkSubscriptionCacheFile sub;
|
||||
in
|
||||
''
|
||||
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
|
||||
mv "${cacheFile}.tmp" "${cacheFile}"
|
||||
echo "Updated subscription: ${sub.tag}"
|
||||
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
|
||||
SOCKS_WAS_ACTIVE=0
|
||||
TUN_WAS_ACTIVE=0
|
||||
PER_APP_TUN_WAS_ACTIVE=0
|
||||
|
||||
systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true
|
||||
systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true
|
||||
systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true
|
||||
|
||||
${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions}
|
||||
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then
|
||||
systemctl restart proxy-suite-socks
|
||||
fi
|
||||
if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then
|
||||
systemctl restart proxy-suite-tun
|
||||
fi
|
||||
if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then
|
||||
systemctl restart proxy-suite-per-app-tun
|
||||
fi
|
||||
fi
|
||||
exit "$FAILED"
|
||||
'';
|
||||
|
||||
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
|
||||
builtins.toJSON (map (sub: sub.tag) singBoxCfg.subscriptions)
|
||||
);
|
||||
in
|
||||
{
|
||||
inherit startSocks startTun startPerAppTun;
|
||||
inherit subscriptionUpdateScript hasSubscriptions subscriptionTagsFile;
|
||||
}
|
||||
@@ -2,12 +2,13 @@
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
packages,
|
||||
cfg,
|
||||
}:
|
||||
|
||||
let
|
||||
t = cfg.tgWsProxy;
|
||||
tgPkg = import ../../pkgs/tg-ws-proxy.nix { inherit pkgs; };
|
||||
tgPkg = packages.tg-ws-proxy;
|
||||
|
||||
dcArgs = lib.concatMapStrings (id: " --dc-ip=${id}:${t.dcIps.${id}}") (builtins.attrNames t.dcIps);
|
||||
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
packages,
|
||||
cfg,
|
||||
}:
|
||||
|
||||
let
|
||||
tray = cfg.tray;
|
||||
|
||||
proxyTray = import ../../pkgs/proxy-suite-tray.nix {
|
||||
inherit pkgs;
|
||||
proxyTray = packages.mkProxySuiteTray {
|
||||
pollInterval = tray.pollInterval;
|
||||
};
|
||||
|
||||
|
||||
@@ -4,10 +4,16 @@
|
||||
pkgs,
|
||||
cfg,
|
||||
zapret,
|
||||
perAppZapretRulesFile,
|
||||
nft,
|
||||
}:
|
||||
|
||||
let
|
||||
z = cfg.zapret;
|
||||
builders = import ./service/builders.nix { inherit lib pkgs; };
|
||||
inherit (builders) mkOneshotService;
|
||||
|
||||
zapretCfg = cfg.zapret;
|
||||
perAppZapretCfg = zapretCfg.perApp;
|
||||
|
||||
iptables = "${pkgs.iptables}/bin/iptables";
|
||||
|
||||
@@ -15,6 +21,7 @@ let
|
||||
inherit (pkgs)
|
||||
iptables
|
||||
ipset
|
||||
nftables
|
||||
coreutils
|
||||
gawk
|
||||
curl
|
||||
@@ -29,66 +36,69 @@ let
|
||||
;
|
||||
};
|
||||
|
||||
hostlistRuleNames = map (rule: rule.name) z.hostlistRules;
|
||||
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
|
||||
|
||||
upstreamZapretPackage =
|
||||
baseZapretPackage =
|
||||
let
|
||||
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
|
||||
in
|
||||
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 =
|
||||
if z.listGeneral != [ ] then
|
||||
pkgs.writeText "proxy-suite-zapret-list-general-user.txt" (
|
||||
lib.concatStringsSep "\n" z.listGeneral + "\n"
|
||||
)
|
||||
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;
|
||||
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
|
||||
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
|
||||
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
|
||||
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
|
||||
|
||||
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
|
||||
builtins.toJSON {
|
||||
includeExtraUpstreamLists = z.includeExtraUpstreamLists;
|
||||
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
|
||||
entries = map (rule: {
|
||||
inherit (rule)
|
||||
name
|
||||
preset
|
||||
nfqwsArgs
|
||||
;
|
||||
}) z.hostlistRules;
|
||||
}) zapretCfg.hostlistRules;
|
||||
}
|
||||
);
|
||||
|
||||
selectedConfigName = lib.strings.sanitizeDerivationName z.configName;
|
||||
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
|
||||
patchConfigScriptSrc = builtins.path {
|
||||
path = ../../scripts/patch-zapret-config.py;
|
||||
name = "patch-zapret-config.py";
|
||||
};
|
||||
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
|
||||
|
||||
customZapretPackage =
|
||||
pkgs.runCommand "proxy-suite-zapret-${selectedConfigName}"
|
||||
mkGlobalBypassScript =
|
||||
filterMark:
|
||||
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
|
||||
zapret_custom_firewall_nft() {
|
||||
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 per-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 per-app-zapret bypass"
|
||||
}
|
||||
'';
|
||||
|
||||
mkDerivedZapretPackage =
|
||||
{
|
||||
packageName,
|
||||
pidDir,
|
||||
configName ? zapretCfg.configName,
|
||||
gameFilter ? zapretCfg.gameFilter,
|
||||
forceDisableFilterMark ? false,
|
||||
filterMark ? null,
|
||||
qnum ? null,
|
||||
modeFilter ? null,
|
||||
desyncMark ? null,
|
||||
desyncMarkPostnat ? null,
|
||||
nftTable ? null,
|
||||
customScript ? null,
|
||||
}:
|
||||
pkgs.runCommand packageName
|
||||
{
|
||||
nativeBuildInputs = with pkgs; [
|
||||
coreutils
|
||||
@@ -100,25 +110,32 @@ let
|
||||
set -euo pipefail
|
||||
|
||||
mkdir -p "$out"
|
||||
cp -a ${upstreamZapretPackage}/. "$out/"
|
||||
cp -a ${baseZapretPackage}/. "$out/"
|
||||
chmod -R u+w "$out/opt/zapret" "$out/bin"
|
||||
|
||||
find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \
|
||||
-e 's|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
|
||||
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
|
||||
{} \;
|
||||
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
|
||||
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
|
||||
{} \;
|
||||
|
||||
if [ -f "$out/opt/zapret/configs/${z.configName}" ]; then
|
||||
cp "$out/opt/zapret/configs/${z.configName}" "$out/opt/zapret/config"
|
||||
if [ -f "$out/opt/zapret/configs/${configName}" ]; then
|
||||
cp "$out/opt/zapret/configs/${configName}" "$out/opt/zapret/config"
|
||||
else
|
||||
echo "proxy-suite: zapret config '${z.configName}' not found in upstream package" >&2
|
||||
echo "proxy-suite: zapret config '${configName}' not found in curated package" >&2
|
||||
ls -la "$out/opt/zapret/configs" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
${pkgs.gnused}/bin/sed -i \
|
||||
-e 's|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
|
||||
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
|
||||
"$out/opt/zapret/config"
|
||||
|
||||
${pkgs.gnused}/bin/sed -i \
|
||||
-e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \
|
||||
"$out/opt/zapret/init.d/sysv/functions"
|
||||
|
||||
append_list_file() {
|
||||
local target="$1"
|
||||
local extra_file="$2"
|
||||
@@ -129,25 +146,46 @@ let
|
||||
mv "$tmp" "$out/opt/zapret/hostlists/$target"
|
||||
}
|
||||
|
||||
${lib.optionalString (listGeneralFile != null) ''
|
||||
append_list_file list-general-user.txt ${listGeneralFile}
|
||||
''}
|
||||
set_config_var() {
|
||||
local key="$1"
|
||||
local value="$2"
|
||||
if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then
|
||||
${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config"
|
||||
else
|
||||
printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config"
|
||||
fi
|
||||
}
|
||||
|
||||
${lib.optionalString (listExcludeFile != null) ''
|
||||
append_list_file list-exclude-user.txt ${listExcludeFile}
|
||||
''}
|
||||
|
||||
${lib.optionalString (ipsetAllFile != null) ''
|
||||
append_list_file ipset-all.txt ${ipsetAllFile}
|
||||
''}
|
||||
|
||||
${lib.optionalString (ipsetExcludeFile != null) ''
|
||||
append_list_file ipset-exclude-user.txt ${ipsetExcludeFile}
|
||||
''}
|
||||
${lib.concatMapStrings
|
||||
(
|
||||
{ name, file }:
|
||||
lib.optionalString (file != null) ''
|
||||
append_list_file ${name} ${file}
|
||||
''
|
||||
)
|
||||
[
|
||||
{
|
||||
name = "list-general-user.txt";
|
||||
file = listGeneralFile;
|
||||
}
|
||||
{
|
||||
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"
|
||||
${lib.optionalString (z.gameFilter != "null") ''
|
||||
echo "${z.gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
|
||||
${lib.optionalString (gameFilter != "null") ''
|
||||
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
|
||||
''}
|
||||
|
||||
${lib.concatMapStrings (
|
||||
@@ -160,20 +198,113 @@ let
|
||||
''
|
||||
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
|
||||
''
|
||||
) z.hostlistRules}
|
||||
) zapretCfg.hostlistRules}
|
||||
|
||||
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
|
||||
|
||||
${lib.optionalString forceDisableFilterMark ''
|
||||
set_config_var FILTER_MARK ""
|
||||
''}
|
||||
${lib.concatMapStrings
|
||||
(
|
||||
{ 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) ''
|
||||
set_config_var QNUM ${toString qnum}
|
||||
''}
|
||||
${lib.optionalString (modeFilter != null) ''
|
||||
set_config_var MODE_FILTER ${modeFilter}
|
||||
''}
|
||||
${lib.optionalString (nftTable != null) ''
|
||||
set_config_var ZAPRET_NFT_TABLE ${nftTable}
|
||||
''}
|
||||
|
||||
${lib.optionalString (customScript != null) ''
|
||||
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
|
||||
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
|
||||
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
|
||||
''}
|
||||
'';
|
||||
|
||||
globalZapretPackage = mkDerivedZapretPackage {
|
||||
packageName = "proxy-suite-zapret-${selectedConfigName}";
|
||||
pidDir = "/run/proxy-suite-zapret";
|
||||
gameFilter = zapretCfg.gameFilter;
|
||||
forceDisableFilterMark = true;
|
||||
customScript =
|
||||
if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null;
|
||||
};
|
||||
|
||||
perAppZapretPackage = mkDerivedZapretPackage {
|
||||
packageName = "proxy-suite-per-app-zapret-${selectedConfigName}";
|
||||
pidDir = "/run/proxy-suite-per-app-zapret";
|
||||
gameFilter = "all";
|
||||
filterMark = perAppZapretCfg.filterMark;
|
||||
qnum = perAppZapretCfg.qnum;
|
||||
modeFilter = "none";
|
||||
desyncMark = 134217728;
|
||||
desyncMarkPostnat = 67108864;
|
||||
nftTable = "proxy_suite_per_app_zapret";
|
||||
};
|
||||
|
||||
zapretCommonPreStart = package: ''
|
||||
${package}/opt/zapret/init.d/sysv/zapret stop || true
|
||||
|
||||
${lib.getExe' pkgs.kmod "modprobe"} xt_NFQUEUE 2>/dev/null || true
|
||||
${lib.getExe' pkgs.kmod "modprobe"} xt_connbytes 2>/dev/null || true
|
||||
${lib.getExe' pkgs.kmod "modprobe"} xt_multiport 2>/dev/null || true
|
||||
|
||||
if ! ${pkgs.ipset}/bin/ipset list nozapret >/dev/null 2>&1; then
|
||||
${pkgs.ipset}/bin/ipset create nozapret hash:net
|
||||
fi
|
||||
'';
|
||||
|
||||
mkZapretEnv = package: [
|
||||
"ZAPRET_BASE=${package}/opt/zapret"
|
||||
"PATH=${lib.makeBinPath runtimeDeps}"
|
||||
];
|
||||
globalZapretEnv = mkZapretEnv globalZapretPackage;
|
||||
perAppZapretEnv = mkZapretEnv perAppZapretPackage;
|
||||
|
||||
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-up" ''
|
||||
set -euo pipefail
|
||||
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
|
||||
${nft} -f ${perAppZapretRulesFile}
|
||||
'';
|
||||
|
||||
perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-down" ''
|
||||
set -euo pipefail
|
||||
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
|
||||
'';
|
||||
|
||||
exemptStart = lib.concatMapStrings (cidr: ''
|
||||
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
||||
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
|
||||
'') z.cidrExemption.cidrs;
|
||||
'') zapretCfg.cidrExemption.cidrs;
|
||||
|
||||
exemptStop = lib.concatMapStrings (cidr: ''
|
||||
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true
|
||||
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true
|
||||
'') z.cidrExemption.cidrs;
|
||||
'') zapretCfg.cidrExemption.cidrs;
|
||||
in
|
||||
{
|
||||
assertions = [
|
||||
@@ -182,61 +313,59 @@ in
|
||||
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";
|
||||
}
|
||||
{
|
||||
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";
|
||||
}
|
||||
];
|
||||
|
||||
services.zapret-discord-youtube = {
|
||||
enable = true;
|
||||
configName = z.configName;
|
||||
gameFilter = z.gameFilter;
|
||||
listGeneral = z.listGeneral;
|
||||
listExclude = z.listExclude;
|
||||
ipsetAll = z.ipsetAll;
|
||||
ipsetExclude = z.ipsetExclude;
|
||||
};
|
||||
environment.systemPackages = lib.mkBefore (
|
||||
[ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
|
||||
);
|
||||
|
||||
environment.systemPackages = lib.mkBefore [ customZapretPackage ];
|
||||
|
||||
systemd.services.zapret-discord-youtube = {
|
||||
preStart = lib.mkForce ''
|
||||
${customZapretPackage}/opt/zapret/init.d/sysv/zapret stop || true
|
||||
|
||||
${lib.getExe' pkgs.kmod "modprobe"} xt_NFQUEUE 2>/dev/null || true
|
||||
${lib.getExe' pkgs.kmod "modprobe"} xt_connbytes 2>/dev/null || true
|
||||
${lib.getExe' pkgs.kmod "modprobe"} xt_multiport 2>/dev/null || true
|
||||
|
||||
if ! ${pkgs.ipset}/bin/ipset list nozapret >/dev/null 2>&1; then
|
||||
${pkgs.ipset}/bin/ipset create nozapret hash:net
|
||||
fi
|
||||
'';
|
||||
|
||||
serviceConfig = {
|
||||
ExecStart = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
ExecStop = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
ExecReload = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
|
||||
Environment = lib.mkForce [
|
||||
"ZAPRET_BASE=${customZapretPackage}/opt/zapret"
|
||||
"PATH=${lib.makeBinPath runtimeDeps}"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf z.cidrExemption.enable {
|
||||
description = "Exempt CIDRs from zapret NFQUEUE";
|
||||
after = [ "zapret-discord-youtube.service" ];
|
||||
wants = [ "zapret-discord-youtube.service" ];
|
||||
systemd.services.zapret-discord-youtube = mkOneshotService {
|
||||
description = "zapret DPI bypass";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
|
||||
ExecStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
|
||||
preStart = zapretCommonPreStart globalZapretPackage;
|
||||
runtimeDirectory = "proxy-suite-zapret";
|
||||
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
extraServiceConfig = {
|
||||
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
|
||||
Environment = globalZapretEnv;
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
|
||||
description = "proxy-suite per-app-routing zapret backend";
|
||||
after = [ "network.target" ];
|
||||
conflicts = [
|
||||
"proxy-suite-tproxy.service"
|
||||
"proxy-suite-tun.service"
|
||||
];
|
||||
preStart = zapretCommonPreStart perAppZapretPackage;
|
||||
runtimeDirectory = "proxy-suite-per-app-zapret";
|
||||
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
execStartPre = "${perAppZapretMarkUpScript}";
|
||||
execStopPost = "${perAppZapretMarkDownScript}";
|
||||
extraServiceConfig.Environment = perAppZapretEnv;
|
||||
});
|
||||
|
||||
systemd.services.proxy-suite-zapret-vm-exempt =
|
||||
lib.mkIf zapretCfg.cidrExemption.enable
|
||||
(mkOneshotService {
|
||||
description = "Exempt CIDRs from zapret NFQUEUE";
|
||||
after = [ "zapret-discord-youtube.service" ];
|
||||
wants = [ "zapret-discord-youtube.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
|
||||
execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
|
||||
});
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
{
|
||||
nixpkgs,
|
||||
pkgsFor,
|
||||
proxySuiteModule,
|
||||
}:
|
||||
|
||||
system:
|
||||
|
||||
let
|
||||
pkgs = pkgsFor system;
|
||||
lib = pkgs.lib;
|
||||
eval = import "${nixpkgs}/nixos/lib/eval-config.nix" {
|
||||
inherit system;
|
||||
modules = [
|
||||
proxySuiteModule
|
||||
{
|
||||
system.stateVersion = lib.trivial.release;
|
||||
}
|
||||
];
|
||||
};
|
||||
filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module");
|
||||
mkGeneratedExampleValue =
|
||||
option:
|
||||
if (option ? _type) && option._type == "option" then
|
||||
if option ? example then
|
||||
option.example
|
||||
else if (option ? type) && ((option.type.name or null) == "submodule") then
|
||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions (option.type.getSubOptions [ ]))
|
||||
else if option ? default then
|
||||
option.default
|
||||
else
|
||||
throw "Cannot generate example value for option ${lib.showOption option.loc}"
|
||||
else
|
||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option);
|
||||
defaultConfigText = lib.generators.toPretty { } eval.config.services.proxy-suite;
|
||||
exampleConfigText = lib.generators.toPretty { } (
|
||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite)
|
||||
);
|
||||
repoRoot = toString ../.;
|
||||
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
|
||||
transformDeclaration =
|
||||
decl:
|
||||
let
|
||||
declStr = toString decl;
|
||||
subpath = lib.removePrefix "/" (lib.removePrefix repoRoot declStr);
|
||||
in
|
||||
if lib.hasPrefix repoRoot declStr then
|
||||
{
|
||||
url = "${repoUrl}/${subpath}";
|
||||
name = subpath;
|
||||
}
|
||||
else
|
||||
decl;
|
||||
optionDocs = pkgs.nixosOptionsDoc {
|
||||
options = {
|
||||
services = {
|
||||
"proxy-suite" = eval.options.services.proxy-suite;
|
||||
};
|
||||
};
|
||||
documentType = "none";
|
||||
variablelistId = "proxy-suite-options";
|
||||
optionIdPrefix = "proxy-suite-opt-";
|
||||
transformOptions = opt: opt // { declarations = map transformDeclaration opt.declarations; };
|
||||
};
|
||||
in
|
||||
pkgs.runCommand "proxy-suite-options.md" { } ''
|
||||
preamble="$TMPDIR/preamble.md"
|
||||
sections="$TMPDIR/sections.md"
|
||||
sections_with_anchors="$TMPDIR/sections-with-anchors.md"
|
||||
section_index="$TMPDIR/sections-index.tsv"
|
||||
toc="$TMPDIR/toc.md"
|
||||
|
||||
cat >"$preamble" <<'EOF'
|
||||
# proxy-suite options
|
||||
|
||||
This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options/default.nix`](/modules/proxy-suite/options/default.nix).
|
||||
Update module option docs there instead of editing this file by hand.
|
||||
|
||||
## Table of contents
|
||||
|
||||
EOF
|
||||
|
||||
cat >"$sections" <<'EOF'
|
||||
## Complete default config
|
||||
|
||||
```nix
|
||||
services.proxy-suite = ${defaultConfigText};
|
||||
```
|
||||
|
||||
## Complete example config
|
||||
|
||||
This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options.
|
||||
|
||||
```nix
|
||||
services.proxy-suite = ${exampleConfigText};
|
||||
```
|
||||
|
||||
EOF
|
||||
|
||||
cat ${optionDocs.optionsCommonMark} >>"$sections"
|
||||
|
||||
: >"$section_index"
|
||||
: >"$sections_with_anchors"
|
||||
awk -v section_index="$section_index" -v out="$sections_with_anchors" '
|
||||
function slugify(text, slug) {
|
||||
slug = text
|
||||
gsub(/\\/, "", slug)
|
||||
slug = tolower(slug)
|
||||
gsub(/[^a-z0-9]+/, "-", slug)
|
||||
sub(/^-+/, "", slug)
|
||||
sub(/-+$/, "", slug)
|
||||
return slug
|
||||
}
|
||||
|
||||
/^## / {
|
||||
title = substr($0, 4)
|
||||
base = slugify(title)
|
||||
count = seen[base]
|
||||
seen[base]++
|
||||
slug = count == 0 ? base : base "-" count
|
||||
|
||||
print title "\t" slug >> section_index
|
||||
print "<a id=\"" slug "\"></a>" >> out
|
||||
}
|
||||
|
||||
{
|
||||
print >> out
|
||||
}
|
||||
' "$sections"
|
||||
|
||||
: >"$toc"
|
||||
awk -F '\t' -v toc="$toc" '
|
||||
function addChild(parent, child, key) {
|
||||
key = parent SUBSEP child
|
||||
if (!(key in seenChild)) {
|
||||
seenChild[key] = 1
|
||||
childCount[parent]++
|
||||
childOrder[parent, childCount[parent]] = child
|
||||
}
|
||||
}
|
||||
|
||||
function indent(depth, i, prefix) {
|
||||
prefix = ""
|
||||
for (i = 0; i < depth; i++) {
|
||||
prefix = prefix " "
|
||||
}
|
||||
return prefix
|
||||
}
|
||||
|
||||
function displayLabel(label) {
|
||||
if (label == "*") {
|
||||
return "item"
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
function printNode(path, label, depth, i, child, childPath, text) {
|
||||
text = displayLabel(label)
|
||||
if (path in slugByPath) {
|
||||
text = "[" text "](#" slugByPath[path] ")"
|
||||
}
|
||||
|
||||
print indent(depth) "- " text >> toc
|
||||
|
||||
for (i = 1; i <= childCount[path]; i++) {
|
||||
child = childOrder[path, i]
|
||||
childPath = path "." child
|
||||
printNode(childPath, child, depth + 1)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
title = $1
|
||||
slug = $2
|
||||
normalized = title
|
||||
gsub(/\\/, "", normalized)
|
||||
|
||||
if (normalized ~ /^Complete /) {
|
||||
sampleCount++
|
||||
sampleTitle[sampleCount] = title
|
||||
sampleSlug[sampleCount] = slug
|
||||
next
|
||||
}
|
||||
|
||||
if (index(normalized, "services.proxy-suite") == 1) {
|
||||
optionRootSeen = 1
|
||||
slugByPath[normalized] = slug
|
||||
|
||||
count = split(normalized, parts, /\./)
|
||||
if (count < 3) {
|
||||
next
|
||||
}
|
||||
|
||||
parent = "services.proxy-suite"
|
||||
for (i = 3; i <= count; i++) {
|
||||
child = parts[i]
|
||||
addChild(parent, child)
|
||||
parent = parent "." child
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
otherCount++
|
||||
otherTitle[otherCount] = title
|
||||
otherSlug[otherCount] = slug
|
||||
}
|
||||
|
||||
END {
|
||||
if (sampleCount > 0) {
|
||||
print "- Config samples" >> toc
|
||||
for (i = 1; i <= sampleCount; i++) {
|
||||
print " - [" sampleTitle[i] "](#" sampleSlug[i] ")" >> toc
|
||||
}
|
||||
}
|
||||
|
||||
if (optionRootSeen) {
|
||||
print "- services.proxy-suite" >> toc
|
||||
for (i = 1; i <= childCount["services.proxy-suite"]; i++) {
|
||||
child = childOrder["services.proxy-suite", i]
|
||||
printNode("services.proxy-suite." child, child, 1)
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 1; i <= otherCount; i++) {
|
||||
print "- [" otherTitle[i] "](#" otherSlug[i] ")" >> toc
|
||||
}
|
||||
}
|
||||
' "$section_index"
|
||||
|
||||
cat "$preamble" >"$out"
|
||||
cat "$toc" >>"$out"
|
||||
printf '\n' >>"$out"
|
||||
cat "$sections_with_anchors" >>"$out"
|
||||
''
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
|
||||
singBox.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;
|
||||
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
|
||||
''
|
||||
@@ -1,4 +1,18 @@
|
||||
{ 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,338 @@
|
||||
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 sing-box proxy stack"
|
||||
echo " tproxy on|off enable/disable TProxy transparent mode"
|
||||
echo " tun on|off enable/disable TUN mode"
|
||||
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 sing-box 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"
|
||||
}
|
||||
|
||||
_status_tray() {
|
||||
printf 'socks_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||
printf 'socks_active=%s\n' "$(_bool _svc_active proxy-suite-socks)"
|
||||
printf 'tproxy_available=%s\n' "$(_bool _svc_exists proxy-suite-tproxy)"
|
||||
printf 'tproxy_active=%s\n' "$(_bool _svc_active proxy-suite-tproxy)"
|
||||
printf 'tun_available=%s\n' "$(_bool _svc_exists proxy-suite-tun)"
|
||||
printf 'tun_active=%s\n' "$(_bool _svc_active proxy-suite-tun)"
|
||||
printf 'zapret_available=%s\n' "$(_bool _svc_exists zapret-discord-youtube)"
|
||||
printf 'zapret_active=%s\n' "$(_bool _svc_active zapret-discord-youtube)"
|
||||
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
|
||||
}
|
||||
|
||||
_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
|
||||
}
|
||||
|
||||
# _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"
|
||||
|
||||
systemctl --user start "$anchor_unit"
|
||||
systemctl start "$backend_svc"
|
||||
systemctl start "$user_svc"
|
||||
|
||||
local status=0
|
||||
systemd-run --user --scope --quiet --collect --same-dir \
|
||||
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
cmd_proxy() {
|
||||
case "${1:-on}" in
|
||||
on)
|
||||
systemctl start proxy-suite-socks
|
||||
;;
|
||||
off)
|
||||
systemctl stop proxy-suite-tproxy || true
|
||||
systemctl stop proxy-suite-tun || true
|
||||
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-}}"
|
||||
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"; }
|
||||
|
||||
RESTART_SERVICES=(
|
||||
proxy-suite-tproxy
|
||||
proxy-suite-tun
|
||||
zapret-discord-youtube
|
||||
)
|
||||
|
||||
cmd_restart() {
|
||||
systemctl restart proxy-suite-socks
|
||||
for svc in "${RESTART_SERVICES[@]}"; do
|
||||
if systemctl is-active --quiet "$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
|
||||
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
|
||||
exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@"
|
||||
;;
|
||||
tun)
|
||||
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \
|
||||
"Profile '$profile' uses route=tun, but singBox.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 singBox.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 or zapret.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="/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)
|
||||
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,54 @@
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
}:
|
||||
|
||||
{
|
||||
clashApi,
|
||||
selection,
|
||||
subscriptionTagsFile,
|
||||
perAppRoutingEnabled,
|
||||
perAppRoutingProxychainsEnabled,
|
||||
perAppRoutingTunEnabled,
|
||||
perAppRoutingTproxyEnabled,
|
||||
perAppRoutingZapretEnabled,
|
||||
perAppRoutingProfilesFile,
|
||||
proxychainsConfigFile,
|
||||
proxychainsQuietArg,
|
||||
}:
|
||||
|
||||
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 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)}
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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:-}"
|
||||
;;
|
||||
|
||||
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
|
||||
@@ -27,6 +27,24 @@ pkgs.stdenv.mkDerivation {
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp proxy-suite-tray $out/bin/
|
||||
|
||||
# Install custom icons in hicolor theme
|
||||
if [ -d icons ]; then
|
||||
mkdir -p $out/share/icons/hicolor/scalable/apps
|
||||
mkdir -p $out/share/icons/hicolor/symbolic/apps
|
||||
cp icons/proxy-suite-disabled.svg \
|
||||
icons/proxy-suite-zapret.svg \
|
||||
icons/proxy-suite-proxy.svg \
|
||||
icons/proxy-suite-active.svg \
|
||||
icons/proxy-suite-tunnel.svg \
|
||||
$out/share/icons/hicolor/scalable/apps/
|
||||
cp icons/proxy-suite-disabled-symbolic.svg \
|
||||
icons/proxy-suite-zapret-symbolic.svg \
|
||||
icons/proxy-suite-proxy-symbolic.svg \
|
||||
icons/proxy-suite-active-symbolic.svg \
|
||||
icons/proxy-suite-tunnel-symbolic.svg \
|
||||
$out/share/icons/hicolor/symbolic/apps/
|
||||
fi
|
||||
'';
|
||||
|
||||
meta = {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<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="currentColor"/>
|
||||
<path d="M 9 13 L 11.5 15.5 L 15.5 9.5"
|
||||
stroke="white" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 354 B |
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Green shield: proxy + zapret both enabled -->
|
||||
<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="#4CAF50" stroke="#2E7D32" stroke-width="0.8"/>
|
||||
<path d="M 9 13 L 11.5 15.5 L 15.5 9.5"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 440 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<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="currentColor"/>
|
||||
<line x1="9" y1="9.5" x2="15" y2="15.5" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
|
||||
<line x1="15" y1="9.5" x2="9" y2="15.5" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 403 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Red shield: everything disabled -->
|
||||
<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="#F44336" stroke="#B71C1C" stroke-width="0.8"/>
|
||||
<line x1="9" y1="9.5" x2="15" y2="15.5"
|
||||
stroke="#FFFFFF" stroke-width="1.4" stroke-linecap="round"/>
|
||||
<line x1="15" y1="9.5" x2="9" y2="15.5"
|
||||
stroke="#FFFFFF" stroke-width="1.4" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 497 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<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="currentColor"/>
|
||||
<circle cx="12" cy="12.5" r="2.5" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 252 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Orange shield: only proxy (SOCKS) enabled -->
|
||||
<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="#FF9800" stroke="#E65100" stroke-width="0.8"/>
|
||||
<!-- Dot in center -->
|
||||
<circle cx="12" cy="12.5" r="2.5" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 363 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<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="currentColor"/>
|
||||
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
|
||||
stroke="white" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 371 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Gold 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"
|
||||
fill="#FFC107" stroke="#F57F17" stroke-width="0.8"/>
|
||||
<!-- 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"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 497 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<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="currentColor"/>
|
||||
<path d="M 9 9 L 15 9 L 9 15 L 15 15"
|
||||
stroke="white" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 352 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Blue shield: only zapret enabled -->
|
||||
<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="#2196F3" stroke="#0D47A1" stroke-width="0.8"/>
|
||||
<!-- Z letter for Zapret -->
|
||||
<path d="M 9 9 L 15 9 L 9 15 L 15 15"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 460 B |
@@ -8,11 +8,8 @@
|
||||
#ifndef POLL_INTERVAL
|
||||
#define POLL_INTERVAL 5
|
||||
#endif
|
||||
#ifndef SYSTEMCTL_BIN
|
||||
#define SYSTEMCTL_BIN "/run/current-system/sw/bin/systemctl"
|
||||
#endif
|
||||
#ifndef PKEXEC_BIN
|
||||
#define PKEXEC_BIN "/run/current-system/sw/bin/pkexec"
|
||||
#ifndef PROXY_CTL_BIN
|
||||
#define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl"
|
||||
#endif
|
||||
|
||||
static AppIndicator *indicator;
|
||||
@@ -21,23 +18,47 @@ static GtkWidget *status_item;
|
||||
static GtkWidget *proxy_item;
|
||||
static GtkWidget *tproxy_item;
|
||||
static GtkWidget *tun_item;
|
||||
static GtkWidget *zapret_item;
|
||||
static GtkWidget *open_controls_item;
|
||||
static GtkWidget *controls_window;
|
||||
static GtkWidget *controls_status_label;
|
||||
static GtkWidget *controls_summary_label;
|
||||
static GtkWidget *controls_core_status_label;
|
||||
static GtkWidget *controls_traffic_status_label;
|
||||
static GtkWidget *controls_zapret_status_label;
|
||||
static GtkWidget *controls_proxy_button;
|
||||
static GtkWidget *controls_tproxy_button;
|
||||
static GtkWidget *controls_tun_button;
|
||||
static GtkWidget *controls_zapret_button;
|
||||
|
||||
static gboolean command_succeeds(gchar **argv) {
|
||||
typedef struct
|
||||
{
|
||||
gboolean loaded;
|
||||
gboolean socks_available;
|
||||
gboolean tproxy_available;
|
||||
gboolean tun_available;
|
||||
gboolean zapret_available;
|
||||
gboolean subscription_update_available;
|
||||
gboolean socks;
|
||||
gboolean tproxy;
|
||||
gboolean tun;
|
||||
gboolean zapret;
|
||||
} ServiceState;
|
||||
|
||||
static ServiceState initial_state;
|
||||
|
||||
static gboolean command_succeeds(gchar **argv)
|
||||
{
|
||||
GError *error = NULL;
|
||||
gint wait_status = 0;
|
||||
|
||||
if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL, &wait_status, &error)) {
|
||||
if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL, &wait_status, &error))
|
||||
{
|
||||
g_clear_error(&error);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
if (!g_spawn_check_wait_status(wait_status, &error)) {
|
||||
if (!g_spawn_check_wait_status(wait_status, &error))
|
||||
{
|
||||
g_clear_error(&error);
|
||||
return FALSE;
|
||||
}
|
||||
@@ -45,17 +66,20 @@ static gboolean command_succeeds(gchar **argv) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static gboolean command_stdout(gchar **argv, gchar **stdout_text) {
|
||||
static gboolean command_stdout(gchar **argv, gchar **stdout_text)
|
||||
{
|
||||
GError *error = NULL;
|
||||
gint wait_status = 0;
|
||||
|
||||
*stdout_text = NULL;
|
||||
if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, stdout_text, NULL, &wait_status, &error)) {
|
||||
if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, stdout_text, NULL, &wait_status, &error))
|
||||
{
|
||||
g_clear_error(&error);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
if (!g_spawn_check_wait_status(wait_status, &error)) {
|
||||
if (!g_spawn_check_wait_status(wait_status, &error))
|
||||
{
|
||||
g_clear_error(&error);
|
||||
g_clear_pointer(stdout_text, g_free);
|
||||
return FALSE;
|
||||
@@ -64,22 +88,28 @@ static gboolean command_stdout(gchar **argv, gchar **stdout_text) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static gboolean on_controls_delete(GtkWidget *widget, GdkEvent *event, gpointer data) {
|
||||
(void)event; (void)data;
|
||||
static gboolean on_controls_delete(GtkWidget *widget, GdkEvent *event, gpointer data)
|
||||
{
|
||||
(void)event;
|
||||
(void)data;
|
||||
gtk_widget_hide(widget);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static void on_close_controls(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
if (controls_window) {
|
||||
static void on_close_controls(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
if (controls_window)
|
||||
{
|
||||
gtk_widget_hide(controls_window);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_open_controls(GtkWidget *item, gpointer data);
|
||||
|
||||
static gboolean on_open_controls_idle(gpointer data) {
|
||||
static gboolean on_open_controls_idle(gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
on_open_controls(NULL, NULL);
|
||||
return G_SOURCE_REMOVE;
|
||||
@@ -89,13 +119,16 @@ static GDBusMessage *on_session_bus_message(
|
||||
GDBusConnection *connection,
|
||||
GDBusMessage *message,
|
||||
gboolean incoming,
|
||||
gpointer user_data
|
||||
) {
|
||||
(void)connection; (void)user_data;
|
||||
if (!incoming || !message) {
|
||||
gpointer user_data)
|
||||
{
|
||||
(void)connection;
|
||||
(void)user_data;
|
||||
if (!incoming || !message)
|
||||
{
|
||||
return message;
|
||||
}
|
||||
if (g_dbus_message_get_message_type(message) != G_DBUS_MESSAGE_TYPE_METHOD_CALL) {
|
||||
if (g_dbus_message_get_message_type(message) != G_DBUS_MESSAGE_TYPE_METHOD_CALL)
|
||||
{
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -106,79 +139,55 @@ static GDBusMessage *on_session_bus_message(
|
||||
if (iface && member && path &&
|
||||
strcmp(iface, "org.kde.StatusNotifierItem") == 0 &&
|
||||
strcmp(member, "Activate") == 0 &&
|
||||
g_str_has_prefix(path, "/org/ayatana/NotificationItem/")) {
|
||||
g_str_has_prefix(path, "/org/ayatana/NotificationItem/"))
|
||||
{
|
||||
g_idle_add(on_open_controls_idle, NULL);
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
static gboolean service_exists(const char *name) {
|
||||
gchar *load_state = NULL;
|
||||
gboolean exists = FALSE;
|
||||
static gboolean run_proxy_ctl1(const char *arg1)
|
||||
{
|
||||
gchar *argv[] = {
|
||||
(gchar *) SYSTEMCTL_BIN,
|
||||
(gchar *) "show",
|
||||
(gchar *) "--value",
|
||||
(gchar *) "--property=LoadState",
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
(gchar *)PROXY_CTL_BIN,
|
||||
(gchar *)arg1,
|
||||
NULL};
|
||||
|
||||
argv[4] = g_strdup_printf("%s.service", name);
|
||||
if (command_stdout(argv, &load_state)) {
|
||||
g_strstrip(load_state);
|
||||
exists = load_state[0] != '\0' && strcmp(load_state, "not-found") != 0;
|
||||
}
|
||||
|
||||
g_free(argv[4]);
|
||||
g_free(load_state);
|
||||
return exists;
|
||||
return command_succeeds(argv);
|
||||
}
|
||||
|
||||
static gboolean service_active(const char *name) {
|
||||
static gboolean run_proxy_ctl2(const char *arg1, const char *arg2)
|
||||
{
|
||||
gchar *argv[] = {
|
||||
(gchar *) SYSTEMCTL_BIN,
|
||||
(gchar *) "is-active",
|
||||
(gchar *) "--quiet",
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
(gchar *)PROXY_CTL_BIN,
|
||||
(gchar *)arg1,
|
||||
(gchar *)arg2,
|
||||
NULL};
|
||||
|
||||
argv[3] = g_strdup_printf("%s.service", name);
|
||||
gboolean active = command_succeeds(argv);
|
||||
g_free(argv[3]);
|
||||
return active;
|
||||
return command_succeeds(argv);
|
||||
}
|
||||
|
||||
static gboolean run_privileged(const char *action, const char *service) {
|
||||
char cmd[512];
|
||||
|
||||
snprintf(
|
||||
cmd,
|
||||
sizeof(cmd),
|
||||
"%s %s %s %s.service",
|
||||
PKEXEC_BIN,
|
||||
SYSTEMCTL_BIN,
|
||||
action,
|
||||
service
|
||||
);
|
||||
|
||||
return system(cmd) == 0;
|
||||
static gboolean parse_proxy_ctl_bool(const char *value)
|
||||
{
|
||||
return value && strcmp(value, "true") == 0;
|
||||
}
|
||||
|
||||
static const char *pick_icon_name(
|
||||
const char *const *candidates,
|
||||
gsize candidates_len,
|
||||
const char *fallback
|
||||
) {
|
||||
const char *fallback)
|
||||
{
|
||||
GtkIconTheme *theme = gtk_icon_theme_get_default();
|
||||
if (!theme) {
|
||||
if (!theme)
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
|
||||
for (gsize i = 0; i < candidates_len; ++i) {
|
||||
if (gtk_icon_theme_has_icon(theme, candidates[i])) {
|
||||
for (gsize i = 0; i < candidates_len; ++i)
|
||||
{
|
||||
if (gtk_icon_theme_has_icon(theme, candidates[i]))
|
||||
{
|
||||
return candidates[i];
|
||||
}
|
||||
}
|
||||
@@ -186,141 +195,399 @@ static const char *pick_icon_name(
|
||||
return fallback;
|
||||
}
|
||||
|
||||
static void update_status(void) {
|
||||
gboolean socks = service_active("proxy-suite-socks");
|
||||
gboolean tproxy = service_active("proxy-suite-tproxy");
|
||||
gboolean tun = service_active("proxy-suite-tun");
|
||||
static ServiceState get_service_state(void)
|
||||
{
|
||||
ServiceState state = {0};
|
||||
gchar *stdout_text = NULL;
|
||||
gchar *argv[] = {
|
||||
(gchar *)PROXY_CTL_BIN,
|
||||
(gchar *)"status",
|
||||
(gchar *)"--tray",
|
||||
NULL};
|
||||
|
||||
if (!command_stdout(argv, &stdout_text))
|
||||
{
|
||||
return state;
|
||||
}
|
||||
|
||||
state.loaded = TRUE;
|
||||
|
||||
gchar **lines = g_strsplit(stdout_text, "\n", -1);
|
||||
for (gchar **line = lines; line && *line; ++line)
|
||||
{
|
||||
if ((*line)[0] == '\0')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
gchar **parts = g_strsplit(*line, "=", 2);
|
||||
if (!parts[0] || !parts[1])
|
||||
{
|
||||
g_strfreev(parts);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (strcmp(parts[0], "socks_available") == 0)
|
||||
{
|
||||
state.socks_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "socks_active") == 0)
|
||||
{
|
||||
state.socks = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "tproxy_available") == 0)
|
||||
{
|
||||
state.tproxy_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "tproxy_active") == 0)
|
||||
{
|
||||
state.tproxy = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "tun_available") == 0)
|
||||
{
|
||||
state.tun_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "tun_active") == 0)
|
||||
{
|
||||
state.tun = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "zapret_available") == 0)
|
||||
{
|
||||
state.zapret_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "zapret_active") == 0)
|
||||
{
|
||||
state.zapret = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "subscription_update_available") == 0)
|
||||
{
|
||||
state.subscription_update_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
|
||||
g_strfreev(parts);
|
||||
}
|
||||
|
||||
g_strfreev(lines);
|
||||
g_free(stdout_text);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
static const char *traffic_mode_label(const ServiceState *state)
|
||||
{
|
||||
if (state->tun)
|
||||
{
|
||||
return "TUN tunnel enabled";
|
||||
}
|
||||
if (state->tproxy)
|
||||
{
|
||||
return "TProxy interception enabled";
|
||||
}
|
||||
return "System-wide routing disabled";
|
||||
}
|
||||
|
||||
static const char *indicator_label_text(const ServiceState *state)
|
||||
{
|
||||
if (state->socks && (state->tproxy || state->tun) && state->zapret)
|
||||
{
|
||||
return "Proxy + traffic + zapret";
|
||||
}
|
||||
if (state->socks && (state->tproxy || state->tun))
|
||||
{
|
||||
return "Proxy + traffic";
|
||||
}
|
||||
if (state->socks && state->zapret)
|
||||
{
|
||||
return "Proxy + zapret";
|
||||
}
|
||||
if (state->socks)
|
||||
{
|
||||
return "Proxy only";
|
||||
}
|
||||
if (state->zapret)
|
||||
{
|
||||
return "Zapret only";
|
||||
}
|
||||
return "Inactive";
|
||||
}
|
||||
|
||||
static void update_status(void)
|
||||
{
|
||||
ServiceState state = get_service_state();
|
||||
/* Gold: TUN/TProxy active (highest priority) */
|
||||
static const char *const tunnel_icons[] = {
|
||||
"proxy-suite-tunnel",
|
||||
"proxy-suite-tunnel-symbolic",
|
||||
"network-vpn",
|
||||
"network-vpn-symbolic"};
|
||||
/* Green: proxy + zapret, no tunnel */
|
||||
static const char *const active_icons[] = {
|
||||
"proxy-suite-active",
|
||||
"proxy-suite-active-symbolic",
|
||||
"network-vpn",
|
||||
"network-vpn-symbolic"
|
||||
};
|
||||
static const char *const partial_icons[] = {
|
||||
"network-vpn-symbolic"};
|
||||
/* Orange: proxy only */
|
||||
static const char *const proxy_icons[] = {
|
||||
"proxy-suite-proxy",
|
||||
"proxy-suite-proxy-symbolic",
|
||||
"network-vpn-acquiring",
|
||||
"network-vpn",
|
||||
"network-vpn-acquiring-symbolic",
|
||||
"network-vpn-symbolic"
|
||||
};
|
||||
static const char *const disconnected_icons[] = {
|
||||
"network-vpn",
|
||||
"network-vpn-symbolic"};
|
||||
/* Blue: zapret only */
|
||||
static const char *const zapret_icons[] = {
|
||||
"proxy-suite-zapret",
|
||||
"proxy-suite-zapret-symbolic",
|
||||
"network-vpn-acquiring",
|
||||
"network-vpn-acquiring-symbolic",
|
||||
"network-vpn",
|
||||
"network-vpn-symbolic"};
|
||||
/* Red: everything disabled */
|
||||
static const char *const disabled_icons[] = {
|
||||
"proxy-suite-disabled",
|
||||
"proxy-suite-disabled-symbolic",
|
||||
"network-vpn-disconnected",
|
||||
"network-offline",
|
||||
"network-error",
|
||||
"process-stop",
|
||||
"dialog-error",
|
||||
"network-vpn-disconnected-symbolic",
|
||||
"network-offline-symbolic",
|
||||
"network-error-symbolic",
|
||||
"process-stop-symbolic",
|
||||
"dialog-error-symbolic"
|
||||
};
|
||||
"dialog-error-symbolic"};
|
||||
|
||||
if (socks) {
|
||||
if (tproxy || tun) {
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn")
|
||||
);
|
||||
} else {
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(partial_icons, G_N_ELEMENTS(partial_icons), "network-vpn-acquiring")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (!state.loaded)
|
||||
{
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(disconnected_icons, G_N_ELEMENTS(disconnected_icons), "network-vpn-disconnected")
|
||||
);
|
||||
pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected"));
|
||||
app_indicator_set_label(indicator, "Status unavailable", "");
|
||||
|
||||
if (status_item)
|
||||
{
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), "[Status] proxy-ctl status unavailable");
|
||||
}
|
||||
if (controls_summary_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_summary_label), "[Status] proxy-ctl status unavailable");
|
||||
}
|
||||
if (controls_core_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] SOCKS proxy: Unknown");
|
||||
}
|
||||
if (controls_traffic_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown");
|
||||
}
|
||||
if (controls_zapret_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item),
|
||||
socks ? "SOCKS Proxy: Running" : "SOCKS Proxy: Stopped");
|
||||
if (controls_status_label) {
|
||||
gtk_label_set_text(GTK_LABEL(controls_status_label),
|
||||
socks ? "SOCKS Proxy: Running" : "SOCKS Proxy: Stopped");
|
||||
const char *traffic = traffic_mode_label(&state);
|
||||
const char *summary = indicator_label_text(&state);
|
||||
const char *zapret = state.zapret ? "Active" : "Stopped";
|
||||
gchar *summary_text = g_strdup_printf(
|
||||
"[Status] %s | Traffic: %s | Zapret: %s",
|
||||
state.socks ? "Proxy ready" : "Proxy down",
|
||||
traffic,
|
||||
zapret);
|
||||
gchar *core_text = g_strdup_printf(
|
||||
"[Core] SOCKS proxy: %s",
|
||||
state.socks ? "Running" : "Stopped");
|
||||
gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic);
|
||||
gchar *zapret_text = g_strdup_printf(
|
||||
"[Zapret] zapret-discord-youtube: %s",
|
||||
zapret);
|
||||
|
||||
if (state.tproxy || state.tun)
|
||||
{
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(tunnel_icons, G_N_ELEMENTS(tunnel_icons), "network-vpn"));
|
||||
}
|
||||
if (proxy_item) {
|
||||
else if (state.socks && state.zapret)
|
||||
{
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn"));
|
||||
}
|
||||
else if (state.socks)
|
||||
{
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(proxy_icons, G_N_ELEMENTS(proxy_icons), "network-vpn-acquiring"));
|
||||
}
|
||||
else if (state.zapret)
|
||||
{
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(zapret_icons, G_N_ELEMENTS(zapret_icons), "network-vpn-acquiring"));
|
||||
}
|
||||
else
|
||||
{
|
||||
app_indicator_set_icon(
|
||||
indicator,
|
||||
pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected"));
|
||||
}
|
||||
app_indicator_set_label(indicator, summary, "");
|
||||
|
||||
if (status_item)
|
||||
{
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), summary_text);
|
||||
}
|
||||
if (controls_summary_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_summary_label), summary_text);
|
||||
}
|
||||
if (controls_core_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text);
|
||||
}
|
||||
if (controls_traffic_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text);
|
||||
}
|
||||
if (controls_zapret_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), zapret_text);
|
||||
}
|
||||
if (proxy_item)
|
||||
{
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item),
|
||||
socks ? "Disable Proxy" : "Enable Proxy");
|
||||
state.socks ? "[Core] Stop SOCKS Proxy" : "[Core] Start SOCKS Proxy");
|
||||
}
|
||||
if (controls_proxy_button) {
|
||||
if (controls_proxy_button)
|
||||
{
|
||||
gtk_button_set_label(GTK_BUTTON(controls_proxy_button),
|
||||
socks ? "Disable Proxy" : "Enable Proxy");
|
||||
state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy");
|
||||
}
|
||||
|
||||
if (tproxy_item) {
|
||||
if (tproxy_item)
|
||||
{
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(tproxy_item),
|
||||
tproxy ? "Disable TProxy" : "Enable TProxy");
|
||||
state.tproxy ? "[Traffic] Stop TProxy Mode" : "[Traffic] Start TProxy Mode");
|
||||
}
|
||||
if (controls_tproxy_button) {
|
||||
if (controls_tproxy_button)
|
||||
{
|
||||
gtk_button_set_label(GTK_BUTTON(controls_tproxy_button),
|
||||
tproxy ? "Disable TProxy" : "Enable TProxy");
|
||||
state.tproxy ? "Stop TProxy Mode" : "Start TProxy Mode");
|
||||
}
|
||||
if (tun_item) {
|
||||
if (tun_item)
|
||||
{
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(tun_item),
|
||||
tun ? "Disable TUN" : "Enable TUN");
|
||||
state.tun ? "[Traffic] Stop TUN Mode" : "[Traffic] Start TUN Mode");
|
||||
}
|
||||
if (controls_tun_button) {
|
||||
if (controls_tun_button)
|
||||
{
|
||||
gtk_button_set_label(GTK_BUTTON(controls_tun_button),
|
||||
tun ? "Disable TUN" : "Enable TUN");
|
||||
state.tun ? "Stop TUN Mode" : "Start TUN Mode");
|
||||
}
|
||||
if (zapret_item)
|
||||
{
|
||||
gtk_menu_item_set_label(
|
||||
GTK_MENU_ITEM(zapret_item),
|
||||
state.zapret ? "[Zapret] Stop zapret-discord-youtube" : "[Zapret] Start zapret-discord-youtube");
|
||||
}
|
||||
if (controls_zapret_button)
|
||||
{
|
||||
gtk_button_set_label(
|
||||
GTK_BUTTON(controls_zapret_button),
|
||||
state.zapret ? "Stop zapret-discord-youtube" : "Start zapret-discord-youtube");
|
||||
}
|
||||
|
||||
g_free(summary_text);
|
||||
g_free(core_text);
|
||||
g_free(traffic_text);
|
||||
g_free(zapret_text);
|
||||
}
|
||||
|
||||
static void on_proxy_toggle(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
if (service_active("proxy-suite-socks")) {
|
||||
if (service_active("proxy-suite-tproxy")) {
|
||||
run_privileged("stop", "proxy-suite-tproxy");
|
||||
}
|
||||
if (service_active("proxy-suite-tun")) {
|
||||
run_privileged("stop", "proxy-suite-tun");
|
||||
}
|
||||
run_privileged("stop", "proxy-suite-socks");
|
||||
} else {
|
||||
run_privileged("start", "proxy-suite-socks");
|
||||
static void on_proxy_toggle(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
ServiceState state = get_service_state();
|
||||
if (state.socks)
|
||||
{
|
||||
run_proxy_ctl2("proxy", "off");
|
||||
}
|
||||
else
|
||||
{
|
||||
run_proxy_ctl2("proxy", "on");
|
||||
}
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_tproxy_toggle(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
if (service_active("proxy-suite-tproxy")) {
|
||||
run_privileged("stop", "proxy-suite-tproxy");
|
||||
} else {
|
||||
run_privileged("start", "proxy-suite-tproxy");
|
||||
static void on_tproxy_toggle(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
ServiceState state = get_service_state();
|
||||
if (state.tproxy)
|
||||
{
|
||||
run_proxy_ctl2("tproxy", "off");
|
||||
}
|
||||
else
|
||||
{
|
||||
run_proxy_ctl2("tproxy", "on");
|
||||
}
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_tun_toggle(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
if (service_active("proxy-suite-tun")) {
|
||||
run_privileged("stop", "proxy-suite-tun");
|
||||
} else {
|
||||
run_privileged("start", "proxy-suite-tun");
|
||||
static void on_tun_toggle(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
ServiceState state = get_service_state();
|
||||
if (state.tun)
|
||||
{
|
||||
run_proxy_ctl2("tun", "off");
|
||||
}
|
||||
else
|
||||
{
|
||||
run_proxy_ctl2("tun", "on");
|
||||
}
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_restart(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
gboolean tun_was_active = service_active("proxy-suite-tun");
|
||||
|
||||
if (run_privileged("restart", "proxy-suite-socks") && tun_was_active) {
|
||||
run_privileged("restart", "proxy-suite-tun");
|
||||
static void on_zapret_toggle(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
ServiceState state = get_service_state();
|
||||
if (state.zapret)
|
||||
{
|
||||
run_proxy_ctl2("zapret", "off");
|
||||
}
|
||||
else
|
||||
{
|
||||
run_proxy_ctl2("zapret", "on");
|
||||
}
|
||||
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_subscription_update(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
run_privileged("start", "proxy-suite-subscription-update");
|
||||
static void on_restart(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
run_proxy_ctl1("restart");
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_open_controls(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
if (!controls_window) {
|
||||
static void on_subscription_update(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
run_proxy_ctl2("subscription", "update");
|
||||
}
|
||||
|
||||
static void on_open_controls(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
if (!controls_window)
|
||||
{
|
||||
return;
|
||||
}
|
||||
update_status();
|
||||
@@ -328,18 +595,22 @@ static void on_open_controls(GtkWidget *item, gpointer data) {
|
||||
gtk_window_present(GTK_WINDOW(controls_window));
|
||||
}
|
||||
|
||||
static void on_quit(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
static void on_quit(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
(void)data;
|
||||
gtk_main_quit();
|
||||
}
|
||||
|
||||
static gboolean on_timer(gpointer data) {
|
||||
static gboolean on_timer(gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
update_status();
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static void build_controls_window(void) {
|
||||
static void build_controls_window(void)
|
||||
{
|
||||
controls_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
gtk_window_set_title(GTK_WINDOW(controls_window), "Proxy Suite Controls");
|
||||
gtk_window_set_resizable(GTK_WINDOW(controls_window), FALSE);
|
||||
@@ -349,58 +620,105 @@ static void build_controls_window(void) {
|
||||
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_add(GTK_CONTAINER(controls_window), box);
|
||||
|
||||
controls_status_label = gtk_label_new("SOCKS Proxy: Unknown");
|
||||
gtk_label_set_xalign(GTK_LABEL(controls_status_label), 0.0f);
|
||||
gtk_box_pack_start(GTK_BOX(box), controls_status_label, FALSE, FALSE, 0);
|
||||
controls_summary_label = gtk_label_new("[Status] Loading service state...");
|
||||
gtk_label_set_xalign(GTK_LABEL(controls_summary_label), 0.0f);
|
||||
gtk_box_pack_start(GTK_BOX(box), controls_summary_label, FALSE, FALSE, 0);
|
||||
|
||||
controls_proxy_button = gtk_button_new_with_label("Enable Proxy");
|
||||
GtkWidget *core_frame = gtk_frame_new("[Core] Proxy");
|
||||
GtkWidget *core_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(core_box), 6);
|
||||
gtk_container_add(GTK_CONTAINER(core_frame), core_box);
|
||||
gtk_box_pack_start(GTK_BOX(box), core_frame, FALSE, FALSE, 0);
|
||||
|
||||
controls_core_status_label = gtk_label_new("[Core] SOCKS proxy: Unknown");
|
||||
gtk_label_set_xalign(GTK_LABEL(controls_core_status_label), 0.0f);
|
||||
gtk_box_pack_start(GTK_BOX(core_box), controls_core_status_label, FALSE, FALSE, 0);
|
||||
|
||||
controls_proxy_button = gtk_button_new_with_label("Start SOCKS Proxy");
|
||||
g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), controls_proxy_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0);
|
||||
|
||||
if (service_exists("proxy-suite-tproxy")) {
|
||||
controls_tproxy_button = gtk_button_new_with_label("Enable TProxy");
|
||||
GtkWidget *traffic_frame = gtk_frame_new("[Traffic] System-wide traffic mode");
|
||||
GtkWidget *traffic_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(traffic_box), 6);
|
||||
gtk_container_add(GTK_CONTAINER(traffic_frame), traffic_box);
|
||||
gtk_box_pack_start(GTK_BOX(box), traffic_frame, FALSE, FALSE, 0);
|
||||
|
||||
controls_traffic_status_label = gtk_label_new("[Traffic] Mode: Unknown");
|
||||
gtk_label_set_xalign(GTK_LABEL(controls_traffic_status_label), 0.0f);
|
||||
gtk_box_pack_start(GTK_BOX(traffic_box), controls_traffic_status_label, FALSE, FALSE, 0);
|
||||
|
||||
if (initial_state.tproxy_available)
|
||||
{
|
||||
controls_tproxy_button = gtk_button_new_with_label("Start TProxy Mode");
|
||||
g_signal_connect(controls_tproxy_button, "clicked", G_CALLBACK(on_tproxy_toggle), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), controls_tproxy_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(traffic_box), controls_tproxy_button, FALSE, FALSE, 0);
|
||||
}
|
||||
|
||||
if (service_exists("proxy-suite-tun")) {
|
||||
controls_tun_button = gtk_button_new_with_label("Enable TUN");
|
||||
if (initial_state.tun_available)
|
||||
{
|
||||
controls_tun_button = gtk_button_new_with_label("Start TUN Mode");
|
||||
g_signal_connect(controls_tun_button, "clicked", G_CALLBACK(on_tun_toggle), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), controls_tun_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(traffic_box), controls_tun_button, FALSE, FALSE, 0);
|
||||
}
|
||||
|
||||
if (service_exists("proxy-suite-subscription-update")) {
|
||||
if (initial_state.zapret_available)
|
||||
{
|
||||
GtkWidget *zapret_frame = gtk_frame_new("[Zapret] DPI bypass");
|
||||
GtkWidget *zapret_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(zapret_box), 6);
|
||||
gtk_container_add(GTK_CONTAINER(zapret_frame), zapret_box);
|
||||
gtk_box_pack_start(GTK_BOX(box), zapret_frame, FALSE, FALSE, 0);
|
||||
|
||||
controls_zapret_status_label = gtk_label_new("[Zapret] zapret-discord-youtube: Unknown");
|
||||
gtk_label_set_xalign(GTK_LABEL(controls_zapret_status_label), 0.0f);
|
||||
gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_status_label, FALSE, FALSE, 0);
|
||||
|
||||
controls_zapret_button = gtk_button_new_with_label("Start zapret-discord-youtube");
|
||||
g_signal_connect(controls_zapret_button, "clicked", G_CALLBACK(on_zapret_toggle), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_button, FALSE, FALSE, 0);
|
||||
}
|
||||
|
||||
GtkWidget *tools_frame = gtk_frame_new("[Tools] Maintenance");
|
||||
GtkWidget *tools_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(tools_box), 6);
|
||||
gtk_container_add(GTK_CONTAINER(tools_frame), tools_box);
|
||||
gtk_box_pack_start(GTK_BOX(box), tools_frame, FALSE, FALSE, 0);
|
||||
|
||||
if (initial_state.subscription_update_available)
|
||||
{
|
||||
GtkWidget *sub_update_button = gtk_button_new_with_label("Update Subscriptions");
|
||||
g_signal_connect(sub_update_button, "clicked", G_CALLBACK(on_subscription_update), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), sub_update_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(tools_box), sub_update_button, FALSE, FALSE, 0);
|
||||
}
|
||||
|
||||
GtkWidget *restart_button = gtk_button_new_with_label("Restart Services");
|
||||
GtkWidget *restart_button = gtk_button_new_with_label("Restart Active Services");
|
||||
g_signal_connect(restart_button, "clicked", G_CALLBACK(on_restart), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), restart_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(tools_box), restart_button, FALSE, FALSE, 0);
|
||||
|
||||
GtkWidget *close_button = gtk_button_new_with_label("Close Window");
|
||||
g_signal_connect(close_button, "clicked", G_CALLBACK(on_close_controls), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), close_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(tools_box), close_button, FALSE, FALSE, 0);
|
||||
|
||||
GtkWidget *quit_button = gtk_button_new_with_label("Exit Tray");
|
||||
g_signal_connect(quit_button, "clicked", G_CALLBACK(on_quit), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), quit_button, FALSE, FALSE, 0);
|
||||
gtk_box_pack_start(GTK_BOX(tools_box), quit_button, FALSE, FALSE, 0);
|
||||
|
||||
gtk_widget_show_all(controls_window);
|
||||
gtk_widget_hide(controls_window);
|
||||
}
|
||||
|
||||
static void build_menu(void) {
|
||||
static void build_menu(void)
|
||||
{
|
||||
menu = gtk_menu_new();
|
||||
|
||||
status_item = gtk_menu_item_new_with_label("SOCKS Proxy: Unknown");
|
||||
status_item = gtk_menu_item_new_with_label("[Status] Loading service state...");
|
||||
gtk_widget_set_sensitive(status_item, FALSE);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), status_item);
|
||||
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
|
||||
|
||||
proxy_item = gtk_menu_item_new_with_label("Enable Proxy");
|
||||
proxy_item = gtk_menu_item_new_with_label("[Core] Start SOCKS Proxy");
|
||||
g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item);
|
||||
|
||||
@@ -410,19 +728,33 @@ static void build_menu(void) {
|
||||
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
|
||||
|
||||
if (service_exists("proxy-suite-tproxy")) {
|
||||
tproxy_item = gtk_menu_item_new_with_label("Enable TProxy");
|
||||
if (initial_state.tproxy_available)
|
||||
{
|
||||
tproxy_item = gtk_menu_item_new_with_label("[Traffic] Start TProxy Mode");
|
||||
g_signal_connect(tproxy_item, "activate", G_CALLBACK(on_tproxy_toggle), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tproxy_item);
|
||||
}
|
||||
|
||||
if (service_exists("proxy-suite-tun")) {
|
||||
tun_item = gtk_menu_item_new_with_label("Enable TUN");
|
||||
if (initial_state.tun_available)
|
||||
{
|
||||
tun_item = gtk_menu_item_new_with_label("[Traffic] Start TUN Mode");
|
||||
g_signal_connect(tun_item, "activate", G_CALLBACK(on_tun_toggle), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item);
|
||||
}
|
||||
|
||||
if (service_exists("proxy-suite-subscription-update")) {
|
||||
if (initial_state.zapret_available)
|
||||
{
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
|
||||
|
||||
zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret-discord-youtube");
|
||||
g_signal_connect(zapret_item, "activate", G_CALLBACK(on_zapret_toggle), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item);
|
||||
}
|
||||
|
||||
if (initial_state.subscription_update_available)
|
||||
{
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
|
||||
|
||||
GtkWidget *sub_update_item = gtk_menu_item_new_with_label("Update Subscriptions");
|
||||
g_signal_connect(sub_update_item, "activate", G_CALLBACK(on_subscription_update), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), sub_update_item);
|
||||
@@ -430,7 +762,7 @@ static void build_menu(void) {
|
||||
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
|
||||
|
||||
GtkWidget *restart_item = gtk_menu_item_new_with_label("Restart Services");
|
||||
GtkWidget *restart_item = gtk_menu_item_new_with_label("[Tools] Restart Active Services");
|
||||
g_signal_connect(restart_item, "activate", G_CALLBACK(on_restart), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), restart_item);
|
||||
|
||||
@@ -443,33 +775,37 @@ static void build_menu(void) {
|
||||
gtk_widget_show_all(menu);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (!gtk_init_check(&argc, &argv)) {
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
if (!gtk_init_check(&argc, &argv))
|
||||
{
|
||||
fprintf(stderr, "proxy-suite-tray: failed to initialize GTK\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
GError *bus_error = NULL;
|
||||
GDBusConnection *session_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &bus_error);
|
||||
if (session_bus) {
|
||||
if (session_bus)
|
||||
{
|
||||
g_dbus_connection_add_filter(session_bus, on_session_bus_message, NULL, NULL);
|
||||
g_object_unref(session_bus);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(
|
||||
stderr,
|
||||
"proxy-suite-tray: warning: failed to monitor session bus: %s\n",
|
||||
bus_error ? bus_error->message : "unknown error"
|
||||
);
|
||||
bus_error ? bus_error->message : "unknown error");
|
||||
g_clear_error(&bus_error);
|
||||
}
|
||||
|
||||
indicator = app_indicator_new(
|
||||
"proxy-suite-tray",
|
||||
"network-vpn-disconnected",
|
||||
APP_INDICATOR_CATEGORY_SYSTEM_SERVICES
|
||||
);
|
||||
"proxy-suite-disabled",
|
||||
APP_INDICATOR_CATEGORY_SYSTEM_SERVICES);
|
||||
app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE);
|
||||
|
||||
initial_state = get_service_state();
|
||||
build_menu();
|
||||
build_controls_window();
|
||||
app_indicator_set_menu(indicator, GTK_MENU(menu));
|
||||
|
||||
@@ -4,8 +4,8 @@ let
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Flowseal";
|
||||
repo = "tg-ws-proxy";
|
||||
rev = "fe4e0e82344d8e8ca5e54b7752cafa934fb763ab";
|
||||
hash = "sha256-tXDfYE1qFYTAWTu7pse/jcovDmX/F42SCGOzsUBmljs=";
|
||||
rev = "v1.6.2";
|
||||
hash = "sha256-0X8N5FklFXJY5rHzozIhgNHjrEfhfPeqY6Yqc3l3ETU=";
|
||||
};
|
||||
|
||||
pythonEnv = pkgs.python3.withPackages (
|
||||
|
||||
@@ -1,383 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
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
|
||||
"""
|
||||
"""Read a proxy URL from stdin and emit a sing-box outbound JSON object."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
|
||||
def _qs(query: str) -> dict:
|
||||
return dict(urllib.parse.parse_qsl(query))
|
||||
|
||||
|
||||
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
|
||||
"""
|
||||
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:
|
||||
"""
|
||||
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)
|
||||
|
||||
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:
|
||||
"""
|
||||
trojan://PASSWORD@HOST:PORT?sni=SNI&fp=chrome&security=tls&type=tcp|ws|grpc&path=...
|
||||
"""
|
||||
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:
|
||||
"""
|
||||
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"
|
||||
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:
|
||||
"""
|
||||
tuic://UUID:PASSWORD@HOST:PORT?congestion_control=bbr&udp_relay_mode=native&alpn=h3&sni=SNI
|
||||
"""
|
||||
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:
|
||||
"""
|
||||
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"
|
||||
|
||||
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:
|
||||
"""
|
||||
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()
|
||||
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,
|
||||
}
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -389,22 +17,17 @@ def main() -> None:
|
||||
args = ap.parse_args()
|
||||
|
||||
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:
|
||||
ob = PARSERS[scheme](url, args.tag)
|
||||
except Exception as e:
|
||||
print(f"error: failed to parse {scheme} URL: {e}", file=sys.stderr)
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark)
|
||||
except ValueError as exc:
|
||||
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)
|
||||
|
||||
if args.routing_mark is not None:
|
||||
ob["routing_mark"] = args.routing_mark
|
||||
|
||||
print(json.dumps(ob))
|
||||
print(json.dumps(outbound))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -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
|
||||
@@ -1,464 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
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
|
||||
"""
|
||||
"""Read a subscription URL from stdin and emit a JSON array of outbounds."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from proxy_parsing import decode_subscription, fetch_raw, 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:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Fetch a proxy subscription URL from stdin and emit a sing-box outbound JSON array."
|
||||
)
|
||||
ap.add_argument("--tag-prefix", required=True, dest="tag_prefix",
|
||||
help="Prefix for outbound tags, e.g. 'my-sub'.")
|
||||
ap.add_argument(
|
||||
"--tag-prefix",
|
||||
required=True,
|
||||
dest="tag_prefix",
|
||||
help="Prefix for outbound tags, e.g. 'my-sub'.",
|
||||
)
|
||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
args = ap.parse_args()
|
||||
|
||||
|
||||
@@ -12,38 +12,25 @@ BUILTIN_ACTIVATION_FALLBACKS = {
|
||||
"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 = {
|
||||
"general": {
|
||||
"match": ["list-general.txt", "list-general-user.txt"],
|
||||
"remove": [
|
||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-general\.txt"|[^ ]*/hostlists/list-general\.txt)',
|
||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-general-user\.txt"|[^ ]*/hostlists/list-general-user\.txt)',
|
||||
],
|
||||
},
|
||||
"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)',
|
||||
],
|
||||
},
|
||||
"general": _mk_family(["general", "general-user"], ["general", "general-user"]),
|
||||
"google": _mk_family(["google"], ["google"]),
|
||||
"instagram": _mk_family(["instagram"], ["instagram"]),
|
||||
"soundcloud": _mk_family(["soundcloud"], ["soundcloud"]),
|
||||
"twitter": _mk_family(["twitter"], ["twitter"]),
|
||||
}
|
||||
|
||||
|
||||
@@ -78,19 +65,32 @@ def add_standard_excludes(line: str, standard_excludes: list[str]) -> str:
|
||||
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(
|
||||
line: str,
|
||||
family: str,
|
||||
hostlist_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> str:
|
||||
rendered = strip_trailing_new(line)
|
||||
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"
|
||||
return _render_args(line, hostlist_path, standard_excludes, preset_family=family)
|
||||
|
||||
|
||||
def render_custom_args(
|
||||
@@ -98,12 +98,7 @@ def render_custom_args(
|
||||
hostlist_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> str:
|
||||
rendered = strip_trailing_new(fragment)
|
||||
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"
|
||||
return _render_args(fragment, hostlist_path, standard_excludes)
|
||||
|
||||
|
||||
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 not matches:
|
||||
raise ValueError(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]
|
||||
raise ValueError(
|
||||
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(
|
||||
@@ -145,8 +145,12 @@ def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
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("--spec", required=True, help="JSON file describing custom hostlist rules")
|
||||
parser.add_argument(
|
||||
"--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()
|
||||
|
||||
config_path = Path(args.config)
|
||||
@@ -177,10 +181,14 @@ def main() -> int:
|
||||
preset = entry.get("preset")
|
||||
if preset:
|
||||
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", []):
|
||||
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:]
|
||||
config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/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 build_outbound(url: str, tag: str, routing_mark: int | None = None) -> dict:
|
||||
scheme = detect_scheme(url)
|
||||
if scheme not in PARSERS:
|
||||
raise ValueError(f"unsupported scheme '{scheme}'")
|
||||
|
||||
outbound = PARSERS[scheme](url, tag)
|
||||
if routing_mark is not None:
|
||||
outbound["routing_mark"] = routing_mark
|
||||
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
|
||||
) -> 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)
|
||||
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
|
||||
@@ -0,0 +1,299 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
|
||||
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]:
|
||||
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":
|
||||
if transport_type == "ws":
|
||||
return {
|
||||
"type": "ws",
|
||||
"path": urllib.parse.unquote(path),
|
||||
"headers": {"Host": host_header},
|
||||
}
|
||||
if transport_type == "grpc":
|
||||
return {
|
||||
"type": "grpc",
|
||||
"service_name": urllib.parse.unquote(service_name),
|
||||
}
|
||||
if transport_type == "h2":
|
||||
return {
|
||||
"type": "http",
|
||||
"host": [host_header],
|
||||
"path": urllib.parse.unquote(path),
|
||||
}
|
||||
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) -> dict:
|
||||
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"] = _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", ""),
|
||||
}
|
||||
elif security == "tls":
|
||||
ob["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
|
||||
|
||||
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"] = _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 parse_shadowsocks(url: str, tag: str) -> dict:
|
||||
userinfo, host, port, _ = _parse_url_parts(url, "ss")
|
||||
|
||||
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"
|
||||
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,
|
||||
}
|
||||
@@ -2,32 +2,13 @@
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
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, *, expect_ok: bool = True):
|
||||
env = dict(os.environ)
|
||||
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
|
||||
def run_parser(url: str):
|
||||
return build_outbound(url, "test-outbound")
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
@@ -65,7 +46,11 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["tls"]["server_name"], "tls.example.com")
|
||||
|
||||
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")
|
||||
self.assertEqual(ob["type"], "shadowsocks")
|
||||
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
|
||||
@@ -97,9 +82,8 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["tls"]["server_name"], "proxy.example.com")
|
||||
|
||||
def test_invalid_scheme_fails(self):
|
||||
proc = run_parser("wireguard://example.com", expect_ok=False)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("unsupported scheme", proc.stderr)
|
||||
with self.assertRaisesRegex(ValueError, "unsupported scheme"):
|
||||
run_parser("wireguard://example.com")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,51 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
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
|
||||
# ---------------------------------------------------------------------------
|
||||
from proxy_parsing import decode_subscription, parse_subscription
|
||||
|
||||
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
|
||||
SS_URI = "ss://{}@ss.example.com:8388".format(
|
||||
@@ -60,32 +17,13 @@ def _make_b64_payload(*uris: str) -> bytes:
|
||||
return base64.b64encode(text.encode())
|
||||
|
||||
|
||||
def run_fetcher(server_data: bytes, tag_prefix: str = "test", *, expect_ok: bool = True, extra_args: list = None):
|
||||
srv, port = _start_server(server_data)
|
||||
url = f"http://127.0.0.1:{port}/sub"
|
||||
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
|
||||
cmd = [sys.executable, str(SCRIPT), "--tag-prefix", tag_prefix] + (extra_args or [])
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
input=url,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
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
|
||||
def run_fetcher(
|
||||
server_data: bytes, tag_prefix: str = "test", *, routing_mark: int | None = None
|
||||
):
|
||||
lines = decode_subscription(server_data)
|
||||
return parse_subscription(lines, tag_prefix, routing_mark)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class FetchSubscriptionTests(unittest.TestCase):
|
||||
|
||||
def test_base64_payload_mixed_protocols(self):
|
||||
@@ -119,6 +57,7 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
tag = obs[0]["tag"]
|
||||
# Tag must contain only safe characters
|
||||
import re
|
||||
|
||||
self.assertRegex(tag, r"^[a-zA-Z0-9_/\-]+$")
|
||||
|
||||
def test_tag_deduplication(self):
|
||||
@@ -145,15 +84,13 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
|
||||
def test_routing_mark_applied(self):
|
||||
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:
|
||||
self.assertEqual(ob["routing_mark"], 2)
|
||||
|
||||
def test_all_invalid_fails(self):
|
||||
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
|
||||
proc = run_fetcher(payload, expect_ok=False)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("no parseable proxy URIs", proc.stderr)
|
||||
self.assertEqual(run_fetcher(payload), [])
|
||||
|
||||
def test_index_tag_fallback_when_no_remark(self):
|
||||
# URIs without a remark should get index-based tags
|
||||
|
||||
@@ -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}"
|
||||