Framework/Scripting/LuaSerializer.cs

Static helper that converts Lua values (from RoleplayFramework.Lua) to a restricted JSON subset and back, for network messages and server-side storage. Serialize walks a LuaValue and rejects nil-unsafe types, NaN/inf, sparsely keyed tables and oversized output. Deserialize is a hand-written recursive-descent reader with its own limits on bytes, depth, element count and string length, throwing FormatException with a reason on bad input.

using System;
using System.Globalization;
using System.Text;
using RoleplayFramework.Lua;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Converts Lua values to and from a strict JSON subset for network messages.
/// Only nil, booleans, finite numbers, strings and tables of those are allowed. A table is either an array
/// (keys 1..n) or a string-keyed object; mixed or sparse tables are rejected, as are functions and userdata.
/// Hard limits on size, depth and element count apply in both directions, so a hostile payload can't
/// exhaust the receiver.
/// </summary>
public static class LuaSerializer
{
	public sealed record Limits( int MaxBytes, int MaxDepth, int MaxElements, int MaxStringLength );

	/// <summary>Network payloads: small and shallow.</summary>
	public static readonly Limits Network = new( 8192, 8, 512, 2048 );

	/// <summary>Server-side storage values: larger, still bounded.</summary>
	public static readonly Limits Storage = new( 512 * 1024, 16, 50_000, 64 * 1024 );

	public const int MaxBytes = 8192;
	public const int MaxDepth = 8;
	public const int MaxElements = 512;
	public const int MaxStringLength = 2048;

	// ------------------------------------------------------------ write

	public static string Serialize( LuaValue value ) => Serialize( value, Network );

	public static string Serialize( LuaValue value, Limits limits )
	{
		var sb = new StringBuilder();
		int elements = 0;
		Write( sb, value, 0, ref elements, limits );
		if ( sb.Length > limits.MaxBytes ) throw new LuaRuntimeException( $"payload too large ({sb.Length} > {limits.MaxBytes} characters)" );
		return sb.ToString();
	}

	static void Write( StringBuilder sb, LuaValue v, int depth, ref int elements, Limits L )
	{
		if ( ++elements > L.MaxElements ) throw new LuaRuntimeException( $"payload has too many values (limit {L.MaxElements})" );
		if ( sb.Length > L.MaxBytes ) throw new LuaRuntimeException( $"payload too large (limit {L.MaxBytes} characters)" );

		switch ( v.Type )
		{
			case LuaType.Nil: sb.Append( "null" ); return;
			case LuaType.Boolean: sb.Append( v.IsTruthy ? "true" : "false" ); return;
			case LuaType.Number:
				if ( double.IsNaN( v.Number ) || double.IsInfinity( v.Number ) ) throw new LuaRuntimeException( "payload cannot contain nan or inf" );
				sb.Append( v.Number.ToString( "R", CultureInfo.InvariantCulture ) );
				return;
			case LuaType.String:
				if ( v.AsString.Length > L.MaxStringLength ) throw new LuaRuntimeException( $"payload string longer than {L.MaxStringLength} characters" );
				WriteString( sb, v.AsString );
				return;
			case LuaType.Table:
				if ( depth >= L.MaxDepth ) throw new LuaRuntimeException( $"payload nested deeper than {L.MaxDepth}" );
				WriteTable( sb, v.AsTable, depth, ref elements, L );
				return;
			default:
				throw new LuaRuntimeException( $"payload cannot contain a {v.TypeName}" );
		}
	}

	static void WriteTable( StringBuilder sb, LuaTable t, int depth, ref int elements, Limits L )
	{
		int len = t.Length;
		int hash = t.HashCount;

		if ( hash == 0 )
		{
			sb.Append( '[' );
			for ( int i = 1; i <= len; i++ )
			{
				if ( i > 1 ) sb.Append( ',' );
				Write( sb, t.Get( i ), depth + 1, ref elements, L );
			}
			sb.Append( ']' );
			return;
		}

		if ( len > 0 ) throw new LuaRuntimeException( "payload tables must be either arrays or string-keyed, not both" );

		sb.Append( '{' );
		bool first = true;
		foreach ( var kv in t.Pairs() )
		{
			if ( !kv.Key.IsString ) throw new LuaRuntimeException( "payload table keys must be strings (or a 1..n array)" );
			if ( !first ) sb.Append( ',' );
			first = false;
			WriteString( sb, kv.Key.AsString );
			sb.Append( ':' );
			Write( sb, kv.Value, depth + 1, ref elements, L );
		}
		sb.Append( '}' );
	}

	static void WriteString( StringBuilder sb, string s )
	{
		sb.Append( '"' );
		foreach ( var c in s )
		{
			switch ( c )
			{
				case '"': sb.Append( "\\\"" ); break;
				case '\\': sb.Append( "\\\\" ); break;
				case '\n': sb.Append( "\\n" ); break;
				case '\r': sb.Append( "\\r" ); break;
				case '\t': sb.Append( "\\t" ); break;
				default:
					if ( c < 0x20 ) sb.Append( "\\u" ).Append( ((int)c).ToString( "x4" ) );
					else sb.Append( c );
					break;
			}
		}
		sb.Append( '"' );
	}

	// ------------------------------------------------------------ read

	/// <summary>Parses an untrusted payload. Throws <see cref="FormatException"/> with a reason on anything invalid.</summary>
	public static LuaValue Deserialize( string text ) => Deserialize( text, Network );

	public static LuaValue Deserialize( string text, Limits limits )
	{
		if ( text is null ) throw new FormatException( "payload is null" );
		if ( text.Length > limits.MaxBytes ) throw new FormatException( $"payload too large ({text.Length} > {limits.MaxBytes})" );

		var p = new Reader( text, limits );
		p.SkipWs();
		var v = p.Value( 0 );
		p.SkipWs();
		if ( !p.End ) throw new FormatException( "trailing characters after payload" );
		return v;
	}

	sealed class Reader
	{
		readonly string _s;
		readonly Limits _l;
		int _i;
		int _elements;

		public Reader( string s, Limits l ) { _s = s; _l = l; }

		public bool End => _i >= _s.Length;

		public void SkipWs()
		{
			while ( _i < _s.Length && (_s[_i] == ' ' || _s[_i] == '\n' || _s[_i] == '\r' || _s[_i] == '\t') ) _i++;
		}

		char Peek() => _i < _s.Length ? _s[_i] : '\0';

		void Expect( char c )
		{
			if ( Peek() != c ) throw new FormatException( $"expected '{c}' at {_i}" );
			_i++;
		}

		bool Literal( string word )
		{
			if ( string.CompareOrdinal( _s, _i, word, 0, word.Length ) != 0 ) return false;
			_i += word.Length;
			return true;
		}

		public LuaValue Value( int depth )
		{
			if ( ++_elements > _l.MaxElements ) throw new FormatException( $"too many values (limit {_l.MaxElements})" );
			if ( depth > _l.MaxDepth ) throw new FormatException( $"nested deeper than {_l.MaxDepth}" );

			char c = Peek();
			switch ( c )
			{
				case 'n': if ( Literal( "null" ) ) return LuaValue.Nil; break;
				case 't': if ( Literal( "true" ) ) return LuaValue.True; break;
				case 'f': if ( Literal( "false" ) ) return LuaValue.False; break;
				case '"': return LuaValue.FromString( String() );
				case '[': return Array( depth );
				case '{': return Object( depth );
				default:
					if ( c == '-' || char.IsAsciiDigit( c ) ) return Number();
					break;
			}
			throw new FormatException( $"unexpected character at {_i}" );
		}

		LuaValue Number()
		{
			int start = _i;
			if ( Peek() == '-' ) _i++;
			while ( char.IsAsciiDigit( Peek() ) || Peek() == '.' || Peek() == 'e' || Peek() == 'E' || Peek() == '+' || Peek() == '-' ) _i++;
			var text = _s.Substring( start, _i - start );
			if ( !double.TryParse( text, NumberStyles.Float, CultureInfo.InvariantCulture, out var d ) || double.IsNaN( d ) || double.IsInfinity( d ) )
				throw new FormatException( $"invalid number '{text}'" );
			return LuaValue.FromNumber( d );
		}

		string String()
		{
			Expect( '"' );
			var sb = new StringBuilder();
			while ( true )
			{
				if ( End ) throw new FormatException( "unterminated string" );
				char c = _s[_i++];
				if ( c == '"' ) break;
				if ( c != '\\' ) { sb.Append( c ); }
				else
				{
					if ( End ) throw new FormatException( "unterminated escape" );
					char e = _s[_i++];
					switch ( e )
					{
						case '"': sb.Append( '"' ); break;
						case '\\': sb.Append( '\\' ); break;
						case '/': sb.Append( '/' ); break;
						case 'n': sb.Append( '\n' ); break;
						case 'r': sb.Append( '\r' ); break;
						case 't': sb.Append( '\t' ); break;
						case 'b': sb.Append( '\b' ); break;
						case 'f': sb.Append( '\f' ); break;
						case 'u':
							{
								if ( _i + 4 > _s.Length ) throw new FormatException( "bad \\u escape" );
								int code = 0;
								for ( int k = 0; k < 4; k++ )
								{
									int h = LuaValue.HexDigit( _s[_i++] );
									if ( h < 0 ) throw new FormatException( "bad \\u escape" );
									code = code * 16 + h;
								}
								sb.Append( (char)code );
								break;
							}
						default: throw new FormatException( $"invalid escape '\\{e}'" );
					}
				}
				if ( sb.Length > _l.MaxStringLength ) throw new FormatException( $"string longer than {_l.MaxStringLength}" );
			}
			return sb.ToString();
		}

		LuaValue Array( int depth )
		{
			Expect( '[' );
			var t = new LuaTable();
			SkipWs();
			if ( Peek() == ']' ) { _i++; return t; }
			int n = 1;
			while ( true )
			{
				SkipWs();
				var v = Value( depth + 1 );
				t.Set( LuaValue.FromNumber( n++ ), v );
				SkipWs();
				if ( Peek() == ',' ) { _i++; continue; }
				Expect( ']' );
				return t;
			}
		}

		LuaValue Object( int depth )
		{
			Expect( '{' );
			var t = new LuaTable();
			SkipWs();
			if ( Peek() == '}' ) { _i++; return t; }
			while ( true )
			{
				SkipWs();
				var key = String();
				SkipWs();
				Expect( ':' );
				SkipWs();
				var v = Value( depth + 1 );
				if ( !v.IsNil ) t.Set( key, v );
				SkipWs();
				if ( Peek() == ',' ) { _i++; continue; }
				Expect( '}' );
				return t;
			}
		}
	}
}