feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events

- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens
  stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/
  SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate
  limit and lockout, role/permission metadata on every endpoint, audit log,
  first-run administrator bootstrap.
- Sequences with keyset paging, ETags and settings_version conflicts; sync
  manifest; frames, proxies, thumbnails and exports streamed with Range.
- Chunked resumable uploads with hash short-circuit, quota and disk checks,
  staging on the archive volume, SHA-256 verification and IArchiveIngest.
- Job engine host, jobs API, render nodes with heartbeat timeout and
  reassignment, WebSocket events, LAN discovery beacon, upload cleanup.
- Windows service host over advapi32 (--service, --install-service,
  --uninstall-service); fails fast without the archive module services.

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 11:32:19 +00:00
1 parent 7353c17d7b
commit c78747053e
56 files changed
+4726 -108

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
using System.Net.WebSockets;
using System.Text.Json;
using Titano.Core.Model;
using Titano.Protocol;
using Titano.Server.Api;
using Titano.Server.Security;
namespace Titano.Server.Events;
/// <summary>
/// <c>WS /api/v1/events</c>: server events as one JSON text message each (<see cref="ServerEvent"/>, discriminated by
/// <c>type</c>). The handshake is authenticated like any API call (bearer header, or the admin cookie from this origin);
/// the token is checked again every minute and the socket closes once it is revoked or expires.
/// </summary>
public static class EventEndpoints
{
private static readonly TimeSpan Revalidate = TimeSpan.FromSeconds(60);
public static void Map(RouteGroupBuilder api) => api.MapGet("/events", RunAsync).Requires(Permissions.Read);
private static async Task<IResult> RunAsync(HttpContext context, Caller caller, EventHub hub, TokenService tokens, IHostApplicationLifetime lifetime)
{
if (!context.WebSockets.IsWebSocketRequest) return ApiErrors.BadRequest(context, "websocket_required");
using var socket = await context.WebSockets.AcceptWebSocketAsync();
using var subscription = hub.Subscribe();
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted, lifetime.ApplicationStopping);
var receiving = ReceiveUntilClosedAsync(socket, stop);
var status = WebSocketCloseStatus.NormalClosure;
try
{
status = await SendAsync(socket, subscription, caller, tokens, stop.Token);
}
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
{
status = lifetime.ApplicationStopping.IsCancellationRequested ? WebSocketCloseStatus.EndpointUnavailable : WebSocketCloseStatus.NormalClosure;
}
finally
{
await stop.CancelAsync();
await receiving;
}
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
await socket.CloseOutputAsync(status, null, timeout.Token);
}
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
{
// The peer is gone.
}
}
return Results.Empty;
}
/// <summary>Forwards events until cancelled; returns the close status when the caller's token stops being valid.</summary>
private static async Task<WebSocketCloseStatus> SendAsync(WebSocket socket, EventHub.Subscription subscription, Caller caller, TokenService tokens,
CancellationToken cancellationToken)
{
while (true)
{
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
wait.CancelAfter(Revalidate);
try
{
while (await subscription.Reader.WaitToReadAsync(wait.Token))
{
while (subscription.Reader.TryRead(out var e))
{
var payload = JsonSerializer.SerializeToUtf8Bytes(e, ProtocolJson.Default.ServerEvent);
await socket.SendAsync(payload, WebSocketMessageType.Text, endOfMessage: true, cancellationToken);
}
}
return WebSocketCloseStatus.NormalClosure;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// Quiet minute: fall through to the token check.
}
}
if (!await tokens.IsStillValidAsync(caller, cancellationToken)) return WebSocketCloseStatus.PolicyViolation;
}
}
private static async Task ReceiveUntilClosedAsync(WebSocket socket, CancellationTokenSource stop)
{
var buffer = new byte[1024];
try
{
while (!stop.IsCancellationRequested)
{
var result = await socket.ReceiveAsync(buffer, stop.Token);
if (result.MessageType == WebSocketMessageType.Close) break;
}
}
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
{
}
await stop.CancelAsync();
}
}
+47
View File
@@ -0,0 +1,47 @@
using System.Threading.Channels;
using Titano.Protocol;
namespace Titano.Server.Events;
/// <summary>
/// Fan-out of server events to WebSocket subscribers (BRIEF §14.3). Each subscriber has a bounded queue that drops
/// its oldest events when it falls behind, so a slow client never holds up the server.
/// </summary>
public sealed class EventHub
{
private const int QueueLength = 512;
private readonly Lock _gate = new();
private Channel<ServerEvent>[] _subscribers = [];
public int SubscriberCount => Volatile.Read(ref _subscribers).Length;
public Subscription Subscribe()
{
var channel = Channel.CreateBounded<ServerEvent>(new BoundedChannelOptions(QueueLength)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
});
lock (_gate) _subscribers = [.. _subscribers, channel];
return new Subscription(this, channel);
}
public void Publish(ServerEvent e)
{
foreach (var subscriber in Volatile.Read(ref _subscribers)) subscriber.Writer.TryWrite(e);
}
private void Remove(Channel<ServerEvent> channel)
{
lock (_gate) _subscribers = [.. _subscribers.Where(c => c != channel)];
channel.Writer.TryComplete();
}
/// <summary>One subscriber's queue; dispose to unsubscribe.</summary>
public sealed class Subscription(EventHub hub, Channel<ServerEvent> channel) : IDisposable
{
public ChannelReader<ServerEvent> Reader => channel.Reader;
public void Dispose() => hub.Remove(channel);
}
}