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:
56 files changed
+4726
-108
No files matched your search
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Data;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
@@ -23,15 +25,44 @@ public enum DatabaseKind
|
||||
|
||||
/// <summary>
|
||||
/// Server configuration (BRIEF §14.9): environment variables override <c>/data/server.json</c>, which overrides defaults.
|
||||
/// Settings applied from the environment are listed in <see cref="Locked"/>; the admin panel cannot change them.
|
||||
/// </summary>
|
||||
public sealed class ServerOptions
|
||||
{
|
||||
/// <summary>Environment variable → setting it fixes, and how its text is applied.</summary>
|
||||
private static readonly (string Variable, string Setting, Action<ServerOptions, string> Apply)[] Variables =
|
||||
[
|
||||
("TITANO_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v),
|
||||
("TITANO_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v),
|
||||
("TITANO_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v),
|
||||
("TITANO_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v),
|
||||
("TITANO_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)),
|
||||
("TITANO_DB_HOST", nameof(DbHost), (o, v) => o.DbHost = v),
|
||||
("TITANO_DB_PORT", nameof(DbPort), (o, v) => o.DbPort = Int("TITANO_DB_PORT", v)),
|
||||
("TITANO_DB_NAME", nameof(DbName), (o, v) => o.DbName = v),
|
||||
("TITANO_DB_USER", nameof(DbUser), (o, v) => o.DbUser = v),
|
||||
("TITANO_DB_PASSWORD", nameof(DbPassword), (o, v) => o.DbPassword = v),
|
||||
("TITANO_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v),
|
||||
("TITANO_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("TITANO_HTTP_PORT", v)),
|
||||
("TITANO_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("TITANO_HTTPS_PORT", v)),
|
||||
("TITANO_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse<TlsMode>(v, ignoreCase: true)),
|
||||
("TITANO_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v),
|
||||
("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v),
|
||||
("TITANO_LANG", nameof(Language), (o, v) => o.Language = v),
|
||||
("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))),
|
||||
("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
];
|
||||
|
||||
public string ServerName { get; set; } = "Titano Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres;
|
||||
|
||||
/// <summary>Complete connection string (from <c>TITANO_DB</c> when it holds one); overrides the <c>Db*</c> parts.</summary>
|
||||
public string? DbConnectionString { get; set; }
|
||||
|
||||
public string DbHost { get; set; } = "postgres";
|
||||
public int DbPort { get; set; } = 5432;
|
||||
public string DbName { get; set; } = "titano";
|
||||
@@ -51,6 +82,27 @@ public sealed class ServerOptions
|
||||
public int JobHistoryDays { get; set; } = 90;
|
||||
public int TokenLifetimeDays { get; set; } = 30;
|
||||
|
||||
/// <summary>Uploads untouched for this long are abandoned: their partial files are deleted.</summary>
|
||||
public int UploadRetentionHours { get; set; } = 48;
|
||||
|
||||
/// <summary>Sign-in attempts accepted per minute and client address (BRIEF §14.2: 5).</summary>
|
||||
public int LoginAttemptsPerMinute { get; set; } = 5;
|
||||
|
||||
/// <summary>Consecutive failed sign-ins that lock an account name for <see cref="LockoutMinutes"/>.</summary>
|
||||
public int LockoutThreshold { get; set; } = 10;
|
||||
|
||||
public int LockoutMinutes { get; set; } = 15;
|
||||
|
||||
/// <summary>A render node silent for this long is offline and its jobs go back to the queue.</summary>
|
||||
public int NodeTimeoutSeconds { get; set; } = 90;
|
||||
|
||||
/// <summary>Chunk uploads one user may run at the same time; more are answered 429.</summary>
|
||||
public int ConcurrentChunksPerUser { get; set; } = 8;
|
||||
|
||||
/// <summary>Settings fixed by environment variables (names of the properties above).</summary>
|
||||
[JsonIgnore]
|
||||
public IReadOnlyCollection<string> Locked { get; private set; } = [];
|
||||
|
||||
[JsonIgnore]
|
||||
public string LogPath => Path.Combine(DataPath, "logs");
|
||||
|
||||
@@ -60,6 +112,17 @@ public sealed class ServerOptions
|
||||
[JsonIgnore]
|
||||
public string UploadsPath => Path.Combine(DataPath, "uploads");
|
||||
|
||||
[JsonIgnore]
|
||||
public string SettingsFile => Path.Combine(DataPath, "server.json");
|
||||
|
||||
/// <summary>Verified uploads wait here, on the archive volume, until the archive ingest moves them into place.</summary>
|
||||
[JsonIgnore]
|
||||
public string StagingPath => Path.Combine(ArchivePath, ".titano", "staging");
|
||||
|
||||
/// <summary>Deleted sequences are moved here (never erased by the server).</summary>
|
||||
[JsonIgnore]
|
||||
public string TrashPath => Path.Combine(ArchivePath, ".titano", "trash");
|
||||
|
||||
/// <summary>Loads <c>{DataPath}/server.json</c> (if present) then applies <c>TITANO_*</c> environment variables.</summary>
|
||||
public static ServerOptions Load(IReadOnlyDictionary<string, string?>? environment = null)
|
||||
{
|
||||
@@ -82,35 +145,38 @@ public sealed class ServerOptions
|
||||
}
|
||||
options.DataPath = dataPath;
|
||||
|
||||
options.ServerName = Env("TITANO_SERVER_NAME") ?? options.ServerName;
|
||||
options.ArchivePath = Env("TITANO_ARCHIVE_PATH") ?? options.ArchivePath;
|
||||
options.AdminUser = Env("TITANO_ADMIN_USER") ?? options.AdminUser;
|
||||
options.AdminPassword = Env("TITANO_ADMIN_PASSWORD") ?? options.AdminPassword;
|
||||
if (Env("TITANO_DB") is { } db) options.Database = Enum.Parse<DatabaseKind>(db, ignoreCase: true);
|
||||
options.DbHost = Env("TITANO_DB_HOST") ?? options.DbHost;
|
||||
if (Env("TITANO_DB_PORT") is { } port) options.DbPort = int.Parse(port, System.Globalization.CultureInfo.InvariantCulture);
|
||||
options.DbName = Env("TITANO_DB_NAME") ?? options.DbName;
|
||||
options.DbUser = Env("TITANO_DB_USER") ?? options.DbUser;
|
||||
options.DbPassword = Env("TITANO_DB_PASSWORD") ?? options.DbPassword;
|
||||
options.DbSslMode = Env("TITANO_DB_SSLMODE") ?? options.DbSslMode;
|
||||
if (Env("TITANO_HTTP_PORT") is { } http) options.HttpPort = int.Parse(http, System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (Env("TITANO_HTTPS_PORT") is { } https) options.HttpsPort = int.Parse(https, System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (Env("TITANO_TLS_MODE") is { } tls) options.TlsMode = Enum.Parse<TlsMode>(tls, ignoreCase: true);
|
||||
options.TlsCert = Env("TITANO_TLS_CERT") ?? options.TlsCert;
|
||||
options.TlsKey = Env("TITANO_TLS_KEY") ?? options.TlsKey;
|
||||
options.Language = Env("TITANO_LANG") ?? options.Language;
|
||||
if (Env("TITANO_WORKERS") is { } workers) options.Workers = Math.Max(1, int.Parse(workers, System.Globalization.CultureInfo.InvariantCulture));
|
||||
if (Env("TITANO_DISCOVERY") is { } discovery) options.Discovery = bool.Parse(discovery);
|
||||
var locked = new List<string>();
|
||||
foreach (var (variable, setting, apply) in Variables)
|
||||
{
|
||||
if (Env(variable) is not { } value) continue;
|
||||
try
|
||||
{
|
||||
apply(options, value);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or ArgumentException)
|
||||
{
|
||||
throw new InvalidOperationException($"{variable} has an invalid value.", ex);
|
||||
}
|
||||
locked.Add(setting);
|
||||
}
|
||||
options.Locked = locked;
|
||||
options.Validate();
|
||||
return options;
|
||||
}
|
||||
|
||||
private static Dictionary<string, string?> ReadEnvironment()
|
||||
/// <summary>The database to open: <see cref="DbConnectionString"/>, the SQLite file in the data folder, or PostgreSQL from the parts.</summary>
|
||||
public DatabaseOptions ToDatabaseOptions()
|
||||
{
|
||||
// Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins.
|
||||
var result = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value;
|
||||
return result;
|
||||
if (DbConnectionString is { Length: > 0 } cs) return DatabaseOptions.Parse(cs);
|
||||
if (Database == DatabaseKind.Sqlite) return DatabaseOptions.Sqlite(Path.Combine(DataPath, "titano.db"));
|
||||
var builder = new System.Text.StringBuilder()
|
||||
.Append("Host=").Append(Quote(DbHost))
|
||||
.Append(";Port=").Append(DbPort.ToString(CultureInfo.InvariantCulture))
|
||||
.Append(";Database=").Append(Quote(DbName))
|
||||
.Append(";Username=").Append(Quote(DbUser))
|
||||
.Append(";SslMode=").Append(Quote(DbSslMode));
|
||||
if (DbPassword is not null) builder.Append(";Password=").Append(Quote(DbPassword));
|
||||
return DatabaseOptions.Postgres(builder.ToString());
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
@@ -122,6 +188,35 @@ public sealed class ServerOptions
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
|
||||
}
|
||||
|
||||
/// <summary>TITANO_DB is <c>postgres</c>, <c>sqlite</c> or a complete connection string (<c>Host=…</c> / <c>Data Source=…</c>).</summary>
|
||||
private void ApplyDatabase(string value)
|
||||
{
|
||||
if (value.Contains('=', StringComparison.Ordinal))
|
||||
{
|
||||
DbConnectionString = value;
|
||||
Database = DatabaseOptions.Parse(value).Dialect == Dialect.Postgres ? DatabaseKind.Postgres : DatabaseKind.Sqlite;
|
||||
return;
|
||||
}
|
||||
Database = Enum.Parse<DatabaseKind>(value, ignoreCase: true);
|
||||
}
|
||||
|
||||
private static int Int(string variable, string value) =>
|
||||
int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : throw new FormatException($"{variable} must be a number.");
|
||||
|
||||
private static string Quote(string value) => "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'";
|
||||
|
||||
private static Dictionary<string, string?> ReadEnvironment()
|
||||
{
|
||||
// Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins.
|
||||
var result = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user