- 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
113 lines
6.3 KiB
C#
113 lines
6.3 KiB
C#
using System.Text;
|
|
using Titano.Core.Model;
|
|
using Titano.Data;
|
|
using Titano.Protocol;
|
|
using Titano.Server.Configuration;
|
|
using Titano.Server.Jobs;
|
|
using Titano.Server.Security;
|
|
using Titano.Server.Storage;
|
|
|
|
namespace Titano.Server.Api;
|
|
|
|
/// <summary>Administration (BRIEF §14.8): dashboard figures, server settings, log tail and downloads, audit log.</summary>
|
|
public static class AdminEndpoints
|
|
{
|
|
private const int MaxTailLines = 2000;
|
|
private const int TailWindowBytes = 1 << 20;
|
|
|
|
public static void Map(RouteGroupBuilder api)
|
|
{
|
|
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
|
|
api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto))
|
|
.Requires(Permissions.ManageArchive);
|
|
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
|
|
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
|
|
|
|
var logs = api.MapGroup("/logs").Requires(Permissions.ManageArchive);
|
|
logs.MapGet("", TailAsync);
|
|
logs.MapGet("/files", (ServerOptions options) => Results.Json(LogFiles(options).Select(f => new LogFileDto(f.Name, f.Length, f.LastWriteTimeUtc)).ToList(),
|
|
ProtocolJson.Default.ListLogFileDto));
|
|
logs.MapGet("/files/{name}", (HttpContext context, string name, ServerOptions options) =>
|
|
{
|
|
// Only names of existing log files are served: the name never becomes part of a path.
|
|
if (LogFiles(options).FirstOrDefault(f => f.Name == name) is not { } file) return ApiErrors.NotFound(context, "log");
|
|
context.Response.Headers.CacheControl = "no-store";
|
|
return Results.File(file.FullName, "text/plain; charset=utf-8", file.Name, file.LastWriteTimeUtc, enableRangeProcessing: true);
|
|
});
|
|
}
|
|
|
|
private static async Task<IResult> DashboardAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, ServerOptions options, ServerState state,
|
|
JobEngineHost jobs, TimeProvider time)
|
|
{
|
|
var ct = context.RequestAborted;
|
|
var now = time.GetUtcNow();
|
|
var today = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
|
|
var users = await db.Users.ListAsync(ct);
|
|
var names = users.ToDictionary(u => u.Id, u => u.Username);
|
|
var counts = await db.Jobs.CountAsync(today, ct);
|
|
var running = await db.Jobs.ListAsync(JobState.Running, null, 10, null, ct);
|
|
var queued = await db.Jobs.ListAsync(JobState.Queued, null, 10, null, ct);
|
|
var nodes = await db.RenderNodes.ListAsync(ct);
|
|
var uploads = await db.Uploads.CommittedPerDayAsync(today.AddDays(-29), ct);
|
|
var activity = await db.Audit.ListAsync(null, null, 12, null, ct);
|
|
return Results.Json(new DashboardDto(
|
|
options.ServerName,
|
|
SystemEndpoints.Version,
|
|
(long)(now - state.StartedAt).TotalSeconds,
|
|
state.Database,
|
|
options.TlsMode.ToString().ToLowerInvariant(),
|
|
options.Discovery,
|
|
users.Count,
|
|
await ArchiveEndpoints.StatsAsync(db, archive, ct),
|
|
new JobCountsDto(counts.Queued, counts.Running, counts.Paused, counts.DoneSince, counts.FailedSince),
|
|
jobs.Workers,
|
|
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
|
|
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
|
|
[.. activity.Items.Select(Dto.Audit)],
|
|
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]),
|
|
ProtocolJson.Default.DashboardDto);
|
|
}
|
|
|
|
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
|
|
{
|
|
switch (store.Save(request))
|
|
{
|
|
case ("setting_locked", var setting):
|
|
return ApiErrors.Conflict(context, "setting_locked", setting);
|
|
case (var code, var setting):
|
|
return ApiErrors.BadRequest(context, code, setting, setting);
|
|
}
|
|
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
|
return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto);
|
|
}
|
|
|
|
private static async Task<IResult> AuditAsync(HttpContext context, TitanoDatabase db, Guid? user, string? action, string? cursor, int? limit)
|
|
{
|
|
var page = await db.Audit.ListAsync(user, string.IsNullOrWhiteSpace(action) ? null : action, limit ?? 100,
|
|
string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
|
|
return Results.Json(new Page<AuditEntryDto>([.. page.Items.Select(Dto.Audit)], page.NextCursor, null), ProtocolJson.Default.PageAuditEntryDto);
|
|
}
|
|
|
|
/// <summary>The last <c>lines</c> lines (default 300) of the newest server log.</summary>
|
|
private static async Task<IResult> TailAsync(HttpContext context, ServerOptions options, int? lines)
|
|
{
|
|
var take = Math.Clamp(lines ?? 300, 1, MaxTailLines);
|
|
if (LogFiles(options).FirstOrDefault() is not { } file) return Results.Json(new LogTailDto(string.Empty, []), ProtocolJson.Default.LogTailDto);
|
|
await using var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
|
var start = Math.Max(0, stream.Length - TailWindowBytes);
|
|
stream.Position = start;
|
|
using var reader = new StreamReader(stream, Encoding.UTF8);
|
|
var text = await reader.ReadToEndAsync(context.RequestAborted);
|
|
var all = text.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
|
// A window that starts mid-file begins with a partial line.
|
|
var complete = start > 0 && all.Length > 0 ? all[1..] : all;
|
|
return Results.Json(new LogTailDto(file.Name, [.. complete.TakeLast(take).Select(l => l.TrimEnd('\r'))]), ProtocolJson.Default.LogTailDto);
|
|
}
|
|
|
|
/// <summary>Server log files, newest first.</summary>
|
|
private static List<FileInfo> LogFiles(ServerOptions options) =>
|
|
Directory.Exists(options.LogPath)
|
|
? [.. new DirectoryInfo(options.LogPath).EnumerateFiles("*.log").OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name)]
|
|
: [];
|
|
}
|