diff --git a/Networking/NetworkManager.cs b/Networking/NetworkManager.cs index a5d2930..6919d10 100644 --- a/Networking/NetworkManager.cs +++ b/Networking/NetworkManager.cs @@ -17,17 +17,19 @@ public sealed class NetworkManager private readonly ConcurrentDictionary _connections = new(); private readonly ISessionRegistry _sessions; private readonly IRedisManager _redis; + private readonly ISessionAudit _sessionAudit; private readonly TimeSpan _tickInterval; private readonly TimeSpan _idleTimeout; private readonly int _maxConnections; - public NetworkManager(ILogger log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis) + public NetworkManager(ILogger log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis, ISessionAudit sessionAudit) { _log = log; _router = router; _sessions = sessions; _redis = redis; + _sessionAudit = sessionAudit; var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20; _tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz); @@ -143,8 +145,8 @@ public sealed class NetworkManager { if (_connections.TryRemove(conn.Id, out _)) { - // If this connection was authenticated, log it out atomically - if (_sessions.TryGet(conn.Id, out var accountId, out var token) && accountId != 0 && !string.IsNullOrEmpty(token)) + if (_sessions.TryGet(conn.Id, out var accountId, out var token) + && accountId != 0 && !string.IsNullOrEmpty(token)) { try { @@ -159,15 +161,19 @@ public sealed class NetworkManager return 1"; await _redis.Db.ScriptEvaluateAsync(lua, - new RedisKey[] { onlineKey, sessKey }, - new RedisValue[] { token }); + new StackExchange.Redis.RedisKey[] { onlineKey, sessKey }, + new StackExchange.Redis.RedisValue[] { token }); + + // NEW: close the SQL session audit row + await _sessionAudit.EndAsync(accountId, token, reason); _sessions.Unbind(conn.Id); _log.LogInformation("Logged out account {AccountId} on disconnect", accountId); } catch (Exception ex) { - _log.LogWarning(ex, "Failed Redis logout cleanup for account {AccountId}", accountId); + _log.LogWarning(ex, "Failed logout cleanup for account {AccountId}", accountId); + try { await _sessionAudit.EndAsync(accountId, token, reason); } catch { } _sessions.Unbind(conn.Id); } } @@ -178,4 +184,5 @@ public sealed class NetworkManager } } + } diff --git a/Program.cs b/Program.cs index a1fabce..dd72871 100644 --- a/Program.cs +++ b/Program.cs @@ -45,6 +45,7 @@ builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); diff --git a/Services/Auth/ISessionAudit.cs b/Services/Auth/ISessionAudit.cs new file mode 100644 index 0000000..d894c41 --- /dev/null +++ b/Services/Auth/ISessionAudit.cs @@ -0,0 +1,10 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace Server.Services.Auth; + +public interface ISessionAudit +{ + /// Marks the session as ended (or deletes it) for this account+token. + Task EndAsync(ulong accountId, string token, string reason, CancellationToken ct = default); +} diff --git a/Services/Auth/SessionAudit.cs b/Services/Auth/SessionAudit.cs new file mode 100644 index 0000000..85d324c --- /dev/null +++ b/Services/Auth/SessionAudit.cs @@ -0,0 +1,64 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Server.Data; + +namespace Server.Services.Auth; + +public sealed class SessionAudit : ISessionAudit +{ + private readonly GameDbContext _db; + private readonly ILogger _log; + + public SessionAudit(GameDbContext db, ILogger log) + { + _db = db; _log = log; + } + + public async Task EndAsync(ulong accountId, string token, string reason, CancellationToken ct = default) + { + var tokenHash = Sha256Hex(token); + + // Try to mark RevokedAt if the column exists; otherwise delete the row. + try + { + var session = await _db.Set() + .Where(s => s.AccountId == accountId && s.TokenHash == tokenHash) + .OrderByDescending(s => s.Id) + .FirstOrDefaultAsync(ct); + + if (session is null) return; + + // If you have a RevokedAt column, prefer marking it: + var revokedAtProp = _db.Entry(session).Property("RevokedAt"); + if (revokedAtProp != null) + { + revokedAtProp.CurrentValue = DateTime.UtcNow; + await _db.SaveChangesAsync(ct); + } + else + { + _db.Remove(session); + await _db.SaveChangesAsync(ct); + } + + _log.LogInformation("Session ended for account {AccountId} (reason={Reason})", accountId, reason); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to end SQL session for account {AccountId}", accountId); + } + } + + private static string Sha256Hex(string s) + { + using var sha = SHA256.Create(); + var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(s)); + return Convert.ToHexString(bytes).ToLowerInvariant(); + } +} diff --git a/data/entities/Session.cs b/data/entities/Session.cs index 26a93fa..3874c1a 100644 --- a/data/entities/Session.cs +++ b/data/entities/Session.cs @@ -13,6 +13,8 @@ public sealed class Session public string? CreatedIp { get; set; } public string? UserAgent { get; set; } public Account? Account { get; set; } + public DateTime? RevokedAt { get; set; } + } public sealed class SessionConfig : IEntityTypeConfiguration @@ -26,6 +28,7 @@ public sealed class SessionConfig : IEntityTypeConfiguration e.Property(x => x.CreatedIp).HasMaxLength(64); e.Property(x => x.UserAgent).HasMaxLength(256); e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property("RevokedAt"); e.HasIndex(x => x.AccountId); e.HasIndex(x => x.TokenHash).IsUnique();