JSON backing store, I/O fixes, Networking Security
Introduced Newtonsoft.Json-backed persistence. Improved backing-store reliability and serialization across the caching stack. Improved networking security posture. Key changes: - Add new GameCult.Caching.NewtonsoftJson project with SingleFile/MultiFile backing stores and polymorphic known-type envelopes. - Add MessagePack helper serialization (DatabaseEntrySerialization) and update MessagePack backing stores to use the shared options/resolver; add DatabaseLink formatter and generator/analyzer docs. - Update CultLib.sln to include the new projects and new caching tests project. - Improve CultCache persistence behavior: track pending store operations, wait for operations on PullAll, and centralize async push handling with error logging. - Harden file I/O in multi-file/single-file stores: atomic temp-file writes, safe Replace/Move semantics, rename-safe deletes, and improved file-watcher subscription and debounce disposal. - Add README files and documentation for several subprojects and packaging projects. These changes add JSON persistence support, improve serialization consistency, and make on-disk operations more robust and observable.
This commit is contained in:
parent
d88eecb4ba
commit
0bfc85a4f2
50 changed files with 3957 additions and 325 deletions
|
|
@ -3,8 +3,6 @@ using System.Collections.Concurrent;
|
|||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
|
|
@ -16,79 +14,129 @@ using R3;
|
|||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
public class Server
|
||||
/// <summary>
|
||||
/// Hosts the server-side authentication, session, and message dispatch pipeline.
|
||||
/// </summary>
|
||||
public class Server : IDisposable
|
||||
{
|
||||
private const string EmailPattern =
|
||||
@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
|
||||
private const string UsernamePattern = @"^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$";
|
||||
private const int ServerPort = 3075;
|
||||
private const float SessionTimeoutSeconds = 1800; // 30 minutes
|
||||
private const float SessionRefreshThresholdSeconds = 300; // 5 minutes
|
||||
private const int MaxLoginAttemptsPerMinute = 5;
|
||||
|
||||
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new(); // Aggregated multicast Action<T> per type
|
||||
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
|
||||
private readonly ConcurrentDictionary<long, User> _users = new();
|
||||
private readonly ConcurrentDictionary<Guid, Session> _sessions = new();
|
||||
private readonly ConcurrentDictionary<Guid, long> _sessionToUserId = new();
|
||||
private readonly ConcurrentDictionary<string, Queue<DateTime>> _loginAttempts = new(); // IP to attempt timestamps
|
||||
private NetManager _netManager;
|
||||
private Stopwatch _timer;
|
||||
private readonly ConcurrentDictionary<string, Queue<DateTimeOffset>> _loginAttempts = new();
|
||||
private readonly ConcurrentDictionary<string, object> _loginAttemptLocks = new();
|
||||
private readonly IDisposable _cleanupSubscription;
|
||||
private readonly CultCache _database;
|
||||
private readonly ServerSecurityOptions _security;
|
||||
private NetManager? _netManager;
|
||||
private Stopwatch? _timer;
|
||||
private ILogger _logger = new NullLogger();
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the logger used by the server.
|
||||
/// </summary>
|
||||
public ILogger Logger
|
||||
{
|
||||
get => _logger;
|
||||
set => _logger = value ?? new NullLogger();
|
||||
}
|
||||
|
||||
private float Time => (float)_timer.Elapsed.TotalSeconds;
|
||||
private float Time => (float)(_timer?.Elapsed.TotalSeconds ?? 0d);
|
||||
|
||||
public Server(CultCache cache)
|
||||
/// <summary>
|
||||
/// Initializes a new server instance over the supplied cache.
|
||||
/// </summary>
|
||||
/// <param name="cache">The backing cache used for player persistence.</param>
|
||||
/// <param name="security">Optional validated server security options. When omitted, strict environment-based configuration is used.</param>
|
||||
public Server(CultCache cache, ServerSecurityOptions? security = null)
|
||||
{
|
||||
_database = cache;
|
||||
_security = security ?? ServerSecurityOptions.FromEnvironment();
|
||||
_database.RegisterIndex<PlayerData>("Email");
|
||||
Observable.Timer(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60))
|
||||
_cleanupSubscription = Observable.Timer(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60))
|
||||
.Subscribe(_ => CleanupExpiredSessions());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates an email address against the server's accepted pattern.
|
||||
/// </summary>
|
||||
/// <param name="email">The email address to validate.</param>
|
||||
/// <returns><c>true</c> when the address matches the expected format.</returns>
|
||||
public bool IsValidEmail(string email) => Regex.IsMatch(email, EmailPattern);
|
||||
|
||||
/// <summary>
|
||||
/// Validates a username against the server's accepted pattern.
|
||||
/// </summary>
|
||||
/// <param name="name">The username to validate.</param>
|
||||
/// <returns><c>true</c> when the username matches the expected format.</returns>
|
||||
public bool IsValidUsername(string name) => Regex.IsMatch(name, UsernamePattern);
|
||||
|
||||
/// <summary>
|
||||
/// Removes all registered message listeners.
|
||||
/// </summary>
|
||||
public void ClearMessageListeners()
|
||||
{
|
||||
_messageDelegates.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a listener for a specific authenticated message type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The message type to subscribe to.</typeparam>
|
||||
/// <param name="callback">The callback to invoke when the message is received.</param>
|
||||
public void AddMessageListener<T>(Action<T> callback) where T : Message
|
||||
{
|
||||
var type = typeof(T);
|
||||
// Atomically aggregate into multicast delegate (thread-safe via CAS)
|
||||
_messageDelegates.AddOrUpdate(type,
|
||||
_ => callback, // First callback
|
||||
_ => callback,
|
||||
(t, current) =>
|
||||
{
|
||||
// Combine with existing (supports multiple callbacks)
|
||||
var combined = Delegate.Combine(current, callback) as Action<T>;
|
||||
return combined ?? throw new InvalidOperationException($"Failed to combine delegates for {t.Name}");
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a previously registered listener for a specific message type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The message type to unsubscribe from.</typeparam>
|
||||
/// <param name="callback">The callback to remove.</param>
|
||||
public void RemoveMessageListener<T>(Action<T> callback) where T : Message
|
||||
{
|
||||
if (_messageDelegates.TryGetValue(typeof(T), out var currentDelegate))
|
||||
{
|
||||
var newDelegate = Delegate.Remove(currentDelegate, callback) as Action<T>;
|
||||
_messageDelegates[typeof(T)] = newDelegate; // Null if empty
|
||||
_messageDelegates[typeof(T)] = newDelegate!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the underlying LiteNetLib server.
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
_netManager.Stop();
|
||||
_netManager?.Stop();
|
||||
_netManager = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts listening for connections and configures message handlers.
|
||||
/// </summary>
|
||||
public void Start()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(Server));
|
||||
}
|
||||
|
||||
Stop();
|
||||
_timer = Stopwatch.StartNew();
|
||||
|
||||
var listener = new EventBasedNetListener();
|
||||
|
|
@ -104,9 +152,13 @@ namespace GameCult.Networking
|
|||
listener.ConnectionRequestEvent += request =>
|
||||
{
|
||||
if (CheckRateLimit(request.RemoteEndPoint.Address.ToString()))
|
||||
request.AcceptIfKey(Secret.ConnectionKey);
|
||||
{
|
||||
request.AcceptIfKey(_security.ConnectionKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
request.Reject();
|
||||
}
|
||||
};
|
||||
|
||||
listener.PeerConnectedEvent += peer =>
|
||||
|
|
@ -118,17 +170,15 @@ namespace GameCult.Networking
|
|||
listener.PeerDisconnectedEvent += (peer, info) =>
|
||||
{
|
||||
Logger.LogInfo($"User Disconnected: {peer.Address}");
|
||||
if (_users.TryRemove(peer.Id, out var user) && user.SessionGuid != Guid.Empty)
|
||||
{
|
||||
_sessions.TryRemove(user.SessionGuid, out _);
|
||||
_sessionToUserId.TryRemove(user.SessionGuid, out _);
|
||||
}
|
||||
_users.TryRemove(peer.Id, out _);
|
||||
};
|
||||
|
||||
listener.NetworkLatencyUpdateEvent += (peer, latency) =>
|
||||
{
|
||||
if (_users.TryGetValue(peer.Id, out var user))
|
||||
{
|
||||
user.Latency = latency;
|
||||
}
|
||||
};
|
||||
|
||||
listener.NetworkReceiveEvent += async (peer, reader, channel, method) =>
|
||||
|
|
@ -136,10 +186,13 @@ namespace GameCult.Networking
|
|||
try
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
var message = MessagePackSerializer.Deserialize<Message>(bytes);
|
||||
var message = MessageSerialization.Deserialize<Message>(bytes);
|
||||
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
|
||||
if (message == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
message.Peer = peer;
|
||||
var user = _users.GetOrAdd(peer.Id, _ => new User { Peer = peer });
|
||||
|
||||
|
|
@ -147,120 +200,42 @@ namespace GameCult.Networking
|
|||
{
|
||||
if (IsVerified(user))
|
||||
{
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage { Nonce = nonce, Session = Secret.EncryptBytes(user.SessionGuid.ToByteArray(), nonce) });
|
||||
SendSessionToken(peer, user.PlayerId);
|
||||
return;
|
||||
}
|
||||
|
||||
Guid sessionGuid;
|
||||
if (message is LoginMessage or RegisterMessage && !CheckRateLimit(peer.Address.ToString()))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Too Many Attempts" });
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message)
|
||||
{
|
||||
case RegisterMessage register:
|
||||
{
|
||||
var name = Secret.DecryptString(register.Name, register.Nonce);
|
||||
var email = Secret.DecryptString(register.Email, register.Nonce);
|
||||
if (!IsValidUsername(name))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsValidEmail(email))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Email Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetIdByIndex<PlayerData>("Email", email) != null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Email Taken" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetIdByName<PlayerData>(name) != null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
return;
|
||||
}
|
||||
sessionGuid = GenerateSessionGuid();
|
||||
var password = Secret.DecryptString(register.Password, register.Nonce);
|
||||
var newUserData = new PlayerData
|
||||
{
|
||||
ID = Guid.NewGuid(),
|
||||
Email = email,
|
||||
PasswordHash = Argon2.Hash(password, memoryCost: 16384),
|
||||
Username = name
|
||||
};
|
||||
await _database.AddAsync(newUserData); // Immediate cache + async file write
|
||||
_sessions.TryAdd(sessionGuid, new Session { Data = newUserData, LastUpdate = DateTime.Now });
|
||||
_sessionToUserId[sessionGuid] = peer.Id;
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage { Nonce = nonce, Session = Secret.EncryptBytes(sessionGuid.ToByteArray(), nonce) });
|
||||
if (_users.TryGetValue(peer.Id, out var u1))
|
||||
u1.SessionGuid = sessionGuid;
|
||||
await HandleRegisterAsync(peer, user, register);
|
||||
break;
|
||||
}
|
||||
case VerifyMessage verify:
|
||||
var session = new Guid(Secret.DecryptBytes(verify.Session, verify.Nonce));
|
||||
if (!_sessions.ContainsKey(session))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Not Found" });
|
||||
return;
|
||||
}
|
||||
if (_users.TryGetValue(peer.Id, out var u2))
|
||||
{
|
||||
u2.SessionGuid = session;
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage { Nonce = nonce, Session = Secret.EncryptBytes(session.ToByteArray(), nonce) });
|
||||
}
|
||||
HandleVerify(peer, user, verify);
|
||||
break;
|
||||
case LoginMessage login:
|
||||
{
|
||||
var auth = Secret.DecryptString(login.Auth, login.Nonce);
|
||||
var isEmail = IsValidEmail(auth);
|
||||
var userData = isEmail ?
|
||||
_database.GetByIndex<PlayerData>("Email", auth) :
|
||||
_database.GetByName<PlayerData>(auth);
|
||||
|
||||
if (userData == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = isEmail ? "Email Not Found" : "Username Not Found" });
|
||||
return;
|
||||
}
|
||||
|
||||
var password = Secret.DecryptString(login.Password, login.Nonce);
|
||||
if (!Argon2.Verify(userData.PasswordHash, password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Password Incorrect" });
|
||||
return;
|
||||
}
|
||||
|
||||
sessionGuid = GenerateSessionGuid();
|
||||
_sessions.TryAdd(sessionGuid, new Session { Data = userData, LastUpdate = DateTime.Now });
|
||||
_sessionToUserId[sessionGuid] = peer.Id;
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage { Nonce = nonce, Session = Secret.EncryptBytes(sessionGuid.ToByteArray(), nonce) });
|
||||
if (_users.TryGetValue(peer.Id, out var u3))
|
||||
u3.SessionGuid = sessionGuid;
|
||||
HandleLogin(peer, user, login);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (IsVerified(user))
|
||||
{
|
||||
// Zero-reflection dispatch via cached multicast delegate
|
||||
if (_messageDelegates.TryGetValue(message.GetType(), out var del) && del != null)
|
||||
{
|
||||
del.DynamicInvoke(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning($"No listener for {message.GetType().Name}");
|
||||
|
||||
if (_sessions.TryGetValue(user.SessionGuid, out var session))
|
||||
session.LastUpdate = DateTime.Now;
|
||||
}
|
||||
|
||||
user.SessionExpiresAt = DateTimeOffset.UtcNow.AddSeconds(SessionTimeoutSeconds);
|
||||
RefreshSessionIfNeeded(peer, user);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -273,21 +248,29 @@ namespace GameCult.Networking
|
|||
}
|
||||
};
|
||||
|
||||
AddMessageListener<ChangeNameMessage>(async (message) =>
|
||||
AddMessageListener<ChangeNameMessage>(async message =>
|
||||
{
|
||||
if (!IsValidUsername(message.Name))
|
||||
{
|
||||
message.Peer.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
message.Peer?.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetIdByName<PlayerData>(message.Name) != null)
|
||||
{
|
||||
message.Peer.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
message.Peer?.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
return;
|
||||
}
|
||||
if (_users.TryGetValue(message.Peer.Id, out var user))
|
||||
|
||||
if (message.Peer != null && _users.TryGetValue(message.Peer.Id, out var user))
|
||||
{
|
||||
var data = SessionData(user);
|
||||
if (data == null)
|
||||
{
|
||||
message.Peer.Send(new ErrorMessage { Error = "User Not Verified" });
|
||||
return;
|
||||
}
|
||||
|
||||
data.Username = message.Name;
|
||||
await _database.AddAsync(data);
|
||||
}
|
||||
|
|
@ -296,64 +279,241 @@ namespace GameCult.Networking
|
|||
Logger.LogInfo($"Server started on port {ServerPort}.");
|
||||
}
|
||||
|
||||
private bool IsVerified(User u) => u != null && _sessions.ContainsKey(u.SessionGuid);
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
private PlayerData SessionData(User user) =>
|
||||
IsVerified(user) ? _sessions[user.SessionGuid].Data : null;
|
||||
_disposed = true;
|
||||
_cleanupSubscription.Dispose();
|
||||
Stop();
|
||||
}
|
||||
|
||||
private async Task HandleRegisterAsync(NetPeer peer, User user, RegisterMessage register)
|
||||
{
|
||||
var name = Secret.DecryptString(register.Name, register.Nonce, _security);
|
||||
var email = Secret.DecryptString(register.Email, register.Nonce, _security);
|
||||
var password = Secret.DecryptString(register.Password, register.Nonce, _security);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(name) || !IsValidUsername(name))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(email) || !IsValidEmail(email))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Email Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetIdByIndex<PlayerData>("Email", email) != null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Email Taken" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetIdByName<PlayerData>(name) != null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Password Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
var newUserData = new PlayerData
|
||||
{
|
||||
ID = Guid.NewGuid(),
|
||||
Email = email,
|
||||
PasswordHash = Argon2.Hash(password, memoryCost: 16384),
|
||||
Username = name
|
||||
};
|
||||
|
||||
await _database.AddAsync(newUserData);
|
||||
AttachUser(user, newUserData.ID);
|
||||
SendSessionToken(peer, newUserData.ID);
|
||||
}
|
||||
|
||||
private void HandleVerify(NetPeer peer, User user, VerifyMessage verify)
|
||||
{
|
||||
var token = Secret.DecryptString(verify.Session, verify.Nonce, _security);
|
||||
if (!Secret.TryValidateSessionToken(token, _security, out var playerId, out _))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.Get<PlayerData>(playerId) == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Not Found" });
|
||||
return;
|
||||
}
|
||||
|
||||
AttachUser(user, playerId);
|
||||
SendSessionToken(peer, playerId);
|
||||
}
|
||||
|
||||
private void HandleLogin(NetPeer peer, User user, LoginMessage login)
|
||||
{
|
||||
var auth = Secret.DecryptString(login.Auth, login.Nonce, _security);
|
||||
var password = Secret.DecryptString(login.Password, login.Nonce, _security);
|
||||
if (string.IsNullOrWhiteSpace(auth) || string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Credentials Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
var isEmail = IsValidEmail(auth);
|
||||
var userData = isEmail
|
||||
? _database.GetByIndex<PlayerData>("Email", auth)
|
||||
: _database.GetByName<PlayerData>(auth);
|
||||
|
||||
if (userData == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = isEmail ? "Email Not Found" : "Username Not Found" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Argon2.Verify(userData.PasswordHash, password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Password Incorrect" });
|
||||
return;
|
||||
}
|
||||
|
||||
AttachUser(user, userData.ID);
|
||||
SendSessionToken(peer, userData.ID);
|
||||
}
|
||||
|
||||
private bool IsVerified(User? user) =>
|
||||
user != null &&
|
||||
user.PlayerId != Guid.Empty &&
|
||||
user.SessionExpiresAt > DateTimeOffset.UtcNow &&
|
||||
_database.Get<PlayerData>(user.PlayerId) != null;
|
||||
|
||||
private PlayerData? SessionData(User user) =>
|
||||
IsVerified(user) ? _database.Get<PlayerData>(user.PlayerId) : null;
|
||||
|
||||
private bool CheckRateLimit(string ip)
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var windowStart = now.AddMinutes(-1);
|
||||
_loginAttempts.AddOrUpdate(
|
||||
ip,
|
||||
_ => new Queue<DateTime>(new[] { now }),
|
||||
(_, queue) =>
|
||||
var queue = _loginAttempts.GetOrAdd(ip, _ => new Queue<DateTimeOffset>());
|
||||
var gate = _loginAttemptLocks.GetOrAdd(ip, _ => new object());
|
||||
|
||||
lock (gate)
|
||||
{
|
||||
while (queue.Count > 0 && queue.Peek() < windowStart)
|
||||
{
|
||||
// Remove attempts older than 1 minute
|
||||
while (queue.Count > 0 && queue.Peek() < windowStart)
|
||||
queue.Dequeue();
|
||||
queue.Enqueue(now);
|
||||
return queue;
|
||||
});
|
||||
queue.Dequeue();
|
||||
}
|
||||
|
||||
return _loginAttempts[ip].Count <= MaxLoginAttemptsPerMinute;
|
||||
}
|
||||
|
||||
private Guid GenerateSessionGuid()
|
||||
{
|
||||
var guid = Guid.NewGuid();
|
||||
// TODO: Implement HMAC signing for session validation
|
||||
return guid;
|
||||
queue.Enqueue(now);
|
||||
return queue.Count <= MaxLoginAttemptsPerMinute;
|
||||
}
|
||||
}
|
||||
|
||||
private void CleanupExpiredSessions()
|
||||
{
|
||||
foreach (var session in _sessions.ToArray())
|
||||
foreach (var entry in _users.ToArray())
|
||||
{
|
||||
if ((DateTime.Now - session.Value.LastUpdate).TotalSeconds > SessionTimeoutSeconds)
|
||||
if (entry.Value.SessionExpiresAt != default && entry.Value.SessionExpiresAt <= DateTimeOffset.UtcNow)
|
||||
{
|
||||
_sessions.TryRemove(session.Key, out _);
|
||||
if (_sessionToUserId.TryRemove(session.Key, out var userId) && _users.TryGetValue(userId, out var user))
|
||||
if (_users.TryRemove(entry.Key, out var user))
|
||||
{
|
||||
user.Peer.Disconnect();
|
||||
_users.TryRemove(userId, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void AttachUser(User user, Guid playerId)
|
||||
{
|
||||
user.PlayerId = playerId;
|
||||
user.SessionExpiresAt = DateTimeOffset.UtcNow.AddSeconds(SessionTimeoutSeconds);
|
||||
}
|
||||
|
||||
private void SendSessionToken(NetPeer peer, Guid playerId)
|
||||
{
|
||||
var expiresAtUtc = DateTimeOffset.UtcNow.AddSeconds(SessionTimeoutSeconds);
|
||||
var token = Secret.CreateSessionToken(playerId, expiresAtUtc, _security);
|
||||
|
||||
if (_users.TryGetValue(peer.Id, out var user))
|
||||
{
|
||||
user.PlayerId = playerId;
|
||||
user.SessionExpiresAt = expiresAtUtc;
|
||||
user.SessionToken = token;
|
||||
}
|
||||
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage
|
||||
{
|
||||
Nonce = nonce,
|
||||
Session = Secret.EncryptString(token, nonce, _security) ?? Array.Empty<byte>()
|
||||
});
|
||||
}
|
||||
|
||||
private void RefreshSessionIfNeeded(NetPeer peer, User user)
|
||||
{
|
||||
if ((user.SessionExpiresAt - DateTimeOffset.UtcNow).TotalSeconds > SessionRefreshThresholdSeconds)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SendSessionToken(peer, user.PlayerId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents an active authenticated session.
|
||||
/// </summary>
|
||||
public class Session
|
||||
{
|
||||
/// <summary>
|
||||
/// The last time the session was observed as active.
|
||||
/// </summary>
|
||||
public DateTime LastUpdate;
|
||||
public PlayerData Data;
|
||||
|
||||
/// <summary>
|
||||
/// Player data associated with the session.
|
||||
/// </summary>
|
||||
public PlayerData Data = null!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tracks connection state for a connected peer.
|
||||
/// </summary>
|
||||
public class User
|
||||
{
|
||||
public NetPeer Peer;
|
||||
/// <summary>
|
||||
/// The connected network peer.
|
||||
/// </summary>
|
||||
public NetPeer Peer = null!;
|
||||
|
||||
/// <summary>
|
||||
/// The last reported latency for the peer.
|
||||
/// </summary>
|
||||
public int Latency;
|
||||
public Guid SessionGuid;
|
||||
|
||||
/// <summary>
|
||||
/// The authenticated player identifier.
|
||||
/// </summary>
|
||||
public Guid PlayerId;
|
||||
|
||||
/// <summary>
|
||||
/// The current session expiration timestamp in UTC.
|
||||
/// </summary>
|
||||
public DateTimeOffset SessionExpiresAt;
|
||||
|
||||
/// <summary>
|
||||
/// The latest signed session token issued to the peer.
|
||||
/// </summary>
|
||||
public string SessionToken = string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue