208 lines
12 KiB
C#
208 lines
12 KiB
C#
using System.Net;
|
||
using System.Text.Json;
|
||
|
||
namespace UCVL.VPNPlus;
|
||
|
||
internal static class ConnectionSelfTest
|
||
{
|
||
private sealed class ProbeResult
|
||
{
|
||
public string Name { get; init; } = "";
|
||
public string Url { get; init; } = "";
|
||
public int? StatusCode { get; init; }
|
||
public long ElapsedMilliseconds { get; init; }
|
||
public string Error { get; init; } = "";
|
||
}
|
||
|
||
private sealed class TestResult
|
||
{
|
||
public DateTimeOffset StartedAt { get; init; }
|
||
public DateTimeOffset FinishedAt { get; set; }
|
||
public string Node { get; set; } = "";
|
||
public string RouteMode { get; set; } = "smart";
|
||
public bool Connected { get; set; }
|
||
public bool Passed { get; set; }
|
||
public bool AuthenticatedCodexConversationTested { get; set; }
|
||
public string Error { get; set; } = "";
|
||
public List<ProbeResult> Probes { get; } = [];
|
||
public Dictionary<string, bool> HandoverChecks { get; } = [];
|
||
public bool PhysicalAdapterSwitchTested { get; set; }
|
||
}
|
||
|
||
internal static async Task<int> RunAsync(int stabilizationMilliseconds = 1500, string? accessToken = null, string routeMode = "smart", bool exerciseHandover = false)
|
||
{
|
||
AppPaths.EnsureDirectory();
|
||
var result = new TestResult { StartedAt = DateTimeOffset.Now, RouteMode = routeMode };
|
||
try
|
||
{
|
||
var token = string.IsNullOrWhiteSpace(accessToken) ? TokenStore.Load() : accessToken;
|
||
if (string.IsNullOrWhiteSpace(token))
|
||
{
|
||
throw new InvalidOperationException("本机没有可用的登录会话。");
|
||
}
|
||
using var api = new VpnApiClient();
|
||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(150));
|
||
var profile = await api.GetProfileAsync(token, timeout.Token);
|
||
var nodes = profile.Nodes
|
||
.Where(item => string.Equals(item.Status, "online", StringComparison.OrdinalIgnoreCase))
|
||
.Concat(profile.Nodes.Where(item => !string.Equals(item.Status, "online", StringComparison.OrdinalIgnoreCase)))
|
||
.DistinctBy(item => item.Slug, StringComparer.OrdinalIgnoreCase)
|
||
.ToList();
|
||
if (nodes.Count == 0) throw new InvalidOperationException("当前账号没有可测试的线路。");
|
||
await using var xray = new XrayManager();
|
||
var failures = new List<string>();
|
||
var excluded = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
for (var attempt = 0; attempt < Math.Min(nodes.Count, 8); attempt++)
|
||
{
|
||
NodeInfo? candidate = null;
|
||
try
|
||
{
|
||
// Exercise the same server-side automatic assignment as the
|
||
// UI, not a private test-only choice from the profile list.
|
||
var config = await api.GetConfigAsync(token, "auto", routeMode, timeout.Token, excluded);
|
||
candidate = config.Node;
|
||
result.Node = candidate.Name;
|
||
await xray.StartAsync(config.GetRuntimeConfigJson(), routeMode, candidate.Slug, timeout.Token);
|
||
break;
|
||
}
|
||
catch (LocalNetworkException) { throw; }
|
||
catch (ApiException exception) when (exception.StatusCode is 401 or 403) { throw; }
|
||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||
{
|
||
failures.Add($"{candidate?.Name ?? "AI assignment"}: {exception.Message}");
|
||
await xray.StopAsync();
|
||
if (candidate is null) break;
|
||
excluded.Add(candidate.Slug);
|
||
}
|
||
}
|
||
if (!xray.IsRunning)
|
||
{
|
||
throw new InvalidOperationException(
|
||
"所有线路均未通过出口验证。" + string.Join(";", failures));
|
||
}
|
||
result.Connected = true;
|
||
await Task.Delay(stabilizationMilliseconds, timeout.Token);
|
||
|
||
using var handler = new SocketsHttpHandler
|
||
{
|
||
UseProxy = true,
|
||
Proxy = new WebProxy("http://127.0.0.1:10809"),
|
||
ConnectTimeout = TimeSpan.FromSeconds(10),
|
||
AutomaticDecompression = DecompressionMethods.All,
|
||
};
|
||
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) };
|
||
client.DefaultRequestHeaders.UserAgent.ParseAdd("UCVL-VPNPlus-ConnectionTest/0.2.2");
|
||
result.Probes.Add(await ProbeAsync(client, "Google", "https://www.google.com/generate_204", timeout.Token));
|
||
result.Probes.Add(await ProbeAsync(client, "OpenAI API", "https://api.openai.com/v1/models", timeout.Token));
|
||
result.Probes.Add(await ProbeAsync(client, "Codex endpoint (unauthenticated)", "https://chatgpt.com/backend-api/codex/models", timeout.Token));
|
||
result.Probes.Add(await ProbeAsync(client, "ChatGPT", "https://chatgpt.com/", timeout.Token));
|
||
result.Probes.Add(await ProbeAsync(client, "管理平台", "https://vpn.toplc.cn/health/", timeout.Token));
|
||
|
||
// A browser following an explicit HTTP proxy is not evidence that
|
||
// native clients use the global TUN. Exercise both paths separately.
|
||
using var nativeHandler = new SocketsHttpHandler { UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(10) };
|
||
using var native = new HttpClient(nativeHandler) { Timeout = TimeSpan.FromSeconds(15) };
|
||
result.Probes.Add(await ProbeAsync(native, "Google via TUN (no HTTP proxy)", "https://www.google.com/generate_204", timeout.Token));
|
||
result.Probes.Add(await ProbeAsync(native, "Codex via TUN (unauthenticated)", "https://chatgpt.com/backend-api/codex/models", timeout.Token));
|
||
|
||
var google = result.Probes.First(item => item.Name == "Google");
|
||
var openAi = result.Probes.First(item => item.Name == "OpenAI API");
|
||
var platform = result.Probes.First(item => item.Name == "管理平台");
|
||
result.Passed = google.StatusCode is 200 or 204
|
||
&& openAi.StatusCode is 200 or 401
|
||
&& platform.StatusCode == 200;
|
||
var codex = result.Probes.First(item => item.Name == "Codex endpoint (unauthenticated)");
|
||
result.Passed = result.Passed && codex.StatusCode is 200 or 401;
|
||
result.Passed = result.Passed
|
||
&& result.Probes.First(item => item.Name == "Google via TUN (no HTTP proxy)").StatusCode is 200 or 204
|
||
&& result.Probes.First(item => item.Name == "Codex via TUN (unauthenticated)").StatusCode is 200 or 401;
|
||
// Probe results establish transport reachability, not an actual
|
||
// authenticated Codex conversation. Keep this distinction explicit.
|
||
if (result.Passed && exerciseHandover)
|
||
{
|
||
// Inject only the observed outage. The real Xray/route/DNS lifecycle
|
||
// executes; physical Wi-Fi/Ethernet adapters are never disabled.
|
||
var initialCore=xray.CoreId;
|
||
var initialNetwork=xray.BoundNetworkFingerprint;
|
||
var handover=new NetworkHandover(xray);
|
||
var now=Environment.TickCount64;
|
||
await handover.ObserveAsync(new(true,null),now,timeout.Token);
|
||
await Task.Delay(3100,timeout.Token);
|
||
var offline=await handover.ObserveAsync(new(true,null),Environment.TickCount64,timeout.Token);
|
||
result.HandoverChecks["outage_stops_real_core_preserves_config"]=offline==NetworkHandover.Result.Offline && !xray.IsRunning && xray.CanRebindNetwork;
|
||
var reading=PhysicalUplink.Read();
|
||
if (!reading.Success || reading.Network is null) throw new IOException("Physical uplink unavailable during protected test");
|
||
await handover.ObserveAsync(reading,Environment.TickCount64,timeout.Token);
|
||
await Task.Delay(3100,timeout.Token);
|
||
var restored=await handover.ObserveAsync(PhysicalUplink.Read(),Environment.TickCount64,timeout.Token);
|
||
result.HandoverChecks["real_core_recreated"]=restored==NetworkHandover.Result.Recovered && xray.IsRunning && xray.CoreId!=initialCore;
|
||
result.HandoverChecks["same_uplink_recovery"]=xray.BoundNetworkFingerprint==initialNetwork;
|
||
api.ResetTransport();
|
||
var fresh=await api.GetProfileAsync(token,timeout.Token);
|
||
result.HandoverChecks["platform_authorization_after_transport_reset"]=fresh.Nodes.Count>0;
|
||
using var freshHandler=new SocketsHttpHandler { UseProxy=false, ConnectTimeout=TimeSpan.FromSeconds(10) };
|
||
using var freshHttp=new HttpClient(freshHandler) { Timeout=TimeSpan.FromSeconds(15) };
|
||
var afterGoogle=await ProbeAsync(freshHttp,"Google after handover via TUN","https://www.google.com/generate_204",timeout.Token);
|
||
var afterCodex=await ProbeAsync(freshHttp,"Codex after handover via TUN","https://chatgpt.com/backend-api/codex/models",timeout.Token);
|
||
result.Probes.Add(afterGoogle); result.Probes.Add(afterCodex);
|
||
result.HandoverChecks["tun_transport_after_rebind"]=afterGoogle.StatusCode is 200 or 204 && afterCodex.StatusCode is 200 or 401;
|
||
var stableCore=xray.CoreId;
|
||
result.HandoverChecks["steady_network_does_not_loop"]=await handover.ObserveAsync(PhysicalUplink.Read(),Environment.TickCount64,timeout.Token)==NetworkHandover.Result.Unchanged && xray.CoreId==stableCore;
|
||
result.Passed &= result.HandoverChecks.Values.All(v=>v);
|
||
}
|
||
if (result.Passed && !exerciseHandover && int.TryParse(Environment.GetEnvironmentVariable("UCVL_VPN_TEST_HOLD_SECONDS"), out var seconds))
|
||
{
|
||
File.WriteAllText(AppPaths.ConnectionSelfTestFile,
|
||
JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
|
||
await Task.Delay(TimeSpan.FromSeconds(Math.Clamp(seconds, 0, 75)), timeout.Token);
|
||
}
|
||
await xray.StopAsync();
|
||
return result.Passed ? 0 : 2;
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
result.Passed = false;
|
||
result.Error = exception.Message;
|
||
AppPaths.WriteError(exception);
|
||
return 3;
|
||
}
|
||
finally
|
||
{
|
||
result.FinishedAt = DateTimeOffset.Now;
|
||
File.WriteAllText(
|
||
AppPaths.ConnectionSelfTestFile,
|
||
JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
|
||
}
|
||
}
|
||
|
||
private static async Task<ProbeResult> ProbeAsync(
|
||
HttpClient client,
|
||
string name,
|
||
string url,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var started = System.Diagnostics.Stopwatch.StartNew();
|
||
try
|
||
{
|
||
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||
return new ProbeResult
|
||
{
|
||
Name = name,
|
||
Url = url,
|
||
StatusCode = (int)response.StatusCode,
|
||
ElapsedMilliseconds = started.ElapsedMilliseconds,
|
||
};
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
return new ProbeResult
|
||
{
|
||
Name = name,
|
||
Url = url,
|
||
ElapsedMilliseconds = started.ElapsedMilliseconds,
|
||
Error = exception.GetBaseException().Message,
|
||
};
|
||
}
|
||
}
|
||
}
|