Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
108 lines
6.4 KiB
C#
108 lines
6.4 KiB
C#
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<string?> 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<int>() != 1 || descriptor["transport"]?.GetValue<string>() != "ssh")
|
|
throw new InvalidOperationException("Несумісний SSH transport.");
|
|
_ = Drain(ownedAgent.StandardOutput);
|
|
return descriptor["endpoint"]?.GetValue<string>();
|
|
}
|
|
|
|
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<string>(), ssh["user"]?.GetValue<string>(),
|
|
ssh["port"]?.GetValue<int>() ?? 22, ssh["identity_file"]?.GetValue<string>(),
|
|
config["remote_port"]!.GetValue<int>(), 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.");
|
|
}
|
|
}
|