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

+128 -58
View File
@@ -1,21 +1,37 @@
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Titano.Core.Diagnostics;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Protocol;
using Titano.Server.Api;
using Titano.Server.Configuration;
using Titano.Server.Events;
using Titano.Server.Jobs;
using Titano.Server.Security;
using Titano.Server.Storage;
namespace Titano.Server.Hosting;
/// <summary>Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program and tests).</summary>
/// <summary>
/// Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program, the Windows service
/// host and tests). The archive module plugs in through <paramref name="configureServices"/> of <see cref="Build"/>:
/// it must register <see cref="IArchiveIngest"/> and <see cref="IFrameAssetLocator"/>, and may add
/// <see cref="Titano.Data.Jobs.IJobHandler"/>s; the server refuses to start without the first two.
/// </summary>
public static class ServerHost
{
public static WebApplication Build(ServerOptions options, string[] args)
/// <summary>Request bodies other than upload chunks stay small (BRIEF §14.2 limits).</summary>
public const long JsonBodyLimit = 1024 * 1024;
public static WebApplication Build(ServerOptions options, string[] args, Action<IServiceCollection>? configureServices = null)
{
Directory.CreateDirectory(options.DataPath);
Directory.CreateDirectory(options.LogPath);
Directory.CreateDirectory(options.UploadsPath);
Directory.CreateDirectory(options.ArchivePath);
var builder = WebApplication.CreateSlimBuilder(args);
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
builder.Logging.ClearProviders();
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
@@ -23,26 +39,67 @@ public static class ServerHost
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information);
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true));
var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server"));
var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) };
builder.WebHost.ConfigureKestrel(k =>
var bootLogger = bootLoggerFactory.CreateLogger("Titano.Server");
var certificate = CertificateStore.Load(options, bootLogger);
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
try
{
k.AddServerHeader = false;
k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024;
k.ListenAnyIP(options.HttpPort);
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
var archive = ServerArchive.OpenAsync(database, options, TimeProvider.System, CancellationToken.None).GetAwaiter().GetResult();
AdminBootstrap.RunAsync(database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
var state = new ServerState
{
l.Protocols = HttpProtocols.Http1AndHttp2;
l.UseHttps(certificate);
TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate),
Database = ServerDatabase.DescribeAsync(database, CancellationToken.None).GetAwaiter().GetResult(),
};
builder.WebHost.ConfigureKestrel(k =>
{
k.AddServerHeader = false;
k.Limits.MaxRequestBodySize = JsonBodyLimit;
k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
k.ListenAnyIP(options.HttpPort);
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
{
l.Protocols = HttpProtocols.Http1AndHttp2;
l.UseHttps(certificate);
});
});
});
builder.Services.AddSingleton(options);
builder.Services.AddSingleton(state);
builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
ConfigureServices(builder.Services, options, state, database, archive);
configureServices?.Invoke(builder.Services);
var app = builder.Build();
RequireArchiveModule(app.Services);
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
ConfigurePipeline(app, options);
app.Logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}",
SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode,
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping"));
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
return app;
}
catch
{
database.DisposeAsync().AsTask().GetAwaiter().GetResult();
throw;
}
}
/// <summary>The single composition root of the server's services.</summary>
public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, TitanoDatabase database, ServerArchive archive)
{
services.AddSingleton(options);
services.AddSingleton(state);
services.AddSingleton(database);
services.AddSingleton(archive);
services.AddSingleton(TimeProvider.System);
services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
if (options.TlsMode == TlsMode.Proxy)
{
builder.Services.Configure<ForwardedHeadersOptions>(f =>
services.Configure<ForwardedHeadersOptions>(f =>
{
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
f.KnownIPNetworks.Clear();
@@ -50,49 +107,62 @@ public static class ServerHost
});
}
var app = builder.Build();
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
var logger = app.Logger;
logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode,
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
services.AddSingleton<EventHub>();
services.AddSingleton<TokenService>();
services.AddSingleton<LoginGuard>();
services.AddSingleton<AuditLog>();
services.AddSingleton<ServerSettingsStore>();
services.AddSingleton<UploadStore>();
services.AddSingleton<UploadService>();
services.AddSingleton<RenderStore>();
services.AddSingleton<SequenceJobs>();
services.AddSingleton<RenderNodeService>();
services.AddSingleton<JobEngineHost>();
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
services.AddSingleton<RenderNodeMonitor>();
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
services.AddSingleton<UploadMaintenance>();
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
services.AddSingleton<DiscoveryBeaconService>();
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
}
private static void ConfigurePipeline(WebApplication app, ServerOptions options)
{
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
app.UseMiddleware<ResponseMiddleware>();
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
app.UseRouting();
app.UseMiddleware<AuthenticationMiddleware>();
app.Use(async (context, next) =>
AdminPanel.Map(app, options);
var api = app.MapGroup("/api/v1");
SystemEndpoints.Map(app, api);
AuthEndpoints.Map(api);
UserEndpoints.Map(api);
SequenceEndpoints.Map(api);
FileEndpoints.Map(api);
UploadEndpoints.Map(api);
JobEndpoints.Map(api);
NodeEndpoints.Map(api);
ArchiveEndpoints.Map(api);
AdminEndpoints.Map(api);
EventEndpoints.Map(api);
app.MapFallback("/api/{**path}", (HttpContext context) => ApiErrors.NotFound(context)).AllowAnonymousCaller();
}
/// <summary>Fails fast when the archive module's services are missing (the server would accept uploads it cannot commit).</summary>
private static void RequireArchiveModule(IServiceProvider services)
{
var registry = services.GetRequiredService<IServiceProviderIsService>();
var missing = new List<string>();
if (!registry.IsService(typeof(IArchiveIngest))) missing.Add($"{typeof(IArchiveIngest).FullName} (commits verified uploads into the archive layout)");
if (!registry.IsService(typeof(IFrameAssetLocator))) missing.Add($"{typeof(IFrameAssetLocator).FullName} (finds proxies and thumbnails)");
if (missing.Count > 0)
{
context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
context.Response.Headers.XContentTypeOptions = "nosniff";
context.Response.Headers["Referrer-Policy"] = "no-referrer";
try
{
await next(context);
}
catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException)
{
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError);
}
});
var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/");
app.MapGet("/", () => Results.Redirect("/admin/"));
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
{
// Relative asset URLs need the trailing slash.
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
{
context.Response.Redirect("/admin/");
return;
}
if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
});
SystemEndpoints.Map(app, options, state);
app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404));
app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping"));
return app;
throw new InvalidOperationException(
"Titano Server cannot start: no implementation is registered for " + string.Join(" and ", missing) +
". Register them in the services callback of ServerHost.Build.");
}
}
}