Files
Chronos/src/Chronos.App/Server/ServerSession.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

273 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.ObjectModel;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Protocol;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Server;
/// <summary>
/// The client's server connection (BRIEF §12.7): drives <see cref="ConnectFlow"/> with the dialogs (fingerprint
/// confirmation before any password is sent, login form), keeps the session token encrypted with DPAPI in the
/// settings, restores it at start, and lists servers announced on the LAN. Runs on the UI thread.
/// </summary>
public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
{
private readonly AppSettings _settings;
private readonly Action _save;
private readonly ITokenProtector _protector;
private readonly ConnectFlow _flow;
private DiscoveryListener? _discovery;
private bool _busy;
public ServerSession(AppSettings settings, Action save, IServerApiFactory factory, ITokenProtector protector)
{
_settings = settings;
_save = save;
_protector = protector;
_flow = new ConnectFlow(factory, this);
_flow.Changed += (_, _) => OnAllPropertiesChanged();
}
public ConnectFlow Flow => _flow;
/// <summary>Servers that announced themselves on this network.</summary>
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
public bool IsConnected => _flow.Step == ConnectStep.Connected;
/// <summary>A connection attempt is running.</summary>
public bool IsBusy
{
get => _busy;
private set => Set(ref _busy, value);
}
/// <summary>Server name for the status strip; null when not connected.</summary>
public string? ServerName => IsConnected ? _flow.Info?.Name : null;
/// <summary>The saved address (last server used).</summary>
public string? SavedAddress => _settings.ServerUrl;
/// <summary>The token of the saved session is present (Disconnect keeps it).</summary>
public bool HasSavedSession => _settings.ServerUrl is not null && _settings.ProtectedToken is not null;
// ---------------- ITrustStore ----------------
public IReadOnlyCollection<string> Fingerprints => [.. _settings.TrustedCertificates.Select(c => c.Fingerprint)];
public void Trust(string server, string fingerprint)
{
if (_settings.TrustedCertificates.Any(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase))) return;
_settings.TrustedCertificates.Add(new TrustedCertificate { Fingerprint = fingerprint, Server = server, TrustedAt = DateTimeOffset.UtcNow });
_save();
Log.Info("server", $"Trusted certificate {fingerprint} of {server}");
}
/// <summary>The trust record of a fingerprint, if the user trusted it.</summary>
public TrustedCertificate? TrustOf(string? fingerprint) =>
fingerprint is null ? null : _settings.TrustedCertificates.FirstOrDefault(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase));
/// <summary>Forgets a trusted certificate; the next connection asks again.</summary>
public void Forget(string fingerprint)
{
if (_settings.TrustedCertificates.RemoveAll(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase)) == 0) return;
_save();
OnAllPropertiesChanged();
}
/// <summary>
/// Forgets a trusted certificate once the user confirmed it (Server screen and Settings › Server alike); the session
/// that relies on it is closed first. True when it was forgotten.
/// </summary>
public bool ConfirmForget(string fingerprint, IAppDialogs dialogs)
{
if (!dialogs.Confirm(ForgetRequest(fingerprint))) return false;
if (IsConnected && string.Equals(TrustOf(_flow.Info?.TlsFingerprint)?.Fingerprint, fingerprint, StringComparison.OrdinalIgnoreCase)) Disconnect();
Forget(fingerprint);
return true;
}
// ---------------- Session ----------------
/// <summary>Resumes the saved session at start; stays signed out quietly when it cannot be reused.</summary>
public async Task RestoreAsync(CancellationToken ct = default)
{
if (_settings.ServerUrl is not { } address || _settings.ProtectedToken is not { } blob) return;
var token = _protector.Unprotect(blob);
if (token is null)
{
Log.Warning("server", "The saved session cannot be decrypted; sign in again");
ForgetToken();
return;
}
IsBusy = true;
try
{
var step = await _flow.RestoreAsync(address, token, ct);
if (step == ConnectStep.Connected) Log.Info("server", $"Session restored on {address}");
else if (_flow.Error is ConnectError.SessionExpired or ConnectError.CertificateChanged) ForgetToken();
}
finally
{
IsBusy = false;
}
}
/// <summary>
/// Connects to <paramref name="address"/>: identifies the server, asks to trust an unknown self-signed
/// certificate, then reuses the saved session or shows the login form. True when connected.
/// </summary>
public async Task<bool> ConnectAsync(string address, IAppDialogs dialogs, CancellationToken ct = default)
{
IsBusy = true;
try
{
var step = await _flow.ProbeAsync(address, ct);
if (step == ConnectStep.AwaitingTrust && _flow.PendingFingerprint is { } fingerprint)
{
var trusted = dialogs.Confirm(TrustRequest(ServerAddress.Display(_flow.Address!), fingerprint));
step = await _flow.ConfirmTrustAsync(trusted, ct);
}
if (step != ConnectStep.AwaitingCredentials) return false;
var display = ServerAddress.Display(_flow.Address!);
if (HasSavedSession && ServerAddress.Display(_settings.ServerUrl) == display && _protector.Unprotect(_settings.ProtectedToken!) is { } token)
{
step = await _flow.RestoreAsync(display, token, ct);
if (step == ConnectStep.Connected)
{
Remember();
return true;
}
if (step != ConnectStep.AwaitingCredentials) return false;
}
// The form may be cancelled while the server is still answering: that answer must not sign this PC in.
using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct);
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
{
var result = await _flow.SignInAsync(user, password, attempt.Token);
// An answer the flow dropped (the form was cancelled meanwhile) carries no error of its own.
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error);
});
if (signedIn && IsConnected)
{
Remember();
return true;
}
await attempt.CancelAsync();
// Signed in just before the cancel was handled: the session the user turned down ends on the server too.
if (IsConnected) await _flow.SignOutAsync();
else if (_flow.Step is ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) _flow.Disconnect();
return false;
}
finally
{
IsBusy = false;
}
}
/// <summary>Signs out on the server and removes the token from this PC.</summary>
public async Task SignOutAsync()
{
await _flow.SignOutAsync();
ForgetToken();
}
/// <summary>Closes the connection and works locally; the saved session is kept for the next Connect.</summary>
public void Disconnect() => _flow.Disconnect();
public void StartDiscovery()
{
if (_discovery is not null) return;
_discovery = new DiscoveryListener();
_discovery.Found += server =>
{
if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
Discovered.Add(server);
};
_discovery.Start();
}
public void Dispose()
{
_discovery?.Dispose();
_discovery = null;
_flow.Dispose();
}
/// <summary>One sentence for a failed step (BRIEF §0.2 rule 6).</summary>
public static string ErrorText(ConnectError error) => Loc.L("Server.Error." + error);
/// <summary>The trust-on-first-use question with the fingerprint split over two lines.</summary>
public static ConfirmRequest TrustRequest(string server, string fingerprint) => new()
{
Heading = Loc.L("Server.Trust.Title"),
Message = Loc.L("Server.Trust.Message", server),
Detail = FormatFingerprint(fingerprint),
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
SafeText = Loc.L("Server.Trust.Cancel"),
SafeToolTip = Loc.L("Tooltips.Server.DontTrust"),
ActionText = Loc.L("Server.Trust.Accept"),
ActionToolTip = Loc.L("Tooltips.Server.Trust"),
};
/// <summary>The destructive question before a trusted certificate is forgotten, with its fingerprint.</summary>
public static ConfirmRequest ForgetRequest(string fingerprint) => new()
{
Heading = Loc.L("Server.Certificate.Title"),
Message = Loc.L("Server.Certificate.Message"),
Detail = FormatFingerprint(fingerprint),
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
SafeText = Loc.L("Server.Certificate.Keep"),
SafeToolTip = Loc.L("Tooltips.Server.KeepTrust"),
ActionText = Loc.L("Server.Certificate.Forget"),
ActionToolTip = Loc.L("Tooltips.Server.ForgetTrust"),
IsDestructive = true,
};
/// <summary>Splits the 32-byte SHA-256 fingerprint into two lines of 16 bytes, each kept left to right.</summary>
public static string FormatFingerprint(string fingerprint)
{
var bytes = fingerprint.Split(':');
return bytes.Length <= 16
? Formatting.LeftToRight(fingerprint)
: Formatting.LeftToRight(string.Join(':', bytes.Take(16))) + "\n" + Formatting.LeftToRight(string.Join(':', bytes.Skip(16)));
}
/// <summary>"9A:3C:71:E0:…" for the status line.</summary>
public static string ShortFingerprint(string fingerprint)
{
var bytes = fingerprint.Split(':');
return bytes.Length <= 4 ? fingerprint : string.Join(':', bytes.Take(4)) + ":…";
}
/// <summary>The account of the session (role, quota) for the Server screen.</summary>
public UserDto? User => IsConnected ? _flow.User : null;
private void Remember()
{
if (_flow.Address is null || _flow.Token is null) return;
var display = ServerAddress.Display(_flow.Address);
_settings.ServerUrl = display;
_settings.ServerUsername = _flow.User?.Username ?? _settings.ServerUsername;
_settings.ProtectedToken = _protector.Protect(_flow.Token);
_settings.RecentServers.RemoveAll(s => s.Equals(display, StringComparison.OrdinalIgnoreCase));
_settings.RecentServers.Insert(0, display);
if (_settings.RecentServers.Count > 8) _settings.RecentServers.RemoveRange(8, _settings.RecentServers.Count - 8);
_save();
Log.Info("server", $"Signed in to {display} as {_settings.ServerUsername}");
OnAllPropertiesChanged();
}
private void ForgetToken()
{
if (_settings.ProtectedToken is null) return;
_settings.ProtectedToken = null;
_save();
OnAllPropertiesChanged();
}
}