using System.Text.Json; using System.Text.Json.Nodes; namespace UCVL.VPNPlus; internal static class SingleNodeClientPolicy { internal const string FixedNodeSlug = "racknerd-newyork-004"; internal const string PublicGatewayIpv4 = "47.104.134.190"; internal const int PublicGatewayPort = 11084; internal static IReadOnlyList Nodes(IEnumerable nodes) => nodes .Where(node => node.Slug == FixedNodeSlug && node.Status.Equals("online", StringComparison.OrdinalIgnoreCase)) .Take(1).ToArray(); internal static IReadOnlyList RouteModes(IEnumerable modes) => modes .Where(mode => mode.Id is "smart" or "global") .GroupBy(mode => mode.Id, StringComparer.Ordinal) .Select(group => group.First()).OrderBy(mode => mode.Id == "smart" ? 0 : 1).ToArray(); internal static string Validate(ConfigResponse response, string routeMode) { if (response.Node.Slug != FixedNodeSlug || response.RouteMode != routeMode || response.ConnectionScope is not ("" or "public")) throw new InvalidOperationException("平台返回的默认线路或代理模式不一致,已保留当前连接。"); var runtime = response.GetRuntimeConfigJson(); ValidateRuntime(runtime); return runtime; } internal static void ValidateRuntime(string configJson) { if (TailnetTransport.Address(configJson) is not null || PrivateAuxiliaryRuntime.IsPrivate(configJson)) throw new InvalidOperationException("新版本只接受默认公网代理入口。"); var (address, port) = ProxyEndpoint(configJson); if (address != PublicGatewayIpv4 || port != PublicGatewayPort) throw new InvalidOperationException("平台返回的公网入口不符合当前发布策略。"); } internal static bool SameProxyIdentity(string currentConfig, string replacementConfig) { try { ValidateRuntime(currentConfig); ValidateRuntime(replacementConfig); return JsonNode.DeepEquals(ProxyOutbound(currentConfig), ProxyOutbound(replacementConfig)); } catch { return false; } } private static (string Address, int Port) ProxyEndpoint(string configJson) { var proxy = ProxyOutbound(configJson); var server = proxy["settings"]?["vnext"]?[0] ?? throw new InvalidOperationException("线路配置缺少代理服务器。"); return (server["address"]?.GetValue()?.Trim() ?? "", server["port"]?.GetValue() ?? 0); } private static JsonObject ProxyOutbound(string configJson) { var root = JsonNode.Parse(configJson)?.AsObject() ?? throw new InvalidOperationException("线路配置为空。"); return root["outbounds"]?.AsArray().OfType() .SingleOrDefault(outbound => outbound["tag"]?.GetValue() == "proxy") ?? throw new InvalidOperationException("线路配置缺少唯一代理出口。"); } internal static bool SelfTest() { static ConfigResponse Response(string slug, string route, string address, int port, bool tailnet = false) { var root = new JsonObject { ["inbounds"] = new JsonArray(), ["outbounds"] = new JsonArray( new JsonObject { ["tag"] = "proxy", ["protocol"] = "vless", ["settings"] = new JsonObject { ["vnext"] = new JsonArray(new JsonObject { ["address"] = address, ["port"] = port, ["users"] = new JsonArray(new JsonObject { ["id"] = "fixture" }) }) }, ["streamSettings"] = new JsonObject { ["security"] = "reality" } }, new JsonObject { ["tag"] = "direct", ["protocol"] = "freedom" }), ["routing"] = new JsonObject { ["rules"] = new JsonArray(new JsonObject { ["type"] = "field", ["outboundTag"] = "proxy" }) } }; if (tailnet) root[TailnetTransport.Marker] = new JsonObject { ["address"] = "100.67.30.7", ["port"] = 11084 }; using var document = JsonDocument.Parse(root.ToJsonString()); return new ConfigResponse { Node = new NodeInfo { Slug = slug, Name = "fixture", Status = "online" }, RouteMode = route, ConnectionScope = "public", Config = document.RootElement.Clone(), Gateway = new GatewayInfo { Ipv4 = address, Host = "vpn.ucvl.cn" }, }; } var smart = Response(FixedNodeSlug, "smart", PublicGatewayIpv4, PublicGatewayPort); var global = Response(FixedNodeSlug, "global", PublicGatewayIpv4, PublicGatewayPort); var smartJson = Validate(smart, "smart"); var globalJson = Validate(global, "global"); bool Rejected(Func action) { try { _ = action(); return false; } catch (InvalidOperationException) { return true; } } return SameProxyIdentity(smartJson, globalJson) && Rejected(() => Validate(Response("aliyun-tokyo-002", "smart", PublicGatewayIpv4, PublicGatewayPort), "smart")) && Rejected(() => Validate(Response(FixedNodeSlug, "smart", "100.67.30.7", PublicGatewayPort, tailnet: true), "smart")) && Rejected(() => Validate(Response(FixedNodeSlug, "smart", PublicGatewayIpv4, 11083), "smart")); } } internal static class LiveProxyModeSwitch { internal static async Task ApplyAsync(string replacementRouting, string rollbackRouting, Func apply, Func> verify, CancellationToken token) { try { await apply(replacementRouting, token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (await verify(token).ConfigureAwait(false)) return true; } catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } catch (Exception error) { AppPaths.WriteError(error); } try { await apply(rollbackRouting, token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (!await verify(token).ConfigureAwait(false)) throw new IOException("原代理模式回滚后验证失败。"); return false; } catch (Exception rollbackError) when (rollbackError is not OperationCanceledException || !token.IsCancellationRequested) { throw new RouteModeRollbackFailedException( "代理模式切换失败,原模式自动恢复也未通过。", rollbackError); } } internal static bool SelfTest() { async Task Success() { var applied = new List(); var result = await ApplyAsync("new", "old", (value, _) => { applied.Add(value); return Task.CompletedTask; }, _ => Task.FromResult(true), CancellationToken.None); return result && applied.SequenceEqual(["new"]); } async Task Rollback() { var applied = new List(); var verifies = 0; var result = await ApplyAsync("new", "old", (value, _) => { applied.Add(value); return Task.CompletedTask; }, _ => Task.FromResult(++verifies > 1), CancellationToken.None); return !result && applied.SequenceEqual(["new", "old"]); } async Task ApplyFailureRollsBack() { var applied = new List(); var result = await ApplyAsync("new", "old", (value, _) => { applied.Add(value); return value == "new" ? Task.FromException(new IOException("fixture")) : Task.CompletedTask; }, _ => Task.FromResult(true), CancellationToken.None); return !result && applied.SequenceEqual(["new", "old"]); } async Task RollbackFailureIsDistinct() { try { await ApplyAsync("new", "old", (value, _) => value == "old" ? Task.FromException(new IOException("fixture rollback failure")) : Task.CompletedTask, _ => Task.FromResult(false), CancellationToken.None); return false; } catch (RouteModeRollbackFailedException) { return true; } catch { return false; } } return Success().GetAwaiter().GetResult() && Rollback().GetAwaiter().GetResult() && ApplyFailureRollsBack().GetAwaiter().GetResult() && RollbackFailureIsDistinct().GetAwaiter().GetResult(); } } internal sealed class RouteModeRollbackFailedException(string message, Exception innerException) : IOException(message, innerException);