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

+285
View File
@@ -336,3 +336,288 @@ fn helper_programs_go_direct_only_from_the_tun() {
assert_eq!(under_tun.len(), 1);
assert_eq!(under_tun[0]["inbound"], json!(["tun-in"]));
}
/// The xray backend's config, rendered and checked by `xray run -test`.
fn render_xray(cfg: &Config, state: &State, dir: &Path) -> (Value, Vec<String>) {
let mut cfg = cfg.clone();
cfg.proxy.backend = Backend::Xray;
let r = render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &env(dir), read_file: &no_files, tun: false }).unwrap();
assert!(r.sing_box.is_none() && r.probe_exits.is_empty());
let x = r.xray.unwrap();
check_xray(&x, dir);
(x, r.warnings)
}
fn xray_rules(x: &Value) -> &Vec<Value> {
x["routing"]["rules"].as_array().unwrap()
}
fn xray_rule<'a>(x: &'a Value, tag: &str) -> Option<&'a Value> {
xray_rules(x).iter().find(|r| r["ruleTag"] == tag)
}
fn xray_tags(x: &Value) -> Vec<&str> {
x["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect()
}
fn xray_dns_tags(x: &Value) -> Vec<&str> {
x["dns"]["servers"].as_array().unwrap().iter().map(|s| s["tag"].as_str().unwrap()).collect()
}
fn xray_base() -> Config {
let mut cfg = base();
cfg.proxy.outbounds[0] = outbound("nl", "trojan://pw@nl.example.com:443?sni=nl.example.com");
cfg
}
#[test]
fn xray_route_modes_change_the_final_the_lists_and_the_dns_order() {
let dir = scratch("xray-modes");
let mut cfg = xray_base();
cfg.proxy.routing.direct.domains = vec!["direct.example".into()];
cfg.proxy.routing.direct.geoips = vec!["cn".into()];
cfg.proxy.routing.block.domains = vec!["ads.example".into()];
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
cfg.proxy.routing.proxy.geosites = vec!["netflix".into()];
for (mode, final_ob, has_direct, remote_first) in [
(None, "nl", true, true),
(Some(RouteMode::Whitelist), "direct", true, false),
(Some(RouteMode::AllProxy), "nl", false, true),
(Some(RouteMode::AllBypass), "direct", false, false),
] {
let state = State { route_mode: mode, ..Default::default() };
let (x, _) = render_xray(&cfg, &state, &dir);
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], final_ob, "{mode:?}");
assert_eq!(xray_rule(&x, "direct-domain").is_some(), has_direct, "{mode:?}");
assert_eq!(xray_rule(&x, "direct-geoip").is_some(), has_direct, "{mode:?}");
// Block and the private-address safety stay in every mode.
assert_eq!(xray_rule(&x, "block-domain").unwrap()["outboundTag"], "block", "{mode:?}");
assert!(xray_rule(&x, "direct-private").is_some(), "{mode:?}");
let proxied = mode != Some(RouteMode::AllBypass);
assert_eq!(xray_rule(&x, "proxy-domain").is_some(), proxied, "{mode:?}");
assert_eq!(xray_rule(&x, "proxy-geosite").is_some(), proxied, "{mode:?}");
// The DNS server the mode prefers comes first.
assert_eq!(xray_dns_tags(&x)[0], if remote_first { "remote" } else { "local" }, "{mode:?}");
}
// The order of the lists: block ahead of direct, the geo lists of the proxy last.
let (x, _) = render_xray(&cfg, &State::default(), &dir);
let pos = |tag: &str| xray_rules(&x).iter().position(|r| r["ruleTag"] == tag).unwrap();
assert!(pos("proxy-domain") < pos("block-domain") && pos("block-domain") < pos("direct-domain"));
assert!(pos("direct-private") < pos("proxy-geosite") && pos("proxy-geosite") < pos("final-default"));
assert_eq!(xray_rule(&x, "proxy-geosite").unwrap()["domain"], json!(["geosite:netflix"]));
assert_eq!(xray_rule(&x, "direct-domain").unwrap()["domain"], json!(["domain:direct.example"]));
assert_eq!(x["routing"]["domainStrategy"], "IPIfNonMatch");
assert_eq!(x["routing"]["domainMatcher"], "hybrid");
}
#[test]
fn xray_dns_follows_routing_default_and_pins_the_proxy_servers() {
let dir = scratch("xray-dns");
let mut cfg = xray_base();
cfg.proxy.dns.remote = DnsUpstream { transport: DnsTransport::Tcp, address: "9.9.9.9".into(), port: 5353 };
let (x, _) = render_xray(&cfg, &State::default(), &dir);
// proxy: remote first; the copy of "local" that answers for the servers' names last.
assert_eq!(xray_dns_tags(&x), ["remote", "local", "local"]);
let servers = x["dns"]["servers"].as_array().unwrap();
assert_eq!(servers[0]["address"], "tcp://9.9.9.9");
assert_eq!(servers[0]["port"], 5353);
assert_eq!(servers[2]["domains"], json!(["full:de.example.com", "full:nl.example.com"]));
assert_eq!(servers[2]["skipFallback"], true);
assert!(servers[1].get("domains").is_none());
// The server's own queries: local direct, remote through the proxy.
assert_eq!(xray_rule(&x, "dns-upstream-direct").unwrap()["outboundTag"], "direct");
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["outboundTag"], "nl");
cfg.proxy.routing.default = RouteDefault::Direct;
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(xray_dns_tags(&x), ["local", "remote", "local"]);
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "direct");
// DoT has no XRay counterpart.
cfg.proxy.backend = Backend::Xray;
cfg.proxy.dns.local.transport = DnsTransport::Tls;
let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err();
assert!(err.0.contains("tls"), "{err}");
}
#[test]
fn xray_urltest_balances_and_a_pin_leaves_one_exit() {
let dir = scratch("xray-urltest");
let mut cfg = xray_base();
cfg.proxy.selection = Selection::Urltest;
cfg.proxy.url_test.url = "https://probe.example/204".into();
cfg.proxy.url_test.interval = "90s".into();
cfg.proxy.outbounds.push(outbound("ru", "trojan://pw@ru.example.com:443?sni=ru.example.com"));
cfg.proxy.outbounds[2].routing.domains = vec!["ru.example".into()];
cfg.proxy.selection_exclude = vec!["ru".into()];
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(xray_tags(&x)[..3], ["proxy-suite-ob-nl", "proxy-suite-ob-de", "proxy-suite-ob-ru"]);
// The balancer takes what selection may pick, not the excluded outbound.
let candidates = json!(["proxy-suite-ob-nl", "proxy-suite-ob-de"]);
assert_eq!(x["routing"]["balancers"], json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]));
assert_eq!(x["observatory"], json!({ "subjectSelector": candidates, "probeUrl": "https://probe.example/204", "probeInterval": "90s" }));
assert_eq!(xray_rule(&x, "final-default").unwrap()["balancerTag"], "proxy");
assert_eq!(xray_rule(&x, "proxy-domain").unwrap()["balancerTag"], "proxy");
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["balancerTag"], "proxy");
// An outbound's own routing names it, renamed with the rest.
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
// A pin: no balancer, no observatory, every "proxy" rule on the one exit.
let state = State { pin: Some("de".into()), ..Default::default() };
let (x, _) = render_xray(&cfg, &state, &dir);
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
for tag in ["final-default", "proxy-domain", "dns-upstream-remote"] {
let r = xray_rule(&x, tag).unwrap();
assert_eq!(r["outboundTag"], "proxy-suite-ob-de", "{tag}");
assert!(r.get("balancerTag").is_none(), "{tag}");
}
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
// One selectable outbound is a pin of its own.
cfg.proxy.selection_exclude = vec!["ru".into(), "de".into()];
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "proxy-suite-ob-nl");
}
#[test]
fn xray_first_selection_takes_the_first_outbound_or_the_pin() {
let dir = scratch("xray-first");
let cfg = xray_base();
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(xray_tags(&x), ["nl", "de", "direct", "block", "dns-out"]);
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "nl");
let state = State { pin: Some("de".into()), ..Default::default() };
let (x, _) = render_xray(&cfg, &state, &dir);
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "de");
// Every tag stays, so a rule naming another outbound still reaches it.
let mut cfg = cfg;
cfg.proxy.routing.rules.push(RoutingRule { outbound: "nl".into(), matches: RouteMatch { ips: vec!["203.0.113.0/24".into()], geoips: vec!["us".into()], ..Default::default() }, ..Default::default() });
cfg.proxy.routing.rules.push(RoutingRule { outbound: "direct".into(), matches: RouteMatch { domains: vec!["lan.example".into()], ..Default::default() }, ..Default::default() });
let (x, _) = render_xray(&cfg, &state, &dir);
assert_eq!(xray_rule(&x, "custom-proxy-ip").unwrap()["outboundTag"], "nl");
assert_eq!(xray_rule(&x, "custom-proxy-geoip").unwrap()["ip"], json!(["geoip:us"]));
assert_eq!(xray_rule(&x, "custom-direct-domain").unwrap()["outboundTag"], "direct");
}
#[test]
fn xray_listener_takes_a_login_and_guards_loopback() {
let dir = scratch("xray-listener");
let mut cfg = xray_base();
let (x, _) = render_xray(&cfg, &State::default(), &dir);
let inbound = &x["inbounds"][0];
assert_eq!(inbound["tag"], "mixed-in");
assert_eq!(inbound["protocol"], "socks");
assert_eq!(inbound["listen"], "127.0.0.1");
assert_eq!(inbound["port"], 1080);
assert_eq!(inbound["settings"]["auth"], "noauth");
assert_eq!(inbound["settings"]["udp"], true);
assert_eq!(x["inbounds"].as_array().unwrap().len(), 1);
cfg.proxy.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None };
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(x["inbounds"][0]["settings"]["auth"], "password");
assert_eq!(x["inbounds"][0]["settings"]["accounts"], json!([{ "user": "me", "pass": "pw" }]));
// Nothing reaches this host's loopback: by address or name through the listener, or from a
// name the direct outbound resolves.
assert_eq!(xray_rule(&x, "guard-loopback-ip").unwrap()["outboundTag"], "block");
assert_eq!(xray_rule(&x, "guard-loopback-domain").unwrap()["domain"], json!(["domain:localhost"]));
let direct = x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "direct").unwrap();
assert_eq!(direct["settings"]["finalRules"].as_array().unwrap().last().unwrap()["action"], "block");
}
#[test]
fn xray_chains_and_helpers_are_xray_outbounds() {
let dir = scratch("xray-chain");
let mut cfg = xray_base();
cfg.proxy.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") });
cfg.proxy.outbounds.push(Outbound { tag: "raw".into(), xray_json: Some(serde_json::from_value(json!({ "protocol": "freedom", "settings": {} })).unwrap()), ..Default::default() });
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::Userspace);
cfg.ssh_proxy.enable = true;
cfg.ssh_proxy.as_outbound = true;
cfg.ssh_proxy.server = SshServer { user: Some("root".into()), host: Some("ssh.example.com".into()), port: 22 };
cfg.whitelist_bypass.enable = true;
cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None });
cfg.proxy.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() });
for urltest in [false, true] {
cfg.proxy.selection = if urltest { Selection::Urltest } else { Selection::First };
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
let prefix = if urltest { "proxy-suite-ob-" } else { "" };
let ob = |tag: &str| x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == format!("{prefix}{tag}")).unwrap_or_else(|| panic!("no {tag}: {:?}", xray_tags(&x)));
assert_eq!(ob("chained")["streamSettings"]["sockopt"]["dialerProxy"], format!("{prefix}nl"));
// The helpers' loopback SOCKS listeners, with the hop login where the service set one.
let tor = ob("tor");
assert_eq!(tor["protocol"], "socks");
assert_eq!(tor["settings"]["address"], "127.0.0.1");
assert!(tor["settings"].get("user").is_none());
assert!(ob("ssh-proxy")["settings"].get("user").is_none());
assert_eq!(ob("warp")["settings"]["user"], "hop");
assert_eq!(ob("warp")["settings"]["pass"], "hop-pass");
assert_eq!(ob("wl")["settings"]["user"], "hop");
assert_eq!(ob("raw")["protocol"], "freedom");
// Tor is for what is routed to it: not selected on its own.
assert_eq!(xray_rule(&x, "final-default").unwrap().get("balancerTag").is_some(), urltest);
if urltest {
let selector = x["routing"]["balancers"][0]["selector"].as_array().unwrap();
assert!(!selector.contains(&json!("proxy-suite-ob-tor")), "{selector:?}");
}
assert_eq!(xray_rule(&x, "tor-onion").unwrap()["outboundTag"], format!("{prefix}tor"));
assert_eq!(xray_rule(&x, "custom-block-domain").unwrap()["outboundTag"], "block");
assert!(warnings.iter().any(|w| w.contains("'gone'")), "{warnings:?}");
}
// Endpoints are sing-box's: left out, with a word.
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
assert!(!xray_tags(&x).contains(&"warp"));
assert!(warnings.iter().any(|w| w.contains("WARP")), "{warnings:?}");
}
#[test]
fn xray_zapret_direct_lists_go_direct() {
let dir = scratch("xray-zapret");
let cfg = xray_base();
let mut e = env(&dir);
e.zapret_direct = RouteMatch { domains: vec!["blocked.example".into()], ips: vec!["198.51.100.0/24".into()], ..Default::default() };
// zapret2's runtime rule-sets are sing-box's: pure XRay has no equivalent.
e.zapret2_direct_rule_set = Some("zapret.json".into());
let mut cfg = cfg;
cfg.proxy.backend = Backend::Xray;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
let x = r.xray.unwrap();
check_xray(&x, &dir);
let domains = xray_rule(&x, "direct-domain").unwrap();
assert_eq!(domains["outboundTag"], "direct");
assert!(domains["domain"].as_array().unwrap().contains(&json!("domain:blocked.example")));
assert!(xray_rule(&x, "direct-ip").unwrap()["ip"].as_array().unwrap().contains(&json!("198.51.100.0/24")));
assert!(!x.to_string().contains("zapret.json"));
}
#[test]
fn xray_backend_refuses_what_it_cannot_do() {
let mut cfg = xray_base();
cfg.proxy.backend = Backend::Xray;
let refused = |cfg: &Config| -> Vec<String> {
ps_core::config::validate(cfg).into_iter().filter(|i| i.severity == Severity::Error).map(|i| i.path).collect()
};
assert!(refused(&cfg).is_empty(), "{:?}", refused(&cfg));
let mut c = cfg.clone();
c.proxy.selection = Selection::Selector;
assert!(refused(&c).contains(&"proxy.selection".to_owned()));
let mut c = cfg.clone();
c.proxy.tun.enable = true;
assert!(refused(&c).contains(&"proxy.tun.enable".to_owned()));
let mut c = cfg.clone();
c.proxy.dns.remote.transport = DnsTransport::Tls;
assert!(refused(&c).contains(&"proxy.dns".to_owned()));
let mut c = cfg.clone();
c.proxy.dns.strategy = Some(DomainStrategy::Ipv4Only);
assert!(refused(&c).contains(&"proxy.dns.strategy".to_owned()));
let mut c = cfg.clone();
c.debug.connection_log.enable = true;
assert!(refused(&c).contains(&"debug.connectionLog.enable".to_owned()));
// The TUN is refused at render too, whatever the validation was told.
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&scratch("xray-tun")), read_file: &no_files, tun: true });
assert!(r.unwrap_err().0.contains("TUN"));
}