Files

60 lines
3.2 KiB
C#
Raw Permalink Normal View History

using System.Text.Json.Nodes;
namespace UCVL.VPNPlus;
// Operator-supplied compatibility addresses for already-authorized nodes.
// These are same-node transports, not new nodes or login grants.
// The authenticated API config remains the authority for credentials and identity.
internal static class KnownTailnetEndpoints
{
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping)
=> Resolve(response, allowCompatibilityMapping, out _);
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping, out string reason)
{
// This switch permits legacy endpoint mapping, not an employee or
// tailnet-membership policy. The API still supplies node authorization.
// An explicit field (including null/invalid metadata) ALWAYS wins. Never
// turn server rejection or an unknown contract into a compiled fallback.
reason = "compatibility_disabled";
if (!allowCompatibilityMapping) return null;
reason = "explicit_endpoint_present";
if (response.HasTailscaleEndpoint) return null;
reason = "config_contract_unsupported";
if (response.ConfigContract != 2) return null;
reason = "scope_unsupported";
if (response.ConnectionScope is not ("" or "public")) return null;
reason = "route_mode_unsupported";
if (response.RouteMode is not ("smart" or "global")) return null;
var mapping = response.Node.Slug switch
{
"aliyun-tokyo-002" => (Host: "002.vpn.toplc.cn", PublicPort: 11082, Address: "100.99.142.38", Port: 10803),
"aliyun-siliconvalley-003" => (Host: "003.vpn.toplc.cn", PublicPort: 11083, Address: "100.124.242.104", Port: 11083),
"racknerd-newyork-004" => (Host: "004.vpn.toplc.cn", PublicPort: 11084, Address: "100.67.30.7", Port: 11084),
_ => default
};
reason = "known_node_unmapped";
if (mapping.Host is null) return null;
try
{
// Check the API's original node endpoint BEFORE the public-gateway
// rewrite. A reused slug/name must not send credentials to an old IP.
var root = JsonNode.Parse(response.Config.GetRawText())!.AsObject();
reason = "config_scope_or_marker_invalid";
if (root.ContainsKey(TailnetTransport.Marker) || PrivateAuxiliaryRuntime.IsPrivate(root)) return null;
var proxy = TailnetTransport.Proxy(root);
reason = "proxy_identity_unsupported";
if (proxy is null) return null;
var server = proxy?["settings"]?["vnext"]?[0];
reason = "known_original_ingress_mismatch";
if (server?["address"]?.GetValue<string>() != mapping.Host
|| server?["port"]?.GetValue<int>() != mapping.PublicPort) return null;
reason = "known_endpoint";
return new TailnetEndpoint { Contract = 1, NodeSlug = response.Node.Slug,
Address = mapping.Address, Port = mapping.Port };
}
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{ reason = "config_invalid"; return null; }
}
}