Windows 0.3.1 clean monitor source delta; no private history or other platform changes
This commit is contained in:
@@ -27,6 +27,7 @@ internal sealed class ProfileEnvelope
|
||||
|
||||
internal sealed class Profile
|
||||
{
|
||||
[JsonPropertyName("can_view_node_traffic")] public bool CanViewNodeTraffic { get; init; }
|
||||
[JsonPropertyName("usage_history_ranges")] public Dictionary<string, UsageHistorySeries>? UsageHistoryRanges { get; init; }
|
||||
[JsonPropertyName("usage_history")] public List<DailyUsage> UsageHistory { get; init; } = [];
|
||||
[JsonPropertyName("username")] public string Username { get; init; } = "";
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ChartFreshnessSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
var at = new DateTimeOffset(2026, 10, 22, 12, 0, 0, TimeSpan.FromHours(8));
|
||||
var now = at;
|
||||
var timeline = new TrafficChartTimeline(() => now);
|
||||
var minute = TimeSpan.FromMinutes(1);
|
||||
checks["empty_history_has_no_fabricated_zero_sample"] = timeline.PointCount == 0
|
||||
&& timeline.Visible(minute).Length == 0 && !timeline.HasFreshSample && timeline.LastSampleAt is null;
|
||||
checks["injected_clock_controls_initial_axis"] = timeline.End == at;
|
||||
checks["measured_zero_is_valid_not_missing"] = timeline.Add(0, 0) && timeline.HasFreshSample
|
||||
&& timeline.PointCount == 1 && timeline.Visible(minute)[0].Up == 0;
|
||||
now = at.AddSeconds(5);
|
||||
checks["valid_sample_preserves_fractional_rates"] = timeline.Add(123.5, 987.25)
|
||||
&& timeline.Visible(minute)[^1] is { Up: 123.5, Down: 987.25 };
|
||||
var beforeGap = timeline.Visible(minute);
|
||||
var previousSegment = beforeGap[^1].Segment;
|
||||
now = at.AddSeconds(10);
|
||||
timeline.MarkUnavailable();
|
||||
checks["missing_reader_advances_axis_without_zero_point"] = timeline.End == now
|
||||
&& timeline.PointCount == 2 && !timeline.HasFreshSample && timeline.LastSampleAt == at.AddSeconds(5);
|
||||
now = at.AddSeconds(15);
|
||||
timeline.MarkUnavailable();
|
||||
timeline.AdvanceClock();
|
||||
checks["repeated_missing_ticks_do_not_add_or_change_values"] = timeline.PointCount == 2
|
||||
&& timeline.Visible(minute).SequenceEqual(beforeGap);
|
||||
now = at.AddSeconds(20);
|
||||
checks["recovery_adds_only_real_sample"] = timeline.Add(12, 34) && timeline.PointCount == 3 && timeline.HasFreshSample;
|
||||
var recovered = timeline.Visible(minute);
|
||||
checks["recovery_starts_new_curve_segment"] = recovered[^1].Segment != previousSegment;
|
||||
checks["recovery_does_not_rewrite_prior_samples_or_accumulate_gap"] = recovered.Take(2).SequenceEqual(beforeGap)
|
||||
&& recovered[^1].Up == 12 && recovered[^1].Down == 34;
|
||||
now = at.AddSeconds(25);
|
||||
checks["subsequent_good_samples_share_recovered_segment"] = timeline.Add(56, 78)
|
||||
&& timeline.Visible(minute)[^1].Segment == recovered[^1].Segment;
|
||||
var latest = timeline.LastSampleAt;
|
||||
var latestCount = timeline.PointCount;
|
||||
checks["duplicate_timestamp_cannot_double_count_display_sample"] = !timeline.Add(900, 800, now)
|
||||
&& timeline.PointCount == latestCount && timeline.LastSampleAt == latest;
|
||||
checks["late_sample_cannot_move_axis_or_replace_current_sample"] = !timeline.Add(900, 800, at.AddSeconds(1))
|
||||
&& timeline.PointCount == latestCount && timeline.End == now && timeline.HasFreshSample;
|
||||
timeline.AdvanceClock(at.AddMinutes(-1));
|
||||
checks["backwards_clock_does_not_rewind_axis"] = timeline.End == now;
|
||||
|
||||
var unannounced = new TrafficChartTimeline(() => now);
|
||||
unannounced.Add(1, 2, at);
|
||||
unannounced.Add(3, 4, at.AddSeconds(5));
|
||||
var segment = unannounced.Visible(minute)[^1].Segment;
|
||||
now = at.AddSeconds(20);
|
||||
unannounced.AdvanceClock();
|
||||
checks["fifteen_second_age_boundary_is_still_fresh"] = unannounced.HasFreshSample;
|
||||
now = at.AddSeconds(21);
|
||||
unannounced.AdvanceClock();
|
||||
checks["silent_reader_stalls_become_unavailable_after_deadline"] = !unannounced.HasFreshSample
|
||||
&& unannounced.PointCount == 2 && unannounced.End == now;
|
||||
now = at.AddSeconds(25);
|
||||
unannounced.Add(5, 6);
|
||||
checks["silent_gap_recovery_does_not_bridge_line"] = unannounced.HasFreshSample
|
||||
&& unannounced.Visible(minute)[^1].Segment != segment;
|
||||
var noTick = new TrafficChartTimeline(() => now);
|
||||
noTick.Add(7, 8, at);
|
||||
noTick.Add(9, 10, at.AddSeconds(20));
|
||||
checks["large_timestamp_gap_breaks_line_even_without_missing_tick"] = noTick.Visible(minute)
|
||||
.Select(point => point.Segment).Distinct().Count() == 2;
|
||||
|
||||
foreach (var (label, up, down) in new[]
|
||||
{
|
||||
("negative_up", -1d, 1d), ("negative_down", 1d, -1d),
|
||||
("nan_up", double.NaN, 1d), ("nan_down", 1d, double.NaN),
|
||||
("positive_infinity", double.PositiveInfinity, 1d), ("negative_infinity", 1d, double.NegativeInfinity)
|
||||
})
|
||||
{
|
||||
var invalid = new TrafficChartTimeline(() => now);
|
||||
invalid.Add(11, 22, at);
|
||||
now = at.AddSeconds(5);
|
||||
checks[label + "_is_missing_not_fake_zero"] = !invalid.Add(up, down) && invalid.PointCount == 1
|
||||
&& !invalid.HasFreshSample && invalid.Visible(minute)[0] is { Up: 11, Down: 22 };
|
||||
now = at.AddSeconds(10);
|
||||
invalid.Add(33, 44);
|
||||
checks[label + "_recovery_breaks_curve"] = invalid.Visible(minute)[0].Segment
|
||||
!= invalid.Visible(minute)[1].Segment;
|
||||
}
|
||||
|
||||
var history = new TrafficChartTimeline(() => now);
|
||||
for (var i = 0; i <= 720; i++) history.Add(i, i * 2, at.AddSeconds(i * 5));
|
||||
checks["actual_five_second_samples_keep_one_hour_inclusive"] = history.PointCount == 721;
|
||||
checks["period_selection_only_filters_actual_samples"] = history.Visible(minute).Length == 13
|
||||
&& history.Visible(TimeSpan.FromMinutes(5)).Length == 61
|
||||
&& history.Visible(TimeSpan.FromMinutes(15)).Length == 181
|
||||
&& history.Visible(TimeSpan.FromMinutes(60)).Length == 721 && history.PointCount == 721;
|
||||
now = at.AddHours(1).AddSeconds(5);
|
||||
history.AdvanceClock();
|
||||
checks["retention_prunes_while_sampling_is_stopped"] = history.PointCount == 720
|
||||
&& history.Visible(TimeSpan.FromMinutes(60))[0].Time == at.AddSeconds(5);
|
||||
now = at.AddHours(1).AddMinutes(2);
|
||||
history.MarkUnavailable();
|
||||
checks["selected_window_expires_without_new_samples"] = history.Visible(minute).Length == 0 && !history.HasFreshSample;
|
||||
now = at.AddHours(2).AddSeconds(1);
|
||||
history.AdvanceClock();
|
||||
checks["whole_history_expires_without_synthetic_points"] = history.PointCount == 0
|
||||
&& history.Visible(TimeSpan.FromHours(1)).Length == 0 && history.LastSampleAt == at.AddHours(1);
|
||||
checks["axis_continues_after_history_is_empty"] = history.End == now;
|
||||
history.Add(99, 88);
|
||||
checks["post_expiry_recovery_is_one_actual_point"] = history.PointCount == 1 && history.HasFreshSample
|
||||
&& history.Visible(minute)[0] is { Up: 99, Down: 88 };
|
||||
history.Reset();
|
||||
checks["reset_discards_old_sample_segment_and_freshness"] = history.PointCount == 0 && !history.HasFreshSample
|
||||
&& history.LastSampleAt is null && history.End == now;
|
||||
history.Add(0, 0);
|
||||
checks["zero_after_reset_is_real_sample_in_initial_segment"] = history.PointCount == 1
|
||||
&& history.Visible(minute)[0].Segment == 0 && history.HasFreshSample;
|
||||
|
||||
var bounded = new TrafficChartTimeline(() => at);
|
||||
for (var i = 0; i < 4000; i++) bounded.Add(i, i, at.AddMilliseconds(i));
|
||||
checks["high_frequency_history_remains_bounded"] = bounded.PointCount == 3600;
|
||||
}
|
||||
catch (Exception exception) { error = exception.ToString(); }
|
||||
var passed = error is null && checks.Count >= 35 && checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "chart-freshness-self-test.json"),
|
||||
JsonSerializer.Serialize(new
|
||||
{
|
||||
passed, checks, error,
|
||||
scope = "pure presentation-history clock and missing-sample policy; not a real-window, network-throughput or cumulative-accounting acceptance",
|
||||
network_modified = false, installed_client_modified = false, credentials_loaded = false,
|
||||
untested = new[] { "physical multi-monitor DPI transitions", "live resize frame latency", "production tray/occlusion pixel stability" }
|
||||
}, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 29;
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ internal static class ConnectionSelfTest
|
||||
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));
|
||||
result.Probes.Add(await ProbeAsync(client, "管理平台", "https://vpn.example.invalid/health/", timeout.Token));
|
||||
|
||||
// A browser following an explicit HTTP proxy is not evidence that
|
||||
// native clients use the global TUN. Exercise both paths separately.
|
||||
|
||||
@@ -98,6 +98,27 @@ internal sealed partial class MainForm
|
||||
checks["whole_content_composition_disabled"] = !_content.ComposeChildren;
|
||||
checks["metric_dirty_refresh_clears_previous_digits"] = CheckMetricRefreshPaint();
|
||||
foreach (var check in CheckTailnetTrafficUi()) checks.Add(check.Key, check.Value);
|
||||
var monitorSize = ClientSize;
|
||||
var monitorAccounting = (_sessionUp, _sessionDown, _trafficChart.PointCount);
|
||||
SetNodeTrafficPermission(true);
|
||||
SetTailnetTrafficVisibility(true);
|
||||
LayoutDashboard();
|
||||
Application.DoEvents();
|
||||
using (var monitorFont = Brand.Font(7.1f))
|
||||
{
|
||||
var monitorTextHeight = TextRenderer.MeasureText("VPN002 上传", monitorFont).Height;
|
||||
var rows = NodeTrafficPanel.TextLayout(_nodeTrafficPanel.ClientSize, DeviceDpi, monitorTextHeight);
|
||||
checks["monitor_two_native_dpi_text_rows_fit"] = rows.Rows.All(row => row.Height >= monitorTextHeight)
|
||||
&& !rows.Rows[0].IntersectsWith(rows.Rows[1]);
|
||||
}
|
||||
checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize
|
||||
&& _nodeTrafficPanel.Top > _dailyCard.Bottom && _nodeTrafficPanel.Bottom < _footer.Top
|
||||
&& !_dashboardScrollBar.Visible && _dashboardBody.Top == 0;
|
||||
checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit();
|
||||
checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount);
|
||||
SetNodeTrafficPermission(false);
|
||||
SetTailnetTrafficVisibility(false);
|
||||
checks["monitor_revoked_hides_and_stops_timer"] = !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled;
|
||||
ShowLogin();
|
||||
checks["hidden_dashboard_does_not_consume_login_wheel"] = !Wheel(_loginText, -120);
|
||||
RequestExit();
|
||||
|
||||
@@ -3,19 +3,19 @@ namespace UCVL.VPNPlus;
|
||||
internal readonly record struct DashboardGeometry(
|
||||
Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge,
|
||||
Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard,
|
||||
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle Footer,
|
||||
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer,
|
||||
int ContentHeight, bool Compact, float VerticalScale);
|
||||
|
||||
// Logical pixels converted once, independent of WinForms autoscaling.
|
||||
internal static class DashboardLayout
|
||||
{
|
||||
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false)
|
||||
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false)
|
||||
{
|
||||
var scale = Math.Max(1f, dpi / 96f);
|
||||
int S(int n) => (int)Math.Round(n * scale);
|
||||
// Tailnet is a subdivision of the existing speed area, not another
|
||||
// dashboard row. Fit the complete canvas even on a small/high-DPI screen.
|
||||
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / (614f * scale));
|
||||
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / ((showServerTraffic ? 718f : 614f) * scale));
|
||||
int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale));
|
||||
var margin = S(20);
|
||||
var gap = Y(10);
|
||||
@@ -43,23 +43,26 @@ internal static class DashboardLayout
|
||||
speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82));
|
||||
// Relative to their matching chart card: totals together; speeds together.
|
||||
Rectangle[] metrics = [Metric(daily, 0, false), Metric(traffic, 0, true), Metric(traffic, 1, true), Metric(daily, 1, false)];
|
||||
var footer = new Rectangle(margin, daily.Bottom + gap, width, Y(76));
|
||||
var serverTraffic = showServerTraffic ? new Rectangle(margin, daily.Bottom + gap, width, Y(94)) : Rectangle.Empty;
|
||||
var footer = new Rectangle(margin, (showServerTraffic ? serverTraffic.Bottom : daily.Bottom) + gap, width, Y(76));
|
||||
return new(welcome, account, identity, logout, status, node, mode, metrics, traffic,
|
||||
tailnet, daily, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
|
||||
tailnet, daily, serverTraffic, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
|
||||
}
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 })
|
||||
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288, 336, 384 })
|
||||
foreach (var width in new[] { 600, 620, 739, 760, 780, 900, 1100, 1600 })
|
||||
foreach (var height in new[] { 350, 418, 560, 720 })
|
||||
foreach (var showTailnet in new[] { false, true })
|
||||
foreach (var showServers in new[] { false, true })
|
||||
{
|
||||
var viewport = new Size(width * dpi / 96, height * dpi / 96);
|
||||
var p = Calculate(viewport, dpi, showTailnet);
|
||||
var p = Calculate(viewport, dpi, showTailnet, showServers);
|
||||
Rectangle[] cards = showTailnet
|
||||
? [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.TailnetTrafficCard, p.DailyCard, p.Footer]
|
||||
: [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.DailyCard, p.Footer];
|
||||
if (showServers) cards = [..cards, p.ServerTrafficCard];
|
||||
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0)) return false;
|
||||
for (var i = 0; i < cards.Length; i++)
|
||||
for (var j = i + 1; j < cards.Length; j++)
|
||||
@@ -70,10 +73,11 @@ internal static class DashboardLayout
|
||||
if (p.Metrics[i].Right > (i == 0 || i == 3 ? p.DailyCard.Width : p.TrafficCard.Width)) return false;
|
||||
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false;
|
||||
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
|
||||
var baseline = Calculate(viewport, dpi, false);
|
||||
var baseline = Calculate(viewport, dpi, false, showServers);
|
||||
if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false;
|
||||
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom
|
||||
|| p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom)) return false;
|
||||
if (showServers && (p.ServerTrafficCard.Top <= p.DailyCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -49,8 +49,15 @@ internal sealed partial class MainForm
|
||||
&& _dailyCard.Controls.OfType<TrafficChart>().Single() == _trafficChart
|
||||
&& _dailyChart.Parent is null && !_dailyChart.Visible;
|
||||
UpdateConnectedTransportPresentation(true);
|
||||
DisplayTraffic(1024, 2048, "互斥入口样本");
|
||||
DisplayTailnetTraffic(1024, 2048, "互斥入口样本");
|
||||
checks["tailnet_sample_is_not_duplicated_as_public_speed"] = _uploadMetric.ValueText == "—"
|
||||
&& _downloadMetric.ValueText == "—" && _uploadMetric.Hint == "未使用公网入口"
|
||||
&& _tailnetUploadMetric.ValueText == "1" && _tailnetDownloadMetric.ValueText == "2";
|
||||
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
|
||||
UpdateConnectedTransportPresentation(false);
|
||||
DisplayTraffic(3072, 4096, "公网样本");
|
||||
checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3" && _downloadMetric.ValueText == "4";
|
||||
checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
|
||||
using var curve = new TrafficChart();
|
||||
var end = DateTimeOffset.Now;
|
||||
|
||||
@@ -22,7 +22,7 @@ internal static class GitReleasePolicySelfTest
|
||||
var release = JsonNode.Parse(JsonSerializer.Serialize(new {
|
||||
tag_name="windows-v0.2.16", draft=false, prerelease=false, body="fixture",
|
||||
assets=new[] {
|
||||
new { name=Name, size=300000, browser_download_url="http://172.16.0.21:3000/untrusted.exe" },
|
||||
new { name=Name, size=300000, browser_download_url="http://192.0.2.21:3000/untrusted.exe" },
|
||||
new { name=Name+".sha256", size=120, browser_download_url="https://untrusted.invalid/sha" },
|
||||
},
|
||||
}))!;
|
||||
|
||||
@@ -105,7 +105,7 @@ internal static class InstallationIntegration
|
||||
!string.Equals(InstallationTransaction.Root((string)Decode(registered)), target, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new IOException("安装目录与当前登记不一致,未覆盖其它安装。");
|
||||
object[] next = [Path.Combine(target, "VPNPlus.exe"), target, "优创⁺纵横家", Path.Combine(target, "VPNPlus.exe"),
|
||||
version, "优创未来(UCVL)", "https://vpn.toplc.cn/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1];
|
||||
version, "优创未来(UCVL)", "https://vpn.example.invalid/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1];
|
||||
var values = Names.Select((name, i) => new Registration(i,
|
||||
Encode(next[i], i < 8 ? RegistryValueKind.String : RegistryValueKind.DWord),
|
||||
Read(hive, Key(target, isolated, KeyIndex(i)), name))).ToList();
|
||||
|
||||
@@ -18,7 +18,7 @@ internal static class LearningSelfTest
|
||||
checks["http_auth_status_is_not_failure"] = Parse("HTTP 401 / 403 / 429 direct learn.example.com:443") is null;
|
||||
checks["proxy_failures_not_direct"] = Parse(line.Replace("proxy/freedom", "proxy/vless/outbound")) is null;
|
||||
checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "192.168.50.111")) is null;
|
||||
checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.toplc.cn")) is null;
|
||||
checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.example.invalid")) is null;
|
||||
checks["source_not_misidentified"] = Parse("tcp:127.0.0.1:777 " + line)?.Target == "learn.example.com";
|
||||
checks["oversized_line_rejected"] = Parse(new string('x', 8193) + line) is null;
|
||||
const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]";
|
||||
@@ -71,7 +71,7 @@ internal static class LearningSelfTest
|
||||
checks["private_precedes_learned"] = JsonNode.Parse(verified)!["routing"]!["rules"]![0]!["ip"]![0]!.GetValue<string>() == "geoip:private";
|
||||
checks["expiry_restores_direct"] = !LearningPolicy.Merge(verified, new() { Contract=1, Revision=new string('b',64) }).Contains("learn.example.com");
|
||||
checks["network_change_restores_direct"] = !LearningPolicy.DirectFirst(verified).Contains("learn.example.com");
|
||||
checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.toplc.cn")));
|
||||
checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.example.invalid")));
|
||||
checks["invalid_manifest_contract_rejected"] = Throws(() => LearningPolicy.Merge(direct, new() { Contract=99, Revision=new string('a',64) }));
|
||||
var runtime = JsonNode.Parse(TunConfigBuilder.Build(direct, "Ethernet", true, includeTun:false, routingApiPort:18090, learningProbePort:18091))!;
|
||||
checks["info_in_memory_access_disabled"] = runtime["log"]!["loglevel"]!.GetValue<string>() == "info" && runtime["log"]!["access"]!.GetValue<string>() == "none";
|
||||
|
||||
@@ -94,7 +94,8 @@ internal sealed partial class MainForm
|
||||
_routeReadOnly.Visible = false;
|
||||
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]);
|
||||
|
||||
ConfigureLabel(_trafficHeading, "代理实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_trafficHeading, "公网入口速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
_trafficCard.AccessibleDescription = "仅当前纵横家使用域名或公网入口的代理速度;Tailscale 入口速度另列,非整机流量。";
|
||||
ConfigureLabel(_dailyHeading, "速度与累计", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted);
|
||||
_sampleLabel.TextAlign = ContentAlignment.MiddleRight;
|
||||
@@ -139,7 +140,7 @@ internal sealed partial class MainForm
|
||||
_footerPoem.TextAlign = ContentAlignment.MiddleRight;
|
||||
_footerCompanyLogo.Image = LoadCompanyLogo();
|
||||
_footerCompanyLogo.SizeMode = PictureBoxSizeMode.Zoom;
|
||||
ConfigureLabel(_footerCompanySite, "vpn.toplc.cn", Brand.Font(8), Brand.Muted);
|
||||
ConfigureLabel(_footerCompanySite, "vpn.example.invalid", Brand.Font(8), Brand.Muted);
|
||||
_footerCompanyLogo.BackColor = Color.Transparent;
|
||||
_footer.Controls.AddRange([_planLabel, _expiryLabel, _footerHint, _footerPoem, _footerCompanyLogo, _footerCompanySite]);
|
||||
foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard })
|
||||
@@ -151,6 +152,7 @@ internal sealed partial class MainForm
|
||||
_trafficCard.Controls.AddRange([_uploadMetric, _downloadMetric]);
|
||||
_dailyCard.Controls.AddRange([_usageMetric, _sessionMetric]);
|
||||
BuildTailnetTrafficCard();
|
||||
BuildNodeTrafficMonitor();
|
||||
_dashboardBody.Controls.Add(_footer);
|
||||
foreach (var label in new[] { _welcomeLabel, _accountLabel, _statusTitle, _statusDetail, _currentNodeLabel, _planLabel, _expiryLabel })
|
||||
{
|
||||
@@ -166,8 +168,11 @@ internal sealed partial class MainForm
|
||||
|
||||
private void DisplayTraffic(double? upload, double? download, string sampling)
|
||||
{
|
||||
_uploadMetric.SetBytes(upload, speed: true, hint: "");
|
||||
_downloadMetric.SetBytes(download, speed: true, hint: "");
|
||||
var publicUpload = _currentNodeUsesTailnet ? null : upload;
|
||||
var publicDownload = _currentNodeUsesTailnet ? null : download;
|
||||
var hint = _currentNodeUsesTailnet ? "未使用公网入口" : "";
|
||||
_uploadMetric.SetBytes(publicUpload, speed: true, hint: hint);
|
||||
_downloadMetric.SetBytes(publicDownload, speed: true, hint: hint);
|
||||
_sampleLabel.Text = sampling;
|
||||
_uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —";
|
||||
_downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —";
|
||||
@@ -180,12 +185,12 @@ internal sealed partial class MainForm
|
||||
{
|
||||
if (_layingOutDashboard || _dashboardView.ClientSize.Width <= 0) return;
|
||||
_layingOutDashboard = true;
|
||||
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _footer];
|
||||
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _nodeTrafficPanel, _footer];
|
||||
foreach (var container in layoutContainers) container.SuspendLayout();
|
||||
try
|
||||
{
|
||||
var viewport = _dashboardView.ClientSize;
|
||||
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible);
|
||||
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible, _canViewNodeTraffic);
|
||||
var titleSize = 17f * Math.Max(.7f, layout.VerticalScale);
|
||||
if (Math.Abs(_statusTitle.Font.Size - titleSize) > .1f)
|
||||
{
|
||||
@@ -205,6 +210,7 @@ internal sealed partial class MainForm
|
||||
var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric };
|
||||
for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]);
|
||||
Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
|
||||
Place(_nodeTrafficPanel, layout.ServerTrafficCard);
|
||||
LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale);
|
||||
|
||||
_statusDot.Bounds = R(24, 15, 42, 46);
|
||||
@@ -226,7 +232,7 @@ internal sealed partial class MainForm
|
||||
_routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28));
|
||||
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28));
|
||||
_trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20);
|
||||
_trafficHeading.Bounds = R(42, 8, 92, 26);
|
||||
_trafficHeading.Bounds = R(42, 8, 150, 26);
|
||||
_dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26));
|
||||
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(120), Y(8), ScaleLogical(106), Y(26));
|
||||
_trafficChart.Bounds = new(ScaleLogical(10), Y(127), _dailyCard.Width - ScaleLogical(20), Y(105));
|
||||
|
||||
@@ -66,6 +66,7 @@ internal sealed partial class MainForm
|
||||
{
|
||||
if (_currentNodeUsesTailnet && !_xray.UsesTailnet)
|
||||
{
|
||||
_tailnetPreference.CommitDomainFallback();
|
||||
if (_currentNodeSlug is not null) _tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64);
|
||||
_transportRetryNodeSlug = null;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ internal sealed partial class MainForm
|
||||
_connectionAttemptCancellation?.Cancel();
|
||||
_accessToken = token;
|
||||
_sessionRevision++;
|
||||
_nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true);
|
||||
_nextNodeTrafficAttempt = DateTimeOffset.MinValue;
|
||||
_learningSync.Reset();
|
||||
_learningSyncCore = null;
|
||||
_tailnetReadiness.Reset();
|
||||
|
||||
@@ -12,7 +12,8 @@ internal sealed partial class MainForm
|
||||
if (selection.Manual || routeMode == "direct")
|
||||
return legacy.Select(a => new PlannedTransport(a)).ToArray();
|
||||
|
||||
_statusDetail.Text = "先并行检测授权内网入口,按响应时间选择;全部不可用后再使用公网。";
|
||||
_statusDetail.Text = _tailnetPreference.DomainOnly ? "本次连接保持域名入口,不再自动切回内网。"
|
||||
: "先 Ping 授权代理内网 IP,按响应时间选择;不通则使用域名。";
|
||||
var publicTailnet = await PublicTailnetSelection.RankAsync(
|
||||
_manualNodeCombo.Items.Cast<NodeInfo>().Where(n => n is not PrivateAuxiliaryNode), routeMode,
|
||||
slug => _failedNodes.ContainsKey(slug) || !_tailnetPreference.MayTry(slug, Environment.TickCount64),
|
||||
|
||||
+28
-12
@@ -507,7 +507,7 @@ internal sealed partial class MainForm : Form
|
||||
_connectionHealth.Invalidate();
|
||||
_nextReconnect = DateTimeOffset.MinValue;
|
||||
_wantConnected = true;
|
||||
if (!reconnect) { _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
|
||||
if (!reconnect) { _tailnetPreference.ResetForUserConnect(); _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
|
||||
foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug);
|
||||
SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…");
|
||||
var replacementStarted = false;
|
||||
@@ -521,7 +521,7 @@ internal sealed partial class MainForm : Form
|
||||
throw new InvalidOperationException("私有节点授权已过期,请刷新账号信息后重试。");
|
||||
if (route.Id == "direct" && selection.Manual && privateGrants.Any(n => n.Slug == selection.NodeSlug))
|
||||
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
|
||||
var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
|
||||
var rankedPrivate = route.Id == "direct" || _tailnetPreference.DomainOnly ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
|
||||
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
|
||||
PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
|
||||
var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
|
||||
@@ -705,7 +705,16 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
private async Task RefreshTrafficAsync()
|
||||
{
|
||||
if (_trafficReading || _busy || !_xray.IsRunning || _exiting) return;
|
||||
_trafficChart.AdvanceClock();
|
||||
if (_exiting) return;
|
||||
if (_trafficReading) return;
|
||||
if (_busy || !_xray.IsRunning)
|
||||
{
|
||||
_trafficChart.MarkUnavailable();
|
||||
_historyStatus.Text = "采样暂停 · 历史时间轴继续推进";
|
||||
DisplayTraffic(null, null, "采样暂停");
|
||||
return;
|
||||
}
|
||||
_trafficReading = true;
|
||||
try
|
||||
{
|
||||
@@ -713,6 +722,8 @@ internal sealed partial class MainForm : Form
|
||||
var counters = await _xray.ReadTrafficAsync(_lifetime.Token);
|
||||
if (counters is null || core != _xray.CoreId)
|
||||
{
|
||||
_trafficChart.MarkUnavailable();
|
||||
_historyStatus.Text = "采样暂不可用 · 不补零";
|
||||
DisplayTraffic(null, null, "采样暂不可用");
|
||||
return;
|
||||
}
|
||||
@@ -726,6 +737,7 @@ internal sealed partial class MainForm : Form
|
||||
DisplayTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
|
||||
_sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计");
|
||||
_trafficChart.Add(up/seconds, down/seconds);
|
||||
_historyStatus.Text = "仅本次运行采样 · B/s";
|
||||
// This is a view of the SAME proxy sample, not a second counter.
|
||||
// A single connected proxy uses either its Tailnet or public ingress.
|
||||
// Do not read the whole Tailscale adapter or add this subset to usage.
|
||||
@@ -733,7 +745,13 @@ internal sealed partial class MainForm : Form
|
||||
DisplayTailnetTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception exception) { AppPaths.WriteError(exception); }
|
||||
catch (Exception exception)
|
||||
{
|
||||
_trafficChart.MarkUnavailable();
|
||||
_historyStatus.Text = "采样暂不可用 · 不补零";
|
||||
DisplayTraffic(null, null, "采样暂不可用");
|
||||
AppPaths.WriteError(exception);
|
||||
}
|
||||
finally { _trafficReading = false; }
|
||||
}
|
||||
|
||||
@@ -776,7 +794,6 @@ internal sealed partial class MainForm : Form
|
||||
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
|
||||
await CheckTailnetReadinessAsync();
|
||||
return;
|
||||
}
|
||||
if (decision == ConnectionHealthPolicy.Decision.Repair) {
|
||||
@@ -786,7 +803,6 @@ internal sealed partial class MainForm : Form
|
||||
_statusDot.ForeColor = _statusTitle.ForeColor;
|
||||
_notifyIcon.Text = "纵横家 · 分流修复中";
|
||||
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
|
||||
await CheckTailnetReadinessAsync();
|
||||
return;
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
|
||||
@@ -798,6 +814,7 @@ internal sealed partial class MainForm : Form
|
||||
// Transport failure is not node failure. Retry the same authorized
|
||||
// node through its original ingress before asking for another node.
|
||||
_tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64);
|
||||
_tailnetPreference.CommitDomainFallback();
|
||||
_transportRetryNodeSlug = _currentNodeSlug;
|
||||
}
|
||||
else _failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5);
|
||||
@@ -995,6 +1012,7 @@ internal sealed partial class MainForm : Form
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
_knownTailnetAllowed = false;
|
||||
_refreshTimer.Stop();
|
||||
SetNodeTrafficPermission(false);
|
||||
_content.SuspendLayout();
|
||||
_loginView.SuspendLayout();
|
||||
try
|
||||
@@ -1035,6 +1053,7 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
_knownTailnetAllowed = true;
|
||||
SetNodeTrafficPermission(profile.CanViewNodeTraffic);
|
||||
var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null;
|
||||
_welcomeLabel.Text = $"你好,{profile.DisplayName}";
|
||||
_accountLabel.Text = profile.Email;
|
||||
@@ -1179,6 +1198,7 @@ internal sealed partial class MainForm : Form
|
||||
_busy = true;
|
||||
StopHandoverMonitoring();
|
||||
_refreshTimer.Stop(); _updateTimer.Stop(); _trafficTimer.Stop(); _healthTimer.Stop();
|
||||
_nodeTrafficTimer.Stop();
|
||||
_lifetime.Cancel();
|
||||
if (_uiOnly || _preview) return _exitCleanupTask = Task.FromResult<Exception?>(null);
|
||||
// The same tracked cleanup serves menu/installer exit and session end.
|
||||
@@ -1253,13 +1273,9 @@ internal sealed partial class MainForm : Form
|
||||
var showItem = new ToolStripMenuItem("显示纵横家");
|
||||
var menu = new ContextMenuStrip();
|
||||
menu.Items.Add(showItem);
|
||||
menu.Items.Add(_tailnetReconnectItem);
|
||||
menu.Items.Add(new ToolStripSeparator());
|
||||
menu.Items.Add(exitItem);
|
||||
showItem.Click += (_, _) => ShowFromTray();
|
||||
_tailnetReconnectItem.Click += async (_, _) => await ReconnectThroughPreferredTailnetAsync();
|
||||
menu.Opening += (_, _) => _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady
|
||||
&& !_busy && !_exiting && _wantConnected && _xray.IsRunning && !_xray.UsesTailnet;
|
||||
exitItem.Click += (_, _) => RequestExit();
|
||||
var notify = new NotifyIcon
|
||||
{
|
||||
@@ -1337,14 +1353,14 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
|
||||
{
|
||||
FileName = "https://vpn.toplc.cn/register/",
|
||||
FileName = "https://vpn.example.invalid/register/",
|
||||
UseShellExecute = true,
|
||||
});
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppPaths.WriteError(exception);
|
||||
MessageBox.Show("无法打开注册页面,请在浏览器访问 https://vpn.toplc.cn/register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
MessageBox.Show("无法打开注册页面,请在浏览器访问 https://vpn.example.invalid/register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed class NodeTrafficSnapshot
|
||||
{
|
||||
[JsonPropertyName("contract")] public int Contract { get; init; }
|
||||
[JsonPropertyName("scope")] public string Scope { get; init; } = "";
|
||||
[JsonPropertyName("source")] public string Source { get; init; } = "";
|
||||
[JsonPropertyName("direction")] public string Direction { get; init; } = "";
|
||||
[JsonPropertyName("counter_since")] public string CounterSince { get; init; } = "";
|
||||
[JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; }
|
||||
[JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = [];
|
||||
}
|
||||
|
||||
internal sealed class NodeTrafficReading
|
||||
{
|
||||
[JsonPropertyName("slug")] public string Slug { get; init; } = "";
|
||||
[JsonPropertyName("name")] public string Name { get; init; } = "";
|
||||
[JsonPropertyName("region")] public string Region { get; init; } = "";
|
||||
[JsonPropertyName("current_upload_bytes_per_second")] public long? UploadRate { get; init; }
|
||||
[JsonPropertyName("current_download_bytes_per_second")] public long? DownloadRate { get; init; }
|
||||
[JsonPropertyName("total_upload_bytes")] public long? TotalUpload { get; init; }
|
||||
[JsonPropertyName("total_download_bytes")] public long? TotalDownload { get; init; }
|
||||
[JsonPropertyName("sampled_at")] public DateTimeOffset? SampledAt { get; init; }
|
||||
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
|
||||
[JsonPropertyName("stale")] public bool Stale { get; init; }
|
||||
[JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; }
|
||||
}
|
||||
|
||||
// Read-only display contract: no personal accounting or route/core mutations.
|
||||
internal static class NodeTrafficPresentation
|
||||
{
|
||||
internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"];
|
||||
internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1
|
||||
&& value.Scope == "server_host_interface" && value.Source == "linux_host_interface"
|
||||
&& value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset"
|
||||
&& value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15)
|
||||
&& value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null)
|
||||
&& value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count
|
||||
&& value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal)
|
||||
&& n.UploadRate is not < 0 && n.DownloadRate is not < 0
|
||||
&& n.TotalUpload is not < 0 && n.TotalDownload is not < 0
|
||||
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30));
|
||||
|
||||
internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale
|
||||
&& row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15)
|
||||
&& row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch);
|
||||
internal static string Bytes(long? bytes, bool speed = false)
|
||||
{
|
||||
if (bytes is null or < 0) return "—";
|
||||
var value = (double)bytes.Value;
|
||||
string[] units = ["B", "KB", "MB", "GB", "TB"];
|
||||
var unit = 0;
|
||||
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
|
||||
return $"{value:0.##} {units[unit]}" + (speed ? "/s" : "");
|
||||
}
|
||||
}
|
||||
|
||||
// One buffered surface, not a table of native child HWNDs. A snapshot swaps
|
||||
// atomically on the UI thread and never changes row count or window height.
|
||||
internal sealed class NodeTrafficPanel : CardPanel
|
||||
{
|
||||
private NodeTrafficSnapshot? _snapshot;
|
||||
private string _status = "等待服务器采样";
|
||||
internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); }
|
||||
internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); }
|
||||
internal NodeTrafficPanel() => AccessibleName = "VPN 服务器上行下行实时速度与累计流量";
|
||||
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
|
||||
{
|
||||
var pad = Math.Max(2, 4 * dpi / 96);
|
||||
var contentHeight = Math.Max(0, size.Height - pad * 2);
|
||||
var title = contentHeight >= fontHeight * 3;
|
||||
var height = contentHeight / (title ? 3 : 2);
|
||||
Rectangle Line(int row) => new(pad, pad + row * height, Math.Max(0, size.Width - pad * 2), height);
|
||||
return (title ? Line(0) : Rectangle.Empty, [Line(title ? 1 : 0), Line(title ? 2 : 1)]);
|
||||
}
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
using var font = Brand.Font(7.1f);
|
||||
var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height);
|
||||
var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis;
|
||||
if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 主 WAN 网卡 · 累计自网卡启动 / 重置", font,
|
||||
layout.Title, Brand.Muted, flags);
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
var slug = NodeTrafficPresentation.Slugs[i];
|
||||
var row = _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug);
|
||||
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now)
|
||||
&& NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新";
|
||||
var name = i == 0 ? "VPN002 东京" : "VPN003 美国";
|
||||
var up = fresh ? row!.UploadRate : null;
|
||||
var down = fresh ? row!.DownloadRate : null;
|
||||
var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
|
||||
: row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报";
|
||||
var text = $"{name} ↑ {NodeTrafficPresentation.Bytes(up, true)} ↓ {NodeTrafficPresentation.Bytes(down, true)}"
|
||||
+ $" 累计 ↑ {NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓ {NodeTrafficPresentation.Bytes(row?.TotalDownload)} {status}";
|
||||
TextRenderer.DrawText(e.Graphics, text, font,
|
||||
layout.Rows[i], Brand.Text, flags);
|
||||
}
|
||||
AccessibleDescription = _status + ";速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。";
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
private readonly NodeTrafficPanel _nodeTrafficPanel = new();
|
||||
private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 };
|
||||
private bool _canViewNodeTraffic, _nodeTrafficReading;
|
||||
private DateTimeOffset _nextNodeTrafficAttempt;
|
||||
private void BuildNodeTrafficMonitor()
|
||||
{
|
||||
_nodeTrafficPanel.Visible = false;
|
||||
_dashboardBody.Controls.Add(_nodeTrafficPanel);
|
||||
_nodeTrafficTimer.Tick += async (_, _) => await RefreshNodeTrafficAsync();
|
||||
_nodeTrafficPanel.Disposed += (_, _) => _nodeTrafficTimer.Dispose();
|
||||
}
|
||||
private void SetNodeTrafficPermission(bool allowed)
|
||||
{
|
||||
if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true);
|
||||
_canViewNodeTraffic = allowed;
|
||||
_nodeTrafficPanel.Visible = allowed;
|
||||
if (allowed && !_preview && !_uiOnly && !_exiting) _nodeTrafficTimer.Start();
|
||||
else _nodeTrafficTimer.Stop();
|
||||
LayoutDashboard();
|
||||
}
|
||||
private async Task RefreshNodeTrafficAsync()
|
||||
{
|
||||
_nodeTrafficPanel.Invalidate();
|
||||
if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting
|
||||
|| string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return;
|
||||
var token = _accessToken;
|
||||
var revision = _sessionRevision;
|
||||
bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token;
|
||||
_nodeTrafficReading = true;
|
||||
try
|
||||
{
|
||||
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token);
|
||||
if (!Current()) return;
|
||||
if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。");
|
||||
_nodeTrafficPanel.SetSnapshot(result);
|
||||
}
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
if (Current()) { _nodeTrafficPanel.Unavailable("监控权限不可用", clear: true); SetNodeTrafficPermission(false); }
|
||||
// An optional monitor must not log out or disconnect the VPN.
|
||||
}
|
||||
catch (ApiException error) when (error.StatusCode is 404 or 405)
|
||||
{
|
||||
if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); }
|
||||
}
|
||||
catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); }
|
||||
catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); }
|
||||
finally { _nodeTrafficReading = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class NodeTrafficSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 10, 22, 8, 0, 0, TimeSpan.Zero);
|
||||
NodeTrafficReading Row(string slug = "aliyun-tokyo-002", bool stale = false, DateTimeOffset? sampled = null,
|
||||
long? up = 10, long? down = 20, long? totalUp = 30, long? totalDown = 40, double? interval = 5, string? epoch = "fixture") => new()
|
||||
{ Slug = slug, Stale = stale, SampledAt = sampled ?? now, UploadRate = up, DownloadRate = down,
|
||||
TotalUpload = totalUp, TotalDownload = totalDown, IntervalSeconds = interval, CounterEpoch = epoch };
|
||||
NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface",
|
||||
string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new()
|
||||
{ Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset",
|
||||
GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] };
|
||||
bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now);
|
||||
checks["exact_two_authorized_server_contract"] = Valid(Snapshot());
|
||||
checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([]));
|
||||
checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")]));
|
||||
checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()]));
|
||||
checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()]));
|
||||
checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate"));
|
||||
checks["unknown_source_rejected"] = !Valid(Snapshot(source: "unknown"));
|
||||
checks["wrong_direction_rejected"] = !Valid(Snapshot(direction: "client_perspective"));
|
||||
checks["stale_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(-16)));
|
||||
checks["future_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(6)));
|
||||
checks["negative_upload_rejected"] = !Valid(Snapshot([Row(up: -1)]));
|
||||
checks["negative_download_rejected"] = !Valid(Snapshot([Row(down: -1)]));
|
||||
checks["negative_total_rejected"] = !Valid(Snapshot([Row(totalUp: -1)]));
|
||||
checks["nonfinite_interval_rejected"] = !Valid(Snapshot([Row(interval: double.NaN)]));
|
||||
checks["unbounded_interval_rejected"] = !Valid(Snapshot([Row(interval: 31)]));
|
||||
checks["fresh_sample_is_current"] = NodeTrafficPresentation.Fresh(Row(), now);
|
||||
checks["backend_stale_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(stale: true), now);
|
||||
checks["client_checks_sample_age_independently"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(-16)), now);
|
||||
checks["future_sample_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(6)), now);
|
||||
checks["first_counter_has_no_invented_rate"] = !NodeTrafficPresentation.Fresh(Row(up: null, down: null, interval: null), now);
|
||||
checks["reset_epoch_required"] = !NodeTrafficPresentation.Fresh(Row(epoch: null), now);
|
||||
checks["missing_is_dash_not_zero"] = NodeTrafficPresentation.Bytes(null, true) == "—";
|
||||
checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0 B/s";
|
||||
checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200 KB/s";
|
||||
checks["cumulative_has_no_speed_suffix"] = NodeTrafficPresentation.Bytes(204800) == "200 KB";
|
||||
checks["all_geometry_monitor_tailnet_cases_fit"] = DashboardLayout.SelfTest();
|
||||
using (var font = Brand.Font(7.1f))
|
||||
{
|
||||
var measuredHeight = TextRenderer.MeasureText("VPN002 上传", font).Height;
|
||||
foreach (var dpi in new[] { 96, 120, 144, 192, 336, 384 })
|
||||
{
|
||||
var view = new Size(620 * dpi / 96, 350 * dpi / 96);
|
||||
var panel = DashboardLayout.Calculate(view, dpi, true, true).ServerTrafficCard;
|
||||
var text = NodeTrafficPanel.TextLayout(panel.Size, dpi, (int)Math.Ceiling(measuredHeight * dpi / 96d));
|
||||
checks["minimum_two_text_rows_fit_" + dpi] = text.Rows.Length == 2
|
||||
&& text.Rows.All(row => row.Height >= measuredHeight * dpi / 96d && row.Bottom <= panel.Height)
|
||||
&& !text.Rows[0].IntersectsWith(text.Rows[1]);
|
||||
}
|
||||
}
|
||||
foreach (var tailnet in new[] { false, true })
|
||||
{
|
||||
var view = new Size(960, 612);
|
||||
var layout = DashboardLayout.Calculate(view, 96, tailnet, true);
|
||||
checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom
|
||||
&& layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom
|
||||
&& (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom);
|
||||
checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height
|
||||
&& layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top;
|
||||
}
|
||||
var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!;
|
||||
checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic;
|
||||
}
|
||||
catch (Exception exception) { error = exception.GetType().Name; }
|
||||
var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-traffic-self-test.json"),
|
||||
JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract and fixed-height geometry only",
|
||||
network_modified = false, credentials_loaded = false, production_sample_observed = false },
|
||||
new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 84;
|
||||
}
|
||||
}
|
||||
@@ -29,41 +29,25 @@ internal static class NodeTransportConnector
|
||||
throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。");
|
||||
var selected = current;
|
||||
var fallback = original;
|
||||
if (!tailnet && preferredTailnetConfig is not null)
|
||||
{
|
||||
// Only a confirmed physical-network recovery calls this method.
|
||||
// Re-check the cached alternate of this SAME authorized config; a
|
||||
// previous-network cooldown must not make public ingress sticky.
|
||||
if (!TailnetTransport.SameAuthorizedFallback(preferredTailnetConfig, current))
|
||||
throw new InvalidOperationException("Tailscale 恢复入口与当前授权线路不匹配。");
|
||||
if (requireRoute is null || endpointProbe is null)
|
||||
throw new InvalidOperationException("Tailscale 恢复入口缺少独立路由或端口验证。");
|
||||
var recheckReason = "route_unavailable";
|
||||
try
|
||||
{
|
||||
var address = TailnetTransport.Address(preferredTailnetConfig)!;
|
||||
requireRoute(address);
|
||||
token.ThrowIfCancellationRequested();
|
||||
recheckReason = "endpoint_unreachable";
|
||||
if (!await endpointProbe(address, TailnetTransport.Port(preferredTailnetConfig), token))
|
||||
diagnostic?.Invoke(new("rebind_skipped", "endpoint_unreachable", ""));
|
||||
else
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
selected = preferredTailnetConfig;
|
||||
fallback = current;
|
||||
tailnet = true;
|
||||
diagnostic?.Invoke(new("rebind_attempt", "tailnet_recovered", ""));
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException && e is not LocalNetworkException)
|
||||
{ diagnostic?.Invoke(new("rebind_skipped", recheckReason, "")); }
|
||||
}
|
||||
// Once domain fallback has been selected, physical-network recovery
|
||||
// retains it. Do not probe/promote a cached internal alternative.
|
||||
// Only an explicit new user connection may select the internal IP again.
|
||||
token.ThrowIfCancellationRequested();
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45));
|
||||
try
|
||||
{
|
||||
if (tailnet && endpointProbe is not null)
|
||||
{
|
||||
var available = await endpointProbe(TailnetTransport.Address(selected)!, TailnetTransport.Port(selected), deadline.Token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!available)
|
||||
{
|
||||
selected = fallback!;
|
||||
tailnet = false;
|
||||
diagnostic?.Invoke(new("rebind_fallback", "ping_unreachable", ""));
|
||||
}
|
||||
}
|
||||
await start(selected, deadline.Token);
|
||||
if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。");
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
@@ -117,9 +101,9 @@ internal static class NodeTransportConnector
|
||||
{
|
||||
try
|
||||
{
|
||||
status("正在检测 Tailscale 入口(最多 3 秒)");
|
||||
status("正在 Ping 代理内网 IP(最多 1 秒)");
|
||||
if (!await endpointProbe(TailnetTransport.Address(tailnet)!, TailnetTransport.Port(tailnet), token))
|
||||
throw new IOException("Tailscale 端口不可达。");
|
||||
throw new IOException("代理内网 IP Ping 不通。");
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
@@ -128,7 +112,7 @@ internal static class NodeTransportConnector
|
||||
tailnet = null;
|
||||
reason = "endpoint_unreachable";
|
||||
Report("tailnet_skipped", reason);
|
||||
status(tailnetOnly ? "Tailscale 端口不可达,继续检测其他授权内网节点" : "Tailscale 端口不可达,使用同一节点公网入口");
|
||||
status(tailnetOnly ? "内网 IP Ping 不通,继续其他授权内网节点" : "内网 IP Ping 不通,回退域名并保持");
|
||||
}
|
||||
}
|
||||
if (tailnet is not null)
|
||||
@@ -163,6 +147,8 @@ internal static class NodeTransportConnector
|
||||
// Automatic selection can test ALL authorized Tailnet nodes first. A
|
||||
// failed alternate must not launch public ingress before that pass ends.
|
||||
if (tailnetOnly) throw new TailnetUnavailableException(reason);
|
||||
if (response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global")
|
||||
preference.CommitDomainFallback();
|
||||
Report("selected", "public_ingress");
|
||||
await start(response.GetRuntimeConfigJson(), token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace UCVL.VPNPlus;
|
||||
// there is no HTTP retry, URL rewrite, system DNS change or TLS bypass.
|
||||
internal static class PlatformBootstrapTransport
|
||||
{
|
||||
internal const string Host = "vpn.toplc.cn";
|
||||
internal const string Host = "vpn.example.invalid";
|
||||
private static readonly IPAddress BootstrapAddress = IPAddress.Parse("192.0.2.1");
|
||||
|
||||
internal static SocketsHttpHandler CreateHandler() => new()
|
||||
|
||||
@@ -12,11 +12,11 @@ internal static class PlatformBootstrapTransportSelfTest
|
||||
using var handler = PlatformBootstrapTransport.CreateHandler();
|
||||
checks.Add(!handler.UseProxy && !handler.AllowAutoRedirect && !handler.UseCookies);
|
||||
checks.Add(handler.SslOptions.RemoteCertificateValidationCallback is null);
|
||||
PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.toplc.cn/api/v1/client/login/"));
|
||||
foreach (var uri in new[] { "http://vpn.toplc.cn/", "https://vpn.toplc.cn:444/", "https://192.0.2.1/",
|
||||
"https://other.invalid/", "https://vpn.toplc.cn.evil.invalid/", "https://user@vpn.toplc.cn/" })
|
||||
PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.example.invalid/api/v1/client/login/"));
|
||||
foreach (var uri in new[] { "http://vpn.example.invalid/", "https://vpn.example.invalid:444/", "https://192.0.2.1/",
|
||||
"https://other.invalid/", "https://vpn.example.invalid.evil.invalid/", "https://user@vpn.example.invalid/" })
|
||||
checks.Add(Rejects(() => PlatformBootstrapTransport.ValidateRequest(new Uri(uri))));
|
||||
checks.Add(Rejects(() => PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.toplc.cn/"), "other.invalid")));
|
||||
checks.Add(Rejects(() => PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.example.invalid/"), "other.invalid")));
|
||||
foreach (var ip in new[] { "198.18.0.0", "198.19.255.255", "::ffff:198.18.0.41" })
|
||||
checks.Add(PlatformBootstrapTransport.IsFakeAddress(IPAddress.Parse(ip)));
|
||||
foreach (var ip in new[] { "198.17.255.255", "198.20.0.0", "192.0.2.1", "::1" })
|
||||
|
||||
@@ -17,7 +17,7 @@ internal static class PrivateAuxiliaryRouting
|
||||
internal const string PhoneAddress = "192.168.50.170";
|
||||
internal const string PhoneTailnetAddress = "100.64.0.4";
|
||||
internal const string PublicPhoneAddress = "192.0.2.1";
|
||||
internal const string PublicPhoneHost = "vpn.toplc.cn";
|
||||
internal const string PublicPhoneHost = "vpn.example.invalid";
|
||||
internal static bool IsRegisteredEndpoint(string? address) =>
|
||||
address is JinanAddress or PhoneAddress or PhoneTailnetAddress or PublicPhoneAddress or PublicPhoneHost;
|
||||
internal static bool ValidEndpoint(PrivateAuxiliaryNode node) =>
|
||||
|
||||
@@ -77,7 +77,7 @@ internal static class PrivateAuxiliaryRoutingSelfTest
|
||||
[slow, fast], empty, Tie, default)).SequenceEqual([slow, fast]);
|
||||
var domain = new PrivateAuxiliaryNode { Slug = "same-site", Name = "济南(博翠明湖)", Status = "candidate",
|
||||
Contract = 1, ExpiresAt = now.AddMinutes(3), TlsLeafSha256 = new string('a', 64),
|
||||
ProbeIpv4 = "192.0.2.1", ConnectAddress = "vpn.toplc.cn", ProbePort = 11080 };
|
||||
ProbeIpv4 = "192.0.2.1", ConnectAddress = "vpn.example.invalid", ProbePort = 11080 };
|
||||
Task<long?> PublicFast(PrivateAuxiliaryNode n, CancellationToken t) => Task.FromResult<long?>(n == domain ? 1 : 90);
|
||||
checks["internal_priority_even_when_domain_ping_is_faster"] = (await PrivateAuxiliaryRouting.RankByLatencyAsync(
|
||||
[domain, slow], empty, PublicFast, default)).SequenceEqual([slow, domain]);
|
||||
@@ -85,7 +85,7 @@ internal static class PrivateAuxiliaryRoutingSelfTest
|
||||
Contract = 1, ExpiresAt = now.AddMinutes(3), TlsLeafSha256 = new string('a', 64),
|
||||
ProbeIpv4 = "100.64.0.4", ConnectionEndpoints = [
|
||||
new() { Address = "100.64.0.4", ProbeIpv4 = "100.64.0.4", Port = 18081 },
|
||||
new() { Address = "vpn.toplc.cn", ProbeIpv4 = "192.0.2.1", Port = 11080 }] };
|
||||
new() { Address = "vpn.example.invalid", ProbeIpv4 = "192.0.2.1", Port = 11080 }] };
|
||||
Task<long?> Both(PrivateAuxiliaryNode n, CancellationToken t) => Task.FromResult<long?>(n.ProbePort == 11080 ? 1 : 90);
|
||||
var fixedSite = ConnectionSelection.Create(true, "same-site", ["same-site"]);
|
||||
var sameSiteRanking = await PrivateAuxiliaryRouting.RankForSelectionAsync(fixedSite, [oneSite], empty, false, Both, default);
|
||||
@@ -94,16 +94,16 @@ internal static class PrivateAuxiliaryRoutingSelfTest
|
||||
checks["manual_can_fallback_transport_not_node"] = ConnectionAttemptPlanner.CreateRanked(fixedSite, sameSiteRanking, 3)
|
||||
.All(a => a.IsPrivate && a.Slug == "same-site");
|
||||
var renewal = PrivateAuxiliaryRouting.ForRenewal(oneSite, domain);
|
||||
checks["renewal_keeps_working_domain_not_preferred_tailnet"] = renewal.EndpointHost == "vpn.toplc.cn"
|
||||
checks["renewal_keeps_working_domain_not_preferred_tailnet"] = renewal.EndpointHost == "vpn.example.invalid"
|
||||
&& renewal.ProbePort == 11080 && renewal.ExpiresAt == oneSite.ExpiresAt;
|
||||
checks["renewal_keeps_working_internal_endpoint"] = PrivateAuxiliaryRouting.ForRenewal(oneSite, sameSiteRanking[0]).ProbeIpv4 == "100.64.0.4";
|
||||
checks["renewal_revoked_transport_rejected"] = Reject(() => PrivateAuxiliaryRouting.ForRenewal(oneSite, Node()));
|
||||
checks["renewal_legacy_endpoint_preserved"] = PrivateAuxiliaryRouting.ForRenewal(grants[0], grants[0]) == grants[0];
|
||||
Task<long?> OnlyDomain(PrivateAuxiliaryNode n, CancellationToken t) => Task.FromResult<long?>(n.ProbePort == 11080 ? 30 : null);
|
||||
checks["failed_internal_selects_same_site_domain"] = (await PrivateAuxiliaryRouting.RankForSelectionAsync(
|
||||
fixedSite, [oneSite], empty, false, OnlyDomain, default)).Single().EndpointHost == "vpn.toplc.cn";
|
||||
fixedSite, [oneSite], empty, false, OnlyDomain, default)).Single().EndpointHost == "vpn.example.invalid";
|
||||
var domainConfig = Config(mutate: r => {
|
||||
r["outbounds"]![0]!["settings"]!["servers"]![0]!["address"] = "vpn.toplc.cn";
|
||||
r["outbounds"]![0]!["settings"]!["servers"]![0]!["address"] = "vpn.example.invalid";
|
||||
r["outbounds"]![0]!["settings"]!["servers"]![0]!["port"] = 11080;
|
||||
});
|
||||
// The fixture config helper is defined below; domain validation is checked there.
|
||||
@@ -155,9 +155,9 @@ internal static class PrivateAuxiliaryRoutingSelfTest
|
||||
checks["compatible_private_config_accepted"] = !Reject(() => PrivateAuxiliaryRouting.ValidateConfig(grants[0], Config(), "smart"));
|
||||
var sameSlugDomain = new PrivateAuxiliaryNode { Slug = "jinan-private", Status = "candidate", Contract = 1,
|
||||
ExpiresAt = now.AddMinutes(3), TlsLeafSha256 = new string('a', 64), ProbeIpv4 = "192.0.2.1",
|
||||
ConnectAddress = "vpn.toplc.cn", ProbePort = 11080 };
|
||||
ConnectAddress = "vpn.example.invalid", ProbePort = 11080 };
|
||||
checks["authorized_domain_mapping_config_accepted"] = !Reject(() => PrivateAuxiliaryRouting.ValidateConfig(sameSlugDomain, domainConfig, "smart"));
|
||||
checks["domain_runtime_keeps_real_hostname"] = PrivateAuxiliaryRuntime.Address(domainConfig.GetRuntimeConfigJson()) == "vpn.toplc.cn";
|
||||
checks["domain_runtime_keeps_real_hostname"] = PrivateAuxiliaryRuntime.Address(domainConfig.GetRuntimeConfigJson()) == "vpn.example.invalid";
|
||||
foreach (var address in new[] { "192.168.50.170", "100.64.0.4" }) {
|
||||
var phoneGrant = Node(address: address);
|
||||
var phoneConfig = Config(mutate: r => r["outbounds"]![0]!["settings"]!["servers"]![0]!["address"] = address);
|
||||
|
||||
@@ -25,6 +25,10 @@ internal static class Program
|
||||
return LearningSyncCoordinatorSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--tailnet-readiness-self-test")
|
||||
return TailnetReadinessSelfTest.Run();
|
||||
if (args.Length == 1 && args[0] == "--chart-freshness-self-test")
|
||||
return ChartFreshnessSelfTest.Run();
|
||||
if (args.Length == 1 && args[0] == "--node-traffic-self-test")
|
||||
return NodeTrafficSelfTest.Run();
|
||||
if (args.Length == 1 && args[0] == "--nextgen-lifecycle-self-test")
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
|
||||
+5
-3
@@ -1,6 +1,6 @@
|
||||
# 纵横家 Windows 0.3.0 开源源码
|
||||
# 纵横家 Windows 0.3.1 开源源码
|
||||
|
||||
基于已冻结的 0.3.0 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
基于已冻结的 0.3.1 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -17,4 +17,6 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
|
||||
|
||||
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
|
||||
|
||||
本次 0.3.0 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
|
||||
本次 0.3.1 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
|
||||
|
||||
0.3.1:固定画布实时速率、主WAN采样显示、节点延迟和粘性连接维护。整机WAN监控与个人套餐分开;未部署的后台、账户限速、真实网络和实窗结论不转移到此清洁源码。
|
||||
|
||||
+17
-8
@@ -188,14 +188,23 @@ internal sealed class ScenicPanel : Panel
|
||||
if (_loginBackdrop is null || _loginBackdrop.Size != ClientSize
|
||||
|| _loginBackdropDpi != DeviceDpi || _loginBackdropFooter != FooterArtwork)
|
||||
{
|
||||
using var next = new Bitmap(Width, Height);
|
||||
using (var graphics = Graphics.FromImage(next))
|
||||
ScenicTheme.Backdrop(graphics, ClientSize, DeviceDpi, footer: FooterArtwork, login: true);
|
||||
var previous = _loginBackdrop;
|
||||
_loginBackdrop = new Bitmap(next);
|
||||
_loginBackdropDpi = DeviceDpi;
|
||||
_loginBackdropFooter = FooterArtwork;
|
||||
previous?.Dispose();
|
||||
Bitmap? next = null;
|
||||
try
|
||||
{
|
||||
next = new Bitmap(Width, Height);
|
||||
using (var graphics = Graphics.FromImage(next))
|
||||
ScenicTheme.Backdrop(graphics, ClientSize, DeviceDpi, footer: FooterArtwork, login: true);
|
||||
// Transfer the completed bitmap rather than copying the whole
|
||||
// canvas on the UI thread. A failed render leaves the previous
|
||||
// cache owned and intact; only the incomplete replacement dies.
|
||||
var previous = _loginBackdrop;
|
||||
_loginBackdrop = next;
|
||||
next = null;
|
||||
_loginBackdropDpi = DeviceDpi;
|
||||
_loginBackdropFooter = FooterArtwork;
|
||||
previous?.Dispose();
|
||||
}
|
||||
finally { next?.Dispose(); }
|
||||
}
|
||||
e.Graphics.DrawImageUnscaled(_loginBackdrop, Point.Empty);
|
||||
}
|
||||
|
||||
+22
-25
@@ -99,29 +99,23 @@ internal static class TailnetTransport
|
||||
|
||||
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
|
||||
|
||||
// Before starting/replacing a core, test only this socket through the existing
|
||||
// user-owned route. ICMP success isn't enough; TCP success still isn't auth.
|
||||
// Selection checks only ICMP through the existing OS network. It never
|
||||
// queries or changes Tailscale; authenticated proxy health is checked after
|
||||
// starting the chosen authorized transport, separately from reachability.
|
||||
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(1));
|
||||
try
|
||||
{
|
||||
var name = RequireExistingRoute(address);
|
||||
var nic = NetworkInterface.GetAllNetworkInterfaces().Single(n => n.Name == name);
|
||||
var index = nic.GetIPProperties().GetIPv4Properties()!.Index;
|
||||
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
// Windows IP_UNICAST_IF=31 is not named by .NET 8's enum.
|
||||
// https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options
|
||||
const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
|
||||
socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(index));
|
||||
await socket.ConnectAsync(new IPEndPoint(IPAddress.Parse(address), port), deadline.Token);
|
||||
return true;
|
||||
using var ping = new Ping();
|
||||
var reply = await ping.SendPingAsync(IPAddress.Parse(address), 1000).WaitAsync(deadline.Token).ConfigureAwait(false);
|
||||
return reply.Status == IPStatus.Success;
|
||||
}
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
|
||||
catch (Exception e) when (e is SocketException or NetworkInformationException or InvalidOperationException) { return false; }
|
||||
catch (Exception e) when (e is PingException or SocketException or NetworkInformationException or InvalidOperationException) { return false; }
|
||||
}
|
||||
|
||||
internal static bool SameAuthorizedFallback(string current, string? fallback)
|
||||
@@ -142,20 +136,21 @@ internal static class TailnetTransport
|
||||
}
|
||||
|
||||
// Read only. No CLI/process/service dependency: user owns the underlying network.
|
||||
// Require an existing more-specific route; never manufacture a /32 through the
|
||||
// phone/default gateway. Bind the proxy socket to that interface so a lost
|
||||
// tailnet route cannot silently recurse into our own TUN.
|
||||
// Ask Windows which existing interface owns this IP path, including a valid
|
||||
// default route. No adapter-name, service or route-prefix prerequisite.
|
||||
// This UDP Connect sends no payload. Refuse our own TUN to avoid recursion;
|
||||
// no /32 or user route is manufactured or removed.
|
||||
internal static string RequireExistingRoute(string address)
|
||||
{
|
||||
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
|
||||
var interfaces = NetworkInterface.GetAllNetworkInterfaces()
|
||||
using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
route.Connect(new IPEndPoint(IPAddress.Parse(address), 443));
|
||||
var local = (route.LocalEndPoint as IPEndPoint)?.Address;
|
||||
var owner = NetworkInterface.GetAllNetworkInterfaces()
|
||||
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
|
||||
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
|
||||
.Select(n => new { n.Name, Index = n.GetIPProperties().GetIPv4Properties()?.Index })
|
||||
.Where(n => n.Index.HasValue).ToDictionary(n => n.Index!.Value, n => n.Name);
|
||||
var index = SelectRoute(address, new WindowsRouteTable().Snapshot(), interfaces.Keys.ToHashSet());
|
||||
return index is { } found ? interfaces[found]
|
||||
: throw new InvalidOperationException("Tailscale 节点路径暂不可用,保留原入口作为回退。");
|
||||
.FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local)));
|
||||
return owner?.Name ?? throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留域名入口作为回退。");
|
||||
}
|
||||
|
||||
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
|
||||
@@ -191,9 +186,11 @@ internal static class TailnetTransport
|
||||
internal sealed class TailnetPreference
|
||||
{
|
||||
private readonly Dictionary<string, long> _cooldowns = new(StringComparer.Ordinal);
|
||||
internal bool DomainOnly { get; private set; }
|
||||
// Only an explicit user connect action resets failures. Automatic recovery
|
||||
// continues respecting the existing monotonic cooldown.
|
||||
internal void ResetForUserConnect() => _cooldowns.Clear();
|
||||
internal bool MayTry(string slug, long now) => !_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry;
|
||||
internal void ResetForUserConnect() { _cooldowns.Clear(); DomainOnly = false; }
|
||||
internal void CommitDomainFallback() => DomainOnly = true;
|
||||
internal bool MayTry(string slug, long now) => !DomainOnly && (!_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry);
|
||||
internal void Failed(string slug, long now) => _cooldowns[slug] = now + 5 * 60_000;
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ internal static class TailnetTransportProbe
|
||||
country = lines.FirstOrDefault(l => l[0] == "loc")?[1];
|
||||
}
|
||||
checks["expected_node_exit"] = node == "aliyun-tokyo-002"
|
||||
? exitIp == "8.216.53.107" && country == "JP" : exitIp == "47.254.94.29" && country == "US";
|
||||
? 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");
|
||||
}
|
||||
|
||||
@@ -92,8 +92,11 @@ internal static class TailnetTransportSelfTest
|
||||
starts.Clear(); routeReads=0;
|
||||
selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, Healthy, Route,_=>{},()=>tick+299999,CancellationToken.None);
|
||||
checks["cooldown_skips_route_and_probe"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && routeReads==0 && probes==0;
|
||||
checks["cooldown_monotonic_expiry"] = preference.MayTry("tokyo",tick+300000) && !preference.MayTry("tokyo",tick+299999);
|
||||
checks["other_node_cooldown_independent"] = preference.MayTry("silicon",tick);
|
||||
checks["domain_fallback_stays_sticky_after_five_minutes"] = !preference.MayTry("tokyo",tick+300000)
|
||||
&& !preference.MayTry("tokyo",tick+86_400_000);
|
||||
checks["domain_fallback_blocks_other_internal_nodes_this_session"] = !preference.MayTry("silicon",tick);
|
||||
preference.ResetForUserConnect();
|
||||
checks["explicit_user_connect_resets_domain_choice"] = preference.MayTry("tokyo",tick+1) && preference.MayTry("silicon",tick+1);
|
||||
starts.Clear(); statuses.Clear();
|
||||
selected = await NodeTransportConnector.ConnectAsync(response,new(),Start,Stop,Healthy,_=>throw new IOException("SYNTHETIC_SECRET route unavailable"),statuses.Add,()=>tick,CancellationToken.None);
|
||||
checks["route_read_failure_keeps_original"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"});
|
||||
@@ -204,7 +207,7 @@ internal static class TailnetTransportSelfTest
|
||||
["contract"] = 1, ["node_slug"] = "aliyun-tokyo-002", ["address"] = "100.65.1.9", ["port"] = 2345
|
||||
}), true)!;
|
||||
checks["explicit_server_metadata_takes_priority"] = Host(future) == "100.65.1.9" && TailnetTransport.Port(future) == 2345;
|
||||
var gatewayKnown = Known(r => r["gateway"] = new JsonObject { ["host"] = "vpn.toplc.cn", ["ipv4"] = "192.0.2.1" });
|
||||
var gatewayKnown = Known(r => r["gateway"] = new JsonObject { ["host"] = "vpn.example.invalid", ["ipv4"] = "192.0.2.1" });
|
||||
checks["compatibility_checks_node_before_gateway_rewrite"] = Host(TailnetTransport.TryPrepare(gatewayKnown, true)!) == "100.64.0.2";
|
||||
checks["compatibility_fallback_keeps_api_public_gateway"] = TailnetTransport.SameAuthorizedFallback(
|
||||
TailnetTransport.TryPrepare(gatewayKnown, true)!, gatewayKnown.GetRuntimeConfigJson()) && Host(gatewayKnown.GetRuntimeConfigJson()) == "192.0.2.1";
|
||||
@@ -221,7 +224,7 @@ internal static class TailnetTransportSelfTest
|
||||
selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,statuses.Add,()=>tick,CancellationToken.None,
|
||||
allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false));
|
||||
checks["closed_port_skips_tailnet_start_and_stop"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && stops == beforeStops && probes == 0;
|
||||
checks["closed_port_status_is_distinct_from_route_failure"] = statuses.Last() == "Tailscale 端口不可达,使用同一节点公网入口";
|
||||
checks["ping_unreachable_status_is_distinct_from_route_failure"] = statuses.Last() == "内网 IP Ping 不通,回退域名并保持";
|
||||
checks["closed_port_sets_node_cooldown"] = !deniedPreference.MayTry(known.Node.Slug,tick+1);
|
||||
starts.Clear();
|
||||
selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None,
|
||||
@@ -283,9 +286,9 @@ internal static class TailnetTransportSelfTest
|
||||
starts.Clear(); beforeStops=stops; probes=0; preflights=0; routeReads=0; diagnostics.Clear();
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>{preflights++;return Task.FromResult(true);},diagnostic:diagnostics.Add);
|
||||
checks["handover_public_rechecks_authorized_tailnet"] = rebound==prepared && starts.SequenceEqual(new[]{"100.64.0.2"})
|
||||
&& stops==beforeStops && preflights==1 && routeReads==1 && probes==1;
|
||||
checks["handover_promotion_requires_verified_exit"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="tailnet_verified");
|
||||
checks["handover_public_never_rechecks_or_promotes_internal"] = rebound==original && starts.SequenceEqual(new[]{"vpn002.example.invalid"})
|
||||
&& stops==beforeStops && preflights==0 && routeReads==0 && probes==0;
|
||||
checks["handover_reports_public_choice"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="public_ingress");
|
||||
starts.Clear(); beforeStops=stops; probes=0;
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(false));
|
||||
@@ -294,13 +297,21 @@ internal static class TailnetTransportSelfTest
|
||||
starts.Clear(); beforeStops=stops;
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,_=>Task.FromResult(false),CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true));
|
||||
checks["handover_promotion_failure_same_node_cleanup_fallback"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","vpn002.example.invalid"}) && stops==beforeStops+1;
|
||||
checks["handover_public_does_not_restart_internal_even_when_probe_would_succeed"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && stops==beforeStops;
|
||||
starts.Clear();
|
||||
try {
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true));
|
||||
checks["handover_ignores_unused_preferred_credentials"] = rebound==original && starts.SequenceEqual(new[]{"vpn002.example.invalid"});
|
||||
} catch { checks["handover_ignores_unused_preferred_credentials"] = false; }
|
||||
starts.Clear();
|
||||
try {
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route);
|
||||
checks["handover_public_needs_no_internal_probe"] = rebound==original && starts.SequenceEqual(new[]{"vpn002.example.invalid"});
|
||||
} catch { checks["handover_public_needs_no_internal_probe"] = false; }
|
||||
starts.Clear();
|
||||
checks["handover_forged_preferred_credentials_rejected_before_start"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
|
||||
checks["handover_promotion_without_probe_rejected"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route)) && starts.Count==0;
|
||||
checks["handover_preferred_cancellation_does_not_start_any_path"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,cancel.Token,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
|
||||
|
||||
@@ -358,6 +369,24 @@ internal static class TailnetTransportSelfTest
|
||||
selected=await NodeTransportConnector.ConnectAsync(response,rankedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None);
|
||||
checks["integration_public_pass_only_after_all_internal_fail"] = !selected
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3","vpn002.example.invalid"});
|
||||
starts.Clear();
|
||||
rebound = await NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,CancellationToken.None,
|
||||
endpointProbe:(_,_,_)=>Task.FromResult(false));
|
||||
checks["handover_ping_failure_uses_domain_without_internal_start"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"vpn002.example.invalid"});
|
||||
var privateResponse = Sample(r => {
|
||||
r["connection_scope"] = "private_auxiliary"; r["config_contract"] = 3;
|
||||
r["config_expires_at"] = DateTimeOffset.UtcNow.AddMinutes(2).ToString("O");
|
||||
r["config"]!["outbounds"]![0] = new JsonObject {
|
||||
["tag"]="proxy",["protocol"]="socks",["settings"]=new JsonObject {
|
||||
["servers"]=new JsonArray(new JsonObject {["address"]="192.168.50.111",["port"]=18081}) }
|
||||
};
|
||||
});
|
||||
var privatePreference = new TailnetPreference();
|
||||
await NodeTransportConnector.ConnectAsync(privateResponse,privatePreference,(_,_)=>Task.CompletedTask,
|
||||
Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None);
|
||||
checks["private_ip_success_is_not_domain_fallback"] = !privatePreference.DomainOnly
|
||||
&& privatePreference.MayTry("tokyo",tick+1);
|
||||
var report = new { passed=checks.Values.All(x=>x), checks, simulated_transport=true,
|
||||
production_network_actions=Array.Empty<string>(), note="Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." };
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
|
||||
|
||||
+96
-22
@@ -5,24 +5,24 @@ namespace UCVL.VPNPlus;
|
||||
// Reads only existing proxy-outbound counters; never the physical adapter.
|
||||
internal sealed class TrafficChart : Control
|
||||
{
|
||||
private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new();
|
||||
private readonly TrafficChartTimeline _timeline;
|
||||
private TimeSpan _period = TimeSpan.FromMinutes(5);
|
||||
internal int PeriodMinutes => (int)_period.TotalMinutes;
|
||||
internal int PointCount => _points.Count;
|
||||
internal int PointCount => _timeline.PointCount;
|
||||
internal int VisiblePointCount => VisiblePoints().Length;
|
||||
internal bool HasFreshSample => _timeline.HasFreshSample;
|
||||
internal DateTimeOffset? LastSampleAt => _timeline.LastSampleAt;
|
||||
internal DateTimeOffset TimelineEnd => _timeline.End;
|
||||
internal void SetPeriodMinutes(int minutes)
|
||||
{
|
||||
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
|
||||
_period = TimeSpan.FromMinutes(minutes);
|
||||
Invalidate();
|
||||
}
|
||||
private (DateTimeOffset Time, double Up, double Down)[] VisiblePoints()
|
||||
{
|
||||
var end = _points.Count == 0 ? DateTimeOffset.Now : _points.Last().Time;
|
||||
return _points.Where(point => end - point.Time <= _period).ToArray();
|
||||
}
|
||||
internal TrafficChart()
|
||||
private TrafficChartTimeline.Sample[] VisiblePoints() => _timeline.Visible(_period);
|
||||
internal TrafficChart(Func<DateTimeOffset>? clock = null)
|
||||
{
|
||||
_timeline = new TrafficChartTimeline(clock);
|
||||
DoubleBuffered = true;
|
||||
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true);
|
||||
SetStyle(ControlStyles.Opaque, false);
|
||||
@@ -31,35 +31,109 @@ internal sealed class TrafficChart : Control
|
||||
}
|
||||
internal void Add(double up, double down, DateTimeOffset? time = null)
|
||||
{
|
||||
var at = time ?? DateTimeOffset.Now;
|
||||
double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0;
|
||||
_points.Enqueue((at, Clean(up), Clean(down)));
|
||||
// Bounded current-session samples only: never turn daily accounting
|
||||
// totals into a fictitious speed curve. Changing range preserves samples.
|
||||
while (_points.Count > 3600 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(60))) _points.Dequeue();
|
||||
_timeline.Add(up, down, time);
|
||||
Invalidate();
|
||||
}
|
||||
internal void Reset() { _points.Clear(); Invalidate(); }
|
||||
// Called by the existing sampling timer even when the reader is busy or
|
||||
// returns no counters. Neither method invents a zero-speed sample or bytes.
|
||||
internal void AdvanceClock(DateTimeOffset? now = null) { _timeline.AdvanceClock(now); Invalidate(); }
|
||||
internal void MarkUnavailable(DateTimeOffset? now = null) { _timeline.MarkUnavailable(now); Invalidate(); }
|
||||
internal void Reset() { _timeline.Reset(); Invalidate(); }
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);
|
||||
_timeline.AdvanceClock();
|
||||
var points = VisiblePoints();
|
||||
var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => Math.Max(p.Up, p.Down)));
|
||||
var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true);
|
||||
if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return;
|
||||
var end = points.Length == 0 ? DateTimeOffset.Now : points[^1].Time;
|
||||
var end = _timeline.End;
|
||||
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]);
|
||||
if (points.Length == 0)
|
||||
{
|
||||
TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
|
||||
TextRenderer.DrawText(e.Graphics, LastSampleAt.HasValue ? "采样暂不可用" : "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
|
||||
ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
|
||||
return;
|
||||
}
|
||||
PointF[] Line(bool up) => points.Select(p => new PointF(
|
||||
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
|
||||
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
|
||||
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: points.Length == 1);
|
||||
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1);
|
||||
foreach (var segment in points.GroupBy(point => point.Segment))
|
||||
{
|
||||
var samples = segment.ToArray();
|
||||
PointF[] Line(bool up) => samples.Select(p => new PointF(
|
||||
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
|
||||
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
|
||||
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: samples.Length == 1);
|
||||
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: samples.Length == 1);
|
||||
}
|
||||
if (!HasFreshSample)
|
||||
TextRenderer.DrawText(e.Graphics, "采样暂不可用", Font, Rectangle.Round(chart.Plot), Brand.Muted,
|
||||
ChartAxis.PaintFlags | TextFormatFlags.Right | TextFormatFlags.Top | TextFormatFlags.SingleLine);
|
||||
}
|
||||
}
|
||||
|
||||
// Pure presentation history: no proxy/adapter reads, cumulative byte totals or
|
||||
// timers. An injected clock makes missing-sample behavior deterministic in tests.
|
||||
internal sealed class TrafficChartTimeline
|
||||
{
|
||||
internal readonly record struct Sample(DateTimeOffset Time, double Up, double Down, long Segment);
|
||||
internal static readonly TimeSpan MaximumSampleAge = TimeSpan.FromSeconds(15);
|
||||
private static readonly TimeSpan Retention = TimeSpan.FromMinutes(60);
|
||||
private readonly Queue<Sample> _points = new();
|
||||
private readonly Func<DateTimeOffset> _clock;
|
||||
private DateTimeOffset? _end, _lastSampleAt;
|
||||
private bool _gapPending, _unavailable = true;
|
||||
private long _segment;
|
||||
internal TrafficChartTimeline(Func<DateTimeOffset>? clock = null) => _clock = clock ?? (() => DateTimeOffset.Now);
|
||||
internal int PointCount => _points.Count;
|
||||
internal DateTimeOffset End => _end ?? _clock();
|
||||
internal DateTimeOffset? LastSampleAt => _lastSampleAt;
|
||||
internal bool HasFreshSample => !_unavailable && _lastSampleAt is { } last && End - last <= MaximumSampleAge;
|
||||
|
||||
private void MoveEnd(DateTimeOffset at)
|
||||
{
|
||||
if (!_end.HasValue || at > _end.Value) _end = at;
|
||||
while (_points.Count > 3600 || (_points.Count > 0 && End - _points.Peek().Time > Retention)) _points.Dequeue();
|
||||
}
|
||||
|
||||
internal void AdvanceClock(DateTimeOffset? now = null)
|
||||
{
|
||||
MoveEnd(now ?? _clock());
|
||||
if (_lastSampleAt is { } last && End - last > MaximumSampleAge)
|
||||
_gapPending = _unavailable = true;
|
||||
}
|
||||
|
||||
internal void MarkUnavailable(DateTimeOffset? now = null)
|
||||
{
|
||||
AdvanceClock(now);
|
||||
_gapPending = _unavailable = true;
|
||||
}
|
||||
|
||||
internal bool Add(double up, double down, DateTimeOffset? time = null)
|
||||
{
|
||||
var at = time ?? _clock();
|
||||
if (!double.IsFinite(up) || !double.IsFinite(down) || up < 0 || down < 0)
|
||||
{
|
||||
MarkUnavailable(at);
|
||||
return false;
|
||||
}
|
||||
// Late/duplicate callbacks must not move the axis backwards, inject a
|
||||
// second point or turn a newer good sample into an unavailable one.
|
||||
if (_lastSampleAt is { } previous && at <= previous) return false;
|
||||
if (_lastSampleAt is { } last && (_gapPending || at - last > MaximumSampleAge)) _segment++;
|
||||
_points.Enqueue(new Sample(at, up, down, _segment));
|
||||
_lastSampleAt = at;
|
||||
_gapPending = _unavailable = false;
|
||||
MoveEnd(at);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal Sample[] Visible(TimeSpan period) => _points.Where(point => End - point.Time <= period).ToArray();
|
||||
internal void Reset()
|
||||
{
|
||||
_points.Clear();
|
||||
_end = _lastSampleAt = null;
|
||||
_gapPending = false;
|
||||
_unavailable = true;
|
||||
_segment = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -249,7 +249,7 @@ internal static class TunConfigBuilder
|
||||
}
|
||||
""";
|
||||
var hosts = GetProxyServerHosts(sample);
|
||||
var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.toplc.cn"))?.AsObject();
|
||||
var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.example.invalid"))?.AsObject();
|
||||
var gatewayOutbound = gatewayConfig?["outbounds"]?.AsArray()[0]?.AsObject();
|
||||
var gatewayServer = gatewayOutbound?["settings"]?["vnext"]?.AsArray()[0]?.AsObject();
|
||||
var gatewayReality = gatewayOutbound?["streamSettings"]?["realitySettings"]?.AsObject();
|
||||
@@ -259,7 +259,7 @@ internal static class TunConfigBuilder
|
||||
var runtimeDnsServers = config?["dns"]?["servers"]?.AsArray();
|
||||
return hosts.Count == 1
|
||||
&& hosts[0] == "203.0.113.10"
|
||||
&& gatewayServer?["address"]?.GetValue<string>() == "vpn.toplc.cn"
|
||||
&& gatewayServer?["address"]?.GetValue<string>() == "vpn.example.invalid"
|
||||
&& gatewayServer?["port"]?.GetValue<int>() == 443
|
||||
&& gatewayReality?["publicKey"]?.GetValue<string>() == "legacy-key"
|
||||
&& tun?["protocol"]?.GetValue<string>() == "tun"
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.3.0</Version>
|
||||
<AssemblyVersion>0.3.0.0</AssemblyVersion>
|
||||
<FileVersion>0.3.0.0</FileVersion>
|
||||
<InformationalVersion>0.3.0</InformationalVersion>
|
||||
<Version>0.3.1</Version>
|
||||
<AssemblyVersion>0.3.1.0</AssemblyVersion>
|
||||
<FileVersion>0.3.1.0</FileVersion>
|
||||
<InformationalVersion>0.3.1</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
@@ -27,7 +27,7 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Recovery helpers and retained test snapshots are not app source. -->
|
||||
<Compile Remove="build\**\*.cs;artifacts\**\*.cs;dist\**\*.cs" />
|
||||
<Compile Remove="build\**\*.cs;artifacts\**\*.cs;dist\**\*.cs;obj\**\*.cs;bin\**\*.cs" />
|
||||
<EmbeddedResource Include="assets\landscape-header-v1.png" LogicalName="UCVL.VPNPlus.assets.landscape-header-v1.png" />
|
||||
<Content Include="assets\zonghengjia-app-logo-v1.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
|
||||
+26
-3
@@ -7,7 +7,7 @@ namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed class VpnApiClient : IDisposable
|
||||
{
|
||||
internal const string BaseAddress = "https://vpn.toplc.cn/";
|
||||
internal const string BaseAddress = "https://vpn.example.invalid/";
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -65,6 +65,14 @@ internal sealed class VpnApiClient : IDisposable
|
||||
return await GitReleaseUpdater.GetLatestAsync(cancellationToken);
|
||||
}
|
||||
|
||||
internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken)
|
||||
{
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/node-traffic/", token);
|
||||
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 32 * 1024);
|
||||
}
|
||||
|
||||
internal async Task<ConfigResponse> GetConfigAsync(string token, string nodeSlug, string routeMode, CancellationToken cancellationToken, IEnumerable<string>? excluded = null)
|
||||
{
|
||||
var url = $"api/v1/client/config/?node={Uri.EscapeDataString(nodeSlug)}&route={Uri.EscapeDataString(routeMode)}";
|
||||
@@ -126,7 +134,7 @@ internal sealed class VpnApiClient : IDisposable
|
||||
return request;
|
||||
}
|
||||
|
||||
private async Task<T> SendAsync<T>(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
private async Task<T> SendAsync<T>(HttpRequestMessage request, CancellationToken cancellationToken, int? maximumBodyBytes = null)
|
||||
{
|
||||
var uri = request.RequestUri ?? throw new InvalidOperationException("管理接口地址为空。");
|
||||
PlatformBootstrapTransport.ValidateRequest(uri.IsAbsoluteUri ? uri : new Uri(new Uri(BaseAddress), uri), request.Headers.Host);
|
||||
@@ -136,7 +144,22 @@ internal sealed class VpnApiClient : IDisposable
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(20));
|
||||
cancellationToken = deadline.Token;
|
||||
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
var payload = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
string payload;
|
||||
if (maximumBodyBytes is { } maximum)
|
||||
{
|
||||
if (response.Content.Headers.ContentLength > maximum) throw new IOException("监控响应过大。");
|
||||
using var body = new MemoryStream();
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
var buffer = new byte[4096];
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(buffer, cancellationToken)) != 0)
|
||||
{
|
||||
if (body.Length + read > maximum) throw new IOException("监控响应过大。");
|
||||
body.Write(buffer, 0, read);
|
||||
}
|
||||
payload = new UTF8Encoding(false, true).GetString(body.ToArray());
|
||||
}
|
||||
else payload = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
string message;
|
||||
|
||||
@@ -93,9 +93,13 @@ internal static class WindowChromeSelfTest
|
||||
// Synthetic close-to-tray contract. The real MainForm branch is
|
||||
// exercised separately by existing StartupSelfTest --uiOnly mode.
|
||||
form.FormClosing += (_, e) => { closeEvents++; e.Cancel = true; form.Hide(); };
|
||||
FitFixtureHeaderToDpi(form, header);
|
||||
form.Show();
|
||||
var initiallyReady = WaitForState(form, FormWindowState.Normal, "initial_show");
|
||||
chrome.LayoutButtons();
|
||||
var blankHeaderPoint = BlankFixtureHeaderPoint(form, header);
|
||||
geometry["fixture_dpi_and_caption"] = $"dpi={form.DeviceDpi}; header={header.ClientRectangle}; button={chrome.MinimizeButton.Bounds}; blank={blankHeaderPoint}";
|
||||
checks["fixture_header_contains_entire_dpi_scaled_caption"] = header.ClientRectangle.Contains(chrome.MinimizeButton.Bounds);
|
||||
checks["client_canvas_replaces_entire_caption"] = initiallyReady && form.RectangleToScreen(form.ClientRectangle) == form.Bounds;
|
||||
checks["native_sizable_style_preserved"] = (ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64() & ChromeNative.NativeFrameStyles) == ChromeNative.NativeFrameStyles;
|
||||
checks["native_caption_style_absent"] = NativeCaptionAbsent(form);
|
||||
@@ -105,7 +109,7 @@ internal static class WindowChromeSelfTest
|
||||
ChromeNative.SetWindowLongPtr(form.Handle, ChromeNative.GwlStyle, (IntPtr)(initialStyle | ChromeNative.WsCaption));
|
||||
checks["native_caption_cannot_return_on_style_refresh"] = NativeCaptionAbsent(form);
|
||||
checks["system_menu_available_for_alt_space"] = ChromeNative.GetSystemMenu(form.Handle, false) != IntPtr.Zero;
|
||||
checks["caption_blank_native_drag"] = Hit(form, header.PointToScreen(new Point(240, 20))) == ChromeNative.HtCaption;
|
||||
checks["caption_blank_native_drag"] = Hit(form, header.PointToScreen(blankHeaderPoint)) == ChromeNative.HtCaption;
|
||||
checks["caption_label_native_drag"] = Hit(form, title.PointToScreen(new Point(8, 8))) == ChromeNative.HtCaption;
|
||||
checks["label_forwards_hit_to_form"] = Hit(title, title.PointToScreen(new Point(8, 8))) == ChromeNative.HtTransparent;
|
||||
checks["combo_keeps_client_input"] = Hit(form, combo.PointToScreen(new Point(10, 10))) == ChromeNative.HtClient && Hit(combo, combo.PointToScreen(new Point(10, 10))) != ChromeNative.HtTransparent;
|
||||
@@ -183,7 +187,7 @@ internal static class WindowChromeSelfTest
|
||||
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScMaximize, IntPtr.Zero);
|
||||
checks["system_maximize_blocked"] = WaitForState(form, FormWindowState.Normal, "blocked_maximize", restoreBounds);
|
||||
ChromeNative.SendMessage(form.Handle, 0xa3 /* WM_NCLBUTTONDBLCLK */, (IntPtr)ChromeNative.HtCaption,
|
||||
Pack(header.PointToScreen(new Point(240, 20))));
|
||||
Pack(header.PointToScreen(blankHeaderPoint)));
|
||||
checks["caption_double_click_does_not_maximize"] = WaitForState(form, FormWindowState.Normal, "blocked_double_click", restoreBounds);
|
||||
chrome.MinimizeButton.PerformClick();
|
||||
var minimized = WaitForState(form, FormWindowState.Minimized, "minimize_button");
|
||||
@@ -248,10 +252,12 @@ internal static class WindowChromeSelfTest
|
||||
var closeEvents = 0;
|
||||
form.FormClosing += (_, e) => { closeEvents++; e.Cancel = true; };
|
||||
using var chrome = new WindowChrome(form, header, () => exitRequests++);
|
||||
FitFixtureHeaderToDpi(form, header);
|
||||
form.Show();
|
||||
var bounds = form.Bounds;
|
||||
checks["mode_fixture_initially_ready"] = waitForState(form, FormWindowState.Normal, "mode_initial", bounds);
|
||||
var button = chrome.MinimizeButton;
|
||||
checks["login_fixture_header_contains_entire_dpi_scaled_caption"] = header.ClientRectangle.Contains(button.Bounds);
|
||||
var buttonBounds = button.Bounds;
|
||||
string ToolTipText() => ((ToolTip)typeof(WindowChrome).GetField("_toolTip",
|
||||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(chrome)!).GetToolTip(button) ?? "";
|
||||
@@ -343,6 +349,34 @@ internal static class WindowChromeSelfTest
|
||||
checks["dashboard_explicit_menu_exit_preserved"] = exitRequests == 5 && closeEvents == 0;
|
||||
}
|
||||
|
||||
private static void FitFixtureHeaderToDpi(Form form, Panel header)
|
||||
{
|
||||
// Get the actual owned HWND's monitor DPI before sizing its synthetic
|
||||
// header. At 350%, the real caption is 105px high plus a 21px inset;
|
||||
// the old fixed 80/100px fixture clipped its background, not the app.
|
||||
_ = form.Handle;
|
||||
var minimum = (int)Math.Ceiling((WindowChrome.CaptionHeight + 12) * form.DeviceDpi / 96.0);
|
||||
header.Height = Math.Max(header.Height, minimum);
|
||||
form.PerformLayout();
|
||||
}
|
||||
|
||||
private static Point BlankFixtureHeaderPoint(Form form, Panel header)
|
||||
{
|
||||
var border = Math.Max(1, (int)Math.Round(6 * form.DeviceDpi / 96.0));
|
||||
// Choose an actually empty client point outside the resize band. A
|
||||
// fixed y=20 becomes HTTOP when the current monitor DPI reaches 336.
|
||||
for (var y = border + 2; y < header.ClientSize.Height - border; y++)
|
||||
for (var x = border + 2; x < header.ClientSize.Width - border; x++)
|
||||
{
|
||||
var point = new Point(x, y);
|
||||
if (header.GetChildAtPoint(point, GetChildAtPointSkip.Invisible) is not null) continue;
|
||||
var inForm = form.PointToClient(header.PointToScreen(point));
|
||||
if (ChromeGeometry.ResizeHitTest(form.ClientSize, inForm, border, true) == ChromeNative.HtClient)
|
||||
return point;
|
||||
}
|
||||
throw new InvalidOperationException("Owned fixture has no blank header point outside its resize band.");
|
||||
}
|
||||
|
||||
private static int Distance(Color a, Color b) => Math.Abs(a.R - b.R) + Math.Abs(a.G - b.G) + Math.Abs(a.B - b.B);
|
||||
internal sealed record MinimizeInputProbe(bool Mouse, bool PointTargetsButton, bool CapturedAfterDown,
|
||||
int Clicks, bool CapturedDuringClick, bool ManagedMinimized, bool NativeMinimized, bool Visible,
|
||||
|
||||
@@ -26,9 +26,9 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
|
||||
private string? _baseConfigJson;
|
||||
private string? _tailnetFallbackConfigJson;
|
||||
// Retain only the authenticated in-memory alternative. A physical-network
|
||||
// recovery already has to restart the core, so it can recheck the overlay
|
||||
// instead of permanently retaining an earlier public fallback.
|
||||
// Retain the authenticated alternative for compatibility/identity checks.
|
||||
// A public fallback is sticky: automatic physical-network recovery must
|
||||
// never promote it to this cached internal alternative.
|
||||
private string? _preferredTailnetConfigJson;
|
||||
private string? _tailnetInterfaceName;
|
||||
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
|
||||
@@ -387,7 +387,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
try
|
||||
{
|
||||
var addresses = await Dns.GetHostAddressesAsync("vpn.toplc.cn", cancellationToken);
|
||||
var addresses = await Dns.GetHostAddressesAsync("vpn.example.invalid", cancellationToken);
|
||||
if (addresses.Any(address => address.AddressFamily == AddressFamily.InterNetwork))
|
||||
{
|
||||
AppPaths.WriteLog($"Windows DNS 已就绪({started.ElapsedMilliseconds} ms)。");
|
||||
|
||||
@@ -212,7 +212,7 @@ function Get-PIBRegistration($Profile) {
|
||||
function Get-PIBCandidateRegistration($Profile,[string]$Version) {
|
||||
$p=Assert-PIBProfile $Profile
|
||||
$data=@((Join-Path $p.Target 'VPNPlus.exe'),$p.Target,'优创⁺纵横家',(Join-Path $p.Target 'VPNPlus.exe'),$Version,
|
||||
'优创未来(UCVL)','https://vpn.toplc.cn/',('"'+(Join-Path $p.Target 'Uninstall.exe')+'"'),1,1)
|
||||
'优创未来(UCVL)','https://vpn.example.invalid/',('"'+(Join-Path $p.Target 'Uninstall.exe')+'"'),1,1)
|
||||
return [ordered]@{Keys=@($true,$true);Values=@(for($i=0;$i -lt 10;$i++){[ordered]@{Kind=$(if($i -lt 8){'String'}else{'DWord'});Data=$data[$i]}})}
|
||||
}
|
||||
function Get-PIBComponents($Manifest) {
|
||||
|
||||
@@ -29,7 +29,7 @@ RequestExecutionLevel admin
|
||||
!ifndef APP_SOURCE_DIR
|
||||
!define APP_SOURCE_DIR "${__FILEDIR__}\..\dist\app"
|
||||
!endif
|
||||
!define PRODUCT_WEB "https://vpn.toplc.cn/"
|
||||
!define PRODUCT_WEB "https://vpn.example.invalid/"
|
||||
!define PRODUCT_DIR_REGKEY "Software\Microsoft\Windows\CurrentVersion\App Paths\VPNPlus.exe"
|
||||
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\UCVL.VPNPlus"
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
保留三个节点身份及已有认证、流量和代理逻辑。新连接优先检测可用内部入口,按响应排序;内部入口不可用时回退同节点域名公网。实际通过 Tailscale 代理验证才显示“VPN002 + Tailscale”或“VPN003 + Tailscale”,公网连接不加后缀,不以 Ping 通冒充代理可用,也不因排序变化迁移健康连接。
|
||||
|
||||
公开源码示例入口(非生产配置)为 VPN002(东京)100.64.0.2:10803、VPN003(硅谷)100.64.0.3:11083;济南(博翠明湖)内部入口为 GL 100.64.0.4:18081,域名入口为 vpn.toplc.cn:11080,GL 仅转发手机 192.168.50.170:18081,实际出口仍由手机夜猫处理。这里仅记录公开导出的示例,不表示可实际连接。保留旧后台省略字段的窄范围兼容,不增加账号或绕过权限,显式禁用字段继续生效。
|
||||
公开源码示例入口(非生产配置)为 VPN002(东京)100.64.0.2:10803、VPN003(硅谷)100.64.0.3:11083;济南(博翠明湖)内部入口为 GL 100.64.0.4:18081,域名入口为 vpn.example.invalid:11080,GL 仅转发手机 192.168.50.170:18081,实际出口仍由手机夜猫处理。这里仅记录公开导出的示例,不表示可实际连接。保留旧后台省略字段的窄范围兼容,不增加账号或绕过权限,显式禁用字段继续生效。
|
||||
|
||||
## 验收范围
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 纵横家 Windows 0.3.1
|
||||
|
||||
正式、非强制更新。沿用现有账号和代理授权,不启停、登录或配置 Tailscale。
|
||||
|
||||
- 连接时先 Ping 已授权代理的内网 IP,能通则优先按响应时间使用内网入口;不通则回退同一节点的公网/域名入口。
|
||||
- 回退后,本次连接的后台恢复、网络切换和自动重试保持公网入口,不因内网恢复再自动切回;手动断开后重新连接才重新选择。
|
||||
- Ping 仅用于入口可达性选择;代理凭据、服务器身份、授权撤销和代理出口验证继续生效。禁用 ICMP 的内网入口会被跳过。
|
||||
- 公网与 Tailscale 当前速率分开,监控固定高度;两台服务器整机 WAN 监控与个人代理流量分开。无有效服务器样本时显示不可用,不显示伪实时数值。
|
||||
- 图表刷新、缺样本断线段及背景缓存优化;保留现有透明山水界面、托盘及退出行为。
|
||||
|
||||
安装包未进行 Authenticode 签名,更新需要 Windows 管理员授权。
|
||||
本次验证包含同包离线回归、合成界面和隔离文件升级/恢复;不等同于当前用户生产覆盖安装、实际 TUN/UDP 共存或长期业务连接验收。
|
||||
共享账户限速执行层仍未启用;本版本不宣称已实现两服务器共享限速或全体用户实测提速。
|
||||
Reference in New Issue
Block a user