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:
Meta Vens 2026-04-18 13:01:24 +01:00
commit 0bfc85a4f2
50 changed files with 3957 additions and 325 deletions

View file

@ -1,52 +1,89 @@
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
/// <summary>
/// Provides client-side connection, authentication, and message dispatch logic.
/// </summary>
public class Client : IDisposable
{
public event Action<string> OnError; // Hook for important user-facing feedback (e.g. via modal UI element)
private NetManager _client;
private NetPeer _peer;
/// <summary>
/// Raised when the client encounters a user-visible error.
/// </summary>
public event Action<string>? OnError; // Hook for important user-facing feedback (e.g. via modal UI element)
private NetManager? _client;
private NetPeer? _peer;
private IDisposable? _pollSubscription;
private IDisposable? _reconnectSubscription;
private bool _disposed;
private bool _manualDisconnect;
private bool _isReconnecting;
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
private Guid _sessionToken;
private string _lastHost;
private string? _sessionToken;
private string _lastHost = "localhost";
private int _lastPort;
private readonly ClientSecurityOptions _security;
private ILogger _logger = new NullLogger();
private static readonly TimeSpan ReconnectDelay = TimeSpan.FromSeconds(1);
/// <summary>
/// Gets or sets the logger used by the client.
/// </summary>
public ILogger Logger
{
get => _logger;
set => _logger = value ?? new NullLogger();
}
/// <summary>
/// Gets the last reported round-trip latency in milliseconds.
/// </summary>
public int Ping { get; private set; }
public bool Verified => _sessionToken != Guid.Empty;
public bool Connected => _client != null;
public Client()
/// <summary>
/// Gets a value indicating whether the client currently has a verified session.
/// </summary>
public bool Verified => !string.IsNullOrWhiteSpace(_sessionToken);
/// <summary>
/// Gets a value indicating whether the network manager has been created.
/// </summary>
public bool Connected => _client is { IsRunning: true } && _peer != null;
/// <summary>
/// Initializes a new client instance.
/// </summary>
/// <param name="security">Validated client security configuration. This must be provided explicitly by the caller.</param>
public Client(ClientSecurityOptions security)
{
_security = security ?? throw new ArgumentNullException(nameof(security));
OnError += s => Logger.LogError(s);
}
/// <summary>
/// Sends a message when the client is connected and authorized to do so.
/// </summary>
/// <typeparam name="T">The message type.</typeparam>
/// <param name="m">The message to send.</param>
public void Send<T>(T m) where T : Message
{
if (Connected)
if (_disposed)
{
throw new ObjectDisposedException(nameof(Client));
}
if (Connected && _peer != null)
{
if (Verified || m is LoginMessage || m is RegisterMessage || m is VerifyMessage)
{
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m as Message)}");
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m)}");
_peer.Send(m);
}
else Logger.LogError("Cannot send, client is not verified!");
@ -54,11 +91,19 @@ namespace GameCult.Networking
else Logger.LogError("Cannot send, client is not connected!");
}
/// <summary>
/// Removes all registered message listeners.
/// </summary>
public void ClearMessageListeners()
{
_messageDelegates.Clear();
}
/// <summary>
/// Adds a listener for a specific 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);
@ -73,15 +118,25 @@ namespace GameCult.Networking
});
}
/// <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 ?? (_ => { }); // Null if empty
}
}
/// <summary>
/// Sends a login request.
/// </summary>
/// <param name="auth">The email address or username.</param>
/// <param name="password">The plaintext password.</param>
public void Login(string auth, string password)
{
if (auth.Length > 0)
@ -92,8 +147,8 @@ namespace GameCult.Networking
Send(new LoginMessage
{
Nonce = nonce,
Auth = Secret.EncryptString(auth, nonce),
Password = Secret.EncryptString(password, nonce)
Auth = Secret.EncryptString(auth, nonce, _security) ?? Array.Empty<byte>(),
Password = Secret.EncryptString(password, nonce, _security) ?? Array.Empty<byte>()
});
}
else OnError?.Invoke("Password Invalid: needs to be at least 8 characters");
@ -101,6 +156,12 @@ namespace GameCult.Networking
else OnError?.Invoke("Email/Username Empty");
}
/// <summary>
/// Sends a registration request.
/// </summary>
/// <param name="email">The email address for the new account.</param>
/// <param name="username">The requested username.</param>
/// <param name="password">The plaintext password.</param>
public void Register(string email, string username, string password)
{
if (email.Length > 0)
@ -113,9 +174,9 @@ namespace GameCult.Networking
Send(new RegisterMessage
{
Nonce = nonce,
Email = Secret.EncryptString(email, nonce),
Name = Secret.EncryptString(username, nonce),
Password = Secret.EncryptString(password, nonce)
Email = Secret.EncryptString(email, nonce, _security) ?? Array.Empty<byte>(),
Name = Secret.EncryptString(username, nonce, _security) ?? Array.Empty<byte>(),
Password = Secret.EncryptString(password, nonce, _security) ?? Array.Empty<byte>()
});
}
else OnError?.Invoke("Password Invalid: needs to be at least 8 characters");
@ -125,20 +186,35 @@ namespace GameCult.Networking
else OnError?.Invoke("Email Empty");
}
/// <summary>
/// Connects the client to a server and starts polling LiteNetLib events.
/// </summary>
/// <param name="host">The remote host name or IP address.</param>
/// <param name="port">The remote server port.</param>
public void Connect(string host = "localhost", int port = 3075)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(Client));
}
_manualDisconnect = false;
_isReconnecting = false;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
_lastHost = host;
_lastPort = port;
EventBasedNetListener listener = new EventBasedNetListener();
DisposeTransport();
var 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());
_peer = _client.Connect(host, port, _security.ConnectionKey);
_pollSubscription = Observable.EveryUpdate().Subscribe(_ => _client?.PollEvents());
listener.NetworkErrorEvent += (point, code) => Logger.LogInfo($"{point.Address}: Error {code}");
listener.NetworkReceiveEvent += (peer, reader, channel, method) =>
{
@ -146,27 +222,24 @@ namespace GameCult.Networking
{
var bytes = reader.GetRemainingBytes();
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
var message = MessagePackSerializer.Deserialize<Message>(bytes);
var message = MessageSerialization.Deserialize<Message>(bytes);
var type = message.GetType();
if (!Verified)
switch (message)
{
switch (message)
{
case LoginSuccessMessage loginSuccess:
_sessionToken = new Guid(Secret.DecryptBytes(loginSuccess.Session, loginSuccess.Nonce));
break;
case ErrorMessage error:
OnError?.Invoke(error.Error);
break;
}
case LoginSuccessMessage loginSuccess:
_sessionToken = Secret.DecryptString(loginSuccess.Session, loginSuccess.Nonce, _security);
break;
case ErrorMessage error:
OnError?.Invoke(error.Error);
break;
}
if (_messageDelegates.TryGetValue(message.GetType(), out var del) && del != null)
if (_messageDelegates.TryGetValue(type, out var del) && del != null)
del.DynamicInvoke(message);
else
Logger.LogWarning($"No listener for {message.GetType().Name}");
Logger.LogWarning($"No listener for {type.Name}");
}
catch (Exception ex)
{
@ -182,19 +255,106 @@ namespace GameCult.Networking
if (Verified)
{
var nonce = Secret.NewNonce;
peer.Send(new VerifyMessage { Nonce = nonce, Session = Secret.EncryptBytes(_sessionToken.ToByteArray(), nonce) });
peer.Send(new VerifyMessage
{
Nonce = nonce,
Session = Secret.EncryptString(_sessionToken, nonce, _security) ?? Array.Empty<byte>()
});
}
};
listener.PeerDisconnectedEvent += (peer, info) =>
{
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} disconnected: {info.Reason}.");
_peer = null;
Connect(_lastHost, _lastPort);
DisposeTransport();
ScheduleReconnect();
};
listener.NetworkLatencyUpdateEvent +=
(peer, latency) => Ping = latency; //Logger($"Ping received: {latency} ms");
}
/// <summary>
/// Disconnects the client and suppresses automatic reconnect.
/// </summary>
public void Disconnect()
{
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
DisposeTransport();
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
DisposeTransport();
}
private void ScheduleReconnect()
{
if (_disposed || _manualDisconnect || string.IsNullOrWhiteSpace(_lastHost) || _isReconnecting)
{
return;
}
_isReconnecting = true;
_reconnectSubscription = Observable.Timer(ReconnectDelay).Subscribe(_ =>
{
_isReconnecting = false;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
try
{
Connect(_lastHost, _lastPort);
}
catch (Exception ex)
{
Logger.LogError($"Reconnect failed: {ex.Message}");
ScheduleReconnect();
}
});
}
private void DisposeTransport()
{
_pollSubscription?.Dispose();
_pollSubscription = null;
if (_peer != null)
{
try
{
_peer.Disconnect();
}
catch
{
// Best-effort cleanup.
}
}
if (_client != null)
{
try
{
_client.Stop();
}
finally
{
_client = null;
_peer = null;
}
}
}
}
}
}

View file

@ -0,0 +1,51 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace GameCult.Networking
{
/// <summary>
/// Carries the client-side networking configuration required to talk to a server.
/// </summary>
public sealed class ClientSecurityOptions
{
private readonly byte[] _encryptionKey;
/// <summary>
/// Shared LiteNetLib connection key and encryption seed.
/// </summary>
public string ConnectionKey { get; }
/// <summary>
/// Initializes a new client security configuration.
/// </summary>
/// <param name="connectionKey">The shared connection key used by both client and server.</param>
public ClientSecurityOptions(string connectionKey)
{
if (string.IsNullOrWhiteSpace(connectionKey))
throw new ArgumentException("Connection key must be provided.", nameof(connectionKey));
ConnectionKey = connectionKey;
_encryptionKey = ComputeSha256(Encoding.UTF8.GetBytes(connectionKey));
}
/// <summary>
/// Creates a deterministic development-only configuration.
/// </summary>
public static ClientSecurityOptions Development()
{
return new ClientSecurityOptions("gamecult-dev-connection-key");
}
internal byte[] GetEncryptionKey()
{
return _encryptionKey;
}
private static byte[] ComputeSha256(byte[] data)
{
using var sha256 = SHA256.Create();
return sha256.ComputeHash(data);
}
}
}

View file

@ -0,0 +1,20 @@
using MessagePack;
namespace GameCult.Networking
{
internal static class MessageSerialization
{
public static readonly MessagePackSerializerOptions Options =
MessagePackSerializer.DefaultOptions.WithSecurity(MessagePackSecurity.UntrustedData);
public static byte[] Serialize<T>(T message) where T : Message
{
return MessagePackSerializer.Serialize(message, Options);
}
public static T Deserialize<T>(byte[] payload)
{
return MessagePackSerializer.Deserialize<T>(payload, Options);
}
}
}

View file

@ -4,66 +4,132 @@ using MessagePack;
namespace GameCult.Networking
{
/// <summary>
/// Base type for all network messages exchanged by the client and server.
/// </summary>
[Union(0, typeof(LoginMessage)),
Union(1, typeof(RegisterMessage)),
Union(2, typeof(VerifyMessage)),
Union(3, typeof(LoginSuccessMessage)),
Union(4, typeof(ErrorMessage)),
Union(5, typeof(ChangeNameMessage)),
Union(6, typeof(ChatMessage)),
MessagePackObject]
public abstract class Message
{
[IgnoreMember] public NetPeer Peer { get; set; }
/// <summary>
/// Gets or sets the peer associated with the received message.
/// </summary>
[IgnoreMember] public NetPeer? Peer { get; set; }
}
/// <summary>
/// Base type for encrypted messages that carry a nonce.
/// </summary>
public class EncryptedMessage : Message
{
[Key(0)] public byte[] Nonce;
/// <summary>
/// Nonce used for AES-GCM encryption of the message payload.
/// </summary>
[Key(0)] public byte[] Nonce = Array.Empty<byte>();
}
/// <summary>
/// Requests authentication with an email or username and password.
/// </summary>
[MessagePackObject]
public class LoginMessage : EncryptedMessage
{
[Key(1)] public byte[] Auth;
[Key(2)] public byte[] Password;
/// <summary>
/// Encrypted email address or username.
/// </summary>
[Key(1)] public byte[] Auth = Array.Empty<byte>();
/// <summary>
/// Encrypted password payload.
/// </summary>
[Key(2)] public byte[] Password = Array.Empty<byte>();
}
/// <summary>
/// Requests registration of a new player account.
/// </summary>
[MessagePackObject]
public class RegisterMessage : EncryptedMessage
{
[Key(1)] public byte[] Email;
[Key(2)] public byte[] Password;
[Key(3)] public byte[] Name;
/// <summary>
/// Encrypted email address.
/// </summary>
[Key(1)] public byte[] Email = Array.Empty<byte>();
/// <summary>
/// Encrypted password payload.
/// </summary>
[Key(2)] public byte[] Password = Array.Empty<byte>();
/// <summary>
/// Encrypted display name payload.
/// </summary>
[Key(3)] public byte[] Name = Array.Empty<byte>();
}
/// <summary>
/// Attempts to restore a previously issued session.
/// </summary>
[MessagePackObject]
public class VerifyMessage : EncryptedMessage
{
[Key(1)] public byte[] Session;
/// <summary>
/// Encrypted session identifier.
/// </summary>
[Key(1)] public byte[] Session = Array.Empty<byte>();
}
/// <summary>
/// Indicates successful authentication or verification.
/// </summary>
[MessagePackObject]
public class LoginSuccessMessage : EncryptedMessage
{
[Key(1)] public byte[] Session;
/// <summary>
/// Encrypted session identifier.
/// </summary>
[Key(1)] public byte[] Session = Array.Empty<byte>();
}
/// <summary>
/// Sends a non-success error back to the client.
/// </summary>
[MessagePackObject]
public class ErrorMessage : Message
{
[Key(0)] public string Error;
/// <summary>
/// Human-readable error text.
/// </summary>
[Key(0)] public string Error = string.Empty;
}
/// <summary>
/// Requests a username change for the authenticated user.
/// </summary>
[MessagePackObject]
public class ChangeNameMessage : Message
{
[Key(0)] public string Name;
/// <summary>
/// Requested new username.
/// </summary>
[Key(0)] public string Name = string.Empty;
}
/// <summary>
/// Carries plain chat text.
/// </summary>
[MessagePackObject]
public class ChatMessage : Message
{
[Key(0)] public string Text;
/// <summary>
/// Chat text content.
/// </summary>
[Key(0)] public string Text = string.Empty;
}
}
}

View file

@ -3,11 +3,20 @@ using MessagePack;
namespace GameCult.Networking
{
/// <summary>
/// Adds MessagePack-based send helpers for <see cref="NetPeer"/>.
/// </summary>
public static class NetPeerExtensions
{
/// <summary>
/// Serializes and sends a message using reliable ordered delivery.
/// </summary>
/// <typeparam name="T">The concrete message type.</typeparam>
/// <param name="peer">The peer to send through.</param>
/// <param name="message">The message to serialize and send.</param>
public static void Send<T>(this NetPeer peer, T message) where T : Message
{
peer.Send(MessagePackSerializer.Serialize(message), DeliveryMethod.ReliableOrdered);
peer.Send(MessageSerialization.Serialize(message), DeliveryMethod.ReliableOrdered);
}
}
}
}

View file

@ -14,19 +14,19 @@ namespace GameCult.Networking
/// Email address of the player.
/// </summary>
[Key(1)]
public string Email;
public string Email = string.Empty;
/// <summary>
/// Password hash of the player.
/// </summary>
[Key(2)]
public string PasswordHash;
public string PasswordHash = string.Empty;
/// <summary>
/// Username of the player.
/// </summary>
[Key(3)]
public string Username;
public string Username = string.Empty;
/// <inheritdoc/>
[IgnoreMember]
@ -36,4 +36,4 @@ namespace GameCult.Networking
set => Username = value;
}
}
}
}

View file

@ -0,0 +1,183 @@
# GameCult.Networking
`GameCult.Networking` provides client/server messaging over LiteNetLib with encrypted credential exchange and signed session tokens.
It is intended for game or game-service scenarios where you want a compact transport layer with a small set of built-in authentication flows rather than a full HTTP stack.
## Scope
The library currently includes:
- a shared message contract model
- a client wrapper around LiteNetLib
- a server wrapper around LiteNetLib
- encrypted login, register, and verify flows
- signed session-token generation and validation
- `PlayerData` integration with `CultCache`
The library is focused on the built-in authentication and session flows in this repository.
## Main Types
- `Message`: base type for all wire messages
- `Client`: client connection, dispatch, reconnect, and login/register helpers
- `Server`: server dispatch, auth flow handling, rate limiting, and session refresh
- `Secret`: encryption and signed-token helper methods
- `PlayerData`: cache-backed player record type
## Authentication Model
The built-in flow is:
1. client connects with the shared LiteNetLib connection key
2. credentials are encrypted with AES-GCM using a per-message nonce
3. server validates credentials and issues a signed session token
4. client stores the encrypted session token and can send `VerifyMessage` on reconnect
5. server validates the token and re-establishes the session
The session token is signed and validated by the server.
## Runtime Secrets
`GameCult.Networking` uses:
- `GAMECULT_CONNECTION_KEY`
- `GAMECULT_SESSION_SIGNING_SECRET`
Production requirements:
- set both before constructing `Server` without explicit `ServerSecurityOptions`
- use high-entropy random values, not human-memorable strings
- keep `GAMECULT_SESSION_SIGNING_SECRET` in your deployment platform's secret store rather than in source control or appsettings checked into the repo
- distribute `GAMECULT_CONNECTION_KEY` to clients through your build or asset pipeline, not through runtime environment variables on shipped clients
- partial configuration is rejected by `ServerSecurityOptions.FromEnvironment()`
Recommended format:
- 32 or more random bytes per value
- store as Base64/Base64Url text if needed
Example PowerShell generation:
```powershell
[Convert]::ToBase64String((1..32 | ForEach-Object { Get-Random -Maximum 256 }))
```
Example environment assignment in PowerShell:
```powershell
$env:GAMECULT_CONNECTION_KEY = "<random-base64-value>"
$env:GAMECULT_SESSION_SIGNING_SECRET = "<different-random-base64-value>"
```
Deployment model:
- the client and server must share the same `GAMECULT_CONNECTION_KEY`
- the server alone needs `GAMECULT_SESSION_SIGNING_SECRET`
- `GAMECULT_CONNECTION_KEY` is shared protocol configuration, not a server-only secret
- rotating `GAMECULT_CONNECTION_KEY` requires a coordinated client/server rollout or multi-key server support during migration
- `GAMECULT_SESSION_SIGNING_SECRET` can be rotated server-side with the usual session invalidation tradeoffs
Strict production-style configuration:
```csharp
using GameCult.Caching;
using GameCult.Networking;
var cache = new CultCache();
var security = ServerSecurityOptions.FromEnvironment();
var server = new Server(cache, security);
```
Explicit local-development server configuration:
```csharp
using GameCult.Caching;
using GameCult.Networking;
var cache = new CultCache();
var security = ServerSecurityOptions.Development();
var server = new Server(cache, security);
```
Explicit client configuration:
```csharp
using GameCult.Networking;
var security = new ClientSecurityOptions("<matching-connection-key>");
var client = new Client(security);
```
Use `ServerSecurityOptions.Development()` only for local development and tests. `Client` does not read environment variables.
## Basic Server Usage
```csharp
using GameCult.Caching;
using GameCult.Logging;
using GameCult.Networking;
var cache = new CultCache();
var server = new Server(cache)
{
Logger = new ConsoleLogger()
};
server.AddMessageListener<ChatMessage>(message =>
{
server.Logger.LogInfo($"Chat: {message.Text}");
});
server.Start();
```
## Basic Client Usage
```csharp
using GameCult.Logging;
using GameCult.Networking;
var client = new Client(new ClientSecurityOptions("<matching-connection-key>"))
{
Logger = new ConsoleLogger()
};
client.OnError += error => client.Logger.LogError($"Client error: {error}");
client.AddMessageListener<ChatMessage>(message => client.Logger.LogInfo($"Chat: {message.Text}"));
client.Connect("localhost", 3075);
client.Login("user@example.com", "correct horse battery staple");
```
## Reconnect Behavior
The client:
- disposes its prior polling subscription before reconnecting
- stops the prior `NetManager`
- schedules reconnect with a short delay
- automatically re-verifies using the stored signed session token
## Important Constraints
- `Server` currently centers on `PlayerData` as the built-in account model.
- Message authorization is based on the built-in verify/login/register flow.
- Transport is LiteNetLib, so this is not a drop-in substitute for HTTP or WebSocket stacks.
## Message Example
Messages derive from `Message` and are MessagePack-serializable:
```csharp
using GameCult.Networking;
using MessagePack;
[MessagePackObject]
public class CustomPingMessage : Message
{
[Key(0)] public string Value = string.Empty;
}
```
If you extend the built-in message set, update the union and serialization model accordingly.

View file

@ -1,15 +1,39 @@
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace GameCult.Networking
{
/// <summary>
/// Provides shared encryption helpers and connection secrets for the networking layer.
/// </summary>
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 Lazy<ServerSecurityOptions> DefaultOptions =
new(() => ServerSecurityOptions.FromEnvironment());
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
/// <summary>
/// Configures the default server security options used by overloads that do not take an explicit options instance.
/// </summary>
public static void ConfigureDefault(ServerSecurityOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
_configuredOptions = options;
}
private static ServerSecurityOptions? _configuredOptions;
/// <summary>
/// Shared LiteNetLib connection key from the configured default options.
/// </summary>
public static string ConnectionKey => GetDefaultOptions().ConnectionKey;
/// <summary>
/// Gets a newly generated nonce suitable for AES-GCM operations.
/// </summary>
public static byte[] NewNonce
{
get
@ -20,18 +44,51 @@ namespace GameCult.Networking
}
}
public static byte[] EncryptString(string input, byte[] nonce)
/// <summary>
/// Encrypts a string using AES-GCM.
/// </summary>
/// <param name="input">The plaintext string to encrypt.</param>
/// <param name="nonce">The nonce to use for the operation.</param>
/// <returns>The encrypted payload, or <c>null</c> when <paramref name="input"/> is null or empty.</returns>
public static byte[]? EncryptString(string? input, byte[] nonce) =>
EncryptString(input, nonce, GetDefaultOptions());
/// <summary>
/// Encrypts a string using AES-GCM.
/// </summary>
public static byte[]? EncryptString(string? input, byte[] nonce, ClientSecurityOptions options)
{
if (string.IsNullOrEmpty(input)) return null;
return EncryptBytes(Encoding.UTF8.GetBytes(input), nonce);
return EncryptBytes(Encoding.UTF8.GetBytes(input), nonce, options);
}
public static byte[] EncryptBytes(byte[] input, byte[] nonce)
/// <summary>
/// Encrypts a string using AES-GCM.
/// </summary>
public static byte[]? EncryptString(string? input, byte[] nonce, ServerSecurityOptions options)
{
if (string.IsNullOrEmpty(input)) return null;
return EncryptBytes(Encoding.UTF8.GetBytes(input), nonce, options);
}
/// <summary>
/// Encrypts a byte array using AES-GCM.
/// </summary>
/// <param name="input">The plaintext bytes to encrypt.</param>
/// <param name="nonce">The nonce to use for the operation.</param>
/// <returns>The authentication tag followed by the ciphertext.</returns>
public static byte[] EncryptBytes(byte[] input, byte[] nonce) =>
EncryptBytes(input, nonce, GetDefaultOptions());
/// <summary>
/// Encrypts a byte array using AES-GCM.
/// </summary>
public static byte[] EncryptBytes(byte[] input, byte[] nonce, ClientSecurityOptions options)
{
if (input == null || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize)
throw new CryptographicException("Invalid input or nonce");
using var aes = new AesGcm(EncryptionKey);
using var aes = new AesGcm(options.GetEncryptionKey());
var ciphertext = new byte[input.Length];
var tag = new byte[AesGcm.TagByteSizes.MaxSize];
aes.Encrypt(nonce, input, ciphertext, tag);
@ -41,24 +98,214 @@ namespace GameCult.Networking
return result;
}
public static string DecryptString(byte[] encrypted, byte[] nonce)
/// <summary>
/// Encrypts a byte array using AES-GCM.
/// </summary>
public static byte[] EncryptBytes(byte[] input, byte[] nonce, ServerSecurityOptions options)
{
if (input == null || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize)
throw new CryptographicException("Invalid input or nonce");
using var aes = new AesGcm(options.GetEncryptionKey());
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;
}
/// <summary>
/// Decrypts an encrypted UTF-8 string payload.
/// </summary>
/// <param name="encrypted">The encrypted bytes produced by the corresponding string or byte encryption overloads.</param>
/// <param name="nonce">The nonce used during encryption.</param>
/// <returns>The decrypted string, or <c>null</c> when the inputs are invalid.</returns>
public static string? DecryptString(byte[]? encrypted, byte[]? nonce) =>
DecryptString(encrypted, nonce, GetDefaultOptions());
/// <summary>
/// Decrypts an encrypted UTF-8 string payload.
/// </summary>
public static string? DecryptString(byte[]? encrypted, byte[]? nonce, ClientSecurityOptions options)
{
if (encrypted == null || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize) return null;
var decrypted = DecryptBytes(encrypted, nonce);
var decrypted = DecryptBytes(encrypted, nonce, options);
return Encoding.UTF8.GetString(decrypted);
}
public static byte[] DecryptBytes(byte[] encrypted, byte[] nonce)
/// <summary>
/// Decrypts an encrypted UTF-8 string payload.
/// </summary>
public static string? DecryptString(byte[]? encrypted, byte[]? nonce, ServerSecurityOptions options)
{
if (encrypted == null || nonce == null || nonce.Length != AesGcm.NonceByteSizes.MaxSize) return null;
var decrypted = DecryptBytes(encrypted, nonce, options);
return Encoding.UTF8.GetString(decrypted);
}
/// <summary>
/// Decrypts an AES-GCM payload into raw bytes.
/// </summary>
/// <param name="encrypted">The encrypted bytes containing the authentication tag prefix.</param>
/// <param name="nonce">The nonce used during encryption.</param>
/// <returns>The decrypted plaintext bytes.</returns>
public static byte[] DecryptBytes(byte[] encrypted, byte[] nonce) =>
DecryptBytes(encrypted, nonce, GetDefaultOptions());
/// <summary>
/// Decrypts an AES-GCM payload into raw bytes.
/// </summary>
public static byte[] DecryptBytes(byte[] encrypted, byte[] nonce, ClientSecurityOptions options)
{
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);
using var aes = new AesGcm(options.GetEncryptionKey());
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;
}
/// <summary>
/// Decrypts an AES-GCM payload into raw bytes.
/// </summary>
public static byte[] DecryptBytes(byte[] encrypted, byte[] nonce, ServerSecurityOptions options)
{
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(options.GetEncryptionKey());
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;
}
/// <summary>
/// Creates a signed session token for the supplied user.
/// </summary>
/// <param name="userId">The authenticated user identifier.</param>
/// <param name="expiresAtUtc">The UTC expiration time for the token.</param>
/// <returns>A tamper-evident session token.</returns>
public static string CreateSessionToken(Guid userId, DateTimeOffset expiresAtUtc) =>
CreateSessionToken(userId, expiresAtUtc, GetDefaultOptions());
/// <summary>
/// Creates a signed session token for the supplied user.
/// </summary>
public static string CreateSessionToken(Guid userId, DateTimeOffset expiresAtUtc, ServerSecurityOptions options)
{
var payload = $"{userId:N}|{expiresAtUtc.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}";
var payloadBytes = Encoding.UTF8.GetBytes(payload);
var signatureBytes = ComputeHmacSha256(options.GetSessionSigningKey(), payloadBytes);
return $"{ToBase64Url(payloadBytes)}.{ToBase64Url(signatureBytes)}";
}
/// <summary>
/// Validates and parses a signed session token.
/// </summary>
/// <param name="token">The token to validate.</param>
/// <param name="userId">The extracted user identifier.</param>
/// <param name="expiresAtUtc">The extracted UTC expiration time.</param>
/// <returns><c>true</c> when the token is valid and unexpired.</returns>
public static bool TryValidateSessionToken(string? token, out Guid userId, out DateTimeOffset expiresAtUtc) =>
TryValidateSessionToken(token, GetDefaultOptions(), out userId, out expiresAtUtc);
/// <summary>
/// Validates and parses a signed session token.
/// </summary>
public static bool TryValidateSessionToken(
string? token,
ServerSecurityOptions options,
out Guid userId,
out DateTimeOffset expiresAtUtc)
{
userId = Guid.Empty;
expiresAtUtc = DateTimeOffset.MinValue;
if (string.IsNullOrWhiteSpace(token))
return false;
var parts = token.Split('.');
if (parts.Length != 2)
return false;
try
{
var payloadBytes = FromBase64Url(parts[0]);
var signatureBytes = FromBase64Url(parts[1]);
var expectedSignature = ComputeHmacSha256(options.GetSessionSigningKey(), payloadBytes);
if (!CryptographicOperations.FixedTimeEquals(signatureBytes, expectedSignature))
return false;
var payload = Encoding.UTF8.GetString(payloadBytes);
var payloadParts = payload.Split('|');
if (payloadParts.Length != 2 ||
!Guid.TryParseExact(payloadParts[0], "N", out userId) ||
!long.TryParse(payloadParts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var expiryUnixSeconds))
{
userId = Guid.Empty;
return false;
}
expiresAtUtc = DateTimeOffset.FromUnixTimeSeconds(expiryUnixSeconds);
return expiresAtUtc > DateTimeOffset.UtcNow;
}
catch (FormatException)
{
userId = Guid.Empty;
expiresAtUtc = DateTimeOffset.MinValue;
return false;
}
}
private static string ToBase64Url(byte[] bytes)
{
return Convert.ToBase64String(bytes)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
private static byte[] FromBase64Url(string input)
{
var padded = input
.Replace('-', '+')
.Replace('_', '/');
switch (padded.Length % 4)
{
case 2:
padded += "==";
break;
case 3:
padded += "=";
break;
}
return Convert.FromBase64String(padded);
}
private static byte[] ComputeSha256(byte[] data)
{
using var sha256 = SHA256.Create();
return sha256.ComputeHash(data);
}
private static byte[] ComputeHmacSha256(byte[] key, byte[] data)
{
using var hmac = new HMACSHA256(key);
return hmac.ComputeHash(data);
}
private static ServerSecurityOptions GetDefaultOptions()
{
return _configuredOptions ?? DefaultOptions.Value;
}
}
}
}

View file

@ -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;
}
}
}

View file

@ -0,0 +1,127 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace GameCult.Networking
{
/// <summary>
/// Carries the server-side networking configuration and server-only signing secret.
/// </summary>
public sealed class ServerSecurityOptions
{
/// <summary>
/// Environment variable name for the LiteNetLib connection key.
/// </summary>
public const string ConnectionKeyEnvironmentVariable = "GAMECULT_CONNECTION_KEY";
/// <summary>
/// Environment variable name for the session-token signing secret.
/// </summary>
public const string SessionSigningSecretEnvironmentVariable = "GAMECULT_SESSION_SIGNING_SECRET";
private readonly byte[] _encryptionKey;
private readonly byte[] _sessionSigningKey;
/// <summary>
/// Shared LiteNetLib connection key and encryption seed.
/// </summary>
public string ConnectionKey { get; }
/// <summary>
/// Gets a value indicating whether the options were created for explicit development use.
/// </summary>
public bool IsDevelopment { get; }
/// <summary>
/// Initializes a new server security configuration.
/// </summary>
public ServerSecurityOptions(string connectionKey, string sessionSigningSecret, bool isDevelopment = false)
{
if (string.IsNullOrWhiteSpace(connectionKey))
throw new ArgumentException("Connection key must be provided.", nameof(connectionKey));
if (string.IsNullOrWhiteSpace(sessionSigningSecret))
throw new ArgumentException("Session signing secret must be provided.", nameof(sessionSigningSecret));
ConnectionKey = connectionKey;
IsDevelopment = isDevelopment;
_encryptionKey = ComputeSha256(Encoding.UTF8.GetBytes(connectionKey));
_sessionSigningKey = ComputeSha256(Encoding.UTF8.GetBytes(sessionSigningSecret));
}
/// <summary>
/// Creates a strict production-style configuration from environment variables.
/// </summary>
/// <param name="allowDevelopmentDefaults">
/// When <c>true</c>, returns <see cref="Development"/> if both environment variables are absent.
/// </param>
public static ServerSecurityOptions FromEnvironment(bool allowDevelopmentDefaults = false)
{
var connectionKey = Environment.GetEnvironmentVariable(ConnectionKeyEnvironmentVariable);
var sessionSigningSecret = Environment.GetEnvironmentVariable(SessionSigningSecretEnvironmentVariable);
var missingConnectionKey = string.IsNullOrWhiteSpace(connectionKey);
var missingSessionSigningSecret = string.IsNullOrWhiteSpace(sessionSigningSecret);
if (missingConnectionKey && missingSessionSigningSecret)
{
if (allowDevelopmentDefaults)
return Development();
throw new InvalidOperationException(
"Server security configuration is not configured. Set " +
$"{ConnectionKeyEnvironmentVariable} and {SessionSigningSecretEnvironmentVariable}, " +
"or explicitly use ServerSecurityOptions.Development() for local development.");
}
if (missingConnectionKey || missingSessionSigningSecret)
{
throw new InvalidOperationException(
"Server security configuration is partially configured. Missing: " +
string.Join(", ", GetMissingVariables(missingConnectionKey, missingSessionSigningSecret)) + ".");
}
return new ServerSecurityOptions(connectionKey!, sessionSigningSecret!);
}
/// <summary>
/// Creates a deterministic development-only configuration.
/// </summary>
public static ServerSecurityOptions Development()
{
return new ServerSecurityOptions(
"gamecult-dev-connection-key",
"gamecult-dev-session-signing-secret",
true);
}
internal byte[] GetEncryptionKey()
{
return _encryptionKey;
}
internal byte[] GetSessionSigningKey()
{
return _sessionSigningKey;
}
internal ClientSecurityOptions ToClientOptions()
{
return new ClientSecurityOptions(ConnectionKey);
}
private static byte[] ComputeSha256(byte[] data)
{
using var sha256 = SHA256.Create();
return sha256.ComputeHash(data);
}
private static string[] GetMissingVariables(bool missingConnectionKey, bool missingSessionSigningSecret)
{
if (missingConnectionKey && missingSessionSigningSecret)
return [ConnectionKeyEnvironmentVariable, SessionSigningSecretEnvironmentVariable];
if (missingConnectionKey)
return [ConnectionKeyEnvironmentVariable];
return [SessionSigningSecretEnvironmentVariable];
}
}
}