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:
Claude committed 2026-10-02 11:32:19 +00:00
1 parent 7353c17d7b
commit c78747053e
56 files changed
+4726 -108

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
using Titano.Core.Model;
namespace Titano.Server.Security;
/// <summary>
/// Endpoint metadata read by <see cref="AuthenticationMiddleware"/>. Every <c>/api</c> endpoint requires a signed-in
/// caller unless it carries <see cref="Anonymous"/>; the most specific rule (endpoint over group) wins whole.
/// </summary>
public sealed class AccessRule
{
public static readonly AccessRule Anonymous = new() { AllowAnonymous = true };
public static readonly AccessRule SignedIn = new();
public bool AllowAnonymous { get; private init; }
/// <summary>The caller needs at least one of these permissions; <see cref="Permissions.None"/> = any signed-in caller.</summary>
public Permissions AnyOf { get; private init; }
/// <summary>Reachable while the account must still replace its temporary password (me, password, logout).</summary>
public bool DuringPasswordChange { get; private init; }
public static AccessRule Requiring(Permissions anyOf) => new() { AnyOf = anyOf };
public static AccessRule PasswordChange { get; } = new() { DuringPasswordChange = true };
}
public static class AccessRuleExtensions
{
public static TBuilder AllowAnonymousCaller<TBuilder>(this TBuilder builder) where TBuilder : IEndpointConventionBuilder =>
builder.WithMetadata(AccessRule.Anonymous);
public static TBuilder Requires<TBuilder>(this TBuilder builder, Permissions anyOf) where TBuilder : IEndpointConventionBuilder =>
builder.WithMetadata(AccessRule.Requiring(anyOf));
public static TBuilder AllowDuringPasswordChange<TBuilder>(this TBuilder builder) where TBuilder : IEndpointConventionBuilder =>
builder.WithMetadata(AccessRule.PasswordChange);
}
+35
View File
@@ -0,0 +1,35 @@
using Titano.Core.Model;
namespace Titano.Server.Security;
/// <summary>Account rules shared by bootstrap, sign-in and user management.</summary>
public static class Accounts
{
public const int MaxUsernameLength = 64;
/// <summary>Letters, digits, dot, dash and underscore; 1–64 characters.</summary>
public static bool IsValidUsername(string? name) =>
name is { Length: > 0 and <= MaxUsernameLength } && name.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_');
/// <summary>The case-insensitive key of a user name (lock-out bookkeeping).</summary>
public static string Key(string? name) => (name ?? string.Empty).Trim().ToLowerInvariant();
/// <summary>The role's default permissions with the render-node right granted or withheld explicitly.</summary>
public static Permissions PermissionsFor(UserRole role, bool renderNode) =>
(RolePermissions.Default(role) & ~Permissions.RenderNode) | (renderNode ? Permissions.RenderNode : Permissions.None);
/// <summary>Parses a role name (admin, editor, uploader, viewer); numbers are not accepted.</summary>
public static bool TryParseRole(string? text, out UserRole role)
{
foreach (var candidate in Enum.GetValues<UserRole>())
{
if (string.Equals(candidate.ToString(), text, StringComparison.OrdinalIgnoreCase))
{
role = candidate;
return true;
}
}
role = default;
return false;
}
}
@@ -0,0 +1,85 @@
using Titano.Core.Model;
using Titano.Data;
using Titano.Server.Configuration;
namespace Titano.Server.Security;
/// <summary>
/// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from
/// <c>TITANO_ADMIN_USER</c>/<c>TITANO_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),
/// never to the log; the file is removed once an administrator changes their password.
/// </summary>
public static class AdminBootstrap
{
public const string DefaultUsername = "admin";
private const string PasswordFileName = "initial-admin-password.txt";
public static async Task RunAsync(TitanoDatabase 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; TITANO_ADMIN_USER and TITANO_ADMIN_PASSWORD are ignored");
return;
}
var username = string.IsNullOrWhiteSpace(options.AdminUser) ? DefaultUsername : options.AdminUser.Trim();
if (!Accounts.IsValidUsername(username))
throw new InvalidOperationException("TITANO_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 TITANO_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);
await File.WriteAllTextAsync(passwordFile, password + Environment.NewLine, cancellationToken).ConfigureAwait(false);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(passwordFile, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
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 TITANO_ADMIN_USER/TITANO_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.
}
}
}
+26
View File
@@ -0,0 +1,26 @@
using Titano.Core.Model;
using Titano.Data;
namespace Titano.Server.Security;
/// <summary>Appends who did what to the audit log (BRIEF §14.2): sign-ins, user, sequence, archive and setting changes.</summary>
public sealed class AuditLog(TitanoDatabase db, TimeProvider time)
{
public Task WriteAsync(Caller caller, HttpContext context, string action, string? targetKind = null, string? targetId = null, string? details = null) =>
WriteAsync(caller.Id, caller.User.Username, context, action, targetKind, targetId, details);
public Task WriteAsync(Guid? userId, string? username, HttpContext? context, string action, string? targetKind = null, string? targetId = null,
string? details = null) =>
db.Audit.AppendAsync(new AuditEntry
{
Id = Guid.CreateVersion7(),
At = time.GetUtcNow(),
UserId = userId,
Username = username,
Action = action,
TargetKind = targetKind,
TargetId = targetId,
Details = details,
RemoteAddress = context?.Connection.RemoteIpAddress?.ToString(),
});
}
@@ -0,0 +1,79 @@
using Titano.Core.Model;
using Titano.Server.Api;
namespace Titano.Server.Security;
/// <summary>
/// Resolves the caller of every <c>/api</c> request (bearer token or admin cookie) and enforces the endpoint's
/// <see cref="AccessRule"/>: 401 without a valid token, 403 for a missing permission, a missing CSRF header on a
/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known.
/// </summary>
public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens)
{
public async Task InvokeAsync(HttpContext context)
{
var rule = context.GetEndpoint()?.Metadata.GetMetadata<AccessRule>();
if (rule is null && !context.Request.Path.StartsWithSegments("/api"))
{
await next(context);
return;
}
rule ??= AccessRule.SignedIn;
if (rule.AllowAnonymous)
{
await next(context);
return;
}
var caller = await AuthenticateAsync(context);
if (caller is null)
{
context.Response.Headers.WWWAuthenticate = "Bearer";
await ApiErrors.WriteAsync(context, StatusCodes.Status401Unauthorized, "unauthorized");
return;
}
if (caller.Source == CredentialSource.Cookie && !IsSameSiteRequest(context, caller))
{
await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "csrf_failed");
return;
}
if (caller.User.MustChangePassword && !rule.DuringPasswordChange)
{
await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "password_change_required");
return;
}
if (rule.AnyOf != Permissions.None && !caller.Has(rule.AnyOf))
{
await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "forbidden");
return;
}
context.Features.Set(caller);
await next(context);
}
private Task<Caller?> AuthenticateAsync(HttpContext context)
{
var authorization = context.Request.Headers.Authorization.ToString();
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return tokens.ValidateAsync(authorization[7..].Trim(), CredentialSource.Bearer, context.RequestAborted);
if (context.Request.Cookies.TryGetValue(SessionCookies.Session, out var cookie))
return tokens.ValidateAsync(cookie, CredentialSource.Cookie, context.RequestAborted);
return Task.FromResult<Caller?>(null);
}
/// <summary>
/// Cookie requests must prove they come from the admin panel: unsafe methods carry the CSRF header, WebSocket
/// upgrades (which cannot) must come from this origin.
/// </summary>
private static bool IsSameSiteRequest(HttpContext context, Caller caller)
{
if (context.WebSockets.IsWebSocketRequest)
{
var origin = context.Request.Headers.Origin.ToString();
return origin.Equals($"{context.Request.Scheme}://{context.Request.Host}", StringComparison.OrdinalIgnoreCase);
}
var method = context.Request.Method;
if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method)) return true;
return SessionCookies.HasValidCsrf(context, caller);
}
}
+92
View File
@@ -0,0 +1,92 @@
using Titano.Server.Configuration;
namespace Titano.Server.Security;
/// <summary>
/// Sign-in throttling (BRIEF §14.2): at most <see cref="ServerOptions.LoginAttemptsPerMinute"/> attempts per client
/// address and minute, and an account name locked for <see cref="ServerOptions.LockoutMinutes"/> after
/// <see cref="ServerOptions.LockoutThreshold"/> consecutive failures. Names without an account are tracked the same
/// way, so a lockout reveals nothing about which names exist. State is per process and resets at restart.
/// </summary>
public sealed class LoginGuard(ServerOptions options, TimeProvider time)
{
private static readonly TimeSpan Window = TimeSpan.FromMinutes(1);
private const int PruneAbove = 10_000;
private readonly Lock _gate = new();
private readonly Dictionary<string, Queue<DateTimeOffset>> _attempts = new(StringComparer.Ordinal);
private readonly Dictionary<string, AccountState> _accounts = new(StringComparer.Ordinal);
/// <summary>Counts an attempt from <paramref name="address"/>; false, with the time to wait, once its budget is spent.</summary>
public bool TryAttempt(string address, out TimeSpan retryAfter)
{
var now = time.GetUtcNow();
lock (_gate)
{
if (_attempts.Count > PruneAbove) Prune(now);
if (!_attempts.TryGetValue(address, out var recent)) _attempts[address] = recent = new Queue<DateTimeOffset>();
while (recent.Count > 0 && now - recent.Peek() >= Window) recent.Dequeue();
if (recent.Count >= options.LoginAttemptsPerMinute)
{
retryAfter = Window - (now - recent.Peek());
return false;
}
recent.Enqueue(now);
retryAfter = TimeSpan.Zero;
return true;
}
}
/// <summary>True while <paramref name="account"/> (a normalised user name) is locked.</summary>
public bool IsLocked(string account, out TimeSpan retryAfter)
{
var now = time.GetUtcNow();
lock (_gate)
{
if (_accounts.TryGetValue(account, out var state) && state.LockedUntil is { } until && until > now)
{
retryAfter = until - now;
return true;
}
retryAfter = TimeSpan.Zero;
return false;
}
}
public void RecordFailure(string account)
{
var now = time.GetUtcNow();
var span = TimeSpan.FromMinutes(options.LockoutMinutes);
lock (_gate)
{
if (_accounts.Count > PruneAbove) Prune(now);
var state = _accounts.GetValueOrDefault(account);
if (state?.LockedUntil is { } until && until > now) return;
if (state is null || state.LockedUntil is not null || now - state.FirstFailure > span) state = new AccountState(0, now, null);
var failures = state.Failures + 1;
_accounts[account] = failures >= options.LockoutThreshold
? new AccountState(0, now, now + span)
: state with { Failures = failures };
}
}
public void RecordSuccess(string account)
{
lock (_gate) _accounts.Remove(account);
}
private void Prune(DateTimeOffset now)
{
foreach (var (address, recent) in _attempts.ToList())
{
if (recent.Count == 0 || now - recent.Last() >= Window) _attempts.Remove(address);
}
var span = TimeSpan.FromMinutes(options.LockoutMinutes);
foreach (var (account, state) in _accounts.ToList())
{
if ((state.LockedUntil ?? state.FirstFailure + span) < now) _accounts.Remove(account);
}
}
private sealed record AccountState(int Failures, DateTimeOffset FirstFailure, DateTimeOffset? LockedUntil);
}
@@ -0,0 +1,69 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Titano.Server.Security;
/// <summary>
/// Password hashes (BRIEF §14.2): PBKDF2-SHA512, 210,000 iterations, 16-byte random salt per hash, stored as
/// <c>pbkdf2-sha512$&lt;iterations&gt;$&lt;salt&gt;$&lt;hash&gt;</c> (base64). The format names its algorithm and cost, so
/// older hashes keep verifying and are upgraded at the next sign-in.
/// </summary>
public static class PasswordHasher
{
public const int MinimumLength = 10;
public const int Iterations = 210_000;
private const string Algorithm = "pbkdf2-sha512";
private const int SaltBytes = 16;
private const int HashBytes = 64;
/// <summary>Verified against unknown user names so a miss costs as much time as a wrong password.</summary>
private static readonly Lazy<string> DummyHash = new(() => Hash(Convert.ToBase64String(RandomNumberGenerator.GetBytes(18))));
public static string Hash(string password)
{
var salt = RandomNumberGenerator.GetBytes(SaltBytes);
var hash = Derive(password, salt, Iterations);
return string.Create(CultureInfo.InvariantCulture, $"{Algorithm}${Iterations}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}");
}
/// <summary>Constant-time check of <paramref name="password"/> against a stored hash; malformed hashes never match.</summary>
public static bool Verify(string password, string storedHash)
{
var parts = storedHash.Split('$');
if (parts.Length != 4 || parts[0] != Algorithm
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var iterations) || iterations < 1)
return false;
byte[] salt, expected;
try
{
salt = Convert.FromBase64String(parts[2]);
expected = Convert.FromBase64String(parts[3]);
}
catch (FormatException)
{
return false;
}
if (salt.Length == 0 || expected.Length == 0) return false;
var actual = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, expected.Length);
return CryptographicOperations.FixedTimeEquals(actual, expected);
}
/// <summary>Spends the same time as <see cref="Verify"/> for a name that has no account.</summary>
public static void VerifyDummy(string password) => Verify(password, DummyHash.Value);
/// <summary>True when the hash was made with fewer iterations than the current policy.</summary>
public static bool NeedsRehash(string storedHash)
{
var parts = storedHash.Split('$');
return parts.Length != 4 || parts[0] != Algorithm
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var iterations) || iterations < Iterations;
}
/// <summary>Policy check for passwords users choose: at least <see cref="MinimumLength"/> characters, not only spaces.</summary>
public static bool IsAcceptable(string? password) =>
password is not null && password.Length >= MinimumLength && !string.IsNullOrWhiteSpace(password);
private static byte[] Derive(string password, byte[] salt, int iterations) =>
Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, HashBytes);
}
@@ -0,0 +1,55 @@
using System.Buffers.Text;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace Titano.Server.Security;
/// <summary>
/// The web admin's cookie session (BRIEF §14.2): the token in an <c>HttpOnly; Secure; SameSite=Strict</c> cookie, plus a
/// script-readable CSRF cookie whose value must come back in <see cref="CsrfHeader"/> on every unsafe request. The CSRF
/// value is derived from the session token, so a planted cookie pair cannot forge it.
/// </summary>
public static class SessionCookies
{
public const string Session = "titano_session";
public const string Csrf = "titano_csrf";
public const string CsrfHeader = "X-CSRF-Token";
public static void Issue(HttpContext context, IssuedToken token)
{
context.Response.Cookies.Append(Session, token.Secret, Options(httpOnly: true));
context.Response.Cookies.Append(Csrf, CsrfFor(token.Stored.TokenHash), Options(httpOnly: false));
}
public static void Clear(HttpContext context)
{
context.Response.Cookies.Delete(Session, Options(httpOnly: true));
context.Response.Cookies.Delete(Csrf, Options(httpOnly: false));
}
/// <summary>Constant-time check of the request's CSRF header against the caller's session.</summary>
public static bool HasValidCsrf(HttpContext context, Caller caller)
{
var header = context.Request.Headers[CsrfHeader].ToString();
var expected = CsrfFor(caller.TokenHash);
return header.Length == expected.Length
&& CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(header), Encoding.ASCII.GetBytes(expected));
}
/// <summary>Secure cookies only travel over HTTPS (or to the machine itself, which browsers treat as secure).</summary>
public static bool IsSecureTransport(HttpContext context) =>
context.Request.IsHttps || (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote));
private static string CsrfFor(string tokenHash) =>
Base64Url.EncodeToString(SHA256.HashData(Encoding.UTF8.GetBytes("titano-csrf|" + tokenHash)));
private static CookieOptions Options(bool httpOnly) => new()
{
HttpOnly = httpOnly,
Secure = true,
SameSite = SameSiteMode.Strict,
Path = "/",
IsEssential = true,
};
}
@@ -0,0 +1,15 @@
using System.Security.Cryptography;
namespace Titano.Server.Security;
/// <summary>One-time passwords for new accounts and resets: three groups of four unambiguous characters (≈ 70 bits).</summary>
public static class TemporaryPassword
{
private const string Alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
public static string Generate()
{
var chars = RandomNumberGenerator.GetItems<char>(Alphabet, 12);
return $"{new string(chars, 0, 4)}-{new string(chars, 4, 4)}-{new string(chars, 8, 4)}";
}
}
@@ -0,0 +1,91 @@
using System.Buffers.Text;
using System.Security.Cryptography;
using System.Text;
using Titano.Core.Model;
using Titano.Data;
using Titano.Server.Configuration;
namespace Titano.Server.Security;
/// <summary>How a request presented its token.</summary>
public enum CredentialSource
{
/// <summary><c>Authorization: Bearer</c> (desktop client, uploader, render node).</summary>
Bearer,
/// <summary>HttpOnly session cookie of the web admin; unsafe methods also need the CSRF header.</summary>
Cookie,
}
/// <summary>The signed-in account behind a request.</summary>
public sealed record Caller(User User, string TokenHash, CredentialSource Source, string? ClientName)
{
public Guid Id => User.Id;
public bool IsAdmin => User.Role == UserRole.Admin;
/// <summary>True when the account holds at least one of <paramref name="any"/>.</summary>
public bool Has(Permissions any) => (User.Permissions & any) != 0;
/// <summary>Minimal-API binding: endpoint handlers take the caller resolved by <see cref="AuthenticationMiddleware"/>.</summary>
public static ValueTask<Caller?> BindAsync(HttpContext context) => ValueTask.FromResult(context.Features.Get<Caller>());
}
/// <summary>A freshly issued token: the secret (returned once) and what is stored (its hash).</summary>
public sealed record IssuedToken(string Secret, SessionToken Stored);
/// <summary>
/// Opaque bearer tokens (BRIEF §14.2): 32 random bytes, stored only as their SHA-256, sliding expiry, revocation.
/// The same tokens back the admin panel's cookie session.
/// </summary>
public sealed class TokenService(TitanoDatabase db, ServerOptions options, TimeProvider time)
{
/// <summary>Sliding expiry is written at most this often per token, not on every request.</summary>
private static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1);
private TimeSpan Lifetime => TimeSpan.FromDays(options.TokenLifetimeDays);
public async Task<IssuedToken> IssueAsync(User user, string? clientName, CancellationToken cancellationToken)
{
var secret = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32));
var now = time.GetUtcNow();
var name = clientName?.Trim();
var token = new SessionToken
{
TokenHash = HashOf(secret),
UserId = user.Id,
ClientName = string.IsNullOrEmpty(name) ? null : name[..Math.Min(name.Length, 100)],
Created = now,
Expires = now + Lifetime,
LastUsed = now,
};
await db.Tokens.InsertAsync(token, cancellationToken).ConfigureAwait(false);
return new IssuedToken(secret, token);
}
/// <summary>The caller a token belongs to, or null when it is unknown, revoked, expired or its account is disabled.</summary>
public async Task<Caller?> ValidateAsync(string secret, CredentialSource source, CancellationToken cancellationToken)
{
if (secret.Length is 0 or > 128) return null;
var hash = HashOf(secret);
var token = await db.Tokens.GetAsync(hash, cancellationToken).ConfigureAwait(false);
var now = time.GetUtcNow();
if (token is null || token.Revoked || token.Expires <= now) return null;
var user = await db.Users.GetAsync(token.UserId, cancellationToken).ConfigureAwait(false);
if (user is null || user.Disabled) return null;
if (now - token.LastUsed >= TouchInterval && !await db.Tokens.TouchAsync(hash, now, now + Lifetime, cancellationToken).ConfigureAwait(false))
return null;
return new Caller(user, hash, source, token.ClientName);
}
/// <summary>True while the caller's token is still live and its account enabled (long-lived WebSocket sessions).</summary>
public async Task<bool> IsStillValidAsync(Caller caller, CancellationToken cancellationToken)
{
var token = await db.Tokens.GetAsync(caller.TokenHash, cancellationToken).ConfigureAwait(false);
if (token is null || token.Revoked || token.Expires <= time.GetUtcNow()) return false;
return await db.Users.GetAsync(caller.Id, cancellationToken).ConfigureAwait(false) is { Disabled: false };
}
/// <summary>Stored form of a token: lower-case hex SHA-256 of its text.</summary>
public static string HashOf(string secret) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(secret)));
}