From ad5c3e0f3781a0861301f4494c94fa504229fd80 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:27:36 +0000 Subject: [PATCH] feat(uploader): settings, DPAPI token, single instance and startup registration uploader.json (server, user, DPAPI CurrentUser-protected token, trusted fingerprints, options, watch folders) written atomically; command line (paths, --tray, --capture); named mutex plus a current-user named pipe that hands a second launch's paths to the running instance; HKCU Run key for "Start with Windows"; coalescing background writer for state files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Infrastructure/CoalescingWriter.cs | 62 +++++++++++ .../Infrastructure/CommandLine.cs | 27 +++++ .../Infrastructure/SingleInstance.cs | 100 ++++++++++++++++++ .../Infrastructure/StartupRegistration.cs | 61 +++++++++++ .../Infrastructure/TokenProtector.cs | 98 +++++++++++++++++ .../Infrastructure/UploaderEnvironment.cs | 37 +++++++ .../Infrastructure/UploaderSettings.cs | 77 ++++++++++++++ .../Uploader/CoalescingWriterTests.cs | 18 ++++ .../Uploader/CommandLineTests.cs | 33 ++++++ .../Uploader/TokenProtectorTests.cs | 27 +++++ 10 files changed, 540 insertions(+) create mode 100644 src/Titano.Uploader/Infrastructure/CoalescingWriter.cs create mode 100644 src/Titano.Uploader/Infrastructure/CommandLine.cs create mode 100644 src/Titano.Uploader/Infrastructure/SingleInstance.cs create mode 100644 src/Titano.Uploader/Infrastructure/StartupRegistration.cs create mode 100644 src/Titano.Uploader/Infrastructure/TokenProtector.cs create mode 100644 src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs create mode 100644 src/Titano.Uploader/Infrastructure/UploaderSettings.cs create mode 100644 tests/Titano.App.Tests/Uploader/CoalescingWriterTests.cs create mode 100644 tests/Titano.App.Tests/Uploader/CommandLineTests.cs create mode 100644 tests/Titano.App.Tests/Uploader/TokenProtectorTests.cs diff --git a/src/Titano.Uploader/Infrastructure/CoalescingWriter.cs b/src/Titano.Uploader/Infrastructure/CoalescingWriter.cs new file mode 100644 index 00000000..31f0cdcc --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/CoalescingWriter.cs @@ -0,0 +1,62 @@ +using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.IO; + +namespace Titano.Uploader.Infrastructure; + +/// +/// Writes state files off the UI thread with . Only the newest content of each file is kept +/// while a write is in progress, so a slow disk never writes an older snapshot after a newer one. +/// +public sealed class CoalescingWriter +{ + private readonly Lock _gate = new(); + private readonly Dictionary _pending = new(StringComparer.OrdinalIgnoreCase); + private Task _worker = Task.CompletedTask; + private bool _running; + + public void Write(string path, byte[] content) + { + lock (_gate) + { + _pending[path] = content; + if (_running) return; + _running = true; + _worker = Task.Run(Drain); + } + } + + /// Waits for pending writes (at exit). + public void Flush(TimeSpan timeout) + { + Task worker; + lock (_gate) worker = _worker; + if (!worker.Wait(timeout)) Log.Warning("persist", "State files still being written at exit"); + } + + private void Drain() + { + while (true) + { + KeyValuePair next; + lock (_gate) + { + if (_pending.Count == 0) + { + _running = false; + return; + } + next = _pending.First(); + _pending.Remove(next.Key); + } + try + { + AtomicFile.WriteAllBytes(next.Key, next.Value); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("persist", $"{next.Key} not written", ex); + } + } + } +} diff --git a/src/Titano.Uploader/Infrastructure/CommandLine.cs b/src/Titano.Uploader/Infrastructure/CommandLine.cs new file mode 100644 index 00000000..f7df7dc0 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/CommandLine.cs @@ -0,0 +1,27 @@ +namespace Titano.Uploader.Infrastructure; + +/// +/// Titano.Uploader.exe [--tray] [--capture <dir>] [files or folders…]: paths are enqueued, --tray +/// starts hidden (used by the Run key), --capture renders screenshots and exits. +/// +public sealed record CommandLine(IReadOnlyList Paths, bool StartInTray, string? CaptureDirectory) +{ + public const string TrayOption = "--tray"; + public const string CaptureOption = "--capture"; + + public static CommandLine Parse(IReadOnlyList args) + { + var paths = new List(); + var tray = false; + string? capture = null; + for (var i = 0; i < args.Count; i++) + { + var a = args[i]; + if (a.Equals(TrayOption, StringComparison.OrdinalIgnoreCase)) tray = true; + else if (a.Equals(CaptureOption, StringComparison.OrdinalIgnoreCase)) + capture = i + 1 < args.Count && !args[i + 1].StartsWith("--", StringComparison.Ordinal) ? args[++i] : "screenshots"; + else if (!a.StartsWith("--", StringComparison.Ordinal) && a.Length > 0) paths.Add(a); + } + return new CommandLine(paths, tray, capture); + } +} diff --git a/src/Titano.Uploader/Infrastructure/SingleInstance.cs b/src/Titano.Uploader/Infrastructure/SingleInstance.cs new file mode 100644 index 00000000..cc39c03c --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/SingleInstance.cs @@ -0,0 +1,100 @@ +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Text; +using Titano.Core.Diagnostics; + +namespace Titano.Uploader.Infrastructure; + +/// +/// One uploader per Windows session: a named mutex marks the running instance, and a second launch hands its +/// file arguments over a named pipe (current user only) before exiting. +/// +public sealed class SingleInstance : IDisposable +{ + private const string MutexName = @"Local\Titano.Uploader"; + private const string Header = "TITANO-UPLOADER/1"; + private const int MaxMessageBytes = 1 << 20; + + private readonly Mutex _mutex; + private readonly CancellationTokenSource _stop = new(); + + private SingleInstance(Mutex mutex) => _mutex = mutex; + + private static string PipeName => $"Titano.Uploader.{Process.GetCurrentProcess().SessionId}.{Environment.UserName}"; + + /// The instance guard, or null when another uploader already runs in this session. + public static SingleInstance? TryAcquire() + { + var mutex = new Mutex(initiallyOwned: true, MutexName, out var createdNew); + if (createdNew) return new SingleInstance(mutex); + mutex.Dispose(); + return null; + } + + /// Sends (absolute paths; empty = just show the window) to the running instance. + public static bool TrySend(IReadOnlyList args) + { + try + { + using var pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.CurrentUserOnly); + pipe.Connect(3000); + pipe.Write(Encode(args)); + pipe.Flush(); + return true; + } + catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException) + { + Log.Warning("instance", "Could not reach the running uploader", ex); + return false; + } + } + + /// Receives messages from later launches; runs on a pool thread. + public void Listen(Action> received) => _ = ListenAsync(received, _stop.Token); + + public void Dispose() + { + _stop.Cancel(); + _mutex.ReleaseMutex(); + _mutex.Dispose(); + _stop.Dispose(); + } + + /// UTF-8: a header line, then one argument per line (paths cannot contain line breaks). + public static byte[] Encode(IReadOnlyList args) => + Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal)))); + + /// Arguments of a message, or null when it is not one of ours. + public static IReadOnlyList? Decode(ReadOnlySpan message) + { + if (message.Length > MaxMessageBytes) return null; + var lines = Encoding.UTF8.GetString(message).Split('\n'); + if (lines[0] != Header) return null; + return [.. lines.Skip(1).Where(l => l.Length > 0)]; + } + + private static async Task ListenAsync(Action> received, CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + await using var pipe = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false); + using var buffer = new MemoryStream(); + await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false); + if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args); + } + catch (OperationCanceledException) + { + return; + } + catch (IOException ex) + { + Log.Warning("instance", "Hand-over pipe failed; listening again", ex); + } + } + } +} diff --git a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs new file mode 100644 index 00000000..0953ab73 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs @@ -0,0 +1,61 @@ +using System.Security; +using Microsoft.Win32; +using Titano.Core.Diagnostics; + +namespace Titano.Uploader.Infrastructure; + +/// "Start with Windows". +public interface IStartupRegistration +{ + bool IsEnabled { get; } + + void SetEnabled(bool enabled); +} + +/// +/// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts the uploader in the tray at sign-in. +/// The registry stays the source of truth because Task Manager can turn it off. +/// +public sealed class RunKeyStartupRegistration : IStartupRegistration +{ + private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + private const string ValueName = "Titano Uploader"; + + public bool IsEnabled + { + get + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(RunKey); + return key?.GetValue(ValueName) is string { Length: > 0 }; + } + catch (SecurityException) + { + return false; + } + } + } + + private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}"; + + public void SetEnabled(bool enabled) + { + try + { + using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true); + if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); + else key.DeleteValue(ValueName, throwOnMissingValue: false); + } + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException) + { + Log.Warning("startup", "Run key not updated", ex); + } + } + + /// Points an existing entry at the current executable (after an update moved it). + public void Refresh() + { + if (IsEnabled) SetEnabled(true); + } +} diff --git a/src/Titano.Uploader/Infrastructure/TokenProtector.cs b/src/Titano.Uploader/Infrastructure/TokenProtector.cs new file mode 100644 index 00000000..d7e9d7b8 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/TokenProtector.cs @@ -0,0 +1,98 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Uploader.Infrastructure; + +/// +/// Encrypts the sign-in token for the current Windows user with DPAPI (CryptProtectData, no machine scope), +/// so uploader.json copied to another account or PC cannot be used. +/// +public static partial class TokenProtector +{ + private const int CryptProtectUiForbidden = 0x1; + + // Ties the blob to this program; other DPAPI consumers of the same user cannot unwrap it by accident. + private static readonly byte[] Entropy = "Titano.Uploader.Token.v1"u8.ToArray(); + + /// Base64 DPAPI blob of . + public static string Protect(string token) + { + var plain = Encoding.UTF8.GetBytes(token); + try + { + return Convert.ToBase64String(Transform(plain, protect: true)); + } + finally + { + CryptographicOperations.ZeroMemory(plain); + } + } + + /// The token, or null when the blob is corrupt or belongs to another user. + public static string? Unprotect(string protectedToken) + { + byte[] blob; + try + { + blob = Convert.FromBase64String(protectedToken); + } + catch (FormatException) + { + return null; + } + try + { + var plain = Transform(blob, protect: false); + var token = Encoding.UTF8.GetString(plain); + CryptographicOperations.ZeroMemory(plain); + return token; + } + catch (CryptographicException) + { + return null; + } + } + + private static unsafe byte[] Transform(byte[] input, bool protect) + { + fixed (byte* inPtr = input) + fixed (byte* entropyPtr = Entropy) + { + var source = new DataBlob { Size = input.Length, Data = (IntPtr)inPtr }; + var entropy = new DataBlob { Size = Entropy.Length, Data = (IntPtr)entropyPtr }; + var ok = protect + ? CryptProtectData(source, null, entropy, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out var output) + : CryptUnprotectData(source, IntPtr.Zero, entropy, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out output); + if (!ok) throw new CryptographicException(Marshal.GetLastPInvokeError()); + try + { + var result = new byte[output.Size]; + Marshal.Copy(output.Data, result, 0, output.Size); + return result; + } + finally + { + LocalFree(output.Data); + } + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public int Size; + public IntPtr Data; + } + + [LibraryImport("crypt32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptProtectData(in DataBlob dataIn, string? description, in DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, out DataBlob dataOut); + + [LibraryImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptUnprotectData(in DataBlob dataIn, IntPtr description, in DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, out DataBlob dataOut); + + [LibraryImport("kernel32.dll")] + private static partial IntPtr LocalFree(IntPtr memory); +} diff --git a/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs b/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs new file mode 100644 index 00000000..993a0fdb --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs @@ -0,0 +1,37 @@ +using System.IO; + +namespace Titano.Uploader.Infrastructure; + +/// +/// Where the uploader keeps its files: %LOCALAPPDATA%\Titano (shared with the client), or .\data next +/// to the executable when portable.txt exists — the same rule as the desktop client. +/// +public sealed class UploaderEnvironment +{ + private UploaderEnvironment(string dataDirectory) + { + DataDirectory = dataDirectory; + Directory.CreateDirectory(DataDirectory); + Directory.CreateDirectory(LogDirectory); + } + + public string DataDirectory { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); + + /// Settings, DPAPI-protected token and trusted certificate fingerprints. + public string SettingsPath => Path.Combine(DataDirectory, "uploader.json"); + + /// The persisted upload queue. + public string QueuePath => Path.Combine(DataDirectory, "uploader-queue.json"); + + /// Files of watch folders the server already confirmed. + public string WatchMemoryPath => Path.Combine(DataDirectory, "uploader-watch.json"); + + public static UploaderEnvironment Detect() + { + var exeDir = AppContext.BaseDirectory; + if (File.Exists(Path.Combine(exeDir, "portable.txt"))) return new UploaderEnvironment(Path.Combine(exeDir, "data")); + var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return new UploaderEnvironment(Path.Combine(local, "Titano")); + } +} diff --git a/src/Titano.Uploader/Infrastructure/UploaderSettings.cs b/src/Titano.Uploader/Infrastructure/UploaderSettings.cs new file mode 100644 index 00000000..d1bc3394 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/UploaderSettings.cs @@ -0,0 +1,77 @@ +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Diagnostics; +using Titano.Core.IO; +using Titano.Ui.Theming; +using Titano.Uploader.Uploads; + +namespace Titano.Uploader.Infrastructure; + +/// +/// uploader.json. The bearer token is stored only DPAPI-protected for the current Windows user +/// (); "Start with Windows" lives in the registry, which stays the source of truth. +/// +public sealed class UploaderSettings +{ + public string? ServerUrl { get; set; } + public string? Username { get; set; } + + /// Base64 of the DPAPI (CurrentUser) blob of the bearer token. + public string? ProtectedToken { get; set; } + + /// SHA-256 fingerprints (XX:XX:…) of self-signed certificates the user trusted (TOFU). + public List TrustedFingerprints { get; set; } = []; + + /// Upload limit in MB/s (decimal megabytes); 0 = unlimited. + public int BandwidthLimit { get; set; } + + public bool MinimizeToTray { get; set; } = true; + public bool DeleteAfterUpload { get; set; } + public UploadTargetMode Target { get; set; } = UploadTargetMode.Sessions; + public Guid? TargetSequenceId { get; set; } + public string? NewSequenceTitle { get; set; } + public List WatchFolders { get; set; } = []; + public string? Language { get; set; } + public AppTheme Theme { get; set; } = AppTheme.Dark; + public WindowPlacement? Window { get; set; } + + public sealed class WatchFolderSettings + { + public string Path { get; set; } = string.Empty; + public int IntervalSeconds { get; set; } = 60; + } + + public sealed class WindowPlacement + { + public double Left { get; set; } + public double Top { get; set; } + public double Width { get; set; } + public double Height { get; set; } + } + + public static UploaderSettings Load(string path) + { + try + { + if (File.Exists(path)) + return JsonSerializer.Deserialize(File.ReadAllBytes(path), UploaderSettingsJson.Default.UploaderSettings) ?? new UploaderSettings(); + } + catch (JsonException ex) + { + // A corrupt settings file must never block startup; defaults apply. + Log.Warning("settings", "uploader.json unreadable; using defaults", ex); + } + catch (IOException ex) + { + Log.Warning("settings", "uploader.json unreadable; using defaults", ex); + } + return new UploaderSettings(); + } + + public void Save(string path) => AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, UploaderSettingsJson.Default.UploaderSettings)); +} + +[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)] +[JsonSerializable(typeof(UploaderSettings))] +internal sealed partial class UploaderSettingsJson : JsonSerializerContext; diff --git a/tests/Titano.App.Tests/Uploader/CoalescingWriterTests.cs b/tests/Titano.App.Tests/Uploader/CoalescingWriterTests.cs new file mode 100644 index 00000000..cf616673 --- /dev/null +++ b/tests/Titano.App.Tests/Uploader/CoalescingWriterTests.cs @@ -0,0 +1,18 @@ +using System.IO; +using Titano.Testing; +using Titano.Uploader.Infrastructure; + +namespace Titano.App.Tests.Uploader; + +public sealed class CoalescingWriterTests(TestContext context) +{ + [Test] + public void KeepsTheNewestContent() + { + var path = Path.Combine(context.CreateTempDirectory(), "uploader-queue.json"); + var writer = new CoalescingWriter(); + for (var i = 0; i < 50; i++) writer.Write(path, [(byte)i]); + writer.Flush(TimeSpan.FromSeconds(10)); + Assert.SequenceEqual([(byte)49], File.ReadAllBytes(path)); + } +} diff --git a/tests/Titano.App.Tests/Uploader/CommandLineTests.cs b/tests/Titano.App.Tests/Uploader/CommandLineTests.cs new file mode 100644 index 00000000..52d381de --- /dev/null +++ b/tests/Titano.App.Tests/Uploader/CommandLineTests.cs @@ -0,0 +1,33 @@ +using Titano.Testing; +using Titano.Uploader.Infrastructure; + +namespace Titano.App.Tests.Uploader; + +public sealed class CommandLineTests +{ + [Test] + public void PathsAndOptionsAreSeparated() + { + var c = CommandLine.Parse([@"E:\", "--tray", @"D:\Cam\IMG_0001.CR2"]); + Assert.SequenceEqual([@"E:\", @"D:\Cam\IMG_0001.CR2"], c.Paths); + Assert.True(c.StartInTray); + Assert.Null(c.CaptureDirectory); + } + + [Test] + public void CaptureTakesAnOptionalDirectory() + { + Assert.Equal("out/shots", CommandLine.Parse(["--capture", "out/shots"]).CaptureDirectory); + Assert.Equal("screenshots", CommandLine.Parse(["--capture"]).CaptureDirectory); + Assert.Equal("screenshots", CommandLine.Parse(["--capture", "--tray"]).CaptureDirectory); + } + + [Test] + public void HandOverMessageRoundTrips() + { + string[] args = [@"E:\", @"\\garage-pi\cam\IMG 1.jpg"]; + Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!); + Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!); + Assert.Null(SingleInstance.Decode("hello\nE:\\"u8)); + } +} diff --git a/tests/Titano.App.Tests/Uploader/TokenProtectorTests.cs b/tests/Titano.App.Tests/Uploader/TokenProtectorTests.cs new file mode 100644 index 00000000..0c928070 --- /dev/null +++ b/tests/Titano.App.Tests/Uploader/TokenProtectorTests.cs @@ -0,0 +1,27 @@ +using Titano.Testing; +using Titano.Uploader.Infrastructure; + +namespace Titano.App.Tests.Uploader; + +public sealed class TokenProtectorTests +{ + [Test] + [WindowsOnly] + public void TokenRoundTripsThroughDpapiWithoutPlainText() + { + const string token = "ttn_4f9a1c2e7b"; + var blob = TokenProtector.Protect(token); + Assert.False(blob.Contains(token, StringComparison.Ordinal)); + Assert.Equal(token, TokenProtector.Unprotect(blob)); + } + + [Test] + [WindowsOnly] + public void DamagedBlobsGiveNoToken() + { + var blob = Convert.FromBase64String(TokenProtector.Protect("secret")); + blob[^1] ^= 0xFF; + Assert.Null(TokenProtector.Unprotect(Convert.ToBase64String(blob))); + Assert.Null(TokenProtector.Unprotect("not base64!")); + } +}