Framework/Players/PlayerSessions.cs

Host-side registry of networked connections for the roleplay framework. Tracks each session's handshake state (awaiting Hello, awaiting content, ready, rejected), sanitizes display names, enforces per-action rate limits and violation kicks, and times out connections that never finish the handshake.

using System;
using System.Collections.Generic;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Net;

namespace RoleplayFramework.Players;

public enum SessionState
{
	/// <summary>Connected, waiting for the client's Framework.Hello.</summary>
	AwaitingHello,

	/// <summary>Hello accepted; waiting for the client to verify the content manifest and load its scripts.</summary>
	AwaitingContent,

	/// <summary>Handshake complete; allowed to play.</summary>
	Ready,

	/// <summary>Rejected and being disconnected.</summary>
	Rejected,
}

/// <summary>Host-side record of one connection. Never trusted from, or sent to, clients as-is.</summary>
public sealed class PlayerSession
{
	public Guid ConnectionId { get; init; }
	public string SteamId { get; init; }
	public string DisplayName { get; set; }
	public SessionState State { get; set; } = SessionState.AwaitingHello;
	public double ConnectedAt { get; set; }
	public string ClientVersion { get; set; }
	public int Violations { get; set; }
	public bool IsActive { get; set; }
	public bool InitialSpawnDone { get; set; }
}

/// <summary>
/// Host-side registry of connections and their handshake state, plus the shared request guard.
/// Every client→host request goes through <see cref="Guard"/>.
/// </summary>
public static class PlayerSessions
{
	public const double HelloTimeoutSeconds = 180; // counts from connecting, so it includes the client loading (or downloading) the map
	public const int MaxViolations = 20;

	static readonly Dictionary<Guid, PlayerSession> _sessions = new();
	static readonly RateLimiter _limiter = new();

	public static IReadOnlyCollection<PlayerSession> All => _sessions.Values;

	public static PlayerSession Get( Guid id ) => _sessions.TryGetValue( id, out var s ) ? s : null;

	public static PlayerSession Ensure( Connection c )
	{
		if ( _sessions.TryGetValue( c.Id, out var s ) ) return s;

		s = new PlayerSession
		{
			ConnectionId = c.Id,
			SteamId = c.SteamId.ToString(),
			DisplayName = SanitizeName( c.DisplayName ),
			ConnectedAt = RealTime.NowDouble,
		};

		// The host's own connection is trusted: it is this process.
		if ( c == Connection.Local ) s.State = SessionState.Ready;

		_sessions[c.Id] = s;
		return s;
	}

	public static void Remove( Guid id )
	{
		_sessions.Remove( id );
		_limiter.Forget( id );
	}

	public static void Clear()
	{
		_sessions.Clear();
		_limiter.Clear();
	}

	/// <summary>Display names come from the platform, but are still bounded and stripped of control characters.</summary>
	public static string SanitizeName( string name )
	{
		if ( string.IsNullOrWhiteSpace( name ) ) return "Player";
		var chars = new List<char>( Math.Min( name.Length, 32 ) );
		foreach ( var ch in name )
		{
			if ( char.IsControl( ch ) ) continue;
			chars.Add( ch );
			if ( chars.Count >= 32 ) break;
		}
		var result = new string( chars.ToArray() ).Trim();
		return result.Length == 0 ? "Player" : result;
	}

	/// <summary>
	/// Validates a client request on the host: sender identity, handshake state and rate limit.
	/// Returns the session when allowed. Rejections are logged; repeat offenders are kicked.
	/// </summary>
	public static bool Guard( Connection caller, string action, double burst, double perSecond, out PlayerSession session, bool requireReady = true )
	{
		session = null;

		if ( !Networking.IsHost && Networking.IsActive )
		{
			// Host RPCs only execute on the host; reaching here elsewhere means a programming error.
			RpLog.Error( "net", $"{action} handled on a non-host" );
			return false;
		}

		if ( caller is null )
		{
			RpLog.Warn( "net", $"Rejected {action}: no caller" );
			return false;
		}

		session = Get( caller.Id );
		if ( session is null )
		{
			RpLog.Warn( "net", $"Rejected {action} from unknown connection {caller.Id}" );
			return false;
		}

		if ( session.State == SessionState.Rejected ) return false;

		if ( requireReady && session.State != SessionState.Ready )
		{
			ReportViolation( caller, session, action, "handshake not complete" );
			return false;
		}

		if ( !_limiter.Allow( caller.Id, action, burst, perSecond ) )
		{
			ReportViolation( caller, session, action, "rate limited" );
			return false;
		}

		return true;
	}

	/// <summary>Records an invalid request. Logged (throttled); repeat offenders are kicked.</summary>
	public static void ReportViolation( Connection caller, PlayerSession session, string action, string reason )
	{
		if ( caller is null || session is null ) return;
		session.Violations++;

		// Log the first few and then every 10th, so a flood can't flood the log.
		if ( session.Violations <= 3 || session.Violations % 10 == 0 )
			RpLog.Warn( "net", $"Rejected {action} from {session.DisplayName} ({session.SteamId}): {reason} [violations: {session.Violations}]" );

		if ( session.Violations >= MaxViolations && caller != Connection.Local )
			Reject( caller, session, "Too many invalid requests" );
	}

	public static void Reject( Connection caller, PlayerSession session, string reason )
	{
		if ( session.State == SessionState.Rejected ) return;
		session.State = SessionState.Rejected;
		RpLog.Warn( "net", $"Disconnecting {session.DisplayName} ({session.SteamId}): {reason}" );
		caller.Kick( reason );
	}

	/// <summary>Handshake: check protocol compatibility and mark the session ready.</summary>
	internal static bool CompleteHello( Connection caller, PlayerSession session, int protocol, string version )
	{
		session.ClientVersion = version;

		if ( protocol != FrameworkInfo.ProtocolVersion )
		{
			Reject( caller, session, $"Incompatible framework version (server protocol v{FrameworkInfo.ProtocolVersion}, yours v{protocol}). Update the game." );
			return false;
		}

		if ( session.State != SessionState.AwaitingHello ) return false; // duplicate Hello: ignore

		session.State = SessionState.AwaitingContent;
		RpLog.Info( "net", $"Handshake accepted: {session.DisplayName} ({session.SteamId}), client {version}; sending content manifest" );
		return true;
	}

	/// <summary>Seconds a connection may take to send Hello and then verify content.</summary>
	public const double ContentTimeoutSeconds = 330; // includes a first-time cloud map download on the client

	/// <summary>Kicks connections that never completed the handshake.</summary>
	internal static void EnforceHelloTimeout()
	{
		if ( !Networking.IsHost ) return;
		double now = RealTime.NowDouble;

		foreach ( var s in new List<PlayerSession>( _sessions.Values ) )
		{
			if ( s.State != SessionState.AwaitingHello && s.State != SessionState.AwaitingContent ) continue;
			var limit = s.State == SessionState.AwaitingHello ? HelloTimeoutSeconds : ContentTimeoutSeconds;
			if ( now - s.ConnectedAt < limit ) continue;

			var c = Connection.Find( s.ConnectionId );
			if ( c is null ) { Remove( s.ConnectionId ); continue; }
			Reject( c, s, s.State == SessionState.AwaitingHello ? "Handshake timed out" : "Timed out while loading the server's scripts" );
		}
	}
}