From 7f76c4ffbbeaf4231b998f85bd2d0b5df3ca56d1 Mon Sep 17 00:00:00 2001 From: fufsob Date: Mon, 14 Sep 2026 02:54:54 +0000 Subject: [PATCH] feat: warp --- README.md | 8 + docs/options/index.md | 7 + docs/options/warp.md | 85 ++++++ modules/proxy-suite/default.nix | 65 +++-- modules/proxy-suite/derived.nix | 29 +- modules/proxy-suite/options/default.nix | 1 + modules/proxy-suite/options/warp.nix | 41 +++ modules/proxy-suite/service-assertions.nix | 269 +++++++++--------- modules/proxy-suite/service/context.nix | 4 + .../script-blocks/backend-jq-filter.nix | 5 +- .../service/script-blocks/outbounds.nix | 71 ++++- modules/proxy-suite/service/scripts.nix | 4 + modules/proxy-suite/warp.nix | 97 +++++++ nix/checks/module-suite.nix | 10 + nix/checks/parsers.nix | 9 + nix/checks/warp.nix | 169 +++++++++++ scripts/test-warp-outbound.py | 48 ++++ scripts/warp_outbound.py | 119 ++++++++ 18 files changed, 864 insertions(+), 177 deletions(-) create mode 100644 docs/options/warp.md create mode 100644 modules/proxy-suite/options/warp.nix create mode 100644 modules/proxy-suite/warp.nix create mode 100644 nix/checks/warp.nix create mode 100644 scripts/test-warp-outbound.py create mode 100644 scripts/warp_outbound.py diff --git a/README.md b/README.md index 6f301bb..6dea654 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github. - zapret DPI bypass, including zapret2, which learns blocked sites at runtime - AmneziaWG 1.x–3.x tunnels from `.conf`, `vpn://`, or Nix - Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel +- Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile - Server inbounds with share links, QR codes, per-user subscriptions and traffic stats - A tray indicator and the `proxy-ctl` CLI @@ -75,6 +76,13 @@ services.proxy-suite = { profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn"; }; + # Registers with wgcf on first start. The exit is Cloudflare, but geolocated to your own country. + warp = { + enable = true; + asOutbound = true; # tag "warp" + asAmneziaWg = true; # proxy-ctl awg on warp + }; + tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy-secret"; diff --git a/docs/options/index.md b/docs/options/index.md index 7e5e9aa..c0fe600 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -15,6 +15,7 @@ Update the module option docs there instead of editing these files by hand. - [tgWsProxy](./tgWsProxy.md) - [tray](./tray.md) - [userControl](./userControl.md) +- [warp](./warp.md) - [zapret](./zapret.md) ## Complete default config @@ -252,6 +253,12 @@ services.proxy-suite = { group = "proxy-suite"; perApp = { }; }; + warp = { + asAmneziaWg = false; + asOutbound = false; + configFile = null; + enable = false; + }; zapret = { cidrExemption = { cidrs = [ ]; diff --git a/docs/options/warp.md b/docs/options/warp.md new file mode 100644 index 0000000..cd4552c --- /dev/null +++ b/docs/options/warp.md @@ -0,0 +1,85 @@ +# services.proxy-suite.warp + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- warp + - [enable](#services-proxy-suite-warp-enable) + - [asAmneziaWg](#services-proxy-suite-warp-asamneziawg) + - [asOutbound](#services-proxy-suite-warp-asoutbound) + - [configFile](#services-proxy-suite-warp-configfile) + + +## services\.proxy-suite\.warp\.enable + +Whether to enable Cloudflare WARP\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.warp\.asAmneziaWg + +Add an AmneziaWG profile named “warp” (` proxy-ctl awg on warp `)\. Requires amneziaWg\.enable\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.warp\.asOutbound + +Add WARP as an outbound tagged “warp”\. sing-box runs it as a WireGuard endpoint, +XRay as a wireguard outbound\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.warp\.configFile + +Runtime path to a WireGuard profile for WARP, as written by ` wgcf register && wgcf generate `\. +Junk-packet lines (Jc, Jmin, Jmax) are honoured by the AmneziaWG profile only\. + +When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare’s terms) +into /var/lib/proxy-suite/warp, through the local proxy when proxy\.enable is set, and +retries until it succeeds\. Until then the warp outbound blocks\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/wgcf-profile.conf" +``` diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index ce8bbc7..11fa431 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -87,30 +87,38 @@ in ; }) - (lib.mkIf (cfg.zapret.engine == "zapret-discord-youtube" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) ( - import ./zapret.nix { - inherit - lib - pkgs - cfg - zapret - ; - inherit (nftr) perAppZapretRulesFile nft; - } - )) + (lib.mkIf + ( + cfg.zapret.engine == "zapret-discord-youtube" + && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable) + ) + ( + import ./zapret.nix { + inherit + lib + pkgs + cfg + zapret + ; + inherit (nftr) perAppZapretRulesFile nft; + } + ) + ) - (lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) ( - import ./zapret2.nix { - inherit - lib - pkgs - cfg - packages - ; - inherit (nftr) perAppZapretRulesFile nft; - zapret2Sources = { inherit nfqws2-keenetic z2k; }; - } - )) + (lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) + ( + import ./zapret2.nix { + inherit + lib + pkgs + cfg + packages + ; + inherit (nftr) perAppZapretRulesFile nft; + zapret2Sources = { inherit nfqws2-keenetic z2k; }; + } + ) + ) (lib.mkIf cfg.tgWsProxy.enable ( import ./tg-ws-proxy.nix { @@ -135,6 +143,17 @@ in } )) + (lib.mkIf cfg.warp.enable ( + import ./warp.nix { + inherit + lib + pkgs + cfg + derived + ; + } + )) + (lib.mkIf cfg.amneziaWg.enable ( import ./amnezia-wg.nix { inherit diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 699f896..71503a7 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -34,6 +34,17 @@ let # Only sing-box dials SSH natively; XRay and standalone tunnels use the OpenSSH unit. sshProxyNativeOutbound = sshProxyOutboundEnabled && !pureXrayEnabled; sshProxyUnitEnabled = sshProxyCfg.enable && !sshProxyNativeOutbound; + warpCfg = cfg.warp // { + # Without a configFile, proxy-suite-warp registers with wgcf into its state dir. + autoRegister = cfg.warp.enable && cfg.warp.configFile == null; + profilePath = + if cfg.warp.configFile != null then + cfg.warp.configFile + else + "/var/lib/proxy-suite/warp/wgcf-profile.conf"; + }; + warpOutboundTag = "warp"; + warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound; proxyInboundsCfg = cfg.inbounds; proxyInboundsEnabled = proxyInboundsCfg.enable; @@ -56,8 +67,7 @@ let ]; # Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay). - proxyInboundsResolveInSingBox = - !pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds; + proxyInboundsResolveInSingBox = !pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds; proxyInboundsGuardPrivate = proxyInboundsEnabled @@ -113,12 +123,16 @@ let "block" ]; outboundTags = map (ob: ob.tag) proxyCfg.outbounds; - effectiveOutboundTags = outboundTags ++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag; + effectiveOutboundTags = + outboundTags + ++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag + ++ lib.optional warpOutboundEnabled warpOutboundTag; subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions; hasStaticOutbounds = proxyCfg.outbounds != [ ]; hasSubscriptions = proxyCfg.subscriptions != [ ]; - hasAvailableOutbounds = hasStaticOutbounds || hasSubscriptions || sshProxyOutboundEnabled; + hasAvailableOutbounds = + hasStaticOutbounds || hasSubscriptions || sshProxyOutboundEnabled || warpOutboundEnabled; collapseNamedOutbounds = selectionMode == "first"; clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first"; perAppZapretEnabled = perAppZapretCfg.enable; @@ -182,7 +196,9 @@ let }; # Subscription tags are deliberately not accepted: they only exist at runtime. - invalidInboundViaTargets = builtins.filter (tag: !builtins.elem tag outboundTags) proxyInboundViaTags; + invalidInboundViaTargets = builtins.filter ( + tag: !builtins.elem tag outboundTags + ) proxyInboundViaTags; invalidRoutingTargets = lib.unique ( map (rule: rule.outbound) ( @@ -222,6 +238,9 @@ in sshProxyOutboundEnabled sshProxyNativeOutbound sshProxyUnitEnabled + warpCfg + warpOutboundTag + warpOutboundEnabled proxyInboundsCfg proxyInboundsEnabled proxyInbounds diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index d0d3d2d..524b60c 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -14,6 +14,7 @@ ./zapret2.nix ./amnezia-wg.nix ./ssh-proxy.nix + ./warp.nix ./tg-ws-proxy.nix ./geodata.nix ./tray.nix diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix new file mode 100644 index 0000000..7a1e450 --- /dev/null +++ b/modules/proxy-suite/options/warp.nix @@ -0,0 +1,41 @@ +{ lib, ... }: + +let + inherit (lib) mkEnableOption mkOption types; +in +{ + options.services.proxy-suite.warp = { + enable = mkEnableOption "Cloudflare WARP"; + + configFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a WireGuard profile for WARP, as written by `wgcf register && wgcf generate`. + Junk-packet lines (Jc, Jmin, Jmax) are honoured by the AmneziaWG profile only. + + When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare's terms) + into /var/lib/proxy-suite/warp, through the local proxy when proxy.enable is set, and + retries until it succeeds. Until then the warp outbound blocks. + ''; + example = "/run/secrets/wgcf-profile.conf"; + }; + + asOutbound = mkOption { + type = types.bool; + default = false; + description = '' + Add WARP as an outbound tagged "warp". sing-box runs it as a WireGuard endpoint, + XRay as a wireguard outbound. + ''; + }; + + asAmneziaWg = mkOption { + type = types.bool; + default = false; + description = '' + Add an AmneziaWG profile named "warp" (`proxy-ctl awg on warp`). Requires amneziaWg.enable. + ''; + }; + }; +} diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 2208f7a..0736bee 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -73,21 +73,32 @@ let (requireEnabled cfg.sshProxy.asOutbound proxyEnabled "proxy-suite: sshProxy.asOutbound requires proxy.enable = true" ) + (mkAssertion ( + !cfg.warp.enable || cfg.warp.asOutbound || cfg.warp.asAmneziaWg + ) "proxy-suite: warp.enable = true needs warp.asOutbound or warp.asAmneziaWg") + (requireEnabled derived.warpOutboundEnabled proxyEnabled + "proxy-suite: warp.asOutbound requires proxy.enable = true" + ) + (requireEnabled ( + cfg.warp.enable && cfg.warp.asAmneziaWg + ) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true") (requireEnabled proxyCfg.autoProxy.enable proxyEnabled "proxy-suite: proxy.autoProxy.enable requires proxy.enable = true" ) (mkAssertion (!(proxyCfg.autoProxy.enable && pureXrayEnabled)) "proxy-suite: proxy.autoProxy needs the sing-box backend: learned routes are local rule-sets that sing-box reloads from disk, and pure XRay has no equivalent" ) - (mkAssertion ( - !cfg.sshProxy.enable || (cfg.sshProxy.server.user != null && cfg.sshProxy.server.host != null) - ) "proxy-suite: sshProxy.server.user and sshProxy.server.host are required when sshProxy.enable = true") + (mkAssertion + (!cfg.sshProxy.enable || (cfg.sshProxy.server.user != null && cfg.sshProxy.server.host != null)) + "proxy-suite: sshProxy.server.user and sshProxy.server.host are required when sshProxy.enable = true" + ) # SingBox dials SSH itself and verifies host keys by value, with no # knownHostsFile and no trust-on-first-use fallback. An empty list accepts # any host key, so refuse rather than silently downgrade the tunnel. - (mkAssertion ( - !derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null - ) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p ` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm.") + (mkAssertion + (!derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null) + "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p ` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm." + ) (mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ]) "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}" ) @@ -104,9 +115,9 @@ let (requireEnabled globalTproxy.enable proxyEnabled "proxy-suite: proxy.tproxy.enable requires proxy.enable = true" ) - (requireEnabled (proxyCfg.autostart == "tun") globalTun.enable - ''proxy-suite: proxy.autostart = "tun" requires proxy.tun.enable = true'' - ) + (requireEnabled ( + proxyCfg.autostart == "tun" + ) globalTun.enable ''proxy-suite: proxy.autostart = "tun" requires proxy.tun.enable = true'') (requireEnabled (proxyCfg.autostart == "tproxy") globalTproxy.enable ''proxy-suite: proxy.autostart = "tproxy" requires proxy.tproxy.enable = true'' ) @@ -199,15 +210,15 @@ let (mkAssertion ( !singBoxEnabled || hybridEnabled || ob.xrayJson == null ) "proxy-suite: outbound '${ob.tag}': xrayJson requires proxy.backend = xray or hybrid") - (mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null)) - "proxy-suite: outbound '${ob.tag}': singBoxJson/json require proxy.backend = sing-box or hybrid" - ) + (mkAssertion ( + !xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null) + ) "proxy-suite: outbound '${ob.tag}': singBoxJson/json require proxy.backend = sing-box or hybrid") (mkAssertion ( !(ob.backend == "xray") || xrayEnabled ) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.backend = xray or hybrid") - (mkAssertion ( - !(ob.backend == "sing-box") || singBoxEnabled - ) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid") + (mkAssertion (!(ob.backend == "sing-box") || singBoxEnabled) + "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid" + ) ]) proxyCfg.outbounds; proxyInboundsCfg = derived.proxyInboundsCfg; @@ -218,132 +229,118 @@ let # A pinned outbound is rendered by the XRay renderer inside the inbound # service, so a sing-box-only definition cannot serve as one. singBoxOnlyPinnedTags = map (ob: ob.tag) ( - builtins.filter ( - ob: ob.singBoxJson != null || ob.json != null - ) derived.proxyInboundViaOutbounds + builtins.filter (ob: ob.singBoxJson != null || ob.json != null) derived.proxyInboundViaOutbounds ); - proxyInboundAssertions = + proxyInboundAssertions = [ + (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) + "proxy-suite: inbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those." + ) + (mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ]) + "proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson." + ) + (requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled + "proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true" + ) + (requireEnabled proxyInboundsEnabled ( + proxyInbounds != [ ] + ) "proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners") + (requireEnabled proxyInboundsNeedLocalProxy proxyEnabled + "proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node." + ) + (requireEnabled proxyInboundsNeedLocalProxy derived.hasAvailableOutbounds + "proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required" + ) + (uniqueValues proxyInboundsEnabled (map ( + ib: ib.listener.port + ) proxyInbounds) "proxy-suite: inbounds.listeners must each use a distinct port") + (requireEnabled (proxyInboundsEnabled && proxyInboundsCfg.subscriptions.enable) + proxyInboundsCfg.shareLinks + "proxy-suite: inbounds.subscriptions are made of the share links, so they need inbounds.shareLinks = true" + ) + (mkAssertion + ( + !proxyInboundsEnabled + || !proxyEnabled + || !builtins.elem proxyCfg.listener.port derived.proxyInboundPorts + ) + "proxy-suite: a proxyInbounds listener port collides with proxy.listener.port (${toString proxyCfg.listener.port})" + ) + (mkAssertion + ( + !proxyInboundsEnabled + || !globalTproxy.enable + || !builtins.elem globalTproxy.port derived.proxyInboundPorts + ) + "proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})" + ) + ] + ++ lib.concatMap ( + ib: + let + l = ib.listener; + prefix = "proxy-suite: inbounds listener '${ib.tag}'"; + firstUser = if l.users == [ ] then null else builtins.head l.users; + needsUuid = builtins.elem l.type [ + "vless" + "vmess" + ]; + needsPassword = builtins.elem l.type [ + "trojan" + "shadowsocks" + "socks" + "http" + ]; + tlsTerminated = l.tls.enable || l.type == "trojan"; + in [ - (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) - "proxy-suite: inbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those." - ) - (mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ]) - "proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson." - ) - (requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled - "proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true" - ) - (requireEnabled proxyInboundsEnabled (proxyInbounds != [ ]) - "proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners" - ) - (requireEnabled proxyInboundsNeedLocalProxy proxyEnabled - "proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node." - ) - (requireEnabled proxyInboundsNeedLocalProxy derived.hasAvailableOutbounds - "proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required" - ) - (uniqueValues proxyInboundsEnabled (map (ib: ib.listener.port) proxyInbounds) - "proxy-suite: inbounds.listeners must each use a distinct port" - ) - (requireEnabled (proxyInboundsEnabled && proxyInboundsCfg.subscriptions.enable) - proxyInboundsCfg.shareLinks - "proxy-suite: inbounds.subscriptions are made of the share links, so they need inbounds.shareLinks = true" - ) - (mkAssertion - ( - !proxyInboundsEnabled - || !proxyEnabled - || !builtins.elem proxyCfg.listener.port derived.proxyInboundPorts - ) - "proxy-suite: a proxyInbounds listener port collides with proxy.listener.port (${toString proxyCfg.listener.port})" - ) - (mkAssertion - ( - !proxyInboundsEnabled - || !globalTproxy.enable - || !builtins.elem globalTproxy.port derived.proxyInboundPorts - ) - "proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})" + (exactlyOneOf proxyInboundsEnabled [ + l.type + l.xrayJson + l.jsonFile + ] "${prefix}: set exactly one of type, xrayJson, or jsonFile") + (mkAssertion ( + !proxyInboundsEnabled || !(l.tls.enable && l.reality.enable) + ) "${prefix}: tls.enable and reality.enable are mutually exclusive") + (mkAssertion ( + !proxyInboundsEnabled || l.type == null || l.users != [ ] + ) "${prefix}: at least one entry in users is required") + (exactlyOneOf (proxyInboundsEnabled && needsUuid && firstUser != null) [ + firstUser.uuid + firstUser.uuidFile + ] "${prefix}: ${toString l.type} users need exactly one of uuid or uuidFile") + (exactlyOneOf (proxyInboundsEnabled && needsPassword && firstUser != null) [ + firstUser.password + firstUser.passwordFile + ] "${prefix}: ${toString l.type} users need exactly one of password or passwordFile") + (exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [ + l.reality.privateKey + l.reality.privateKeyFile + ] "${prefix}: reality needs exactly one of privateKey or privateKeyFile") + (mkAssertion ( + !proxyInboundsEnabled || !l.reality.enable || l.reality.serverNames != [ ] + ) "${prefix}: reality.serverNames must not be empty") + (requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks) + (l.reality.publicKey != null) + "${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set inbounds.shareLinks = false." ) + (mkAssertion ( + !proxyInboundsEnabled + || !tlsTerminated + || l.reality.enable + || (l.tls.certificateFile != null && l.tls.keyFile != null) + ) "${prefix}: TLS termination needs both tls.certificateFile and tls.keyFile") + (mkAssertion ( + !proxyInboundsEnabled || l.flow == null || (l.type == "vless" && l.transport.type == "raw") + ) "${prefix}: flow is only valid on a vless listener with transport.type = \"raw\"") + (mkAssertion ( + !proxyInboundsEnabled + || l.tls.alpn == null + || !builtins.elem "h3" l.tls.alpn + || (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable) + ) "${prefix}: tls.alpn \"h3\" is served only by the xhttp transport with tls.enable (not REALITY)") ] - ++ lib.concatMap ( - ib: - let - l = ib.listener; - prefix = "proxy-suite: inbounds listener '${ib.tag}'"; - firstUser = if l.users == [ ] then null else builtins.head l.users; - needsUuid = builtins.elem l.type [ - "vless" - "vmess" - ]; - needsPassword = builtins.elem l.type [ - "trojan" - "shadowsocks" - "socks" - "http" - ]; - tlsTerminated = l.tls.enable || l.type == "trojan"; - in - [ - (exactlyOneOf proxyInboundsEnabled [ - l.type - l.xrayJson - l.jsonFile - ] "${prefix}: set exactly one of type, xrayJson, or jsonFile") - (mkAssertion ( - !proxyInboundsEnabled || !(l.tls.enable && l.reality.enable) - ) "${prefix}: tls.enable and reality.enable are mutually exclusive") - (mkAssertion ( - !proxyInboundsEnabled || l.type == null || l.users != [ ] - ) "${prefix}: at least one entry in users is required") - (exactlyOneOf (proxyInboundsEnabled && needsUuid && firstUser != null) [ - firstUser.uuid - firstUser.uuidFile - ] "${prefix}: ${toString l.type} users need exactly one of uuid or uuidFile") - (exactlyOneOf (proxyInboundsEnabled && needsPassword && firstUser != null) [ - firstUser.password - firstUser.passwordFile - ] "${prefix}: ${toString l.type} users need exactly one of password or passwordFile") - (exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [ - l.reality.privateKey - l.reality.privateKeyFile - ] "${prefix}: reality needs exactly one of privateKey or privateKeyFile") - (mkAssertion ( - !proxyInboundsEnabled || !l.reality.enable || l.reality.serverNames != [ ] - ) "${prefix}: reality.serverNames must not be empty") - (requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks) - (l.reality.publicKey != null) - "${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set inbounds.shareLinks = false." - ) - (mkAssertion - ( - !proxyInboundsEnabled - || !tlsTerminated - || l.reality.enable - || (l.tls.certificateFile != null && l.tls.keyFile != null) - ) - "${prefix}: TLS termination needs both tls.certificateFile and tls.keyFile" - ) - (mkAssertion - ( - !proxyInboundsEnabled - || l.flow == null - || (l.type == "vless" && l.transport.type == "raw") - ) - "${prefix}: flow is only valid on a vless listener with transport.type = \"raw\"" - ) - (mkAssertion - ( - !proxyInboundsEnabled - || l.tls.alpn == null - || !builtins.elem "h3" l.tls.alpn - || (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable) - ) - "${prefix}: tls.alpn \"h3\" is served only by the xhttp transport with tls.enable (not REALITY)" - ) - ] - ) proxyInbounds; + ) proxyInbounds; subscriptionAssertions = lib.concatMap (sub: [ (exactlyOneOf proxyEnabled [ diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 629acf4..f9e5800 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -49,6 +49,7 @@ let sshProxyCfg sshProxyOutboundEnabled sshProxyUnitEnabled + warpCfg proxyInboundsCfg proxyInboundsEnabled proxyInboundsNeedLocalProxy @@ -75,6 +76,7 @@ let proxySuiteScriptsDir = ../../../scripts; parserScriptsPythonPath = proxySuiteScriptsDir; buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py"; + warpOutboundPy = "${proxySuiteScriptsDir}/warp_outbound.py"; buildInboundPy = "${proxySuiteScriptsDir}/build-inbound.py"; fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py"; @@ -91,6 +93,7 @@ let singBoxCfg proxyCfg sshProxyCfg + warpCfg xrayEnabled hybridEnabled pureXrayEnabled @@ -109,6 +112,7 @@ let xray parserScriptsPythonPath buildOutboundPy + warpOutboundPy buildInboundPy fetchSubscriptionPy ; diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index 3b1bae6..5a663f6 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -87,7 +87,10 @@ else [.route.rules[] | select(((.action? // "") == "hijack-dns") and (((.inbound? // []) | index("xray-dns-in")) != null))]; - .outbounds = $obs + .outbounds + # sing-box runs WireGuard as an endpoint, not an outbound. + .outbounds = ($obs | map(select(.type != "wireguard"))) + .outbounds + | ($obs | map(select(.type == "wireguard"))) as $endpoints + | if $endpoints == [] then . else .endpoints = (.endpoints // []) + $endpoints end | if $auth_enabled then (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] else . end diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 10accd8..24a155e 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -4,6 +4,7 @@ singBoxCfg, proxyCfg, sshProxyCfg, + warpCfg, pureXrayEnabled, hybridEnabled, collapseNamedOutbounds, @@ -17,6 +18,7 @@ python3, parserScriptsPythonPath, buildOutboundPy, + warpOutboundPy, mkSubscriptionBlock, mkSubscriptionLoadHelperBlock, runtimeSubscriptionsBlock, @@ -293,18 +295,16 @@ let sshProxyCfg.server.host else "[${sshProxyCfg.server.host}]:${toString sshProxyCfg.server.port}"; - hostKeyFileBlock = - lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null) - '' - SSH_HOST_KEYS=$(${pkgs.openssh}/bin/ssh-keygen -F ${lib.escapeShellArg knownHostsTarget} \ - -f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \ - | ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))') - if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then - echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2 - exit 1 - fi - OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON") - ''; + hostKeyFileBlock = lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null) '' + SSH_HOST_KEYS=$(${pkgs.openssh}/bin/ssh-keygen -F ${lib.escapeShellArg knownHostsTarget} \ + -f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \ + | ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))') + if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then + echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2 + exit 1 + fi + OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON") + ''; in '' # outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"}) @@ -319,6 +319,49 @@ let _proxy_suite_record_tag_source ${sshProxyTag} ssh ''; + # The profile is a secret, so it is converted at start rather than baked into the store. + # Hybrid runs WARP in sing-box, like the SSH outbound. + mkWarpOutboundBlock = + routingMark: + let + markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"; + profile = lib.escapeShellArg warpCfg.profilePath; + convert = '' + OB_JSON=$(${python3} ${warpOutboundPy} --backend ${ + if pureXrayEnabled then "xray" else "sing-box" + } --tag warp${markArg} < ${profile}) || exit 1 + ''; + blockJson = + if pureXrayEnabled then + ''{"protocol":"blackhole","tag":"warp","settings":{}}'' + else + ''{"type":"block","tag":"warp"}''; + in + '' + # outbound: warp (${if pureXrayEnabled then "XRay wireguard" else "sing-box WireGuard endpoint"}) + ${ + if warpCfg.autoRegister then + '' + if [ -s ${profile} ]; then + ${convert} + else + # proxy-suite-warp restarts this service once wgcf has registered. + echo "proxy-suite: warning: no WARP profile yet; warp blocks until proxy-suite-warp registers" >&2 + OB_JSON='${blockJson}' + fi + '' + else + convert + } + ${ + if hybridEnabled then + ''_proxy_suite_add_sing_box_ob "$OB_JSON"'' + else + ''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")'' + } + _proxy_suite_record_tag_source warp warp + ''; + mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock; runtimeOutboundsBlock = '' @@ -377,6 +420,9 @@ let ) proxyCfg.subscriptions; sshProxyBlock = lib.optionalString sshProxyCfg.asOutbound (mkSshProxyOutboundBlock routingMark); + warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound) ( + mkWarpOutboundBlock routingMark + ); wrapperBlock = if pureXrayEnabled && selectionMode == "urltest" then @@ -445,6 +491,7 @@ let + runtimeSubscriptionsBlock + runtimeOutboundsBlock + sshProxyBlock + + warpBlock + requireOutboundsBlock + pinBlock + inventoryBlock diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 766d93f..75f9f70 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -5,6 +5,7 @@ singBoxCfg, proxyCfg, sshProxyCfg, + warpCfg, xrayEnabled, hybridEnabled, pureXrayEnabled, @@ -21,6 +22,7 @@ xray, parserScriptsPythonPath, buildOutboundPy, + warpOutboundPy, fetchSubscriptionPy, tproxyFile, tunFile, @@ -109,6 +111,7 @@ let singBoxCfg proxyCfg sshProxyCfg + warpCfg pureXrayEnabled hybridEnabled collapseNamedOutbounds @@ -122,6 +125,7 @@ let python3 parserScriptsPythonPath buildOutboundPy + warpOutboundPy mkSubscriptionBlock mkSubscriptionLoadHelperBlock runtimeSubscriptionsBlock diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix new file mode 100644 index 0000000..5257d74 --- /dev/null +++ b/modules/proxy-suite/warp.nix @@ -0,0 +1,97 @@ +# Cloudflare WARP: the AmneziaWG profile and, without a configFile, wgcf registration. +{ + lib, + pkgs, + cfg, + derived, +}: + +let + w = derived.warpCfg; + listener = cfg.proxy.listener; + auth = listener.auth; + host = + if + builtins.elem listener.address [ + "0.0.0.0" + "::" + ] + then + "127.0.0.1" + else + listener.address; + hostPart = if lib.hasInfix ":" host then "[${host}]" else host; + passwordSource = + if auth.passwordFile != null then + auth.passwordFile + else if auth.password != null then + pkgs.writeText "proxy-suite-warp-proxy-password" auth.password + else + null; + userinfo = lib.optionalString (auth.username != null && passwordSource != null) '' + userinfo=$(${pkgs.jq}/bin/jq -rn --arg u ${lib.escapeShellArg auth.username} \ + --rawfile p ${lib.escapeShellArg passwordSource} '"\($u | @uri):\($p | rtrimstr("\n") | @uri)@"') + ''; + + registerScript = pkgs.writeShellScript "proxy-suite-warp-register" '' + set -euo pipefail + [ -s wgcf-profile.conf ] && exit 0 + + register() { + [ -s wgcf-account.toml ] || wgcf register --accept-tos + wgcf generate + } + + ${ + if cfg.proxy.enable then + '' + # The API is blocked in some countries, so the local proxy goes first. It may + # still be coming up, as when a switch restarts it alongside this unit. + for _ in {1..30}; do + (exec 3<>/dev/tcp/${host}/${toString listener.port}) 2>/dev/null && break + sleep 1 + done + userinfo= + ${userinfo} + HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" register || register + ${lib.optionalString w.asOutbound "${pkgs.systemd}/bin/systemctl --no-block try-restart proxy-suite-socks.service"} + '' + else + "register" + } + ''; +in +{ + services.proxy-suite.amneziaWg.profiles = lib.mkIf w.asAmneziaWg { + warp.configFile = w.profilePath; + }; + + systemd.services = lib.mkIf w.autoRegister { + proxy-suite-warp = { + description = "proxy-suite - register a Cloudflare WARP device with wgcf"; + after = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + path = [ pkgs.wgcf ]; + # Retried until it registers. Not a oneshot: a slow or failed registration must not + # hold up or fail a switch. + startLimitIntervalSec = 0; + serviceConfig = { + Type = "simple"; + RemainAfterExit = true; + Restart = "on-failure"; + RestartSec = 30; + StateDirectory = "proxy-suite/warp"; + StateDirectoryMode = "0700"; + WorkingDirectory = "/var/lib/proxy-suite/warp"; + UMask = "0077"; + ExecStart = registerScript; + }; + }; + + # Only pulls registration in: a simple unit gives the profile no ordering guarantee. + proxy-suite-awg-warp = lib.mkIf w.asAmneziaWg { + wants = [ "proxy-suite-warp.service" ]; + }; + }; +} diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index e2f9f2d..37a3e72 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -117,6 +117,15 @@ let ; }; + warpChecks = import ./warp.nix { + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + ; + }; + proxyInboundsChecks = import ./proxy-inbounds.nix { inherit pkgs @@ -238,6 +247,7 @@ let ++ coreProxyChecks.assertions ++ localProxyAuthChecks.assertions ++ sshProxyChecks.assertions + ++ warpChecks.assertions ++ proxyInboundsChecks.assertions ++ tgWsProxyChecks.assertions ++ xrayBackendChecks.assertions diff --git a/nix/checks/parsers.nix b/nix/checks/parsers.nix index 82047a4..dc25910 100644 --- a/nix/checks/parsers.nix +++ b/nix/checks/parsers.nix @@ -28,6 +28,15 @@ touch "$out" ''; + warp-outbound-parser = + pkgs.runCommand "warp-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } + '' + export PYTHONDONTWRITEBYTECODE=1 + export PYTHONPATH=${../../scripts}:$PYTHONPATH + python ${../../scripts/test-warp-outbound.py} + touch "$out" + ''; + amneziawg-config-parser = pkgs.runCommand "amneziawg-config-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } '' diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix new file mode 100644 index 0000000..11f73c6 --- /dev/null +++ b/nix/checks/warp.nix @@ -0,0 +1,169 @@ +{ + pkgs, + evalProxySuite, + mkBadProxySuiteFixture, + mkFailingAssertions, +}: + +let + generated = import ./read-generated.nix; + inherit (pkgs.lib) hasInfix; + + profile = "/run/secrets/wgcf-profile.conf"; + markOf = fixture: toString fixture.config.services.proxy-suite.proxy.tproxy.proxyMark; + + mkFixture = + backend: warp: + evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + warp = { + enable = true; + configFile = profile; + } + // warp; + proxy = { + enable = true; + inherit backend; + }; + }; + } + ]; + startOf = + fixture: + generated.readDerivation + fixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; + convertCall = + fixture: flag: + "warp_outbound.py --backend ${flag} --tag warp --routing-mark ${markOf fixture} < ${pkgs.lib.escapeShellArg profile}"; + + singBox = mkFixture "sing-box" { asOutbound = true; }; + singBoxStart = startOf singBox; + xray = mkFixture "xray" { asOutbound = true; }; + xrayStart = startOf xray; + hybrid = mkFixture "hybrid" { asOutbound = true; }; + hybridStart = startOf hybrid; + auto = mkFixture "sing-box" { + asOutbound = true; + configFile = null; + }; + autoStart = startOf auto; + + amneziaWg = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + amneziaWg.enable = true; + warp = { + enable = true; + configFile = profile; + asAmneziaWg = true; + }; + }; + } + ]; + + invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture [ + # Enabled but used for nothing. + { + enable = true; + warp = { + enable = true; + configFile = profile; + }; + } + # asOutbound without a backend. + { + enable = true; + warp = { + enable = true; + configFile = profile; + asOutbound = true; + }; + } + # asAmneziaWg without AmneziaWG. + { + enable = true; + warp = { + enable = true; + configFile = profile; + asAmneziaWg = true; + }; + } + # Tag collision with a declared outbound. + { + enable = true; + warp = { + enable = true; + configFile = profile; + asOutbound = true; + }; + proxy = { + enable = true; + outbounds = [ + { + tag = "warp"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + } + ]; +in +{ + assertions = [ + ( + assert hasInfix (convertCall singBox "sing-box") singBoxStart; + true + ) + ( + assert hasInfix "_proxy_suite_record_tag_source warp warp" singBoxStart; + true + ) + # The profile is read at start; the private key never reaches the store. + ( + assert !(hasInfix "PrivateKey" singBoxStart); + true + ) + ( + assert hasInfix (convertCall xray "xray") xrayStart; + true + ) + ( + assert hasInfix (convertCall hybrid "sing-box") hybridStart; + true + ) + ( + assert hasInfix "_proxy_suite_add_sing_box_ob \"$OB_JSON\"" hybridStart; + true + ) + ( + assert !(singBox.config.systemd.services ? "proxy-suite-warp"); + true + ) + ( + assert auto.config.systemd.services ? "proxy-suite-warp"; + true + ) + ( + assert hasInfix "if [ -s /var/lib/proxy-suite/warp/wgcf-profile.conf ]" autoStart; + true + ) + ( + assert hasInfix "OB_JSON='{\"type\":\"block\",\"tag\":\"warp\"}'" autoStart; + true + ) + ( + assert amneziaWg.config.services.proxy-suite.amneziaWg.profiles.warp.configFile == profile; + true + ) + ( + assert amneziaWg.config.systemd.services ? "proxy-suite-awg-warp"; + true + ) + ] + ++ invalidAssertions; +} diff --git a/scripts/test-warp-outbound.py b/scripts/test-warp-outbound.py new file mode 100644 index 0000000..e8ab4ee --- /dev/null +++ b/scripts/test-warp-outbound.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + +import unittest + +from warp_outbound import ConfigError, build + +WGCF = """[Interface] +PrivateKey = priv= +Address = 172.16.0.2/32, 2606:4700:110:8d58::2/128 +DNS = 1.1.1.1 +MTU = 1280 +[Peer] +PublicKey = pub= +AllowedIPs = 0.0.0.0/0, ::/0 +Endpoint = engage.cloudflareclient.com:2408 +""" + + +class WarpOutboundTest(unittest.TestCase): + def test_sing_box_endpoint(self): + ob = build(WGCF, "sing-box", "warp", 255) + self.assertEqual(ob["type"], "wireguard") + self.assertEqual(ob["address"], ["172.16.0.2/32", "2606:4700:110:8d58::2/128"]) + self.assertEqual(ob["private_key"], "priv=") + self.assertEqual(ob["routing_mark"], 255) + self.assertEqual( + ob["peers"], + [{"address": "engage.cloudflareclient.com", "port": 2408, "public_key": "pub=", "allowed_ips": ["0.0.0.0/0", "::/0"]}], + ) + + def test_xray_outbound(self): + ob = build(WGCF, "xray", "warp", None) + self.assertEqual(ob["protocol"], "wireguard") + self.assertEqual(ob["settings"]["secretKey"], "priv=") + self.assertEqual(ob["settings"]["peers"][0]["endpoint"], "engage.cloudflareclient.com:2408") + self.assertNotIn("streamSettings", ob) + + def test_ipv6_endpoint(self): + ob = build(WGCF.replace("engage.cloudflareclient.com:2408", "[2606:4700:d0::a29f:c001]:500"), "sing-box", "warp", None) + self.assertEqual((ob["peers"][0]["address"], ob["peers"][0]["port"]), ("2606:4700:d0::a29f:c001", 500)) + + def test_rejects_missing_peer(self): + with self.assertRaises(ConfigError): + build(WGCF.split("[Peer]")[0], "sing-box", "warp", None) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/warp_outbound.py b/scripts/warp_outbound.py new file mode 100644 index 0000000..6aa6cc8 --- /dev/null +++ b/scripts/warp_outbound.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Turn a WireGuard .conf (e.g. wgcf-profile.conf) into a WARP outbound for sing-box or XRay.""" + +from __future__ import annotations + +import argparse +import json +import sys +from typing import Any + + +class ConfigError(ValueError): + pass + + +def parse_conf(text: str) -> tuple[dict[str, str], dict[str, str]]: + """Return the [Interface] section and the first [Peer], keys lowercased.""" + sections: list[tuple[str, dict[str, str]]] = [] + for line in text.splitlines(): + stripped = line.split("#", 1)[0].strip() + if stripped.startswith("[") and stripped.endswith("]"): + sections.append((stripped[1:-1].strip().lower(), {})) + elif "=" in stripped and sections: + key, value = (part.strip() for part in stripped.split("=", 1)) + sections[-1][1][key.lower()] = value + interface = next((s for name, s in sections if name == "interface"), None) + peer = next((s for name, s in sections if name == "peer"), None) + if interface is None or peer is None: + raise ConfigError("configuration requires [Interface] and [Peer] sections") + for section, key in ((interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")): + if not section.get(key): + raise ConfigError(f"configuration has no {key}") + return interface, peer + + +def _split(value: str) -> list[str]: + return [item.strip() for item in value.split(",") if item.strip()] + + +def split_endpoint(endpoint: str) -> tuple[str, int]: + host, sep, port = endpoint.rpartition(":") + if not sep or not port.isdigit() or not host: + raise ConfigError(f"endpoint '{endpoint}' is not host:port") + return host.strip("[]"), int(port) + + +def build(text: str, backend: str, tag: str, routing_mark: int | None) -> dict[str, Any]: + interface, peer = parse_conf(text) + addresses = _split(interface["address"]) + allowed_ips = _split(peer.get("allowedips", "")) or ["0.0.0.0/0", "::/0"] + mtu = int(interface.get("mtu") or 1280) + keepalive = int(peer["persistentkeepalive"]) if peer.get("persistentkeepalive") else None + psk = peer.get("presharedkey") + host, port = split_endpoint(peer["endpoint"]) + + if backend == "xray": + xray_peer: dict[str, Any] = { + "publicKey": peer["publickey"], + "endpoint": peer["endpoint"], + "allowedIPs": allowed_ips, + } + if keepalive is not None: + xray_peer["keepAlive"] = keepalive + if psk: + xray_peer["preSharedKey"] = psk + outbound: dict[str, Any] = { + "protocol": "wireguard", + "tag": tag, + "settings": { + "secretKey": interface["privatekey"], + "address": addresses, + "peers": [xray_peer], + "mtu": mtu, + }, + } + if routing_mark is not None: + outbound["streamSettings"] = {"sockopt": {"mark": routing_mark}} + return outbound + + # sing-box >= 1.11: WireGuard is an endpoint; the start script moves it out of outbounds. + sb_peer: dict[str, Any] = { + "address": host, + "port": port, + "public_key": peer["publickey"], + "allowed_ips": allowed_ips, + } + if keepalive is not None: + sb_peer["persistent_keepalive_interval"] = keepalive + if psk: + sb_peer["pre_shared_key"] = psk + endpoint: dict[str, Any] = { + "type": "wireguard", + "tag": tag, + "address": addresses, + "private_key": interface["privatekey"], + "mtu": mtu, + "peers": [sb_peer], + } + if routing_mark is not None: + endpoint["routing_mark"] = routing_mark + return endpoint + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--backend", choices=["sing-box", "xray"], required=True) + parser.add_argument("--tag", default="warp") + parser.add_argument("--routing-mark", type=int) + args = parser.parse_args() + try: + print(json.dumps(build(sys.stdin.read(), args.backend, args.tag, args.routing_mark))) + except (ConfigError, ValueError) as error: + print(f"proxy-suite: warp: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main())