using System.Diagnostics; using System.Net; using System.Net.Http; using System.Text.Json; using Chronos.Protocol; using Chronos.Protocol.Client; namespace Chronos.App.Server; /// The calls the connection makes; implemented over , faked in tests. public interface IServerApi : IDisposable { Uri BaseAddress { get; } /// Bearer token sent with every request. string? Token { get; set; } /// Throws while the certificate is neither valid nor trusted. Task GetInfoAsync(CancellationToken ct); Task LoginAsync(string username, string password, CancellationToken ct); Task MeAsync(CancellationToken ct); Task LogoutAsync(CancellationToken ct); } /// Creates API clients pinned to the certificates the user trusts. public interface IServerApiFactory { IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints); } /// Certificates trusted on first use (persisted in the settings). public interface ITrustStore { IReadOnlyCollection Fingerprints { get; } void Trust(string server, string fingerprint); } /// Where the connection stands (BRIEF ยง12.7). public enum ConnectStep { /// Nothing started, or signed out. Idle, /// Reading the server's identity (no credentials are sent). Probing, /// The certificate is self-signed and unknown: the user must confirm its fingerprint first. AwaitingTrust, /// The server is identified and trusted: the login form may send the password. AwaitingCredentials, SigningIn, Connected, Failed, } /// Why the last step failed. public enum ConnectError { None, InvalidAddress, Unreachable, NotChronos, Untrusted, BadCredentials, /// A saved session was rejected (expired or revoked token); sign in again. SessionExpired, /// The certificate differs from the trusted one; the saved session was dropped. CertificateChanged, Failed, /// The address is this PC's own shared library (owner review 5, #67), which this desktop already has open. OwnLibrary, } /// /// Trust-on-first-use connection state machine, mirroring the uploader: the server's identity is read first /// (GET server/info, which needs no credentials); a self-signed certificate that is not trusted yet stops the /// flow at until the user confirms its fingerprint; only then can /// send the password. A saved token is restored the same way, and a changed certificate /// never reuses it. Not thread-safe; drive it from the UI. /// public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : IDisposable { private IServerApi? _api; public ConnectStep Step { get; private set; } = ConnectStep.Idle; public ConnectError Error { get; private set; } /// Normalised API base ("https://nas.local:8443/"). public Uri? Address { get; private set; } /// The fingerprint waiting for the user's decision. public string? PendingFingerprint { get; private set; } public ServerInfo? Info { get; private set; } public UserDto? User { get; private set; } /// Round trip of the identity request. public TimeSpan? Latency { get; private set; } /// The token of the signed-in session (store it encrypted). public string? Token => Step == ConnectStep.Connected ? _api?.Token : null; /// The signed-in client, for the screens that talk to the server. public IServerApi? Api => Step == ConnectStep.Connected ? _api : null; /// Raised after every step change. public event EventHandler? Changed; /// /// True for this PC's own shared library, by its certificate fingerprint or its server id (owner review 5, #67): the /// flow refuses it before any trust question or password. /// public Func? IsOwnLibrary { get; set; } /// Identifies the server at : ends in AwaitingTrust, AwaitingCredentials or Failed. public async Task ProbeAsync(string address, CancellationToken ct = default) { Reset(); if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress); Address = uri; return await IdentifyAsync(ct); } /// The user's answer to the fingerprint question; trusting it identifies the server again. public async Task ConfirmTrustAsync(bool trusted, CancellationToken ct = default) { if (Step != ConnectStep.AwaitingTrust || PendingFingerprint is null || Address is null) return Step; if (!trusted) return Fail(ConnectError.Untrusted); trust.Trust(ServerAddress.Display(Address), PendingFingerprint); PendingFingerprint = null; return await IdentifyAsync(ct); } /// /// Sends the credentials; only possible once the server is identified and trusted. An answer that arrives after the /// flow moved on (disconnected, or connecting elsewhere) changes nothing. /// public async Task SignInAsync(string username, string password, CancellationToken ct = default) { if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is not { } api) return Step; if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials); Set(ConnectStep.SigningIn, ConnectError.None); try { var login = await api.LoginAsync(username.Trim(), password, ct); if (!ReferenceEquals(api, _api)) return Step; if (login.Token is null) return Retry(ConnectError.BadCredentials); // ChronosClient keeps the token itself; set it explicitly so every IServerApi behaves the same. api.Token = login.Token; User = login.User; return Set(ConnectStep.Connected, ConnectError.None); } catch (Exception ex) when (Classify(ex, ct) is { } error) { if (!ReferenceEquals(api, _api)) return Step; return error is ConnectError.BadCredentials ? Retry(error) : Fail(error); } } /// Resumes a saved session: Connected, or AwaitingCredentials/AwaitingTrust when it cannot be reused. public async Task RestoreAsync(string address, string token, CancellationToken ct = default) { Reset(); if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress); Address = uri; if (await IdentifyAsync(ct) != ConnectStep.AwaitingCredentials) { // Never resend a token to a server whose certificate is no longer the trusted one. if (Step == ConnectStep.AwaitingTrust) Error = ConnectError.CertificateChanged; Changed?.Invoke(this, EventArgs.Empty); return Step; } _api!.Token = token; try { User = await _api.MeAsync(ct); return Set(ConnectStep.Connected, ConnectError.None); } catch (Exception ex) when (Classify(ex, ct) is { } error) { _api.Token = null; return error is ConnectError.BadCredentials ? Retry(ConnectError.SessionExpired) : Fail(error); } } /// Ends the session on the server (best effort) and forgets it here. public async Task SignOutAsync() { if (_api is { Token: not null } api) { try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await api.LogoutAsync(timeout.Token); } catch (Exception ex) when (ex is HttpRequestException or ChronosApiException or OperationCanceledException or UntrustedCertificateException) { // The token is forgotten locally either way. } } Reset(); Changed?.Invoke(this, EventArgs.Empty); } /// Drops the connection without signing out (the saved token stays valid). public void Disconnect() { Reset(); Changed?.Invoke(this, EventArgs.Empty); } public void Dispose() => Reset(); private async Task IdentifyAsync(CancellationToken ct) { Set(ConnectStep.Probing, ConnectError.None); _api?.Dispose(); _api = factory.Create(Address!, trust.Fingerprints); try { var clock = Stopwatch.StartNew(); Info = await _api.GetInfoAsync(ct); Latency = clock.Elapsed; if (IsOwnLibrary?.Invoke(Info.TlsFingerprint, Info.ServerId) == true) return Fail(ConnectError.OwnLibrary); return Set(ConnectStep.AwaitingCredentials, ConnectError.None); } catch (UntrustedCertificateException untrusted) { if (IsOwnLibrary?.Invoke(untrusted.Fingerprint, null) == true) return Fail(ConnectError.OwnLibrary); PendingFingerprint = untrusted.Fingerprint; return Set(ConnectStep.AwaitingTrust, ConnectError.None); } catch (Exception ex) when (Classify(ex, ct) is { } error) { return Fail(error); } } private void Reset() { _api?.Dispose(); _api = null; Step = ConnectStep.Idle; Error = ConnectError.None; Address = null; PendingFingerprint = null; Info = null; User = null; Latency = null; } private ConnectStep Set(ConnectStep step, ConnectError error) { Step = step; Error = error; Changed?.Invoke(this, EventArgs.Empty); return step; } /// Back to the login form with an error (wrong password, expired session). private ConnectStep Retry(ConnectError error) => Set(ConnectStep.AwaitingCredentials, error); private ConnectStep Fail(ConnectError error) { _api?.Dispose(); _api = null; return Set(ConnectStep.Failed, error); } /// Expected failures as an error code; null lets unexpected exceptions propagate. internal static ConnectError? Classify(Exception ex, CancellationToken ct) => ex switch { UntrustedCertificateException => ConnectError.Untrusted, NotChronosServerException => ConnectError.NotChronos, ChronosApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => ConnectError.BadCredentials, ChronosApiException { Status: HttpStatusCode.NotFound } => ConnectError.NotChronos, ChronosApiException api when api.IsTransient => ConnectError.Unreachable, ChronosApiException => ConnectError.Failed, JsonException or NotSupportedException => ConnectError.NotChronos, HttpRequestException => ConnectError.Unreachable, OperationCanceledException when !ct.IsCancellationRequested => ConnectError.Unreachable, _ => null, }; } /// Server addresses as typed in the address field. public static class ServerAddress { /// /// Accepts "nas.local" (https on port 8443 assumed), "nas.local:9443" or a full http(s) URL, which keeps its scheme's /// port; the result is the API base, ending with "/" (, shared with the uploader). /// public static bool TryParse(string? text, out Uri uri) => ChronosAddress.TryParse(text, out uri); /// The address as shown in the field: the base URL without its trailing slash. public static string Display(Uri uri) => uri.ToString().TrimEnd('/'); /// Same, for stored text. public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty; }