using System.Text.Json.Nodes; namespace UCVL.VPNPlus; internal static class TunConfigBuilder { internal static string OverrideProxyServerAddress(string baseConfigJson, string? gatewayAddress) { if (string.IsNullOrWhiteSpace(gatewayAddress)) return baseConfigJson; var root = JsonNode.Parse(baseConfigJson)?.AsObject() ?? throw new InvalidOperationException("服务端线路配置为空。"); if (root["outbounds"] is not JsonArray outbounds) return baseConfigJson; foreach (var node in outbounds) { if (node is not JsonObject outbound || !string.Equals(outbound["tag"]?.GetValue(), "proxy", StringComparison.OrdinalIgnoreCase) || outbound["settings"]?["vnext"] is not JsonArray servers) { continue; } foreach (var server in servers) if (server is JsonObject item) item["address"] = gatewayAddress.Trim(); } return root.ToJsonString(); } // Production must capture native sockets as well as browser proxy traffic. // Keep validation explicitly TUN-free: Xray -test starts its inbounds too. internal static string BuildRuntime(string baseConfigJson, string physicalInterfaceName, bool includeLocalLearning, int routingApiPort) => Build(baseConfigJson, physicalInterfaceName, includeLocalLearning, includeTun: true, routingApiPort: routingApiPort); internal static string Build( string baseConfigJson, string physicalInterfaceName, bool includeLocalLearning, bool includeTun = true, int routingApiPort = 0, int learningProbePort = 0, int directProbePort = 0, string? tailnetInterfaceName = null) { var root = JsonNode.Parse(baseConfigJson)?.AsObject() ?? throw new InvalidOperationException("服务端线路配置为空。"); var inbounds = root["inbounds"]?.AsArray() ?? throw new InvalidOperationException("线路配置缺少入站定义。"); var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(root); var tailnet = TailnetTransport.Address(root) is not null; if (tailnet && (privateAuxiliary || string.IsNullOrWhiteSpace(tailnetInterfaceName))) throw new InvalidOperationException("Tailscale 入口缺少已验证的网络路径。"); root.Remove(PrivateAuxiliaryRuntime.Marker); // Client metadata is not an Xray setting. root.Remove(TailnetTransport.Marker); if (includeTun) { inbounds.Insert(0, new JsonObject { ["tag"] = "tun-in", ["port"] = 0, ["protocol"] = "tun", ["settings"] = new JsonObject { ["name"] = TunRouting.AdapterName, ["MTU"] = 1500, }, ["sniffing"] = new JsonObject { ["enabled"] = true, ["destOverride"] = new JsonArray("http", "tls", "quic"), ["routeOnly"] = false, }, }); } var outbounds = root["outbounds"]?.AsArray() ?? throw new InvalidOperationException("线路配置缺少出站定义。"); foreach (var node in outbounds) { if (node is not JsonObject outbound) continue; if (outbound["streamSettings"] is not JsonObject streamSettings) { streamSettings = new JsonObject(); outbound["streamSettings"] = streamSettings; } if (streamSettings["sockopt"] is not JsonObject sockopt) { sockopt = new JsonObject(); streamSettings["sockopt"] = sockopt; } if (streamSettings["realitySettings"] is JsonObject realitySettings && realitySettings["password"] is null && realitySettings["publicKey"] is JsonNode legacyPublicKey) { realitySettings["password"] = legacyPublicKey.DeepClone(); realitySettings.Remove("publicKey"); } sockopt["interface"] = physicalInterfaceName; if (privateAuxiliary && outbound["tag"]?.GetValue() == "proxy") sockopt.Remove("interface"); // Preserve the user's LAN/Tailscale route to .111. if (tailnet && outbound["tag"]?.GetValue() == "proxy") sockopt["interface"] = tailnetInterfaceName; // Only this socket uses the user's tailnet path. } // Local rules now require same-network direct failure + proxy TLS proof. // Do not load the old failure-only, seven-day learning file. if (includeLocalLearning) root["log"] = new JsonObject { ["loglevel"] = "info", ["access"] = "none" }; // Windows NRPT queries for proxy domains must not follow the smart // mode's default DIRECT rule. Use independent UDP resolvers through // the proxy instead of DoH here. A single reused HTTP/2 DoH connection // can stall every lookup when a mobile/NPM path briefly resets, which // is especially visible as repeated Codex reconnects. if (root["routing"]?["rules"] is JsonArray dnsRules) { AddTailnetDirectRule(dnsRules); root["dns"] = new JsonObject { ["tag"] = "ucvl-dns-query", ["queryStrategy"] = "UseIPv4", ["servers"] = privateAuxiliary ? new JsonArray("https://8.8.8.8/dns-query", "https://1.1.1.1/dns-query") : new JsonArray("1.1.1.1", "8.8.8.8") }; // Zero3 is TCP-only. Its DNS therefore uses HTTPS INSIDE the pinned // proxy, never SOCKS UDP (which would not have the same TLS protection). // Public 0.2.5-compatible UDP DNS above remains unchanged. if (privateAuxiliary) { outbounds.Add(new JsonObject { ["tag"] = "ucvl-private-udp-block", ["protocol"] = "blackhole" }); dnsRules.Insert(0, new JsonObject { ["type"] = "field", ["network"] = "udp", ["outboundTag"] = "ucvl-private-udp-block" }); } outbounds.Add(new JsonObject { ["tag"] = "ucvl-dns-out", ["protocol"] = "dns", ["settings"] = new JsonObject { ["nonIPQuery"] = "reject" } }); dnsRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("tun-in"), ["ip"] = new JsonArray("8.8.8.8", "1.1.1.1"), ["port"] = "53", ["outboundTag"] = "ucvl-dns-out" }); dnsRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-dns-query"), ["outboundTag"] = "proxy" }); } if (learningProbePort > 0) { inbounds.Add(new JsonObject { ["tag"] = "ucvl-learning-probe", ["listen"] = "127.0.0.1", ["port"] = learningProbePort, ["protocol"] = "socks", ["settings"] = new JsonObject { ["auth"] = "noauth", ["udp"] = false } }); var probeRules = root["routing"]!["rules"]!.AsArray(); probeRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-learning-probe"), ["outboundTag"] = "proxy" }); probeRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-learning-probe"), ["ip"] = new JsonArray("geoip:private"), ["outboundTag"] = "block" }); } if (directProbePort > 0) { // Independent, physical-interface-bound direct path, unaffected by learned rules. // Never sniff or use domains on this listener: caller pins an already checked public IP. inbounds.Add(new JsonObject { ["tag"]="ucvl-direct-probe", ["listen"]="127.0.0.1", ["port"]=directProbePort, ["protocol"]="socks", ["settings"]=new JsonObject { ["auth"]="noauth", ["udp"]=false } }); outbounds.Add(new JsonObject { ["tag"]="ucvl-learning-direct", ["protocol"]="freedom", ["streamSettings"]=new JsonObject { ["sockopt"]=new JsonObject { ["interface"]=physicalInterfaceName } } }); var rules = root["routing"]!["rules"]!.AsArray(); rules.Insert(0, new JsonObject { ["type"]="field", ["inboundTag"]=new JsonArray("ucvl-direct-probe"), ["outboundTag"]="ucvl-learning-direct" }); rules.Insert(0, new JsonObject { ["type"]="field", ["inboundTag"]=new JsonArray("ucvl-direct-probe"), ["ip"]=new JsonArray("geoip:private"), ["outboundTag"]="block" }); } if (routingApiPort > 0) { RoutingRuleBatches.TagInitialRules(root); // Local control only: never expose the routing API on a LAN address. root["api"] = new JsonObject { ["tag"] = "ucvl-routing-api", ["listen"] = $"127.0.0.1:{routingApiPort}", ["services"] = new JsonArray("RoutingService", "StatsService"), }; root["stats"] = new JsonObject(); if (root["policy"] is not JsonObject policy) { policy = new JsonObject(); root["policy"] = policy; } if (policy["system"] is not JsonObject system) { system = new JsonObject(); policy["system"] = system; } system["statsOutboundUplink"] = true; system["statsOutboundDownlink"] = true; } return root.ToJsonString(); } internal static string BuildRoutingUpdate(string baseConfigJson) { var root = JsonNode.Parse(baseConfigJson)?.AsObject() ?? throw new InvalidOperationException("线路配置为空。"); AddLocalLearningRules(root); if (root["routing"]?["rules"] is JsonArray rules) AddTailnetDirectRule(rules); return new JsonObject { ["routing"] = root["routing"]?.DeepClone() ?? throw new InvalidOperationException("线路配置缺少路由规则。") }.ToJsonString(); } internal static string BuildLearningRouting(string config, string physicalInterfaceName, int learningProbePort, int directProbePort, string? tailnetInterfaceName) { var runtime = JsonNode.Parse(Build(config, physicalInterfaceName, includeLocalLearning:true, includeTun:false, learningProbePort:learningProbePort, directProbePort:directProbePort, tailnetInterfaceName:tailnetInterfaceName))!; return new JsonObject { ["routing"] = runtime["routing"]!.DeepClone() }.ToJsonString(); } internal static IReadOnlyList GetProxyServerHosts(string baseConfigJson) { var root = JsonNode.Parse(baseConfigJson)?.AsObject() ?? throw new InvalidOperationException("服务端线路配置为空。"); var hosts = new List(); if (root["outbounds"] is not JsonArray outbounds) return hosts; foreach (var node in outbounds) { if (node is not JsonObject outbound || !string.Equals(outbound["tag"]?.GetValue(), "proxy", StringComparison.OrdinalIgnoreCase) || (outbound["settings"]?["vnext"] ?? (PrivateAuxiliaryRuntime.IsPrivate(root) ? outbound["settings"]?["servers"] : null)) is not JsonArray servers) { continue; } foreach (var server in servers) { var address = server?["address"]?.GetValue()?.Trim(); if (!string.IsNullOrWhiteSpace(address)) hosts.Add(address); } } return hosts.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); } internal static bool SelfTest() { const string sample = """ { "inbounds": [], "outbounds": [ { "tag": "proxy", "protocol": "vless", "settings": {"vnext": [{"address": "203.0.113.10", "port": 443}]}, "streamSettings": { "security": "reality", "realitySettings": {"publicKey": "legacy-key"} } }, {"tag": "direct", "protocol": "freedom"} ], "routing": {"rules": []} } """; var hosts = GetProxyServerHosts(sample); var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.toplc.cn"))?.AsObject(); var gatewayOutbound = gatewayConfig?["outbounds"]?.AsArray()[0]?.AsObject(); var gatewayServer = gatewayOutbound?["settings"]?["vnext"]?.AsArray()[0]?.AsObject(); var gatewayReality = gatewayOutbound?["streamSettings"]?["realitySettings"]?.AsObject(); var config = JsonNode.Parse(BuildRuntime(sample, "Ethernet", includeLocalLearning: false, routingApiPort: 18090))?.AsObject(); var validation = JsonNode.Parse(Build(sample, "Ethernet", includeLocalLearning: false, includeTun: false))?.AsObject(); var tun = config?["inbounds"]?[0]; var runtimeDnsServers = config?["dns"]?["servers"]?.AsArray(); return hosts.Count == 1 && hosts[0] == "203.0.113.10" && gatewayServer?["address"]?.GetValue() == "vpn.toplc.cn" && gatewayServer?["port"]?.GetValue() == 443 && gatewayReality?["publicKey"]?.GetValue() == "legacy-key" && tun?["protocol"]?.GetValue() == "tun" && tun?["sniffing"]?["routeOnly"]?.GetValue() == false && config?["api"]?["listen"]?.GetValue() == "127.0.0.1:18090" && validation?["inbounds"]?.AsArray().Count == 0 && config?["outbounds"]?[0]?["streamSettings"]?["realitySettings"]?["password"]?.GetValue() == "legacy-key" && config?["outbounds"]?[0]?["streamSettings"]?["realitySettings"]?["publicKey"] is null && config?["outbounds"]?[0]?["streamSettings"]?["sockopt"]?["interface"]?.GetValue() == "Ethernet" && runtimeDnsServers?[0]?.GetValue() == "1.1.1.1" && runtimeDnsServers?[1]?.GetValue() == "8.8.8.8"; } private static void AddTailnetDirectRule(JsonArray rules) { // Control and relay traffic must reach the underlay before any proxy rule // can depend on the Tailscale connection. Internal DNS and probe rules // are added ahead of this rule. rules.Insert(0, new JsonObject { ["type"] = "field", ["domain"] = new JsonArray("regexp:" + TailnetDnsPolicy.DomainPattern), ["outboundTag"] = "direct", }); } private static void AddLocalLearningRules(JsonObject root) { if (root["routing"] is not JsonObject routing || routing["rules"] is not JsonArray rules) return; var learned = LearningStore.GetActiveTargets(); var domains = learned.Where(item => item.TargetType == "domain").Select(item => $"full:{item.Target}").Distinct().ToList(); var ips = learned.Where(item => item.TargetType == "ip") .Select(item => $"{item.Target}/{(item.Target.Contains(':') ? "128" : "32")}") .Distinct() .ToList(); var insertAt = Math.Min(1, rules.Count); if (ips.Count > 0) { rules.Insert(insertAt, new JsonObject { ["type"] = "field", ["ip"] = new JsonArray(ips.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()), ["outboundTag"] = "proxy", }); } if (domains.Count > 0) { rules.Insert(insertAt, new JsonObject { ["type"] = "field", ["domain"] = new JsonArray(domains.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()), ["outboundTag"] = "proxy", }); } } }