feat(app): library, jobs, settings, server, welcome and about screens
Local-mode composition root (SQLite index, one JobEngine fed by a single handler registration list), keyset-paged library with thumbnail cache and hover scrub, live job list with throttled updates and the shell job bar, settings with live template validation and encoder self-test, server connection with trust-on-first-use and DPAPI token, first-run welcome, About with update check, and --capture screenshots with synthetic data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
94 files changed
+10130
-374
No files matched your search
@@ -0,0 +1,298 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>The calls the connection makes; implemented over <see cref="TitanoClient"/>, faked in tests.</summary>
|
||||
public interface IServerApi : IDisposable
|
||||
{
|
||||
Uri BaseAddress { get; }
|
||||
|
||||
/// <summary>Bearer token sent with every request.</summary>
|
||||
string? Token { get; set; }
|
||||
|
||||
/// <summary>Throws <see cref="UntrustedCertificateException"/> while the certificate is neither valid nor trusted.</summary>
|
||||
Task<ServerInfo> GetInfoAsync(CancellationToken ct);
|
||||
|
||||
Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct);
|
||||
|
||||
Task<UserDto> MeAsync(CancellationToken ct);
|
||||
|
||||
Task LogoutAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Creates API clients pinned to the certificates the user trusts.</summary>
|
||||
public interface IServerApiFactory
|
||||
{
|
||||
IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints);
|
||||
}
|
||||
|
||||
/// <summary>Certificates trusted on first use (persisted in the settings).</summary>
|
||||
public interface ITrustStore
|
||||
{
|
||||
IReadOnlyCollection<string> Fingerprints { get; }
|
||||
|
||||
void Trust(string server, string fingerprint);
|
||||
}
|
||||
|
||||
/// <summary>Where the connection stands (BRIEF §12.7).</summary>
|
||||
public enum ConnectStep
|
||||
{
|
||||
/// <summary>Nothing started, or signed out.</summary>
|
||||
Idle,
|
||||
|
||||
/// <summary>Reading the server's identity (no credentials are sent).</summary>
|
||||
Probing,
|
||||
|
||||
/// <summary>The certificate is self-signed and unknown: the user must confirm its fingerprint first.</summary>
|
||||
AwaitingTrust,
|
||||
|
||||
/// <summary>The server is identified and trusted: the login form may send the password.</summary>
|
||||
AwaitingCredentials,
|
||||
|
||||
SigningIn,
|
||||
Connected,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Why the last step failed.</summary>
|
||||
public enum ConnectError
|
||||
{
|
||||
None,
|
||||
InvalidAddress,
|
||||
Unreachable,
|
||||
NotTitano,
|
||||
Untrusted,
|
||||
BadCredentials,
|
||||
|
||||
/// <summary>A saved session was rejected (expired or revoked token); sign in again.</summary>
|
||||
SessionExpired,
|
||||
|
||||
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
|
||||
CertificateChanged,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trust-on-first-use connection state machine, mirroring the uploader: the server's identity is read first
|
||||
/// (<c>GET server/info</c>, which needs no credentials); a self-signed certificate that is not trusted yet stops the
|
||||
/// flow at <see cref="ConnectStep.AwaitingTrust"/> until the user confirms its fingerprint; only then can
|
||||
/// <see cref="SignInAsync"/> 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.
|
||||
/// </summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Normalised API base ("https://nas.local:8443/").</summary>
|
||||
public Uri? Address { get; private set; }
|
||||
|
||||
/// <summary>The fingerprint waiting for the user's decision.</summary>
|
||||
public string? PendingFingerprint { get; private set; }
|
||||
|
||||
public ServerInfo? Info { get; private set; }
|
||||
public UserDto? User { get; private set; }
|
||||
|
||||
/// <summary>Round trip of the identity request.</summary>
|
||||
public TimeSpan? Latency { get; private set; }
|
||||
|
||||
/// <summary>The token of the signed-in session (store it encrypted).</summary>
|
||||
public string? Token => Step == ConnectStep.Connected ? _api?.Token : null;
|
||||
|
||||
/// <summary>The signed-in client, for the screens that talk to the server.</summary>
|
||||
public IServerApi? Api => Step == ConnectStep.Connected ? _api : null;
|
||||
|
||||
/// <summary>Raised after every step change.</summary>
|
||||
public event EventHandler? Changed;
|
||||
|
||||
/// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary>
|
||||
public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default)
|
||||
{
|
||||
Reset();
|
||||
if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
|
||||
Address = uri;
|
||||
return await IdentifyAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>The user's answer to the fingerprint question; trusting it identifies the server again.</summary>
|
||||
public async Task<ConnectStep> 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);
|
||||
}
|
||||
|
||||
/// <summary>Sends the credentials; only possible once the server is identified and trusted.</summary>
|
||||
public async Task<ConnectStep> SignInAsync(string username, string password, CancellationToken ct = default)
|
||||
{
|
||||
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is null) 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 (login.Token is null) return Retry(ConnectError.BadCredentials);
|
||||
User = login.User;
|
||||
return Set(ConnectStep.Connected, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resumes a saved session: Connected, or AwaitingCredentials/AwaitingTrust when it cannot be reused.</summary>
|
||||
public async Task<ConnectStep> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the session on the server (best effort) and forgets it here.</summary>
|
||||
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 TitanoApiException or OperationCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
// The token is forgotten locally either way.
|
||||
}
|
||||
}
|
||||
Reset();
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Drops the connection without signing out (the saved token stays valid).</summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
Reset();
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Dispose() => Reset();
|
||||
|
||||
private async Task<ConnectStep> 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;
|
||||
return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
|
||||
}
|
||||
catch (UntrustedCertificateException untrusted)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Back to the login form with an error (wrong password, expired session).</summary>
|
||||
private ConnectStep Retry(ConnectError error) => Set(ConnectStep.AwaitingCredentials, error);
|
||||
|
||||
private ConnectStep Fail(ConnectError error)
|
||||
{
|
||||
_api?.Dispose();
|
||||
_api = null;
|
||||
return Set(ConnectStep.Failed, error);
|
||||
}
|
||||
|
||||
/// <summary>Expected failures as an error code; null lets unexpected exceptions propagate.</summary>
|
||||
internal static ConnectError? Classify(Exception ex, CancellationToken ct) => ex switch
|
||||
{
|
||||
UntrustedCertificateException => ConnectError.Untrusted,
|
||||
TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => ConnectError.BadCredentials,
|
||||
TitanoApiException { Status: HttpStatusCode.NotFound } => ConnectError.NotTitano,
|
||||
TitanoApiException api when api.IsTransient => ConnectError.Unreachable,
|
||||
TitanoApiException => ConnectError.Failed,
|
||||
JsonException or NotSupportedException => ConnectError.NotTitano,
|
||||
HttpRequestException => ConnectError.Unreachable,
|
||||
OperationCanceledException when !ct.IsCancellationRequested => ConnectError.Unreachable,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Server addresses as typed in the address field.</summary>
|
||||
public static class ServerAddress
|
||||
{
|
||||
/// <summary>Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/".</summary>
|
||||
public static bool TryParse(string? text, out Uri uri)
|
||||
{
|
||||
uri = null!;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
var trimmed = text.Trim();
|
||||
if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed;
|
||||
if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false;
|
||||
var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty };
|
||||
if (!builder.Path.EndsWith('/')) builder.Path += "/";
|
||||
uri = builder.Uri;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The address as shown in the field: the base URL without its trailing slash.</summary>
|
||||
public static string Display(Uri uri) => uri.ToString().TrimEnd('/');
|
||||
|
||||
/// <summary>Same, for stored text.</summary>
|
||||
public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Windows.Security;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary><see cref="IServerApi"/> over the protocol's <see cref="TitanoClient"/>.</summary>
|
||||
public sealed class TitanoServerApi(TitanoClient client) : IServerApi
|
||||
{
|
||||
public TitanoClient Client { get; } = client;
|
||||
|
||||
public Uri BaseAddress => Client.BaseAddress;
|
||||
|
||||
public string? Token
|
||||
{
|
||||
get => Client.Token;
|
||||
set => Client.Token = value;
|
||||
}
|
||||
|
||||
public Task<ServerInfo> GetInfoAsync(CancellationToken ct) => Client.GetInfoAsync(ct);
|
||||
|
||||
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct) => Client.LoginAsync(username, password, ct);
|
||||
|
||||
public Task<UserDto> MeAsync(CancellationToken ct) => Client.MeAsync(ct);
|
||||
|
||||
public Task LogoutAsync(CancellationToken ct) => Client.LogoutAsync(ct);
|
||||
|
||||
public void Dispose() => Client.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Creates <see cref="TitanoServerApi"/> clients with a fresh certificate pinning per connection attempt.</summary>
|
||||
public sealed class TitanoServerApiFactory : IServerApiFactory
|
||||
{
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) =>
|
||||
// A fresh pinning per client: the last rejected fingerprint must not outlive a trust decision.
|
||||
new TitanoServerApi(new TitanoClient(baseAddress, new CertificatePinning(trustedFingerprints), $"Titano ({Environment.MachineName})"));
|
||||
}
|
||||
|
||||
/// <summary>Encrypts the session token at rest.</summary>
|
||||
public interface ITokenProtector
|
||||
{
|
||||
string Protect(string token);
|
||||
|
||||
/// <summary>The token, or null when the blob is corrupt or belongs to another Windows user.</summary>
|
||||
string? Unprotect(string protectedToken);
|
||||
}
|
||||
|
||||
/// <summary>DPAPI, current-user scope, with entropy that ties the blob to the desktop client.</summary>
|
||||
public sealed class DpapiTokenProtector : ITokenProtector
|
||||
{
|
||||
private static readonly byte[] Entropy = "Titano.App.Token.v1"u8.ToArray();
|
||||
|
||||
public string Protect(string token) => Dpapi.ProtectString(token, Entropy);
|
||||
|
||||
public string? Unprotect(string protectedToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Dpapi.UnprotectString(protectedToken, Entropy);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or CryptographicException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Titano Server announced on the LAN.</summary>
|
||||
public sealed record DiscoveredServer(string Name, string Address);
|
||||
|
||||
/// <summary>
|
||||
/// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) and reports each server once.
|
||||
/// Beacons are unauthenticated: they only fill the address field, never trust a certificate.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryListener : IDisposable
|
||||
{
|
||||
private readonly HashSet<string> _seen = new(StringComparer.OrdinalIgnoreCase);
|
||||
private CancellationTokenSource? _cts;
|
||||
|
||||
/// <summary>Raised on the synchronization context of the thread that called <see cref="Start"/>.</summary>
|
||||
public event Action<DiscoveredServer>? Found;
|
||||
|
||||
public bool IsRunning => _cts is not null;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_cts is not null) return;
|
||||
_cts = new CancellationTokenSource();
|
||||
var context = SynchronizationContext.Current;
|
||||
var token = _cts.Token;
|
||||
_ = Task.Run(() => ListenAsync(context, token));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
}
|
||||
|
||||
private static string AddressOf(DiscoveryBeacon beacon, IPAddress sender)
|
||||
{
|
||||
var host = sender.AddressFamily == AddressFamily.InterNetworkV6 ? "[" + sender + "]" : sender.ToString();
|
||||
return beacon.HttpsPort > 0 ? $"https://{host}:{beacon.HttpsPort}" : $"http://{host}:{beacon.HttpPort}";
|
||||
}
|
||||
|
||||
private async Task ListenAsync(SynchronizationContext? context, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var udp = new UdpClient();
|
||||
// The uploader may listen on the same port.
|
||||
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
udp.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryBeacon.Port));
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
|
||||
if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
|
||||
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address));
|
||||
lock (_seen)
|
||||
{
|
||||
if (!_seen.Add(server.Address)) continue;
|
||||
}
|
||||
if (context is null) Found?.Invoke(server);
|
||||
else context.Post(_ => Found?.Invoke(server), null);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Log.Info("discovery", "LAN discovery unavailable: " + ex.Message);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.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();
|
||||
}
|
||||
|
||||
// ---------------- 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;
|
||||
}
|
||||
|
||||
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
|
||||
{
|
||||
var result = await _flow.SignInAsync(user, password, ct);
|
||||
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error);
|
||||
});
|
||||
if (signedIn && IsConnected)
|
||||
{
|
||||
Remember();
|
||||
return true;
|
||||
}
|
||||
if (!IsConnected && _flow.Step == ConnectStep.AwaitingCredentials) _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>Splits the 32-byte SHA-256 fingerprint into two lines of 16 bytes.</summary>
|
||||
public static string FormatFingerprint(string fingerprint)
|
||||
{
|
||||
var bytes = fingerprint.Split(':');
|
||||
return bytes.Length <= 16 ? fingerprint : string.Join(':', bytes.Take(16)) + "\n" + 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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user