more internal updates

This commit is contained in:
FUFSoB committed 2026-04-15 14:49:13 +05:00
1 parent d3c68f7a9a
commit f54ae974ef
11 files changed
+708 -1003

No files matched your search

+23 -11
View File
@@ -1751,8 +1751,9 @@ one of “udp”, “tcp”, “tls”
Netfilter mark set on packets intercepted by TProxy so policy routing
can send them to the local loopback route table\. Used by TProxy mode\.
Mark applied to intercepted packets in TProxy mode\.
A matching ` ip rule ` routes this mark to singBox\.routeTable, which
points traffic to loopback for local proxy processing\.
@@ -2234,8 +2235,8 @@ true
Netfilter mark set on sing-box’s own outbound packets so they bypass
TProxy re-interception loops\. Used by TProxy mode\.
Mark applied to sing-box egress packets in TProxy mode so they bypass
re-interception and do not loop back into the transparent proxy path\.
@@ -2268,8 +2269,9 @@ signed integer
Policy routing table used to redirect TProxy-marked packets to the
loopback interface\. Used by TProxy mode\.
Policy-routing table number used for TProxy interception flow\.
The module installs a local default route in this table and binds it
to singBox\.fwmark\.
@@ -3362,7 +3364,9 @@ list of string
Listen port for the local sing-box TProxy inbound\. Used by TProxy mode\.
Local listen port for sing-box’s TProxy inbound\.
nftables redirection created by proxy-suite-tproxy sends intercepted
TCP/UDP traffic to this port\.
@@ -3705,7 +3709,9 @@ true
Map of Telegram DC ID to IP address for relay\.
Mapping of Telegram DC IDs to relay IPs\.
Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by
tg-ws-proxy for MTProto relay selection\.
@@ -3742,7 +3748,9 @@ attribute set of string
Address to bind tg-ws-proxy to\.
Bind address for tg-ws-proxy\.
Keep ` 127.0.0.1 ` for local-only usage; bind to ` 0.0.0.0 ` only when you
intentionally expose the proxy to other hosts\.
@@ -3775,7 +3783,9 @@ string
Listen port for the tg-ws-proxy service\.
TCP listen port for tg-ws-proxy\.
Telegram clients connect to this endpoint when using the local MTProto
WebSocket proxy\.
@@ -3948,7 +3958,9 @@ true
Status polling interval in seconds for the tray application\.
Tray status refresh interval in seconds\.
Lower values make UI state changes appear faster, while higher values
reduce background polling overhead\.
+9 -4
View File
@@ -35,18 +35,23 @@
nixosModules.zapret = zapret.nixosModules.default;
overlays.default = final: prev: {
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = final; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = final; };
inherit (import ./pkgs/default.nix { pkgs = final; })
tg-ws-proxy
proxy-suite-tray
;
};
packages = forAll (
system:
let
pkgs = pkgsFor system;
suitePkgs = import ./pkgs/default.nix { inherit pkgs; };
in
{
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { inherit pkgs; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { inherit pkgs; };
inherit (suitePkgs)
tg-ws-proxy
proxy-suite-tray
;
optionsDoc = mkOptionsDoc system;
update-options-doc = pkgs.writeShellApplication {
name = "update-options-doc";
+59 -39
View File
@@ -545,44 +545,48 @@ in
example = 1080;
};
tproxyPort = mkOption {
type = types.port;
default = 1081;
description = ''
Listen port for the local sing-box TProxy inbound. Used by TProxy mode.
'';
example = 1081;
};
tproxyPort = mkOption {
type = types.port;
default = 1081;
description = ''
Local listen port for sing-box's TProxy inbound.
nftables redirection created by proxy-suite-tproxy sends intercepted
TCP/UDP traffic to this port.
'';
example = 1081;
};
fwmark = mkOption {
type = types.int;
default = 1;
description = ''
Netfilter mark set on packets intercepted by TProxy so policy routing
can send them to the local loopback route table. Used by TProxy mode.
'';
example = 1;
};
fwmark = mkOption {
type = types.int;
default = 1;
description = ''
Mark applied to intercepted packets in TProxy mode.
A matching `ip rule` routes this mark to singBox.routeTable, which
points traffic to loopback for local proxy processing.
'';
example = 1;
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = ''
Netfilter mark set on sing-box's own outbound packets so they bypass
TProxy re-interception loops. Used by TProxy mode.
'';
example = 2;
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = ''
Mark applied to sing-box egress packets in TProxy mode so they bypass
re-interception and do not loop back into the transparent proxy path.
'';
example = 2;
};
routeTable = mkOption {
type = types.int;
default = 100;
description = ''
Policy routing table used to redirect TProxy-marked packets to the
loopback interface. Used by TProxy mode.
'';
example = 100;
};
routeTable = mkOption {
type = types.int;
default = 100;
description = ''
Policy-routing table number used for TProxy interception flow.
The module installs a local default route in this table and binds it
to singBox.fwmark.
'';
example = 100;
};
proxyByDefault = mkOption {
type = types.bool;
@@ -1217,7 +1221,11 @@ in
pollInterval = mkOption {
type = types.int;
default = 5;
description = "Status polling interval in seconds for the tray application.";
description = ''
Tray status refresh interval in seconds.
Lower values make UI state changes appear faster, while higher values
reduce background polling overhead.
'';
example = 5;
};
@@ -1238,14 +1246,22 @@ in
port = mkOption {
type = types.port;
default = 1076;
description = "Listen port for the tg-ws-proxy service.";
description = ''
TCP listen port for tg-ws-proxy.
Telegram clients connect to this endpoint when using the local MTProto
WebSocket proxy.
'';
example = 1076;
};
host = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to bind tg-ws-proxy to.";
description = ''
Bind address for tg-ws-proxy.
Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you
intentionally expose the proxy to other hosts.
'';
example = "127.0.0.1";
};
@@ -1277,7 +1293,11 @@ in
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = "Map of Telegram DC ID to IP address for relay.";
description = ''
Mapping of Telegram DC IDs to relay IPs.
Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by
tg-ws-proxy for MTProto relay selection.
'';
example = {
"2" = "149.154.167.220";
"4" = "149.154.167.220";
+194
View File
@@ -0,0 +1,194 @@
{
lib,
cfg,
sb,
t,
ar,
art,
artp,
arz,
builtinTags,
outboundTags,
invalidRoutingTargets,
effectiveAppRoutingProfileNames,
hasProxychainsProfiles,
hasTunProfiles,
hasTproxyProfiles,
hasZapretProfiles,
}:
[
{
assertion = !sb.enable || (sb.outbounds != [ ] || sb.subscriptions != [ ]);
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
}
{
assertion = builtins.length outboundTags == builtins.length (lib.unique outboundTags);
message = "proxy-suite: outbound tags must be unique";
}
{
assertion = builtins.all (tag: !builtins.elem tag builtinTags) outboundTags;
message = "proxy-suite: outbound tags must not use reserved names: proxy, direct, block";
}
{
assertion = invalidRoutingTargets == [ ];
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
}
{
assertion = !(sb.tproxy.enable && sb.tproxy.autostart && sb.tun.enable && sb.tun.autostart);
message = "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
}
{
assertion = ar.enable || ar.profiles == [ ];
message = "proxy-suite: appRouting.profiles requires appRouting.enable = true";
}
{
assertion = !ar.proxychains.enable || ar.enable;
message = "proxy-suite: appRouting.proxychains.enable requires appRouting.enable = true";
}
{
assertion = builtins.length effectiveAppRoutingProfileNames == builtins.length (lib.unique effectiveAppRoutingProfileNames);
message = "proxy-suite: appRouting profile names must be unique";
}
{
assertion = !hasProxychainsProfiles || ar.proxychains.enable;
message = "proxy-suite: route=proxychains in appRouting.profiles requires appRouting.proxychains.enable = true";
}
{
assertion = !art.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tun.enable requires appRouting.enable = true";
}
{
assertion = !(hasTunProfiles && !art.enable);
message = "proxy-suite: route=tun in appRouting profiles requires appRouting.backends.tun.enable = true";
}
{
assertion = !artp.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tproxy.enable requires appRouting.enable = true";
}
{
assertion = !(hasTproxyProfiles && !artp.enable);
message = "proxy-suite: route=tproxy in appRouting profiles requires appRouting.backends.tproxy.enable = true";
}
{
assertion = !arz.enable || ar.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires appRouting.enable = true";
}
{
assertion = !arz.enable || cfg.zapret.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires zapret.enable = true";
}
{
assertion = !(hasZapretProfiles && (!arz.enable || !cfg.zapret.enable));
message = "proxy-suite: route=zapret in appRouting profiles requires appRouting.backends.zapret.enable = true and zapret.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.fwmark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.proxyMark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable must differ from singBox.routeTable when singBox.tproxy.enable = true";
}
{
assertion = !(artp.enable && artp.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.fwmark";
}
{
assertion = !(artp.enable && artp.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.proxyMark";
}
{
assertion = !(artp.enable && artp.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tproxy.routeTable must differ from singBox.routeTable";
}
{
assertion = !(art.enable && artp.enable && art.fwmark == artp.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.tproxy.fwmark must differ";
}
{
assertion = !(art.enable && artp.enable && art.routeTable == artp.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable and appRouting.backends.tproxy.routeTable must differ";
}
{
assertion = !(arz.enable && arz.filterMark == sb.fwmark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.fwmark";
}
{
assertion = !(arz.enable && arz.filterMark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.proxyMark";
}
{
assertion = !(art.enable && arz.enable && art.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(artp.enable && arz.enable && artp.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 536870912 1073741824 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.proxyMark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.proxyMark must not use app-zapret internal desync mark bits";
}
{
assertion = !(art.enable && arz.enable && builtins.elem art.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tun.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(artp.enable && arz.enable && builtins.elem artp.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use app-zapret internal desync mark bits";
}
{
assertion =
!t.enable
||
builtins.length (
builtins.filter (x: x != null) [
t.secret
t.secretFile
]
) == 1;
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
}
]
++ lib.concatMap (ob: [
{
assertion =
builtins.length (
builtins.filter (x: x != null) [
ob.urlFile
ob.url
ob.json
]
) == 1;
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
}
]) sb.outbounds
++ lib.concatMap (sub: [
{
assertion =
builtins.length (
builtins.filter (x: x != null) [
sub.urlFile
sub.url
]
) == 1;
message = "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url";
}
]) sb.subscriptions
+42 -199
View File
@@ -64,7 +64,25 @@ let
seqBin = "${pkgs.coreutils}/bin/seq";
findBin = "${pkgs.findutils}/bin/find";
fetchSubscriptionPy = ../../scripts/fetch-subscription.py;
proxySuiteScriptsDir = ../../scripts;
parserScriptsPythonPath = lib.escapeShellArg (toString proxySuiteScriptsDir);
buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py";
fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py";
mkSubscriptionUrlSource =
sub:
if sub.urlFile != null then
sub.urlFile
else
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
mkSubscriptionFetchCommand =
sub:
let
urlSource = mkSubscriptionUrlSource sub;
in
''
printf '%s' "$(cat ${lib.escapeShellArg urlSource})" \
| PYTHONPATH=${parserScriptsPythonPath} ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag}
'';
# Build the shell code block for a single outbound entry.
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
@@ -99,7 +117,7 @@ let
''
# outbound: ${tag}
URL=$(cat ${lib.escapeShellArg urlSource})
OB_JSON=$(printf '%s' "$URL" | ${python3} ${../../scripts/build-outbound.py} --tag ${lib.escapeShellArg tag}${markArg})
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH=${parserScriptsPythonPath} ${python3} ${buildOutboundPy} --tag ${lib.escapeShellArg tag}${markArg})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
@@ -107,23 +125,13 @@ let
# Fetches subscription into the cache on first run; subsequent starts use the cache.
mkSubscriptionBlock =
sub: routingMark:
let
urlSource =
if sub.urlFile != null then
sub.urlFile
else
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
in
''
# subscription: ${sub.tag}
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
CACHE_FILE="$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
if [ ! -f "$CACHE_FILE" ]; then
mkdir -p "$CACHE_DIR"
SUB_URL=$(cat ${lib.escapeShellArg urlSource})
if printf '%s' "$SUB_URL" \
| ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} \
> "$CACHE_FILE.tmp"; then
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
else
rm -f "$CACHE_FILE.tmp"
@@ -239,18 +247,8 @@ let
# Shell code to fetch a single subscription into the cache (used in update service).
mkSubscriptionFetchBlock =
sub:
let
urlSource =
if sub.urlFile != null then
sub.urlFile
else
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
in
''
SUB_URL=$(cat ${lib.escapeShellArg urlSource})
if printf '%s' "$SUB_URL" \
| ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} \
> "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"; then
if ${mkSubscriptionFetchCommand sub} > "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"; then
mv "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp" \
"$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
echo "Updated subscription: ${sub.tag}"
@@ -905,181 +903,26 @@ in
mkAnchorService appZapretSliceName "Anchor service for proxy-suite app zapret slice";
};
assertions = [
{
assertion = !sb.enable || (sb.outbounds != [ ] || sb.subscriptions != [ ]);
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
}
{
assertion = builtins.length outboundTags == builtins.length (lib.unique outboundTags);
message = "proxy-suite: outbound tags must be unique";
}
{
assertion = builtins.all (tag: !builtins.elem tag builtinTags) outboundTags;
message = "proxy-suite: outbound tags must not use reserved names: proxy, direct, block";
}
{
assertion = invalidRoutingTargets == [ ];
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
}
{
assertion = !(sb.tproxy.enable && sb.tproxy.autostart && sb.tun.enable && sb.tun.autostart);
message = "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
}
{
assertion = ar.enable || ar.profiles == [ ];
message = "proxy-suite: appRouting.profiles requires appRouting.enable = true";
}
{
assertion = !ar.proxychains.enable || ar.enable;
message = "proxy-suite: appRouting.proxychains.enable requires appRouting.enable = true";
}
{
assertion = builtins.length effectiveAppRoutingProfileNames == builtins.length (lib.unique effectiveAppRoutingProfileNames);
message = "proxy-suite: appRouting profile names must be unique";
}
{
assertion = !hasProxychainsProfiles || ar.proxychains.enable;
message = "proxy-suite: route=proxychains in appRouting.profiles requires appRouting.proxychains.enable = true";
}
{
assertion = !art.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tun.enable requires appRouting.enable = true";
}
{
assertion = !(hasTunProfiles && !art.enable);
message = "proxy-suite: route=tun in appRouting profiles requires appRouting.backends.tun.enable = true";
}
{
assertion = !artp.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tproxy.enable requires appRouting.enable = true";
}
{
assertion = !(hasTproxyProfiles && !artp.enable);
message = "proxy-suite: route=tproxy in appRouting profiles requires appRouting.backends.tproxy.enable = true";
}
{
assertion = !arz.enable || ar.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires appRouting.enable = true";
}
{
assertion = !arz.enable || cfg.zapret.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires zapret.enable = true";
}
{
assertion = !(hasZapretProfiles && (!arz.enable || !cfg.zapret.enable));
message = "proxy-suite: route=zapret in appRouting profiles requires appRouting.backends.zapret.enable = true and zapret.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.fwmark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.proxyMark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable must differ from singBox.routeTable when singBox.tproxy.enable = true";
}
{
assertion = !(artp.enable && artp.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.fwmark";
}
{
assertion = !(artp.enable && artp.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.proxyMark";
}
{
assertion = !(artp.enable && artp.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tproxy.routeTable must differ from singBox.routeTable";
}
{
assertion = !(art.enable && artp.enable && art.fwmark == artp.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.tproxy.fwmark must differ";
}
{
assertion = !(art.enable && artp.enable && art.routeTable == artp.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable and appRouting.backends.tproxy.routeTable must differ";
}
{
assertion = !(arz.enable && arz.filterMark == sb.fwmark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.fwmark";
}
{
assertion = !(arz.enable && arz.filterMark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.proxyMark";
}
{
assertion = !(art.enable && arz.enable && art.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(artp.enable && arz.enable && artp.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 536870912 1073741824 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.proxyMark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.proxyMark must not use app-zapret internal desync mark bits";
}
{
assertion = !(art.enable && arz.enable && builtins.elem art.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tun.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(artp.enable && arz.enable && builtins.elem artp.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use app-zapret internal desync mark bits";
}
{
assertion =
!t.enable
||
builtins.length (
builtins.filter (x: x != null) [
t.secret
t.secretFile
]
) == 1;
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
}
]
++ lib.concatMap (ob: [
{
assertion =
builtins.length (
builtins.filter (x: x != null) [
ob.urlFile
ob.url
ob.json
]
) == 1;
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
}
]) sb.outbounds
++ lib.concatMap (sub: [
{
assertion =
builtins.length (
builtins.filter (x: x != null) [
sub.urlFile
sub.url
]
) == 1;
message = "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url";
}
]) sb.subscriptions;
assertions = import ./service-assertions.nix {
inherit
lib
cfg
sb
t
ar
art
artp
arz
builtinTags
outboundTags
invalidRoutingTargets
effectiveAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
};
systemd.services = {
proxy-suite-socks = {
+8 -27
View File
@@ -40,36 +40,17 @@ let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
listGeneralFile =
if z.listGeneral != [ ] then
pkgs.writeText "proxy-suite-zapret-list-general-user.txt" (
lib.concatStringsSep "\n" z.listGeneral + "\n"
)
mkOptionalHostlistFile =
fileName: entries:
if entries != [ ] then
pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n")
else
null;
listExcludeFile =
if z.listExclude != [ ] then
pkgs.writeText "proxy-suite-zapret-list-exclude-user.txt" (
lib.concatStringsSep "\n" z.listExclude + "\n"
)
else
null;
ipsetAllFile =
if z.ipsetAll != [ ] then
pkgs.writeText "proxy-suite-zapret-ipset-all.txt" (lib.concatStringsSep "\n" z.ipsetAll + "\n")
else
null;
ipsetExcludeFile =
if z.ipsetExclude != [ ] then
pkgs.writeText "proxy-suite-zapret-ipset-exclude-user.txt" (
lib.concatStringsSep "\n" z.ipsetExclude + "\n"
)
else
null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" z.listGeneral;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" z.listExclude;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" z.ipsetAll;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" z.ipsetExclude;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
+69 -54
View File
@@ -130,6 +130,12 @@ let
];
};
};
mkFixture = proxySuiteConfig: evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = proxySuiteConfig;
}
];
minimal = evalProxySuite [ baseModule ];
@@ -145,66 +151,51 @@ let
];
duplicateTags = forceEval (
(evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
singBox.outbounds = [
{
tag = "dup";
url = "http://one.example.com:8080";
}
{
tag = "dup";
url = "http://two.example.com:8080";
}
];
};
}
]).config.system.build.toplevel.drvPath
(mkFixture {
enable = true;
singBox.outbounds = [
{
tag = "dup";
url = "http://one.example.com:8080";
}
{
tag = "dup";
url = "http://two.example.com:8080";
}
];
}).config.system.build.toplevel.drvPath
);
reservedTag = forceEval (
(evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
singBox.outbounds = [
{
tag = "proxy";
url = "http://proxy.example.com:8080";
}
];
};
}
]).config.system.build.toplevel.drvPath
(mkFixture {
enable = true;
singBox.outbounds = [
{
tag = "proxy";
url = "http://proxy.example.com:8080";
}
];
}).config.system.build.toplevel.drvPath
);
unknownRoutingTarget = forceEval (
(evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
singBox = {
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
routing.rules = [
{
outbound = "missing";
domains = [ "example.com" ];
}
];
};
};
}
]).config.system.build.toplevel.drvPath
(mkFixture {
enable = true;
singBox = {
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
routing.rules = [
{
outbound = "missing";
domains = [ "example.com" ];
}
];
};
}).config.system.build.toplevel.drvPath
);
tproxyWithFirewall = evalProxySuite [
@@ -1556,6 +1547,28 @@ let
true
)
# -- runtime parser: socks start script sets PYTHONPATH for static URL parser imports --
(
let
startScript =
subscriptionWithStaticFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart;
scriptText = builtins.readFile startScript;
in
assert builtins.match ".*PYTHONPATH=.*build-outbound\\.py.*" scriptText != null;
true
)
# -- subscription/runtime parser: update script sets PYTHONPATH for parser module imports --
(
let
updateScript =
subscriptionOnlyFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart;
scriptText = builtins.readFile updateScript;
in
assert builtins.match ".*PYTHONPATH=.*fetch-subscription\\.py.*" scriptText != null;
true
)
# -- subscription: no update service/timer without subscriptions --
(
assert !(minimal.config.systemd.services ? "proxy-suite-subscription-update");
@@ -1980,6 +1993,7 @@ in
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"
@@ -1989,6 +2003,7 @@ in
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"
+1
View File
@@ -1,4 +1,5 @@
{ pkgs }:
{
tg-ws-proxy = import ./tg-ws-proxy.nix { inherit pkgs; };
proxy-suite-tray = import ./proxy-suite-tray.nix { inherit pkgs; };
}
+1 -335
View File
@@ -10,343 +10,9 @@ Supported schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
"""
import argparse
import base64
import json
import sys
import urllib.parse
def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query))
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
"""Strip scheme+fragment, return (userinfo, host, port_str, params).
userinfo is "" when no '@' is present."""
rest = url[len(f"{scheme}://"):]
rest, _, _ = rest.partition("#")
if "@" in rest:
userinfo, _, rest = rest.partition("@")
else:
userinfo = ""
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
return userinfo, host, port, _qs(query)
def _mk_transport(
transport_type: str,
path: str = "/",
host_header: str = "",
service_name: str = "",
) -> "dict | None":
"""Build a sing-box transport dict for ws/grpc/h2. Returns None for tcp."""
if transport_type == "ws":
return {
"type": "ws",
"path": urllib.parse.unquote(path),
"headers": {"Host": host_header},
}
elif transport_type == "grpc":
return {
"type": "grpc",
"service_name": urllib.parse.unquote(service_name),
}
elif transport_type == "h2":
return {
"type": "http",
"host": [host_header],
"path": urllib.parse.unquote(path),
}
return None
def parse_vless(url: str, tag: str) -> dict:
"""
vless://UUID@HOST:PORT?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=SID&flow=FLOW&type=tcp
vless://UUID@HOST:PORT?security=tls&sni=SNI&fp=chrome&type=ws&path=/path&host=HOST
"""
userinfo, host, port, params = _parse_url_parts(url, "vless")
security = params.get("security", "none")
transport = params.get("type", "tcp")
ob: dict = {
"type": "vless",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": userinfo,
"packet_encoding": "xudp",
}
if security == "reality":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
"reality": {
"enabled": True,
"public_key": params["pbk"],
"short_id": params.get("sid", ""),
},
}
elif security == "tls":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
tr = _mk_transport(
transport,
path=params.get("path", "/"),
host_header=params.get("host", host),
service_name=params.get("serviceName", ""),
)
if tr is not None:
ob["transport"] = tr
flow = urllib.parse.unquote(params.get("flow", ""))
if flow:
ob["flow"] = flow
return ob
def parse_vmess(url: str, tag: str) -> dict:
"""
vmess://BASE64 where BASE64 decodes to a JSON object (V2 link format).
Fields: v, ps, add, port, id, aid, scy, net, type, host, path, tls, sni, alpn, fp
"""
b64 = url[len("vmess://"):]
pad = "=" * (-len(b64) % 4)
try:
data = json.loads(base64.b64decode(b64 + pad))
except Exception:
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
host = str(data["add"])
port = int(data["port"])
net = data.get("net", "tcp")
tls_field = str(data.get("tls", ""))
sni = str(data.get("sni") or data.get("host") or host)
ob: dict = {
"type": "vmess",
"tag": tag,
"server": host,
"server_port": port,
"uuid": data["id"],
"security": data.get("scy", "auto"),
"alter_id": int(data.get("aid", 0)),
}
if tls_field in ("tls", "reality"):
ob["tls"] = {"enabled": True, "server_name": sni}
if data.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
if data.get("alpn"):
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
path = str(data.get("path") or "/")
h_host = str(data.get("host") or host)
# vmess grpc uses path as service_name; other transports use path/h_host directly
tr = _mk_transport(
net if net != "http" else "h2",
path=path,
host_header=h_host,
service_name=path.lstrip("/"),
)
if tr is not None:
ob["transport"] = tr
return ob
def parse_trojan(url: str, tag: str) -> dict:
"""
trojan://PASSWORD@HOST:PORT?sni=SNI&fp=chrome&security=tls&type=tcp|ws|grpc&path=...
"""
userinfo, host, port, params = _parse_url_parts(url, "trojan")
transport = params.get("type", "tcp")
ob: dict = {
"type": "trojan",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
},
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
tr = _mk_transport(
transport,
path=params.get("path", "/"),
host_header=params.get("host", host),
service_name=params.get("serviceName", ""),
)
if tr is not None:
ob["transport"] = tr
return ob
def parse_shadowsocks(url: str, tag: str) -> dict:
"""
SIP002: ss://BASE64(method:password)@HOST:PORT[?plugin=...]#remark
plain: ss://method:password@HOST:PORT#remark
"""
rest = url[len("ss://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, _ = rest.partition("?")
host, _, port = hostpart.rpartition(":")
# Try SIP002 base64 decode first
pad = "=" * (-len(userinfo) % 4)
try:
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
if ":" not in decoded:
raise ValueError
method, password = decoded.split(":", 1)
except Exception:
plain = urllib.parse.unquote(userinfo)
method, password = plain.split(":", 1)
return {
"type": "shadowsocks",
"tag": tag,
"server": host,
"server_port": int(port),
"method": method,
"password": password,
}
def parse_hysteria2(url: str, tag: str) -> dict:
"""
hysteria2://PASSWORD@HOST:PORT?sni=SNI&insecure=1&obfs=salamander&obfs-password=PASS
hy2://... (same, shorter alias)
"""
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
userinfo, host, port, params = _parse_url_parts(url, scheme)
ob: dict = {
"type": "hysteria2",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"insecure": params.get("insecure", "0") == "1",
},
}
if params.get("obfs") == "salamander":
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
return ob
def parse_tuic(url: str, tag: str) -> dict:
"""
tuic://UUID:PASSWORD@HOST:PORT?congestion_control=bbr&udp_relay_mode=native&alpn=h3&sni=SNI
"""
userinfo, host, port, params = _parse_url_parts(url, "tuic")
uuid, _, password = userinfo.partition(":")
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
return {
"type": "tuic",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": uuid,
"password": urllib.parse.unquote(password),
"congestion_control": params.get("congestion_control", "bbr"),
"udp_relay_mode": params.get("udp_relay_mode", "native"),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"alpn": alpn,
},
}
def parse_socks(url: str, tag: str) -> dict:
"""
socks5://[user:pass@]host:port[#remark]
socks5h://... (socks5 with remote DNS resolution – same wire format)
socks4://host:port[#remark]
socks4a://host:port[#remark]
"""
scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5"
userinfo, host, port, _ = _parse_url_parts(url, scheme)
ob: dict = {"type": "socks", "tag": tag, "version": version}
if userinfo and ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
ob["server"] = host
ob["server_port"] = int(port)
return ob
def parse_http_proxy(url: str, tag: str) -> dict:
"""
http://[user:pass@]host:port[#remark] – plain HTTP CONNECT proxy
https://[user:pass@]host:port[#remark] – HTTP CONNECT proxy over TLS
"""
scheme = url.split("://")[0].lower()
userinfo, host, port, _ = _parse_url_parts(url, scheme)
ob: dict = {"type": "http", "tag": tag}
if userinfo and ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
ob["server"] = host
ob["server_port"] = int(port)
if scheme == "https":
ob["tls"] = {"enabled": True, "server_name": host}
return ob
PARSERS = {
"vless": parse_vless,
"vmess": parse_vmess,
"trojan": parse_trojan,
"ss": parse_shadowsocks,
"hysteria2": parse_hysteria2,
"hy2": parse_hysteria2,
"tuic": parse_tuic,
"socks5": parse_socks,
"socks5h": parse_socks,
"socks4": parse_socks,
"socks4a": parse_socks,
"http": parse_http_proxy,
"https": parse_http_proxy,
}
from proxy_url_parsers import PARSERS
def main() -> None:
+1 -334
View File
@@ -23,340 +23,7 @@ import sys
import urllib.parse
import urllib.request
# ---------------------------------------------------------------------------
# Proxy URL parsers (identical to build-outbound.py)
# ---------------------------------------------------------------------------
def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query))
def parse_vless(url: str, tag: str) -> dict:
rest = url[len("vless://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
ob: dict = {
"type": "vless",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": userinfo,
"packet_encoding": "xudp",
}
security = params.get("security", "none")
transport = params.get("type", "tcp")
if security == "reality":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
"reality": {
"enabled": True,
"public_key": params["pbk"],
"short_id": params.get("sid", ""),
},
}
elif security == "tls":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws":
ob["transport"] = {
"type": "ws",
"path": urllib.parse.unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", host)},
}
elif transport == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
elif transport == "h2":
ob["transport"] = {
"type": "http",
"host": [params.get("host", host)],
"path": urllib.parse.unquote(params.get("path", "/")),
}
flow = urllib.parse.unquote(params.get("flow", ""))
if flow:
ob["flow"] = flow
return ob
def parse_vmess(url: str, tag: str) -> dict:
b64 = url[len("vmess://"):]
pad = "=" * (-len(b64) % 4)
try:
data = json.loads(base64.b64decode(b64 + pad))
except Exception:
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
host = str(data["add"])
port = int(data["port"])
net = data.get("net", "tcp")
tls_field = str(data.get("tls", ""))
sni = str(data.get("sni") or data.get("host") or host)
ob: dict = {
"type": "vmess",
"tag": tag,
"server": host,
"server_port": port,
"uuid": data["id"],
"security": data.get("scy", "auto"),
"alter_id": int(data.get("aid", 0)),
}
if tls_field in ("tls", "reality"):
ob["tls"] = {"enabled": True, "server_name": sni}
if data.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
if data.get("alpn"):
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
path = str(data.get("path") or "/")
h_host = str(data.get("host") or host)
if net == "ws":
ob["transport"] = {
"type": "ws",
"path": path,
"headers": {"Host": h_host},
}
elif net == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": path.lstrip("/"),
}
elif net in ("h2", "http"):
ob["transport"] = {
"type": "http",
"host": [h_host],
"path": path,
}
return ob
def parse_trojan(url: str, tag: str) -> dict:
rest = url[len("trojan://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
password = urllib.parse.unquote(userinfo)
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
transport = params.get("type", "tcp")
ob: dict = {
"type": "trojan",
"tag": tag,
"server": host,
"server_port": int(port),
"password": password,
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
},
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws":
ob["transport"] = {
"type": "ws",
"path": urllib.parse.unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", host)},
}
elif transport == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
return ob
def parse_shadowsocks(url: str, tag: str) -> dict:
rest = url[len("ss://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, _ = rest.partition("?")
host, _, port = hostpart.rpartition(":")
pad = "=" * (-len(userinfo) % 4)
try:
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
if ":" not in decoded:
raise ValueError
method, password = decoded.split(":", 1)
except Exception:
plain = urllib.parse.unquote(userinfo)
method, password = plain.split(":", 1)
return {
"type": "shadowsocks",
"tag": tag,
"server": host,
"server_port": int(port),
"method": method,
"password": password,
}
def parse_hysteria2(url: str, tag: str) -> dict:
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
ob: dict = {
"type": "hysteria2",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"insecure": params.get("insecure", "0") == "1",
},
}
if params.get("obfs") == "salamander":
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
return ob
def parse_tuic(url: str, tag: str) -> dict:
rest = url[len("tuic://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
uuid, _, password = userinfo.partition(":")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
alpn_raw = params.get("alpn", "h3")
alpn = [a for a in alpn_raw.split(",") if a]
return {
"type": "tuic",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": uuid,
"password": urllib.parse.unquote(password),
"congestion_control": params.get("congestion_control", "bbr"),
"udp_relay_mode": params.get("udp_relay_mode", "native"),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"alpn": alpn,
},
}
def parse_socks(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5"
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
ob: dict = {
"type": "socks",
"tag": tag,
"version": version,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob["server"] = host
ob["server_port"] = int(port)
return ob
def parse_http_proxy(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
ob: dict = {
"type": "http",
"tag": tag,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob["server"] = host
ob["server_port"] = int(port)
if scheme == "https":
ob["tls"] = {"enabled": True, "server_name": host}
return ob
PARSERS = {
"vless": parse_vless,
"vmess": parse_vmess,
"trojan": parse_trojan,
"ss": parse_shadowsocks,
"hysteria2": parse_hysteria2,
"hy2": parse_hysteria2,
"tuic": parse_tuic,
"socks5": parse_socks,
"socks5h": parse_socks,
"socks4": parse_socks,
"socks4a": parse_socks,
"http": parse_http_proxy,
"https": parse_http_proxy,
}
from proxy_url_parsers import PARSERS
# ---------------------------------------------------------------------------
+301
View File
@@ -0,0 +1,301 @@
#!/usr/bin/env python3
import base64
import json
import urllib.parse
def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query))
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
rest = url[len(f"{scheme}://"):]
rest, _, _ = rest.partition("#")
if "@" in rest:
userinfo, _, rest = rest.partition("@")
else:
userinfo = ""
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
return userinfo, host, port, _qs(query)
def _mk_transport(
transport_type: str,
path: str = "/",
host_header: str = "",
service_name: str = "",
) -> "dict | None":
if transport_type == "ws":
return {
"type": "ws",
"path": urllib.parse.unquote(path),
"headers": {"Host": host_header},
}
if transport_type == "grpc":
return {
"type": "grpc",
"service_name": urllib.parse.unquote(service_name),
}
if transport_type == "h2":
return {
"type": "http",
"host": [host_header],
"path": urllib.parse.unquote(path),
}
return None
def parse_vless(url: str, tag: str) -> dict:
userinfo, host, port, params = _parse_url_parts(url, "vless")
security = params.get("security", "none")
transport = params.get("type", "tcp")
ob: dict = {
"type": "vless",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": userinfo,
"packet_encoding": "xudp",
}
if security == "reality":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
"reality": {
"enabled": True,
"public_key": params["pbk"],
"short_id": params.get("sid", ""),
},
}
elif security == "tls":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
tr = _mk_transport(
transport,
path=params.get("path", "/"),
host_header=params.get("host", host),
service_name=params.get("serviceName", ""),
)
if tr is not None:
ob["transport"] = tr
flow = urllib.parse.unquote(params.get("flow", ""))
if flow:
ob["flow"] = flow
return ob
def parse_vmess(url: str, tag: str) -> dict:
b64 = url[len("vmess://"):]
pad = "=" * (-len(b64) % 4)
try:
data = json.loads(base64.b64decode(b64 + pad))
except Exception:
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
host = str(data["add"])
port = int(data["port"])
net = data.get("net", "tcp")
tls_field = str(data.get("tls", ""))
sni = str(data.get("sni") or data.get("host") or host)
ob: dict = {
"type": "vmess",
"tag": tag,
"server": host,
"server_port": port,
"uuid": data["id"],
"security": data.get("scy", "auto"),
"alter_id": int(data.get("aid", 0)),
}
if tls_field in ("tls", "reality"):
ob["tls"] = {"enabled": True, "server_name": sni}
if data.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
if data.get("alpn"):
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
path = str(data.get("path") or "/")
h_host = str(data.get("host") or host)
tr = _mk_transport(
net if net != "http" else "h2",
path=path,
host_header=h_host,
service_name=path.lstrip("/"),
)
if tr is not None:
ob["transport"] = tr
return ob
def parse_trojan(url: str, tag: str) -> dict:
userinfo, host, port, params = _parse_url_parts(url, "trojan")
transport = params.get("type", "tcp")
ob: dict = {
"type": "trojan",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
},
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
tr = _mk_transport(
transport,
path=params.get("path", "/"),
host_header=params.get("host", host),
service_name=params.get("serviceName", ""),
)
if tr is not None:
ob["transport"] = tr
return ob
def parse_shadowsocks(url: str, tag: str) -> dict:
rest = url[len("ss://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, _ = rest.partition("?")
host, _, port = hostpart.rpartition(":")
pad = "=" * (-len(userinfo) % 4)
try:
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
if ":" not in decoded:
raise ValueError
method, password = decoded.split(":", 1)
except Exception:
plain = urllib.parse.unquote(userinfo)
method, password = plain.split(":", 1)
return {
"type": "shadowsocks",
"tag": tag,
"server": host,
"server_port": int(port),
"method": method,
"password": password,
}
def parse_hysteria2(url: str, tag: str) -> dict:
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
userinfo, host, port, params = _parse_url_parts(url, scheme)
ob: dict = {
"type": "hysteria2",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"insecure": params.get("insecure", "0") == "1",
},
}
if params.get("obfs") == "salamander":
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
return ob
def parse_tuic(url: str, tag: str) -> dict:
userinfo, host, port, params = _parse_url_parts(url, "tuic")
uuid, _, password = userinfo.partition(":")
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
return {
"type": "tuic",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": uuid,
"password": urllib.parse.unquote(password),
"congestion_control": params.get("congestion_control", "bbr"),
"udp_relay_mode": params.get("udp_relay_mode", "native"),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"alpn": alpn,
},
}
def parse_socks(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5"
userinfo, host, port, _ = _parse_url_parts(url, scheme)
ob: dict = {"type": "socks", "tag": tag, "version": version}
if userinfo and ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
ob["server"] = host
ob["server_port"] = int(port)
return ob
def parse_http_proxy(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
userinfo, host, port, _ = _parse_url_parts(url, scheme)
ob: dict = {"type": "http", "tag": tag}
if userinfo and ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
ob["server"] = host
ob["server_port"] = int(port)
if scheme == "https":
ob["tls"] = {"enabled": True, "server_name": host}
return ob
PARSERS = {
"vless": parse_vless,
"vmess": parse_vmess,
"trojan": parse_trojan,
"ss": parse_shadowsocks,
"hysteria2": parse_hysteria2,
"hy2": parse_hysteria2,
"tuic": parse_tuic,
"socks5": parse_socks,
"socks5h": parse_socks,
"socks4": parse_socks,
"socks4a": parse_socks,
"http": parse_http_proxy,
"https": parse_http_proxy,
}