Publish reviewed history-free open-source snapshot (2026-10-12)
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Opt-in node audit: isolated loopback ports, no TUN, no proxy/route/NRPT changes.
|
||||
// Uses the app's own saved platform session; never exports the token or node config.
|
||||
internal static class NodeMatrixSelfTest
|
||||
{
|
||||
private sealed record Probe(string Target, int? HttpStatus, long Milliseconds, string Error);
|
||||
internal static async Task<int> RunAsync()
|
||||
{
|
||||
var folder = Path.Combine(Path.GetTempPath(), "ucvl-node-audit-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(folder);
|
||||
var outcomes = new List<object>();
|
||||
var report = new Dictionary<string, object> {
|
||||
["started_at"] = DateTimeOffset.Now, ["version"] = Application.ProductVersion,
|
||||
["executable_sha256"] = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Environment.ProcessPath!))),
|
||||
["system_network_modified"] = false, ["authenticated_codex_conversation_tested"] = false,
|
||||
["test_scope"] = "explicit HTTP proxy and runtime UDP DNS; not full-device TUN or UI acceptance",
|
||||
["nodes"] = outcomes,
|
||||
};
|
||||
try
|
||||
{
|
||||
using var lifetime = new CancellationTokenSource(TimeSpan.FromMinutes(6));
|
||||
var token = TokenStore.Load();
|
||||
if (string.IsNullOrWhiteSpace(token)) throw new IOException("没有可用的平台登录会话。");
|
||||
using var api = new VpnApiClient();
|
||||
var profile = await api.GetProfileAsync(token, lifetime.Token);
|
||||
foreach (var node in profile.Nodes)
|
||||
{
|
||||
var results = new List<object>();
|
||||
var result = new Dictionary<string, object> { ["node"] = node.Name, ["slug"] = node.Slug, ["rounds"] = results };
|
||||
outcomes.Add(result);
|
||||
Process? core = null;
|
||||
string? configPath = null;
|
||||
try
|
||||
{
|
||||
var response = await api.GetConfigAsync(token, node.Slug, "smart", lifetime.Token);
|
||||
var baseConfig = response.GetRuntimeConfigJson();
|
||||
var addresses = new List<IPAddress>();
|
||||
foreach (var host in TunConfigBuilder.GetProxyServerHosts(baseConfig))
|
||||
addresses.AddRange(await Dns.GetHostAddressesAsync(host, lifetime.Token));
|
||||
var physical = TunRouting.GetPhysicalNetwork(addresses);
|
||||
result["interface"] = physical.InterfaceName;
|
||||
result["gateway_hosts"] = TunConfigBuilder.GetProxyServerHosts(baseConfig);
|
||||
var httpPort = FreeTcpPort();
|
||||
using var udpReservation = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
|
||||
var dnsPort = ((IPEndPoint)udpReservation.Client.LocalEndPoint!).Port;
|
||||
var root = JsonNode.Parse(baseConfig)!.AsObject();
|
||||
root["inbounds"] = new JsonArray(
|
||||
new JsonObject { ["tag"] = "audit-http", ["listen"] = "127.0.0.1", ["port"] = httpPort, ["protocol"] = "http" },
|
||||
new JsonObject { ["tag"] = "tun-in", ["listen"] = "127.0.0.1", ["port"] = dnsPort, ["protocol"] = "dokodemo-door",
|
||||
["settings"] = new JsonObject { ["address"] = "1.1.1.1", ["port"] = 53, ["network"] = "udp" } });
|
||||
root = JsonNode.Parse(TunConfigBuilder.Build(root.ToJsonString(), physical.InterfaceName,
|
||||
includeLocalLearning: false, includeTun: false))!.AsObject();
|
||||
root["routing"]!["rules"]!.AsArray().Insert(0, new JsonObject {
|
||||
["type"] = "field", ["inboundTag"] = new JsonArray("audit-http"), ["outboundTag"] = "proxy" });
|
||||
root["log"] = new JsonObject { ["loglevel"] = "none" };
|
||||
root.Remove("api");
|
||||
configPath = Path.Combine(folder, Guid.NewGuid().ToString("N") + ".json");
|
||||
File.WriteAllText(configPath, root.ToJsonString());
|
||||
var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "xray", "xray.exe")) {
|
||||
UseShellExecute = false, CreateNoWindow = true,
|
||||
WorkingDirectory = Path.Combine(AppContext.BaseDirectory, "xray"),
|
||||
RedirectStandardOutput = true, RedirectStandardError = true,
|
||||
};
|
||||
start.ArgumentList.Add("run"); start.ArgumentList.Add("-c"); start.ArgumentList.Add(configPath);
|
||||
udpReservation.Close();
|
||||
core = Process.Start(start) ?? throw new IOException("节点测试内核未启动。");
|
||||
_ = core.StandardOutput.ReadToEndAsync();
|
||||
_ = core.StandardError.ReadToEndAsync();
|
||||
result["core_pid"] = core.Id;
|
||||
await Task.Delay(800, lifetime.Token);
|
||||
if (core.HasExited) throw new IOException("节点测试内核退出,代码 " + core.ExitCode);
|
||||
using var client = new HttpClient(new SocketsHttpHandler {
|
||||
UseProxy = true, Proxy = new WebProxy($"http://127.0.0.1:{httpPort}"),
|
||||
ConnectTimeout = TimeSpan.FromSeconds(6), AllowAutoRedirect = false,
|
||||
}) { Timeout = TimeSpan.FromSeconds(10) };
|
||||
for (var round = 1; round <= 3; round++)
|
||||
{
|
||||
var probes = await Task.WhenAll(
|
||||
HttpProbe(client, "Google", "https://www.google.com/generate_204", lifetime.Token),
|
||||
HttpProbe(client, "OpenAI", "https://api.openai.com/v1/models", lifetime.Token),
|
||||
HttpProbe(client, "Codex (no authentication)", "https://chatgpt.com/backend-api/codex/models", lifetime.Token));
|
||||
var dns = await DnsProbe(dnsPort, lifetime.Token);
|
||||
results.Add(new { round, probes, runtime_dns = dns });
|
||||
Save();
|
||||
await Task.Delay(1000, lifetime.Token);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { result["error"] = ex.GetBaseException().Message; }
|
||||
finally
|
||||
{
|
||||
if (core is not null)
|
||||
{
|
||||
try { if (!core.HasExited) core.Kill(entireProcessTree: true); await core.WaitForExitAsync(); }
|
||||
finally { core.Dispose(); }
|
||||
}
|
||||
if (configPath is not null && File.Exists(configPath)) File.Delete(configPath);
|
||||
Save();
|
||||
}
|
||||
}
|
||||
report["result"] = "CHECKED"; // Never silently turn reachability into full acceptance.
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex) { report["error"] = ex.GetBaseException().Message; return 3; }
|
||||
finally { report["finished_at"] = DateTimeOffset.Now; Save(); }
|
||||
|
||||
void Save() => File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-matrix-self-test.json"),
|
||||
JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
|
||||
private static int FreeTcpPort()
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
return ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
}
|
||||
|
||||
private static async Task<Probe> HttpProbe(HttpClient client, string name, string url, CancellationToken token)
|
||||
{
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
|
||||
return new(name, (int)response.StatusCode, elapsed.ElapsedMilliseconds, "");
|
||||
}
|
||||
catch (Exception ex) { return new(name, null, elapsed.ElapsedMilliseconds, ex.GetBaseException().Message); }
|
||||
}
|
||||
|
||||
private static async Task<object> DnsProbe(int port, CancellationToken token)
|
||||
{
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(8));
|
||||
using var udp = new UdpClient();
|
||||
udp.Connect(IPAddress.Loopback, port);
|
||||
var query = new List<byte> { 0x4a, 0x21, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
|
||||
foreach (var label in "chatgpt.com".Split('.')) { query.Add((byte)label.Length); query.AddRange(Encoding.ASCII.GetBytes(label)); }
|
||||
query.AddRange(new byte[] { 0, 0, 1, 0, 1 });
|
||||
await udp.SendAsync(query.ToArray(), timeout.Token);
|
||||
var response = (await udp.ReceiveAsync(timeout.Token)).Buffer;
|
||||
var valid = response.Length >= 12 && response[0] == 0x4a && response[1] == 0x21
|
||||
&& (response[2] & 0x80) != 0 && (response[3] & 15) == 0 && (response[6] != 0 || response[7] != 0);
|
||||
return new { passed = valid, milliseconds = elapsed.ElapsedMilliseconds };
|
||||
}
|
||||
catch (Exception ex) { return new { passed = false, milliseconds = elapsed.ElapsedMilliseconds, error = ex.GetBaseException().Message }; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user