using System.Diagnostics; using System.Text.Json.Nodes; namespace Strata.Desktop; internal static partial class CoreClient { internal sealed record RemoteConnection(string Host, string? User, int Port, string? IdentityFile, int NodePort, string Token); private static RemoteConnection? selectedRemote; private static bool selectedLocal; public static string SourceLabel => selectedRemote is { } remote ? $"SSH · {remote.Host}" : Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") != null && !selectedLocal ? "Налаштований вузол" : "Ваш комп’ютер"; // Only before the management window/observers exist; never rebind pending UUIDs. public static async Task OpenSelection(RemoteConnection? remote, CancellationToken token) { if (remote != null) ValidateRemote(remote); await Gate.WaitAsync(token); try { if (client != null) throw new InvalidOperationException("Спочатку закрийте поточну сесію керування."); CloseTransport(); selectedRemote = remote; selectedLocal = remote == null; } finally { Gate.Release(); } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(15)); await Connect(timeout.Token); } private static void ValidateRemote(RemoteConnection remote) { static bool Identifier(string value) => value.Length is > 0 and <= 128 && char.IsAsciiLetterOrDigit(value[0]) && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-'); if (remote.Host.Length is 0 or > 253 || !char.IsAsciiLetterOrDigit(remote.Host[0]) || !remote.Host.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-' or ':') || remote.User is { } user && !Identifier(user) || remote.Port is < 1 or > 65535 || remote.NodePort is < 1 or > 65535) throw new InvalidOperationException("Перевірте SSH host, користувача та порти."); if (remote.IdentityFile is { } identity && (!Path.IsPathFullyQualified(identity) || identity.Length > 4096 || identity.Any(char.IsControl))) throw new InvalidOperationException("Потрібен абсолютний шлях до SSH-ключа."); if (remote.Token.Length is < 32 or > 4096 || remote.Token.Any(c => c < 33 || c > 126)) throw new InvalidOperationException("Потрібен ключ доступу node: 32–4096 друкованих ASCII-символів."); } private static string CoreExecutable() { var executable = Environment.GetEnvironmentVariable("STRATA_DESKTOP_CORE") ?? Path.Combine(AppContext.BaseDirectory, OperatingSystem.IsWindows() ? "strata-desktop.exe" : "strata-desktop"); if (!Path.IsPathFullyQualified(executable) || !File.Exists(executable)) throw new InvalidOperationException("Rust core не знайдено. Зберіть desktop-core або вкажіть абсолютний STRATA_DESKTOP_CORE."); return executable; } private static async Task BootstrapRemote(RemoteConnection remote, CancellationToken token) { ValidateRemote(remote); credential = remote.Token; ownedAgent = new Process { StartInfo = new ProcessStartInfo(CoreExecutable()) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true }}; ownedAgent.StartInfo.ArgumentList.Add("ssh-tunnel"); ownedAgent.StartInfo.ArgumentList.Add("--stdio-lifetime"); ownedAgent.StartInfo.Environment.Remove("STRATA_NODE_TOKEN"); ownedAgent.StartInfo.Environment.Remove("STRATA_BOOTSTRAP_TOKEN"); ownedAgent.Start(); _ = Drain(ownedAgent.StandardError); var config = new JsonObject { ["schema_version"] = 1, ["ssh"] = new JsonObject { ["schema_version"] = 1, ["id"] = "desktop", ["host"] = remote.Host, ["user"] = remote.User, ["port"] = remote.Port, ["identity_file"] = remote.IdentityFile }, ["listen"] = "127.0.0.1:0", ["remote_port"] = remote.NodePort, ["max_connections"] = 4 }; await ownedAgent.StandardInput.WriteLineAsync(config.ToJsonString().AsMemory(), token); await ownedAgent.StandardInput.FlushAsync(token); var line = await ReadLineBounded(ownedAgent.StandardOutput, token); var descriptor = JsonNode.Parse(line) as JsonObject; if (descriptor?["schema_version"]?.GetValue() != 1 || descriptor["transport"]?.GetValue() != "ssh") throw new InvalidOperationException("Несумісний SSH transport."); _ = Drain(ownedAgent.StandardOutput); return descriptor["endpoint"]?.GetValue(); } public static async Task ConnectionSelfCheck(string path) { var config = JsonNode.Parse(await File.ReadAllTextAsync(path))!.AsObject(); var ssh = config["ssh"]!; var remote = new RemoteConnection(ssh["host"]!.GetValue(), ssh["user"]?.GetValue(), ssh["port"]?.GetValue() ?? 22, ssh["identity_file"]?.GetValue(), config["remote_port"]!.GetValue(), Environment.GetEnvironmentVariable("STRATA_NODE_TOKEN")!); try { await OpenSelection(remote with { Token = new string('x', 64) }, CancellationToken.None); throw new InvalidOperationException("Incorrect credential accepted"); } catch (Grpc.Core.RpcException e) when (e.StatusCode == Grpc.Core.StatusCode.Unauthenticated) {} await OpenSelection(remote, CancellationToken.None); var transportPid = ownedAgent!.Id; await SelfCheck(); try { await OpenSelection(null, CancellationToken.None); throw new Exception("Active session silently rebound"); } catch (InvalidOperationException) {} Close(); try { using var process = Process.GetProcessById(transportPid); if (!process.HasExited) throw new Exception("Owned transport survived close"); } catch (ArgumentException) {} await OpenSelection(null, CancellationToken.None); await SelfCheck(); Close(); Console.WriteLine("PASS: desktop connection selection, real owned SSH, auth retry, no active rebind, cleanup, local gRPC selection."); } }