basic subscription implementation

This commit is contained in:
FUFSoB committed 2026-04-12 17:41:27 +05:00
1 parent aa5428fc9b
commit 2fb920d812
7 files changed
+1258 -31

No files matched your search

+76 -1
View File
@@ -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
View File
@@ -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;
};
};
};