Chronos Server for Windows is replaced by Settings > Server > Share this library: Chronos Desktop hosts the server engine in its own process over its own index, archive and processing services, job engine and scheduler, so a second PC, the Uploader and render nodes use this PC's library without a Windows service or a second index. - Chronos.Server is a library; Chronos.Server.Host is the console exe that Docker and development runs start. The App references the library and the ASP.NET Core shared framework (no package). - ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and never creates, starts or disposes them; no static log sink, no console lifetime; server.json plus desktop-owned values locked "Set in Chronos Desktop"; only upload-cleanup and audit-cleanup schedules are added. - Both modes: by-id endpoints scoped to the served archive, a client's render export folder dropped; hosted mode exposes server job kinds only. - Desktop: LibraryShare (start after the schedules, stop first, port in use named), Settings > Server sharing rows, Server > This library panel (state, addresses with Copy, ports, fingerprint, temporary admin password, clients, admin panel), own library refused by ConnectFlow and dropped from LAN discovery, the uploads sweep step, thumbnails after scans while sharing, capture scenes server-share and server-share-failed. - Removed: the Windows service hosting of Chronos.Server, its switches and its tests. Refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
12 KiB
C#
310 lines
12 KiB
C#
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;
|
|
|
|
/// <summary>The calls the connection makes; implemented over <see cref="ChronosClient"/>, 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,
|
|
NotChronos,
|
|
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>The address is this PC's own shared library (owner review 5, #67), which this desktop already has open.</summary>
|
|
OwnLibrary,
|
|
}
|
|
|
|
/// <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>
|
|
/// 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.
|
|
/// </summary>
|
|
public Func<string?, Guid?, bool>? IsOwnLibrary { get; set; }
|
|
|
|
/// <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. An answer that arrives after the
|
|
/// flow moved on (disconnected, or connecting elsewhere) changes nothing.
|
|
/// </summary>
|
|
public async Task<ConnectStep> 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);
|
|
}
|
|
}
|
|
|
|
/// <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 ChronosApiException 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;
|
|
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;
|
|
}
|
|
|
|
/// <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,
|
|
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,
|
|
};
|
|
}
|
|
|
|
/// <summary>Server addresses as typed in the address field.</summary>
|
|
public static class ServerAddress
|
|
{
|
|
/// <summary>
|
|
/// 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 "/" (<see cref="ChronosAddress"/>, shared with the uploader).
|
|
/// </summary>
|
|
public static bool TryParse(string? text, out Uri uri) => ChronosAddress.TryParse(text, out uri);
|
|
|
|
/// <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;
|
|
}
|