Files
Chronos/src/Chronos.Uploader/Server/ServerSession.cs
T
Alby96andClaude Opus 5.5 369e754bec fix(server): public ports as settings, container port lock and client address; clients default to 8443 and name non-Chronos servers
The owner's Uploader could not connect: the panel showed the container's
listening ports (8080/8443) as if clients used them, the public ports were
only environment variables (CHRONOS_PUBLIC_HTTP_PORT not even in the Unraid
template), and the clients mapped a bare host to 443, where another service
answered.

- Public HTTP/HTTPS ports are settings (server.json, or locked by
  CHRONOS_PUBLIC_*) and apply at once; ServerSettingsDto gains appended
  PublicHttpPort, PublicHttpsPort and InContainer members.
- In a container the listening ports are fixed by the template: locked in the
  panel, and saved values from earlier versions are ignored with a warning.
- Settings > Network and TLS shows the client address with a Copy button; the
  discovery tooltip says a container needs network type Host.
- ChronosAddress (shared by Chronos and the Uploader): no scheme and no port is
  https on 8443, https:// keeps 443, a typed port is kept, IPv6 is bracketed.
- GetInfoAsync throws NotChronosServerException for answers that are not a
  Chronos server; another service's certificate is never offered for trust
  and no credentials are sent to it. Both clients name the address asked.
- Unraid template, compose file, user guide, README, BRIEF, DECISIONS,
  CHANGELOG (with an Unraid upgrade note) and ARCHITECTURE updated; en/it
  strings added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:53:49 +01:00

462 lines
16 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.ComponentModel;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Uploads;
namespace Chronos.Uploader.Server;
/// <summary>Connection shown in the header.</summary>
public enum ConnectionState
{
/// <summary>First run: no server chosen yet.</summary>
NotConfigured,
SigningIn,
Connected,
/// <summary>Signed in, but the server cannot be reached; probed every 30 s.</summary>
Offline,
/// <summary>A server is known but there is no valid token.</summary>
SignedOut,
}
/// <summary>Outcome of the sign-in form.</summary>
public enum SignInResult
{
Success,
InvalidAddress,
Unreachable,
NotChronos,
/// <summary>The certificate is self-signed and unknown: ask the user to trust its fingerprint.</summary>
Untrusted,
BadCredentials,
Failed,
}
/// <summary>The server connection as the window sees it.</summary>
public interface IServerSession : INotifyPropertyChanged
{
ConnectionState State { get; }
/// <summary>Server address as the user typed or discovered it.</summary>
string? Address { get; }
string? Username { get; }
/// <summary>Quota in bytes; 0 = unlimited.</summary>
long QuotaBytes { get; }
long UsedBytes { get; }
/// <summary>Upload limit in MB/s; 0 = unlimited.</summary>
int BandwidthLimit { get; set; }
/// <summary>Raised when the server ended the session (token rejected or certificate changed).</summary>
event EventHandler<ServerProblem>? SessionEnded;
/// <summary>Signs in; <see cref="SignInResult.Untrusted"/> comes with the fingerprint to show.</summary>
Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct);
/// <summary>Remembers a certificate fingerprint the user confirmed (trust on first use).</summary>
void Trust(string fingerprint);
Task SignOutAsync();
/// <summary>Refreshes the account (quota) when connected.</summary>
Task RefreshAsync();
Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct);
}
/// <summary>
/// Owns the <see cref="ChronosClient"/>: sign-in with trust-on-first-use, token restore from DPAPI, offline probing,
/// and the upload transport. Runs on the UI thread.
/// </summary>
public sealed class ServerSession : IServerSession, IUploadTransport, IDisposable
{
private static readonly TimeSpan ProbeInterval = TimeSpan.FromSeconds(30);
private readonly UploaderSettings _settings;
private readonly Action _saveSettings;
private ChronosClient? _client;
private ConnectionState _state;
private string? _username;
private long _quotaBytes;
private long _usedBytes;
private int _bandwidthLimit;
private CancellationTokenSource? _probe;
public ServerSession(UploaderSettings settings, Action saveSettings)
{
_settings = settings;
_saveSettings = saveSettings;
_username = settings.Username;
_bandwidthLimit = Math.Max(0, settings.BandwidthLimit);
_state = settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
}
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler? ReadyChanged;
public event EventHandler<ServerProblem>? SessionEnded;
public ConnectionState State
{
get => _state;
private set
{
if (_state == value) return;
var wasReady = IsReady;
_state = value;
OnPropertyChanged();
if (wasReady != IsReady) ReadyChanged?.Invoke(this, EventArgs.Empty);
}
}
public bool IsReady => _state == ConnectionState.Connected && _client is not null;
public string? Address => _settings.ServerUrl;
public string? Username
{
get => _username;
private set => Set(ref _username, value);
}
public long QuotaBytes
{
get => _quotaBytes;
private set => Set(ref _quotaBytes, value);
}
public long UsedBytes
{
get => _usedBytes;
private set => Set(ref _usedBytes, value);
}
public int BandwidthLimit
{
get => _bandwidthLimit;
set
{
if (!Set(ref _bandwidthLimit, Math.Max(0, value))) return;
ApplyBandwidth();
}
}
/// <summary>Restores the saved session, if any, in the background.</summary>
public void Start()
{
if (_settings.ServerUrl is null || _settings.ProtectedToken is null) return;
var token = TokenProtector.Unprotect(_settings.ProtectedToken);
if (token is null || !ServerAddress.TryParse(_settings.ServerUrl, out var uri))
{
Log.Warning("session", "Saved token cannot be used; sign in again");
State = ConnectionState.SignedOut;
return;
}
UseClient(CreateClient(uri));
_client!.Token = token;
State = ConnectionState.SigningIn;
_ = RefreshAsync();
}
public async Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct)
{
if (!ServerAddress.TryParse(address, out var uri)) return (SignInResult.InvalidAddress, null);
StopProbing();
var previous = State;
State = ConnectionState.SigningIn;
var client = CreateClient(uri);
try
{
await client.GetInfoAsync(ct);
var login = await client.LoginAsync(username, password, ct);
if (login.Token is null) throw new ChronosApiException(HttpStatusCode.Unauthorized, new ApiError("no_token", "No token issued"));
_settings.ServerUrl = uri.ToString();
_settings.Username = login.User.Username;
_settings.ProtectedToken = TokenProtector.Protect(login.Token);
_saveSettings();
UseClient(client);
OnPropertyChanged(nameof(Address));
Username = login.User.Username;
SetQuota(login.User);
State = ConnectionState.Connected;
Log.Info("session", $"Signed in to {uri} as {login.User.Username}");
return (SignInResult.Success, null);
}
catch (Exception ex)
{
client.Dispose();
State = previous == ConnectionState.SigningIn ? ConnectionState.NotConfigured : previous;
var result = Classify(ex, ct);
if (result == SignInResult.Failed) Log.Warning("session", $"Sign-in to {uri} failed", ex);
return (result, (ex as UntrustedCertificateException)?.Fingerprint);
}
}
public void Trust(string fingerprint)
{
if (_settings.TrustedFingerprints.Contains(fingerprint, StringComparer.OrdinalIgnoreCase)) return;
_settings.TrustedFingerprints.Add(fingerprint);
_saveSettings();
Log.Info("session", $"Trusted certificate {fingerprint}");
}
public async Task SignOutAsync()
{
StopProbing();
if (_client is { Token: not null } client)
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await client.LogoutAsync(timeout.Token);
}
catch (Exception ex) when (ex is HttpRequestException or ChronosApiException or OperationCanceledException or UntrustedCertificateException)
{
// The token is forgotten locally either way.
Log.Info("session", "Logout not confirmed by the server: " + ex.Message);
}
}
ForgetToken();
}
public async Task RefreshAsync()
{
if (_client is not { } client) return;
try
{
var me = await client.MeAsync();
Username = me.Username;
SetQuota(me);
State = ConnectionState.Connected;
StopProbing();
}
catch (Exception ex) when (IsServerProblem(ex, CancellationToken.None, out var problem))
{
OnServerProblem(problem, ex);
}
catch (ChronosApiException ex)
{
Log.Warning("session", "Account refresh failed", ex);
}
}
public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct)
{
if (!IsReady) return [];
var all = new List<SequenceDto>();
string? cursor = null;
try
{
// Five pages of 200 cover any realistic choice list.
for (var page = 0; page < 5; page++)
{
var result = await _client!.ListSequencesAsync(cursor: cursor, ct: ct);
all.AddRange(result.Items);
cursor = result.NextCursor;
if (cursor is null) break;
}
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
}
catch (ChronosApiException ex)
{
Log.Warning("session", "Sequence list unavailable", ex);
}
return all;
}
// ---------------- IUploadTransport ----------------
public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress<UploadProgress> progress, CancellationToken ct)
{
var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut);
try
{
var result = await client.UploadFileAsync(item.Path, sequenceId, item.CapturedAt, item.SessionKey, sha256, progress, ct);
// The client reports an existing file as index −1 (or no frame at all).
return result is null || result.Index < 0 ? (UploadOutcome.AlreadyOnServer, result?.FrameId) : (UploadOutcome.Verified, result.FrameId);
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
throw new ServerUnavailableException(problem, ex);
}
}
public async Task<Guid> CreateSequenceAsync(string? title, CancellationToken ct)
{
var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut);
try
{
var created = await client.CreateSequenceAsync(new CreateSequenceRequest(string.IsNullOrWhiteSpace(title) ? null : title.Trim(), null), ct);
Log.Info("session", $"Created sequence {created.Id} \"{created.DisplayTitle}\"");
return created.Id;
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
throw new ServerUnavailableException(problem, ex);
}
}
public void Dispose()
{
StopProbing();
_client?.Dispose();
}
// ---------------- Plumbing ----------------
private ChronosClient CreateClient(Uri uri)
{
// A fresh pinning per client: the protocol's last-rejected fingerprint must not outlive a trust decision.
var client = new ChronosClient(uri, new CertificatePinning(_settings.TrustedFingerprints), $"Chronos Uploader ({Environment.MachineName})");
client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
return client;
}
private void UseClient(ChronosClient client)
{
if (ReferenceEquals(_client, client)) return;
_client?.Dispose();
_client = client;
}
private void ApplyBandwidth()
{
if (_client is not null) _client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
}
private void SetQuota(UserDto user)
{
QuotaBytes = user.QuotaBytes;
UsedBytes = user.UsedBytes;
}
private void ForgetToken()
{
if (_client is not null) _client.Token = null;
_settings.ProtectedToken = null;
_saveSettings();
QuotaBytes = 0;
UsedBytes = 0;
State = _settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
}
private bool IsServerProblem(Exception ex, CancellationToken ct, out ServerProblem problem)
{
problem = ServerProblem.Unreachable;
switch (ex)
{
case ChronosApiException { Status: HttpStatusCode.Unauthorized }:
problem = ServerProblem.SignedOut;
return true;
case ChronosApiException api:
return api.IsTransient;
case UntrustedCertificateException untrusted:
// The pinning remembers its last rejection; once trusted, a later network error can still carry it.
if (!_settings.TrustedFingerprints.Contains(untrusted.Fingerprint, StringComparer.OrdinalIgnoreCase))
problem = ServerProblem.CertificateChanged;
return true;
case HttpRequestException:
return true;
case OperationCanceledException when !ct.IsCancellationRequested:
return true; // request timeout
default:
return false;
}
}
private void OnServerProblem(ServerProblem problem, Exception ex)
{
switch (problem)
{
case ServerProblem.SignedOut:
Log.Warning("session", "The server rejected the token; signing out");
StopProbing();
ForgetToken();
SessionEnded?.Invoke(this, problem);
break;
case ServerProblem.CertificateChanged:
// Never upload to a server whose certificate changed: the user must sign in and confirm it again.
Log.Warning("session", "The server certificate changed; sign in again to review it", ex);
StopProbing();
ForgetToken();
SessionEnded?.Invoke(this, problem);
break;
default:
if (State != ConnectionState.Offline) Log.Warning("session", "Server unreachable; retrying every 30 s", ex);
State = ConnectionState.Offline;
StartProbing();
break;
}
}
private void StartProbing()
{
if (_probe is not null) return;
_probe = new CancellationTokenSource();
_ = ProbeAsync(_probe.Token);
}
private void StopProbing()
{
_probe?.Cancel();
_probe?.Dispose();
_probe = null;
}
private async Task ProbeAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested && State == ConnectionState.Offline)
{
await Task.Delay(ProbeInterval, ct);
await RefreshAsync();
}
}
catch (OperationCanceledException)
{
}
}
private static SignInResult Classify(Exception ex, CancellationToken ct) => ex switch
{
UntrustedCertificateException => SignInResult.Untrusted,
NotChronosServerException => SignInResult.NotChronos,
ChronosApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials,
ChronosApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotChronos,
ChronosApiException api when api.IsTransient => SignInResult.Unreachable,
JsonException or NotSupportedException => SignInResult.NotChronos,
HttpRequestException => SignInResult.Unreachable,
OperationCanceledException when !ct.IsCancellationRequested => SignInResult.Unreachable,
_ => SignInResult.Failed,
};
private bool Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(name);
return true;
}
private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}