windows: the XRay-only backend; zapret beside the TUN

XRay alone (proxy.backend = "xray"), as upstream's xray.nix and its
start-time filter make it: the mixed-in listener with its login, DNS remote
and local ordered by the route mode with the servers' names on local,
IPIfNonMatch routing in upstream's order and modes, zapret's direct lists;
urltest as prefixed tags under a leastPing balancer and observatory, a pin
or first as one exit; chains by dialerProxy; Tor, SSH, WARP, AmneziaWG and
whitelist-bypass as SOCKS hops. What needs sing-box is refused for it, as
upstream asserts (TUN, groups, rule sets, autoProxy, selector/failover,
DoT, dns.strategy and the like). The service checks it with xray run -test
and runs it with its component's geodata (XRAY_LOCATION_ASSET); latency
tests and autoProxy stand aside.

zapret beside the TUN: winws2 gets the TUN's addresses left out in its
--wf-raw-filter (with the cutoff probe's ports); Flowseal's winws, which
takes no ANDed part, gets its own filter as it saves it (--wf-save) with
them left out, through --wf-raw. WinDivert negates single tests only: the
part is spelled positively, and compiled by WinDivert's own parser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-28 00:05:21 +03:00
1 parent 2dd563ed61
commit d675fdddb5
15 files changed
+831 -34

No files matched your search

+7 -3
View File
@@ -7,6 +7,9 @@ pub mod groups;
mod outbounds;
mod routing;
mod sing_box;
mod xray;
/// The TUN's IPv6 address (its IPv4 one is configured).
pub use sing_box::TUN_IPV6_ADDRESS;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
@@ -160,9 +163,10 @@ pub fn render(input: &Input) -> Result<Rendered, RenderError> {
let (config, sidecar) = sing_box::config(input, &assembly, &probe_exits, &mut warnings)?;
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, probe_exits, warnings })
}
crate::config::Backend::Xray => Err(RenderError(
"the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(),
)),
crate::config::Backend::Xray => {
let config = xray::config(input, &assembly, &mut warnings)?;
Ok(Rendered { sing_box: None, xray: Some(config), inventory: assembly.inventory, probe_exits: Vec::new(), warnings })
}
}
}
+28 -6
View File
@@ -54,6 +54,8 @@ pub(super) struct Assembly {
/// The hybrid sidecar's XRay outbounds.
pub xray: Vec<Value>,
pub inventory: Inventory,
/// What selection may pick on its own (the XRay backend builds its "proxy" from it).
pub selectable: Vec<String>,
}
struct Builder<'a> {
@@ -136,6 +138,14 @@ impl Builder<'_> {
/// A loopback SOCKS hop to a helper the service runs.
fn hop(&self, tag: &str, port: u16, login: bool) -> Value {
if self.backend == Backend::Xray {
let mut ob = json!({ "protocol": "socks", "tag": tag, "settings": { "address": "127.0.0.1", "port": port } });
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
ob["settings"]["user"] = user.clone().into();
ob["settings"]["pass"] = pass.clone().into();
}
return ob;
}
let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port });
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
ob["username"] = user.clone().into();
@@ -276,6 +286,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
}
ExtraKind::Warp { device } => match device.kind {
crate::config::WarpOutboundKind::SingBox => {
if p.backend == Backend::Xray {
warnings.push(format!("WARP device '{}': a sing-box endpoint needs the sing-box or hybrid backend (use \"userspace\"); leaving it out", device.tag));
continue;
}
let Some(profile) = input.env.warp_profiles.get(&device.tag) else {
warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag));
continue;
@@ -296,6 +310,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
},
ExtraKind::Awg { profile, kind, port } => match kind {
crate::config::AwgOutboundKind::SingBox => {
if p.backend == Backend::Xray {
warnings.push(format!("AmneziaWG outbound '{profile}': a sing-box endpoint needs the sing-box or hybrid backend (use \"userspace\"); leaving it out"));
continue;
}
let Some(conf) = input.env.awg_profiles.get(&profile) else {
warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out"));
continue;
@@ -341,7 +359,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
// Groups, against the outbounds this start has. A group whose name an outbound took, or
// that contains itself, is left out.
let mut group_cfg = p.groups.clone();
if let Some(warp) = warp_group(cfg) {
// Groups need sing-box (validated); the XRay backend has none, nor a "warp" group.
if p.backend == Backend::Xray {
group_cfg.clear();
} else if let Some(warp) = warp_group(cfg) {
group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp);
}
group_cfg.retain(|name, _| {
@@ -424,11 +445,12 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
.cloned()
.collect();
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest.
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest. The
// XRay backend builds its own from `selectable` and the pin.
let mut every: Vec<String> = b.order.clone();
every.extend(resolved.groups.keys().cloned());
let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() };
let wrapper = match p.selection {
let wrapper = if p.backend == Backend::Xray { Value::Null } else { match p.selection {
Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }),
Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
@@ -446,8 +468,8 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
"interval": p.url_test.interval, "tolerance": p.url_test.tolerance,
}),
};
let mut outbounds = vec![wrapper];
} };
let mut outbounds = if wrapper.is_null() { Vec::new() } else { vec![wrapper] };
outbounds.append(&mut b.outbounds);
outbounds.extend(resolved.outbounds.iter().cloned());
@@ -472,7 +494,7 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
.map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned())))
.collect(),
};
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory })
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory, selectable })
}
/// With two or more WARP devices, "warp" names a group of them.
@@ -52,7 +52,7 @@ fn hop_ports(input: &Input) -> Vec<u16> {
out
}
fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
pub(super) fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
let auth = &input.cfg.proxy.listener.auth;
let Some(user) = &auth.username else { return Ok(None) };
let password = match (&auth.password, &auth.password_file) {
+334
View File
@@ -0,0 +1,334 @@
//! The XRay-only backend's whole config: upstream's `config-templates/xray.nix` (its `tproxy`
//! variant, without TProxy), `rules/xray.nix` and the start-time `backend-filter-xray.template.jq`.
//! The transparent modes (TProxy, TUN, per-app TUN) have no counterpart here.
use std::collections::BTreeSet;
use serde_json::{Map, Value, json};
use super::outbounds::Assembly;
use super::routing::{LOOPBACK, direct_match};
use super::sing_box::{apply_xmux, listener_users, xray_log_level};
use super::{Input, RenderError, RouteMode};
use crate::config::{DnsTransport, DnsUpstream, RouteDefault, RouteMatch, Selection};
use crate::derived;
/// `urltest` renames every outbound so the balancer's selector can be a prefix.
const PREFIX: &str = "proxy-suite-ob-";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Category {
Proxy,
Direct,
Block,
/// Private addresses and the Telegram relay's: direct, but kept in every mode.
Safety,
}
fn category(target: &str) -> Category {
match target {
"direct" => Category::Direct,
"block" => Category::Block,
_ => Category::Proxy,
}
}
struct Section {
priority: i64,
category: Category,
rules: Vec<Value>,
}
/// Where a rule's outbound is in this config.
struct Targets {
prefixed: bool,
/// The one outbound "proxy" stands for (a pin, "first", or a balancer of one), renamed.
single: Option<String>,
}
impl Targets {
/// `{type, ruleTag, <fields>}` and its target: "proxy" is the balancer or the one exit.
fn rule(&self, rule_tag: &str, fields: Value, outbound: &str) -> Value {
let mut rule = json!({ "type": "field", "ruleTag": rule_tag });
if let Value::Object(f) = fields {
rule.as_object_mut().unwrap().extend(f);
}
match outbound {
"proxy" => match &self.single {
Some(tag) => rule["outboundTag"] = tag.clone().into(),
None => rule["balancerTag"] = "proxy".into(),
},
"direct" | "block" => rule["outboundTag"] = outbound.into(),
tag if self.prefixed => rule["outboundTag"] = format!("{PREFIX}{tag}").into(),
tag => rule["outboundTag"] = tag.into(),
}
rule
}
/// One rule per kind of match, as upstream's `mkXrayCustomRuleEntries` (a rule matches any
/// of them): `<prefix>-domain`, `-ip`, `-geosite`, `-geoip`.
fn match_rules(&self, rule_tag: &dyn Fn(&str) -> String, outbound: &str, m: &RouteMatch) -> Vec<Value> {
let mut rules = Vec::new();
if !m.domains.is_empty() {
let domains: Vec<String> = m.domains.iter().map(|d| format!("domain:{d}")).collect();
rules.push(self.rule(&rule_tag("domain"), json!({ "domain": domains }), outbound));
}
if !m.ips.is_empty() {
rules.push(self.rule(&rule_tag("ip"), json!({ "ip": m.ips }), outbound));
}
if !m.geosites.is_empty() {
let sites: Vec<String> = m.geosites.iter().map(|s| format!("geosite:{s}")).collect();
rules.push(self.rule(&rule_tag("geosite"), json!({ "domain": sites }), outbound));
}
if !m.geoips.is_empty() {
let ips: Vec<String> = m.geoips.iter().map(|s| format!("geoip:{s}")).collect();
rules.push(self.rule(&rule_tag("geoip"), json!({ "ip": ips }), outbound));
}
rules
}
}
fn dns_server(tag: &str, upstream: &DnsUpstream) -> Result<Value, RenderError> {
let address = match upstream.transport {
DnsTransport::Udp => upstream.address.clone(),
DnsTransport::Tcp => format!("tcp://{}", upstream.address),
DnsTransport::Tls => return Err(RenderError("proxy.dns.*.type = \"tls\" is not supported with the xray backend; use udp or tcp DNS".into())),
};
Ok(json!({ "address": address, "tag": tag, "port": upstream.port, "queryStrategy": "UseIP" }))
}
/// Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy
/// (the jq's `xray_server_names`).
fn server_names(outbounds: &[Value]) -> BTreeSet<String> {
let mut names = BTreeSet::new();
for ob in outbounds {
let settings = &ob["settings"];
let addresses = settings["vnext"]
.as_array()
.into_iter()
.flatten()
.chain(settings["servers"].as_array().into_iter().flatten())
.map(|s| &s["address"])
.chain(std::iter::once(&settings["address"]));
for a in addresses.filter_map(Value::as_str) {
let numeric = a.chars().all(|c| c.is_ascii_digit() || c == '.');
if !numeric && !a.contains(':') && a != "localhost" {
names.insert(a.to_owned());
}
}
}
names
}
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<Value, RenderError> {
if input.tun {
return Err(RenderError("the TUN with the xray backend is not on Windows yet".into()));
}
let cfg = input.cfg;
let p = &cfg.proxy;
let r = &p.routing;
// "proxy": a balancer over every selectable outbound on urltest, else the one exit. XRay has
// no selector: a pin leaves the balancer with one outbound, which is the path "first" takes.
let urltest = p.selection == Selection::Urltest;
let pinned = &asm.inventory.pinned;
let single_raw = if !pinned.is_empty() {
Some(pinned.clone())
} else if urltest {
(asm.selectable.len() == 1).then(|| asm.selectable[0].clone())
} else {
asm.selectable.first().cloned()
};
let targets = Targets {
prefixed: urltest,
single: single_raw.map(|t| if urltest { format!("{PREFIX}{t}") } else { t }),
};
let balanced = urltest && targets.single.is_none();
// Outbounds: the exits, then the builtin ones.
let mut outbounds: Vec<Value> = Vec::new();
for ob in &asm.outbounds {
let mut ob = ob.clone();
apply_xmux(input, &mut ob);
if urltest {
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
ob["tag"] = format!("{PREFIX}{tag}").into();
if let Some(hop) = ob.pointer("/streamSettings/sockopt/dialerProxy").and_then(Value::as_str) {
ob["streamSettings"]["sockopt"]["dialerProxy"] = format!("{PREFIX}{hop}").into();
}
}
outbounds.push(ob);
}
let names = server_names(&outbounds);
// No loopback by any name for what goes direct, besides the resolvers on it: the loopback
// hops, the helpers' listeners and whatever else listens there are nothing to dial.
let loopback_dns_ports: BTreeSet<u16> = [&p.dns.local, &p.dns.remote]
.into_iter()
.filter(|u| u.address.starts_with("127.") || u.address == "::1" || u.address == "localhost")
.map(|u| u.port)
.collect();
let mut final_rules = Vec::new();
if !loopback_dns_ports.is_empty() {
let ports: Vec<String> = loopback_dns_ports.iter().map(u16::to_string).collect();
final_rules.push(json!({ "action": "allow", "ip": LOOPBACK, "port": ports.join(",") }));
}
final_rules.push(json!({ "action": "block", "ip": LOOPBACK, "blockDelay": 0 }));
outbounds.push(json!({ "protocol": "freedom", "tag": "direct", "settings": { "finalRules": final_rules } }));
outbounds.push(json!({ "protocol": "blackhole", "tag": "block", "settings": {} }));
// No rule takes packets to dns-out here (those are TProxy's and the TUN's), but it is the
// template's: .onion is told there is no such name, other record types go on.
let mut dns_rules = Vec::new();
if derived::tor_route_onion(cfg) {
dns_rules.push(json!({ "action": "return", "rCode": 3, "domain": ["domain:onion"] }));
}
dns_rules.push(json!({ "action": "direct", "qType": "2-27,29-65535" }));
outbounds.push(json!({ "protocol": "dns", "tag": "dns-out", "settings": { "userLevel": 0, "rules": dns_rules } }));
// The mode: the configured default, or proxy-ctl's override.
let mode = input.state.route_mode.unwrap_or(match r.default {
RouteDefault::Proxy => RouteMode::Blacklist,
RouteDefault::Direct => RouteMode::Whitelist,
});
let (final_outbound, remote_first) = match mode {
RouteMode::Blacklist | RouteMode::AllProxy => ("proxy", true),
RouteMode::Whitelist | RouteMode::AllBypass => ("direct", false),
};
// DNS: the preferred server first (the backend filter's `xray_dns_server_order`), proxy
// servers' names pinned to a copy of "local".
let remote = dns_server("remote", &p.dns.remote)?;
let local = dns_server("local", &p.dns.local)?;
let mut servers = if remote_first { vec![remote, local.clone()] } else { vec![local.clone(), remote] };
if !names.is_empty() {
let mut pinned_local = local;
pinned_local["domains"] = names.iter().map(|n| format!("full:{n}")).collect::<Vec<_>>().into();
pinned_local["skipFallback"] = true.into();
servers.push(pinned_local);
}
// Rules. What XRay's DNS asks for goes by the server's tag: "local" direct, "remote" through
// the proxy.
let mut rules = vec![
targets.rule("dns-upstream-direct", json!({ "inboundTag": ["local"], "network": "tcp,udp" }), "direct"),
targets.rule("dns-upstream-remote", json!({ "inboundTag": ["remote"], "network": "tcp,udp" }), "proxy"),
];
// Nothing reaches this host's loopback through the proxy, by address or by name. Upstream
// guards the transparent inbounds only (its firewall keeps the rest from other users);
// Windows has no such firewall here, so the local listener too.
let onion = derived::tor_route_onion(cfg) && asm.inventory.tags.iter().any(|t| t == derived::TOR_OUTBOUND_TAG);
let mut common = vec![
targets.rule("guard-loopback-ip", json!({ "inboundTag": ["mixed-in"], "ip": LOOPBACK }), "block"),
targets.rule("guard-loopback-domain", json!({ "inboundTag": ["mixed-in"], "domain": ["domain:localhost"] }), "block"),
];
if onion {
common.push(targets.rule("tor-onion", json!({ "domain": ["domain:onion"] }), derived::TOR_OUTBOUND_TAG));
}
rules.extend(common);
let known = |t: &str| asm.inventory.tags.iter().any(|x| x == t);
let mut sections = Vec::new();
let custom_tag = |outbound: &str| {
let c = match category(outbound) {
Category::Direct => "direct",
Category::Block => "block",
_ => "proxy",
};
let c = c.to_owned();
move |kind: &str| format!("custom-{c}-{kind}")
};
for ob in &p.outbounds {
if ob.routing.is_empty() {
continue;
}
let outbound = if known(&ob.tag) {
ob.tag.as_str()
} else {
warnings.push(format!("outbound '{}' is not running: what its routing sends to it is blocked until it is", ob.tag));
"block"
};
let tag = custom_tag(outbound);
sections.push(Section { priority: 100, category: category(outbound), rules: targets.match_rules(&tag, outbound, &ob.routing) });
}
for (i, rule) in r.rules.iter().enumerate() {
if rule.disabled {
continue;
}
let name = rule.name.clone().unwrap_or_else(|| format!("#{i}"));
let outbound = if derived::BUILTIN_TAGS.contains(&rule.outbound.as_str()) || known(&rule.outbound) {
rule.outbound.as_str()
} else {
warnings.push(format!("routing rule {name}: no outbound named '{}' is running; what it matches is blocked until it is", rule.outbound));
"block"
};
let tag = custom_tag(outbound);
sections.push(Section {
priority: rule.priority.unwrap_or(100),
category: category(outbound),
rules: targets.match_rules(&tag, outbound, &rule.matches),
});
}
let direct = direct_match(input);
let fixed = |prefix: &'static str| move |kind: &str| format!("{prefix}-{kind}");
let proxy_primary = RouteMatch { domains: r.proxy.domains.clone(), ips: r.proxy.ips.clone(), ..Default::default() };
let proxy_geo = RouteMatch { geosites: r.proxy.geosites.clone(), geoips: r.proxy.geoips.clone(), ..Default::default() };
sections.push(Section { priority: 200, category: Category::Proxy, rules: targets.match_rules(&fixed("proxy"), "proxy", &proxy_primary) });
// Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too).
sections.push(Section { priority: 300, category: Category::Block, rules: targets.match_rules(&fixed("block"), "block", &r.block) });
sections.push(Section { priority: 400, category: Category::Direct, rules: targets.match_rules(&fixed("direct"), "direct", &direct) });
let mut safety = vec![targets.rule("direct-private", json!({ "ip": ["geoip:private"] }), "direct")];
let tg = &cfg.tg_ws_proxy;
if tg.enable && tg.bypass_transparent_proxy && !tg.dc_ips.is_empty() {
let ips: BTreeSet<&String> = tg.dc_ips.values().collect();
safety.push(targets.rule("direct-tg-relay", json!({ "ip": ips }), "direct"));
}
sections.push(Section { priority: 400, category: Category::Safety, rules: safety });
// Geosite and geoip lists last: they are the heaviest to match.
sections.push(Section { priority: 500, category: Category::Proxy, rules: targets.match_rules(&fixed("proxy"), "proxy", &proxy_geo) });
let keep = |c: Category| match mode {
RouteMode::AllProxy => c != Category::Direct,
RouteMode::AllBypass => matches!(c, Category::Block | Category::Safety),
_ => true,
};
// A stable sort: among equals, the list's own order.
sections.sort_by_key(|s| s.priority);
rules.extend(sections.into_iter().filter(|s| keep(s.category)).flat_map(|s| s.rules));
rules.push(targets.rule("final-default", json!({ "network": "tcp,udp" }), final_outbound));
let mut routing = json!({ "domainStrategy": "IPIfNonMatch", "domainMatcher": "hybrid", "rules": rules });
let mut config = Map::new();
if balanced {
// Only what selection may pick: not proxy.selectionExclude, nor what is disabled.
let candidates: Vec<String> = asm.selectable.iter().map(|t| format!("{PREFIX}{t}")).collect();
routing["balancers"] = json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]);
config.insert(
"observatory".into(),
json!({ "subjectSelector": candidates, "probeUrl": p.url_test.url, "probeInterval": p.url_test.interval }),
);
}
// The listener: sniffing puts a name in place of the address a client connected to, so the
// domain rules see it.
let mut settings = json!({ "auth": "noauth", "udp": true, "ip": p.listener.address });
if let Some(users) = listener_users(input)? {
let accounts: Vec<Value> =
users.as_array().into_iter().flatten().map(|u| json!({ "user": u["username"], "pass": u["password"] })).collect();
settings["auth"] = "password".into();
settings["accounts"] = accounts.into();
}
let mixed = json!({
"tag": "mixed-in", "protocol": "socks", "listen": p.listener.address, "port": p.listener.port,
"settings": settings,
"sniffing": { "enabled": true, "destOverride": ["http", "tls", "quic"] },
});
config.insert("log".into(), json!({ "loglevel": xray_log_level(input), "access": "none" }));
config.insert("dns".into(), json!({ "queryStrategy": "UseIP", "servers": servers }));
config.insert("inbounds".into(), json!([mixed]));
config.insert("outbounds".into(), Value::Array(outbounds));
config.insert("routing".into(), routing);
Ok(Value::Object(config))
}