basic subscription implementation
This commit is contained in:
7 files changed
+1258
-31
No files matched your search
@@ -4,7 +4,7 @@ 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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -13,12 +13,13 @@ The goal is to replace GUI clients like v2rayN and their ilk – you configure y
|
||||
- **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
|
||||
- **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** – MTProto WebSocket relay for sharing with others or for clients that don't support SOCKS
|
||||
- **Telegram proxy** – local MTProto WebSocket proxy using tg-ws-proxy
|
||||
|
||||
---
|
||||
|
||||
@@ -167,6 +168,92 @@ singBox = {
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
# every 3 minutes 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)
|
||||
};
|
||||
```
|
||||
|
||||
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).
|
||||
|
||||
### 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 = [ "youtube.com" "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.
|
||||
@@ -222,17 +309,21 @@ In `first` selection mode, per-outbound tags are resolved to `"proxy"` automatic
|
||||
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 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
|
||||
@@ -340,13 +431,14 @@ tgWsProxy = {
|
||||
|
||||
## 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 |
|
||||
| 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.
|
||||
|
||||
@@ -408,6 +500,7 @@ Features:
|
||||
- **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
|
||||
|
||||
|
||||
@@ -57,6 +57,43 @@ let
|
||||
// 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 {
|
||||
@@ -182,10 +219,48 @@ in
|
||||
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.
|
||||
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"
|
||||
|
||||
+178
-14
@@ -30,6 +30,8 @@ let
|
||||
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.
|
||||
@@ -67,20 +69,66 @@ let
|
||||
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" then
|
||||
# Only the first outbound, tagged "proxy" so sing-box routes to it.
|
||||
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")
|
||||
@@ -101,7 +149,7 @@ let
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
in
|
||||
outboundBlocks + wrapperBlock;
|
||||
outboundBlocks + subscriptionBlocks + wrapperBlock;
|
||||
|
||||
mkStartScript =
|
||||
{
|
||||
@@ -142,6 +190,50 @@ let
|
||||
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; [
|
||||
@@ -152,6 +244,7 @@ let
|
||||
# Embedded at build time from module config
|
||||
CLASH_API="${clashApi}"
|
||||
SELECTION="${selection}"
|
||||
SUB_TAGS=(${subscriptionTagsList})
|
||||
|
||||
ALL_SERVICES=(
|
||||
proxy-suite-socks
|
||||
@@ -166,13 +259,15 @@ let
|
||||
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 " 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
|
||||
}
|
||||
|
||||
@@ -259,6 +354,38 @@ let
|
||||
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
|
||||
;;
|
||||
@@ -275,8 +402,8 @@ in
|
||||
|
||||
assertions = [
|
||||
{
|
||||
assertion = !sb.enable || sb.outbounds != [ ];
|
||||
message = "proxy-suite: singBox.outbounds must not be empty when singBox.enable = true";
|
||||
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);
|
||||
@@ -315,7 +442,19 @@ in
|
||||
) == 1;
|
||||
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
|
||||
}
|
||||
]) sb.outbounds;
|
||||
]) 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.
|
||||
@@ -328,6 +467,7 @@ in
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = "proxy-suite-socks";
|
||||
StateDirectory = "proxy-suite";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -374,6 +514,30 @@ in
|
||||
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;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
+211
@@ -466,6 +466,132 @@ let
|
||||
}
|
||||
];
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Subscription fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
subscriptionOnlyFixture = evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.subscriptions = [
|
||||
{
|
||||
tag = "community";
|
||||
url = "https://example.com/sub/token";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
subscriptionWithStaticFixture = evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox = {
|
||||
outbounds = [
|
||||
{
|
||||
tag = "own-vps";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
subscriptions = [
|
||||
{
|
||||
tag = "backup";
|
||||
url = "https://example.com/sub/token";
|
||||
}
|
||||
];
|
||||
selection = "urltest";
|
||||
subscriptionUpdateInterval = "6h";
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
# selection=first with subscriptions only – start script must rename first
|
||||
# subscription outbound to "proxy" so routing rules resolve at runtime.
|
||||
subscriptionFirstSelectionFixture = evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox = {
|
||||
subscriptions = [
|
||||
{
|
||||
tag = "community";
|
||||
url = "https://example.com/sub/token";
|
||||
}
|
||||
];
|
||||
selection = "first";
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
subscriptionUrlFileFixture = evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.subscriptions = [
|
||||
{
|
||||
tag = "private";
|
||||
urlFile = "/run/secrets/sub-url";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
# Validation failures
|
||||
subscriptionBothSources = forceEval (
|
||||
(evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.subscriptions = [
|
||||
{
|
||||
tag = "bad";
|
||||
url = "https://example.com/sub/token";
|
||||
urlFile = "/run/secrets/sub-url";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
]).config.system.build.toplevel.drvPath
|
||||
);
|
||||
|
||||
subscriptionNoSources = forceEval (
|
||||
(evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
singBox.subscriptions = [
|
||||
{
|
||||
tag = "bad";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
]).config.system.build.toplevel.drvPath
|
||||
);
|
||||
|
||||
noOutboundsNoSubscriptions = forceEval (
|
||||
(evalProxySuite [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
# neither outbounds nor subscriptions set
|
||||
};
|
||||
}
|
||||
]).config.system.build.toplevel.drvPath
|
||||
);
|
||||
|
||||
blockGeoFixture = evalProxySuite [
|
||||
baseModule
|
||||
{
|
||||
@@ -697,6 +823,82 @@ let
|
||||
".*/[^/]*proxy-suite-tray\\.desktop$";
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: basic config is accepted --
|
||||
(
|
||||
assert subscriptionOnlyFixture.config.services.proxy-suite.singBox.subscriptions != [ ];
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: update service is created when subscriptions are configured --
|
||||
(
|
||||
assert subscriptionOnlyFixture.config.systemd.services ? "proxy-suite-subscription-update";
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: update timer is created when subscriptions are configured --
|
||||
(
|
||||
assert subscriptionOnlyFixture.config.systemd.timers ? "proxy-suite-subscription-update";
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: StateDirectory set on socks service --
|
||||
(
|
||||
assert subscriptionOnlyFixture.config.systemd.services."proxy-suite-socks".serviceConfig.StateDirectory
|
||||
== "proxy-suite";
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: custom update interval flows through to timer --
|
||||
(
|
||||
assert subscriptionWithStaticFixture.config.systemd.timers."proxy-suite-subscription-update".timerConfig.OnUnitActiveSec
|
||||
== "6h";
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: selection=first renames first subscription outbound to "proxy" --
|
||||
(
|
||||
let
|
||||
startScript = subscriptionFirstSelectionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart;
|
||||
scriptText = builtins.readFile startScript;
|
||||
in
|
||||
assert builtins.match ".*proxy.*" scriptText != null;
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: no update service/timer without subscriptions --
|
||||
(
|
||||
assert !(minimal.config.systemd.services ? "proxy-suite-subscription-update");
|
||||
true
|
||||
)
|
||||
(
|
||||
assert !(minimal.config.systemd.timers ? "proxy-suite-subscription-update");
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: urlFile form accepted --
|
||||
(
|
||||
assert subscriptionUrlFileFixture.config.services.proxy-suite.singBox.subscriptions != [ ];
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: both url + urlFile fails --
|
||||
(
|
||||
assert subscriptionBothSources.success == false;
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: neither url nor urlFile fails --
|
||||
(
|
||||
assert subscriptionNoSources.success == false;
|
||||
true
|
||||
)
|
||||
|
||||
# -- subscription: no outbounds + no subscriptions fails --
|
||||
(
|
||||
assert noOutboundsNoSubscriptions.success == false;
|
||||
true
|
||||
)
|
||||
];
|
||||
in
|
||||
{
|
||||
@@ -729,6 +931,15 @@ in
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
fetch-subscription-parser =
|
||||
pkgs.runCommand "fetch-subscription-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||
''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export FETCH_SUBSCRIPTION_SCRIPT=${../scripts/fetch-subscription.py}
|
||||
python ${../scripts/test-fetch-subscription.py}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
no-secrets = pkgs.runCommand "proxy-suite-no-secrets-check" { } ''
|
||||
repo_root=${../.}
|
||||
if ${rg} --pcre2 -n -I -H -S \
|
||||
|
||||
@@ -313,6 +313,11 @@ static void on_restart(GtkWidget *item, gpointer data) {
|
||||
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_open_controls(GtkWidget *item, gpointer data) {
|
||||
(void)item; (void)data;
|
||||
if (!controls_window) {
|
||||
@@ -364,6 +369,12 @@ static void build_controls_window(void) {
|
||||
gtk_box_pack_start(GTK_BOX(box), controls_tun_button, FALSE, FALSE, 0);
|
||||
}
|
||||
|
||||
if (service_exists("proxy-suite-subscription-update")) {
|
||||
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);
|
||||
}
|
||||
|
||||
GtkWidget *restart_button = gtk_button_new_with_label("Restart Services");
|
||||
g_signal_connect(restart_button, "clicked", G_CALLBACK(on_restart), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(box), restart_button, FALSE, FALSE, 0);
|
||||
@@ -411,6 +422,12 @@ static void build_menu(void) {
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item);
|
||||
}
|
||||
|
||||
if (service_exists("proxy-suite-subscription-update")) {
|
||||
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);
|
||||
}
|
||||
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
|
||||
|
||||
GtkWidget *restart_item = gtk_menu_item_new_with_label("Restart Services");
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
#!/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
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
args = ap.parse_args()
|
||||
|
||||
url = sys.stdin.read().strip()
|
||||
if not url:
|
||||
print("error: no URL provided on stdin", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
raw = fetch_raw(url)
|
||||
except Exception as exc:
|
||||
print(f"error: failed to fetch subscription: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
lines = decode_subscription(raw)
|
||||
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark)
|
||||
|
||||
if not outbounds:
|
||||
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(json.dumps(outbounds))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
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(
|
||||
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
|
||||
)
|
||||
HY2_URI = "hy2://secret@hy.example.com:443?sni=hy.example.com"
|
||||
INVALID_URI = "wireguard://example.com:51820"
|
||||
|
||||
|
||||
def _make_b64_payload(*uris: str) -> bytes:
|
||||
text = "\n".join(uris)
|
||||
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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class FetchSubscriptionTests(unittest.TestCase):
|
||||
|
||||
def test_base64_payload_mixed_protocols(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI)
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 3)
|
||||
types = {ob["type"] for ob in obs}
|
||||
self.assertEqual(types, {"vless", "shadowsocks", "hysteria2"})
|
||||
|
||||
def test_plain_text_payload(self):
|
||||
payload = "\n".join([VLESS_URI, SS_URI]).encode()
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 2)
|
||||
|
||||
def test_tag_prefix_applied(self):
|
||||
payload = _make_b64_payload(VLESS_URI)
|
||||
obs = run_fetcher(payload, tag_prefix="mysub")
|
||||
self.assertTrue(obs[0]["tag"].startswith("mysub-"))
|
||||
|
||||
def test_remark_used_in_tag(self):
|
||||
uri_with_remark = VLESS_URI + "#My Server DE"
|
||||
payload = _make_b64_payload(uri_with_remark)
|
||||
obs = run_fetcher(payload, tag_prefix="sub")
|
||||
# Remark should be slugified and appear in tag
|
||||
self.assertIn("My-Server-DE", obs[0]["tag"])
|
||||
|
||||
def test_remark_special_chars_slugified(self):
|
||||
uri_with_remark = VLESS_URI + "#Server @ 🇩🇪 #1"
|
||||
payload = _make_b64_payload(uri_with_remark)
|
||||
obs = run_fetcher(payload, tag_prefix="sub")
|
||||
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):
|
||||
# Two entries with the same remark → distinct tags
|
||||
uri1 = VLESS_URI + "#Server"
|
||||
uri2 = SS_URI + "#Server"
|
||||
payload = _make_b64_payload(uri1, uri2)
|
||||
obs = run_fetcher(payload, tag_prefix="sub")
|
||||
tags = [ob["tag"] for ob in obs]
|
||||
self.assertEqual(len(tags), len(set(tags)), "Tags must be unique")
|
||||
|
||||
def test_invalid_lines_skipped(self):
|
||||
payload = _make_b64_payload(INVALID_URI, VLESS_URI)
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 1)
|
||||
self.assertEqual(obs[0]["type"], "vless")
|
||||
|
||||
def test_invalid_lines_warn_on_stderr(self):
|
||||
# A syntactically invalid URI for a known scheme should warn, not crash.
|
||||
broken_vless = "vless://not-a-valid-vless-url"
|
||||
payload = _make_b64_payload(broken_vless, SS_URI)
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 1)
|
||||
|
||||
def test_routing_mark_applied(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI)
|
||||
obs = run_fetcher(payload, extra_args=["--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)
|
||||
|
||||
def test_index_tag_fallback_when_no_remark(self):
|
||||
# URIs without a remark should get index-based tags
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI)
|
||||
obs = run_fetcher(payload, tag_prefix="sub")
|
||||
for ob in obs:
|
||||
# Tags follow the pattern sub-<index>
|
||||
self.assertRegex(ob["tag"], r"^sub-\d+$")
|
||||
|
||||
def test_empty_lines_ignored(self):
|
||||
text = f"\n\n{VLESS_URI}\n\n{SS_URI}\n\n"
|
||||
payload = base64.b64encode(text.encode())
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 2)
|
||||
|
||||
def test_trailing_whitespace_in_uris(self):
|
||||
text = f"{VLESS_URI} \r\n{SS_URI} \r\n"
|
||||
payload = base64.b64encode(text.encode())
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user