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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:27:36 +00:00
1 parent 27f0d73f05
commit ad5c3e0f37
10 files changed
+540

No files matched your search

@@ -0,0 +1,62 @@
using System.IO;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
namespace Titano.Uploader.Infrastructure;
/// <summary>
/// Writes state files off the UI thread with <see cref="AtomicFile"/>. 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.
/// </summary>
public sealed class CoalescingWriter
{
private readonly Lock _gate = new();
private readonly Dictionary<string, byte[]> _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);
}
}
/// <summary>Waits for pending writes (at exit).</summary>
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<string, byte[]> 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);
}
}
}
}
@@ -0,0 +1,27 @@
namespace Titano.Uploader.Infrastructure;
/// <summary>
/// <c>Titano.Uploader.exe [--tray] [--capture &lt;dir&gt;] [files or folders…]</c>: paths are enqueued, <c>--tray</c>
/// starts hidden (used by the Run key), <c>--capture</c> renders screenshots and exits.
/// </summary>
public sealed record CommandLine(IReadOnlyList<string> Paths, bool StartInTray, string? CaptureDirectory)
{
public const string TrayOption = "--tray";
public const string CaptureOption = "--capture";
public static CommandLine Parse(IReadOnlyList<string> args)
{
var paths = new List<string>();
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);
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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}";
/// <summary>The instance guard, or null when another uploader already runs in this session.</summary>
public static SingleInstance? TryAcquire()
{
var mutex = new Mutex(initiallyOwned: true, MutexName, out var createdNew);
if (createdNew) return new SingleInstance(mutex);
mutex.Dispose();
return null;
}
/// <summary>Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the running instance.</summary>
public static bool TrySend(IReadOnlyList<string> 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;
}
}
/// <summary>Receives messages from later launches; <paramref name="received"/> runs on a pool thread.</summary>
public void Listen(Action<IReadOnlyList<string>> received) => _ = ListenAsync(received, _stop.Token);
public void Dispose()
{
_stop.Cancel();
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
}
/// <summary>UTF-8: a header line, then one argument per line (paths cannot contain line breaks).</summary>
public static byte[] Encode(IReadOnlyList<string> args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// <summary>Arguments of a message, or null when it is not one of ours.</summary>
public static IReadOnlyList<string>? Decode(ReadOnlySpan<byte> 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<IReadOnlyList<string>> 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);
}
}
}
}
@@ -0,0 +1,61 @@
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
namespace Titano.Uploader.Infrastructure;
/// <summary>"Start with Windows".</summary>
public interface IStartupRegistration
{
bool IsEnabled { get; }
void SetEnabled(bool enabled);
}
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> 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.
/// </summary>
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);
}
}
/// <summary>Points an existing entry at the current executable (after an update moved it).</summary>
public void Refresh()
{
if (IsEnabled) SetEnabled(true);
}
}
@@ -0,0 +1,98 @@
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace Titano.Uploader.Infrastructure;
/// <summary>
/// Encrypts the sign-in token for the current Windows user with DPAPI (<c>CryptProtectData</c>, no machine scope),
/// so <c>uploader.json</c> copied to another account or PC cannot be used.
/// </summary>
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();
/// <summary>Base64 DPAPI blob of <paramref name="token"/>.</summary>
public static string Protect(string token)
{
var plain = Encoding.UTF8.GetBytes(token);
try
{
return Convert.ToBase64String(Transform(plain, protect: true));
}
finally
{
CryptographicOperations.ZeroMemory(plain);
}
}
/// <summary>The token, or null when the blob is corrupt or belongs to another user.</summary>
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);
}
@@ -0,0 +1,37 @@
using System.IO;
namespace Titano.Uploader.Infrastructure;
/// <summary>
/// Where the uploader keeps its files: <c>%LOCALAPPDATA%\Titano</c> (shared with the client), or <c>.\data</c> next
/// to the executable when <c>portable.txt</c> exists — the same rule as the desktop client.
/// </summary>
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");
/// <summary>Settings, DPAPI-protected token and trusted certificate fingerprints.</summary>
public string SettingsPath => Path.Combine(DataDirectory, "uploader.json");
/// <summary>The persisted upload queue.</summary>
public string QueuePath => Path.Combine(DataDirectory, "uploader-queue.json");
/// <summary>Files of watch folders the server already confirmed.</summary>
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"));
}
}
@@ -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;
/// <summary>
/// <c>uploader.json</c>. The bearer token is stored only DPAPI-protected for the current Windows user
/// (<see cref="TokenProtector"/>); "Start with Windows" lives in the registry, which stays the source of truth.
/// </summary>
public sealed class UploaderSettings
{
public string? ServerUrl { get; set; }
public string? Username { get; set; }
/// <summary>Base64 of the DPAPI (CurrentUser) blob of the bearer token.</summary>
public string? ProtectedToken { get; set; }
/// <summary>SHA-256 fingerprints (XX:XX:…) of self-signed certificates the user trusted (TOFU).</summary>
public List<string> TrustedFingerprints { get; set; } = [];
/// <summary>Upload limit in MB/s (decimal megabytes); 0 = unlimited.</summary>
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<WatchFolderSettings> 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;
@@ -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));
}
}
@@ -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));
}
}
@@ -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!"));
}
}