refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
using System.Globalization;
using System.Net;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting;
/// <summary>
/// Serves the embedded admin panel at <c>/admin</c>. Requests over plain HTTP from another machine are redirected to
/// the HTTPS listener, on the port clients reach it on (<see cref="ServerOptions.PublicHttpsPort"/> when a container
/// port is published as another host port), because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not
/// survive plain HTTP.
/// </summary>
public static class AdminPanel
{
public static void Map(WebApplication app, ServerOptions options)
{
var files = new EmbeddedStaticFiles(typeof(AdminPanel).Assembly, "admin/");
var server = app.Services.GetRequiredService<IServer>();
app.MapGet("/", () => Results.Redirect("/admin/"));
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
{
if (HttpsLocation(context, options, server) is { } secure)
{
context.Response.Redirect(secure);
return;
}
// Relative asset URLs need the trailing slash.
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
{
context.Response.Redirect("/admin/");
return;
}
if (!await files.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
});
}
/// <summary>
/// True when TLS mode is proxy but this request did not reach the server through a trusted proxy over HTTPS (BRIEF
/// §14.2: the admin warns). The server has no HTTPS listener in that mode, so a request is HTTPS only when a proxy
/// listed in <see cref="ServerOptions.TrustedProxies"/> forwarded it as such.
/// </summary>
public static bool BypassesProxy(HttpContext context, ServerOptions options) =>
options.TlsMode == TlsMode.Proxy && !context.Request.IsHttps;
internal static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
{
if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null;
if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null;
foreach (var address in server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [])
{
if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
var port = options.PublicHttpsPort?.ToString(CultureInfo.InvariantCulture) ?? address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
}
return null;
}
}
@@ -0,0 +1,79 @@
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting;
/// <summary>
/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls
/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy).
/// </summary>
public static class CertificateStore
{
public static X509Certificate2? Load(ServerOptions options, ILogger logger)
{
switch (options.TlsMode)
{
case TlsMode.Proxy:
return null;
case TlsMode.Pem:
{
var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey);
return Exportable(pem);
}
default:
{
Directory.CreateDirectory(options.TlsPath);
var path = Path.Combine(options.TlsPath, "server.pfx");
if (File.Exists(path))
{
var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable);
if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing;
logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter);
}
var created = CreateSelfSigned(options.ServerName);
// The PKCS#12 export carries the private key without a password: only the server's account may read it.
DataFolderAccess.WritePrivateFile(path, created.Export(X509ContentType.Pkcs12));
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
return created;
}
}
}
/// <summary>SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use.</summary>
public static string Fingerprint(X509Certificate2 certificate) =>
string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
public static X509Certificate2 CreateSelfSigned(string serverName)
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Chronos"), key, HashAlgorithmName.SHA256);
var san = new SubjectAlternativeNameBuilder();
san.AddDnsName("localhost");
try
{
var host = Dns.GetHostName();
san.AddDnsName(host);
foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6))
san.AddIpAddress(address);
}
catch (SocketException)
{
// Without name resolution the certificate still covers localhost.
}
san.AddIpAddress(IPAddress.Loopback);
request.CertificateExtensions.Add(san.Build());
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5));
return Exportable(certificate);
}
private static X509Certificate2 Exportable(X509Certificate2 certificate) =>
X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable);
private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray());
}
@@ -0,0 +1,312 @@
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Core.Archiving;
namespace Chronos.Server.Hosting;
/// <summary>
/// Keeps the data folder and its secrets private (BRIEF §14.2): it holds the database, the TLS private key, the
/// temporary admin password and <c>server.json</c>. On Windows the folder sits in <c>%ProgramData%</c>, whose ACL lets
/// every local user read it and create files in it, so it gets a protected DACL (nothing inherited) that allows only
/// SYSTEM, Administrators and the account the server runs as; everything inside inherits that. Those accounts must also
/// own the folder and everything in it, and nothing in it may be a link: an owner can always change the ACL back, and
/// whoever planted a file chose what it says. Elsewhere the container entrypoint owns <c>/data</c>, and secrets are
/// written with mode 0600. An archive folder the server creates on Windows gets the same accounts (see
/// <see cref="PrepareArchive"/>).
/// </summary>
public static class DataFolderAccess
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
private const int GenericAll = 0x10000000;
private const int GenericWrite = 0x40000000;
/// <summary>Rights that let an account replace or alter a file or folder (including the generic forms).</summary>
[SupportedOSPlatform("windows")]
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
/// <summary>
/// Creates the folder if needed and, on Windows, refuses a folder that holds a link or an entry owned by anyone
/// else, then replaces an ACL that grants anyone else access.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Something in the folder is a link or belongs to another account, or the ACL cannot be read or changed (the account
/// is not an administrator).
/// </exception>
public static void Restrict(string folder)
{
if (!OperatingSystem.IsWindows())
{
Directory.CreateDirectory(folder);
return;
}
try
{
RestrictOnWindows(new DirectoryInfo(folder));
}
catch (UnauthorizedAccessException ex)
{
throw new InvalidOperationException(
$"Chronos Server cannot check or restrict access to {folder}: {ex.Message} Run it once as an administrator; if someone else changed the folder's access, delete the folder.", ex);
}
}
/// <summary>
/// Reads a file the server acts on (<c>server.json</c>). On Windows its owner must be SYSTEM, Administrators or the
/// server's account, checked on the handle that is read, so a file another user planted (or swapped in) is refused
/// before any of its settings is used.
/// </summary>
/// <exception cref="InvalidOperationException">The file belongs to another account.</exception>
public static string ReadTrustedText(string path)
{
if (!OperatingSystem.IsWindows()) return File.ReadAllText(path);
return ReadTrustedText(path, AllowedAccounts());
}
/// <summary>Writes a secret that only the server's account (and, on Windows, SYSTEM and Administrators) may read.</summary>
public static void WritePrivateFile(string path, ReadOnlySpan<byte> contents)
{
if (OperatingSystem.IsWindows())
{
WritePrivateFileOnWindows(new FileInfo(path), contents);
return;
}
using (var stream = new FileStream(path, new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write, UnixCreateMode = OwnerOnly }))
stream.Write(contents);
// A file that already existed keeps its old mode otherwise.
File.SetUnixFileMode(path, OwnerOnly);
}
/// <summary>
/// Creates the archive folder when it is missing, and says whether accounts other than SYSTEM, Administrators and the
/// server's own can change it (always false off Windows, where the container entrypoint checks the archive). On
/// Windows a folder created here gets a protected ACL: those accounts change it, other local users may only read it;
/// a <c>.chronos</c> folder (staging, trash) created here is private. Whoever can write where the server moves files
/// can put a link in place of a folder and send the server's writes elsewhere; an existing archive is only reported,
/// because its ACL is its owner's choice.
/// </summary>
public static bool PrepareArchive(string root)
{
if (!OperatingSystem.IsWindows())
{
Directory.CreateDirectory(root);
return false;
}
var folder = new DirectoryInfo(root);
if (!folder.Exists)
{
if (folder.Parent is { } parent) parent.Create();
folder.Create(ArchiveFolderSecurity());
folder.Refresh();
}
// Created before the archive engine would create it with the archive's ACL; an existing one is left as it is.
var meta = new DirectoryInfo(new ArchivePaths(root).MetaDirectory);
if (!meta.Exists) meta.Create(PrivateFolderSecurity());
return OthersCanChange(folder);
}
/// <summary>
/// True when the ACL is protected, its owner is SYSTEM, Administrators or this process's account, and it names no
/// other account.
/// </summary>
[SupportedOSPlatform("windows")]
public static bool IsPrivate(FileSystemSecurity security)
{
if (!security.AreAccessRulesProtected) return false;
var allowed = AllowedAccounts();
if (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !allowed.Contains(owner)) return false;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains((SecurityIdentifier)rule.IdentityReference)) return false;
}
return true;
}
/// <summary>
/// The first problem with <paramref name="folder"/> or anything inside it, as a sentence for the operator, or null:
/// a link (it would carry what the server reads, writes and secures elsewhere) or an owner outside
/// <paramref name="owners"/> (who may have written the contents and can always change the ACL back). Links are
/// reported, never followed.
/// </summary>
[SupportedOSPlatform("windows")]
internal static string? FindUntrusted(DirectoryInfo folder, IReadOnlySet<SecurityIdentifier> owners)
{
var everything = new EnumerationOptions { AttributesToSkip = 0, IgnoreInaccessible = false };
var pending = new Stack<DirectoryInfo>();
pending.Push(folder);
while (pending.TryPop(out var directory))
{
if (Untrusted(directory, owners) is { } problem) return problem;
foreach (var entry in directory.EnumerateFileSystemInfos("*", everything))
{
if (entry is DirectoryInfo child && !IsLink(child)) pending.Push(child);
else if (Untrusted(entry, owners) is { } entryProblem) return entryProblem;
}
}
return null;
}
/// <inheritdoc cref="ReadTrustedText(string)"/>
[SupportedOSPlatform("windows")]
internal static string ReadTrustedText(string path, IReadOnlySet<SecurityIdentifier> owners)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
if (UntrustedOwner(path, stream.GetAccessControl(), owners) is { } problem) throw new InvalidOperationException(problem);
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
/// <summary>
/// True when the owner is outside <paramref name="trusted"/> or an allow entry gives change rights to such an
/// account. Entries that only pass to children count too, since new files would inherit them; CREATOR OWNER and
/// CREATOR GROUP stand for whoever creates a child, which already takes change rights on the folder.
/// </summary>
[SupportedOSPlatform("windows")]
internal static bool IsChangeableByOthers(FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> trusted, bool checkOwner)
{
if (checkOwner && (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !trusted.Contains(owner))) return true;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType != AccessControlType.Allow || (rule.FileSystemRights & ChangeRights) == 0) continue;
var account = (SecurityIdentifier)rule.IdentityReference;
if (trusted.Contains(account) || account.IsWellKnown(WellKnownSidType.CreatorOwnerSid) || account.IsWellKnown(WellKnownSidType.CreatorGroupSid)) continue;
return true;
}
return false;
}
/// <summary>SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).</summary>
[SupportedOSPlatform("windows")]
internal static HashSet<SecurityIdentifier> AllowedAccounts()
{
using var identity = WindowsIdentity.GetCurrent();
var accounts = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
};
if (identity.User is { } user) accounts.Add(user);
return accounts;
}
[SupportedOSPlatform("windows")]
private static void RestrictOnWindows(DirectoryInfo folder)
{
if (!folder.Exists)
{
if (folder.Parent is { } parent) parent.Create();
folder.Create(PrivateFolderSecurity());
folder.Refresh();
}
// Before the ACL is touched: a folder another user created in advance, or a file planted in an older version's
// folder, stays theirs whatever the ACL says, and a link would carry the new ACL elsewhere.
if (FindUntrusted(folder, AllowedAccounts()) is { } problem) throw new InvalidOperationException(problem);
// An older version, or Windows' default inheritance from %ProgramData%, left the folder readable by every user.
// Setting the DACL by name also replaces what the files inside inherited.
if (!IsPrivate(folder.GetAccessControl())) folder.SetAccessControl(PrivateFolderSecurity());
}
[SupportedOSPlatform("windows")]
private static string? Untrusted(FileSystemInfo entry, IReadOnlySet<SecurityIdentifier> owners)
{
if (IsLink(entry))
{
return $"{entry.FullName} is a link to {entry.LinkTarget}, and Chronos Server follows no links in its data folder. "
+ "Delete the link (CHRONOS_DATA_PATH moves the data folder) and start the server again.";
}
FileSystemSecurity security = entry is DirectoryInfo directory
? directory.GetAccessControl(AccessControlSections.Owner)
: ((FileInfo)entry).GetAccessControl(AccessControlSections.Owner);
return UntrustedOwner(entry.FullName, security, owners);
}
[SupportedOSPlatform("windows")]
private static string? UntrustedOwner(string path, FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> owners)
{
var owner = security.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
if (owner is not null && owners.Contains(owner)) return null;
return $"{path} belongs to {(owner is null ? "no account" : AccountName(owner))}, not to SYSTEM, Administrators or the account Chronos Server "
+ "runs as, so it cannot be trusted. Check it, then delete it or make Administrators its owner, and start the server again.";
}
/// <summary>A symbolic link or junction (other reparse points, such as deduplicated files, are ordinary files).</summary>
private static bool IsLink(FileSystemInfo entry) => (entry.Attributes & FileAttributes.ReparsePoint) != 0 && entry.LinkTarget is not null;
[SupportedOSPlatform("windows")]
private static string AccountName(SecurityIdentifier account)
{
try
{
return account.Translate(typeof(NTAccount)).Value;
}
catch (IdentityNotMappedException)
{
return account.Value;
}
}
[SupportedOSPlatform("windows")]
private static bool OthersCanChange(DirectoryInfo folder)
{
try
{
return IsChangeableByOthers(folder.GetAccessControl(), AllowedAccounts(), checkOwner: true);
}
catch (NotSupportedException)
{
// A volume without ACLs (FAT, exFAT): everyone can change everything.
return true;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or IOException or InvalidOperationException)
{
// The ACL cannot be read (some network shares); the warning would be a guess.
return false;
}
}
[SupportedOSPlatform("windows")]
private static void WritePrivateFileOnWindows(FileInfo file, ReadOnlySpan<byte> contents)
{
// A file that already exists is replaced, never rewritten in place: it would keep its owner, who could change its
// ACL back at any time, and a link would carry the secret elsewhere. The new file is owned by this account.
file.Delete();
using var stream = file.Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, PrivateFileSecurity());
stream.Write(contents);
}
/// <summary>A protected DACL that gives the allowed accounts full control, passed on to everything inside.</summary>
[SupportedOSPlatform("windows")]
private static DirectorySecurity PrivateFolderSecurity()
{
var security = new DirectorySecurity();
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
foreach (var account in AllowedAccounts())
{
security.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
}
return security;
}
/// <summary>The private DACL, plus read access for every local user (photos and renders, never <c>.chronos</c>).</summary>
[SupportedOSPlatform("windows")]
private static DirectorySecurity ArchiveFolderSecurity()
{
var security = PrivateFolderSecurity();
security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
return security;
}
[SupportedOSPlatform("windows")]
private static FileSecurity PrivateFileSecurity()
{
var security = new FileSecurity();
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
foreach (var account in AllowedAccounts())
security.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow));
return security;
}
}
@@ -0,0 +1,103 @@
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting;
/// <summary>
/// LAN discovery (BRIEF §14.9, <c>CHRONOS_DISCOVERY</c>): every few seconds a <see cref="DiscoveryBeacon"/> is broadcast on
/// UDP port <see cref="DiscoveryBeacon.Port"/> of every IPv4 network, so clients can offer this server on first run.
/// Switching discovery off in the settings stops it without a restart. In a container the broadcasts reach the LAN
/// only with host networking; on a bridge network they stay on the bridge.
/// </summary>
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger<DiscoveryBeaconService> logger) : BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var udp = new UdpClient(AddressFamily.InterNetwork) { EnableBroadcast = true };
var warned = false;
while (!stoppingToken.IsCancellationRequested)
{
if (options.Discovery)
{
try
{
await SendOnceAsync(udp, BroadcastTargets(), stoppingToken);
}
catch (SocketException ex) when (!warned)
{
warned = true;
logger.LogInformation("LAN discovery beacon cannot be sent: {Reason}", ex.Message);
}
catch (SocketException)
{
// Already reported once; networks may come and go.
}
}
try
{
await Task.Delay(Interval, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
}
}
/// <summary>
/// The beacon for the ports clients reach: the public ports when set, else the ports Kestrel actually listens on
/// (HTTPS 0 when TLS is terminated elsewhere).
/// </summary>
public DiscoveryBeacon CreateBeacon() => new(
options.ServerName,
SystemEndpoints.Version,
options.PublicHttpPort ?? BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
state.TlsFingerprint is null ? 0 : options.PublicHttpsPort ?? BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
state.TlsFingerprint);
public async Task SendOnceAsync(UdpClient udp, IEnumerable<IPEndPoint> targets, CancellationToken cancellationToken)
{
var datagram = CreateBeacon().ToBytes();
foreach (var target in targets) await udp.SendAsync(datagram, target, cancellationToken);
}
/// <summary>The limited broadcast address plus the directed broadcast of each IPv4 interface that is up.</summary>
private static List<IPEndPoint> BroadcastTargets()
{
var targets = new List<IPEndPoint> { new(IPAddress.Broadcast, DiscoveryBeacon.Port) };
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
foreach (var unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.AddressFamily != AddressFamily.InterNetwork || unicast.IPv4Mask is not { } mask) continue;
var address = unicast.Address.GetAddressBytes();
var bits = mask.GetAddressBytes();
for (var i = 0; i < 4; i++) address[i] = (byte)(address[i] | ~bits[i]);
var broadcast = new IPEndPoint(new IPAddress(address), DiscoveryBeacon.Port);
if (!targets.Contains(broadcast)) targets.Add(broadcast);
}
}
return targets;
}
private int? BoundPort(string scheme)
{
var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [];
foreach (var address in addresses)
{
if (Uri.TryCreate(address.Replace("[::]", "localhost", StringComparison.Ordinal).Replace("0.0.0.0", "localhost", StringComparison.Ordinal),
UriKind.Absolute, out var uri) && uri.Scheme == scheme)
return uri.Port;
}
return null;
}
}
@@ -0,0 +1,70 @@
using System.Collections.Frozen;
using System.Reflection;
using System.Security.Cryptography;
namespace Chronos.Server.Hosting;
/// <summary>
/// Serves the admin panel from embedded resources named <c>admin/…</c> (no build step, single-file friendly),
/// with strong ETags, conditional GET and SPA fallback to <c>index.html</c>.
/// </summary>
public sealed class EmbeddedStaticFiles
{
private static readonly FrozenDictionary<string, string> ContentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
[".html"] = "text/html; charset=utf-8",
[".js"] = "text/javascript; charset=utf-8",
[".mjs"] = "text/javascript; charset=utf-8",
[".css"] = "text/css; charset=utf-8",
[".svg"] = "image/svg+xml",
[".png"] = "image/png",
[".json"] = "application/json; charset=utf-8",
[".ico"] = "image/x-icon",
[".woff2"] = "font/woff2",
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
private readonly FrozenDictionary<string, (byte[] Content, string ETag, string ContentType)> _files;
public EmbeddedStaticFiles(Assembly assembly, string prefix)
{
var files = new Dictionary<string, (byte[], string, string)>(StringComparer.OrdinalIgnoreCase);
foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal)))
{
using var stream = assembly.GetManifestResourceStream(name)!;
using var ms = new MemoryStream();
stream.CopyTo(ms);
var bytes = ms.ToArray();
var path = name[prefix.Length..].Replace('\\', '/');
var etag = "\"" + Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12)) + "\"";
var type = ContentTypes.TryGetValue(Path.GetExtension(path), out var t) ? t : "application/octet-stream";
files[path] = (bytes, etag, type);
}
_files = files.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
}
public int Count => _files.Count;
public async Task<bool> TryServeAsync(HttpContext context, string relativePath)
{
var path = relativePath.TrimStart('/');
if (path.Length == 0) path = "index.html";
if (!_files.TryGetValue(path, out var file))
{
// Client-side routes (no extension) fall back to the shell.
if (Path.HasExtension(path) || !_files.TryGetValue("index.html", out file)) return false;
}
var response = context.Response;
response.Headers.ETag = file.ETag;
response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600";
response.Headers.XContentTypeOptions = "nosniff";
if (context.Request.Headers.IfNoneMatch == file.ETag)
{
response.StatusCode = StatusCodes.Status304NotModified;
return true;
}
response.ContentType = file.ContentType;
response.ContentLength = file.Content.Length;
if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted);
return true;
}
}
@@ -0,0 +1,63 @@
using Chronos.Core.Diagnostics;
using CoreLogLevel = Chronos.Core.Diagnostics.LogLevel;
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Chronos.Server.Hosting;
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
public void Dispose() => sink.Dispose();
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel)) return;
var level = logLevel switch
{
MsLogLevel.Trace => CoreLogLevel.Trace,
MsLogLevel.Debug => CoreLogLevel.Debug,
MsLogLevel.Information => CoreLogLevel.Info,
MsLogLevel.Warning => CoreLogLevel.Warning,
_ => CoreLogLevel.Error,
};
sink.Write(level, category, formatter(state, exception), exception);
}
}
}
/// <summary>Bridges engine logging (Chronos.Core.Diagnostics.Log) into ASP.NET Core logging.</summary>
public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
{
public void Write(CoreLogLevel level, string category, string message, Exception? exception)
{
ILogger logger;
try
{
logger = factory.CreateLogger("Chronos." + category);
}
catch (ObjectDisposedException)
{
// The host that installed this sink has shut down (engine code may outlive it); the line is dropped.
return;
}
var ms = level switch
{
CoreLogLevel.Trace => MsLogLevel.Trace,
CoreLogLevel.Debug => MsLogLevel.Debug,
CoreLogLevel.Info => MsLogLevel.Information,
CoreLogLevel.Warning => MsLogLevel.Warning,
_ => MsLogLevel.Error,
};
#pragma warning disable CA2254 // Engine messages are preformatted.
logger.Log(ms, exception, message);
#pragma warning restore CA2254
}
}
+26
View File
@@ -0,0 +1,26 @@
using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting;
/// <summary>
/// <c>Chronos.Server --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
/// HEALTHCHECK needs no curl/wget in the image.
/// </summary>
public static class HealthProbe
{
public static async Task<int> RunAsync()
{
try
{
var port = ServerOptions.Load().HttpPort;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
using var response = await http.GetAsync(new Uri($"http://127.0.0.1:{port}/health")).ConfigureAwait(false);
return response.IsSuccessStatusCode ? 0 : 1;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException)
{
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
return 1;
}
}
}
@@ -0,0 +1,74 @@
using Chronos.Protocol;
using Chronos.Server.Api;
namespace Chronos.Server.Hosting;
/// <summary>
/// First middleware of the pipeline: API version and security headers on every response, and the
/// <c>{ code, message, details }</c> error body for failures that did not produce one (bad requests, unhandled
/// exceptions, unknown methods).
/// </summary>
public sealed class ResponseMiddleware(RequestDelegate next, ILogger<ResponseMiddleware> logger)
{
/// <summary>The admin panel loads nothing from elsewhere and is never framed.</summary>
private const string AdminPolicy =
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; " +
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
public async Task InvokeAsync(HttpContext context)
{
var headers = context.Response.Headers;
headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
headers.XContentTypeOptions = "nosniff";
headers["Referrer-Policy"] = "no-referrer";
var api = context.Request.Path.StartsWithSegments("/api");
if (api) headers.CacheControl = "no-store";
if (context.Request.Path.StartsWithSegments("/admin"))
{
headers.ContentSecurityPolicy = AdminPolicy;
headers.XFrameOptions = "DENY";
}
try
{
await next(context);
}
catch (BadHttpRequestException ex) when (!context.Response.HasStarted)
{
await ApiErrors.WriteAsync(context, ex.StatusCode, CodeFor(ex.StatusCode));
return;
}
catch (FormatException) when (!context.Response.HasStarted && context.Request.Query.ContainsKey("cursor"))
{
// Repositories reject cursors that do not belong to the listing.
await ApiErrors.WriteAsync(context, StatusCodes.Status400BadRequest, "invalid_cursor");
return;
}
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (!context.Response.HasStarted)
{
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
await ApiErrors.WriteAsync(context, StatusCodes.Status500InternalServerError, "internal");
return;
}
var response = context.Response;
if (api && response.StatusCode >= 400 && !response.HasStarted && response.ContentType is null)
await ApiErrors.WriteAsync(context, response.StatusCode, CodeFor(response.StatusCode));
}
private static string CodeFor(int status) => status switch
{
StatusCodes.Status400BadRequest => "bad_request",
StatusCodes.Status401Unauthorized => "unauthorized",
StatusCodes.Status403Forbidden => "forbidden",
StatusCodes.Status404NotFound => "not_found",
StatusCodes.Status405MethodNotAllowed => "method_not_allowed",
StatusCodes.Status413PayloadTooLarge => "too_large",
StatusCodes.Status415UnsupportedMediaType => "unsupported_media_type",
_ => "internal",
};
}
@@ -0,0 +1,80 @@
namespace Chronos.Server.Hosting;
/// <summary>What <c>Chronos.Server</c> was asked to do.</summary>
public enum ServerCommand
{
/// <summary>Run in the console (Docker, Linux, development).</summary>
Run,
/// <summary>Run under the Windows Service Control Manager (the command line the installed service uses).</summary>
Service,
InstallService,
UninstallService,
/// <summary>Probe <c>/health</c> of the local server and exit 0/1 (container health check).</summary>
HealthCheck,
Help,
}
/// <summary>Command-line switches of the server; anything else is passed on to the web host.</summary>
public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<string> HostArguments, string? Error)
{
public const string Usage = """
Chronos Server — time-lapse archive, uploads, jobs and rendering.
Usage: Chronos.Server [--service | --install-service | --uninstall-service | --healthcheck | --help]
(no switch) run in the console until Ctrl+C
--service run under the Windows Service Control Manager
--install-service register the "ChronosServer" Windows service (automatic start, LocalSystem)
--uninstall-service stop and remove the Windows service
--healthcheck exit 0 when the local server answers /health, 1 otherwise
Configuration: /data/server.json (CHRONOS_DATA_PATH) overridden by environment variables:
CHRONOS_ARCHIVE_PATH CHRONOS_DATA_PATH CHRONOS_SERVER_NAME CHRONOS_ADMIN_USER CHRONOS_ADMIN_PASSWORD
CHRONOS_DB (postgres | sqlite | connection string) CHRONOS_DB_HOST CHRONOS_DB_PORT CHRONOS_DB_NAME CHRONOS_DB_USER
CHRONOS_DB_PASSWORD CHRONOS_DB_SSLMODE CHRONOS_HTTP_PORT CHRONOS_HTTPS_PORT CHRONOS_TLS_MODE (auto | pem | proxy)
CHRONOS_TLS_CERT CHRONOS_TLS_KEY CHRONOS_LANG
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
cores); CHRONOS_WORKERS, its former name, still sets it
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
CHRONOS_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
CHRONOS_DISCOVERY LAN beacon (true | false); in a container it needs host networking
CHRONOS_PUBLIC_HTTP_PORT, CHRONOS_PUBLIC_HTTPS_PORT
ports clients reach when the container's ports are published as other host ports
(admin redirect to HTTPS, LAN beacon)
CHRONOS_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
(default: loopback only; list a proxy in another container or on another machine)
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
""";
public static ServerCommandLine Parse(IReadOnlyList<string> args)
{
var command = ServerCommand.Run;
var rest = new List<string>();
string? error = null;
foreach (var arg in args)
{
ServerCommand? parsed = arg switch
{
"--service" => ServerCommand.Service,
"--install-service" => ServerCommand.InstallService,
"--uninstall-service" => ServerCommand.UninstallService,
"--healthcheck" => ServerCommand.HealthCheck,
"--help" or "-h" or "-?" or "/?" => ServerCommand.Help,
_ => null,
};
if (parsed is not { } switchCommand)
{
rest.Add(arg);
continue;
}
if (command != ServerCommand.Run && command != switchCommand) error = $"{arg} cannot be combined with another command switch.";
command = switchCommand;
}
return new ServerCommandLine(command, rest, error);
}
}
@@ -0,0 +1,41 @@
using Chronos.Data;
using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting;
/// <summary>Opens and migrates the server database at startup (BRIEF §6.1), waiting for a PostgreSQL container that is still starting.</summary>
public static class ServerDatabase
{
private const int Attempts = 10;
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(3);
public static async Task<ChronosDatabase> OpenAsync(ServerOptions options, ILogger logger, CancellationToken cancellationToken)
{
var settings = options.ToDatabaseOptions();
for (var attempt = 1; ; attempt++)
{
try
{
var db = await ChronosDatabase.OpenAsync(settings, cancellationToken).ConfigureAwait(false);
logger.LogInformation("Database {Dialect} ready, schema version {Version}", db.Dialect, db.SchemaVersion);
return db;
}
catch (DatabaseConnectionException ex) when (attempt < Attempts)
{
logger.LogWarning("Database not reachable yet ({Reason}); retry {Attempt} of {Attempts} in {Delay} s",
ex.Message, attempt, Attempts - 1, RetryDelay.TotalSeconds);
await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>Engine and version, e.g. "PostgreSQL 17.2" or "SQLite 3.45.1".</summary>
public static async Task<string> DescribeAsync(ChronosDatabase db, CancellationToken cancellationToken)
{
await using var session = await db.Database.OpenAsync(cancellationToken).ConfigureAwait(false);
var postgres = db.Dialect == Dialect.Postgres;
var version = await session.ScalarAsync<string>(postgres ? "SHOW server_version" : "SELECT sqlite_version()", [], cancellationToken).ConfigureAwait(false);
var number = version?.Split(' ', 2)[0] ?? string.Empty;
return (postgres ? "PostgreSQL " : "SQLite ") + number;
}
}
+191
View File
@@ -0,0 +1,191 @@
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Chronos.Core.Diagnostics;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Hosting;
/// <summary>
/// Builds the Chronos Server web application from <see cref="ServerOptions"/> (used by Program, the Windows service
/// host and tests). The archive module plugs in through the <c>configureServices</c> callback of <see cref="Build"/>,
/// which runs before the server's own registrations: it must register <see cref="IArchiveIngest"/> and
/// <see cref="IFrameAssetLocator"/> (the server refuses to start without them), may add
/// <see cref="Chronos.Data.Jobs.IJobHandler"/>s, and may resolve <see cref="ChronosDatabase"/>, <see cref="ServerArchive"/>
/// and <see cref="ServerOptions"/> from DI in its factories.
/// </summary>
public static class ServerHost
{
/// <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)
{
// Before anything is written there: the folder holds the database, the TLS key and the first admin password.
DataFolderAccess.Restrict(options.DataPath);
Directory.CreateDirectory(options.LogPath);
Directory.CreateDirectory(options.UploadsPath);
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(options.LogLevel);
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", options.LogLevel > Microsoft.Extensions.Logging.LogLevel.Information ? options.LogLevel : Microsoft.Extensions.Logging.LogLevel.Information);
// The archive module registers first, so a missing piece stops the server before it touches the database.
configureServices?.Invoke(builder.Services);
RequireArchiveModule(builder.Services);
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.LogLevel));
var bootLogger = bootLoggerFactory.CreateLogger("Chronos.Server");
var certificate = CertificateStore.Load(options, bootLogger);
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
try
{
var archive = ServerArchive.OpenAsync(database, options, CancellationToken.None).GetAwaiter().GetResult();
AdminBootstrap.RunAsync(database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
var state = new ServerState
{
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);
});
});
ConfigureServices(builder.Services, options, state, database, archive);
var app = builder.Build();
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
ConfigurePipeline(app, options);
app.Logger.LogInformation("Chronos 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);
if (archiveOpenToOthers)
{
app.Logger.LogWarning("Accounts other than SYSTEM, Administrators and the one Chronos Server runs as can change the archive {Archive}: "
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
options.ArchivePath);
}
if (options.FormerWorkersVariable)
{
app.Logger.LogWarning("CHRONOS_WORKERS is the former name of CHRONOS_PARALLELISM: jobs now run one at a time, and the value is how many "
+ "photos the running job processes at once. Rename the variable.");
}
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Chronos 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, ChronosDatabase database, ServerArchive archive)
{
services.AddSingleton(options);
services.AddSingleton(state);
services.AddSingleton(database);
services.AddSingleton(archive);
services.TryAddSingleton(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)
{
// Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would
// otherwise pick its own address for the sign-in rate limit and the audit log, and claim HTTPS.
var trusted = options.TrustedProxyNetworks();
services.Configure<ForwardedHeadersOptions>(f =>
{
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
f.KnownIPNetworks.Clear();
f.KnownProxies.Clear();
foreach (var network in trusted) f.KnownIPNetworks.Add(network);
});
}
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<RenderUploads>();
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>();
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);
DiagnosticsEndpoints.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(IServiceCollection services)
{
var missing = new List<string>();
if (!services.Any(d => d.ServiceType == typeof(IArchiveIngest))) missing.Add($"{typeof(IArchiveIngest).FullName} (commits verified uploads into the archive layout)");
if (!services.Any(d => d.ServiceType == typeof(IFrameAssetLocator))) missing.Add($"{typeof(IFrameAssetLocator).FullName} (finds proxies and thumbnails)");
if (missing.Count > 0)
{
throw new InvalidOperationException(
"Chronos Server cannot start: no implementation is registered for " + string.Join(" and ", missing) +
". Register them in the services callback of ServerHost.Build.");
}
}
}
@@ -0,0 +1,58 @@
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// Errors of the Windows service in the Application event log (source <c>ChronosServer</c>). A service has no console,
/// and a start-up failure comes before the server's log file exists (the data folder that holds it may be the very
/// thing refused), so Event Viewer is where an operator finds why the service stopped. The source is not registered
/// with a message file: Event Viewer says it found no description for the event, then shows the text whole.
/// </summary>
internal static unsafe class ServiceEventLog
{
public const uint StartFailed = 1;
public const uint StopFailed = 2;
/// <summary>ReportEvent takes at most 31,839 characters per string.</summary>
public const int MaxLength = 31_839;
/// <summary>
/// The event text: <paramref name="what"/> and the reason the server gave (the entry to check, for a refused data
/// folder), then the exception for a bug report; cut to <see cref="MaxLength"/>.
/// </summary>
public static string Describe(string what, Exception exception)
{
var text = $"{what} {exception.Message}{Environment.NewLine}{Environment.NewLine}{exception}";
if (text.Length <= MaxLength) return text;
var cut = MaxLength - 1;
// Never half a surrogate pair.
if (char.IsHighSurrogate(text[cut - 1])) cut--;
return string.Concat(text.AsSpan(0, cut), "…");
}
/// <summary>Writes an error event; false when the event log could not be written (the console still gets it).</summary>
[SupportedOSPlatform("windows")]
public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text);
/// <summary><see cref="Error(uint, string)"/> as <paramref name="sourceName"/> (tests write as their own source).</summary>
[SupportedOSPlatform("windows")]
internal static bool Error(string sourceName, uint eventId, string text)
{
var source = RegisterEventSourceW(null, sourceName);
if (source == 0) return false;
try
{
fixed (char* chars = text.Length <= MaxLength ? text : text[..MaxLength])
{
var strings = stackalloc char*[1];
strings[0] = chars;
return ReportEventW(source, EventLogErrorType, 0, eventId, 0, 1, 0, strings, null);
}
}
finally
{
DeregisterEventSource(source);
}
}
}
@@ -0,0 +1,160 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using Chronos.Core.Localization;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
/// (automatic start, LocalSystem, command line <c>"…\Chronos.Server.exe" --service</c>) or stops and removes it.
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. A LocalSystem service runs whatever
/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM,
/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to
/// any program of that user. Otherwise <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
/// </summary>
[SupportedOSPlatform("windows")]
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Chronos Server";
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
public static void Install()
{
if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem);
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
var service = CreateServiceW(manager, WindowsServiceHost.ServiceName, DisplayName, ServiceAllAccess, ServiceWin32OwnProcess, ServiceAutoStart,
ServiceErrorNormal, CommandLine(), null, 0, null, null, null);
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
fixed (char* text = Loc.L("Server.Service.Description"))
{
var description = new ServiceDescription { Description = text };
ChangeServiceConfig2W(service, ServiceConfigDescription, &description);
}
}
finally
{
CloseServiceHandle(service);
}
}
finally
{
CloseServiceHandle(manager);
}
}
public static void Uninstall()
{
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
var service = OpenServiceW(manager, WindowsServiceHost.ServiceName, Delete | ServiceStop | ServiceQueryStatus);
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
ServiceStatus status;
if (!ControlService(service, ControlStop, &status) && Marshal.GetLastPInvokeError() is var stopError && stopError != ErrorServiceNotActive)
throw new Win32Exception(stopError);
if (!DeleteService(service) && Marshal.GetLastPInvokeError() is var deleteError && deleteError != ErrorServiceMarkedForDelete)
throw new Win32Exception(deleteError);
}
finally
{
CloseServiceHandle(service);
}
}
finally
{
CloseServiceHandle(manager);
}
}
/// <summary>
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
/// </summary>
internal static string? UnsafeLocation()
{
var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program);
if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open);
// Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it.
if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host
&& !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase))
{
if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host);
if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen);
}
return null;
}
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
internal static bool IsUnderProgramFiles(string path)
{
var full = Path.GetFullPath(path);
foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 })
{
var root = Environment.GetFolderPath(folder);
if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than
/// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none.
/// </summary>
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> trusted)
{
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
foreach (var file in folder.EnumerateFiles())
{
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
}
if (!recursive) return null;
foreach (var child in folder.EnumerateDirectories())
{
if (FindChangeable(child, recursive: true, trusted) is { } path) return path;
}
return null;
}
private static HashSet<SecurityIdentifier> TrustedAccounts()
{
var trusted = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
TrustedInstaller,
};
// Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it.
using var identity = WindowsIdentity.GetCurrent();
if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user);
return trusted;
}
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
private static string CommandLine()
{
var process = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is unknown.");
// Assembly.Location is empty in a single-file app; under dotnet the entry assembly sits in the base directory.
var assembly = Path.Combine(AppContext.BaseDirectory, typeof(ServiceInstaller).Assembly.GetName().Name + ".dll");
return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase)
? $"\"{process}\" \"{assembly}\" --service"
: $"\"{process}\" --service";
}
}
@@ -0,0 +1,107 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace Chronos.Server.Hosting.Windows;
/// <summary>Service Control Manager and event log functions of advapi32 (no Windows-only package needed).</summary>
[SupportedOSPlatform("windows")]
internal static unsafe partial class ServiceNative
{
public const uint ServiceWin32OwnProcess = 0x10;
public const uint ServiceAutoStart = 2;
public const uint ServiceErrorNormal = 1;
public const uint ScManagerConnect = 0x1;
public const uint ScManagerCreateService = 0x2;
public const uint ServiceAllAccess = 0xF01FF;
public const uint ServiceQueryStatus = 0x4;
public const uint ServiceStop = 0x20;
public const uint Delete = 0x10000;
public const uint ServiceConfigDescription = 1;
public const uint ControlStop = 1;
public const uint ControlInterrogate = 4;
public const uint ControlShutdown = 5;
public const int ErrorFailedServiceControllerConnect = 1063;
public const int ErrorServiceNotActive = 1062;
public const int ErrorServiceMarkedForDelete = 1072;
public const uint NoError = 0;
public const uint ErrorCallNotImplemented = 120;
public const uint ErrorExceptionInService = 1064;
public const ushort EventLogErrorType = 0x1;
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatus
{
public uint ServiceType;
public uint CurrentState;
public uint ControlsAccepted;
public uint Win32ExitCode;
public uint ServiceSpecificExitCode;
public uint CheckPoint;
public uint WaitHint;
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceTableEntry
{
public char* ServiceName;
public delegate* unmanaged[Stdcall]<uint, char**, void> ServiceProc;
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceDescription
{
public char* Description;
}
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool StartServiceCtrlDispatcherW(ServiceTableEntry* table);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint RegisterServiceCtrlHandlerExW(string serviceName, delegate* unmanaged[Stdcall]<uint, uint, nint, nint, uint> handler, nint context);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetServiceStatus(nint statusHandle, ServiceStatus* status);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint CreateServiceW(nint manager, string serviceName, string displayName, uint desiredAccess, uint serviceType, uint startType,
uint errorControl, string binaryPathName, string? loadOrderGroup, nint tagId, string? dependencies, string? serviceStartName, string? password);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ChangeServiceConfig2W(nint service, uint infoLevel, void* info);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ControlService(nint service, uint control, ServiceStatus* status);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeleteService(nint service);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool CloseServiceHandle(nint handle);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint RegisterEventSourceW(string? uncServerName, string sourceName);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ReportEventW(nint eventLog, ushort type, ushort category, uint eventId, nint userSid, ushort stringCount, uint dataSize,
char** strings, void* rawData);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeregisterEventSource(nint eventLog);
}
@@ -0,0 +1,68 @@
namespace Chronos.Server.Hosting.Windows;
/// <summary>SERVICE_STATUS.dwCurrentState values the server reports.</summary>
public enum ServiceState : uint
{
Stopped = 1,
StartPending = 2,
StopPending = 3,
Running = 4,
}
/// <summary>One status report for <c>SetServiceStatus</c>.</summary>
public readonly record struct ServiceStatusReport(ServiceState State, uint ControlsAccepted, uint CheckPoint, uint WaitHintMilliseconds, uint ExitCode);
/// <summary>
/// The service's state machine and the rules of SERVICE_STATUS: no controls are accepted while pending, the check point
/// grows with every pending report and is zero otherwise, a stopped service carries its exit code.
/// </summary>
public sealed class ServiceStatusTracker
{
public const uint AcceptStop = 0x1;
public const uint AcceptShutdown = 0x4;
private readonly Lock _gate = new();
private uint _checkPoint;
public ServiceStatusReport Current { get; private set; } = new(ServiceState.Stopped, 0, 0, 0, 0);
public ServiceStatusReport StartPending(uint waitHintMilliseconds) => Pending(ServiceState.StartPending, waitHintMilliseconds, ServiceState.Stopped, ServiceState.StartPending);
public ServiceStatusReport Running()
{
lock (_gate)
{
Require(ServiceState.StartPending);
_checkPoint = 0;
return Current = new ServiceStatusReport(ServiceState.Running, AcceptStop | AcceptShutdown, 0, 0, 0);
}
}
/// <summary>Stopping from start-up or from running; repeating it reports progress (a higher check point).</summary>
public ServiceStatusReport StopPending(uint waitHintMilliseconds) =>
Pending(ServiceState.StopPending, waitHintMilliseconds, ServiceState.StartPending, ServiceState.Running, ServiceState.StopPending);
public ServiceStatusReport Stopped(uint exitCode)
{
lock (_gate)
{
_checkPoint = 0;
return Current = new ServiceStatusReport(ServiceState.Stopped, 0, 0, 0, exitCode);
}
}
private ServiceStatusReport Pending(ServiceState state, uint waitHintMilliseconds, params ServiceState[] from)
{
lock (_gate)
{
Require(from);
_checkPoint = Current.State == state ? _checkPoint + 1 : 1;
return Current = new ServiceStatusReport(state, 0, _checkPoint, waitHintMilliseconds, 0);
}
}
private void Require(params ServiceState[] allowed)
{
if (!allowed.Contains(Current.State)) throw new InvalidOperationException($"A service cannot go from {Current.State} to that state.");
}
}
@@ -0,0 +1,121 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW,
/// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running
/// jobs keep their checkpoints and resume at the next start. A failure to start or stop goes to the Application event
/// log (<see cref="ServiceEventLog"/>), since a service has no console.
/// </summary>
[SupportedOSPlatform("windows")]
public static class WindowsServiceHost
{
public const string ServiceName = "ChronosServer";
private const uint StartWaitHint = 60_000;
private const uint StopWaitHint = 35_000;
private static readonly ServiceStatusTracker Status = new();
private static Func<WebApplication>? _build;
private static WebApplication? _app;
private static nint _statusHandle;
/// <summary>
/// Hands the process to the Service Control Manager and returns when the service has stopped. False when the
/// process was not started by the SCM (for example from a console).
/// </summary>
public static unsafe bool Run(Func<WebApplication> build)
{
_build = build;
fixed (char* name = ServiceName)
{
var table = stackalloc ServiceTableEntry[2];
table[0] = new ServiceTableEntry { ServiceName = name, ServiceProc = &ServiceMain };
table[1] = default;
if (StartServiceCtrlDispatcherW(table)) return true;
}
var error = Marshal.GetLastPInvokeError();
if (error == ErrorFailedServiceControllerConnect) return false;
throw new Win32Exception(error);
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe void ServiceMain(uint argc, char** argv)
{
_statusHandle = RegisterServiceCtrlHandlerExW(ServiceName, &Handler, 0);
if (_statusHandle == 0) return;
Report(Status.StartPending(StartWaitHint));
try
{
_app = _build!();
_app.StartAsync().GetAwaiter().GetResult();
Report(Status.Running());
}
catch (Exception ex)
{
// A refused data folder or server.json says which entry to check; the SCM itself records only error 1064.
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StartFailed, ServiceEventLog.Describe("Chronos Server did not start:", ex));
Report(Status.Stopped(ErrorExceptionInService));
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe uint Handler(uint control, uint eventType, nint eventData, nint context)
{
switch (control)
{
case ControlStop or ControlShutdown:
if (Status.Current.State is ServiceState.Running or ServiceState.StartPending)
{
Report(Status.StopPending(StopWaitHint));
// The handler must return at once; the host stops on the thread pool.
_ = Task.Run(StopAsync);
}
return NoError;
case ControlInterrogate:
Report(Status.Current);
return NoError;
default:
return ErrorCallNotImplemented;
}
}
private static async Task StopAsync()
{
uint exitCode = 0;
try
{
if (_app is { } app)
{
await app.StopAsync();
await app.DisposeAsync();
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StopFailed, ServiceEventLog.Describe("Chronos Server did not stop cleanly:", ex));
exitCode = ErrorExceptionInService;
}
Report(Status.Stopped(exitCode));
}
private static unsafe void Report(ServiceStatusReport report)
{
var status = new ServiceStatus
{
ServiceType = ServiceWin32OwnProcess,
CurrentState = (uint)report.State,
ControlsAccepted = report.ControlsAccepted,
Win32ExitCode = report.ExitCode,
CheckPoint = report.CheckPoint,
WaitHint = report.WaitHintMilliseconds,
};
SetServiceStatus(_statusHandle, &status);
}
}