From 42d96c962d0f4eb50481d3d8f12f2f2a4492227f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:27:36 +0000 Subject: [PATCH] feat(uploader): server session with trust-on-first-use sign-in and LAN discovery Checks the certificate before sending the password and returns an unknown self-signed fingerprint for confirmation; restores the saved token, reports quota, probes every 30 s while offline, signs out when the token is rejected or the certificate changes, and maps transport failures for the engine. UDP beacon listener for servers on the LAN. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Server/DiscoveryListener.cs | 79 +++ src/Titano.Uploader/Server/ServerAddress.cs | 21 + src/Titano.Uploader/Server/ServerSession.cs | 460 ++++++++++++++++++ .../Uploader/ServerAddressTests.cs | 25 + 4 files changed, 585 insertions(+) create mode 100644 src/Titano.Uploader/Server/DiscoveryListener.cs create mode 100644 src/Titano.Uploader/Server/ServerAddress.cs create mode 100644 src/Titano.Uploader/Server/ServerSession.cs create mode 100644 tests/Titano.App.Tests/Uploader/ServerAddressTests.cs diff --git a/src/Titano.Uploader/Server/DiscoveryListener.cs b/src/Titano.Uploader/Server/DiscoveryListener.cs new file mode 100644 index 00000000..18286c83 --- /dev/null +++ b/src/Titano.Uploader/Server/DiscoveryListener.cs @@ -0,0 +1,79 @@ +using System.Net; +using System.Net.Sockets; +using Titano.Core.Diagnostics; +using Titano.Protocol; + +namespace Titano.Uploader.Server; + +/// A Titano Server announced on the LAN. +public sealed record DiscoveredServer(string Name, string Address) +{ + public override string ToString() => Name + " · " + Address; +} + +/// +/// Listens for the server's UDP beacon () while the connect form is open and reports +/// each server once. Beacons are unauthenticated: they only fill the address field, never trust a certificate. +/// +public sealed class DiscoveryListener : IDisposable +{ + private readonly HashSet _seen = new(StringComparer.OrdinalIgnoreCase); + private CancellationTokenSource? _cts; + + /// Raised on the thread that called . + public event Action? Found; + + public void Start() + { + if (_cts is not null) return; + _cts = new CancellationTokenSource(); + var context = SynchronizationContext.Current; + _ = Task.Run(() => ListenAsync(context, _cts.Token)); + } + + public void Stop() + { + _cts?.Cancel(); + _cts?.Dispose(); + _cts = null; + } + + public void Dispose() => Stop(); + + /// The address the client should use for sent from . + public 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 desktop client 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); + } + } +} diff --git a/src/Titano.Uploader/Server/ServerAddress.cs b/src/Titano.Uploader/Server/ServerAddress.cs new file mode 100644 index 00000000..6d025400 --- /dev/null +++ b/src/Titano.Uploader/Server/ServerAddress.cs @@ -0,0 +1,21 @@ +namespace Titano.Uploader.Server; + +/// Server addresses as typed in the sign-in form. +public static class ServerAddress +{ + /// + /// Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/". + /// + 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; + } +} diff --git a/src/Titano.Uploader/Server/ServerSession.cs b/src/Titano.Uploader/Server/ServerSession.cs new file mode 100644 index 00000000..7a672483 --- /dev/null +++ b/src/Titano.Uploader/Server/ServerSession.cs @@ -0,0 +1,460 @@ +using System.ComponentModel; +using System.Net; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text.Json; +using Titano.Core.Diagnostics; +using Titano.Protocol; +using Titano.Protocol.Client; +using Titano.Uploader.Infrastructure; +using Titano.Uploader.Uploads; + +namespace Titano.Uploader.Server; + +/// Connection shown in the header. +public enum ConnectionState +{ + /// First run: no server chosen yet. + NotConfigured, + SigningIn, + Connected, + + /// Signed in, but the server cannot be reached; probed every 30 s. + Offline, + + /// A server is known but there is no valid token. + SignedOut, +} + +/// Outcome of the sign-in form. +public enum SignInResult +{ + Success, + InvalidAddress, + Unreachable, + NotTitano, + + /// The certificate is self-signed and unknown: ask the user to trust its fingerprint. + Untrusted, + BadCredentials, + Failed, +} + +/// The server connection as the window sees it. +public interface IServerSession : INotifyPropertyChanged +{ + ConnectionState State { get; } + + /// Server address as the user typed or discovered it. + string? Address { get; } + + string? Username { get; } + + /// Quota in bytes; 0 = unlimited. + long QuotaBytes { get; } + + long UsedBytes { get; } + + /// Upload limit in MB/s; 0 = unlimited. + int BandwidthLimit { get; set; } + + /// Raised when the server ended the session (token rejected or certificate changed). + event EventHandler? SessionEnded; + + /// Signs in; comes with the fingerprint to show. + Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct); + + /// Remembers a certificate fingerprint the user confirmed (trust on first use). + void Trust(string fingerprint); + + Task SignOutAsync(); + + /// Refreshes the account (quota) when connected. + Task RefreshAsync(); + + Task> ListSequencesAsync(CancellationToken ct); +} + +/// +/// Owns the : sign-in with trust-on-first-use, token restore from DPAPI, offline probing, +/// and the upload transport. Runs on the UI thread. +/// +public sealed class ServerSession : IServerSession, IUploadTransport, IDisposable +{ + private static readonly TimeSpan ProbeInterval = TimeSpan.FromSeconds(30); + + private readonly UploaderSettings _settings; + private readonly Action _saveSettings; + private TitanoClient? _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? 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(); + } + } + + /// Restores the saved session, if any, in the background. + 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 TitanoApiException(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 TitanoApiException 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 (TitanoApiException ex) + { + Log.Warning("session", "Account refresh failed", ex); + } + } + + public async Task> ListSequencesAsync(CancellationToken ct) + { + if (!IsReady) return []; + var all = new List(); + 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 (TitanoApiException 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 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 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 TitanoClient CreateClient(Uri uri) + { + // A fresh pinning per client: the protocol's last-rejected fingerprint must not outlive a trust decision. + var client = new TitanoClient(uri, new CertificatePinning(_settings.TrustedFingerprints), $"Titano Uploader ({Environment.MachineName})"); + client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L; + return client; + } + + private void UseClient(TitanoClient 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 TitanoApiException { Status: HttpStatusCode.Unauthorized }: + problem = ServerProblem.SignedOut; + return true; + case TitanoApiException 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, + TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials, + TitanoApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotTitano, + TitanoApiException api when api.IsTransient => SignInResult.Unreachable, + JsonException or NotSupportedException => SignInResult.NotTitano, + HttpRequestException => SignInResult.Unreachable, + OperationCanceledException when !ct.IsCancellationRequested => SignInResult.Unreachable, + _ => SignInResult.Failed, + }; + + private bool Set(ref T field, T value, [CallerMemberName] string? name = null) + { + if (EqualityComparer.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)); +} diff --git a/tests/Titano.App.Tests/Uploader/ServerAddressTests.cs b/tests/Titano.App.Tests/Uploader/ServerAddressTests.cs new file mode 100644 index 00000000..1d28c92c --- /dev/null +++ b/tests/Titano.App.Tests/Uploader/ServerAddressTests.cs @@ -0,0 +1,25 @@ +using Titano.Testing; +using Titano.Uploader.Server; + +namespace Titano.App.Tests.Uploader; + +public sealed class ServerAddressTests +{ + [Theory] + [Case("nas.local:8443", "https://nas.local:8443/")] + [Case("https://nas.local:8443", "https://nas.local:8443/")] + [Case(" http://192.168.1.20:8080/titano ", "http://192.168.1.20:8080/titano/")] + [Case("https://nas.local/?x=1#y", "https://nas.local/")] + public void ServerAddressesBecomeApiBases(string typed, string expected) + { + Assert.True(ServerAddress.TryParse(typed, out var uri)); + Assert.Equal(expected, uri.ToString()); + } + + [Theory] + [Case("")] + [Case(" ")] + [Case("ftp://nas.local")] + [Case("https://")] + public void InvalidServerAddressesAreRejected(string typed) => Assert.False(ServerAddress.TryParse(typed, out _)); +}