Files
Chronos/src/Chronos.Server/Security/AdminBootstrap.cs
T
Alby96andClaude Opus 5.5 8d41992d84 feat: Chronos Desktop shares its library on the LAN (owner review 5 P4)
Chronos Server for Windows is replaced by Settings > Server > Share this
library: Chronos Desktop hosts the server engine in its own process over its
own index, archive and processing services, job engine and scheduler, so a
second PC, the Uploader and render nodes use this PC's library without a
Windows service or a second index.

- Chronos.Server is a library; Chronos.Server.Host is the console exe that
  Docker and development runs start. The App references the library and the
  ASP.NET Core shared framework (no package).
- ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and
  never creates, starts or disposes them; no static log sink, no console
  lifetime; server.json plus desktop-owned values locked "Set in Chronos
  Desktop"; only upload-cleanup and audit-cleanup schedules are added.
- Both modes: by-id endpoints scoped to the served archive, a client's
  render export folder dropped; hosted mode exposes server job kinds only.
- Desktop: LibraryShare (start after the schedules, stop first, port in
  use named), Settings > Server sharing rows, Server > This library panel
  (state, addresses with Copy, ports, fingerprint, temporary admin
  password, clients, admin panel), own library refused by ConnectFlow and
  dropped from LAN discovery, the uploads sweep step, thumbnails after scans
  while sharing, capture scenes server-share and server-share-failed.
- Removed: the Windows service hosting of Chronos.Server, its switches and
  its tests.

Refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:55:50 +01:00

89 lines
4.0 KiB
C#

using System.Text;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
namespace Chronos.Server.Security;
/// <summary>
/// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from
/// <c>CHRONOS_ADMIN_USER</c>/<c>CHRONOS_ADMIN_PASSWORD</c> and must change its password at first sign-in. Without a
/// configured password a temporary one is generated and written to <c>/data/initial-admin-password.txt</c> (owner-only;
/// on Windows readable by the server's account and Administrators), never to the log; the file is removed once an
/// administrator changes their password.
/// </summary>
public static class AdminBootstrap
{
public const string DefaultUsername = "admin";
/// <summary>The file in the data folder that holds a generated temporary password until an administrator sets their own.</summary>
public const string PasswordFileName = "initial-admin-password.txt";
public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken)
{
var users = await db.Users.ListAsync(cancellationToken).ConfigureAwait(false);
if (users.Any(u => u.Role == UserRole.Admin))
{
if (!string.IsNullOrEmpty(options.AdminPassword))
logger.LogInformation("An administrator exists; CHRONOS_ADMIN_USER and CHRONOS_ADMIN_PASSWORD are ignored");
return;
}
var username = string.IsNullOrWhiteSpace(options.AdminUser) ? DefaultUsername : options.AdminUser.Trim();
if (!Accounts.IsValidUsername(username))
throw new InvalidOperationException("CHRONOS_ADMIN_USER may only contain letters, digits, dot, dash and underscore (up to 64 characters).");
if (users.Any(u => Accounts.Key(u.Username) == Accounts.Key(username)))
throw new InvalidOperationException($"No administrator exists and CHRONOS_ADMIN_USER '{username}' names an existing account; choose another name.");
var password = options.AdminPassword;
string? passwordFile = null;
if (string.IsNullOrEmpty(password))
{
password = TemporaryPassword.Generate();
passwordFile = Path.Combine(options.DataPath, PasswordFileName);
DataFolderAccess.WritePrivateFile(passwordFile, Encoding.UTF8.GetBytes(password + Environment.NewLine));
}
var admin = new User
{
Id = Guid.CreateVersion7(),
Username = username,
DisplayName = null,
PasswordHash = PasswordHasher.Hash(password),
Role = UserRole.Admin,
Permissions = Permissions.All,
MustChangePassword = true,
Created = time.GetUtcNow(),
};
await db.Users.CreateAsync(admin, cancellationToken).ConfigureAwait(false);
await db.Audit.AppendAsync(new AuditEntry
{
Id = Guid.CreateVersion7(),
At = admin.Created,
Action = "user_created",
TargetKind = "user",
TargetId = admin.Id.ToString(),
Details = "admin",
Username = username,
}, cancellationToken).ConfigureAwait(false);
if (passwordFile is null)
logger.LogWarning("Created administrator '{User}' from CHRONOS_ADMIN_USER/CHRONOS_ADMIN_PASSWORD; the password must be changed at first sign-in", username);
else
logger.LogWarning("Created administrator '{User}'; its temporary password is in {File} and must be changed at first sign-in", username, passwordFile);
}
/// <summary>Removes the generated password file (called when an administrator sets their own password).</summary>
public static void ForgetInitialPassword(ServerOptions options)
{
try
{
File.Delete(Path.Combine(options.DataPath, PasswordFileName));
}
catch (IOException)
{
// Best effort: the file holds a password that no longer works.
}
}
}