using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Text.Json; using System.Text.Json.Nodes; namespace UCVL.VPNPlus; // Explicit operator diagnostic. Real config comes over stdin; no saved token, // TUN, routes, proxy settings, login changes, or production singleton startup. internal static class TailnetTransportProbe { internal static async Task RunAsync(string xrayPath) { var checks = new Dictionary(); string? failure = null, node = null, endpoint = null, exitIp = null, country = null; using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60)); try { var input = await Console.In.ReadLineAsync(deadline.Token); if (input is null || input.Length > 262144 || !File.Exists(xrayPath)) throw new InvalidOperationException("probe_input"); var response = JsonSerializer.Deserialize(input) ?? throw new InvalidOperationException("probe_config"); node = response.Node.Slug; if (node is not ("aliyun-tokyo-002" or "aliyun-siliconvalley-003")) throw new InvalidOperationException("probe_node"); var prepared = TailnetTransport.TryPrepare(response, allowKnownEndpoints: true) ?? throw new InvalidOperationException("probe_not_eligible"); endpoint = TailnetTransport.Address(prepared)!; checks["same_authorized_fallback"] = TailnetTransport.SameAuthorizedFallback(prepared, response.GetRuntimeConfigJson()); checks["three_second_preflight"] = await TailnetTransport.ProbeEndpointAsync(endpoint, TailnetTransport.Port(prepared), deadline.Token); if (!checks.Values.All(v => v)) throw new IOException("probe_preflight_failed"); var interfaceName = TailnetTransport.RequireExistingRoute(endpoint); var runtime = JsonNode.Parse(TunConfigBuilder.Build(prepared, interfaceName, false, includeTun: false, tailnetInterfaceName: interfaceName))!.AsObject(); var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); runtime["inbounds"] = new JsonArray(new JsonObject { ["tag"] = "tailnet-isolated-http", ["listen"] = "127.0.0.1", ["port"] = port, ["protocol"] = "http", ["settings"] = new JsonObject() }); var proxy = runtime["outbounds"]!.AsArray().Single(o => o?["tag"]?.GetValue() == "proxy")!.DeepClone(); runtime["outbounds"] = new JsonArray(proxy); // no DIRECT/public fallback can fake a pass runtime["routing"] = new JsonObject { ["rules"] = new JsonArray() }; runtime.Remove("dns"); runtime.Remove("api"); runtime["log"] = new JsonObject { ["loglevel"] = "none" }; checks["real_runtime_binds_existing_interface"] = proxy["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == interfaceName; checks["one_tailnet_outbound_no_fallback"] = runtime["outbounds"]!.AsArray().Count == 1 && proxy["settings"]!["vnext"]![0]!["address"]!.GetValue() == endpoint; using var process = new Process { StartInfo = new ProcessStartInfo { FileName = xrayPath, WorkingDirectory = Path.GetDirectoryName(Path.GetFullPath(xrayPath))!, UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true } }; process.StartInfo.ArgumentList.Add("run"); process.StartInfo.ArgumentList.Add("-c"); process.StartInfo.ArgumentList.Add("stdin:"); process.Start(); var output = process.StandardOutput.ReadToEndAsync(); var errors = process.StandardError.ReadToEndAsync(); try { await process.StandardInput.WriteAsync(runtime.ToJsonString().AsMemory(), deadline.Token); process.StandardInput.Close(); var ready = Stopwatch.StartNew(); while (true) { if (process.HasExited) throw new IOException("probe_core_exited"); try { using var socket = new TcpClient(); await socket.ConnectAsync(IPAddress.Loopback, port, deadline.Token); break; } catch (SocketException) when (ready.Elapsed < TimeSpan.FromSeconds(5)) { await Task.Delay(100, deadline.Token); } } using var client = new HttpClient(new SocketsHttpHandler { UseProxy = true, Proxy = new WebProxy($"http://127.0.0.1:{port}"), AllowAutoRedirect = false, ConnectTimeout = TimeSpan.FromSeconds(8) }) { Timeout = TimeSpan.FromSeconds(15) }; using (var google = await client.GetAsync("https://www.google.com/generate_204", deadline.Token)) checks["authenticated_google_https_204"] = google.StatusCode == HttpStatusCode.NoContent; using (var trace = await client.GetAsync("https://www.cloudflare.com/cdn-cgi/trace", deadline.Token)) { checks["authenticated_trace_https_200"] = trace.StatusCode == HttpStatusCode.OK; var body = await trace.Content.ReadAsStringAsync(deadline.Token); var lines = body.Split('\n').Where(l => l.StartsWith("ip=") || l.StartsWith("loc=")).Select(l => l.Trim().Split('=', 2)).ToArray(); exitIp = lines.FirstOrDefault(l => l[0] == "ip")?[1]; country = lines.FirstOrDefault(l => l[0] == "loc")?[1]; } checks["expected_node_exit"] = node == "aliyun-tokyo-002" ? exitIp == "198.51.100.22" && country == "JP" : exitIp == "203.0.113.23" && country == "US"; checks["actual_transport_label"] = NodePresentation.WithTransport(node == "aliyun-tokyo-002" ? "VPN002" : "VPN003", true) == (node == "aliyun-tokyo-002" ? "VPN002 + Tailscale" : "VPN003 + Tailscale"); } finally { if (!process.HasExited) process.Kill(entireProcessTree: true); // only this owned test child await process.WaitForExitAsync(); await Task.WhenAll(output, errors); // consume, but never persist runtime/private output checks["owned_test_core_stopped"] = process.HasExited; } } catch (Exception e) { failure = e.GetType().Name; } var passed = failure is null && checks.Count >= 9 && checks.Values.All(v => v); var report = JsonSerializer.Serialize(new { passed, node, endpoint, exitIp, country, checks, failure, network_modified = false, tun_started = false, config_saved = false, production_released = false, full_client_acceptance = false }, new JsonSerializerOptions { WriteIndented = true }); // Refuse overwriting a previous run's evidence; runner uses a fresh directory. using (var file = new FileStream(Path.Combine(AppContext.BaseDirectory, "tailnet-live-probe.json"), FileMode.CreateNew)) using (var writer = new StreamWriter(file)) writer.Write(report); Console.WriteLine(report); return passed ? 0 : 82; } }