another round of refactoring
This commit is contained in:
23 files changed
+1362
-1090
No files matched your search
@@ -8,10 +8,9 @@
|
||||
}:
|
||||
|
||||
let
|
||||
singBoxCfg = cfg.singBox;
|
||||
globalTun = singBoxCfg.tun;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppTun = singBoxCfg.tun.perApp;
|
||||
derived = import ./derived.nix { inherit lib cfg; };
|
||||
inherit (derived) singBoxCfg globalTun globalTproxy clashApiEnabled;
|
||||
perAppTun = derived.perAppRoutingTun;
|
||||
direct = rules.direct;
|
||||
|
||||
mkDnsServer =
|
||||
@@ -43,7 +42,7 @@ let
|
||||
final = if singBoxCfg.proxyByDefault then "remote" else "local";
|
||||
};
|
||||
|
||||
clashApiBlock = lib.optionalAttrs (singBoxCfg.selection != "first") {
|
||||
clashApiBlock = lib.optionalAttrs clashApiEnabled {
|
||||
experimental = {
|
||||
clash_api = {
|
||||
external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||
@@ -64,7 +63,7 @@ let
|
||||
tunStrictRoute ? true,
|
||||
forceLocalDnsViaProxy ? false,
|
||||
useOutboundRoutingMark ? false,
|
||||
enableClashApi ? true,
|
||||
enableClashApi ? clashApiEnabled,
|
||||
}:
|
||||
{
|
||||
log.level = "warn";
|
||||
@@ -130,7 +129,6 @@ let
|
||||
enableMixed = true;
|
||||
enableTProxy = true;
|
||||
useOutboundRoutingMark = true;
|
||||
enableClashApi = true;
|
||||
};
|
||||
|
||||
tunTemplate = mkConfig {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
lib,
|
||||
cfg,
|
||||
}:
|
||||
|
||||
let
|
||||
singBoxCfg = cfg.singBox;
|
||||
perAppRoutingCfg = cfg.perAppRouting;
|
||||
globalTun = singBoxCfg.tun;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppRoutingTun = singBoxCfg.tun.perApp;
|
||||
perAppRoutingTproxy = singBoxCfg.tproxy.perApp;
|
||||
perAppZapretCfg = cfg.zapret.perApp;
|
||||
userControlCfg = cfg.userControl;
|
||||
|
||||
selectionMode = singBoxCfg.selection;
|
||||
builtinTags = [ "proxy" "direct" "block" ];
|
||||
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds;
|
||||
subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions;
|
||||
|
||||
hasStaticOutbounds = singBoxCfg.outbounds != [ ];
|
||||
hasSubscriptions = singBoxCfg.subscriptions != [ ];
|
||||
collapseNamedOutbounds = selectionMode == "first";
|
||||
clashApiEnabled = selectionMode != "first";
|
||||
perAppZapretEnabled = cfg.zapret.enable && perAppZapretCfg.enable;
|
||||
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
|
||||
|
||||
invalidRoutingTargets = lib.unique (
|
||||
map (rule: rule.outbound) (
|
||||
builtins.filter (rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)) singBoxCfg.routing.rules
|
||||
)
|
||||
);
|
||||
in
|
||||
{
|
||||
inherit
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
perAppZapretEnabled
|
||||
userControlCfg
|
||||
userControlEnabled
|
||||
selectionMode
|
||||
builtinTags
|
||||
outboundTags
|
||||
subscriptionTags
|
||||
hasStaticOutbounds
|
||||
hasSubscriptions
|
||||
collapseNamedOutbounds
|
||||
clashApiEnabled
|
||||
invalidRoutingTargets
|
||||
;
|
||||
}
|
||||
@@ -7,8 +7,9 @@
|
||||
}:
|
||||
|
||||
let
|
||||
derived = import ./derived.nix { inherit lib cfg; };
|
||||
r = cfg.singBox.routing;
|
||||
singBoxCfg = cfg.singBox;
|
||||
singBoxCfg = derived.singBoxCfg;
|
||||
zapretCfg = cfg.zapret;
|
||||
|
||||
trim = lib.strings.trim;
|
||||
@@ -98,13 +99,8 @@ let
|
||||
# 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 singBoxCfg.selection == "first" && !builtins.elem tag builtinTags then "proxy" else tag;
|
||||
tag: if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then "proxy" else tag;
|
||||
|
||||
# Collect per-outbound routing attached directly to outbound definitions.
|
||||
perOutboundRules = lib.concatMap (
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
{
|
||||
lib,
|
||||
cfg,
|
||||
singBoxCfg,
|
||||
derived,
|
||||
tgWsProxyCfg,
|
||||
perAppRoutingCfg,
|
||||
perAppRoutingTun,
|
||||
perAppRoutingTproxy,
|
||||
perAppZapretCfg,
|
||||
builtinTags,
|
||||
outboundTags,
|
||||
subscriptionTags,
|
||||
@@ -19,233 +15,284 @@
|
||||
}:
|
||||
|
||||
let
|
||||
globalTun = singBoxCfg.tun;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
assertions = import ./service/assertions-lib.nix { inherit lib; };
|
||||
inherit (assertions)
|
||||
mkAssertion
|
||||
requireEnabled
|
||||
requireAvailable
|
||||
uniqueValues
|
||||
notEqualWhen
|
||||
forbiddenValues
|
||||
exactlyOneOf
|
||||
;
|
||||
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
;
|
||||
|
||||
featureAssertions = [
|
||||
(requireAvailable
|
||||
singBoxCfg.enable
|
||||
(singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ])
|
||||
"proxy-suite: at least one outbound or subscription is required when singBox.enable = true")
|
||||
(uniqueValues
|
||||
singBoxCfg.enable
|
||||
outboundTags
|
||||
"proxy-suite: outbound tags must be unique")
|
||||
(uniqueValues
|
||||
singBoxCfg.enable
|
||||
subscriptionTags
|
||||
"proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes")
|
||||
(mkAssertion
|
||||
(!singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags)
|
||||
"proxy-suite: outbound tags must not use reserved names: proxy, direct, block")
|
||||
(mkAssertion
|
||||
(!singBoxCfg.enable || invalidRoutingTargets == [ ])
|
||||
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}")
|
||||
(requireEnabled globalTun.enable singBoxCfg.enable "proxy-suite: singBox.tun.enable requires singBox.enable = true")
|
||||
(requireEnabled globalTproxy.enable singBoxCfg.enable "proxy-suite: singBox.tproxy.enable requires singBox.enable = true")
|
||||
(requireEnabled globalTun.autostart globalTun.enable "proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true")
|
||||
(requireEnabled globalTproxy.autostart globalTproxy.enable "proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true")
|
||||
(mkAssertion
|
||||
(! (globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart))
|
||||
"proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time")
|
||||
];
|
||||
|
||||
perAppRoutingAssertions = [
|
||||
(requireAvailable
|
||||
(perAppRoutingCfg.profiles != [ ])
|
||||
perAppRoutingCfg.enable
|
||||
"proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true")
|
||||
(requireEnabled
|
||||
perAppRoutingCfg.proxychains.enable
|
||||
perAppRoutingCfg.enable
|
||||
"proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true")
|
||||
(requireEnabled
|
||||
perAppRoutingCfg.proxychains.enable
|
||||
singBoxCfg.enable
|
||||
"proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true")
|
||||
(uniqueValues
|
||||
true
|
||||
effectivePerAppRoutingProfileNames
|
||||
"proxy-suite: perAppRouting profile names must be unique")
|
||||
(requireAvailable
|
||||
hasProxychainsProfiles
|
||||
perAppRoutingCfg.proxychains.enable
|
||||
"proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true")
|
||||
(requireAvailable
|
||||
hasProxychainsProfiles
|
||||
singBoxCfg.enable
|
||||
"proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true")
|
||||
(requireEnabled
|
||||
perAppRoutingTun.enable
|
||||
perAppRoutingCfg.enable
|
||||
"proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true")
|
||||
(requireEnabled
|
||||
perAppRoutingTun.enable
|
||||
singBoxCfg.enable
|
||||
"proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true")
|
||||
(requireAvailable
|
||||
hasTunProfiles
|
||||
perAppRoutingTun.enable
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true")
|
||||
(requireAvailable
|
||||
hasTunProfiles
|
||||
singBoxCfg.enable
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true")
|
||||
(requireEnabled
|
||||
perAppRoutingTproxy.enable
|
||||
perAppRoutingCfg.enable
|
||||
"proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true")
|
||||
(requireEnabled
|
||||
perAppRoutingTproxy.enable
|
||||
singBoxCfg.enable
|
||||
"proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true")
|
||||
(requireAvailable
|
||||
hasTproxyProfiles
|
||||
perAppRoutingTproxy.enable
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true")
|
||||
(requireAvailable
|
||||
hasTproxyProfiles
|
||||
singBoxCfg.enable
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true")
|
||||
(requireEnabled
|
||||
perAppZapretCfg.enable
|
||||
perAppRoutingCfg.enable
|
||||
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true")
|
||||
(requireEnabled
|
||||
perAppZapretCfg.enable
|
||||
cfg.zapret.enable
|
||||
"proxy-suite: zapret.perApp.enable requires zapret.enable = true")
|
||||
(requireAvailable
|
||||
hasZapretProfiles
|
||||
(perAppZapretCfg.enable && cfg.zapret.enable)
|
||||
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true and zapret.enable = true")
|
||||
];
|
||||
|
||||
collisionAssertions = map (
|
||||
item:
|
||||
notEqualWhen item.condition item.left item.right item.message
|
||||
) [
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = globalTproxy.fwmark;
|
||||
message =
|
||||
"proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message =
|
||||
"proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = globalTproxy.routeTable;
|
||||
message =
|
||||
"proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.routeTable;
|
||||
right = globalTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.routeTable must differ from singBox.tproxy.routeTable";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = perAppRoutingTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and singBox.tproxy.perApp.fwmark must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = perAppRoutingTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tun.perApp.routeTable and singBox.tproxy.perApp.routeTable must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
left = perAppZapretCfg.filterMark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
left = perAppZapretCfg.filterMark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
];
|
||||
|
||||
forbiddenValueAssertions = map (
|
||||
item:
|
||||
forbiddenValues item.condition item.value item.disallowed item.message
|
||||
) [
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = perAppZapretCfg.filterMark;
|
||||
disallowed = [ 536870912 1073741824 ];
|
||||
message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = globalTproxy.fwmark;
|
||||
disallowed = [ 67108864 134217728 ];
|
||||
message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = globalTproxy.proxyMark;
|
||||
disallowed = [ 67108864 134217728 ];
|
||||
message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||
value = perAppRoutingTun.fwmark;
|
||||
disallowed = [ 67108864 134217728 ];
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
|
||||
value = perAppRoutingTproxy.fwmark;
|
||||
disallowed = [ 67108864 134217728 ];
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = perAppZapretCfg.filterMark;
|
||||
disallowed = [ 67108864 134217728 ];
|
||||
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
];
|
||||
|
||||
secretAssertions = [
|
||||
(exactlyOneOf
|
||||
tgWsProxyCfg.enable
|
||||
[
|
||||
tgWsProxyCfg.secret
|
||||
tgWsProxyCfg.secretFile
|
||||
]
|
||||
"proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
|
||||
];
|
||||
|
||||
outboundAssertions = lib.concatMap (ob: [
|
||||
(exactlyOneOf
|
||||
singBoxCfg.enable
|
||||
[
|
||||
ob.urlFile
|
||||
ob.url
|
||||
ob.json
|
||||
]
|
||||
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json")
|
||||
]) singBoxCfg.outbounds;
|
||||
|
||||
subscriptionAssertions = lib.concatMap (sub: [
|
||||
(exactlyOneOf
|
||||
singBoxCfg.enable
|
||||
[
|
||||
sub.urlFile
|
||||
sub.url
|
||||
]
|
||||
"proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
|
||||
]) singBoxCfg.subscriptions;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = !singBoxCfg.enable || (singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]);
|
||||
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !singBoxCfg.enable || builtins.length outboundTags == builtins.length (lib.unique outboundTags);
|
||||
message = "proxy-suite: outbound tags must be unique";
|
||||
}
|
||||
{
|
||||
assertion = !singBoxCfg.enable || builtins.length subscriptionTags == builtins.length (lib.unique subscriptionTags);
|
||||
message = "proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes";
|
||||
}
|
||||
{
|
||||
assertion = !singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags;
|
||||
message = "proxy-suite: outbound tags must not use reserved names: proxy, direct, block";
|
||||
}
|
||||
{
|
||||
assertion = !singBoxCfg.enable || invalidRoutingTargets == [ ];
|
||||
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
|
||||
}
|
||||
{
|
||||
assertion = !globalTun.enable || singBoxCfg.enable;
|
||||
message = "proxy-suite: singBox.tun.enable requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !globalTproxy.enable || singBoxCfg.enable;
|
||||
message = "proxy-suite: singBox.tproxy.enable requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !globalTun.autostart || globalTun.enable;
|
||||
message = "proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !globalTproxy.autostart || globalTproxy.enable;
|
||||
message = "proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart);
|
||||
message =
|
||||
"proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
|
||||
}
|
||||
{
|
||||
assertion = perAppRoutingCfg.enable || perAppRoutingCfg.profiles == [ ];
|
||||
message = "proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppRoutingCfg.proxychains.enable || perAppRoutingCfg.enable;
|
||||
message = "proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppRoutingCfg.proxychains.enable || singBoxCfg.enable;
|
||||
message = "proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = builtins.length effectivePerAppRoutingProfileNames == builtins.length (lib.unique effectivePerAppRoutingProfileNames);
|
||||
message = "proxy-suite: perAppRouting profile names must be unique";
|
||||
}
|
||||
{
|
||||
assertion = !hasProxychainsProfiles || perAppRoutingCfg.proxychains.enable;
|
||||
message = "proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !hasProxychainsProfiles || singBoxCfg.enable;
|
||||
message = "proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppRoutingTun.enable || perAppRoutingCfg.enable;
|
||||
message = "proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppRoutingTun.enable || singBoxCfg.enable;
|
||||
message = "proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !(hasTunProfiles && !perAppRoutingTun.enable);
|
||||
message = "proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !hasTunProfiles || singBoxCfg.enable;
|
||||
message = "proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppRoutingTproxy.enable || perAppRoutingCfg.enable;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppRoutingTproxy.enable || singBoxCfg.enable;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !(hasTproxyProfiles && !perAppRoutingTproxy.enable);
|
||||
message = "proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !hasTproxyProfiles || singBoxCfg.enable;
|
||||
message = "proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppZapretCfg.enable || perAppRoutingCfg.enable;
|
||||
message = "proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !perAppZapretCfg.enable || cfg.zapret.enable;
|
||||
message = "proxy-suite: zapret.perApp.enable requires zapret.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !(hasZapretProfiles && (!perAppZapretCfg.enable || !cfg.zapret.enable));
|
||||
message = "proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true and zapret.enable = true";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && globalTproxy.enable && perAppRoutingTun.fwmark == globalTproxy.fwmark);
|
||||
message =
|
||||
"proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && globalTproxy.enable && perAppRoutingTun.fwmark == globalTproxy.proxyMark);
|
||||
message =
|
||||
"proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && globalTproxy.enable && perAppRoutingTun.routeTable == globalTproxy.routeTable);
|
||||
message =
|
||||
"proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTproxy.enable && perAppRoutingTproxy.fwmark == globalTproxy.fwmark);
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTproxy.enable && perAppRoutingTproxy.fwmark == globalTproxy.proxyMark);
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTproxy.enable && perAppRoutingTproxy.routeTable == globalTproxy.routeTable);
|
||||
message = "proxy-suite: singBox.tproxy.perApp.routeTable must differ from singBox.tproxy.routeTable";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && perAppRoutingTproxy.enable && perAppRoutingTun.fwmark == perAppRoutingTproxy.fwmark);
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and singBox.tproxy.perApp.fwmark must differ";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && perAppRoutingTproxy.enable && perAppRoutingTun.routeTable == perAppRoutingTproxy.routeTable);
|
||||
message = "proxy-suite: singBox.tun.perApp.routeTable and singBox.tproxy.perApp.routeTable must differ";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppZapretCfg.enable && perAppZapretCfg.filterMark == globalTproxy.fwmark);
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppZapretCfg.enable && perAppZapretCfg.filterMark == globalTproxy.proxyMark);
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && perAppZapretCfg.enable && perAppRoutingTun.fwmark == perAppZapretCfg.filterMark);
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTproxy.enable && perAppZapretCfg.enable && perAppRoutingTproxy.fwmark == perAppZapretCfg.filterMark);
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppZapretCfg.enable && builtins.elem perAppZapretCfg.filterMark [ 536870912 1073741824 ]);
|
||||
message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppZapretCfg.enable && builtins.elem globalTproxy.fwmark [ 67108864 134217728 ]);
|
||||
message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppZapretCfg.enable && builtins.elem globalTproxy.proxyMark [ 67108864 134217728 ]);
|
||||
message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTun.enable && perAppZapretCfg.enable && builtins.elem perAppRoutingTun.fwmark [ 67108864 134217728 ]);
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppRoutingTproxy.enable && perAppZapretCfg.enable && builtins.elem perAppRoutingTproxy.fwmark [ 67108864 134217728 ]);
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
assertion = !(perAppZapretCfg.enable && builtins.elem perAppZapretCfg.filterMark [ 67108864 134217728 ]);
|
||||
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
assertion =
|
||||
!tgWsProxyCfg.enable
|
||||
||
|
||||
builtins.length (
|
||||
builtins.filter (x: x != null) [
|
||||
tgWsProxyCfg.secret
|
||||
tgWsProxyCfg.secretFile
|
||||
]
|
||||
) == 1;
|
||||
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
|
||||
}
|
||||
]
|
||||
++ lib.concatMap (ob: [
|
||||
{
|
||||
assertion =
|
||||
!singBoxCfg.enable
|
||||
||
|
||||
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";
|
||||
}
|
||||
]) singBoxCfg.outbounds
|
||||
++ lib.concatMap (sub: [
|
||||
{
|
||||
assertion =
|
||||
!singBoxCfg.enable
|
||||
||
|
||||
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";
|
||||
}
|
||||
]) singBoxCfg.subscriptions
|
||||
featureAssertions
|
||||
++ perAppRoutingAssertions
|
||||
++ collisionAssertions
|
||||
++ forbiddenValueAssertions
|
||||
++ secretAssertions
|
||||
++ outboundAssertions
|
||||
++ subscriptionAssertions
|
||||
@@ -0,0 +1,23 @@
|
||||
{ lib }:
|
||||
|
||||
rec {
|
||||
mkAssertion = assertion: message: { inherit assertion message; };
|
||||
|
||||
requireEnabled = featureEnabled: dependencyEnabled: message:
|
||||
mkAssertion (!featureEnabled || dependencyEnabled) message;
|
||||
|
||||
requireAvailable = featureUsed: dependencyEnabled: message:
|
||||
mkAssertion (!featureUsed || dependencyEnabled) message;
|
||||
|
||||
uniqueValues = condition: values: message:
|
||||
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
|
||||
|
||||
notEqualWhen = condition: left: right: message:
|
||||
mkAssertion (!(condition && left == right)) message;
|
||||
|
||||
forbiddenValues = condition: value: disallowed: message:
|
||||
mkAssertion (!(condition && builtins.elem value disallowed)) message;
|
||||
|
||||
exactlyOneOf = condition: values: message:
|
||||
mkAssertion (!condition || builtins.length (builtins.filter (value: value != null) values) == 1) message;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
}:
|
||||
|
||||
let
|
||||
mkOptionalTopLevel =
|
||||
{
|
||||
description,
|
||||
after ? [ ],
|
||||
wantedBy ? [ ],
|
||||
wants ? [ ],
|
||||
requires ? [ ],
|
||||
conflicts ? [ ],
|
||||
preStart ? null,
|
||||
}:
|
||||
{
|
||||
inherit description after wantedBy wants requires conflicts;
|
||||
}
|
||||
// lib.optionalAttrs (preStart != null) { inherit preStart; };
|
||||
in
|
||||
rec {
|
||||
mkNamedUnits =
|
||||
entries:
|
||||
lib.listToAttrs (
|
||||
map (entry: lib.nameValuePair entry.name entry.value) (builtins.filter (entry: entry.enable) entries)
|
||||
);
|
||||
|
||||
mkRestartingService =
|
||||
{
|
||||
description,
|
||||
execStart,
|
||||
runtimeDirectory,
|
||||
stateDirectory ? null,
|
||||
after ? [ ],
|
||||
wantedBy ? [ ],
|
||||
wants ? [ ],
|
||||
requires ? [ ],
|
||||
conflicts ? [ ],
|
||||
execStartPost ? null,
|
||||
execStopPost ? null,
|
||||
extraServiceConfig ? { },
|
||||
preStart ? null,
|
||||
}:
|
||||
(mkOptionalTopLevel {
|
||||
inherit
|
||||
description
|
||||
after
|
||||
wantedBy
|
||||
wants
|
||||
requires
|
||||
conflicts
|
||||
preStart
|
||||
;
|
||||
})
|
||||
// {
|
||||
serviceConfig =
|
||||
{
|
||||
ExecStart = execStart;
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = runtimeDirectory;
|
||||
}
|
||||
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
|
||||
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
|
||||
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
|
||||
// extraServiceConfig;
|
||||
};
|
||||
|
||||
mkOneshotService =
|
||||
{
|
||||
description,
|
||||
execStart,
|
||||
execStop ? null,
|
||||
execStartPre ? null,
|
||||
execStartPost ? null,
|
||||
execStopPost ? null,
|
||||
runtimeDirectory ? null,
|
||||
stateDirectory ? null,
|
||||
after ? [ ],
|
||||
wantedBy ? [ ],
|
||||
wants ? [ ],
|
||||
requires ? [ ],
|
||||
conflicts ? [ ],
|
||||
extraServiceConfig ? { },
|
||||
preStart ? null,
|
||||
}:
|
||||
(mkOptionalTopLevel {
|
||||
inherit
|
||||
description
|
||||
after
|
||||
wantedBy
|
||||
wants
|
||||
requires
|
||||
conflicts
|
||||
preStart
|
||||
;
|
||||
})
|
||||
// {
|
||||
serviceConfig =
|
||||
{
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = execStart;
|
||||
}
|
||||
// lib.optionalAttrs (execStop != null) { ExecStop = execStop; }
|
||||
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
|
||||
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
|
||||
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
|
||||
// lib.optionalAttrs (runtimeDirectory != null) { RuntimeDirectory = runtimeDirectory; }
|
||||
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
|
||||
// extraServiceConfig;
|
||||
};
|
||||
|
||||
mkUserRuleService =
|
||||
{
|
||||
description,
|
||||
backendService,
|
||||
execStart,
|
||||
execStop,
|
||||
}:
|
||||
mkOneshotService {
|
||||
inherit description execStart execStop;
|
||||
requires = [ "${backendService}.service" ];
|
||||
after = [ "${backendService}.service" ];
|
||||
};
|
||||
|
||||
mkAnchorService =
|
||||
sliceName: description:
|
||||
mkOneshotService {
|
||||
inherit description;
|
||||
execStart = "${pkgs.coreutils}/bin/true";
|
||||
execStop = "${pkgs.coreutils}/bin/true";
|
||||
extraServiceConfig.Slice = sliceName;
|
||||
};
|
||||
}
|
||||
@@ -15,23 +15,24 @@
|
||||
}:
|
||||
|
||||
let
|
||||
singBoxCfg = cfg.singBox;
|
||||
perAppRoutingCfg = cfg.perAppRouting;
|
||||
globalTun = singBoxCfg.tun;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppRoutingTun = singBoxCfg.tun.perApp;
|
||||
perAppRoutingTproxy = singBoxCfg.tproxy.perApp;
|
||||
perAppZapretCfg = cfg.zapret.perApp;
|
||||
userControlCfg = cfg.userControl;
|
||||
|
||||
builtinTags = [ "proxy" "direct" "block" ];
|
||||
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds;
|
||||
subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions;
|
||||
invalidRoutingTargets = lib.unique (
|
||||
map (rule: rule.outbound) (
|
||||
builtins.filter (rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)) singBoxCfg.routing.rules
|
||||
)
|
||||
);
|
||||
derived = import ../derived.nix { inherit lib cfg; };
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
userControlCfg
|
||||
selectionMode
|
||||
builtinTags
|
||||
outboundTags
|
||||
subscriptionTags
|
||||
invalidRoutingTargets
|
||||
collapseNamedOutbounds
|
||||
hasSubscriptions
|
||||
;
|
||||
|
||||
# Tool paths – defined once here and passed into sub-modules as needed.
|
||||
jq = "${pkgs.jq}/bin/jq";
|
||||
@@ -54,7 +55,7 @@ let
|
||||
};
|
||||
|
||||
scripts = import ./scripts.nix {
|
||||
inherit lib pkgs singBoxCfg perAppRoutingTun;
|
||||
inherit lib pkgs singBoxCfg perAppRoutingTun selectionMode collapseNamedOutbounds hasSubscriptions;
|
||||
inherit jq python3 singBox parserScriptsPythonPath buildOutboundPy fetchSubscriptionPy;
|
||||
inherit tproxyFile tunFile perAppTunFile;
|
||||
};
|
||||
@@ -68,7 +69,15 @@ let
|
||||
};
|
||||
|
||||
control = import ./control.nix {
|
||||
inherit packages singBoxCfg perAppRoutingCfg perAppRoutingTun perAppRoutingTproxy perAppZapretCfg;
|
||||
inherit
|
||||
packages
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
selectionMode
|
||||
;
|
||||
zapretEnabled = cfg.zapret.enable;
|
||||
inherit (scripts) subscriptionTagsFile;
|
||||
inherit (perAppRouting)
|
||||
@@ -80,6 +89,7 @@ let
|
||||
in
|
||||
{
|
||||
inherit
|
||||
derived
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
perAppRoutingTun,
|
||||
perAppRoutingTproxy,
|
||||
perAppZapretCfg,
|
||||
selectionMode,
|
||||
zapretEnabled,
|
||||
subscriptionTagsFile,
|
||||
perAppRoutingProfilesFile,
|
||||
@@ -15,7 +16,7 @@
|
||||
{
|
||||
proxyCtl = packages.mkProxyCtl {
|
||||
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||
selection = singBoxCfg.selection;
|
||||
selection = selectionMode;
|
||||
inherit
|
||||
subscriptionTagsFile
|
||||
perAppRoutingProfilesFile
|
||||
|
||||
@@ -34,7 +34,24 @@ let
|
||||
;
|
||||
};
|
||||
|
||||
builders = import ./builders.nix { inherit lib pkgs; };
|
||||
inherit (builders)
|
||||
mkNamedUnits
|
||||
mkRestartingService
|
||||
mkOneshotService
|
||||
mkUserRuleService
|
||||
mkAnchorService
|
||||
;
|
||||
|
||||
inherit (context)
|
||||
derived
|
||||
polkit
|
||||
scripts
|
||||
perAppRouting
|
||||
control
|
||||
;
|
||||
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
@@ -43,30 +60,209 @@ let
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
userControlCfg
|
||||
builtinTags
|
||||
userControlEnabled
|
||||
perAppZapretEnabled
|
||||
hasSubscriptions
|
||||
outboundTags
|
||||
subscriptionTags
|
||||
invalidRoutingTargets
|
||||
polkit
|
||||
scripts
|
||||
perAppRouting
|
||||
control
|
||||
builtinTags
|
||||
;
|
||||
|
||||
serviceNames = {
|
||||
socks = "proxy-suite-socks";
|
||||
tproxy = "proxy-suite-tproxy";
|
||||
tun = "proxy-suite-tun";
|
||||
perAppTun = "proxy-suite-per-app-tun";
|
||||
perAppTproxy = "proxy-suite-per-app-tproxy";
|
||||
perAppZapret = "proxy-suite-per-app-zapret";
|
||||
subscriptionUpdate = "proxy-suite-subscription-update";
|
||||
};
|
||||
|
||||
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
${nft} -f ${nftablesRulesFile}
|
||||
${ip} route add local default dev lo table ${toString globalTproxy.routeTable}
|
||||
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
|
||||
'';
|
||||
|
||||
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
systemServiceEntries = [
|
||||
{
|
||||
enable = singBoxCfg.enable;
|
||||
name = serviceNames.socks;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box proxy client (SOCKS + TProxy-ready)";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = scripts.startSocks;
|
||||
runtimeDirectory = serviceNames.socks;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && globalTproxy.enable;
|
||||
name = serviceNames.tproxy;
|
||||
value = mkOneshotService {
|
||||
description = "sing-box TProxy – nftables rules and policy routing";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
];
|
||||
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
|
||||
requires = [ "${serviceNames.socks}.service" ];
|
||||
conflicts = [
|
||||
"${serviceNames.tun}.service"
|
||||
"${serviceNames.perAppTproxy}.service"
|
||||
];
|
||||
execStart = tproxyUpScript;
|
||||
execStop = tproxyDownScript;
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && globalTun.enable;
|
||||
name = serviceNames.tun;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box TUN proxy client";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
|
||||
conflicts = [ "${serviceNames.tproxy}.service" ];
|
||||
execStart = scripts.startTun;
|
||||
runtimeDirectory = serviceNames.tun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTun.enable;
|
||||
name = serviceNames.perAppTun;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box per-app-routing TUN backend";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
execStart = scripts.startPerAppTun;
|
||||
execStartPost = perAppRouting.perAppTunUpScript;
|
||||
execStopPost = perAppRouting.perAppTunDownScript;
|
||||
runtimeDirectory = serviceNames.perAppTun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTun.enable;
|
||||
name = "${serviceNames.perAppTun}-user@";
|
||||
value = mkUserRuleService {
|
||||
description = "Enable proxy-suite app TUN marking for user %i";
|
||||
backendService = serviceNames.perAppTun;
|
||||
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
|
||||
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTproxy.enable;
|
||||
name = serviceNames.perAppTproxy;
|
||||
value = mkOneshotService {
|
||||
description = "proxy-suite per-app-routing TProxy backend";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
];
|
||||
requires = [ "${serviceNames.socks}.service" ];
|
||||
conflicts = [
|
||||
"${serviceNames.tproxy}.service"
|
||||
"${serviceNames.tun}.service"
|
||||
];
|
||||
execStart = perAppRouting.perAppTproxyUpScript;
|
||||
execStop = perAppRouting.perAppTproxyDownScript;
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTproxy.enable;
|
||||
name = "${serviceNames.perAppTproxy}-user@";
|
||||
value = mkUserRuleService {
|
||||
description = "Enable proxy-suite app TProxy marking for user %i";
|
||||
backendService = serviceNames.perAppTproxy;
|
||||
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
|
||||
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = perAppZapretEnabled;
|
||||
name = "${serviceNames.perAppZapret}-user@";
|
||||
value = mkUserRuleService {
|
||||
description = "Enable proxy-suite app zapret marking for user %i";
|
||||
backendService = serviceNames.perAppZapret;
|
||||
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
|
||||
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && hasSubscriptions;
|
||||
name = serviceNames.subscriptionUpdate;
|
||||
value = mkOneshotService {
|
||||
description = "Refresh proxy-suite subscription caches";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
execStart = scripts.subscriptionUpdateScript;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
userServiceEntries = [
|
||||
{
|
||||
enable = perAppRoutingTun.enable;
|
||||
name = "${serviceNames.perAppTun}-anchor";
|
||||
value =
|
||||
mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
|
||||
}
|
||||
{
|
||||
enable = perAppRoutingTproxy.enable;
|
||||
name = "${serviceNames.perAppTproxy}-anchor";
|
||||
value =
|
||||
mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
|
||||
}
|
||||
{
|
||||
enable = perAppZapretEnabled;
|
||||
name = "${serviceNames.perAppZapret}-anchor";
|
||||
value =
|
||||
mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
|
||||
}
|
||||
];
|
||||
|
||||
timerEntries = [
|
||||
{
|
||||
enable = singBoxCfg.enable && hasSubscriptions;
|
||||
name = serviceNames.subscriptionUpdate;
|
||||
value = {
|
||||
description = "Periodic proxy-suite subscription refresh";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnBootSec = "5m";
|
||||
OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval;
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
in
|
||||
{
|
||||
environment.systemPackages = [ control.proxyCtl ];
|
||||
|
||||
# nftables must be on for TProxy to work.
|
||||
networking.nftables.enable = lib.mkIf (
|
||||
globalTproxy.enable || perAppRoutingTun.enable || perAppRoutingTproxy.enable || perAppZapretCfg.enable
|
||||
globalTproxy.enable || perAppRoutingTun.enable || perAppRoutingTproxy.enable || perAppZapretEnabled
|
||||
) (lib.mkDefault true);
|
||||
|
||||
users.groups = lib.mkIf (cfg.enable && polkit.userControlEnabled) {
|
||||
users.groups = lib.mkIf (cfg.enable && userControlEnabled) {
|
||||
"${userControlCfg.group}" = { };
|
||||
};
|
||||
|
||||
security.polkit.enable = lib.mkIf (cfg.enable && polkit.userControlEnabled) true;
|
||||
security.polkit.extraConfig = lib.mkIf (cfg.enable && polkit.userControlEnabled) (lib.mkAfter ''
|
||||
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
|
||||
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (lib.mkAfter ''
|
||||
polkit.addRule(function(action, subject) {
|
||||
if (!subject.isInGroup("${userControlCfg.group}")) {
|
||||
return null;
|
||||
@@ -83,24 +279,10 @@ in
|
||||
});
|
||||
'');
|
||||
|
||||
systemd.user.services =
|
||||
lib.optionalAttrs perAppRoutingTun.enable {
|
||||
proxy-suite-per-app-tun-anchor =
|
||||
perAppRouting.mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
|
||||
}
|
||||
// lib.optionalAttrs perAppRoutingTproxy.enable {
|
||||
proxy-suite-per-app-tproxy-anchor =
|
||||
perAppRouting.mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
|
||||
}
|
||||
// lib.optionalAttrs (perAppZapretCfg.enable && cfg.zapret.enable) {
|
||||
proxy-suite-per-app-zapret-anchor =
|
||||
perAppRouting.mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
|
||||
};
|
||||
systemd.user.services = mkNamedUnits userServiceEntries;
|
||||
|
||||
assertions = import ../service-assertions.nix {
|
||||
inherit lib cfg;
|
||||
inherit singBoxCfg perAppRoutingCfg perAppRoutingTun perAppRoutingTproxy;
|
||||
perAppZapretCfg = perAppZapretCfg;
|
||||
inherit lib cfg derived;
|
||||
tgWsProxyCfg = cfg.tgWsProxy;
|
||||
inherit builtinTags outboundTags subscriptionTags invalidRoutingTargets;
|
||||
inherit (perAppRouting)
|
||||
@@ -112,162 +294,7 @@ in
|
||||
;
|
||||
};
|
||||
|
||||
systemd.services = {
|
||||
}
|
||||
// lib.optionalAttrs singBoxCfg.enable {
|
||||
proxy-suite-socks = {
|
||||
description = "sing-box proxy client (SOCKS + TProxy-ready)";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${scripts.startSocks}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = "proxy-suite-socks";
|
||||
StateDirectory = "proxy-suite";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (singBoxCfg.enable && globalTproxy.enable) {
|
||||
proxy-suite-tproxy = {
|
||||
description = "sing-box TProxy – nftables rules and policy routing";
|
||||
after = [
|
||||
"network.target"
|
||||
"proxy-suite-socks.service"
|
||||
];
|
||||
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
|
||||
requires = [ "proxy-suite-socks.service" ];
|
||||
conflicts = [
|
||||
"proxy-suite-tun.service"
|
||||
"proxy-suite-per-app-tproxy.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 globalTproxy.routeTable}
|
||||
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.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 globalTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (singBoxCfg.enable && globalTun.enable) {
|
||||
proxy-suite-tun = {
|
||||
description = "sing-box TUN proxy client";
|
||||
after = [ "network-online.target" ];
|
||||
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
conflicts = [ "proxy-suite-tproxy.service" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${scripts.startTun}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = "proxy-suite-tun";
|
||||
StateDirectory = "proxy-suite";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (singBoxCfg.enable && perAppRoutingTun.enable) {
|
||||
proxy-suite-per-app-tun = {
|
||||
description = "sing-box per-app-routing TUN backend";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${scripts.startPerAppTun}";
|
||||
ExecStartPost = "${perAppRouting.perAppTunUpScript}";
|
||||
ExecStopPost = "${perAppRouting.perAppTunDownScript}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
RuntimeDirectory = "proxy-suite-per-app-tun";
|
||||
StateDirectory = "proxy-suite";
|
||||
};
|
||||
};
|
||||
systemd.services = mkNamedUnits systemServiceEntries;
|
||||
|
||||
"proxy-suite-per-app-tun-user@" = {
|
||||
description = "Enable proxy-suite app TUN marking for user %i";
|
||||
requires = [ "proxy-suite-per-app-tun.service" ];
|
||||
after = [ "proxy-suite-per-app-tun.service" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = "${perAppRouting.perAppTunUserRuleStart} %i";
|
||||
ExecStop = "${perAppRouting.perAppTunUserRuleStop} %i";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (singBoxCfg.enable && perAppRoutingTproxy.enable) {
|
||||
proxy-suite-per-app-tproxy = {
|
||||
description = "proxy-suite per-app-routing TProxy backend";
|
||||
after = [
|
||||
"network.target"
|
||||
"proxy-suite-socks.service"
|
||||
];
|
||||
requires = [ "proxy-suite-socks.service" ];
|
||||
conflicts = [
|
||||
"proxy-suite-tproxy.service"
|
||||
"proxy-suite-tun.service"
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = "${perAppRouting.perAppTproxyUpScript}";
|
||||
ExecStop = "${perAppRouting.perAppTproxyDownScript}";
|
||||
};
|
||||
};
|
||||
|
||||
"proxy-suite-per-app-tproxy-user@" = {
|
||||
description = "Enable proxy-suite app TProxy marking for user %i";
|
||||
requires = [ "proxy-suite-per-app-tproxy.service" ];
|
||||
after = [ "proxy-suite-per-app-tproxy.service" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
|
||||
ExecStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (perAppZapretCfg.enable && cfg.zapret.enable) {
|
||||
"proxy-suite-per-app-zapret-user@" = {
|
||||
description = "Enable proxy-suite app zapret marking for user %i";
|
||||
requires = [ "proxy-suite-per-app-zapret.service" ];
|
||||
after = [ "proxy-suite-per-app-zapret.service" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
|
||||
ExecStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
|
||||
};
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (singBoxCfg.enable && scripts.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 = "${scripts.subscriptionUpdateScript}";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
systemd.timers = lib.optionalAttrs (singBoxCfg.enable && scripts.hasSubscriptions) {
|
||||
proxy-suite-subscription-update = {
|
||||
description = "Periodic proxy-suite subscription refresh";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnBootSec = "5m";
|
||||
OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval;
|
||||
};
|
||||
};
|
||||
};
|
||||
systemd.timers = mkNamedUnits timerEntries;
|
||||
}
|
||||
@@ -22,6 +22,9 @@
|
||||
}:
|
||||
|
||||
let
|
||||
builders = import ./builders.nix { inherit lib pkgs; };
|
||||
inherit (builders) mkAnchorService;
|
||||
|
||||
perAppTunSliceName = "proxy-suite-per-app-tun.slice";
|
||||
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
|
||||
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
|
||||
@@ -238,16 +241,6 @@ let
|
||||
nftChain = "output";
|
||||
};
|
||||
|
||||
mkAnchorService = sliceName: desc: {
|
||||
description = desc;
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
Slice = sliceName;
|
||||
ExecStart = "${pkgs.coreutils}/bin/true";
|
||||
ExecStop = "${pkgs.coreutils}/bin/true";
|
||||
};
|
||||
};
|
||||
in
|
||||
{
|
||||
inherit
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
pkgs,
|
||||
singBoxCfg,
|
||||
perAppRoutingTun,
|
||||
selectionMode,
|
||||
collapseNamedOutbounds,
|
||||
hasSubscriptions,
|
||||
jq,
|
||||
python3,
|
||||
singBox,
|
||||
@@ -108,7 +111,7 @@ let
|
||||
routingMark:
|
||||
let
|
||||
outboundBlocks =
|
||||
if singBoxCfg.selection == "first" && singBoxCfg.outbounds != [ ] then
|
||||
if collapseNamedOutbounds && singBoxCfg.outbounds != [ ] then
|
||||
# Only the first static outbound, tagged "proxy" so sing-box routes to it.
|
||||
mkOutboundBlock (builtins.head singBoxCfg.outbounds) routingMark "proxy"
|
||||
else
|
||||
@@ -118,7 +121,7 @@ let
|
||||
lib.concatMapStrings (sub: mkSubscriptionBlock sub routingMark) singBoxCfg.subscriptions;
|
||||
|
||||
wrapperBlock =
|
||||
if singBoxCfg.selection == "first" then
|
||||
if collapseNamedOutbounds then
|
||||
# When there are no static outbounds, subscription outbounds keep their
|
||||
# real tags. Rename the first one to "proxy" so routing rules resolve.
|
||||
lib.optionalString (singBoxCfg.outbounds == [ ] && singBoxCfg.subscriptions != [ ]) ''
|
||||
@@ -128,7 +131,7 @@ let
|
||||
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
|
||||
fi
|
||||
''
|
||||
else if singBoxCfg.selection == "selector" then
|
||||
else if selectionMode == "selector" then
|
||||
''
|
||||
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
|
||||
@@ -244,7 +247,6 @@ let
|
||||
exit "$FAILED"
|
||||
'';
|
||||
|
||||
hasSubscriptions = singBoxCfg.subscriptions != [ ];
|
||||
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
|
||||
builtins.toJSON (map (sub: sub.tag) singBoxCfg.subscriptions)
|
||||
);
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
}:
|
||||
|
||||
let
|
||||
builders = import ./service/builders.nix { inherit lib pkgs; };
|
||||
inherit (builders) mkOneshotService;
|
||||
|
||||
zapretCfg = cfg.zapret;
|
||||
perAppZapretCfg = zapretCfg.perApp;
|
||||
|
||||
@@ -297,52 +300,46 @@ in
|
||||
[ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
|
||||
);
|
||||
|
||||
systemd.services.zapret-discord-youtube = {
|
||||
systemd.services.zapret-discord-youtube = mkOneshotService {
|
||||
description = "zapret DPI bypass";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
preStart = zapretCommonPreStart globalZapretPackage;
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
RuntimeDirectory = "proxy-suite-zapret";
|
||||
ExecStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
ExecStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
runtimeDirectory = "proxy-suite-zapret";
|
||||
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
extraServiceConfig = {
|
||||
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
|
||||
Environment = globalZapretEnv;
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable {
|
||||
description = "proxy-suite per-app-routing zapret backend";
|
||||
after = [ "network.target" ];
|
||||
conflicts = [
|
||||
"proxy-suite-tproxy.service"
|
||||
"proxy-suite-tun.service"
|
||||
];
|
||||
preStart = zapretCommonPreStart perAppZapretPackage;
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
RuntimeDirectory = "proxy-suite-per-app-zapret";
|
||||
ExecStartPre = "${perAppZapretMarkUpScript}";
|
||||
ExecStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
ExecStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
ExecStopPost = "${perAppZapretMarkDownScript}";
|
||||
Environment = perAppZapretEnv;
|
||||
};
|
||||
};
|
||||
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (
|
||||
mkOneshotService {
|
||||
description = "proxy-suite per-app-routing zapret backend";
|
||||
after = [ "network.target" ];
|
||||
conflicts = [
|
||||
"proxy-suite-tproxy.service"
|
||||
"proxy-suite-tun.service"
|
||||
];
|
||||
preStart = zapretCommonPreStart perAppZapretPackage;
|
||||
runtimeDirectory = "proxy-suite-per-app-zapret";
|
||||
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
|
||||
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
|
||||
execStartPre = "${perAppZapretMarkUpScript}";
|
||||
execStopPost = "${perAppZapretMarkDownScript}";
|
||||
extraServiceConfig.Environment = perAppZapretEnv;
|
||||
}
|
||||
);
|
||||
|
||||
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf zapretCfg.cidrExemption.enable {
|
||||
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;
|
||||
};
|
||||
};
|
||||
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf zapretCfg.cidrExemption.enable (
|
||||
mkOneshotService {
|
||||
description = "Exempt CIDRs from zapret NFQUEUE";
|
||||
after = [ "zapret-discord-youtube.service" ];
|
||||
wants = [ "zapret-discord-youtube.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
|
||||
execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
|
||||
}
|
||||
);
|
||||
}
|
||||
+15
-65
@@ -9,10 +9,23 @@
|
||||
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
parserChecks = import ./checks/parsers.nix { inherit pkgs; };
|
||||
readmeDocSource = builtins.readFile ../nix/readme-doc.nix;
|
||||
trayModuleSource = builtins.readFile ../modules/proxy-suite/tray.nix;
|
||||
tgWsProxyModuleSource = builtins.readFile ../modules/proxy-suite/tg-ws-proxy.nix;
|
||||
controlModuleSource = builtins.readFile ../modules/proxy-suite/service/control.nix;
|
||||
repoChecks = import ./checks/repo.nix {
|
||||
inherit
|
||||
pkgs
|
||||
rg
|
||||
generatedOptionsDoc
|
||||
generatedReadmeDoc
|
||||
readmeDocSource
|
||||
trayModuleSource
|
||||
tgWsProxyModuleSource
|
||||
controlModuleSource
|
||||
;
|
||||
};
|
||||
evalProxySuite =
|
||||
modules:
|
||||
import "${nixpkgs}/nixos/lib/eval-config.nix" {
|
||||
@@ -2331,69 +2344,6 @@ in
|
||||
grep -F -- '--filter-tcp=443 --dpi-desync=fake,multisplit --hostlist="${zapretHostlistBase}/hostlists/list-example.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude-user.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude-user.txt" --new' "${zapretHostlistBase}/config"
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
build-outbound-parser =
|
||||
pkgs.runCommand "build-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||
''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export PYTHONPATH=${../scripts}:$PYTHONPATH
|
||||
export BUILD_OUTBOUND_SCRIPT=${../scripts/build-outbound.py}
|
||||
python ${../scripts/test-build-outbound.py}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
fetch-subscription-parser =
|
||||
pkgs.runCommand "fetch-subscription-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||
''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export PYTHONPATH=${../scripts}:$PYTHONPATH
|
||||
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 \
|
||||
-e '-----BEGIN (RSA|DSA|EC|OPENSSH|PGP) PRIVATE KEY-----' \
|
||||
-e 'ghp_[A-Za-z0-9]{36}' \
|
||||
-e 'github_pat_[A-Za-z0-9_]{20,}' \
|
||||
-e 'glpat-[A-Za-z0-9_-]{20,}' \
|
||||
-e 'xox[baprs]-[A-Za-z0-9-]{10,}' \
|
||||
-e 'AKIA[0-9A-Z]{16}' \
|
||||
-e 'AIza[0-9A-Za-z_-]{35}' \
|
||||
-e 'sk-(proj-)?[A-Za-z0-9_-]{20,}' \
|
||||
"$repo_root"; then
|
||||
echo "secret-like content detected in source tree" >&2
|
||||
exit 1
|
||||
fi
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
options-doc = pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||
diff -u ${../docs/options.md} ${generatedOptionsDoc}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
readme-doc = pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||
diff -u ${../README.md} ${generatedReadmeDoc}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
readme-doc-source = builtins.seq
|
||||
(
|
||||
assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource);
|
||||
assert !(pkgs.lib.hasInfix "packageByPattern" readmeDocSource);
|
||||
true
|
||||
)
|
||||
(pkgs.writeText "proxy-suite-readme-doc-source-check" "ok");
|
||||
|
||||
package-source = builtins.seq
|
||||
(
|
||||
assert !(pkgs.lib.hasInfix "../../pkgs/proxy-suite-tray.nix" trayModuleSource);
|
||||
assert !(pkgs.lib.hasInfix "../../pkgs/tg-ws-proxy.nix" tgWsProxyModuleSource);
|
||||
assert !(pkgs.lib.hasInfix "../../../pkgs/proxy-ctl.nix" controlModuleSource);
|
||||
true
|
||||
)
|
||||
(pkgs.writeText "proxy-suite-package-source-check" "ok");
|
||||
}
|
||||
// parserChecks
|
||||
// repoChecks
|
||||
@@ -0,0 +1,21 @@
|
||||
{ pkgs }:
|
||||
|
||||
{
|
||||
build-outbound-parser =
|
||||
pkgs.runCommand "build-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||
''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export PYTHONPATH=${../../scripts}:$PYTHONPATH
|
||||
python ${../../scripts/test-build-outbound.py}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
fetch-subscription-parser =
|
||||
pkgs.runCommand "fetch-subscription-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; }
|
||||
''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export PYTHONPATH=${../../scripts}:$PYTHONPATH
|
||||
python ${../../scripts/test-fetch-subscription.py}
|
||||
touch "$out"
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
pkgs,
|
||||
rg,
|
||||
generatedOptionsDoc,
|
||||
generatedReadmeDoc,
|
||||
readmeDocSource,
|
||||
trayModuleSource,
|
||||
tgWsProxyModuleSource,
|
||||
controlModuleSource,
|
||||
}:
|
||||
|
||||
{
|
||||
no-secrets = pkgs.runCommand "proxy-suite-no-secrets-check" { } ''
|
||||
repo_root=${../../.}
|
||||
if ${rg} --pcre2 -n -I -H -S \
|
||||
-e '-----BEGIN (RSA|DSA|EC|OPENSSH|PGP) PRIVATE KEY-----' \
|
||||
-e 'ghp_[A-Za-z0-9]{36}' \
|
||||
-e 'github_pat_[A-Za-z0-9_]{20,}' \
|
||||
-e 'glpat-[A-Za-z0-9_-]{20,}' \
|
||||
-e 'xox[baprs]-[A-Za-z0-9-]{10,}' \
|
||||
-e 'AKIA[0-9A-Z]{16}' \
|
||||
-e 'AIza[0-9A-Za-z_-]{35}' \
|
||||
-e 'sk-(proj-)?[A-Za-z0-9_-]{20,}' \
|
||||
"$repo_root"; then
|
||||
echo "secret-like content detected in source tree" >&2
|
||||
exit 1
|
||||
fi
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
options-doc = pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||
diff -u ${../../docs/options.md} ${generatedOptionsDoc}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
readme-doc = pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||
diff -u ${../../README.md} ${generatedReadmeDoc}
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
readme-doc-source = builtins.seq
|
||||
(
|
||||
assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource);
|
||||
assert !(pkgs.lib.hasInfix "packageByPattern" readmeDocSource);
|
||||
true
|
||||
)
|
||||
(pkgs.writeText "proxy-suite-readme-doc-source-check" "ok");
|
||||
|
||||
package-source = builtins.seq
|
||||
(
|
||||
assert !(pkgs.lib.hasInfix "../../pkgs/proxy-suite-tray.nix" trayModuleSource);
|
||||
assert !(pkgs.lib.hasInfix "../../pkgs/tg-ws-proxy.nix" tgWsProxyModuleSource);
|
||||
assert !(pkgs.lib.hasInfix "../../../pkgs/proxy-ctl.nix" controlModuleSource);
|
||||
true
|
||||
)
|
||||
(pkgs.writeText "proxy-suite-package-source-check" "ok");
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
ALL_SERVICES=(
|
||||
proxy-suite-socks
|
||||
proxy-suite-tproxy
|
||||
proxy-suite-tun
|
||||
proxy-suite-tg-ws-proxy
|
||||
proxy-suite-zapret-vm-exempt
|
||||
zapret-discord-youtube
|
||||
)
|
||||
|
||||
_usage() {
|
||||
local status="${1:-1}"
|
||||
echo "Usage: proxy-ctl <command> [args]"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " help show this help message"
|
||||
echo " status [--tray] show status of all proxy-suite services"
|
||||
echo " proxy on|off enable/disable the sing-box proxy stack"
|
||||
echo " tproxy on|off enable/disable TProxy transparent mode"
|
||||
echo " tun on|off enable/disable TUN mode"
|
||||
echo " zapret on|off enable/disable zapret-discord-youtube"
|
||||
echo " restart restart active global proxy-suite services"
|
||||
echo " logs [service] follow service logs (default: proxy-suite-socks)"
|
||||
echo " outbounds list outbounds and current selection"
|
||||
echo " select <tag> switch to a specific outbound (selector mode)"
|
||||
echo " apps list configured per-app routing profiles"
|
||||
echo " wrap <profile> -- <cmd> run a command via a perAppRouting profile"
|
||||
echo " subscription list show subscriptions, cache age, and proxy count"
|
||||
echo " subscription update force-refresh all subscription caches and restart active sing-box services"
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
_svc_status() {
|
||||
local svc="$1"
|
||||
if ! systemctl cat "$svc" &>/dev/null; then
|
||||
return
|
||||
fi
|
||||
local state
|
||||
state=$(systemctl is-active "$svc" 2>/dev/null || true)
|
||||
printf " %-44s %s\n" "$svc" "$state"
|
||||
}
|
||||
|
||||
_bool() {
|
||||
if "$@"; then
|
||||
printf true
|
||||
else
|
||||
printf false
|
||||
fi
|
||||
}
|
||||
|
||||
_svc_exists() {
|
||||
systemctl cat "$1" &>/dev/null
|
||||
}
|
||||
|
||||
_svc_active() {
|
||||
systemctl is-active --quiet "$1"
|
||||
}
|
||||
|
||||
_status_tray() {
|
||||
printf 'socks_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||
printf 'socks_active=%s\n' "$(_bool _svc_active proxy-suite-socks)"
|
||||
printf 'tproxy_available=%s\n' "$(_bool _svc_exists proxy-suite-tproxy)"
|
||||
printf 'tproxy_active=%s\n' "$(_bool _svc_active proxy-suite-tproxy)"
|
||||
printf 'tun_available=%s\n' "$(_bool _svc_exists proxy-suite-tun)"
|
||||
printf 'tun_active=%s\n' "$(_bool _svc_active proxy-suite-tun)"
|
||||
printf 'zapret_available=%s\n' "$(_bool _svc_exists zapret-discord-youtube)"
|
||||
printf 'zapret_active=%s\n' "$(_bool _svc_active zapret-discord-youtube)"
|
||||
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
|
||||
}
|
||||
|
||||
_ensure_app_routing() {
|
||||
if [ "$PER_APP_ROUTING_ENABLED" != "1" ]; then
|
||||
echo "perAppRouting is not enabled in services.proxy-suite.perAppRouting."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
_profile_route() {
|
||||
local profile="$1"
|
||||
jq -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$PER_APP_ROUTING_PROFILES_FILE"
|
||||
}
|
||||
|
||||
_scope_running() {
|
||||
systemctl --user list-units --type=scope --state=running --plain --no-legend "$1-*" \
|
||||
| grep -q .
|
||||
}
|
||||
|
||||
_any_user_active() {
|
||||
systemctl list-units --type=service --state=active --plain --no-legend "$1*.service" \
|
||||
| grep -q .
|
||||
}
|
||||
|
||||
_check_no_global_proxy() {
|
||||
if systemctl is-active --quiet proxy-suite-tun.service; then
|
||||
echo "Global proxy-suite-tun.service is active. Stop it before using route=$1 profiles."
|
||||
exit 1
|
||||
fi
|
||||
if systemctl is-active --quiet proxy-suite-tproxy.service; then
|
||||
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=$1 profiles."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
|
||||
_wrap_slice() {
|
||||
local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
|
||||
shift 4
|
||||
if [ "$enabled" != "1" ]; then
|
||||
echo "$disabled_msg"
|
||||
exit 1
|
||||
fi
|
||||
local uid; uid="$(id -u)"
|
||||
local scope_unit="$slice_base-${profile}-$$"
|
||||
local anchor_unit="$slice_base-anchor.service"
|
||||
local user_svc="$slice_base-user@$uid.service"
|
||||
|
||||
systemctl --user start "$anchor_unit"
|
||||
systemctl start "$backend_svc"
|
||||
systemctl start "$user_svc"
|
||||
|
||||
local status=0
|
||||
systemd-run --user --scope --quiet --collect --same-dir \
|
||||
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||
|
||||
if ! _scope_running "$slice_base"; then
|
||||
systemctl stop "$user_svc" || true
|
||||
systemctl --user stop "$anchor_unit" || true
|
||||
if ! _any_user_active "$slice_base-user@"; then
|
||||
systemctl stop "$backend_svc" || true
|
||||
fi
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
cmd_status() {
|
||||
if [ "${1:-}" = "--tray" ]; then
|
||||
_status_tray
|
||||
return
|
||||
fi
|
||||
|
||||
echo "proxy-suite services:"
|
||||
for svc in "${ALL_SERVICES[@]}"; do
|
||||
_svc_status "$svc"
|
||||
done
|
||||
}
|
||||
|
||||
cmd_proxy() {
|
||||
case "${1:-on}" in
|
||||
on)
|
||||
systemctl start proxy-suite-socks
|
||||
;;
|
||||
off)
|
||||
systemctl stop proxy-suite-tproxy || true
|
||||
systemctl stop proxy-suite-tun || true
|
||||
systemctl stop proxy-suite-socks
|
||||
;;
|
||||
*)
|
||||
echo "Usage: proxy-ctl proxy on|off"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
cmd_mode_toggle() {
|
||||
local name="$1" default_action="${2:-on}"
|
||||
case "${3:-$default_action}" in
|
||||
on)
|
||||
systemctl start "$name"
|
||||
;;
|
||||
off)
|
||||
systemctl stop "$name"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: proxy-ctl ${name#proxy-suite-} on|off"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
cmd_zapret() {
|
||||
case "${1:-on}" in
|
||||
on)
|
||||
systemctl start zapret-discord-youtube
|
||||
;;
|
||||
off)
|
||||
systemctl stop zapret-discord-youtube
|
||||
;;
|
||||
*)
|
||||
echo "Usage: proxy-ctl zapret on|off"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
cmd_restart() {
|
||||
systemctl restart proxy-suite-socks
|
||||
if systemctl is-active --quiet proxy-suite-tproxy; then
|
||||
systemctl restart proxy-suite-tproxy
|
||||
fi
|
||||
if systemctl is-active --quiet proxy-suite-tun; then
|
||||
systemctl restart proxy-suite-tun
|
||||
fi
|
||||
if systemctl is-active --quiet zapret-discord-youtube; then
|
||||
systemctl restart zapret-discord-youtube
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_outbounds() {
|
||||
local data now ob_type
|
||||
data=$(curl -sf "$CLASH_API/proxies/proxy" 2>/dev/null) || {
|
||||
echo "Clash API not available."
|
||||
echo " - Make sure proxy-suite-socks is running"
|
||||
echo " - selection must be 'selector' or 'urltest' (currently: $SELECTION)"
|
||||
exit 1
|
||||
}
|
||||
now=$(echo "$data" | jq -r '.now // "n/a"')
|
||||
ob_type=$(echo "$data" | jq -r '.type // "n/a"')
|
||||
echo "Type: $ob_type"
|
||||
echo "Current: $now"
|
||||
echo ""
|
||||
echo "Available:"
|
||||
echo "$data" | jq -r '.all[]? | " " + .'
|
||||
}
|
||||
|
||||
cmd_select() {
|
||||
local tag payload
|
||||
tag="${1:?Usage: proxy-ctl select <outbound-tag>}"
|
||||
if [ "$SELECTION" != "selector" ]; then
|
||||
echo "selection must be 'selector' (currently: $SELECTION)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
payload=$(jq -cn --arg name "$tag" '{name:$name}')
|
||||
if curl -sf -X PUT "$CLASH_API/proxies/proxy" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$payload" >/dev/null; then
|
||||
echo "Switched to: $tag"
|
||||
else
|
||||
echo "Failed – is proxy-suite-socks running with selector mode?"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_apps() {
|
||||
_ensure_app_routing
|
||||
if [ "$(jq 'length' "$PER_APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then
|
||||
echo "No perAppRouting profiles configured."
|
||||
return
|
||||
fi
|
||||
|
||||
printf " %-24s %s\n" "PROFILE" "ROUTE"
|
||||
jq -r '.[] | " " + (.name | tostring) + "\t" + (.route | tostring)' \
|
||||
"$PER_APP_ROUTING_PROFILES_FILE" \
|
||||
| while IFS=$'\t' read -r profile route; do
|
||||
printf "%-26s %s\n" "$profile" "$route"
|
||||
done
|
||||
}
|
||||
|
||||
cmd_wrap() {
|
||||
local route
|
||||
profile="${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
|
||||
shift || true
|
||||
if [ "${1:-}" = "--" ]; then
|
||||
shift
|
||||
fi
|
||||
if [ "$#" -eq 0 ]; then
|
||||
echo "Usage: proxy-ctl wrap <profile> -- <command> [args...]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
_ensure_app_routing
|
||||
route="$(_profile_route "$profile")"
|
||||
if [ -z "$route" ] || [ "$route" = "null" ]; then
|
||||
echo "Unknown perAppRouting profile: $profile"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$route" in
|
||||
direct)
|
||||
exec "$@"
|
||||
;;
|
||||
proxychains)
|
||||
if [ "$PER_APP_ROUTING_PROXYCHAINS_ENABLED" != "1" ]; then
|
||||
echo "Profile '$profile' uses route=proxychains, but perAppRouting.proxychains.enable is false."
|
||||
exit 1
|
||||
fi
|
||||
exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@"
|
||||
;;
|
||||
tun)
|
||||
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \
|
||||
"Profile '$profile' uses route=tun, but singBox.tun.perApp.enable is false." \
|
||||
"proxy-suite-per-app-tun.service" "$@"
|
||||
;;
|
||||
tproxy)
|
||||
_check_no_global_proxy tproxy
|
||||
_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \
|
||||
"Profile '$profile' uses route=tproxy, but singBox.tproxy.perApp.enable is false." \
|
||||
"proxy-suite-per-app-tproxy.service" "$@"
|
||||
;;
|
||||
zapret)
|
||||
_check_no_global_proxy zapret
|
||||
_wrap_slice "proxy-suite-per-app-zapret" "$PER_APP_ROUTING_ZAPRET_ENABLED" \
|
||||
"Profile '$profile' uses route=zapret, but zapret.perApp.enable or zapret.enable is false." \
|
||||
"proxy-suite-per-app-zapret.service" "$@"
|
||||
;;
|
||||
*)
|
||||
echo "Route backend '$route' is not implemented in this build."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
cmd_subscription() {
|
||||
local subcmd cache age count t
|
||||
subcmd="${1:-list}"
|
||||
shift || true
|
||||
|
||||
case "$subcmd" in
|
||||
list)
|
||||
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||
if [ ${#SUB_TAGS[@]} -eq 0 ]; then
|
||||
echo "No subscriptions configured."
|
||||
return
|
||||
fi
|
||||
|
||||
printf " %-30s %-22s %s\n" "TAG" "LAST UPDATED" "PROXIES"
|
||||
for t in "${SUB_TAGS[@]}"; do
|
||||
cache="$CACHE_DIR/$t.json"
|
||||
if [ -f "$cache" ]; then
|
||||
age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown")
|
||||
count=$(jq 'length' "$cache" 2>/dev/null || echo "?")
|
||||
else
|
||||
age="(no cache)"
|
||||
count="-"
|
||||
fi
|
||||
printf " %-30s %-22s %s\n" "$t" "$age" "$count"
|
||||
done
|
||||
;;
|
||||
update)
|
||||
systemctl start proxy-suite-subscription-update
|
||||
echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: proxy-ctl subscription list|update"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
+5
-1
@@ -18,7 +18,11 @@
|
||||
}:
|
||||
|
||||
let
|
||||
unwrapped = pkgs.writeShellScriptBin "proxy-ctl" (builtins.readFile ./proxy-ctl.sh);
|
||||
unwrapped = pkgs.writeShellScriptBin "proxy-ctl" (
|
||||
builtins.readFile ./proxy-ctl-lib.sh
|
||||
+ "\n"
|
||||
+ builtins.readFile ./proxy-ctl.sh
|
||||
);
|
||||
in
|
||||
pkgs.symlinkJoin {
|
||||
name = "proxy-ctl";
|
||||
|
||||
+11
-295
@@ -9,139 +9,6 @@ if [ -n "$SUB_TAGS_FILE" ] && [ -f "$SUB_TAGS_FILE" ]; then
|
||||
mapfile -t SUB_TAGS < <(jq -r '.[]' "$SUB_TAGS_FILE")
|
||||
fi
|
||||
|
||||
ALL_SERVICES=(
|
||||
proxy-suite-socks
|
||||
proxy-suite-tproxy
|
||||
proxy-suite-tun
|
||||
proxy-suite-tg-ws-proxy
|
||||
proxy-suite-zapret-vm-exempt
|
||||
zapret-discord-youtube
|
||||
)
|
||||
|
||||
_usage() {
|
||||
local status="${1:-1}"
|
||||
echo "Usage: proxy-ctl <command> [args]"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " help show this help message"
|
||||
echo " status [--tray] show status of all proxy-suite services"
|
||||
echo " proxy on|off enable/disable the sing-box proxy stack"
|
||||
echo " tproxy on|off enable/disable TProxy transparent mode"
|
||||
echo " tun on|off enable/disable TUN mode"
|
||||
echo " zapret on|off enable/disable zapret-discord-youtube"
|
||||
echo " restart restart active global proxy-suite services"
|
||||
echo " logs [service] follow service logs (default: proxy-suite-socks)"
|
||||
echo " outbounds list outbounds and current selection"
|
||||
echo " select <tag> switch to a specific outbound (selector mode)"
|
||||
echo " apps list configured per-app routing profiles"
|
||||
echo " wrap <profile> -- <cmd> run a command via a perAppRouting profile"
|
||||
echo " subscription list show subscriptions, cache age, and proxy count"
|
||||
echo " subscription update force-refresh all subscription caches and restart active sing-box services"
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
_svc_status() {
|
||||
local svc="$1"
|
||||
if ! systemctl cat "$svc" &>/dev/null; then
|
||||
return
|
||||
fi
|
||||
local state
|
||||
state=$(systemctl is-active "$svc" 2>/dev/null || true)
|
||||
printf " %-44s %s\n" "$svc" "$state"
|
||||
}
|
||||
|
||||
_bool() {
|
||||
if "$@"; then
|
||||
printf true
|
||||
else
|
||||
printf false
|
||||
fi
|
||||
}
|
||||
|
||||
_svc_exists() {
|
||||
systemctl cat "$1" &>/dev/null
|
||||
}
|
||||
|
||||
_svc_active() {
|
||||
systemctl is-active --quiet "$1"
|
||||
}
|
||||
|
||||
_status_tray() {
|
||||
printf 'socks_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||
printf 'socks_active=%s\n' "$(_bool _svc_active proxy-suite-socks)"
|
||||
printf 'tproxy_available=%s\n' "$(_bool _svc_exists proxy-suite-tproxy)"
|
||||
printf 'tproxy_active=%s\n' "$(_bool _svc_active proxy-suite-tproxy)"
|
||||
printf 'tun_available=%s\n' "$(_bool _svc_exists proxy-suite-tun)"
|
||||
printf 'tun_active=%s\n' "$(_bool _svc_active proxy-suite-tun)"
|
||||
printf 'zapret_available=%s\n' "$(_bool _svc_exists zapret-discord-youtube)"
|
||||
printf 'zapret_active=%s\n' "$(_bool _svc_active zapret-discord-youtube)"
|
||||
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
|
||||
}
|
||||
|
||||
_ensure_app_routing() {
|
||||
if [ "$PER_APP_ROUTING_ENABLED" != "1" ]; then
|
||||
echo "perAppRouting is not enabled in services.proxy-suite.perAppRouting."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
_profile_route() {
|
||||
local profile="$1"
|
||||
jq -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$PER_APP_ROUTING_PROFILES_FILE"
|
||||
}
|
||||
|
||||
_scope_running() {
|
||||
systemctl --user list-units --type=scope --state=running --plain --no-legend "$1-*" \
|
||||
| grep -q .
|
||||
}
|
||||
|
||||
_any_user_active() {
|
||||
systemctl list-units --type=service --state=active --plain --no-legend "$1*.service" \
|
||||
| grep -q .
|
||||
}
|
||||
|
||||
_check_no_global_proxy() {
|
||||
if systemctl is-active --quiet proxy-suite-tun.service; then
|
||||
echo "Global proxy-suite-tun.service is active. Stop it before using route=$1 profiles."
|
||||
exit 1
|
||||
fi
|
||||
if systemctl is-active --quiet proxy-suite-tproxy.service; then
|
||||
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=$1 profiles."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
|
||||
_wrap_slice() {
|
||||
local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
|
||||
shift 4
|
||||
if [ "$enabled" != "1" ]; then
|
||||
echo "$disabled_msg"
|
||||
exit 1
|
||||
fi
|
||||
local uid; uid="$(id -u)"
|
||||
local scope_unit="$slice_base-${profile}-$$"
|
||||
local anchor_unit="$slice_base-anchor.service"
|
||||
local user_svc="$slice_base-user@$uid.service"
|
||||
|
||||
systemctl --user start "$anchor_unit"
|
||||
systemctl start "$backend_svc"
|
||||
systemctl start "$user_svc"
|
||||
|
||||
local status=0
|
||||
systemd-run --user --scope --quiet --collect --same-dir \
|
||||
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||
|
||||
if ! _scope_running "$slice_base"; then
|
||||
systemctl stop "$user_svc" || true
|
||||
systemctl --user stop "$anchor_unit" || true
|
||||
if ! _any_user_active "$slice_base-user@"; then
|
||||
systemctl stop "$backend_svc" || true
|
||||
fi
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
cmd="${1:-status}"
|
||||
shift || true
|
||||
|
||||
@@ -151,66 +18,27 @@ case "$cmd" in
|
||||
;;
|
||||
|
||||
status)
|
||||
if [ "${1:-}" = "--tray" ]; then
|
||||
_status_tray
|
||||
else
|
||||
echo "proxy-suite services:"
|
||||
for svc in "${ALL_SERVICES[@]}"; do
|
||||
_svc_status "$svc"
|
||||
done
|
||||
fi
|
||||
cmd_status "$@"
|
||||
;;
|
||||
|
||||
proxy)
|
||||
case "${1:-on}" in
|
||||
on)
|
||||
systemctl start proxy-suite-socks
|
||||
;;
|
||||
off)
|
||||
systemctl stop proxy-suite-tproxy || true
|
||||
systemctl stop proxy-suite-tun || true
|
||||
systemctl stop proxy-suite-socks
|
||||
;;
|
||||
*)
|
||||
echo "Usage: proxy-ctl proxy on|off"; exit 1 ;;
|
||||
esac
|
||||
cmd_proxy "$@"
|
||||
;;
|
||||
|
||||
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
|
||||
cmd_mode_toggle proxy-suite-tproxy on "${1:-}"
|
||||
;;
|
||||
|
||||
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
|
||||
cmd_mode_toggle proxy-suite-tun on "${1:-}"
|
||||
;;
|
||||
|
||||
zapret)
|
||||
case "${1:-on}" in
|
||||
on) systemctl start zapret-discord-youtube ;;
|
||||
off) systemctl stop zapret-discord-youtube ;;
|
||||
*) echo "Usage: proxy-ctl zapret on|off"; exit 1 ;;
|
||||
esac
|
||||
cmd_zapret "$@"
|
||||
;;
|
||||
|
||||
restart)
|
||||
systemctl restart proxy-suite-socks
|
||||
if systemctl is-active --quiet proxy-suite-tproxy; then
|
||||
systemctl restart proxy-suite-tproxy
|
||||
fi
|
||||
if systemctl is-active --quiet proxy-suite-tun; then
|
||||
systemctl restart proxy-suite-tun
|
||||
fi
|
||||
if systemctl is-active --quiet zapret-discord-youtube; then
|
||||
systemctl restart zapret-discord-youtube
|
||||
fi
|
||||
cmd_restart
|
||||
;;
|
||||
|
||||
logs)
|
||||
@@ -220,135 +48,23 @@ case "$cmd" in
|
||||
;;
|
||||
|
||||
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[]? | " " + .'
|
||||
cmd_outbounds
|
||||
;;
|
||||
|
||||
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
|
||||
cmd_select "$@"
|
||||
;;
|
||||
|
||||
apps)
|
||||
_ensure_app_routing
|
||||
if [ "$(jq 'length' "$PER_APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then
|
||||
echo "No perAppRouting profiles configured."
|
||||
else
|
||||
printf " %-24s %s\n" "PROFILE" "ROUTE"
|
||||
jq -r '.[] | " " + (.name | tostring) + "\t" + (.route | tostring)' \
|
||||
"$PER_APP_ROUTING_PROFILES_FILE" \
|
||||
| while IFS=$'\t' read -r profile route; do
|
||||
printf "%-26s %s\n" "$profile" "$route"
|
||||
done
|
||||
fi
|
||||
cmd_apps
|
||||
;;
|
||||
|
||||
wrap)
|
||||
profile="${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
|
||||
shift || true
|
||||
if [ "${1:-}" = "--" ]; then
|
||||
shift
|
||||
fi
|
||||
if [ "$#" -eq 0 ]; then
|
||||
echo "Usage: proxy-ctl wrap <profile> -- <command> [args...]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
_ensure_app_routing
|
||||
route="$(_profile_route "$profile")"
|
||||
if [ -z "$route" ] || [ "$route" = "null" ]; then
|
||||
echo "Unknown perAppRouting profile: $profile"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$route" in
|
||||
direct)
|
||||
exec "$@"
|
||||
;;
|
||||
proxychains)
|
||||
if [ "$PER_APP_ROUTING_PROXYCHAINS_ENABLED" != "1" ]; then
|
||||
echo "Profile '$profile' uses route=proxychains, but perAppRouting.proxychains.enable is false."
|
||||
exit 1
|
||||
fi
|
||||
exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@"
|
||||
;;
|
||||
tun)
|
||||
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \
|
||||
"Profile '$profile' uses route=tun, but singBox.tun.perApp.enable is false." \
|
||||
"proxy-suite-per-app-tun.service" "$@"
|
||||
;;
|
||||
tproxy)
|
||||
_check_no_global_proxy tproxy
|
||||
_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \
|
||||
"Profile '$profile' uses route=tproxy, but singBox.tproxy.perApp.enable is false." \
|
||||
"proxy-suite-per-app-tproxy.service" "$@"
|
||||
;;
|
||||
zapret)
|
||||
_check_no_global_proxy zapret
|
||||
_wrap_slice "proxy-suite-per-app-zapret" "$PER_APP_ROUTING_ZAPRET_ENABLED" \
|
||||
"Profile '$profile' uses route=zapret, but zapret.perApp.enable or zapret.enable is false." \
|
||||
"proxy-suite-per-app-zapret.service" "$@"
|
||||
;;
|
||||
*)
|
||||
echo "Route backend '$route' is not implemented in this build."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
cmd_wrap "$@"
|
||||
;;
|
||||
|
||||
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
|
||||
cmd_subscription "$@"
|
||||
;;
|
||||
|
||||
*)
|
||||
|
||||
+11
-23
@@ -1,18 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Read a proxy URL from stdin, emit a sing-box outbound JSON object to stdout.
|
||||
|
||||
Usage:
|
||||
echo "vless://..." | build-outbound.py --tag my-server [--routing-mark 2]
|
||||
|
||||
Supported schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
|
||||
socks5, socks5h, socks4, socks4a, http, https
|
||||
"""
|
||||
"""Read a proxy URL from stdin and emit a sing-box outbound JSON object."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from proxy_url_parsers import PARSERS
|
||||
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -24,22 +17,17 @@ def main() -> None:
|
||||
args = ap.parse_args()
|
||||
|
||||
url = sys.stdin.read().strip()
|
||||
scheme = url.split("://")[0].lower()
|
||||
|
||||
if scheme not in PARSERS:
|
||||
print(f"error: unsupported scheme '{scheme}'", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
ob = PARSERS[scheme](url, args.tag)
|
||||
except Exception as e:
|
||||
print(f"error: failed to parse {scheme} URL: {e}", file=sys.stderr)
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark)
|
||||
except ValueError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except Exception as exc:
|
||||
scheme = url.split("://", 1)[0].lower()
|
||||
print(f"error: failed to parse {scheme} URL: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if args.routing_mark is not None:
|
||||
ob["routing_mark"] = args.routing_mark
|
||||
|
||||
print(json.dumps(ob))
|
||||
print(json.dumps(outbound))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,119 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Read a subscription URL from stdin, fetch it, decode it, and emit a JSON array
|
||||
of sing-box outbound objects to stdout.
|
||||
|
||||
Usage:
|
||||
echo "https://example.com/sub" | fetch-subscription.py --tag-prefix my-sub
|
||||
echo "https://example.com/sub" | fetch-subscription.py --tag-prefix my-sub --routing-mark 2
|
||||
|
||||
The subscription endpoint must return either:
|
||||
- A base64-encoded blob that decodes to newline-separated proxy URIs, or
|
||||
- Plain newline-separated proxy URIs directly.
|
||||
|
||||
Supported URI schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
|
||||
socks5, socks5h, socks4, socks4a, http, https
|
||||
"""
|
||||
"""Read a subscription URL from stdin and emit a JSON array of outbounds."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from proxy_url_parsers import PARSERS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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
|
||||
from proxy_parsing import decode_subscription, fetch_raw, parse_subscription
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from proxy_url_parsers import PARSERS
|
||||
|
||||
|
||||
def detect_scheme(url: str) -> str:
|
||||
return url.split("://", 1)[0].lower()
|
||||
|
||||
|
||||
def build_outbound(url: str, tag: str, routing_mark: int | None = None) -> dict:
|
||||
scheme = detect_scheme(url)
|
||||
if scheme not in PARSERS:
|
||||
raise ValueError(f"unsupported scheme '{scheme}'")
|
||||
|
||||
outbound = PARSERS[scheme](url, tag)
|
||||
if routing_mark is not None:
|
||||
outbound["routing_mark"] = routing_mark
|
||||
return outbound
|
||||
|
||||
|
||||
def fetch_raw(url: str) -> bytes:
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "v2rayN/6.0"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def decode_subscription(data: bytes) -> list[str]:
|
||||
text = None
|
||||
stripped = data.strip()
|
||||
try:
|
||||
pad = b"=" * (-len(stripped) % 4)
|
||||
decoded = base64.b64decode(stripped + pad).decode("utf-8")
|
||||
if any(f"{scheme}://" in decoded for scheme in PARSERS):
|
||||
text = decoded
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if text is None:
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
|
||||
return [line.strip() for line in text.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def slugify_tag(remark: str) -> str:
|
||||
slug = re.sub(r"[^a-zA-Z0-9_-]", "-", remark)
|
||||
slug = re.sub(r"-{2,}", "-", slug).strip("-")
|
||||
return slug[:60] or "proxy"
|
||||
|
||||
|
||||
def make_tag(prefix: str, remark: str, index: int) -> str:
|
||||
if remark:
|
||||
return f"{prefix}-{slugify_tag(urllib.parse.unquote(remark))}"
|
||||
return f"{prefix}-{index}"
|
||||
|
||||
|
||||
def parse_subscription(lines: list[str], tag_prefix: str, routing_mark: int | None) -> list[dict]:
|
||||
outbounds = []
|
||||
seen_tags: set[str] = set()
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
scheme = detect_scheme(line)
|
||||
if scheme not in PARSERS:
|
||||
continue
|
||||
|
||||
remark = line.split("#", 1)[1] if "#" in line else ""
|
||||
base_tag = make_tag(tag_prefix, remark, index)
|
||||
tag = base_tag
|
||||
|
||||
if tag in seen_tags:
|
||||
suffix = 2
|
||||
while f"{base_tag}-{suffix}" in seen_tags:
|
||||
suffix += 1
|
||||
tag = f"{base_tag}-{suffix}"
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark)
|
||||
except Exception as exc:
|
||||
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
seen_tags.add(tag)
|
||||
outbounds.append(outbound)
|
||||
|
||||
return outbounds
|
||||
@@ -2,32 +2,13 @@
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
SCRIPT = Path(os.environ.get("BUILD_OUTBOUND_SCRIPT", Path(__file__).with_name("build-outbound.py")))
|
||||
|
||||
|
||||
def run_parser(url: str, *, expect_ok: bool = True):
|
||||
env = dict(os.environ)
|
||||
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(SCRIPT), "--tag", "test-outbound"],
|
||||
input=url,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
if expect_ok:
|
||||
if proc.returncode != 0:
|
||||
raise AssertionError(proc.stderr)
|
||||
return json.loads(proc.stdout)
|
||||
return proc
|
||||
def run_parser(url: str):
|
||||
return build_outbound(url, "test-outbound")
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
@@ -97,9 +78,8 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["tls"]["server_name"], "proxy.example.com")
|
||||
|
||||
def test_invalid_scheme_fails(self):
|
||||
proc = run_parser("wireguard://example.com", expect_ok=False)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("unsupported scheme", proc.stderr)
|
||||
with self.assertRaisesRegex(ValueError, "unsupported scheme"):
|
||||
run_parser("wireguard://example.com")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,51 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SCRIPT = Path(os.environ.get("FETCH_SUBSCRIPTION_SCRIPT", Path(__file__).with_name("fetch-subscription.py")))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tiny embedded HTTP server for test fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _FixtureHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
body = self.server.response_data
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass # silence access log during tests
|
||||
|
||||
|
||||
def _start_server(data: bytes):
|
||||
"""Start an ephemeral HTTP server on a random port. Returns (server, port)."""
|
||||
srv = HTTPServer(("127.0.0.1", 0), _FixtureHandler)
|
||||
srv.response_data = data
|
||||
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
# Give the server a moment to enter its accept loop.
|
||||
time.sleep(0.05)
|
||||
return srv, srv.server_address[1]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
from proxy_parsing import decode_subscription, parse_subscription
|
||||
|
||||
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
|
||||
SS_URI = "ss://{}@ss.example.com:8388".format(
|
||||
@@ -60,26 +17,9 @@ def _make_b64_payload(*uris: str) -> bytes:
|
||||
return base64.b64encode(text.encode())
|
||||
|
||||
|
||||
def run_fetcher(server_data: bytes, tag_prefix: str = "test", *, expect_ok: bool = True, extra_args: list = None):
|
||||
srv, port = _start_server(server_data)
|
||||
url = f"http://127.0.0.1:{port}/sub"
|
||||
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
|
||||
cmd = [sys.executable, str(SCRIPT), "--tag-prefix", tag_prefix] + (extra_args or [])
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
input=url,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
if expect_ok:
|
||||
if proc.returncode != 0:
|
||||
raise AssertionError(f"Expected success, got:\n{proc.stderr}")
|
||||
return json.loads(proc.stdout)
|
||||
return proc
|
||||
def run_fetcher(server_data: bytes, tag_prefix: str = "test", *, routing_mark: int | None = None):
|
||||
lines = decode_subscription(server_data)
|
||||
return parse_subscription(lines, tag_prefix, routing_mark)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -145,15 +85,13 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
|
||||
def test_routing_mark_applied(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI)
|
||||
obs = run_fetcher(payload, extra_args=["--routing-mark", "2"])
|
||||
obs = run_fetcher(payload, routing_mark=2)
|
||||
for ob in obs:
|
||||
self.assertEqual(ob["routing_mark"], 2)
|
||||
|
||||
def test_all_invalid_fails(self):
|
||||
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
|
||||
proc = run_fetcher(payload, expect_ok=False)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("no parseable proxy URIs", proc.stderr)
|
||||
self.assertEqual(run_fetcher(payload), [])
|
||||
|
||||
def test_index_tag_fallback_when_no_remark(self):
|
||||
# URIs without a remark should get index-based tags
|
||||
|
||||
Reference in new issue
Block a user