using Titano.Server.Configuration; namespace Titano.Server.Security; /// /// Sign-in throttling (BRIEF ยง14.2): at most attempts per client /// address and minute, and an account name locked for after /// 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. /// 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> _attempts = new(StringComparer.Ordinal); private readonly Dictionary _accounts = new(StringComparer.Ordinal); /// Counts an attempt from ; false, with the time to wait, once its budget is spent. 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(); 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; } } /// True while (a normalised user name) is locked. 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); }