Initial commit
This commit is contained in:
commit
137cb2ce13
215 changed files with 659023 additions and 0 deletions
200
src/GameCult.Networking/Client.cs
Normal file
200
src/GameCult.Networking/Client.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using GameCult.Logging;
|
||||
using LiteNetLib;
|
||||
using MessagePack;
|
||||
using MessagePack.Resolvers;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
public class Client
|
||||
{
|
||||
public event Action<string> OnError; // Hook for important user-facing feedback (e.g. via modal UI element)
|
||||
private NetManager _client;
|
||||
private NetPeer _peer;
|
||||
|
||||
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
|
||||
|
||||
|
||||
private Guid _sessionToken;
|
||||
private string _lastHost;
|
||||
private int _lastPort;
|
||||
private ILogger _logger = new NullLogger();
|
||||
|
||||
public ILogger Logger
|
||||
{
|
||||
get => _logger;
|
||||
set => _logger = value ?? new NullLogger();
|
||||
}
|
||||
|
||||
public int Ping { get; private set; }
|
||||
public bool Verified => _sessionToken != Guid.Empty;
|
||||
public bool Connected => _client != null;
|
||||
|
||||
public Client()
|
||||
{
|
||||
OnError += s => Logger.LogError(s);
|
||||
}
|
||||
|
||||
public void Send<T>(T m) where T : Message
|
||||
{
|
||||
if (Connected)
|
||||
{
|
||||
if (Verified || m is LoginMessage || m is RegisterMessage || m is VerifyMessage)
|
||||
{
|
||||
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m as Message)}");
|
||||
_peer.Send(m);
|
||||
}
|
||||
else Logger.LogError("Cannot send, client is not verified!");
|
||||
}
|
||||
else Logger.LogError("Cannot send, client is not connected!");
|
||||
}
|
||||
|
||||
public void ClearMessageListeners()
|
||||
{
|
||||
_messageDelegates.Clear();
|
||||
}
|
||||
|
||||
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
|
||||
(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}");
|
||||
});
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
public void Login(string auth, string password)
|
||||
{
|
||||
if (auth.Length > 0)
|
||||
{
|
||||
if (password.Length is >= 8 and < 32)
|
||||
{
|
||||
var nonce = Secret.NewNonce;
|
||||
Send(new LoginMessage
|
||||
{
|
||||
Nonce = nonce,
|
||||
Auth = Secret.EncryptString(auth, nonce),
|
||||
Password = Secret.EncryptString(password, nonce)
|
||||
});
|
||||
}
|
||||
else OnError?.Invoke("Password Invalid: needs to be at least 8 characters");
|
||||
}
|
||||
else OnError?.Invoke("Email/Username Empty");
|
||||
}
|
||||
|
||||
public void Register(string email, string username, string password)
|
||||
{
|
||||
if (email.Length > 0)
|
||||
{
|
||||
if (username.Length > 0)
|
||||
{
|
||||
if (password.Length is >= 8 and < 32)
|
||||
{
|
||||
var nonce = Secret.NewNonce;
|
||||
Send(new RegisterMessage
|
||||
{
|
||||
Nonce = nonce,
|
||||
Email = Secret.EncryptString(email, nonce),
|
||||
Name = Secret.EncryptString(username, nonce),
|
||||
Password = Secret.EncryptString(password, nonce)
|
||||
});
|
||||
}
|
||||
else OnError?.Invoke("Password Invalid: needs to be at least 8 characters");
|
||||
}
|
||||
else OnError?.Invoke("Username Empty");
|
||||
}
|
||||
else OnError?.Invoke("Email Empty");
|
||||
}
|
||||
|
||||
public void Connect(string host = "localhost", int port = 3075)
|
||||
{
|
||||
_lastHost = host;
|
||||
_lastPort = port;
|
||||
|
||||
EventBasedNetListener listener = new EventBasedNetListener();
|
||||
_client = new NetManager(listener)
|
||||
{
|
||||
// UnsyncedEvents = true,
|
||||
NatPunchEnabled = true
|
||||
};
|
||||
_client.Start(3074);
|
||||
_peer = _client.Connect(host, port, Secret.ConnectionKey);
|
||||
Observable.EveryUpdate().Subscribe(_ => _client.PollEvents());
|
||||
listener.NetworkErrorEvent += (point, code) => Logger.LogInfo($"{point.Address}: Error {code}");
|
||||
listener.NetworkReceiveEvent += (peer, reader, channel, method) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
|
||||
var message = MessagePackSerializer.Deserialize<Message>(bytes);
|
||||
var type = message.GetType();
|
||||
|
||||
if (!Verified)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case LoginSuccessMessage loginSuccess:
|
||||
_sessionToken = new Guid(Secret.DecryptBytes(loginSuccess.Session, loginSuccess.Nonce));
|
||||
break;
|
||||
case ErrorMessage error:
|
||||
OnError?.Invoke(error.Error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (_messageDelegates.TryGetValue(message.GetType(), out var del) && del != null)
|
||||
del.DynamicInvoke(message);
|
||||
else
|
||||
Logger.LogWarning($"No listener for {message.GetType().Name}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError($"Message processing failed: {ex.Message}");
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
listener.PeerConnectedEvent += peer =>
|
||||
{
|
||||
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} connected.");
|
||||
_peer = peer;
|
||||
if (Verified)
|
||||
{
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new VerifyMessage { Nonce = nonce, Session = Secret.EncryptBytes(_sessionToken.ToByteArray(), nonce) });
|
||||
}
|
||||
};
|
||||
|
||||
listener.PeerDisconnectedEvent += (peer, info) =>
|
||||
{
|
||||
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} disconnected: {info.Reason}.");
|
||||
_peer = null;
|
||||
Connect(_lastHost, _lastPort);
|
||||
};
|
||||
|
||||
listener.NetworkLatencyUpdateEvent +=
|
||||
(peer, latency) => Ping = latency; //Logger($"Ping received: {latency} ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/GameCult.Networking/GameCult.Networking.csproj
Normal file
14
src/GameCult.Networking/GameCult.Networking.csproj
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<Description>CultNet: Secure, high-performance messaging for games/servers</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GameCult.Logging\GameCult.Logging.csproj" />
|
||||
<ProjectReference Include="..\GameCult.Caching\GameCult.Caching.csproj" />
|
||||
<PackageReference Include="MessagePack" Version="3.1.4" />
|
||||
<PackageReference Include="R3" Version="1.3.0" />
|
||||
<PackageReference Include="LiteNetLib" Version="1.3.1" />
|
||||
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
69
src/GameCult.Networking/Messages.cs
Normal file
69
src/GameCult.Networking/Messages.cs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
using System;
|
||||
using LiteNetLib;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
|
||||
[Union(0, typeof(LoginMessage)),
|
||||
Union(1, typeof(RegisterMessage)),
|
||||
Union(2, typeof(VerifyMessage)),
|
||||
Union(3, typeof(LoginSuccessMessage)),
|
||||
Union(4, typeof(ErrorMessage)),
|
||||
Union(5, typeof(ChangeNameMessage)),
|
||||
MessagePackObject]
|
||||
public abstract class Message
|
||||
{
|
||||
[IgnoreMember] public NetPeer Peer { get; set; }
|
||||
}
|
||||
|
||||
public class EncryptedMessage : Message
|
||||
{
|
||||
[Key(0)] public byte[] Nonce;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class LoginMessage : EncryptedMessage
|
||||
{
|
||||
[Key(1)] public byte[] Auth;
|
||||
[Key(2)] public byte[] Password;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class RegisterMessage : EncryptedMessage
|
||||
{
|
||||
[Key(1)] public byte[] Email;
|
||||
[Key(2)] public byte[] Password;
|
||||
[Key(3)] public byte[] Name;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class VerifyMessage : EncryptedMessage
|
||||
{
|
||||
[Key(1)] public byte[] Session;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class LoginSuccessMessage : EncryptedMessage
|
||||
{
|
||||
[Key(1)] public byte[] Session;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class ErrorMessage : Message
|
||||
{
|
||||
[Key(0)] public string Error;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class ChangeNameMessage : Message
|
||||
{
|
||||
[Key(0)] public string Name;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class ChatMessage : Message
|
||||
{
|
||||
[Key(0)] public string Text;
|
||||
}
|
||||
}
|
||||
13
src/GameCult.Networking/NetPeerExtensions.cs
Normal file
13
src/GameCult.Networking/NetPeerExtensions.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
using LiteNetLib;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
public static class NetPeerExtensions
|
||||
{
|
||||
public static void Send<T>(this NetPeer peer, T message) where T : Message
|
||||
{
|
||||
peer.Send(MessagePackSerializer.Serialize(message), DeliveryMethod.ReliableOrdered);
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/GameCult.Networking/PlayerData.cs
Normal file
39
src/GameCult.Networking/PlayerData.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
/// <summary>
|
||||
/// Player data stored in the database.
|
||||
/// For MessagePack serialization, uses [MessagePackObject] and [Key(n)] attributes.
|
||||
/// </summary>
|
||||
public class PlayerData : DatabaseEntry, INamedEntry
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Email address of the player.
|
||||
/// </summary>
|
||||
[Key(1)]
|
||||
public string Email;
|
||||
|
||||
/// <summary>
|
||||
/// Password hash of the player.
|
||||
/// </summary>
|
||||
[Key(2)]
|
||||
public string PasswordHash;
|
||||
|
||||
/// <summary>
|
||||
/// Username of the player.
|
||||
/// </summary>
|
||||
[Key(3)]
|
||||
public string Username;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[IgnoreMember]
|
||||
public string EntryName
|
||||
{
|
||||
get => Username;
|
||||
set => Username = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
64
src/GameCult.Networking/Secret.cs
Normal file
64
src/GameCult.Networking/Secret.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
public static class Secret
|
||||
{
|
||||
public const string ConnectionKey = "cultpong-843ctnsw";
|
||||
public static readonly byte[] EncryptionKey = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(ConnectionKey)); // PSK
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
|
||||
public static byte[] NewNonce
|
||||
{
|
||||
get
|
||||
{
|
||||
var bytes = new byte[AesGcm.NonceByteSizes.MaxSize];
|
||||
Rng.GetBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] EncryptString(string input, byte[] nonce)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input)) return null;
|
||||
return EncryptBytes(Encoding.UTF8.GetBytes(input), nonce);
|
||||
}
|
||||
|
||||
public static byte[] EncryptBytes(byte[] input, byte[] nonce)
|
||||
{
|
||||
if (input == null || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize)
|
||||
throw new CryptographicException("Invalid input or nonce");
|
||||
|
||||
using var aes = new AesGcm(EncryptionKey);
|
||||
var ciphertext = new byte[input.Length];
|
||||
var tag = new byte[AesGcm.TagByteSizes.MaxSize];
|
||||
aes.Encrypt(nonce, input, ciphertext, tag);
|
||||
var result = new byte[tag.Length + ciphertext.Length];
|
||||
Buffer.BlockCopy(tag, 0, result, 0, tag.Length);
|
||||
Buffer.BlockCopy(ciphertext, 0, result, tag.Length, ciphertext.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string DecryptString(byte[] encrypted, byte[] nonce)
|
||||
{
|
||||
if (encrypted == null || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize) return null;
|
||||
var decrypted = DecryptBytes(encrypted, nonce);
|
||||
return Encoding.UTF8.GetString(decrypted);
|
||||
}
|
||||
|
||||
public static byte[] DecryptBytes(byte[] encrypted, byte[] nonce)
|
||||
{
|
||||
if (encrypted == null || encrypted.Length < AesGcm.TagByteSizes.MaxSize || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize)
|
||||
throw new CryptographicException("Invalid encrypted data or nonce");
|
||||
|
||||
using var aes = new AesGcm(EncryptionKey);
|
||||
var decrypted = new byte[encrypted.Length - AesGcm.TagByteSizes.MaxSize];
|
||||
var tag = encrypted[..AesGcm.TagByteSizes.MaxSize];
|
||||
var ciphertext = encrypted[AesGcm.TagByteSizes.MaxSize..];
|
||||
aes.Decrypt(nonce, ciphertext, tag, decrypted);
|
||||
return decrypted;
|
||||
}
|
||||
}
|
||||
}
|
||||
359
src/GameCult.Networking/Server.cs
Normal file
359
src/GameCult.Networking/Server.cs
Normal file
|
|
@ -0,0 +1,359 @@
|
|||
using System;
|
||||
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;
|
||||
using GameCult.Logging;
|
||||
using Isopoh.Cryptography.Argon2;
|
||||
using LiteNetLib;
|
||||
using MessagePack;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
public class Server
|
||||
{
|
||||
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 int MaxLoginAttemptsPerMinute = 5;
|
||||
|
||||
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new(); // Aggregated multicast Action<T> per type
|
||||
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 CultCache _database;
|
||||
private ILogger _logger = new NullLogger();
|
||||
|
||||
public ILogger Logger
|
||||
{
|
||||
get => _logger;
|
||||
set => _logger = value ?? new NullLogger();
|
||||
}
|
||||
|
||||
private float Time => (float)_timer.Elapsed.TotalSeconds;
|
||||
|
||||
public Server(CultCache cache)
|
||||
{
|
||||
_database = cache;
|
||||
_database.RegisterIndex<PlayerData>("Email");
|
||||
Observable.Timer(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60))
|
||||
.Subscribe(_ => CleanupExpiredSessions());
|
||||
}
|
||||
|
||||
public bool IsValidEmail(string email) => Regex.IsMatch(email, EmailPattern);
|
||||
public bool IsValidUsername(string name) => Regex.IsMatch(name, UsernamePattern);
|
||||
|
||||
public void ClearMessageListeners()
|
||||
{
|
||||
_messageDelegates.Clear();
|
||||
}
|
||||
|
||||
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
|
||||
(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}");
|
||||
});
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_netManager.Stop();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_timer = Stopwatch.StartNew();
|
||||
|
||||
var listener = new EventBasedNetListener();
|
||||
_netManager = new NetManager(listener)
|
||||
{
|
||||
UnsyncedEvents = true,
|
||||
NatPunchEnabled = true
|
||||
};
|
||||
_netManager.Start(ServerPort);
|
||||
|
||||
listener.NetworkErrorEvent += (point, code) => Logger.LogInfo($"{point.Address}: Error {code}");
|
||||
|
||||
listener.ConnectionRequestEvent += request =>
|
||||
{
|
||||
if (CheckRateLimit(request.RemoteEndPoint.Address.ToString()))
|
||||
request.AcceptIfKey(Secret.ConnectionKey);
|
||||
else
|
||||
request.Reject();
|
||||
};
|
||||
|
||||
listener.PeerConnectedEvent += peer =>
|
||||
{
|
||||
Logger.LogInfo($"User Connected: {peer.Address}");
|
||||
_users.TryAdd(peer.Id, new User { Peer = peer });
|
||||
};
|
||||
|
||||
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 _);
|
||||
}
|
||||
};
|
||||
|
||||
listener.NetworkLatencyUpdateEvent += (peer, latency) =>
|
||||
{
|
||||
if (_users.TryGetValue(peer.Id, out var user))
|
||||
user.Latency = latency;
|
||||
};
|
||||
|
||||
listener.NetworkReceiveEvent += async (peer, reader, channel, method) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
var message = MessagePackSerializer.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 });
|
||||
|
||||
if (message is LoginMessage or RegisterMessage or VerifyMessage)
|
||||
{
|
||||
if (IsVerified(user))
|
||||
{
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage { Nonce = nonce, Session = Secret.EncryptBytes(user.SessionGuid.ToByteArray(), nonce) });
|
||||
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;
|
||||
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) });
|
||||
}
|
||||
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;
|
||||
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;
|
||||
}
|
||||
else
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "User Not Verified" });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError($"Message processing failed: {ex.Message}");
|
||||
}
|
||||
};
|
||||
|
||||
AddMessageListener<ChangeNameMessage>(async (message) =>
|
||||
{
|
||||
if (!IsValidUsername(message.Name))
|
||||
{
|
||||
message.Peer.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
return;
|
||||
}
|
||||
if (_database.GetIdByName<PlayerData>(message.Name) != null)
|
||||
{
|
||||
message.Peer.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
return;
|
||||
}
|
||||
if (_users.TryGetValue(message.Peer.Id, out var user))
|
||||
{
|
||||
var data = SessionData(user);
|
||||
data.Username = message.Name;
|
||||
await _database.AddAsync(data);
|
||||
}
|
||||
});
|
||||
|
||||
Logger.LogInfo($"Server started on port {ServerPort}.");
|
||||
}
|
||||
|
||||
private bool IsVerified(User u) => u != null && _sessions.ContainsKey(u.SessionGuid);
|
||||
|
||||
private PlayerData SessionData(User user) =>
|
||||
IsVerified(user) ? _sessions[user.SessionGuid].Data : null;
|
||||
|
||||
private bool CheckRateLimit(string ip)
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var windowStart = now.AddMinutes(-1);
|
||||
_loginAttempts.AddOrUpdate(
|
||||
ip,
|
||||
_ => new Queue<DateTime>(new[] { now }),
|
||||
(_, queue) =>
|
||||
{
|
||||
// Remove attempts older than 1 minute
|
||||
while (queue.Count > 0 && queue.Peek() < windowStart)
|
||||
queue.Dequeue();
|
||||
queue.Enqueue(now);
|
||||
return queue;
|
||||
});
|
||||
|
||||
return _loginAttempts[ip].Count <= MaxLoginAttemptsPerMinute;
|
||||
}
|
||||
|
||||
private Guid GenerateSessionGuid()
|
||||
{
|
||||
var guid = Guid.NewGuid();
|
||||
// TODO: Implement HMAC signing for session validation
|
||||
return guid;
|
||||
}
|
||||
|
||||
private void CleanupExpiredSessions()
|
||||
{
|
||||
foreach (var session in _sessions.ToArray())
|
||||
{
|
||||
if ((DateTime.Now - session.Value.LastUpdate).TotalSeconds > SessionTimeoutSeconds)
|
||||
{
|
||||
_sessions.TryRemove(session.Key, out _);
|
||||
if (_sessionToUserId.TryRemove(session.Key, out var userId) && _users.TryGetValue(userId, out var user))
|
||||
{
|
||||
user.Peer.Disconnect();
|
||||
_users.TryRemove(userId, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Session
|
||||
{
|
||||
public DateTime LastUpdate;
|
||||
public PlayerData Data;
|
||||
}
|
||||
|
||||
public class User
|
||||
{
|
||||
public NetPeer Peer;
|
||||
public int Latency;
|
||||
public Guid SessionGuid;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue