Framework/Networking/FrameworkRpc.cs

Typed RPC entry points for the RoleplayFramework. Handles the client handshake (Hello with protocol and framework version) and a player respawn request, both guarded by rate limits in PlayerSessions before dispatching to PlayerManager or the Lua content manifest. Includes a helper that truncates and strips control characters from untrusted strings.

using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Players;

namespace RoleplayFramework.Net;

/// <summary>
/// Typed framework messages. Client→host messages are [Rpc.Host] static methods: they run only on the host,
/// with <see cref="Rpc.Caller"/> as the engine-authenticated sender. Every handler validates before acting;
/// clients never choose what code runs, only which registered action to request.
/// </summary>
public static class FrameworkRpc
{
	// ------------------------------------------------------------ client side

	/// <summary>Sends this client's handshake. Called once the client's world scene has started.</summary>
	public static void SendHello()
	{
		RpLog.Info( "net", $"Sending handshake (protocol v{FrameworkInfo.ProtocolVersion})" );
		Hello( FrameworkInfo.ProtocolVersion, FrameworkInfo.Version );
	}

	// ------------------------------------------------------------ client → host

	/// <summary>Framework.Hello: protocol handshake. Allowed before the session is ready.</summary>
	[Rpc.Host]
	public static void Hello( int protocolVersion, string frameworkVersion )
	{
		var caller = Rpc.Caller;
		if ( !PlayerSessions.Guard( caller, "Framework.Hello", burst: 3, perSecond: 0.2, out var session, requireReady: false ) )
			return;

		var version = Bound( frameworkVersion, 32 );
		if ( PlayerSessions.CompleteHello( caller, session, protocolVersion, version ) )
			Scripting.LuaContent.SendManifestTo( caller );
	}

	/// <summary>Player.RequestRespawn: ask to be moved to a spawn point (e.g. when stuck).</summary>
	[Rpc.Host]
	public static void RequestRespawn()
	{
		var caller = Rpc.Caller;
		if ( !PlayerSessions.Guard( caller, "Player.RequestRespawn", burst: 1, perSecond: 1.0 / 5.0, out _ ) )
			return;

		PlayerManager.Current?.Respawn( caller );
	}

	// ------------------------------------------------------------ helpers

	/// <summary>Bounds untrusted strings: null → "", truncated, control characters removed.</summary>
	public static string Bound( string s, int maxLength )
	{
		if ( string.IsNullOrEmpty( s ) ) return "";
		if ( s.Length > maxLength ) s = s.Substring( 0, maxLength );
		var chars = s.ToCharArray();
		int n = 0;
		foreach ( var ch in chars ) if ( !char.IsControl( ch ) ) chars[n++] = ch;
		return new string( chars, 0, n );
	}
}