initial commit
This commit is contained in:
17 files changed
+2533
No files matched your search
+22
@@ -0,0 +1,22 @@
|
||||
.codex
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
# Nix build outputs
|
||||
result
|
||||
result-*
|
||||
|
||||
# Local shell/dev environment state
|
||||
.direnv/
|
||||
|
||||
# Likely secret material
|
||||
.env
|
||||
.env.*
|
||||
secrets/
|
||||
*.age
|
||||
*.pem
|
||||
*.key
|
||||
*.p12
|
||||
*.pfx
|
||||
@@ -0,0 +1,331 @@
|
||||
# proxy-suite-flake
|
||||
|
||||
Declarative proxy stack for NixOS. One flake, one module, done.
|
||||
|
||||
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 and their ilk — 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
|
||||
- **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** — MTProto WebSocket relay for sharing with others or for clients that don't support SOCKS
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
Add to your flake inputs:
|
||||
|
||||
```nix
|
||||
inputs.proxy-suite.url = "github:FUFSoB/proxy-suite-flake";
|
||||
```
|
||||
|
||||
No need to add zapret separately — it comes along as a transitive input.
|
||||
|
||||
Add the module to your NixOS configuration:
|
||||
|
||||
```nix
|
||||
imports = [ inputs.proxy-suite.nixosModules.default ];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Basic configuration
|
||||
|
||||
```nix
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
|
||||
singBox = {
|
||||
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;
|
||||
}
|
||||
];
|
||||
|
||||
routing.direct = {
|
||||
domains = [ "youtube.com" "discord.com" "x.com" "reddit.com" ];
|
||||
geosites = [ "category-ru" ];
|
||||
geoips = [ "ru" ];
|
||||
};
|
||||
routing.proxy.geosites = [ "google" ];
|
||||
};
|
||||
|
||||
zapret.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";
|
||||
};
|
||||
};
|
||||
};
|
||||
}];
|
||||
```
|
||||
|
||||
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
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
**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)
|
||||
```
|
||||
|
||||
`outbounds` works with `selection = "selector"` or `"urltest"`. `select` requires `selection = "selector"` and talks to the Clash-compatible REST API embedded in sing-box.
|
||||
|
||||
---
|
||||
|
||||
## 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 — useful for sites like YouTube and Discord that are throttled or blocked by inspection rather than IP bans.
|
||||
|
||||
```nix
|
||||
zapret = {
|
||||
enable = true;
|
||||
configName = "general(ALT)";
|
||||
|
||||
# Extra domains beyond zapret's built-in list
|
||||
listGeneral = [ "pixiv.net" "pximg.net" ];
|
||||
};
|
||||
```
|
||||
|
||||
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)
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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 |
|
||||
|
||||
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";
|
||||
```
|
||||
Generated
+99
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1775710090,
|
||||
"narHash": "sha256-ar3rofg+awPB8QXDaFJhJ2jJhu+KqN/PRCXeyuXR76E=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "4c1018dae018162ec878d42fec712642d214fdfa",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs",
|
||||
"zapret": "zapret"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"zapret": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"zapret-flowseal": "zapret-flowseal"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1775231936,
|
||||
"narHash": "sha256-jvyi6D2Ps0zicpIcn24tacIymQOyUVY6lr6B5RLQkx8=",
|
||||
"owner": "kartavkun",
|
||||
"repo": "zapret-discord-youtube",
|
||||
"rev": "b3e3f854f8d9cf35ddbcbfa7a03cb0a1334dd7eb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "kartavkun",
|
||||
"repo": "zapret-discord-youtube",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"zapret-flowseal": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1775228068,
|
||||
"narHash": "sha256-LAbCZRwoGxQcgO1nio33NlxBXIdsTQJxHQxu1RWctIA=",
|
||||
"owner": "Flowseal",
|
||||
"repo": "zapret-discord-youtube",
|
||||
"rev": "22a9ca3bc067441789c83bd80c00d38e54be51c4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "Flowseal",
|
||||
"repo": "zapret-discord-youtube",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
description = "NixOS proxy suite — sing-box, zapret, tg-ws-proxy";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
zapret = {
|
||||
url = "github:kartavkun/zapret-discord-youtube";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs =
|
||||
{ self, nixpkgs, zapret }:
|
||||
let
|
||||
systems = [
|
||||
"x86_64-linux"
|
||||
"aarch64-linux"
|
||||
];
|
||||
forAll = nixpkgs.lib.genAttrs systems;
|
||||
pkgsFor = system: import nixpkgs { inherit system; };
|
||||
proxySuiteModule = import ./modules/proxy-suite { inherit zapret; };
|
||||
in
|
||||
{
|
||||
# Main module — bakes in the zapret flake so consumers don't need it as a separate input.
|
||||
nixosModules.default = proxySuiteModule;
|
||||
|
||||
# Re-export zapret standalone for users who want just that.
|
||||
nixosModules.zapret = zapret.nixosModules.default;
|
||||
|
||||
overlays.default = final: prev: {
|
||||
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = final; };
|
||||
};
|
||||
|
||||
packages = forAll (system: {
|
||||
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = pkgsFor system; };
|
||||
});
|
||||
|
||||
checks = forAll (system: import ./nix/checks.nix {
|
||||
inherit system nixpkgs proxySuiteModule;
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
# Build-time sing-box configuration templates.
|
||||
# The proxy outbound(s) are injected at service start time, not here.
|
||||
{ lib, pkgs, cfg, rules }:
|
||||
|
||||
let
|
||||
sb = cfg.singBox;
|
||||
|
||||
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
|
||||
experimental = {
|
||||
clash_api = {
|
||||
external_controller = "127.0.0.1:${toString sb.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 (builtins.elem "category-ru" sb.routing.direct.geosites) {
|
||||
rule_set = [ "geosite-category-ru" ];
|
||||
server = "local";
|
||||
};
|
||||
final = "remote";
|
||||
};
|
||||
|
||||
dnsConfigTun = dnsConfig // {
|
||||
servers = map (
|
||||
s: if s.tag == "local" then s // { detour = "proxy"; } else s
|
||||
) dnsConfig.servers;
|
||||
};
|
||||
|
||||
mkConfig =
|
||||
{
|
||||
enableMixed ? false,
|
||||
enableTProxy ? false,
|
||||
enableTun ? false,
|
||||
useOutboundRoutingMark ? false,
|
||||
}:
|
||||
{
|
||||
log.level = "warn";
|
||||
|
||||
dns = if enableTun then dnsConfigTun else dnsConfig;
|
||||
|
||||
inbounds =
|
||||
lib.optional enableMixed {
|
||||
type = "mixed";
|
||||
tag = "mixed-in";
|
||||
listen = sb.listenAddress;
|
||||
listen_port = sb.port;
|
||||
}
|
||||
++ lib.optional enableTProxy {
|
||||
type = "tproxy";
|
||||
tag = "tproxy-in";
|
||||
listen = "127.0.0.1";
|
||||
listen_port = sb.tproxyPort;
|
||||
}
|
||||
++ 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;
|
||||
stack = "mixed";
|
||||
};
|
||||
|
||||
# proxy outbound(s) are prepended at runtime by the start script
|
||||
outbounds = [
|
||||
(
|
||||
{ type = "direct"; tag = "direct"; }
|
||||
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = sb.proxyMark; }
|
||||
)
|
||||
{ type = "block"; tag = "block"; }
|
||||
];
|
||||
|
||||
route = {
|
||||
default_domain_resolver = "local";
|
||||
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
||||
rules = rules.routingRules;
|
||||
final = if sb.proxyByDefault then "proxy" else "direct";
|
||||
} // lib.optionalAttrs enableTun { auto_detect_interface = true; };
|
||||
}
|
||||
// clashApiBlock;
|
||||
|
||||
tproxyTemplate = mkConfig {
|
||||
enableMixed = true;
|
||||
enableTProxy = true;
|
||||
useOutboundRoutingMark = true;
|
||||
};
|
||||
|
||||
tunTemplate = mkConfig {
|
||||
enableTun = true;
|
||||
};
|
||||
|
||||
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
|
||||
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
|
||||
|
||||
in
|
||||
{
|
||||
inherit tproxyFile tunFile;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# Factory function — receives the zapret flake, returns a NixOS module.
|
||||
# This lets consumers add a single flake input and get everything transitively.
|
||||
{ zapret }:
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
cfg = config.services.proxy-suite;
|
||||
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
|
||||
];
|
||||
|
||||
config = lib.mkIf cfg.enable (lib.mkMerge [
|
||||
(lib.mkIf cfg.singBox.enable (
|
||||
let
|
||||
rules = import ./rules.nix { inherit lib pkgs cfg; };
|
||||
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;
|
||||
}
|
||||
))
|
||||
|
||||
(lib.mkIf cfg.zapret.enable (
|
||||
import ./zapret.nix { inherit lib pkgs cfg; }
|
||||
))
|
||||
|
||||
(lib.mkIf cfg.tgWsProxy.enable (
|
||||
import ./tg-ws-proxy.nix { inherit lib pkgs cfg; }
|
||||
))
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
# TProxy nftables rules
|
||||
{ lib, pkgs, cfg }:
|
||||
|
||||
let
|
||||
sb = cfg.singBox;
|
||||
|
||||
localSubnetLines = lib.concatMapStrings (cidr: ''
|
||||
ip daddr ${cidr} tcp dport != 53 return
|
||||
ip daddr ${cidr} udp dport != 53 return
|
||||
'') sb.tproxy.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
|
||||
}
|
||||
|
||||
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}
|
||||
}
|
||||
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}
|
||||
}
|
||||
}
|
||||
'';
|
||||
|
||||
ip = "${pkgs.iproute2}/bin/ip";
|
||||
nft = "${pkgs.nftables}/bin/nft";
|
||||
|
||||
in
|
||||
{
|
||||
inherit nftablesRulesFile ip nft;
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
# 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;
|
||||
};
|
||||
|
||||
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;
|
||||
};
|
||||
};
|
||||
|
||||
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 is required when singBox.enable = true.
|
||||
'';
|
||||
};
|
||||
|
||||
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 every 3 minutes and auto-switch to the fastest
|
||||
'';
|
||||
};
|
||||
|
||||
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 = {
|
||||
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 = [ "category-ru" ];
|
||||
description = "sing-geosite names to send direct.";
|
||||
};
|
||||
geoips = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ "ru" ];
|
||||
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.";
|
||||
};
|
||||
};
|
||||
|
||||
# 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";
|
||||
|
||||
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.";
|
||||
};
|
||||
|
||||
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.
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
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,128 @@
|
||||
# Routing rules and rule-set definitions for sing-box
|
||||
{ lib, pkgs, cfg }:
|
||||
|
||||
let
|
||||
r = cfg.singBox.routing;
|
||||
sb = cfg.singBox;
|
||||
|
||||
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;
|
||||
outbound = tag;
|
||||
};
|
||||
|
||||
# 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;
|
||||
|
||||
# Collect per-outbound routing attached directly to outbound definitions.
|
||||
perOutboundRules = lib.concatMap (ob:
|
||||
let
|
||||
ro = ob.routing;
|
||||
hasAny = ro.domains != [ ] || ro.ips != [ ] || ro.geosites != [ ] || ro.geoips != [ ];
|
||||
in
|
||||
lib.optional hasAny {
|
||||
outbound = resolveTag ob.tag;
|
||||
inherit (ro) domains ips geosites geoips;
|
||||
}
|
||||
) sb.outbounds;
|
||||
|
||||
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
||||
customRules = perOutboundRules ++ map (rule: rule // { outbound = resolveTag rule.outbound; }) r.rules;
|
||||
|
||||
# Build sing-box routing rule entries from a custom rule record.
|
||||
mkCustomRuleEntries =
|
||||
rule: lib.flatten [
|
||||
(mkDomainRule rule.outbound rule.domains)
|
||||
(mkIPRule rule.outbound rule.ips)
|
||||
(mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites))
|
||||
(mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips))
|
||||
];
|
||||
|
||||
# All geosite names referenced anywhere (for rule-set file definitions).
|
||||
allGeositeNames = lib.unique (
|
||||
r.proxy.geosites
|
||||
++ r.direct.geosites
|
||||
++ lib.concatMap (rule: rule.geosites) customRules
|
||||
);
|
||||
|
||||
# All geoip names referenced anywhere.
|
||||
allGeoIPNames = lib.unique (
|
||||
r.proxy.geoips
|
||||
++ r.direct.geoips
|
||||
++ lib.concatMap (rule: rule.geoips) customRules
|
||||
);
|
||||
|
||||
geositeRuleSets = map (name: {
|
||||
tag = "geosite-${name}";
|
||||
type = "local";
|
||||
format = "binary";
|
||||
path = "${pkgs.sing-geosite}/share/sing-box/rule-set/geosite-${name}.srs";
|
||||
}) allGeositeNames;
|
||||
|
||||
geoIPRuleSets = map (name: {
|
||||
tag = "geoip-${name}";
|
||||
type = "local";
|
||||
format = "binary";
|
||||
path = "${pkgs.sing-geoip}/share/sing-box/rule-set/geoip-${name}.srs";
|
||||
}) allGeoIPNames;
|
||||
|
||||
routingRules = lib.flatten [
|
||||
{
|
||||
network = [ "tcp" "udp" ];
|
||||
port = 53;
|
||||
action = "hijack-dns";
|
||||
}
|
||||
{ action = "sniff"; }
|
||||
|
||||
# Per-outbound and explicit rules come first — they take priority.
|
||||
(lib.concatMap mkCustomRuleEntries customRules)
|
||||
|
||||
# Global proxy lists
|
||||
(mkDomainRule "proxy" r.proxy.domains)
|
||||
(mkIPRule "proxy" r.proxy.ips)
|
||||
|
||||
# Global direct lists
|
||||
(mkDomainRule "direct" r.direct.domains)
|
||||
(mkIPRule "direct" r.direct.ips)
|
||||
(mkRulesetRule "direct" (map (s: "geosite-${s}") r.direct.geosites))
|
||||
(mkRulesetRule "direct" (map (s: "geoip-${s}") r.direct.geoips))
|
||||
|
||||
{ ip_is_private = true; outbound = "direct"; }
|
||||
|
||||
# Global proxy geo lists
|
||||
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
|
||||
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
|
||||
|
||||
# Block
|
||||
(mkDomainRule "block" r.block.domains)
|
||||
(mkIPRule "block" r.block.ips)
|
||||
];
|
||||
|
||||
in
|
||||
{
|
||||
inherit
|
||||
geositeRuleSets
|
||||
geoIPRuleSets
|
||||
routingRules
|
||||
;
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
# 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";
|
||||
|
||||
# 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")
|
||||
'';
|
||||
|
||||
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
|
||||
mkOutboundScript =
|
||||
routingMark:
|
||||
let
|
||||
outboundBlocks =
|
||||
if sb.selection == "first" then
|
||||
# Only the first 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;
|
||||
|
||||
wrapperBlock =
|
||||
if sb.selection == "first" then
|
||||
""
|
||||
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" \
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags,url:"https://www.gstatic.com/generate_204",interval:"3m",tolerance:50}')
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
in
|
||||
outboundBlocks + 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;
|
||||
|
||||
proxyCtl = pkgs.writeShellApplication {
|
||||
name = "proxy-ctl";
|
||||
runtimeInputs = with pkgs; [ curl jq ];
|
||||
text = ''
|
||||
# Embedded at build time from module config
|
||||
CLASH_API="${clashApi}"
|
||||
SELECTION="${selection}"
|
||||
|
||||
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)"
|
||||
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
|
||||
;;
|
||||
|
||||
*)
|
||||
_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 != [ ];
|
||||
message = "proxy-suite: singBox.outbounds must not be empty 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;
|
||||
|
||||
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";
|
||||
};
|
||||
};
|
||||
}
|
||||
// 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";
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Telegram MTProto WebSocket proxy service
|
||||
{ lib, pkgs, cfg }:
|
||||
|
||||
let
|
||||
t = cfg.tgWsProxy;
|
||||
tgPkg = import ../../pkgs/tg-ws-proxy.nix { inherit pkgs; };
|
||||
|
||||
dcArgs = lib.concatMapStrings (id: " --dc-ip=${id}:${t.dcIps.${id}}") (
|
||||
builtins.attrNames t.dcIps
|
||||
);
|
||||
secretArg =
|
||||
if t.secretFile != null then
|
||||
" --secret-file=%d/tg_ws_proxy_secret"
|
||||
else
|
||||
" --secret=${t.secret}";
|
||||
in
|
||||
{
|
||||
systemd.services.proxy-suite-tg-ws-proxy = {
|
||||
description = "Telegram MTProto WebSocket proxy";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${tgPkg}/bin/tg-ws-proxy --port=${toString t.port} --host=${t.host}${secretArg}${dcArgs}";
|
||||
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# zapret DPI bypass configuration + optional CIDR exemption from NFQUEUE
|
||||
{ lib, pkgs, cfg }:
|
||||
|
||||
let
|
||||
z = cfg.zapret;
|
||||
|
||||
iptables = "${pkgs.iptables}/bin/iptables";
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
in
|
||||
{
|
||||
services.zapret-discord-youtube = {
|
||||
enable = true;
|
||||
configName = z.configName;
|
||||
gameFilter = z.gameFilter;
|
||||
listGeneral = z.listGeneral;
|
||||
listExclude = z.listExclude;
|
||||
ipsetAll = z.ipsetAll;
|
||||
ipsetExclude = z.ipsetExclude;
|
||||
};
|
||||
|
||||
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" ];
|
||||
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;
|
||||
};
|
||||
};
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
{
|
||||
system,
|
||||
nixpkgs,
|
||||
proxySuiteModule,
|
||||
}:
|
||||
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
evalProxySuite =
|
||||
modules:
|
||||
import "${nixpkgs}/nixos/lib/eval-config.nix" {
|
||||
inherit system;
|
||||
modules = [ proxySuiteModule ] ++ modules;
|
||||
};
|
||||
forceEval = value: builtins.tryEval (builtins.deepSeq value true);
|
||||
rg = "${pkgs.ripgrep}/bin/rg";
|
||||
|
||||
baseModule = {
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.outbounds = [
|
||||
{
|
||||
tag = "primary";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
minimal = evalProxySuite [ baseModule ];
|
||||
|
||||
tgSecretFile = evalProxySuite [
|
||||
baseModule
|
||||
{
|
||||
services.proxy-suite.tgWsProxy = {
|
||||
enable = true;
|
||||
host = "127.0.0.1";
|
||||
secretFile = "/run/secrets/tg-ws-proxy";
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
duplicateTags = forceEval (
|
||||
(evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.outbounds = [
|
||||
{
|
||||
tag = "dup";
|
||||
url = "http://one.example.com:8080";
|
||||
}
|
||||
{
|
||||
tag = "dup";
|
||||
url = "http://two.example.com:8080";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
]).config.system.build.toplevel.drvPath
|
||||
);
|
||||
|
||||
reservedTag = forceEval (
|
||||
(evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.outbounds = [
|
||||
{
|
||||
tag = "proxy";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
]).config.system.build.toplevel.drvPath
|
||||
);
|
||||
|
||||
unknownRoutingTarget = forceEval (
|
||||
(evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox = {
|
||||
outbounds = [
|
||||
{
|
||||
tag = "primary";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
routing.rules = [
|
||||
{
|
||||
outbound = "missing";
|
||||
domains = [ "example.com" ];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
]).config.system.build.toplevel.drvPath
|
||||
);
|
||||
|
||||
tproxyWithFirewall = evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
networking.firewall.enable = true;
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox = {
|
||||
tproxy.enable = true;
|
||||
outbounds = [
|
||||
{
|
||||
tag = "primary";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
routingOrFixture = evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox = {
|
||||
outbounds = [
|
||||
{
|
||||
tag = "primary";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
routing.rules = [
|
||||
{
|
||||
outbound = "primary";
|
||||
domains = [ "example.com" ];
|
||||
geoips = [ "us" ];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
routingOrRules = (import ../modules/proxy-suite/rules.nix {
|
||||
lib = pkgs.lib;
|
||||
inherit pkgs;
|
||||
cfg = routingOrFixture.config.services.proxy-suite;
|
||||
}).routingRules;
|
||||
|
||||
routingOrDomainRules = builtins.filter (
|
||||
rule: (rule ? domain_suffix) && rule.domain_suffix == [ "example.com" ]
|
||||
) routingOrRules;
|
||||
|
||||
routingOrGeoIPRules = builtins.filter (
|
||||
rule: (rule ? rule_set) && rule.rule_set == [ "geoip-us" ]
|
||||
) routingOrRules;
|
||||
|
||||
validated =
|
||||
builtins.seq (assert minimal.config.services.proxy-suite.singBox.listenAddress == "127.0.0.1"; true) (
|
||||
builtins.seq (assert tgSecretFile.config.services.proxy-suite.tgWsProxy.host == "127.0.0.1"; true) (
|
||||
builtins.seq (
|
||||
assert tgSecretFile.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig.LoadCredential
|
||||
== [ "tg_ws_proxy_secret:/run/secrets/tg-ws-proxy" ];
|
||||
true
|
||||
) (
|
||||
builtins.seq (assert duplicateTags.success == false; true) (
|
||||
builtins.seq (assert reservedTag.success == false; true) (
|
||||
builtins.seq (assert unknownRoutingTarget.success == false; true) (
|
||||
builtins.seq (assert tproxyWithFirewall.config.networking.firewall.enable; true) (
|
||||
builtins.seq (
|
||||
assert builtins.length routingOrDomainRules == 1;
|
||||
true
|
||||
) (
|
||||
builtins.seq (
|
||||
assert builtins.length routingOrGeoIPRules == 1;
|
||||
true
|
||||
) (
|
||||
builtins.seq (
|
||||
assert (builtins.head routingOrDomainRules).outbound == "proxy";
|
||||
true
|
||||
) (
|
||||
assert (builtins.head routingOrGeoIPRules).outbound == "proxy"; true
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
in
|
||||
{
|
||||
proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok");
|
||||
|
||||
build-outbound-parser = pkgs.runCommand "build-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export BUILD_OUTBOUND_SCRIPT=${../scripts/build-outbound.py}
|
||||
python ${../scripts/test-build-outbound.py}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
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"
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{ pkgs }:
|
||||
{
|
||||
tg-ws-proxy = import ./tg-ws-proxy.nix { inherit pkgs; };
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{ pkgs }:
|
||||
|
||||
let
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Flowseal";
|
||||
repo = "tg-ws-proxy";
|
||||
rev = "fe4e0e82344d8e8ca5e54b7752cafa934fb763ab";
|
||||
hash = "sha256-tXDfYE1qFYTAWTu7pse/jcovDmX/F42SCGOzsUBmljs=";
|
||||
};
|
||||
|
||||
pythonEnv = pkgs.python3.withPackages (
|
||||
ps: with ps; [
|
||||
websockets
|
||||
requests
|
||||
cryptography
|
||||
]
|
||||
);
|
||||
in
|
||||
pkgs.writeShellApplication {
|
||||
name = "tg-ws-proxy";
|
||||
runtimeInputs = [ pythonEnv ];
|
||||
text = ''
|
||||
set -euo pipefail
|
||||
|
||||
secret=""
|
||||
script_path="${src}/proxy/tg_ws_proxy.py"
|
||||
args=()
|
||||
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--secret-file=*)
|
||||
secret=$(tr -d '\r\n' < "''${1#--secret-file=}")
|
||||
shift
|
||||
;;
|
||||
--secret-file)
|
||||
secret=$(tr -d '\r\n' < "$2")
|
||||
shift 2
|
||||
;;
|
||||
--secret=*)
|
||||
secret="''${1#--secret=}"
|
||||
shift
|
||||
;;
|
||||
--secret)
|
||||
secret="$2"
|
||||
shift 2
|
||||
;;
|
||||
*)
|
||||
args+=("$1")
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
export PYTHONPATH="${src}"
|
||||
if [ -n "$secret" ]; then
|
||||
export TG_WS_PROXY_SECRET="$secret"
|
||||
fi
|
||||
|
||||
exec python - "$script_path" "''${args[@]}" <<'PY'
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
|
||||
script_path = sys.argv[1]
|
||||
args = sys.argv[2:]
|
||||
secret = os.environ.get("TG_WS_PROXY_SECRET")
|
||||
|
||||
if secret is not None:
|
||||
args.extend(["--secret", secret])
|
||||
|
||||
sys.argv = ["tg_ws_proxy.py", *args]
|
||||
runpy.run_path(script_path, run_name="__main__")
|
||||
PY
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
#!/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
|
||||
"""
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Convert a proxy URL from stdin into a sing-box outbound JSON object."
|
||||
)
|
||||
ap.add_argument("--tag", required=True)
|
||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
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)
|
||||
sys.exit(1)
|
||||
|
||||
if args.routing_mark is not None:
|
||||
ob["routing_mark"] = args.routing_mark
|
||||
|
||||
print(json.dumps(ob))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
def test_vless_reality(self):
|
||||
ob = run_parser(
|
||||
"vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
|
||||
)
|
||||
self.assertEqual(ob["type"], "vless")
|
||||
self.assertEqual(ob["server"], "example.com")
|
||||
self.assertEqual(ob["tls"]["reality"]["public_key"], "pubkey")
|
||||
|
||||
def test_vmess(self):
|
||||
payload = {
|
||||
"add": "vmess.example.com",
|
||||
"port": "443",
|
||||
"id": "00000000-0000-0000-0000-000000000000",
|
||||
"aid": "0",
|
||||
"scy": "auto",
|
||||
"net": "ws",
|
||||
"host": "cdn.example.com",
|
||||
"path": "/ws",
|
||||
"tls": "tls",
|
||||
"sni": "cdn.example.com",
|
||||
}
|
||||
encoded = base64.b64encode(json.dumps(payload).encode()).decode()
|
||||
ob = run_parser(f"vmess://{encoded}")
|
||||
self.assertEqual(ob["type"], "vmess")
|
||||
self.assertEqual(ob["transport"]["type"], "ws")
|
||||
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
|
||||
|
||||
def test_trojan(self):
|
||||
ob = run_parser("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome")
|
||||
self.assertEqual(ob["type"], "trojan")
|
||||
self.assertEqual(ob["password"], "secret")
|
||||
self.assertEqual(ob["tls"]["server_name"], "tls.example.com")
|
||||
|
||||
def test_shadowsocks(self):
|
||||
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")
|
||||
|
||||
def test_hysteria2(self):
|
||||
ob = run_parser(
|
||||
"hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask"
|
||||
)
|
||||
self.assertEqual(ob["type"], "hysteria2")
|
||||
self.assertTrue(ob["tls"]["insecure"])
|
||||
self.assertEqual(ob["obfs"]["password"], "mask")
|
||||
|
||||
def test_tuic(self):
|
||||
ob = run_parser(
|
||||
"tuic://00000000-0000-0000-0000-000000000000:secret@example.com:443?sni=tuic.example.com&alpn=h3,hq-29"
|
||||
)
|
||||
self.assertEqual(ob["type"], "tuic")
|
||||
self.assertEqual(ob["tls"]["alpn"], ["h3", "hq-29"])
|
||||
|
||||
def test_socks5(self):
|
||||
ob = run_parser("socks5://user:pass@example.com:1080")
|
||||
self.assertEqual(ob["type"], "socks")
|
||||
self.assertEqual(ob["version"], "5")
|
||||
self.assertEqual(ob["username"], "user")
|
||||
|
||||
def test_https_proxy(self):
|
||||
ob = run_parser("https://proxy.example.com:8443")
|
||||
self.assertEqual(ob["type"], "http")
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user