Files
Chronos/src/Titano.Server/Api/SystemEndpoints.cs
T
Claude c78747053e 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
2026-10-02 11:32:19 +00:00

106 lines
4.4 KiB
C#

using System.Globalization;
using System.Reflection;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Security;
namespace Titano.Server.Api;
/// <summary><c>/health</c>, <c>/api/v1/server/info</c> and <c>/api/v1/i18n/{culture}</c> (all anonymous).</summary>
public static class SystemEndpoints
{
private static readonly string[] AdminAreas = ["Common", "Admin"];
/// <summary>Languages with translated resources (English plus every satellite of the catalog), for the admin language menu.</summary>
private static readonly Lazy<string> AdminLanguages = new(() => string.Join(',', Languages.Shipped.Where(code =>
{
if (code == "en") return true;
try
{
typeof(Loc).Assembly.GetSatelliteAssembly(CultureInfo.GetCultureInfo(code));
return true;
}
catch (FileNotFoundException)
{
return false;
}
})));
public static string Version { get; } =
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
public static void Map(WebApplication app, RouteGroupBuilder api)
{
app.MapGet("/health", HealthAsync);
api.MapGet("/server/info", (ServerOptions options, ServerState state) => Results.Json(new ServerInfo(
options.ServerName,
Version,
ApiVersion.Current,
state.Capabilities,
state.TlsFingerprint,
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength)), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
api.MapGet("/i18n/{culture}", (string culture) =>
{
CultureInfo ci;
try
{
ci = Languages.BestMatch(CultureInfo.GetCultureInfo(culture));
}
catch (CultureNotFoundException)
{
ci = CultureInfo.GetCultureInfo("en");
}
var strings = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var area in AdminAreas)
foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v;
strings["$culture"] = ci.Name;
strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false";
strings["$languages"] = AdminLanguages.Value;
return Results.Json(strings, ProtocolJson.Default.DictionaryStringString);
}).AllowAnonymousCaller();
}
/// <summary>Liveness for the container health check: 503 while the database cannot be reached.</summary>
private static async Task<IResult> HealthAsync(HttpContext context, ServerOptions options, TitanoDatabase db)
{
var checks = new Dictionary<string, string>(StringComparer.Ordinal)
{
["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing",
["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing",
};
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
timeout.CancelAfter(TimeSpan.FromSeconds(3));
try
{
await using var session = await db.Database.OpenAsync(timeout.Token);
await session.ExecuteAsync("SELECT 1", [], timeout.Token);
checks["database"] = "ok";
}
catch (Exception ex) when (ex is DatabaseException or OperationCanceledException or IOException)
{
checks["database"] = "unavailable";
}
var healthy = checks["database"] == "ok";
return Results.Json(new HealthStatus(healthy ? "ok" : "unavailable", Version, checks), ProtocolJson.Default.HealthStatus,
statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
}
}
/// <summary>Process-wide facts computed at startup.</summary>
public sealed class ServerState
{
public string? TlsFingerprint { get; init; }
/// <summary>Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1").</summary>
public string Database { get; init; } = string.Empty;
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"];
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
}