{"TotalCount":19,"Files":[{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistCommands.cs","FileName":"SboxlistCommands.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System.Text;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Console commands for the owner (type them in the server console, or in the editor console\n/// while playing). They act only on the host; on a client they say so and do nothing.\n/// \u003C/summary\u003E\npublic static class SboxlistCommands\n{\n\tstatic SboxlistService HostService()\n\t{\n\t\tif ( !Networking.IsHost )\n\t\t{\n\t\t\tLog.Warning( \u0022[sboxlist] run this on the server (host), not on a client\u0022 );\n\t\t\treturn null;\n\t\t}\n\n\t\tvar service = SboxlistService.Instance;\n\t\tif ( service is null ) Log.Warning( \u0022[sboxlist] there is no SboxlistService component in the scene\u0022 );\n\t\treturn service;\n\t}\n\n\t[ConCmd( \u0022sbl_status\u0022 )]\n\tpublic static void Status()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tLog.Info( $\u0022[sboxlist] {SboxlistService.Version}, {service.Sites.Count} site(s), config {SboxlistConfig.FullPath()}\u0022 );\n\t\tforeach ( var site in service.Sites ) Log.Info( \u0022[sboxlist] \u0022 \u002B site.Describe() );\n\t}\n\n\t[ConCmd( \u0022sbl_info\u0022 )]\n\tpublic static void Info()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tforeach ( var site in service.Sites ) _ = site.InfoAsync();\n\t}\n\n\t[ConCmd( \u0022sbl_heartbeat\u0022 )]\n\tpublic static void Heartbeat()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tforeach ( var site in service.Sites ) site.ForceHeartbeat();\n\t\tLog.Info( \u0022[sboxlist] heartbeat on the next frame\u0022 );\n\t}\n\n\t[ConCmd( \u0022sbl_testvote\u0022 )]\n\tpublic static void Testvote()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tforeach ( var site in service.Sites ) _ = site.RequestTestvoteAsync();\n\t}\n\n\t[ConCmd( \u0022sbl_reload\u0022 )]\n\tpublic static void Reload()\n\t{\n\t\tvar service = HostService();\n\t\tservice?.Reload();\n\t}\n\n\t/// \u003Csummary\u003EVerifies the HMAC-SHA256 implementation against fixed RFC 4231 and protocol v1 vectors offline.\u003C/summary\u003E\n\t[ConCmd( \u0022sbl_hmac_selftest\u0022 )]\n\tpublic static void HmacSelftest()\n\t{\n\t\tvar rfc = SboxlistCrypto.Hex( SboxlistCrypto.HmacSha256( Encoding.UTF8.GetBytes( \u0022Jefe\u0022 ), Encoding.UTF8.GetBytes( \u0022what do ya want for nothing?\u0022 ) ) );\n\t\tvar rfcOk = rfc == \u00225bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843\u0022;\n\t\tLog.Info( $\u0022[sboxlist] RFC 4231 case 2: {rfc} {(rfcOk ? \u0022PASS\u0022 : \u0022FAIL\u0022)}\u0022 );\n\n\t\tvar key = SboxlistCrypto.KeyFromToken( \u0022sbs_\u0022 \u002B new string( \u0027A\u0027, 43 ) );\n\t\tvar body = Encoding.UTF8.GetBytes( \u0022{\\\u0022v\\\u0022:1,\\\u0022type\\\u0022:\\\u0022heartbeat\\\u0022}\u0022 );\n\t\tvar sig = SboxlistCrypto.Signature( key, \u00223f2a9c1e-5b7d-4e8a-9c0d-1a2b3c4d5e6f\u0022, \u00221790000000\u0022, \u0022abcdefghijklmnop\u0022, body );\n\t\tvar sigOk = sig == \u002262c1de08862566ae6cc2008bcef3a3bccb56c6e0e53897f48fc08883ae2cccfd\u0022;\n\t\tLog.Info( $\u0022[sboxlist] protocol v1 vector: {sig} {(sigOk ? \u0022PASS\u0022 : \u0022FAIL\u0022)}\u0022 );\n\t}\n\n\t/// \u003Csummary\u003ESafe built-in target for testing console-command rewards: logs the resolved SteamID64 and amount.\u003C/summary\u003E\n\t[ConCmd( \u0022sbl_test_reward\u0022 )]\n\tpublic static void TestReward( string steamId, int amount )\n\t{\n\t\tLog.Info( $\u0022[sboxlist] sbl_test_reward ran: steamid {steamId}, amount {amount}\u0022 );\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"JsonRead.cs","FileName":"JsonRead.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System.Text.Json.Nodes;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003EReads fields from untrusted JSON without throwing. A wrong type reads as null.\u003C/summary\u003E\ninternal static class JsonRead\n{\n\tpublic static string Str( JsonNode node, string key )\n\t{\n\t\ttry { return node?[key]?.GetValue\u003Cstring\u003E(); }\n\t\tcatch { return null; }\n\t}\n\n\tpublic static long? Long( JsonNode node, string key )\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar value = node?[key];\n\t\t\tif ( value is null ) return null;\n\t\t\treturn value.GetValue\u003Clong\u003E();\n\t\t}\n\t\tcatch { return null; }\n\t}\n\n\tpublic static bool? Bool( JsonNode node, string key )\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar value = node?[key];\n\t\t\tif ( value is null ) return null;\n\t\t\treturn value.GetValue\u003Cbool\u003E();\n\t\t}\n\t\tcatch { return null; }\n\t}\n\n\tpublic static JsonNode Get( JsonNode node, string key )\n\t{\n\t\ttry { return node?[key]; }\n\t\tcatch { return null; }\n\t}\n\n\tpublic static JsonNode Parse( string text )\n\t{\n\t\ttry { return string.IsNullOrEmpty( text ) ? null : JsonNode.Parse( text ); }\n\t\tcatch { return null; }\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// One message of a poll or join answer. Protocol v1 (sboxlist.com) sends each message as JSON\n\t/// text, the v0.2 spec sends an object. Returns the object, or null for anything else.\n\t/// \u003C/summary\u003E\n\tpublic static JsonNode Message( JsonNode element ) =\u003E Message( element, out _ );\n\n\tpublic static JsonNode Message( JsonNode element, out int rawChars )\n\t{\n\t\trawChars = 0;\n\t\tif ( element is null ) return null;\n\t\tif ( element is JsonObject )\n\t\t{\n\t\t\trawChars = element.ToJsonString().Length;\n\t\t\treturn element;\n\t\t}\n\t\ttry\n\t\t{\n\t\t\tvar text = element.GetValue\u003Cstring\u003E();\n\t\t\tif ( text is null ) return null;\n\t\t\trawChars = text.Length;\n\t\t\treturn JsonNode.Parse( text ) as JsonObject;\n\t\t}\n\t\tcatch { return null; }\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistCrypto.cs","FileName":"SboxlistCrypto.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Hashing for the protocol. Only SHA256 is on the s\u0026amp;box whitelist (HMACSHA256 and\n/// RandomNumberGenerator are not), so HMAC is built by hand (RFC 2104) and nonces come from Guid.\n/// \u003C/summary\u003E\npublic static class SboxlistCrypto\n{\n\tpublic static string Hex( byte[] bytes ) =\u003E Convert.ToHexString( bytes ).ToLowerInvariant();\n\n\tpublic static byte[] Sha256( byte[] data ) =\u003E SHA256.HashData( data );\n\n\tpublic static string Sha256Hex( byte[] data ) =\u003E Hex( Sha256( data ) );\n\n\t/// \u003Csummary\u003EHMAC-SHA256 from SHA256 alone: H((K0 ^ opad) || H((K0 ^ ipad) || message)).\u003C/summary\u003E\n\tpublic static byte[] HmacSha256( byte[] key, byte[] message )\n\t{\n\t\tconst int block = 64;\n\t\tvar k = key.Length \u003E block ? Sha256( key ) : key;\n\n\t\tvar inner = new byte[block \u002B message.Length];\n\t\tvar outer = new byte[block \u002B 32];\n\n\t\tfor ( var i = 0; i \u003C block; i\u002B\u002B )\n\t\t{\n\t\t\tvar b = i \u003C k.Length ? k[i] : (byte)0;\n\t\t\tinner[i] = (byte)(b ^ 0x36);\n\t\t\touter[i] = (byte)(b ^ 0x5c);\n\t\t}\n\n\t\tfor ( var i = 0; i \u003C message.Length; i\u002B\u002B )\n\t\t\tinner[block \u002B i] = message[i];\n\n\t\tvar innerHash = Sha256( inner );\n\t\tfor ( var i = 0; i \u003C 32; i\u002B\u002B )\n\t\t\touter[block \u002B i] = innerHash[i];\n\n\t\treturn Sha256( outer );\n\t}\n\n\t/// \u003Csummary\u003EA nonce only has to be unique: 32 hex characters from a new Guid.\u003C/summary\u003E\n\tpublic static string NewNonce() =\u003E Guid.NewGuid().ToString( \u0022N\u0022 );\n\n\t/// \u003Csummary\u003EThe HMAC key of variant B: the 32 bytes of sha256(token). The site stores the same.\u003C/summary\u003E\n\tpublic static byte[] KeyFromToken( string token ) =\u003E Sha256( Encoding.UTF8.GetBytes( token ) );\n\n\t/// \u003Csummary\u003EVariant B signature over \u0022sbl1\\n serverId \\n timestamp \\n nonce \\n hex(sha256(body))\u0022.\u003C/summary\u003E\n\tpublic static string Signature( byte[] key, string serverId, string timestamp, string nonce, byte[] body )\n\t{\n\t\tvar canonical = \u0022sbl1\\n\u0022 \u002B serverId \u002B \u0022\\n\u0022 \u002B timestamp \u002B \u0022\\n\u0022 \u002B nonce \u002B \u0022\\n\u0022 \u002B Sha256Hex( body );\n\t\treturn Hex( HmacSha256( key, Encoding.UTF8.GetBytes( canonical ) ) );\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistEvents.cs","FileName":"SboxlistEvents.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003EA vote that arrived from a site (on the host).\u003C/summary\u003E\npublic sealed class VoteInfo\n{\n\tpublic string SiteId { get; init; }\n\tpublic string Id { get; init; }\n\t/// \u003Csummary\u003E\u0022steam\u0022 or \u0022name\u0022.\u003C/summary\u003E\n\tpublic string IdentityKind { get; init; }\n\t/// \u003Csummary\u003EA SteamID64 (as text) or the name the voter typed.\u003C/summary\u003E\n\tpublic string IdentityKey { get; init; }\n\tpublic string At { get; init; }\n\tpublic bool IsTest { get; init; }\n\t/// \u003Csummary\u003EThe voter\u0027s active Connection if they are online right now; null when offline or for a test vote.\u003C/summary\u003E\n\tpublic Connection OnlinePlayer { get; init; }\n}\n\n/// \u003Csummary\u003E\n/// An item or currency reward for the game to hand out on the host (ISboxlistListener.OnVoteReward\n/// or SboxlistEvents.RewardReceived). Call Refuse(reason) if the reward cannot be granted so the\n/// site records ok:false with the reason in the owner\u0027s reward log.\n/// \u003C/summary\u003E\npublic sealed class RewardInfo\n{\n\tpublic string SiteId { get; init; }\n\tpublic string Id { get; init; }\n\tpublic string VoteId { get; init; }\n\tpublic string RuleId { get; init; }\n\t/// \u003Csummary\u003E\u0022item\u0022 or \u0022currency\u0022.\u003C/summary\u003E\n\tpublic string Kind { get; init; }\n\tpublic string Payload { get; init; }\n\tpublic long Amount { get; init; }\n\t/// \u003Csummary\u003E\u0022steam\u0022 or \u0022name\u0022.\u003C/summary\u003E\n\tpublic string IdentityKind { get; init; }\n\t/// \u003Csummary\u003EA SteamID64 (as text) or the name the voter typed.\u003C/summary\u003E\n\tpublic string IdentityKey { get; init; }\n\t/// \u003Csummary\u003EThe player who joined and gets the reward.\u003C/summary\u003E\n\tpublic Connection Player { get; init; }\n\t/// \u003Csummary\u003ESet to true by your listener when handled (automatically set for RewardReceived subscribers).\u003C/summary\u003E\n\tpublic bool Handled { get; set; }\n\t/// \u003Csummary\u003ENon-null when the game refused the reward via Refuse(reason).\u003C/summary\u003E\n\tpublic string Error { get; private set; }\n\n\t/// \u003Csummary\u003EMarks this reward as refused; the library sends ok:false with this reason in votes/ack.\u003C/summary\u003E\n\tpublic void Refuse( string reason )\n\t{\n\t\tHandled = true;\n\t\tError = string.IsNullOrWhiteSpace( reason ) ? \u0022refused by game\u0022 : reason.Trim();\n\t}\n}\n\n/// \u003Csummary\u003E\n/// A chat, toast or broadcast message delivered to a client (ISboxlistNotificationListener or\n/// SboxlistEvents.NotificationReceived). Set Handled = true in your custom UI to suppress the\n/// default Sandbox.Platform.Chat fallback.\n/// \u003C/summary\u003E\npublic sealed class VoteNotification\n{\n\t/// \u003Csummary\u003E\u0022chat\u0022 or \u0022toast\u0022.\u003C/summary\u003E\n\tpublic string Kind { get; init; }\n\t/// \u003Csummary\u003ETrue when sent to everyone via BroadcastChat / BroadcastToast; false when sent to one voter.\u003C/summary\u003E\n\tpublic bool IsBroadcast { get; init; }\n\t/// \u003Csummary\u003EFormatted message text with {name}, {steamid} and {amount} already replaced.\u003C/summary\u003E\n\tpublic string Text { get; init; }\n\t/// \u003Csummary\u003ESet to true to suppress the default Platform.Chat line.\u003C/summary\u003E\n\tpublic bool Handled { get; set; }\n}\n\n/// \u003Csummary\u003E\n/// Idiomatic s\u0026amp;box scene event interface for host-side vote announcements and item/currency\n/// rewards. Implement on any Component or GameObjectSystem in your active scene \u2014 no manual \u002B= / -=\n/// needed and safe across hotloads.\n/// \u003C/summary\u003E\npublic interface ISboxlistListener : ISceneEvent\u003CISboxlistListener\u003E\n{\n\tvoid OnVoteReceived( VoteInfo vote ) { }\n\tvoid OnVoteReward( RewardInfo reward ) { }\n}\n\n/// \u003Csummary\u003E\n/// Idiomatic s\u0026amp;box scene event interface for client-side custom notifications. Implement on any\n/// Razor Panel (@implements ISboxlistNotificationListener), PanelComponent or Component in your\n/// scene, and set notification.Handled = true to replace the default chat output with your own UI.\n/// \u003C/summary\u003E\npublic interface ISboxlistNotificationListener : ISceneEvent\u003CISboxlistNotificationListener\u003E\n{\n\tvoid OnVoteNotification( VoteNotification notification ) { }\n}\n\n/// \u003Csummary\u003E\n/// Static hooks for games that prefer C# events over scene interfaces (ISboxlistListener /\n/// ISboxlistNotificationListener). VoteReceived and RewardReceived fire on the host;\n/// NotificationReceived and ToastShown fire on the target client.\n/// \u003C/summary\u003E\npublic static class SboxlistEvents\n{\n\tpublic static event Action\u003CVoteInfo\u003E VoteReceived;\n\tpublic static event Action\u003CRewardInfo\u003E RewardReceived;\n\tpublic static event Action\u003CVoteNotification\u003E NotificationReceived;\n\tpublic static event Action\u003Cstring\u003E ToastShown;\n\n\tinternal static void RaiseVote( VoteInfo vote )\n\t{\n\t\tSafe( () =\u003E ISceneEvent\u003CISboxlistListener\u003E.Post( x =\u003E x.OnVoteReceived( vote ) ), \u0022ISboxlistListener.OnVoteReceived\u0022 );\n\t\tSafe( () =\u003E VoteReceived?.Invoke( vote ), \u0022VoteReceived\u0022 );\n\t}\n\n\tinternal static void DispatchReward( RewardInfo reward )\n\t{\n\t\ttry\n\t\t{\n\t\t\tISceneEvent\u003CISboxlistListener\u003E.Post( x =\u003E x.OnVoteReward( reward ) );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Warning( $\u0022[sboxlist] an ISboxlistListener.OnVoteReward handler threw: {e.Message}\u0022 );\n\t\t\treward.Refuse( \u0022handler threw: \u0022 \u002B e.Message );\n\t\t\treturn;\n\t\t}\n\n\t\tvar handlers = RewardReceived;\n\t\tif ( handlers is not null )\n\t\t{\n\t\t\treward.Handled = true;\n\t\t\ttry\n\t\t\t{\n\t\t\t\thandlers.Invoke( reward );\n\t\t\t}\n\t\t\tcatch ( Exception e )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] a RewardReceived handler threw: {e.Message}\u0022 );\n\t\t\t\treward.Refuse( \u0022handler threw: \u0022 \u002B e.Message );\n\t\t\t}\n\t\t}\n\t}\n\n\tinternal static void DispatchNotification( VoteNotification notification )\n\t{\n\t\tSafe( () =\u003E ISceneEvent\u003CISboxlistNotificationListener\u003E.Post( x =\u003E x.OnVoteNotification( notification ) ), \u0022ISboxlistNotificationListener\u0022 );\n\t\tSafe( () =\u003E NotificationReceived?.Invoke( notification ), \u0022NotificationReceived\u0022 );\n\t}\n\n\tinternal static void RaiseToast( string text ) =\u003E Safe( () =\u003E ToastShown?.Invoke( text ), \u0022ToastShown\u0022 );\n\n\tstatic void Safe( Action action, string name )\n\t{\n\t\ttry { action(); }\n\t\tcatch ( Exception e ) { Log.Warning( $\u0022[sboxlist] a {name} handler threw: {e.Message}\u0022 ); }\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistEvents.cs","FileName":"SboxlistEvents.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003EA vote that arrived from a site (on the host).\u003C/summary\u003E\npublic sealed class VoteInfo\n{\n\tpublic string SiteId { get; init; }\n\tpublic string Id { get; init; }\n\t/// \u003Csummary\u003E\u0022steam\u0022 or \u0022name\u0022.\u003C/summary\u003E\n\tpublic string IdentityKind { get; init; }\n\t/// \u003Csummary\u003EA SteamID64 (as text) or the name the voter typed.\u003C/summary\u003E\n\tpublic string IdentityKey { get; init; }\n\tpublic string At { get; init; }\n\tpublic bool IsTest { get; init; }\n\t/// \u003Csummary\u003EThe voter\u0027s active Connection if they are online right now; null when offline or for a test vote.\u003C/summary\u003E\n\tpublic Connection OnlinePlayer { get; init; }\n}\n\n/// \u003Csummary\u003E\n/// An item or currency reward for the game to hand out on the host (ISboxlistListener.OnVoteReward\n/// or SboxlistEvents.RewardReceived). Call Refuse(reason) if the reward cannot be granted so the\n/// site records ok:false with the reason in the owner\u0027s reward log.\n/// \u003C/summary\u003E\npublic sealed class RewardInfo\n{\n\tpublic string SiteId { get; init; }\n\tpublic string Id { get; init; }\n\tpublic string VoteId { get; init; }\n\tpublic string RuleId { get; init; }\n\t/// \u003Csummary\u003E\u0022item\u0022 or \u0022currency\u0022.\u003C/summary\u003E\n\tpublic string Kind { get; init; }\n\tpublic string Payload { get; init; }\n\tpublic long Amount { get; init; }\n\t/// \u003Csummary\u003E\u0022steam\u0022 or \u0022name\u0022.\u003C/summary\u003E\n\tpublic string IdentityKind { get; init; }\n\t/// \u003Csummary\u003EA SteamID64 (as text) or the name the voter typed.\u003C/summary\u003E\n\tpublic string IdentityKey { get; init; }\n\t/// \u003Csummary\u003EThe player who joined and gets the reward.\u003C/summary\u003E\n\tpublic Connection Player { get; init; }\n\t/// \u003Csummary\u003ESet to true by your listener when handled (automatically set for RewardReceived subscribers).\u003C/summary\u003E\n\tpublic bool Handled { get; set; }\n\t/// \u003Csummary\u003ENon-null when the game refused the reward via Refuse(reason).\u003C/summary\u003E\n\tpublic string Error { get; private set; }\n\n\t/// \u003Csummary\u003EMarks this reward as refused; the library sends ok:false with this reason in votes/ack.\u003C/summary\u003E\n\tpublic void Refuse( string reason )\n\t{\n\t\tHandled = true;\n\t\tError = string.IsNullOrWhiteSpace( reason ) ? \u0022refused by game\u0022 : reason.Trim();\n\t}\n}\n\n/// \u003Csummary\u003E\n/// A chat, toast or broadcast message delivered to a client (ISboxlistNotificationListener or\n/// SboxlistEvents.NotificationReceived). Set Handled = true in your custom UI to suppress the\n/// default Sandbox.Platform.Chat fallback.\n/// \u003C/summary\u003E\npublic sealed class VoteNotification\n{\n\t/// \u003Csummary\u003E\u0022chat\u0022 or \u0022toast\u0022.\u003C/summary\u003E\n\tpublic string Kind { get; init; }\n\t/// \u003Csummary\u003ETrue when sent to everyone via BroadcastChat / BroadcastToast; false when sent to one voter.\u003C/summary\u003E\n\tpublic bool IsBroadcast { get; init; }\n\t/// \u003Csummary\u003EFormatted message text with {name}, {steamid} and {amount} already replaced.\u003C/summary\u003E\n\tpublic string Text { get; init; }\n\t/// \u003Csummary\u003ESet to true to suppress the default Platform.Chat line.\u003C/summary\u003E\n\tpublic bool Handled { get; set; }\n}\n\n/// \u003Csummary\u003E\n/// Idiomatic s\u0026amp;box scene event interface for host-side vote announcements and item/currency\n/// rewards. Implement on any Component or GameObjectSystem in your active scene \u2014 no manual \u002B= / -=\n/// needed and safe across hotloads.\n/// \u003C/summary\u003E\npublic interface ISboxlistListener : ISceneEvent\u003CISboxlistListener\u003E\n{\n\tvoid OnVoteReceived( VoteInfo vote ) { }\n\tvoid OnVoteReward( RewardInfo reward ) { }\n}\n\n/// \u003Csummary\u003E\n/// Idiomatic s\u0026amp;box scene event interface for client-side custom notifications. Implement on any\n/// Razor Panel (@implements ISboxlistNotificationListener), PanelComponent or Component in your\n/// scene, and set notification.Handled = true to replace the default chat output with your own UI.\n/// \u003C/summary\u003E\npublic interface ISboxlistNotificationListener : ISceneEvent\u003CISboxlistNotificationListener\u003E\n{\n\tvoid OnVoteNotification( VoteNotification notification ) { }\n}\n\n/// \u003Csummary\u003E\n/// Static hooks for games that prefer C# events over scene interfaces (ISboxlistListener /\n/// ISboxlistNotificationListener). VoteReceived and RewardReceived fire on the host;\n/// NotificationReceived and ToastShown fire on the target client.\n/// \u003C/summary\u003E\npublic static class SboxlistEvents\n{\n\tpublic static event Action\u003CVoteInfo\u003E VoteReceived;\n\tpublic static event Action\u003CRewardInfo\u003E RewardReceived;\n\tpublic static event Action\u003CVoteNotification\u003E NotificationReceived;\n\tpublic static event Action\u003Cstring\u003E ToastShown;\n\n\tinternal static void RaiseVote( VoteInfo vote )\n\t{\n\t\tSafe( () =\u003E ISceneEvent\u003CISboxlistListener\u003E.Post( x =\u003E x.OnVoteReceived( vote ) ), \u0022ISboxlistListener.OnVoteReceived\u0022 );\n\t\tSafe( () =\u003E VoteReceived?.Invoke( vote ), \u0022VoteReceived\u0022 );\n\t}\n\n\tinternal static void DispatchReward( RewardInfo reward )\n\t{\n\t\ttry\n\t\t{\n\t\t\tISceneEvent\u003CISboxlistListener\u003E.Post( x =\u003E x.OnVoteReward( reward ) );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Warning( $\u0022[sboxlist] an ISboxlistListener.OnVoteReward handler threw: {e.Message}\u0022 );\n\t\t\treward.Refuse( \u0022handler threw: \u0022 \u002B e.Message );\n\t\t\treturn;\n\t\t}\n\n\t\tvar handlers = RewardReceived;\n\t\tif ( handlers is not null )\n\t\t{\n\t\t\treward.Handled = true;\n\t\t\ttry\n\t\t\t{\n\t\t\t\thandlers.Invoke( reward );\n\t\t\t}\n\t\t\tcatch ( Exception e )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] a RewardReceived handler threw: {e.Message}\u0022 );\n\t\t\t\treward.Refuse( \u0022handler threw: \u0022 \u002B e.Message );\n\t\t\t}\n\t\t}\n\t}\n\n\tinternal static void DispatchNotification( VoteNotification notification )\n\t{\n\t\tSafe( () =\u003E ISceneEvent\u003CISboxlistNotificationListener\u003E.Post( x =\u003E x.OnVoteNotification( notification ) ), \u0022ISboxlistNotificationListener\u0022 );\n\t\tSafe( () =\u003E NotificationReceived?.Invoke( notification ), \u0022NotificationReceived\u0022 );\n\t}\n\n\tinternal static void RaiseToast( string text ) =\u003E Safe( () =\u003E ToastShown?.Invoke( text ), \u0022ToastShown\u0022 );\n\n\tstatic void Safe( Action action, string name )\n\t{\n\t\ttry { action(); }\n\t\tcatch ( Exception e ) { Log.Warning( $\u0022[sboxlist] a {name} handler threw: {e.Message}\u0022 ); }\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistRewards.cs","FileName":"SboxlistRewards.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Globalization;\nusing System.Text;\nusing System.Text.Json.Nodes;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Runs one reward message (PROTOCOL.md 6.6) for the player who joined. Returns null when done,\n/// or the reason it was refused (that reason goes back to the site in the ack).\n/// \u003C/summary\u003E\npublic static class SboxlistRewards\n{\n\tinternal static string Run( SiteClient site, JsonNode reward, Connection player )\n\t{\n\t\tvar kind = JsonRead.Str( reward, \u0022kind\u0022 ) ?? \u0022\u0022;\n\t\tvar payload = JsonRead.Str( reward, \u0022payload\u0022 ) ?? \u0022\u0022;\n\t\tvar amount = JsonRead.Long( reward, \u0022amount\u0022 ) ?? 0;\n\t\tvar identity = JsonRead.Get( reward, \u0022identity\u0022 );\n\t\tvar identityKind = JsonRead.Str( identity, \u0022kind\u0022 ) ?? \u0022\u0022;\n\t\tvar identityKey = JsonRead.Str( identity, \u0022key\u0022 ) ?? \u0022\u0022;\n\n\t\tif ( amount \u003C 1 || amount \u003E 1_000_000 ) return \u0022amount out of range\u0022;\n\t\tvar payloadProblem = PayloadProblem( payload );\n\t\tif ( payloadProblem is not null ) return payloadProblem;\n\n\t\tswitch ( kind )\n\t\t{\n\t\t\tcase \u0022console\u0022:\n\t\t\t{\n\t\t\t\tvar command = ConsoleCommand( payload, identityKind, identityKey, amount, out var problem );\n\t\t\t\tif ( command is null ) return problem;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tConsoleSystem.Run( command );\n\t\t\t\t\tLog.Info( $\u0022[sboxlist] {site.Config.SiteId}: reward ran: {command}\u0022 );\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\treturn Clip( $\u0022console: {e.Message}\u0022 );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcase \u0022chat\u0022:\n\t\t\tcase \u0022toast\u0022:\n\t\t\t{\n\t\t\t\tvar textProblem = TextProblem( payload, identityKind, identityKey );\n\t\t\t\tif ( textProblem is not null ) return textProblem;\n\t\t\t\tvar text = Text( payload, player, identityKind, identityKey, amount );\n\t\t\t\tSboxlistPlayerMessages.SendTo( player, kind, text );\n\t\t\t\tLog.Info( $\u0022[sboxlist] {site.Config.SiteId}: {kind} to {player.DisplayName}: {text}\u0022 );\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tcase \u0022item\u0022:\n\t\t\tcase \u0022currency\u0022:\n\t\t\t{\n\t\t\t\tvar info = new RewardInfo\n\t\t\t\t{\n\t\t\t\t\tSiteId = site.Config.SiteId,\n\t\t\t\t\tId = JsonRead.Str( reward, \u0022id\u0022 ),\n\t\t\t\t\tVoteId = JsonRead.Str( reward, \u0022voteId\u0022 ),\n\t\t\t\t\tRuleId = JsonRead.Str( reward, \u0022ruleId\u0022 ),\n\t\t\t\t\tKind = kind,\n\t\t\t\t\tPayload = payload,\n\t\t\t\t\tAmount = amount,\n\t\t\t\t\tIdentityKind = identityKind,\n\t\t\t\t\tIdentityKey = identityKey,\n\t\t\t\t\tPlayer = player,\n\t\t\t\t};\n\t\t\t\tSboxlistEvents.DispatchReward( info );\n\t\t\t\tif ( !info.Handled ) return \u0022the game has no RewardReceived handler\u0022;\n\t\t\t\tif ( info.Error is not null ) return Clip( info.Error );\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\treturn \u0022unsupported kind\u0022;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// One command, no ; quotes backquote backslash or control characters. {steamid} only for a\n\t/// Steam voter, {name} only for a name voter (put in double quotes), {amount}. Anything else: refused.\n\t/// \u003C/summary\u003E\n\tpublic static string ConsoleCommand( string payload, string identityKind, string identityKey, long amount, out string problem )\n\t{\n\t\tproblem = null;\n\t\tif ( string.IsNullOrWhiteSpace( payload ) ) { problem = \u0022empty command\u0022; return null; }\n\t\tif ( HasForbidden( payload ) ) { problem = \u0022command holds ; quote backquote backslash or a control character\u0022; return null; }\n\n\t\tvar sb = new StringBuilder();\n\t\tvar i = 0;\n\t\twhile ( i \u003C payload.Length )\n\t\t{\n\t\t\tvar c = payload[i];\n\t\t\tif ( c == \u0027}\u0027 ) { problem = \u0022stray }\u0022; return null; }\n\t\t\tif ( c != \u0027{\u0027 ) { sb.Append( c ); i\u002B\u002B; continue; }\n\n\t\t\tvar end = payload.IndexOf( \u0027}\u0027, i );\n\t\t\tif ( end \u003C 0 ) { problem = \u0022unclosed {\u0022; return null; }\n\t\t\tvar token = payload.Substring( i, end - i \u002B 1 );\n\n\t\t\tswitch ( token )\n\t\t\t{\n\t\t\t\tcase \u0022{amount}\u0022:\n\t\t\t\t\tsb.Append( amount.ToString( CultureInfo.InvariantCulture ) );\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022{steamid}\u0022:\n\t\t\t\t\tif ( identityKind != \u0022steam\u0022 ) { problem = \u0022{steamid} needs a Steam voter\u0022; return null; }\n\t\t\t\t\tif ( !IsDigits( identityKey, 17 ) ) { problem = \u0022bad SteamID64\u0022; return null; }\n\t\t\t\t\tsb.Append( identityKey );\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022{name}\u0022:\n\t\t\t\t\tif ( identityKind != \u0022name\u0022 ) { problem = \u0022{name} needs a name voter\u0022; return null; }\n\t\t\t\t\tif ( string.IsNullOrEmpty( identityKey ) || HasForbidden( identityKey ) ) { problem = \u0022the name holds a character a command may not\u0022; return null; }\n\t\t\t\t\tsb.Append( \u0027\u0022\u0027 ).Append( identityKey ).Append( \u0027\u0022\u0027 );\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tproblem = $\u0022unknown placeholder {token}\u0022;\n\t\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\ti = end \u002B 1;\n\t\t}\n\n\t\treturn sb.ToString().Trim();\n\t}\n\n\t/// \u003Csummary\u003EChat and toast text: {name} is the player\u0027s name here, {steamid} and {amount} as given.\u003C/summary\u003E\n\tstatic string Text( string payload, Connection player, string identityKind, string identityKey, long amount )\n\t{\n\t\tvar name = player?.DisplayName ?? (identityKind == \u0022name\u0022 ? identityKey : \u0022\u0022);\n\t\tvar steam = identityKind == \u0022steam\u0022 ? identityKey : \u0022\u0022;\n\t\treturn payload\n\t\t\t.Replace( \u0022{name}\u0022, name )\n\t\t\t.Replace( \u0022{steamid}\u0022, steam )\n\t\t\t.Replace( \u0022{amount}\u0022, amount.ToString( CultureInfo.InvariantCulture ) );\n\t}\n\n\t/// \u003Csummary\u003EChat and toast text: only {name}, {steamid} and {amount}; {steamid} needs a Steam voter. Anything else is refused (PROTOCOL.md 6.6).\u003C/summary\u003E\n\tstatic string TextProblem( string payload, string identityKind, string identityKey )\n\t{\n\t\tvar i = 0;\n\t\twhile ( i \u003C payload.Length )\n\t\t{\n\t\t\tvar c = payload[i];\n\t\t\tif ( c == \u0027}\u0027 ) return \u0022stray }\u0022;\n\t\t\tif ( c != \u0027{\u0027 ) { i\u002B\u002B; continue; }\n\n\t\t\tvar end = payload.IndexOf( \u0027}\u0027, i );\n\t\t\tif ( end \u003C 0 ) return \u0022unclosed {\u0022;\n\t\t\tvar token = payload.Substring( i, end - i \u002B 1 );\n\t\t\tswitch ( token )\n\t\t\t{\n\t\t\t\tcase \u0022{amount}\u0022:\n\t\t\t\tcase \u0022{name}\u0022:\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022{steamid}\u0022:\n\t\t\t\t\tif ( identityKind != \u0022steam\u0022 || !IsDigits( identityKey, 17 ) ) return \u0022{steamid} needs a Steam voter\u0022;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn $\u0022unknown placeholder {token}\u0022;\n\t\t\t}\n\n\t\t\ti = end \u002B 1;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003EPROTOCOL.md 6.6: at most 200 code points, no control character and no lone surrogate.\u003C/summary\u003E\n\tinternal static string PayloadProblem( string s )\n\t{\n\t\tif ( s is null ) return \u0022empty payload\u0022;\n\t\tvar codePoints = 0;\n\t\tfor ( var i = 0; i \u003C s.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = s[i];\n\t\t\tif ( char.IsControl( c ) ) return \u0022payload holds a control character\u0022;\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C s.Length \u0026\u0026 char.IsLowSurrogate( s[i \u002B 1] ) ) i\u002B\u002B;\n\t\t\telse if ( char.IsSurrogate( c ) ) return \u0022payload holds a lone surrogate\u0022;\n\t\t\tif ( \u002B\u002BcodePoints \u003E 200 ) return \u0022payload too long\u0022;\n\t\t}\n\t\treturn null;\n\t}\n\n\tstatic bool HasForbidden( string s )\n\t{\n\t\tfor ( var i = 0; i \u003C s.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = s[i];\n\t\t\tif ( c == \u0027;\u0027 || c == \u0027\u0022\u0027 || c == \u0027\\\u0027\u0027 || c == \u0027\u0060\u0027 || c == \u0027\\\\\u0027 || char.IsControl( c ) ) return true;\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C s.Length \u0026\u0026 char.IsLowSurrogate( s[i \u002B 1] ) ) { i\u002B\u002B; continue; }\n\t\t\tif ( char.IsSurrogate( c ) ) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstatic bool IsDigits( string s, int length )\n\t{\n\t\tif ( s is null || s.Length != length ) return false;\n\t\tforeach ( var c in s ) if ( c \u003C \u00270\u0027 || c \u003E \u00279\u0027 ) return false;\n\t\treturn true;\n\t}\n\n\tstatic string Clip( string s ) =\u003E SiteClient.Clip( s, 200 );\n}\n\n/// \u003Csummary\u003E\n/// Messages on one player\u0027s screen. The host calls SendTo; the RPC runs only on that player\u0027s\n/// machine (Rpc.FilterInclude), and only the host may call it (NetFlags.HostOnly), so a client\n/// cannot fake a reward message to other players.\n/// \u003C/summary\u003E\npublic static class SboxlistPlayerMessages\n{\n\t/// \u003Csummary\u003ESends a reward chat or toast message from the host to one specific player.\u003C/summary\u003E\n\tpublic static void SendTo( Connection player, string kind, string text )\n\t{\n\t\tif ( !Networking.IsHost || player is null ) return;\n\t\tusing ( Rpc.FilterInclude( player ) )\n\t\t{\n\t\t\tShow( kind, text );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EBroadcasts a chat message from the host to all connected players (e.g. \u0022Player voted!\u0022).\u003C/summary\u003E\n\tpublic static void BroadcastChat( string text )\n\t{\n\t\tif ( !Networking.IsHost || string.IsNullOrEmpty( text ) ) return;\n\t\tShow( \u0022broadcast_chat\u0022, SiteClient.Clip( text, 300 ) );\n\t}\n\n\t/// \u003Csummary\u003EBroadcasts a toast notification from the host to all connected players.\u003C/summary\u003E\n\tpublic static void BroadcastToast( string text )\n\t{\n\t\tif ( !Networking.IsHost || string.IsNullOrEmpty( text ) ) return;\n\t\tShow( \u0022broadcast_toast\u0022, SiteClient.Clip( text, 300 ) );\n\t}\n\n\t[Rpc.Broadcast( NetFlags.Reliable | NetFlags.HostOnly )]\n\tpublic static void Show( string kind, string text )\n\t{\n\t\tvar isToast = kind == \u0022toast\u0022 || kind == \u0022broadcast_toast\u0022;\n\t\tvar isBroadcast = kind == \u0022broadcast_chat\u0022 || kind == \u0022broadcast_toast\u0022;\n\t\tvar notification = new VoteNotification\n\t\t{\n\t\t\tKind = isToast ? \u0022toast\u0022 : \u0022chat\u0022,\n\t\t\tIsBroadcast = isBroadcast,\n\t\t\tText = text,\n\t\t};\n\n\t\tSboxlistEvents.DispatchNotification( notification );\n\t\tif ( isToast ) SboxlistEvents.RaiseToast( text );\n\n\t\tif ( notification.Handled ) return;\n\n\t\tif ( isToast )\n\t\t\tSandbox.Platform.Chat.AddText( \u0022\u2605 \u0022 \u002B text );\n\t\telse\n\t\t\tSandbox.Platform.Chat.AddText( text );\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistConfig.cs","FileName":"SboxlistConfig.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Text.Json.Nodes;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003EOne server list this server is listed on (PROTOCOL.md section 7).\u003C/summary\u003E\npublic sealed class SiteConfig\n{\n\tpublic string SiteId { get; set; } = \u0022\u0022;\n\tpublic string BaseUrl { get; set; } = \u0022\u0022;\n\tpublic string ServerId { get; set; } = \u0022\u0022;\n\tpublic string Token { get; set; } = \u0022\u0022;\n\t/// \u003Csummary\u003Ehmac for sboxlist.com (protocol v1 accepts hmac only); bearer only for a site that accepts it.\u003C/summary\u003E\n\tpublic string Auth { get; set; } = \u0022hmac\u0022;\n\tpublic bool Rewards { get; set; } = true;\n}\n\n/// \u003Csummary\u003E\n/// Reads the site list. First choice: data/\u0026lt;org\u0026gt;/\u0026lt;package\u0026gt;/sboxlist.json on the server\u0027s own\n/// disk (FileSystem.Data). Fallback for one site: the hidden ConVars below, set from the start\n/// script (\u002Bsbl_base_url ... \u002Bsbl_server_id ... \u002Bsbl_token ...). The token is never put in a\n/// prefab, a scene or a published package.\n/// \u003C/summary\u003E\npublic static class SboxlistConfig\n{\n\tpublic const string FileName = \u0022sboxlist.json\u0022;\n\n\t[ConVar( \u0022sbl_base_url\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarBaseUrl { get; set; } = \u0022\u0022;\n\n\t[ConVar( \u0022sbl_server_id\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarServerId { get; set; } = \u0022\u0022;\n\n\t[ConVar( \u0022sbl_token\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarToken { get; set; } = \u0022\u0022;\n\n\t[ConVar( \u0022sbl_auth\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarAuth { get; set; } = \u0022hmac\u0022;\n\n\t/// \u003Csummary\u003ELogs every request and answer (never the token).\u003C/summary\u003E\n\t[ConVar( \u0022sbl_debug\u0022 )]\n\tpublic static bool Debug { get; set; } = false;\n\n\tpublic static string FullPath()\n\t{\n\t\ttry { return FileSystem.Data.GetFullPath( FileName ); }\n\t\tcatch ( Exception e ) { return $\u0022(unknown: {e.Message})\u0022; }\n\t}\n\n\tpublic static List\u003CSiteConfig\u003E Load( out string source )\n\t{\n\t\tvar sites = new List\u003CSiteConfig\u003E();\n\n\t\tif ( FileSystem.Data.FileExists( FileName ) )\n\t\t{\n\t\t\tsource = FullPath();\n\t\t\tJsonNode root;\n\t\t\ttry\n\t\t\t{\n\t\t\t\troot = JsonNode.Parse( FileSystem.Data.ReadAllText( FileName ) );\n\t\t\t}\n\t\t\tcatch ( Exception e )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {source} is not valid JSON: {e.Message}\u0022 );\n\t\t\t\treturn sites;\n\t\t\t}\n\n\t\t\tif ( root?[\u0022sites\u0022] is JsonArray list )\n\t\t\t{\n\t\t\t\tforeach ( var item in list )\n\t\t\t\t{\n\t\t\t\t\tvar site = new SiteConfig\n\t\t\t\t\t{\n\t\t\t\t\t\tSiteId = JsonRead.Str( item, \u0022siteId\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tBaseUrl = JsonRead.Str( item, \u0022baseUrl\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tServerId = JsonRead.Str( item, \u0022serverId\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tToken = JsonRead.Str( item, \u0022token\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tAuth = JsonRead.Str( item, \u0022auth\u0022 ) ?? \u0022hmac\u0022,\n\t\t\t\t\t\tRewards = JsonRead.Bool( item, \u0022rewards\u0022 ) ?? true,\n\t\t\t\t\t};\n\t\t\t\t\tAddIfValid( sites, site );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {source} has no \\\u0022sites\\\u0022 list\u0022 );\n\t\t\t}\n\n\t\t\tif ( JsonRead.Bool( root, \u0022debug\u0022 ) == true ) Debug = true;\n\t\t\treturn sites;\n\t\t}\n\n\t\tif ( !string.IsNullOrWhiteSpace( ConVarBaseUrl ) )\n\t\t{\n\t\t\tsource = \u0022ConVars sbl_base_url / sbl_server_id / sbl_token\u0022;\n\t\t\tAddIfValid( sites, new SiteConfig\n\t\t\t{\n\t\t\t\tSiteId = HostOf( ConVarBaseUrl ),\n\t\t\t\tBaseUrl = ConVarBaseUrl.Trim(),\n\t\t\t\tServerId = ConVarServerId.Trim(),\n\t\t\t\tToken = ConVarToken.Trim(),\n\t\t\t\tAuth = string.IsNullOrWhiteSpace( ConVarAuth ) ? \u0022hmac\u0022 : ConVarAuth.Trim(),\n\t\t\t\tRewards = true,\n\t\t\t} );\n\t\t\treturn sites;\n\t\t}\n\n\t\tsource = $\u0022nothing found (looked for {FullPath()} and the sbl_* ConVars)\u0022;\n\t\treturn sites;\n\t}\n\n\tstatic void AddIfValid( List\u003CSiteConfig\u003E sites, SiteConfig site )\n\t{\n\t\tsite.BaseUrl = site.BaseUrl.Trim().TrimEnd( \u0027/\u0027 );\n\t\tsite.Auth = site.Auth.Trim().ToLowerInvariant();\n\t\tif ( string.IsNullOrWhiteSpace( site.SiteId ) ) site.SiteId = HostOf( site.BaseUrl );\n\n\t\tvar problem = Problem( site );\n\t\tif ( problem is not null )\n\t\t{\n\t\t\tLog.Warning( $\u0022[sboxlist] site \u0027{site.SiteId}\u0027 skipped: {problem}\u0022 );\n\t\t\treturn;\n\t\t}\n\n\t\tvar warning = LocalhostWarning( site.BaseUrl );\n\t\tif ( warning is not null ) Log.Warning( $\u0022[sboxlist] site \u0027{site.SiteId}\u0027: {warning}\u0022 );\n\n\t\tforeach ( var existing in sites )\n\t\t{\n\t\t\tif ( existing.SiteId == site.SiteId )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] site \u0027{site.SiteId}\u0027 is listed twice; the second one is skipped\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tsites.Add( site );\n\t}\n\n\t/// \u003Csummary\u003EThe reason a site is refused, or null. The site checks what it receives; this checks what the plugin is given.\u003C/summary\u003E\n\tstatic string Problem( SiteConfig s )\n\t{\n\t\tvar url = BaseUrlProblem( s.BaseUrl );\n\t\tif ( url is not null ) return url;\n\t\tif ( !IsSiteId( s.SiteId ) ) return \u0022siteId must be lowercase letters, digits, dots and dashes, starting with a letter or digit\u0022;\n\t\tif ( !IsIdent( s.ServerId, 1, 64 ) ) return \u0022serverId must be 1-64 of A-Z a-z 0-9 _ -\u0022;\n\t\tif ( !IsToken( s.Token ) ) return \u0022token must be sbs_ or sbt_ followed by 43 characters\u0022;\n\t\tif ( s.Auth != \u0022bearer\u0022 \u0026\u0026 s.Auth != \u0022hmac\u0022 ) return \u0022auth must be hmac or bearer\u0022;\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// https with a domain name (s\u0026amp;box refuses IP addresses), or http on localhost for tests.\n\t/// The port of a localhost address is only a warning, see LocalhostWarning.\n\t/// \u003C/summary\u003E\n\tinternal static string BaseUrlProblem( string url )\n\t{\n\t\tif ( string.IsNullOrEmpty( url ) ) return \u0022baseUrl must be a full URL\u0022;\n\t\tif ( !Uri.TryCreate( url, UriKind.Absolute, out var uri ) ) return \u0022baseUrl must be a full URL\u0022;\n\t\tif ( uri.Scheme == \u0022https\u0022 )\n\t\t\treturn IsDomainName( uri.Host ) ? null : \u0022baseUrl must name a domain, not an IP address\u0022;\n\t\tif ( uri.Scheme == \u0022http\u0022 \u0026\u0026 uri.Host == \u0022localhost\u0022 )\n\t\t\treturn null;\n\t\treturn \u0022baseUrl must start with https:// and name a domain (http is allowed for localhost only, for tests)\u0022;\n\t}\n\n\t/// \u003Csummary\u003Es\u0026amp;box allows localhost only on ports 80, 443, 8080 and 8443, unless the editor or server runs with -allowlocalhttp.\u003C/summary\u003E\n\tinternal static string LocalhostWarning( string url )\n\t{\n\t\tif ( !Uri.TryCreate( url, UriKind.Absolute, out var uri ) || uri.Scheme != \u0022http\u0022 || uri.Host != \u0022localhost\u0022 ) return null;\n\t\tif ( uri.Port == 80 || uri.Port == 443 || uri.Port == 8080 || uri.Port == 8443 ) return null;\n\t\treturn $\u0022s\u0026box refuses localhost port {uri.Port} unless the editor or server runs with -allowlocalhttp\u0022;\n\t}\n\n\t/// \u003Csummary\u003EA domain name has a dot, and is not an IPv4 address (digits and dots only) or an IPv6 literal.\u003C/summary\u003E\n\tstatic bool IsDomainName( string host )\n\t{\n\t\tif ( string.IsNullOrEmpty( host ) || host.Length \u003E 253 || host.IndexOf( \u0027.\u0027 ) \u003C 0 ) return false;\n\t\tvar letters = false;\n\t\tforeach ( var c in host )\n\t\t{\n\t\t\tif ( c == \u0027:\u0027 || c == \u0027[\u0027 || c == \u0027]\u0027 ) return false;\n\t\t\tif ( !(char.IsDigit( c ) || c == \u0027.\u0027) ) letters = true;\n\t\t}\n\t\treturn letters;\n\t}\n\n\t/// \u003Csummary\u003Esbs_ is the protocol v1 server secret prefix; sbt_ is the generic protocol token prefix (PROTOCOL.md section 4).\u003C/summary\u003E\n\tinternal static bool IsToken( string token )\n\t{\n\t\tif ( token is null || token.Length != 47 ) return false;\n\t\tif ( !(token.StartsWith( \u0022sbs_\u0022 ) || token.StartsWith( \u0022sbt_\u0022 )) ) return false;\n\t\treturn IsIdent( token.Substring( 4 ), 43, 43 );\n\t}\n\n\t/// \u003Csummary\u003EA site id: lowercase letters, digits, dots and dashes; at most 63 characters; starts with a letter or digit.\u003C/summary\u003E\n\tinternal static bool IsSiteId( string value )\n\t{\n\t\tif ( string.IsNullOrEmpty( value ) || value.Length \u003E 63 ) return false;\n\t\tfor ( var i = 0; i \u003C value.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = value[i];\n\t\t\tvar letterOrDigit = (c \u003E= \u0027a\u0027 \u0026\u0026 c \u003C= \u0027z\u0027) || (c \u003E= \u00270\u0027 \u0026\u0026 c \u003C= \u00279\u0027);\n\t\t\tif ( i == 0 ? !letterOrDigit : !(letterOrDigit || c == \u0027.\u0027 || c == \u0027-\u0027) ) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tinternal static bool IsIdent( string value, int min, int max )\n\t{\n\t\tif ( value is null || value.Length \u003C min || value.Length \u003E max ) return false;\n\t\tforeach ( var c in value )\n\t\t{\n\t\t\tvar ok = (c \u003E= \u0027a\u0027 \u0026\u0026 c \u003C= \u0027z\u0027) || (c \u003E= \u0027A\u0027 \u0026\u0026 c \u003C= \u0027Z\u0027) || (c \u003E= \u00270\u0027 \u0026\u0026 c \u003C= \u00279\u0027) || c == \u0027_\u0027 || c == \u0027-\u0027;\n\t\t\tif ( !ok ) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstatic string HostOf( string url )\n\t{\n\t\ttry { return new Uri( url.Trim() ).Host.ToLowerInvariant(); }\n\t\tcatch { return \u0022site\u0022; }\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistRewards.cs","FileName":"SboxlistRewards.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Globalization;\nusing System.Text;\nusing System.Text.Json.Nodes;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Runs one reward message (PROTOCOL.md 6.6) for the player who joined. Returns null when done,\n/// or the reason it was refused (that reason goes back to the site in the ack).\n/// \u003C/summary\u003E\npublic static class SboxlistRewards\n{\n\tinternal static string Run( SiteClient site, JsonNode reward, Connection player )\n\t{\n\t\tvar kind = JsonRead.Str( reward, \u0022kind\u0022 ) ?? \u0022\u0022;\n\t\tvar payload = JsonRead.Str( reward, \u0022payload\u0022 ) ?? \u0022\u0022;\n\t\tvar amount = JsonRead.Long( reward, \u0022amount\u0022 ) ?? 0;\n\t\tvar identity = JsonRead.Get( reward, \u0022identity\u0022 );\n\t\tvar identityKind = JsonRead.Str( identity, \u0022kind\u0022 ) ?? \u0022\u0022;\n\t\tvar identityKey = JsonRead.Str( identity, \u0022key\u0022 ) ?? \u0022\u0022;\n\n\t\tif ( amount \u003C 1 || amount \u003E 1_000_000 ) return \u0022amount out of range\u0022;\n\t\tvar payloadProblem = PayloadProblem( payload );\n\t\tif ( payloadProblem is not null ) return payloadProblem;\n\n\t\tswitch ( kind )\n\t\t{\n\t\t\tcase \u0022console\u0022:\n\t\t\t{\n\t\t\t\tvar command = ConsoleCommand( payload, identityKind, identityKey, amount, out var problem );\n\t\t\t\tif ( command is null ) return problem;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tConsoleSystem.Run( command );\n\t\t\t\t\tLog.Info( $\u0022[sboxlist] {site.Config.SiteId}: reward ran: {command}\u0022 );\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\treturn Clip( $\u0022console: {e.Message}\u0022 );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcase \u0022chat\u0022:\n\t\t\tcase \u0022toast\u0022:\n\t\t\t{\n\t\t\t\tvar textProblem = TextProblem( payload, identityKind, identityKey );\n\t\t\t\tif ( textProblem is not null ) return textProblem;\n\t\t\t\tvar text = Text( payload, player, identityKind, identityKey, amount );\n\t\t\t\tSboxlistPlayerMessages.SendTo( player, kind, text );\n\t\t\t\tLog.Info( $\u0022[sboxlist] {site.Config.SiteId}: {kind} to {player.DisplayName}: {text}\u0022 );\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tcase \u0022item\u0022:\n\t\t\tcase \u0022currency\u0022:\n\t\t\t{\n\t\t\t\tvar info = new RewardInfo\n\t\t\t\t{\n\t\t\t\t\tSiteId = site.Config.SiteId,\n\t\t\t\t\tId = JsonRead.Str( reward, \u0022id\u0022 ),\n\t\t\t\t\tVoteId = JsonRead.Str( reward, \u0022voteId\u0022 ),\n\t\t\t\t\tRuleId = JsonRead.Str( reward, \u0022ruleId\u0022 ),\n\t\t\t\t\tKind = kind,\n\t\t\t\t\tPayload = payload,\n\t\t\t\t\tAmount = amount,\n\t\t\t\t\tIdentityKind = identityKind,\n\t\t\t\t\tIdentityKey = identityKey,\n\t\t\t\t\tPlayer = player,\n\t\t\t\t};\n\t\t\t\tSboxlistEvents.DispatchReward( info );\n\t\t\t\tif ( !info.Handled ) return \u0022the game has no RewardReceived handler\u0022;\n\t\t\t\tif ( info.Error is not null ) return Clip( info.Error );\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\treturn \u0022unsupported kind\u0022;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// One command, no ; quotes backquote backslash or control characters. {steamid} only for a\n\t/// Steam voter, {name} only for a name voter (put in double quotes), {amount}. Anything else: refused.\n\t/// \u003C/summary\u003E\n\tpublic static string ConsoleCommand( string payload, string identityKind, string identityKey, long amount, out string problem )\n\t{\n\t\tproblem = null;\n\t\tif ( string.IsNullOrWhiteSpace( payload ) ) { problem = \u0022empty command\u0022; return null; }\n\t\tif ( HasForbidden( payload ) ) { problem = \u0022command holds ; quote backquote backslash or a control character\u0022; return null; }\n\n\t\tvar sb = new StringBuilder();\n\t\tvar i = 0;\n\t\twhile ( i \u003C payload.Length )\n\t\t{\n\t\t\tvar c = payload[i];\n\t\t\tif ( c == \u0027}\u0027 ) { problem = \u0022stray }\u0022; return null; }\n\t\t\tif ( c != \u0027{\u0027 ) { sb.Append( c ); i\u002B\u002B; continue; }\n\n\t\t\tvar end = payload.IndexOf( \u0027}\u0027, i );\n\t\t\tif ( end \u003C 0 ) { problem = \u0022unclosed {\u0022; return null; }\n\t\t\tvar token = payload.Substring( i, end - i \u002B 1 );\n\n\t\t\tswitch ( token )\n\t\t\t{\n\t\t\t\tcase \u0022{amount}\u0022:\n\t\t\t\t\tsb.Append( amount.ToString( CultureInfo.InvariantCulture ) );\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022{steamid}\u0022:\n\t\t\t\t\tif ( identityKind != \u0022steam\u0022 ) { problem = \u0022{steamid} needs a Steam voter\u0022; return null; }\n\t\t\t\t\tif ( !IsDigits( identityKey, 17 ) ) { problem = \u0022bad SteamID64\u0022; return null; }\n\t\t\t\t\tsb.Append( identityKey );\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022{name}\u0022:\n\t\t\t\t\tif ( identityKind != \u0022name\u0022 ) { problem = \u0022{name} needs a name voter\u0022; return null; }\n\t\t\t\t\tif ( string.IsNullOrEmpty( identityKey ) || HasForbidden( identityKey ) ) { problem = \u0022the name holds a character a command may not\u0022; return null; }\n\t\t\t\t\tsb.Append( \u0027\u0022\u0027 ).Append( identityKey ).Append( \u0027\u0022\u0027 );\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tproblem = $\u0022unknown placeholder {token}\u0022;\n\t\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\ti = end \u002B 1;\n\t\t}\n\n\t\treturn sb.ToString().Trim();\n\t}\n\n\t/// \u003Csummary\u003EChat and toast text: {name} is the player\u0027s name here, {steamid} and {amount} as given.\u003C/summary\u003E\n\tstatic string Text( string payload, Connection player, string identityKind, string identityKey, long amount )\n\t{\n\t\tvar name = player?.DisplayName ?? (identityKind == \u0022name\u0022 ? identityKey : \u0022\u0022);\n\t\tvar steam = identityKind == \u0022steam\u0022 ? identityKey : \u0022\u0022;\n\t\treturn payload\n\t\t\t.Replace( \u0022{name}\u0022, name )\n\t\t\t.Replace( \u0022{steamid}\u0022, steam )\n\t\t\t.Replace( \u0022{amount}\u0022, amount.ToString( CultureInfo.InvariantCulture ) );\n\t}\n\n\t/// \u003Csummary\u003EChat and toast text: only {name}, {steamid} and {amount}; {steamid} needs a Steam voter. Anything else is refused (PROTOCOL.md 6.6).\u003C/summary\u003E\n\tstatic string TextProblem( string payload, string identityKind, string identityKey )\n\t{\n\t\tvar i = 0;\n\t\twhile ( i \u003C payload.Length )\n\t\t{\n\t\t\tvar c = payload[i];\n\t\t\tif ( c == \u0027}\u0027 ) return \u0022stray }\u0022;\n\t\t\tif ( c != \u0027{\u0027 ) { i\u002B\u002B; continue; }\n\n\t\t\tvar end = payload.IndexOf( \u0027}\u0027, i );\n\t\t\tif ( end \u003C 0 ) return \u0022unclosed {\u0022;\n\t\t\tvar token = payload.Substring( i, end - i \u002B 1 );\n\t\t\tswitch ( token )\n\t\t\t{\n\t\t\t\tcase \u0022{amount}\u0022:\n\t\t\t\tcase \u0022{name}\u0022:\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022{steamid}\u0022:\n\t\t\t\t\tif ( identityKind != \u0022steam\u0022 || !IsDigits( identityKey, 17 ) ) return \u0022{steamid} needs a Steam voter\u0022;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn $\u0022unknown placeholder {token}\u0022;\n\t\t\t}\n\n\t\t\ti = end \u002B 1;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003EPROTOCOL.md 6.6: at most 200 code points, no control character and no lone surrogate.\u003C/summary\u003E\n\tinternal static string PayloadProblem( string s )\n\t{\n\t\tif ( s is null ) return \u0022empty payload\u0022;\n\t\tvar codePoints = 0;\n\t\tfor ( var i = 0; i \u003C s.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = s[i];\n\t\t\tif ( char.IsControl( c ) ) return \u0022payload holds a control character\u0022;\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C s.Length \u0026\u0026 char.IsLowSurrogate( s[i \u002B 1] ) ) i\u002B\u002B;\n\t\t\telse if ( char.IsSurrogate( c ) ) return \u0022payload holds a lone surrogate\u0022;\n\t\t\tif ( \u002B\u002BcodePoints \u003E 200 ) return \u0022payload too long\u0022;\n\t\t}\n\t\treturn null;\n\t}\n\n\tstatic bool HasForbidden( string s )\n\t{\n\t\tfor ( var i = 0; i \u003C s.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = s[i];\n\t\t\tif ( c == \u0027;\u0027 || c == \u0027\u0022\u0027 || c == \u0027\\\u0027\u0027 || c == \u0027\u0060\u0027 || c == \u0027\\\\\u0027 || char.IsControl( c ) ) return true;\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C s.Length \u0026\u0026 char.IsLowSurrogate( s[i \u002B 1] ) ) { i\u002B\u002B; continue; }\n\t\t\tif ( char.IsSurrogate( c ) ) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstatic bool IsDigits( string s, int length )\n\t{\n\t\tif ( s is null || s.Length != length ) return false;\n\t\tforeach ( var c in s ) if ( c \u003C \u00270\u0027 || c \u003E \u00279\u0027 ) return false;\n\t\treturn true;\n\t}\n\n\tstatic string Clip( string s ) =\u003E SiteClient.Clip( s, 200 );\n}\n\n/// \u003Csummary\u003E\n/// Messages on one player\u0027s screen. The host calls SendTo; the RPC runs only on that player\u0027s\n/// machine (Rpc.FilterInclude), and only the host may call it (NetFlags.HostOnly), so a client\n/// cannot fake a reward message to other players.\n/// \u003C/summary\u003E\npublic static class SboxlistPlayerMessages\n{\n\t/// \u003Csummary\u003ESends a reward chat or toast message from the host to one specific player.\u003C/summary\u003E\n\tpublic static void SendTo( Connection player, string kind, string text )\n\t{\n\t\tif ( !Networking.IsHost || player is null ) return;\n\t\tusing ( Rpc.FilterInclude( player ) )\n\t\t{\n\t\t\tShow( kind, text );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EBroadcasts a chat message from the host to all connected players (e.g. \u0022Player voted!\u0022).\u003C/summary\u003E\n\tpublic static void BroadcastChat( string text )\n\t{\n\t\tif ( !Networking.IsHost || string.IsNullOrEmpty( text ) ) return;\n\t\tShow( \u0022broadcast_chat\u0022, SiteClient.Clip( text, 300 ) );\n\t}\n\n\t/// \u003Csummary\u003EBroadcasts a toast notification from the host to all connected players.\u003C/summary\u003E\n\tpublic static void BroadcastToast( string text )\n\t{\n\t\tif ( !Networking.IsHost || string.IsNullOrEmpty( text ) ) return;\n\t\tShow( \u0022broadcast_toast\u0022, SiteClient.Clip( text, 300 ) );\n\t}\n\n\t[Rpc.Broadcast( NetFlags.Reliable | NetFlags.HostOnly )]\n\tpublic static void Show( string kind, string text )\n\t{\n\t\tvar isToast = kind == \u0022toast\u0022 || kind == \u0022broadcast_toast\u0022;\n\t\tvar isBroadcast = kind == \u0022broadcast_chat\u0022 || kind == \u0022broadcast_toast\u0022;\n\t\tvar notification = new VoteNotification\n\t\t{\n\t\t\tKind = isToast ? \u0022toast\u0022 : \u0022chat\u0022,\n\t\t\tIsBroadcast = isBroadcast,\n\t\t\tText = text,\n\t\t};\n\n\t\tSboxlistEvents.DispatchNotification( notification );\n\t\tif ( isToast ) SboxlistEvents.RaiseToast( text );\n\n\t\tif ( notification.Handled ) return;\n\n\t\tif ( isToast )\n\t\t\tSandbox.Platform.Chat.AddText( \u0022\u2605 \u0022 \u002B text );\n\t\telse\n\t\t\tSandbox.Platform.Chat.AddText( text );\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistToastHud.cs","FileName":"SboxlistToastHud.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System.Collections.Generic;\nusing Sandbox;\nusing Sandbox.UI;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Optional ready-made on-screen toast HUD component. Add this component alongside SboxlistService\n/// (it automatically creates a ScreenPanel if none is on the GameObject) to show dark vote-reward\n/// toast banners in the top-right corner without writing custom UI code. Games with their own\n/// Razor HUD can omit this component and implement ISboxlistNotificationListener instead.\n/// \u003C/summary\u003E\npublic sealed class SboxlistToastHud : PanelComponent, ISboxlistNotificationListener\n{\n\tsealed class Entry\n\t{\n\t\tpublic string Text;\n\t\tpublic double ExpiresAt;\n\t}\n\n\t/// \u003Csummary\u003EHow many seconds each toast card stays on screen.\u003C/summary\u003E\n\t[Property] public float DisplaySeconds { get; set; } = 6.0f;\n\n\t/// \u003Csummary\u003EWhen true, suppresses the duplicate \u0022\u2605 ...\u0022 line in Sandbox.Platform.Chat for toasts.\u003C/summary\u003E\n\t[Property] public bool SuppressDefaultChat { get; set; } = false;\n\n\treadonly List\u003CEntry\u003E entries = new();\n\n\tprotected override void OnStart()\n\t{\n\t\tbase.OnStart();\n\t\tif ( !Application.IsDedicatedServer )\n\t\t\tComponents.GetOrCreate\u003CScreenPanel\u003E();\n\t}\n\n\tpublic void OnVoteNotification( VoteNotification notification )\n\t{\n\t\tif ( notification is null || notification.Kind != \u0022toast\u0022 ) return;\n\t\tif ( SuppressDefaultChat ) notification.Handled = true;\n\t\tif ( Application.IsDedicatedServer ) return;\n\n\t\tvar duration = DisplaySeconds \u003C 1f ? 1f : DisplaySeconds;\n\t\tentries.Add( new Entry { Text = \u0022\u2605 \u0022 \u002B notification.Text, ExpiresAt = RealTime.NowDouble \u002B duration } );\n\t\twhile ( entries.Count \u003E 5 ) entries.RemoveAt( 0 );\n\t\tRebuild();\n\t}\n\n\tprotected override void OnTreeFirstBuilt()\n\t{\n\t\tbase.OnTreeFirstBuilt();\n\t\tif ( Panel is null ) return;\n\t\tPanel.Style.Position = PositionMode.Absolute;\n\t\tPanel.Style.Top = 24;\n\t\tPanel.Style.Right = 24;\n\t\tPanel.Style.FlexDirection = FlexDirection.Column;\n\t\tPanel.Style.ZIndex = 1000;\n\t\tRebuild();\n\t}\n\n\tprotected override void OnUpdate()\n\t{\n\t\tbase.OnUpdate();\n\t\tif ( entries.Count == 0 ) return;\n\t\tvar now = RealTime.NowDouble;\n\t\tvar removed = false;\n\t\tfor ( var i = entries.Count - 1; i \u003E= 0; i-- )\n\t\t{\n\t\t\tif ( entries[i].ExpiresAt \u003C= now )\n\t\t\t{\n\t\t\t\tentries.RemoveAt( i );\n\t\t\t\tremoved = true;\n\t\t\t}\n\t\t}\n\t\tif ( removed ) Rebuild();\n\t}\n\n\tvoid Rebuild()\n\t{\n\t\tif ( Panel is null ) return;\n\t\tPanel.DeleteChildren( true );\n\t\tforeach ( var entry in entries )\n\t\t{\n\t\t\tvar card = Panel.AddChild\u003CLabel\u003E();\n\t\t\tcard.Text = entry.Text;\n\t\t\tcard.Style.BackgroundColor = new Color( 0.09f, 0.11f, 0.13f, 0.95f );\n\t\t\tcard.Style.FontColor = Color.White;\n\t\t\tcard.Style.FontSize = 16;\n\t\t\tcard.Style.FontWeight = 600;\n\t\t\tcard.Style.PaddingLeft = 14;\n\t\t\tcard.Style.PaddingRight = 14;\n\t\t\tcard.Style.PaddingTop = 10;\n\t\t\tcard.Style.PaddingBottom = 10;\n\t\t\tcard.Style.MarginBottom = 8;\n\t\t\tcard.Style.BorderLeftWidth = 4;\n\t\t\tcard.Style.BorderLeftColor = new Color( 0.31f, 0.27f, 0.90f );\n\t\t}\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SiteClient.cs","FileName":"SiteClient.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json.Nodes;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Talks to one site (PROTOCOL.md section 6): heartbeat every 60 s, poll every 15 s, acks right\n/// after, a join per player, test votes on request. Runs on the host only, from the main thread\n/// (SboxlistService.OnUpdate); never two requests of the same kind at once.\n/// \u003C/summary\u003E\npublic sealed class SiteClient\n{\n\t/// \u003Csummary\u003EThe largest body a site accepts (PROTOCOL.md section 2).\u003C/summary\u003E\n\tinternal const int MaxBodyBytes = 16384;\n\n\t/// \u003Csummary\u003EOne ack batch stays well under MaxBodyBytes, so 50 long acks still fit.\u003C/summary\u003E\n\tconst int MaxAckBatchBytes = 12000;\n\n\t/// \u003Csummary\u003EHow often a join (reward request) is tried before it is given up.\u003C/summary\u003E\n\tconst int MaxJoinAttempts = 3;\n\n\t/// \u003Csummary\u003EWhat a site has already delivered. Kept per site and server id, so a reload or a restarted site does not pay twice (this process only).\u003C/summary\u003E\n\tsealed class Dedupe\n\t{\n\t\tpublic readonly HashSet\u003Cstring\u003E Votes = new();\n\t\tpublic readonly Queue\u003Cstring\u003E VoteOrder = new();\n\t\tpublic readonly HashSet\u003Cstring\u003E Rewards = new();\n\t\tpublic readonly Queue\u003Cstring\u003E RewardOrder = new();\n\t}\n\n\tstatic readonly Dictionary\u003Cstring, Dedupe\u003E dedupes = new();\n\n\tpublic SiteConfig Config { get; }\n\n\tpublic int LastStatus { get; private set; }\n\tpublic string LastRoute { get; private set; } = \u0022\u0022;\n\tpublic string LastError { get; private set; } = \u0022\u0022;\n\tpublic bool HeartbeatAccepted { get; private set; }\n\tpublic bool Disabled { get; private set; }\n\tpublic string DisabledReason { get; private set; } = \u0022\u0022;\n\tpublic int VotesReceived { get; private set; }\n\tpublic int RewardsRun { get; private set; }\n\tpublic string LastVoteId { get; private set; } = \u0022\u0022;\n\tpublic double? ClockOffsetSeconds { get; private set; }\n\n\treadonly SboxlistService service;\n\treadonly byte[] hmacKey;\n\treadonly Dedupe dedupe;\n\n\tlong lastSequence;\n\tdouble nextHeartbeatAt;\n\tdouble nextPollAt;\n\tdouble pausedUntil;\n\tdouble ackRetryAt;\n\tdouble joinRetryAt;\n\tint ackLimit = 50;\n\tint failures;\n\tbool heartbeatBusy, pollBusy, ackBusy, joinBusy, testvoteBusy, infoBusy;\n\n\treadonly List\u003CJsonObject\u003E pendingAcks = new();\n\treadonly Queue\u003CJoinRequest\u003E joins = new();\n\n\tsealed class JoinRequest\n\t{\n\t\tpublic Connection Player;\n\t\tpublic string Reason;\n\t\tpublic int Attempts;\n\t}\n\n\tinternal sealed class Reply\n\t{\n\t\tpublic string Route = \u0022\u0022;\n\t\tpublic int Status;\n\t\tpublic long? RetryAfterSeconds;\n\t\tpublic JsonNode Json;\n\t\tpublic string Text = \u0022\u0022;\n\t\tpublic string Error = \u0022\u0022;\n\t\tpublic bool Ok =\u003E Status \u003E= 200 \u0026\u0026 Status \u003C 300;\n\t}\n\n\tpublic SiteClient( SiteConfig config, SboxlistService service )\n\t{\n\t\tConfig = config;\n\t\tthis.service = service;\n\t\thmacKey = SboxlistCrypto.KeyFromToken( config.Token );\n\n\t\tvar key = config.SiteId \u002B \u0022|\u0022 \u002B config.ServerId;\n\t\tif ( !dedupes.TryGetValue( key, out var found ) )\n\t\t{\n\t\t\tfound = new Dedupe();\n\t\t\tdedupes[key] = found;\n\t\t}\n\t\tdedupe = found;\n\t}\n\n\tdouble Now =\u003E RealTime.NowDouble;\n\n\tpublic void Tick()\n\t{\n\t\tif ( Disabled || Now \u003C pausedUntil ) return;\n\n\t\tif ( !heartbeatBusy \u0026\u0026 Now \u003E= nextHeartbeatAt ) _ = HeartbeatAsync();\n\t\tif ( !pollBusy \u0026\u0026 Now \u003E= nextPollAt ) _ = PollAsync();\n\t\tif ( !ackBusy \u0026\u0026 pendingAcks.Count \u003E 0 \u0026\u0026 Now \u003E= ackRetryAt ) _ = FlushAcksAsync();\n\t\tif ( !joinBusy \u0026\u0026 joins.Count \u003E 0 \u0026\u0026 Now \u003E= joinRetryAt ) _ = JoinAsync( joins.Dequeue() );\n\t}\n\n\tpublic void ForceHeartbeat()\n\t{\n\t\tnextHeartbeatAt = 0;\n\t\tpausedUntil = 0;\n\t}\n\n\tpublic void QueueJoin( Connection player, string reason )\n\t{\n\t\tif ( player is null || !Config.Rewards || Disabled ) return;\n\t\tjoins.Enqueue( new JoinRequest { Player = player, Reason = reason } );\n\t}\n\n\t// ---------------------------------------------------------------- requests\n\n\tstring Url( string route ) =\u003E Config.BaseUrl \u002B \u0022/v1/\u0022 \u002B route;\n\n\tinternal async Task\u003CReply\u003E SendAsync( string route, JsonObject body )\n\t{\n\t\tbody[\u0022v\u0022] = 1;\n\t\tbody[\u0022serverId\u0022] = Config.ServerId;\n\t\tvar json = body.ToJsonString();\n\t\tvar bytes = Encoding.UTF8.GetBytes( json );\n\t\tvar reply = new Reply { Route = route };\n\n\t\tif ( bytes.Length \u003E MaxBodyBytes )\n\t\t{\n\t\t\t// A bug in what we send (the ack batches are sized to prevent it): refused without a request.\n\t\t\treply.Status = 413;\n\t\t\treply.Error = $\u0022the body is {bytes.Length} bytes; the limit is {MaxBodyBytes}\u0022;\n\t\t\tLastRoute = route;\n\t\t\tLastStatus = reply.Status;\n\t\t\treturn reply;\n\t\t}\n\n\t\tvar timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString( CultureInfo.InvariantCulture );\n\t\tvar nonce = SboxlistCrypto.NewNonce();\n\n\t\tvar headers = new Dictionary\u003Cstring, string\u003E\n\t\t{\n\t\t\t[\u0022x-sbl-server\u0022] = Config.ServerId,\n\t\t\t[\u0022x-sbl-timestamp\u0022] = timestamp,\n\t\t\t[\u0022x-sbl-nonce\u0022] = nonce,\n\t\t\t[\u0022x-sbl-protocol\u0022] = \u00221\u0022,\n\t\t};\n\n\t\tif ( Config.Auth == \u0022hmac\u0022 )\n\t\t\theaders[\u0022x-sbl-signature\u0022] = SboxlistCrypto.Signature( hmacKey, Config.ServerId, timestamp, nonce, bytes );\n\t\telse\n\t\t\theaders[\u0022Authorization\u0022] = \u0022Bearer \u0022 \u002B Config.Token;\n\n\t\tif ( SboxlistConfig.Debug ) Log.Info( $\u0022[sboxlist] {Config.SiteId} \u2192 POST {route} {json}\u0022 );\n\n\t\ttry\n\t\t{\n\t\t\tusing var cts = new CancellationTokenSource( TimeSpan.FromSeconds( 10 ) );\n\t\t\tusing var content = new StringContent( json, Encoding.UTF8, \u0022application/json\u0022 );\n\t\t\tusing var response = await Http.RequestAsync( Url( route ), \u0022POST\u0022, content, headers, cts.Token );\n\t\t\treply.Status = (int)response.StatusCode;\n\t\t\tif ( response.Headers.TryGetValues( \u0022Retry-After\u0022, out var retryValues ) )\n\t\t\t{\n\t\t\t\tforeach ( var val in retryValues )\n\t\t\t\t{\n\t\t\t\t\tif ( val is not null \u0026\u0026 long.TryParse( val.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var retrySec ) )\n\t\t\t\t\t{\n\t\t\t\t\t\treply.RetryAfterSeconds = retrySec;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treply.Text = await response.Content.ReadAsStringAsync();\n\t\t\treply.Json = JsonRead.Parse( reply.Text );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\treply.Status = 0;\n\t\t\treply.Error = e.Message;\n\t\t}\n\n\t\tLastRoute = route;\n\t\tLastStatus = reply.Status;\n\t\tif ( SboxlistConfig.Debug ) Log.Info( $\u0022[sboxlist] {Config.SiteId} \u2190 {route} {reply.Status} {(reply.Status == 0 ? reply.Error : reply.Text)}\u0022 );\n\t\treturn reply;\n\t}\n\n\t/// \u003Csummary\u003ETurns a failed answer into \u0022wait this long\u0022 (seconds), and stops the site when retrying is pointless.\u003C/summary\u003E\n\tdouble Failed( Reply r )\n\t{\n\t\tvar error = JsonRead.Get( r.Json, \u0022error\u0022 );\n\t\tvar code = JsonRead.Str( error, \u0022code\u0022 ) ?? \u0022\u0022;\n\t\tvar message = JsonRead.Str( error, \u0022message\u0022 ) ?? r.Error;\n\t\tvar field = JsonRead.Str( error, \u0022field\u0022 );\n\t\tvar hint = JsonRead.Str( error, \u0022hint\u0022 );\n\t\tLastError = $\u0022{r.Route}: HTTP {r.Status} {code} {message}{(field is null ? \u0022\u0022 : $\u0022 (field {field})\u0022)}{(hint is null ? \u0022\u0022 : $\u0022 ({hint})\u0022)}\u0022.Trim();\n\n\t\tswitch ( r.Status )\n\t\t{\n\t\t\tcase 0:\n\t\t\tcase \u003E= 500:\n\t\t\t\tfailures\u002B\u002B;\n\t\t\t\tvar wait = Backoff( failures );\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: {LastError}; trying again in {wait:0} s\u0022 );\n\t\t\t\treturn wait;\n\n\t\t\tcase 429:\n\t\t\t\t// Protocol v0.2 sends retryAfterSeconds in the body; sboxlist.com (v1) sends only the Retry-After header (PROTOCOL.md 8, 14).\n\t\t\t\tvar retry = JsonRead.Long( error, \u0022retryAfterSeconds\u0022 ) ?? r.RetryAfterSeconds ?? 5;\n\t\t\t\treturn Math.Clamp( retry, 1, 300 );\n\n\t\t\tcase 401:\n\t\t\t\tvar tip = Config.Auth == \u0022bearer\u0022 ? \u0022 sboxlist.com accepts hmac only: set auth to hmac.\u0022 : \u0022\u0022;\n\t\t\t\tif ( Now \u003E= pausedUntil )\n\t\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: refused (401). Check the token, the auth setting and the server clock.{tip}\u0022 );\n\t\t\t\tpausedUntil = Now \u002B 60;\n\t\t\t\treturn 60;\n\n\t\t\tcase 404:\n\t\t\tcase 410:\n\t\t\t\tStop( LastError );\n\t\t\t\treturn 300;\n\n\t\t\tcase 400 when code == \u0022unsupported_version\u0022:\n\t\t\t\tStop( \u0022the site does not speak protocol 1; update the plugin\u0022 );\n\t\t\t\treturn 300;\n\n\t\t\tcase 400 when field == \u0022serverId\u0022:\n\t\t\t\tStop( \u0022the site refuses this serverId; use the id the site shows (sboxlist.com needs a UUID)\u0022 );\n\t\t\t\treturn 300;\n\n\t\t\tdefault:\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: {LastError}\u0022 );\n\t\t\t\treturn 60;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003ETrouble that may pass: no answer, a rate limit, refused for now (401), a server error.\u003C/summary\u003E\n\tstatic bool Retryable( int status ) =\u003E status == 0 || status == 401 || status == 429 || status \u003E= 500;\n\n\t/// \u003Csummary\u003E15, 30, 60, 120, then 300 s, with up to 20 % jitter (PROTOCOL.md section 8).\u003C/summary\u003E\n\tstatic double Backoff( int failures )\n\t{\n\t\tdouble[] steps = { 15, 30, 60, 120, 300 };\n\t\tvar step = steps[Math.Min( Math.Max( failures, 1 ) - 1, steps.Length - 1 )];\n\t\tvar jitter = Guid.NewGuid().ToByteArray()[0] / 255.0 * 0.2;\n\t\treturn Math.Min( 300, step * (1 \u002B jitter) );\n\t}\n\n\tvoid Stop( string reason )\n\t{\n\t\tDisabled = true;\n\t\tDisabledReason = reason;\n\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: stopped until sbl_reload or a restart: {reason}\u0022 );\n\t}\n\n\tvoid ClearErrorFrom( string route )\n\t{\n\t\tif ( LastError.StartsWith( route \u002B \u0022:\u0022 ) ) LastError = \u0022\u0022;\n\t}\n\n\t// ---------------------------------------------------------------- heartbeat\n\n\tasync Task HeartbeatAsync()\n\t{\n\t\theartbeatBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar now = DateTimeOffset.UtcNow;\n\t\t\tlastSequence = Math.Max( lastSequence \u002B 1, now.ToUnixTimeMilliseconds() );\n\t\t\tvar players = service.PlayerCount();\n\t\t\tvar maxPlayers = Math.Clamp( Math.Max( Networking.MaxPlayers, players ), 1, 1024 );\n\t\t\tvar stamp = now.UtcDateTime.ToString( \u0022yyyy-MM-dd\u0027T\u0027HH:mm:ss.fff\u0027Z\u0027\u0022, CultureInfo.InvariantCulture );\n\n\t\t\tvar body = new JsonObject\n\t\t\t{\n\t\t\t\t[\u0022type\u0022] = \u0022heartbeat\u0022,\n\t\t\t\t[\u0022sequence\u0022] = lastSequence,\n\t\t\t\t[\u0022players\u0022] = Math.Min( players, maxPlayers ),\n\t\t\t\t[\u0022maxPlayers\u0022] = maxPlayers,\n\t\t\t\t[\u0022bots\u0022] = 0,\n\t\t\t\t[\u0022map\u0022] = Clip( service.MapName, 128 ),\n\t\t\t\t[\u0022package\u0022] = Clip( Game.Ident ?? \u0022\u0022, 128 ),\n\t\t\t\t[\u0022build\u0022] = \u0022\u0022,\n\t\t\t\t[\u0022uptimeSeconds\u0022] = service.UptimeSeconds,\n\t\t\t\t// Protocol v1 (sboxlist.com) reads serverTimestamp; the v0.2 spec and the test backend read serverTime.\n\t\t\t\t// Both are sent, because each side ignores the fields it does not know (PROTOCOL.md section 3).\n\t\t\t\t[\u0022serverTime\u0022] = stamp,\n\t\t\t\t[\u0022serverTimestamp\u0022] = stamp,\n\t\t\t\t[\u0022plugin\u0022] = \u0022sboxlist/\u0022 \u002B SboxlistService.Version,\n\t\t\t};\n\n\t\t\tvar r = await SendAsync( \u0022heartbeat\u0022, body );\n\t\t\tif ( r.Ok )\n\t\t\t{\n\t\t\t\tfailures = 0;\n\t\t\t\tif ( !HeartbeatAccepted ) Log.Info( $\u0022[sboxlist] {Config.SiteId}: heartbeat accepted\u0022 );\n\t\t\t\tHeartbeatAccepted = true;\n\t\t\t\tLastError = \u0022\u0022;\n\t\t\t\tvar next = JsonRead.Long( r.Json, \u0022nextHeartbeatSeconds\u0022 ) ?? 60;\n\t\t\t\tnextHeartbeatAt = Now \u002B Math.Clamp( next, 20, 3600 );\n\t\t\t}\n\t\t\telse if ( r.Status == 409 )\n\t\t\t{\n\t\t\t\tnextHeartbeatAt = Now \u002B 60;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tHeartbeatAccepted = false;\n\t\t\t\tnextHeartbeatAt = Now \u002B Failed( r );\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\theartbeatBusy = false;\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- poll and ack\n\n\tasync Task PollAsync()\n\t{\n\t\tpollBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar r = await SendAsync( \u0022votes/poll\u0022, new JsonObject { [\u0022type\u0022] = \u0022poll\u0022 } );\n\t\t\tif ( !r.Ok )\n\t\t\t{\n\t\t\t\tnextPollAt = Now \u002B Failed( r );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfailures = 0;\n\t\t\tClearErrorFrom( r.Route );\n\t\t\tif ( JsonRead.Get( r.Json, \u0022messages\u0022 ) is JsonArray messages )\n\t\t\t{\n\t\t\t\tforeach ( var element in messages )\n\t\t\t\t{\n\t\t\t\t\tvar message = JsonRead.Message( element, out var rawChars );\n\t\t\t\t\tif ( message is null ) continue;\n\t\t\t\t\ttry { HandleMessage( message, rawChars ); }\n\t\t\t\t\tcatch ( Exception e ) { Log.Warning( $\u0022[sboxlist] {Config.SiteId}: a message could not be handled: {e.Message}\u0022 ); }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar after = JsonRead.Long( r.Json, \u0022pollAfterSeconds\u0022 ) ?? 15;\n\t\t\tnextPollAt = Now \u002B Math.Clamp( after, 5, 300 );\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tpollBusy = false;\n\t\t}\n\t}\n\n\tvoid HandleMessage( JsonNode message, int rawChars )\n\t{\n\t\tvar id = JsonRead.Str( message, \u0022id\u0022 );\n\t\tif ( !SboxlistConfig.IsIdent( id, 1, 64 ) ) return;\n\n\t\tvar type = JsonRead.Str( message, \u0022type\u0022 );\n\t\tif ( rawChars \u003E 4096 || (message?.ToJsonString().Length ?? 0) \u003E 4096 ) { Ack( id, false, \u0022vote\u0022, \u0022message too long\u0022 ); return; }\n\t\tif ( type != \u0022vote\u0022 ) { Ack( id, false, \u0022vote\u0022, \u0022unsupported\u0022 ); return; }\n\n\t\t// Seen before (our ack was lost): ack again, do nothing else.\n\t\tif ( !Remember( dedupe.Votes, dedupe.VoteOrder, id ) ) { Ack( id, true, \u0022vote\u0022 ); return; }\n\n\t\tvar identity = JsonRead.Get( message, \u0022identity\u0022 );\n\t\tvar idKind = JsonRead.Str( identity, \u0022kind\u0022 ) ?? \u0022\u0022;\n\t\tvar idKey = JsonRead.Str( identity, \u0022key\u0022 ) ?? \u0022\u0022;\n\t\tvar isTest = JsonRead.Bool( message, \u0022test\u0022 ) ?? id.StartsWith( \u0022test-\u0022 );\n\t\tvar online = isTest ? null : service.FindPlayer( idKind, idKey );\n\n\t\tvar vote = new VoteInfo\n\t\t{\n\t\t\tSiteId = Config.SiteId,\n\t\t\tId = id,\n\t\t\tIdentityKind = idKind,\n\t\t\tIdentityKey = idKey,\n\t\t\tAt = JsonRead.Str( message, \u0022at\u0022 ) ?? \u0022\u0022,\n\t\t\tIsTest = isTest,\n\t\t\tOnlinePlayer = online,\n\t\t};\n\n\t\tVotesReceived\u002B\u002B;\n\t\tLastVoteId = id;\n\t\tLog.Info( vote.IsTest\n\t\t\t? $\u0022[sboxlist] {Config.SiteId}: test vote arrived ({id}), identity {vote.IdentityKind} {vote.IdentityKey}\u0022\n\t\t\t: $\u0022[sboxlist] {Config.SiteId}: vote {id} from {vote.IdentityKind} {vote.IdentityKey}\u0022 );\n\n\t\tSboxlistEvents.RaiseVote( vote );\n\t\tAck( id, true, \u0022vote\u0022 );\n\n\t\t// The voter is online right now: ask for the reward at once.\n\t\tif ( !vote.IsTest \u0026\u0026 Config.Rewards \u0026\u0026 online is not null )\n\t\t\tQueueJoin( online, \u0022vote\u0022 );\n\t}\n\n\tinternal void Ack( string id, bool ok, string kind, string error = null )\n\t{\n\t\tvar item = new JsonObject { [\u0022id\u0022] = id, [\u0022ok\u0022] = ok, [\u0022kind\u0022] = kind };\n\t\tif ( error is not null ) item[\u0022error\u0022] = Clip( error, 200 );\n\t\tpendingAcks.Add( item );\n\t}\n\n\tasync Task FlushAcksAsync()\n\t{\n\t\tackBusy = true;\n\t\ttry\n\t\t{\n\t\t\t// One batch: up to ackLimit acks and about 12 KB, so the body stays under the site\u0027s limit.\n\t\t\tvar batch = new List\u003CJsonObject\u003E();\n\t\t\tvar size = 0;\n\t\t\tforeach ( var item in pendingAcks )\n\t\t\t{\n\t\t\t\tvar length = Encoding.UTF8.GetByteCount( item.ToJsonString() ) \u002B 1;\n\t\t\t\tif ( batch.Count == ackLimit || (batch.Count \u003E 0 \u0026\u0026 size \u002B length \u003E MaxAckBatchBytes) ) break;\n\t\t\t\tbatch.Add( item );\n\t\t\t\tsize \u002B= length;\n\t\t\t}\n\t\t\tpendingAcks.RemoveRange( 0, batch.Count );\n\n\t\t\t// The request gets copies: a JSON node can have one parent only, and the originals go back if the send fails.\n\t\t\tvar list = new JsonArray();\n\t\t\tforeach ( var item in batch ) list.Add( (JsonObject)JsonNode.Parse( item.ToJsonString() ) );\n\n\t\t\tvar r = await SendAsync( \u0022votes/ack\u0022, new JsonObject { [\u0022type\u0022] = \u0022ack\u0022, [\u0022acks\u0022] = list } );\n\t\t\tif ( r.Ok )\n\t\t\t{\n\t\t\t\tackLimit = 50;\n\t\t\t\tClearErrorFrom( r.Route );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The site refused several acks together: send them one at a time, so one bad item is dropped alone.\n\t\t\tif ( batch.Count \u003E 1 \u0026\u0026 (r.Status == 400 || r.Status == 413) )\n\t\t\t{\n\t\t\t\tackLimit = 1;\n\t\t\t\tpendingAcks.InsertRange( 0, batch );\n\t\t\t\tackRetryAt = Now;\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: the site refused {batch.Count} acks together (HTTP {r.Status}); sending them one by one\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The site refused this ack itself (a bug in what we sent, or an unknown field): sending it again changes nothing.\n\t\t\t// A vote whose ack never arrives is sent again by the site, and then it is acked again.\n\t\t\tif ( r.Status == 400 || r.Status == 405 || r.Status == 413 || r.Status == 415 )\n\t\t\t{\n\t\t\t\tFailed( r );\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: {batch.Count} ack(s) dropped\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Network trouble, 429, 5xx, 401, 404 or 410: keep the acks and try again later, on the ack route\u0027s own timer.\n\t\t\tpendingAcks.InsertRange( 0, batch );\n\t\t\tackRetryAt = Now \u002B Failed( r );\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tackBusy = false;\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- join and rewards\n\n\tasync Task JoinAsync( JoinRequest join )\n\t{\n\t\tjoinBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar player = join.Player;\n\t\t\tvar steam = player.SteamId.ValueUnsigned;\n\t\t\tvar steamText = steam == 0 ? null : steam.ToString( CultureInfo.InvariantCulture );\n\t\t\tif ( !IsIndividualSteamId( steamText ) ) steamText = null;\n\n\t\t\t// Protocol v1 name rule: 1 to 32 code points, no NUL, no unpaired surrogate. A name\n\t\t\t// outside it is not sent: the join carries the SteamID64 alone (the SteamID-only join), so a Steam vote is still paid,\n\t\t\t// and no name vote can match it. A player with neither a usable name nor a SteamID64 is not sent at all.\n\t\t\t// The name is sent exactly as the server reports it, with no trimming and no character removal.\n\t\t\tvar name = player.DisplayName ?? \u0022\u0022;\n\t\t\tvar nameFits = FitsJoinName( name );\n\t\t\tif ( !nameFits \u0026\u0026 steamText is null )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: a player with no usable name and no SteamID64 cannot be matched to a vote; no join sent\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar who = nameFits ? name : steamText;\n\n\t\t\tvar body = new JsonObject\n\t\t\t{\n\t\t\t\t[\u0022type\u0022] = \u0022join\u0022,\n\t\t\t\t[\u0022reason\u0022] = join.Reason,\n\t\t\t\t[\u0022playerName\u0022] = nameFits ? name : null,\n\t\t\t\t[\u0022steamId\u0022] = steamText,\n\t\t\t};\n\n\t\t\tvar r = await SendAsync( \u0022rewards/join\u0022, body );\n\t\t\tif ( !r.Ok )\n\t\t\t{\n\t\t\t\tvar wait = Failed( r );\n\t\t\t\tif ( Retryable( r.Status ) \u0026\u0026 join.Attempts \u002B 1 \u003C MaxJoinAttempts )\n\t\t\t\t{\n\t\t\t\t\t// A vote is acked before its reward is asked for, so the site will not send it again: the join is tried again.\n\t\t\t\t\tjoin.Attempts\u002B\u002B;\n\t\t\t\t\tjoinRetryAt = Now \u002B wait;\n\t\t\t\t\tjoins.Enqueue( join );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: the reward request for {who} was given up after {join.Attempts \u002B 1} attempt(s)\u0022 );\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tClearErrorFrom( r.Route );\n\t\t\tif ( JsonRead.Get( r.Json, \u0022messages\u0022 ) is JsonArray rewards )\n\t\t\t{\n\t\t\t\tforeach ( var element in rewards )\n\t\t\t\t{\n\t\t\t\t\tvar reward = JsonRead.Message( element, out var rawChars );\n\t\t\t\t\tif ( reward is null ) continue;\n\t\t\t\t\ttry { RunReward( reward, player, rawChars ); }\n\t\t\t\t\tcatch ( Exception e ) { Log.Warning( $\u0022[sboxlist] {Config.SiteId}: a reward could not be run: {e.Message}\u0022 ); }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tjoinBusy = false;\n\t\t}\n\t}\n\n\tvoid RunReward( JsonNode reward, Connection player, int rawChars )\n\t{\n\t\tvar id = JsonRead.Str( reward, \u0022id\u0022 );\n\t\tif ( !SboxlistConfig.IsIdent( id, 1, 64 ) )\n\t\t{\n\t\t\t// Without an id the library cannot ack the reward, so the site could never close it (PROTOCOL.md 6.6).\n\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: a reward without a valid id was dropped; the site must send one (PROTOCOL.md 6.6)\u0022 );\n\t\t\treturn;\n\t\t}\n\n\t\tif ( !Remember( dedupe.Rewards, dedupe.RewardOrder, id ) ) { Ack( id, true, \u0022reward\u0022 ); return; }\n\n\t\t// Remembered above, so a run that fails is never run again: it is acked with the reason instead.\n\t\tstring error;\n\t\tif ( rawChars \u003E 4096 || (reward?.ToJsonString().Length ?? 0) \u003E 4096 )\n\t\t\terror = \u0022message too long\u0022;\n\t\telse if ( JsonRead.Str( reward, \u0022type\u0022 ) is string rtype \u0026\u0026 rtype != \u0022reward\u0022 )\n\t\t\terror = \u0022unsupported\u0022;\n\t\telse\n\t\t{\n\t\t\ttry { error = SboxlistRewards.Run( this, reward, player ); }\n\t\t\tcatch ( Exception e ) { error = Clip( \u0022reward failed: \u0022 \u002B e.Message, 200 ); }\n\t\t}\n\n\t\tif ( error is null ) RewardsRun\u002B\u002B;\n\t\tAck( id, error is null, \u0022reward\u0022, error );\n\t}\n\n\t// ---------------------------------------------------------------- operator commands\n\n\tpublic async Task RequestTestvoteAsync()\n\t{\n\t\tif ( testvoteBusy ) return;\n\t\ttestvoteBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar r = await SendAsync( \u0022votes/testvote\u0022, new JsonObject { [\u0022type\u0022] = \u0022testvote\u0022 } );\n\t\t\tif ( r.Ok )\n\t\t\t{\n\t\t\t\tClearErrorFrom( r.Route );\n\t\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: test vote {JsonRead.Str( r.Json, \u0022id\u0022 )} queued; it arrives with the next poll\u0022 );\n\t\t\t\tnextPollAt = Math.Min( nextPollAt, Now \u002B 1 );\n\t\t\t}\n\t\t\telse if ( r.Status == 404 )\n\t\t\t{\n\t\t\t\t// Not a stop: a site without a server-side test vote (sboxlist.com has none) just says so.\n\t\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: this site has no server-side test vote; use the site\u0027s own test vote\u0022 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFailed( r );\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: test vote refused: {LastError}\u0022 );\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\ttestvoteBusy = false;\n\t\t}\n\t}\n\n\tpublic async Task InfoAsync()\n\t{\n\t\tif ( infoBusy ) return;\n\t\tinfoBusy = true;\n\t\ttry\n\t\t{\n\t\t\tusing var cts = new CancellationTokenSource( TimeSpan.FromSeconds( 10 ) );\n\t\t\tusing var response = await Http.RequestAsync( Url( \u0022info\u0022 ), \u0022GET\u0022, null, null, cts.Token );\n\t\t\tif ( (int)response.StatusCode == 404 )\n\t\t\t{\n\t\t\t\t// Not a stop: a site without /v1/info (sboxlist.com has none) just is not clock-checked.\n\t\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: this site has no /v1/info; the clock is not checked\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar text = await response.Content.ReadAsStringAsync();\n\t\t\tvar json = JsonRead.Parse( text );\n\t\t\tvar serverTime = JsonRead.Long( json, \u0022serverTime\u0022 );\n\t\t\tif ( serverTime is long t ) ClockOffsetSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - t;\n\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: info HTTP {(int)response.StatusCode}, site \u0027{JsonRead.Str( json, \u0022siteId\u0022 )}\u0027, clock difference {ClockOffsetSeconds?.ToString( \u00220\u0022 ) ?? \u0022?\u0022} s\u0022 );\n\t\t\tif ( ClockOffsetSeconds is double d \u0026\u0026 Math.Abs( d ) \u003E 60 )\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: this clock is {d:0} s off the site\u0027s; over 300 s every request is refused\u0022 );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: info failed: {e.Message}\u0022 );\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tinfoBusy = false;\n\t\t}\n\t}\n\n\tpublic string Describe()\n\t{\n\t\tvar state = Disabled ? $\u0022STOPPED ({DisabledReason})\u0022 : HeartbeatAccepted ? \u0022online\u0022 : \u0022not accepted yet\u0022;\n\t\treturn $\u0022{Config.SiteId} [{Config.Auth}] {state}; last {LastRoute} HTTP {LastStatus}; votes {VotesReceived}, rewards {RewardsRun}; acks waiting {pendingAcks.Count}, joins waiting {joins.Count}\u0022\n\t\t\t\u002B (LastError.Length \u003E 0 ? $\u0022; last error: {LastError}\u0022 : \u0022\u0022);\n\t}\n\n\t// ---------------------------------------------------------------- helpers\n\n\tstatic bool Remember( HashSet\u003Cstring\u003E set, Queue\u003Cstring\u003E order, string id )\n\t{\n\t\tif ( !set.Add( id ) ) return false;\n\t\torder.Enqueue( id );\n\t\twhile ( order.Count \u003E 1000 ) set.Remove( order.Dequeue() );\n\t\treturn true;\n\t}\n\n\t/// \u003Csummary\u003EClips text to max characters without splitting surrogate pairs or keeping control/lone-surrogate characters.\u003C/summary\u003E\n\tinternal static string Clip( string value, int max )\n\t{\n\t\tif ( string.IsNullOrEmpty( value ) || max \u003C= 0 ) return \u0022\u0022;\n\t\tvar sb = new StringBuilder( Math.Min( value.Length, max ) );\n\t\tfor ( var i = 0; i \u003C value.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = value[i];\n\t\t\tif ( char.IsControl( c ) )\n\t\t\t{\n\t\t\t\tif ( sb.Length \u002B 1 \u003E max ) break;\n\t\t\t\tsb.Append( \u0027 \u0027 );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C value.Length \u0026\u0026 char.IsLowSurrogate( value[i \u002B 1] ) )\n\t\t\t{\n\t\t\t\tif ( sb.Length \u002B 2 \u003E max ) break;\n\t\t\t\tsb.Append( c ).Append( value[\u002B\u002Bi] );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( char.IsSurrogate( c ) )\n\t\t\t{\n\t\t\t\tif ( sb.Length \u002B 1 \u003E max ) break;\n\t\t\t\tsb.Append( \u0027 \u0027 );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( sb.Length \u002B 1 \u003E max ) break;\n\t\t\tsb.Append( c );\n\t\t}\n\t\treturn sb.ToString();\n\t}\n\n\t/// \u003Csummary\u003EValve Universe 1 AccountType 1 Individual SteamID64 (sboxlist.com protocol v1 STEAM_ID: 7656119 \u002B 10 digits).\u003C/summary\u003E\n\tinternal static bool IsIndividualSteamId( string value )\n\t{\n\t\tif ( value is null || value.Length != 17 || !value.StartsWith( \u00227656119\u0022 ) ) return false;\n\t\tforeach ( var c in value ) if ( c \u003C \u00270\u0027 || c \u003E \u00279\u0027 ) return false;\n\t\treturn true;\n\t}\n\n\t/// Protocol v1 join name rule: 1 to 32 code points, no NUL and no unpaired surrogate.\n\tinternal static bool FitsJoinName( string name )\n\t{\n\t\tif ( string.IsNullOrEmpty( name ) ) return false;\n\t\tvar codePoints = 0;\n\t\tfor ( var i = 0; i \u003C name.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = name[i];\n\t\t\tif ( c == \u0027\\0\u0027 ) return false;\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C name.Length \u0026\u0026 char.IsLowSurrogate( name[i \u002B 1] ) ) i\u002B\u002B;\n\t\t\telse if ( char.IsSurrogate( c ) ) return false;\n\t\t\tif ( \u002B\u002BcodePoints \u003E 32 ) return false;\n\t\t}\n\t\treturn true;\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistService.cs","FileName":"SboxlistService.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Put one of these in the scene the server loads (next to the NetworkHelper). It runs only on\n/// the host: it reads the config, sends heartbeats, polls for votes and asks for rewards when a\n/// player joins. Clients do nothing.\n/// \u003C/summary\u003E\npublic sealed class SboxlistService : Component, Component.INetworkListener\n{\n\tpublic const string Version = \u00221.0.0\u0022;\n\n\tpublic static SboxlistService Instance { get; private set; }\n\n\tpublic IReadOnlyList\u003CSiteClient\u003E Sites =\u003E sites;\n\n\treadonly List\u003CSiteClient\u003E sites = new();\n\tdouble startedAt;\n\tbool loaded;\n\n\tprotected override void OnStart()\n\t{\n\t\tInstance = this;\n\t\tstartedAt = RealTime.NowDouble;\n\t}\n\n\tprotected override void OnUpdate()\n\t{\n\t\tif ( !Networking.IsHost ) return;\n\n\t\tif ( !loaded )\n\t\t{\n\t\t\tloaded = true;\n\t\t\tReload();\n\t\t}\n\n\t\tforeach ( var site in sites )\n\t\t\tsite.Tick();\n\t}\n\n\tprotected override void OnDestroy()\n\t{\n\t\tif ( Instance == this ) Instance = null;\n\t}\n\n\tpublic void Reload()\n\t{\n\t\tvar previous = new List\u003CSiteClient\u003E( sites );\n\t\tsites.Clear();\n\t\tvar configs = SboxlistConfig.Load( out var source );\n\t\tLog.Info( $\u0022[sboxlist] {Version} config: {source}\u0022 );\n\t\tLog.Info( $\u0022[sboxlist] config file path: {SboxlistConfig.FullPath()}\u0022 );\n\n\t\tforeach ( var config in configs )\n\t\t{\n\t\t\t// A running site with the same identity keeps its state (pending acks and, through its server id, what it\n\t\t\t// has seen). Only the rewards setting can change in place. A stopped site starts again.\n\t\t\tvar kept = previous.FirstOrDefault( s =\u003E !s.Disabled \u0026\u0026 SameSite( s.Config, config ) );\n\t\t\tif ( kept is not null )\n\t\t\t{\n\t\t\t\tkept.Config.Rewards = config.Rewards;\n\t\t\t\tsites.Add( kept );\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvar site = new SiteClient( config, this );\n\t\t\tsites.Add( site );\n\t\t\tLog.Info( $\u0022[sboxlist] site {config.SiteId}: {config.BaseUrl} as {config.ServerId}, auth {config.Auth}, rewards {(config.Rewards ? \u0022on\u0022 : \u0022off\u0022)}\u0022 );\n\t\t\t_ = site.InfoAsync();\n\t\t}\n\n\t\tif ( sites.Count == 0 )\n\t\t\tLog.Warning( \u0022[sboxlist] no site configured; nothing will be sent\u0022 );\n\t}\n\n\tstatic bool SameSite( SiteConfig a, SiteConfig b ) =\u003E\n\t\ta.SiteId == b.SiteId \u0026\u0026 a.BaseUrl == b.BaseUrl \u0026\u0026 a.ServerId == b.ServerId \u0026\u0026 a.Token == b.Token \u0026\u0026 a.Auth == b.Auth;\n\n\t/// \u003Csummary\u003ECalled on the host when a player is fully in the game.\u003C/summary\u003E\n\tpublic void OnActive( Connection channel )\n\t{\n\t\tif ( !Networking.IsHost || channel is null ) return;\n\t\tif ( Application.IsDedicatedServer \u0026\u0026 channel.IsHost ) return;\n\t\tforeach ( var site in sites )\n\t\t\tsite.QueueJoin( channel, \u0022join\u0022 );\n\t}\n\n\tinternal int PlayerCount()\n\t{\n\t\tvar all = Connection.All;\n\t\tif ( all is null ) return 0;\n\t\treturn Application.IsDedicatedServer ? all.Count( c =\u003E !c.IsHost ) : all.Count;\n\t}\n\n\tinternal string MapName =\u003E Scene?.Name ?? \u0022\u0022;\n\n\tinternal long UptimeSeconds =\u003E (long)Math.Max( 0, RealTime.NowDouble - startedAt );\n\n\t/// \u003Csummary\u003EThe connected player a vote belongs to, by SteamID64 or by exact name.\u003C/summary\u003E\n\tinternal Connection FindPlayer( string identityKind, string identityKey )\n\t{\n\t\tvar all = Connection.All;\n\t\tif ( all is null || string.IsNullOrEmpty( identityKey ) ) return null;\n\n\t\tforeach ( var c in all )\n\t\t{\n\t\t\tif ( Application.IsDedicatedServer \u0026\u0026 c.IsHost ) continue;\n\t\t\tif ( identityKind == \u0022steam\u0022 \u0026\u0026 c.SteamId.ValueUnsigned.ToString( System.Globalization.CultureInfo.InvariantCulture ) == identityKey ) return c;\n\t\t\tif ( identityKind == \u0022name\u0022 \u0026\u0026 c.DisplayName == identityKey ) return c;\n\t\t}\n\n\t\treturn null;\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SboxlistCommands.cs","FileName":"SboxlistCommands.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System.Text;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Console commands for the owner (type them in the server console, or in the editor console\n/// while playing). They act only on the host; on a client they say so and do nothing.\n/// \u003C/summary\u003E\npublic static class SboxlistCommands\n{\n\tstatic SboxlistService HostService()\n\t{\n\t\tif ( !Networking.IsHost )\n\t\t{\n\t\t\tLog.Warning( \u0022[sboxlist] run this on the server (host), not on a client\u0022 );\n\t\t\treturn null;\n\t\t}\n\n\t\tvar service = SboxlistService.Instance;\n\t\tif ( service is null ) Log.Warning( \u0022[sboxlist] there is no SboxlistService component in the scene\u0022 );\n\t\treturn service;\n\t}\n\n\t[ConCmd( \u0022sbl_status\u0022 )]\n\tpublic static void Status()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tLog.Info( $\u0022[sboxlist] {SboxlistService.Version}, {service.Sites.Count} site(s), config {SboxlistConfig.FullPath()}\u0022 );\n\t\tforeach ( var site in service.Sites ) Log.Info( \u0022[sboxlist] \u0022 \u002B site.Describe() );\n\t}\n\n\t[ConCmd( \u0022sbl_info\u0022 )]\n\tpublic static void Info()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tforeach ( var site in service.Sites ) _ = site.InfoAsync();\n\t}\n\n\t[ConCmd( \u0022sbl_heartbeat\u0022 )]\n\tpublic static void Heartbeat()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tforeach ( var site in service.Sites ) site.ForceHeartbeat();\n\t\tLog.Info( \u0022[sboxlist] heartbeat on the next frame\u0022 );\n\t}\n\n\t[ConCmd( \u0022sbl_testvote\u0022 )]\n\tpublic static void Testvote()\n\t{\n\t\tvar service = HostService();\n\t\tif ( service is null ) return;\n\t\tforeach ( var site in service.Sites ) _ = site.RequestTestvoteAsync();\n\t}\n\n\t[ConCmd( \u0022sbl_reload\u0022 )]\n\tpublic static void Reload()\n\t{\n\t\tvar service = HostService();\n\t\tservice?.Reload();\n\t}\n\n\t/// \u003Csummary\u003EVerifies the HMAC-SHA256 implementation against fixed RFC 4231 and protocol v1 vectors offline.\u003C/summary\u003E\n\t[ConCmd( \u0022sbl_hmac_selftest\u0022 )]\n\tpublic static void HmacSelftest()\n\t{\n\t\tvar rfc = SboxlistCrypto.Hex( SboxlistCrypto.HmacSha256( Encoding.UTF8.GetBytes( \u0022Jefe\u0022 ), Encoding.UTF8.GetBytes( \u0022what do ya want for nothing?\u0022 ) ) );\n\t\tvar rfcOk = rfc == \u00225bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843\u0022;\n\t\tLog.Info( $\u0022[sboxlist] RFC 4231 case 2: {rfc} {(rfcOk ? \u0022PASS\u0022 : \u0022FAIL\u0022)}\u0022 );\n\n\t\tvar key = SboxlistCrypto.KeyFromToken( \u0022sbs_\u0022 \u002B new string( \u0027A\u0027, 43 ) );\n\t\tvar body = Encoding.UTF8.GetBytes( \u0022{\\\u0022v\\\u0022:1,\\\u0022type\\\u0022:\\\u0022heartbeat\\\u0022}\u0022 );\n\t\tvar sig = SboxlistCrypto.Signature( key, \u00223f2a9c1e-5b7d-4e8a-9c0d-1a2b3c4d5e6f\u0022, \u00221790000000\u0022, \u0022abcdefghijklmnop\u0022, body );\n\t\tvar sigOk = sig == \u002262c1de08862566ae6cc2008bcef3a3bccb56c6e0e53897f48fc08883ae2cccfd\u0022;\n\t\tLog.Info( $\u0022[sboxlist] protocol v1 vector: {sig} {(sigOk ? \u0022PASS\u0022 : \u0022FAIL\u0022)}\u0022 );\n\t}\n\n\t/// \u003Csummary\u003ESafe built-in target for testing console-command rewards: logs the resolved SteamID64 and amount.\u003C/summary\u003E\n\t[ConCmd( \u0022sbl_test_reward\u0022 )]\n\tpublic static void TestReward( string steamId, int amount )\n\t{\n\t\tLog.Info( $\u0022[sboxlist] sbl_test_reward ran: steamid {steamId}, amount {amount}\u0022 );\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"SiteClient.cs","FileName":"SiteClient.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json.Nodes;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Talks to one site (PROTOCOL.md section 6): heartbeat every 60 s, poll every 15 s, acks right\n/// after, a join per player, test votes on request. Runs on the host only, from the main thread\n/// (SboxlistService.OnUpdate); never two requests of the same kind at once.\n/// \u003C/summary\u003E\npublic sealed class SiteClient\n{\n\t/// \u003Csummary\u003EThe largest body a site accepts (PROTOCOL.md section 2).\u003C/summary\u003E\n\tinternal const int MaxBodyBytes = 16384;\n\n\t/// \u003Csummary\u003EOne ack batch stays well under MaxBodyBytes, so 50 long acks still fit.\u003C/summary\u003E\n\tconst int MaxAckBatchBytes = 12000;\n\n\t/// \u003Csummary\u003EHow often a join (reward request) is tried before it is given up.\u003C/summary\u003E\n\tconst int MaxJoinAttempts = 3;\n\n\t/// \u003Csummary\u003EWhat a site has already delivered. Kept per site and server id, so a reload or a restarted site does not pay twice (this process only).\u003C/summary\u003E\n\tsealed class Dedupe\n\t{\n\t\tpublic readonly HashSet\u003Cstring\u003E Votes = new();\n\t\tpublic readonly Queue\u003Cstring\u003E VoteOrder = new();\n\t\tpublic readonly HashSet\u003Cstring\u003E Rewards = new();\n\t\tpublic readonly Queue\u003Cstring\u003E RewardOrder = new();\n\t}\n\n\tstatic readonly Dictionary\u003Cstring, Dedupe\u003E dedupes = new();\n\n\tpublic SiteConfig Config { get; }\n\n\tpublic int LastStatus { get; private set; }\n\tpublic string LastRoute { get; private set; } = \u0022\u0022;\n\tpublic string LastError { get; private set; } = \u0022\u0022;\n\tpublic bool HeartbeatAccepted { get; private set; }\n\tpublic bool Disabled { get; private set; }\n\tpublic string DisabledReason { get; private set; } = \u0022\u0022;\n\tpublic int VotesReceived { get; private set; }\n\tpublic int RewardsRun { get; private set; }\n\tpublic string LastVoteId { get; private set; } = \u0022\u0022;\n\tpublic double? ClockOffsetSeconds { get; private set; }\n\n\treadonly SboxlistService service;\n\treadonly byte[] hmacKey;\n\treadonly Dedupe dedupe;\n\n\tlong lastSequence;\n\tdouble nextHeartbeatAt;\n\tdouble nextPollAt;\n\tdouble pausedUntil;\n\tdouble ackRetryAt;\n\tdouble joinRetryAt;\n\tint ackLimit = 50;\n\tint failures;\n\tbool heartbeatBusy, pollBusy, ackBusy, joinBusy, testvoteBusy, infoBusy;\n\n\treadonly List\u003CJsonObject\u003E pendingAcks = new();\n\treadonly Queue\u003CJoinRequest\u003E joins = new();\n\n\tsealed class JoinRequest\n\t{\n\t\tpublic Connection Player;\n\t\tpublic string Reason;\n\t\tpublic int Attempts;\n\t}\n\n\tinternal sealed class Reply\n\t{\n\t\tpublic string Route = \u0022\u0022;\n\t\tpublic int Status;\n\t\tpublic long? RetryAfterSeconds;\n\t\tpublic JsonNode Json;\n\t\tpublic string Text = \u0022\u0022;\n\t\tpublic string Error = \u0022\u0022;\n\t\tpublic bool Ok =\u003E Status \u003E= 200 \u0026\u0026 Status \u003C 300;\n\t}\n\n\tpublic SiteClient( SiteConfig config, SboxlistService service )\n\t{\n\t\tConfig = config;\n\t\tthis.service = service;\n\t\thmacKey = SboxlistCrypto.KeyFromToken( config.Token );\n\n\t\tvar key = config.SiteId \u002B \u0022|\u0022 \u002B config.ServerId;\n\t\tif ( !dedupes.TryGetValue( key, out var found ) )\n\t\t{\n\t\t\tfound = new Dedupe();\n\t\t\tdedupes[key] = found;\n\t\t}\n\t\tdedupe = found;\n\t}\n\n\tdouble Now =\u003E RealTime.NowDouble;\n\n\tpublic void Tick()\n\t{\n\t\tif ( Disabled || Now \u003C pausedUntil ) return;\n\n\t\tif ( !heartbeatBusy \u0026\u0026 Now \u003E= nextHeartbeatAt ) _ = HeartbeatAsync();\n\t\tif ( !pollBusy \u0026\u0026 Now \u003E= nextPollAt ) _ = PollAsync();\n\t\tif ( !ackBusy \u0026\u0026 pendingAcks.Count \u003E 0 \u0026\u0026 Now \u003E= ackRetryAt ) _ = FlushAcksAsync();\n\t\tif ( !joinBusy \u0026\u0026 joins.Count \u003E 0 \u0026\u0026 Now \u003E= joinRetryAt ) _ = JoinAsync( joins.Dequeue() );\n\t}\n\n\tpublic void ForceHeartbeat()\n\t{\n\t\tnextHeartbeatAt = 0;\n\t\tpausedUntil = 0;\n\t}\n\n\tpublic void QueueJoin( Connection player, string reason )\n\t{\n\t\tif ( player is null || !Config.Rewards || Disabled ) return;\n\t\tjoins.Enqueue( new JoinRequest { Player = player, Reason = reason } );\n\t}\n\n\t// ---------------------------------------------------------------- requests\n\n\tstring Url( string route ) =\u003E Config.BaseUrl \u002B \u0022/v1/\u0022 \u002B route;\n\n\tinternal async Task\u003CReply\u003E SendAsync( string route, JsonObject body )\n\t{\n\t\tbody[\u0022v\u0022] = 1;\n\t\tbody[\u0022serverId\u0022] = Config.ServerId;\n\t\tvar json = body.ToJsonString();\n\t\tvar bytes = Encoding.UTF8.GetBytes( json );\n\t\tvar reply = new Reply { Route = route };\n\n\t\tif ( bytes.Length \u003E MaxBodyBytes )\n\t\t{\n\t\t\t// A bug in what we send (the ack batches are sized to prevent it): refused without a request.\n\t\t\treply.Status = 413;\n\t\t\treply.Error = $\u0022the body is {bytes.Length} bytes; the limit is {MaxBodyBytes}\u0022;\n\t\t\tLastRoute = route;\n\t\t\tLastStatus = reply.Status;\n\t\t\treturn reply;\n\t\t}\n\n\t\tvar timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString( CultureInfo.InvariantCulture );\n\t\tvar nonce = SboxlistCrypto.NewNonce();\n\n\t\tvar headers = new Dictionary\u003Cstring, string\u003E\n\t\t{\n\t\t\t[\u0022x-sbl-server\u0022] = Config.ServerId,\n\t\t\t[\u0022x-sbl-timestamp\u0022] = timestamp,\n\t\t\t[\u0022x-sbl-nonce\u0022] = nonce,\n\t\t\t[\u0022x-sbl-protocol\u0022] = \u00221\u0022,\n\t\t};\n\n\t\tif ( Config.Auth == \u0022hmac\u0022 )\n\t\t\theaders[\u0022x-sbl-signature\u0022] = SboxlistCrypto.Signature( hmacKey, Config.ServerId, timestamp, nonce, bytes );\n\t\telse\n\t\t\theaders[\u0022Authorization\u0022] = \u0022Bearer \u0022 \u002B Config.Token;\n\n\t\tif ( SboxlistConfig.Debug ) Log.Info( $\u0022[sboxlist] {Config.SiteId} \u2192 POST {route} {json}\u0022 );\n\n\t\ttry\n\t\t{\n\t\t\tusing var cts = new CancellationTokenSource( TimeSpan.FromSeconds( 10 ) );\n\t\t\tusing var content = new StringContent( json, Encoding.UTF8, \u0022application/json\u0022 );\n\t\t\tusing var response = await Http.RequestAsync( Url( route ), \u0022POST\u0022, content, headers, cts.Token );\n\t\t\treply.Status = (int)response.StatusCode;\n\t\t\tif ( response.Headers.TryGetValues( \u0022Retry-After\u0022, out var retryValues ) )\n\t\t\t{\n\t\t\t\tforeach ( var val in retryValues )\n\t\t\t\t{\n\t\t\t\t\tif ( val is not null \u0026\u0026 long.TryParse( val.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var retrySec ) )\n\t\t\t\t\t{\n\t\t\t\t\t\treply.RetryAfterSeconds = retrySec;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treply.Text = await response.Content.ReadAsStringAsync();\n\t\t\treply.Json = JsonRead.Parse( reply.Text );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\treply.Status = 0;\n\t\t\treply.Error = e.Message;\n\t\t}\n\n\t\tLastRoute = route;\n\t\tLastStatus = reply.Status;\n\t\tif ( SboxlistConfig.Debug ) Log.Info( $\u0022[sboxlist] {Config.SiteId} \u2190 {route} {reply.Status} {(reply.Status == 0 ? reply.Error : reply.Text)}\u0022 );\n\t\treturn reply;\n\t}\n\n\t/// \u003Csummary\u003ETurns a failed answer into \u0022wait this long\u0022 (seconds), and stops the site when retrying is pointless.\u003C/summary\u003E\n\tdouble Failed( Reply r )\n\t{\n\t\tvar error = JsonRead.Get( r.Json, \u0022error\u0022 );\n\t\tvar code = JsonRead.Str( error, \u0022code\u0022 ) ?? \u0022\u0022;\n\t\tvar message = JsonRead.Str( error, \u0022message\u0022 ) ?? r.Error;\n\t\tvar field = JsonRead.Str( error, \u0022field\u0022 );\n\t\tvar hint = JsonRead.Str( error, \u0022hint\u0022 );\n\t\tLastError = $\u0022{r.Route}: HTTP {r.Status} {code} {message}{(field is null ? \u0022\u0022 : $\u0022 (field {field})\u0022)}{(hint is null ? \u0022\u0022 : $\u0022 ({hint})\u0022)}\u0022.Trim();\n\n\t\tswitch ( r.Status )\n\t\t{\n\t\t\tcase 0:\n\t\t\tcase \u003E= 500:\n\t\t\t\tfailures\u002B\u002B;\n\t\t\t\tvar wait = Backoff( failures );\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: {LastError}; trying again in {wait:0} s\u0022 );\n\t\t\t\treturn wait;\n\n\t\t\tcase 429:\n\t\t\t\t// Protocol v0.2 sends retryAfterSeconds in the body; sboxlist.com (v1) sends only the Retry-After header (PROTOCOL.md 8, 14).\n\t\t\t\tvar retry = JsonRead.Long( error, \u0022retryAfterSeconds\u0022 ) ?? r.RetryAfterSeconds ?? 5;\n\t\t\t\treturn Math.Clamp( retry, 1, 300 );\n\n\t\t\tcase 401:\n\t\t\t\tvar tip = Config.Auth == \u0022bearer\u0022 ? \u0022 sboxlist.com accepts hmac only: set auth to hmac.\u0022 : \u0022\u0022;\n\t\t\t\tif ( Now \u003E= pausedUntil )\n\t\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: refused (401). Check the token, the auth setting and the server clock.{tip}\u0022 );\n\t\t\t\tpausedUntil = Now \u002B 60;\n\t\t\t\treturn 60;\n\n\t\t\tcase 404:\n\t\t\tcase 410:\n\t\t\t\tStop( LastError );\n\t\t\t\treturn 300;\n\n\t\t\tcase 400 when code == \u0022unsupported_version\u0022:\n\t\t\t\tStop( \u0022the site does not speak protocol 1; update the plugin\u0022 );\n\t\t\t\treturn 300;\n\n\t\t\tcase 400 when field == \u0022serverId\u0022:\n\t\t\t\tStop( \u0022the site refuses this serverId; use the id the site shows (sboxlist.com needs a UUID)\u0022 );\n\t\t\t\treturn 300;\n\n\t\t\tdefault:\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: {LastError}\u0022 );\n\t\t\t\treturn 60;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003ETrouble that may pass: no answer, a rate limit, refused for now (401), a server error.\u003C/summary\u003E\n\tstatic bool Retryable( int status ) =\u003E status == 0 || status == 401 || status == 429 || status \u003E= 500;\n\n\t/// \u003Csummary\u003E15, 30, 60, 120, then 300 s, with up to 20 % jitter (PROTOCOL.md section 8).\u003C/summary\u003E\n\tstatic double Backoff( int failures )\n\t{\n\t\tdouble[] steps = { 15, 30, 60, 120, 300 };\n\t\tvar step = steps[Math.Min( Math.Max( failures, 1 ) - 1, steps.Length - 1 )];\n\t\tvar jitter = Guid.NewGuid().ToByteArray()[0] / 255.0 * 0.2;\n\t\treturn Math.Min( 300, step * (1 \u002B jitter) );\n\t}\n\n\tvoid Stop( string reason )\n\t{\n\t\tDisabled = true;\n\t\tDisabledReason = reason;\n\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: stopped until sbl_reload or a restart: {reason}\u0022 );\n\t}\n\n\tvoid ClearErrorFrom( string route )\n\t{\n\t\tif ( LastError.StartsWith( route \u002B \u0022:\u0022 ) ) LastError = \u0022\u0022;\n\t}\n\n\t// ---------------------------------------------------------------- heartbeat\n\n\tasync Task HeartbeatAsync()\n\t{\n\t\theartbeatBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar now = DateTimeOffset.UtcNow;\n\t\t\tlastSequence = Math.Max( lastSequence \u002B 1, now.ToUnixTimeMilliseconds() );\n\t\t\tvar players = service.PlayerCount();\n\t\t\tvar maxPlayers = Math.Clamp( Math.Max( Networking.MaxPlayers, players ), 1, 1024 );\n\t\t\tvar stamp = now.UtcDateTime.ToString( \u0022yyyy-MM-dd\u0027T\u0027HH:mm:ss.fff\u0027Z\u0027\u0022, CultureInfo.InvariantCulture );\n\n\t\t\tvar body = new JsonObject\n\t\t\t{\n\t\t\t\t[\u0022type\u0022] = \u0022heartbeat\u0022,\n\t\t\t\t[\u0022sequence\u0022] = lastSequence,\n\t\t\t\t[\u0022players\u0022] = Math.Min( players, maxPlayers ),\n\t\t\t\t[\u0022maxPlayers\u0022] = maxPlayers,\n\t\t\t\t[\u0022bots\u0022] = 0,\n\t\t\t\t[\u0022map\u0022] = Clip( service.MapName, 128 ),\n\t\t\t\t[\u0022package\u0022] = Clip( Game.Ident ?? \u0022\u0022, 128 ),\n\t\t\t\t[\u0022build\u0022] = \u0022\u0022,\n\t\t\t\t[\u0022uptimeSeconds\u0022] = service.UptimeSeconds,\n\t\t\t\t// Protocol v1 (sboxlist.com) reads serverTimestamp; the v0.2 spec and the test backend read serverTime.\n\t\t\t\t// Both are sent, because each side ignores the fields it does not know (PROTOCOL.md section 3).\n\t\t\t\t[\u0022serverTime\u0022] = stamp,\n\t\t\t\t[\u0022serverTimestamp\u0022] = stamp,\n\t\t\t\t[\u0022plugin\u0022] = \u0022sboxlist/\u0022 \u002B SboxlistService.Version,\n\t\t\t};\n\n\t\t\tvar r = await SendAsync( \u0022heartbeat\u0022, body );\n\t\t\tif ( r.Ok )\n\t\t\t{\n\t\t\t\tfailures = 0;\n\t\t\t\tif ( !HeartbeatAccepted ) Log.Info( $\u0022[sboxlist] {Config.SiteId}: heartbeat accepted\u0022 );\n\t\t\t\tHeartbeatAccepted = true;\n\t\t\t\tLastError = \u0022\u0022;\n\t\t\t\tvar next = JsonRead.Long( r.Json, \u0022nextHeartbeatSeconds\u0022 ) ?? 60;\n\t\t\t\tnextHeartbeatAt = Now \u002B Math.Clamp( next, 20, 3600 );\n\t\t\t}\n\t\t\telse if ( r.Status == 409 )\n\t\t\t{\n\t\t\t\tnextHeartbeatAt = Now \u002B 60;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tHeartbeatAccepted = false;\n\t\t\t\tnextHeartbeatAt = Now \u002B Failed( r );\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\theartbeatBusy = false;\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- poll and ack\n\n\tasync Task PollAsync()\n\t{\n\t\tpollBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar r = await SendAsync( \u0022votes/poll\u0022, new JsonObject { [\u0022type\u0022] = \u0022poll\u0022 } );\n\t\t\tif ( !r.Ok )\n\t\t\t{\n\t\t\t\tnextPollAt = Now \u002B Failed( r );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfailures = 0;\n\t\t\tClearErrorFrom( r.Route );\n\t\t\tif ( JsonRead.Get( r.Json, \u0022messages\u0022 ) is JsonArray messages )\n\t\t\t{\n\t\t\t\tforeach ( var element in messages )\n\t\t\t\t{\n\t\t\t\t\tvar message = JsonRead.Message( element, out var rawChars );\n\t\t\t\t\tif ( message is null ) continue;\n\t\t\t\t\ttry { HandleMessage( message, rawChars ); }\n\t\t\t\t\tcatch ( Exception e ) { Log.Warning( $\u0022[sboxlist] {Config.SiteId}: a message could not be handled: {e.Message}\u0022 ); }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar after = JsonRead.Long( r.Json, \u0022pollAfterSeconds\u0022 ) ?? 15;\n\t\t\tnextPollAt = Now \u002B Math.Clamp( after, 5, 300 );\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tpollBusy = false;\n\t\t}\n\t}\n\n\tvoid HandleMessage( JsonNode message, int rawChars )\n\t{\n\t\tvar id = JsonRead.Str( message, \u0022id\u0022 );\n\t\tif ( !SboxlistConfig.IsIdent( id, 1, 64 ) ) return;\n\n\t\tvar type = JsonRead.Str( message, \u0022type\u0022 );\n\t\tif ( rawChars \u003E 4096 || (message?.ToJsonString().Length ?? 0) \u003E 4096 ) { Ack( id, false, \u0022vote\u0022, \u0022message too long\u0022 ); return; }\n\t\tif ( type != \u0022vote\u0022 ) { Ack( id, false, \u0022vote\u0022, \u0022unsupported\u0022 ); return; }\n\n\t\t// Seen before (our ack was lost): ack again, do nothing else.\n\t\tif ( !Remember( dedupe.Votes, dedupe.VoteOrder, id ) ) { Ack( id, true, \u0022vote\u0022 ); return; }\n\n\t\tvar identity = JsonRead.Get( message, \u0022identity\u0022 );\n\t\tvar idKind = JsonRead.Str( identity, \u0022kind\u0022 ) ?? \u0022\u0022;\n\t\tvar idKey = JsonRead.Str( identity, \u0022key\u0022 ) ?? \u0022\u0022;\n\t\tvar isTest = JsonRead.Bool( message, \u0022test\u0022 ) ?? id.StartsWith( \u0022test-\u0022 );\n\t\tvar online = isTest ? null : service.FindPlayer( idKind, idKey );\n\n\t\tvar vote = new VoteInfo\n\t\t{\n\t\t\tSiteId = Config.SiteId,\n\t\t\tId = id,\n\t\t\tIdentityKind = idKind,\n\t\t\tIdentityKey = idKey,\n\t\t\tAt = JsonRead.Str( message, \u0022at\u0022 ) ?? \u0022\u0022,\n\t\t\tIsTest = isTest,\n\t\t\tOnlinePlayer = online,\n\t\t};\n\n\t\tVotesReceived\u002B\u002B;\n\t\tLastVoteId = id;\n\t\tLog.Info( vote.IsTest\n\t\t\t? $\u0022[sboxlist] {Config.SiteId}: test vote arrived ({id}), identity {vote.IdentityKind} {vote.IdentityKey}\u0022\n\t\t\t: $\u0022[sboxlist] {Config.SiteId}: vote {id} from {vote.IdentityKind} {vote.IdentityKey}\u0022 );\n\n\t\tSboxlistEvents.RaiseVote( vote );\n\t\tAck( id, true, \u0022vote\u0022 );\n\n\t\t// The voter is online right now: ask for the reward at once.\n\t\tif ( !vote.IsTest \u0026\u0026 Config.Rewards \u0026\u0026 online is not null )\n\t\t\tQueueJoin( online, \u0022vote\u0022 );\n\t}\n\n\tinternal void Ack( string id, bool ok, string kind, string error = null )\n\t{\n\t\tvar item = new JsonObject { [\u0022id\u0022] = id, [\u0022ok\u0022] = ok, [\u0022kind\u0022] = kind };\n\t\tif ( error is not null ) item[\u0022error\u0022] = Clip( error, 200 );\n\t\tpendingAcks.Add( item );\n\t}\n\n\tasync Task FlushAcksAsync()\n\t{\n\t\tackBusy = true;\n\t\ttry\n\t\t{\n\t\t\t// One batch: up to ackLimit acks and about 12 KB, so the body stays under the site\u0027s limit.\n\t\t\tvar batch = new List\u003CJsonObject\u003E();\n\t\t\tvar size = 0;\n\t\t\tforeach ( var item in pendingAcks )\n\t\t\t{\n\t\t\t\tvar length = Encoding.UTF8.GetByteCount( item.ToJsonString() ) \u002B 1;\n\t\t\t\tif ( batch.Count == ackLimit || (batch.Count \u003E 0 \u0026\u0026 size \u002B length \u003E MaxAckBatchBytes) ) break;\n\t\t\t\tbatch.Add( item );\n\t\t\t\tsize \u002B= length;\n\t\t\t}\n\t\t\tpendingAcks.RemoveRange( 0, batch.Count );\n\n\t\t\t// The request gets copies: a JSON node can have one parent only, and the originals go back if the send fails.\n\t\t\tvar list = new JsonArray();\n\t\t\tforeach ( var item in batch ) list.Add( (JsonObject)JsonNode.Parse( item.ToJsonString() ) );\n\n\t\t\tvar r = await SendAsync( \u0022votes/ack\u0022, new JsonObject { [\u0022type\u0022] = \u0022ack\u0022, [\u0022acks\u0022] = list } );\n\t\t\tif ( r.Ok )\n\t\t\t{\n\t\t\t\tackLimit = 50;\n\t\t\t\tClearErrorFrom( r.Route );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The site refused several acks together: send them one at a time, so one bad item is dropped alone.\n\t\t\tif ( batch.Count \u003E 1 \u0026\u0026 (r.Status == 400 || r.Status == 413) )\n\t\t\t{\n\t\t\t\tackLimit = 1;\n\t\t\t\tpendingAcks.InsertRange( 0, batch );\n\t\t\t\tackRetryAt = Now;\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: the site refused {batch.Count} acks together (HTTP {r.Status}); sending them one by one\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The site refused this ack itself (a bug in what we sent, or an unknown field): sending it again changes nothing.\n\t\t\t// A vote whose ack never arrives is sent again by the site, and then it is acked again.\n\t\t\tif ( r.Status == 400 || r.Status == 405 || r.Status == 413 || r.Status == 415 )\n\t\t\t{\n\t\t\t\tFailed( r );\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: {batch.Count} ack(s) dropped\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Network trouble, 429, 5xx, 401, 404 or 410: keep the acks and try again later, on the ack route\u0027s own timer.\n\t\t\tpendingAcks.InsertRange( 0, batch );\n\t\t\tackRetryAt = Now \u002B Failed( r );\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tackBusy = false;\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- join and rewards\n\n\tasync Task JoinAsync( JoinRequest join )\n\t{\n\t\tjoinBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar player = join.Player;\n\t\t\tvar steam = player.SteamId.ValueUnsigned;\n\t\t\tvar steamText = steam == 0 ? null : steam.ToString( CultureInfo.InvariantCulture );\n\t\t\tif ( !IsIndividualSteamId( steamText ) ) steamText = null;\n\n\t\t\t// Protocol v1 name rule: 1 to 32 code points, no NUL, no unpaired surrogate. A name\n\t\t\t// outside it is not sent: the join carries the SteamID64 alone (the SteamID-only join), so a Steam vote is still paid,\n\t\t\t// and no name vote can match it. A player with neither a usable name nor a SteamID64 is not sent at all.\n\t\t\t// The name is sent exactly as the server reports it, with no trimming and no character removal.\n\t\t\tvar name = player.DisplayName ?? \u0022\u0022;\n\t\t\tvar nameFits = FitsJoinName( name );\n\t\t\tif ( !nameFits \u0026\u0026 steamText is null )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: a player with no usable name and no SteamID64 cannot be matched to a vote; no join sent\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar who = nameFits ? name : steamText;\n\n\t\t\tvar body = new JsonObject\n\t\t\t{\n\t\t\t\t[\u0022type\u0022] = \u0022join\u0022,\n\t\t\t\t[\u0022reason\u0022] = join.Reason,\n\t\t\t\t[\u0022playerName\u0022] = nameFits ? name : null,\n\t\t\t\t[\u0022steamId\u0022] = steamText,\n\t\t\t};\n\n\t\t\tvar r = await SendAsync( \u0022rewards/join\u0022, body );\n\t\t\tif ( !r.Ok )\n\t\t\t{\n\t\t\t\tvar wait = Failed( r );\n\t\t\t\tif ( Retryable( r.Status ) \u0026\u0026 join.Attempts \u002B 1 \u003C MaxJoinAttempts )\n\t\t\t\t{\n\t\t\t\t\t// A vote is acked before its reward is asked for, so the site will not send it again: the join is tried again.\n\t\t\t\t\tjoin.Attempts\u002B\u002B;\n\t\t\t\t\tjoinRetryAt = Now \u002B wait;\n\t\t\t\t\tjoins.Enqueue( join );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: the reward request for {who} was given up after {join.Attempts \u002B 1} attempt(s)\u0022 );\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tClearErrorFrom( r.Route );\n\t\t\tif ( JsonRead.Get( r.Json, \u0022messages\u0022 ) is JsonArray rewards )\n\t\t\t{\n\t\t\t\tforeach ( var element in rewards )\n\t\t\t\t{\n\t\t\t\t\tvar reward = JsonRead.Message( element, out var rawChars );\n\t\t\t\t\tif ( reward is null ) continue;\n\t\t\t\t\ttry { RunReward( reward, player, rawChars ); }\n\t\t\t\t\tcatch ( Exception e ) { Log.Warning( $\u0022[sboxlist] {Config.SiteId}: a reward could not be run: {e.Message}\u0022 ); }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tjoinBusy = false;\n\t\t}\n\t}\n\n\tvoid RunReward( JsonNode reward, Connection player, int rawChars )\n\t{\n\t\tvar id = JsonRead.Str( reward, \u0022id\u0022 );\n\t\tif ( !SboxlistConfig.IsIdent( id, 1, 64 ) )\n\t\t{\n\t\t\t// Without an id the library cannot ack the reward, so the site could never close it (PROTOCOL.md 6.6).\n\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: a reward without a valid id was dropped; the site must send one (PROTOCOL.md 6.6)\u0022 );\n\t\t\treturn;\n\t\t}\n\n\t\tif ( !Remember( dedupe.Rewards, dedupe.RewardOrder, id ) ) { Ack( id, true, \u0022reward\u0022 ); return; }\n\n\t\t// Remembered above, so a run that fails is never run again: it is acked with the reason instead.\n\t\tstring error;\n\t\tif ( rawChars \u003E 4096 || (reward?.ToJsonString().Length ?? 0) \u003E 4096 )\n\t\t\terror = \u0022message too long\u0022;\n\t\telse if ( JsonRead.Str( reward, \u0022type\u0022 ) is string rtype \u0026\u0026 rtype != \u0022reward\u0022 )\n\t\t\terror = \u0022unsupported\u0022;\n\t\telse\n\t\t{\n\t\t\ttry { error = SboxlistRewards.Run( this, reward, player ); }\n\t\t\tcatch ( Exception e ) { error = Clip( \u0022reward failed: \u0022 \u002B e.Message, 200 ); }\n\t\t}\n\n\t\tif ( error is null ) RewardsRun\u002B\u002B;\n\t\tAck( id, error is null, \u0022reward\u0022, error );\n\t}\n\n\t// ---------------------------------------------------------------- operator commands\n\n\tpublic async Task RequestTestvoteAsync()\n\t{\n\t\tif ( testvoteBusy ) return;\n\t\ttestvoteBusy = true;\n\t\ttry\n\t\t{\n\t\t\tvar r = await SendAsync( \u0022votes/testvote\u0022, new JsonObject { [\u0022type\u0022] = \u0022testvote\u0022 } );\n\t\t\tif ( r.Ok )\n\t\t\t{\n\t\t\t\tClearErrorFrom( r.Route );\n\t\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: test vote {JsonRead.Str( r.Json, \u0022id\u0022 )} queued; it arrives with the next poll\u0022 );\n\t\t\t\tnextPollAt = Math.Min( nextPollAt, Now \u002B 1 );\n\t\t\t}\n\t\t\telse if ( r.Status == 404 )\n\t\t\t{\n\t\t\t\t// Not a stop: a site without a server-side test vote (sboxlist.com has none) just says so.\n\t\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: this site has no server-side test vote; use the site\u0027s own test vote\u0022 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFailed( r );\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: test vote refused: {LastError}\u0022 );\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\ttestvoteBusy = false;\n\t\t}\n\t}\n\n\tpublic async Task InfoAsync()\n\t{\n\t\tif ( infoBusy ) return;\n\t\tinfoBusy = true;\n\t\ttry\n\t\t{\n\t\t\tusing var cts = new CancellationTokenSource( TimeSpan.FromSeconds( 10 ) );\n\t\t\tusing var response = await Http.RequestAsync( Url( \u0022info\u0022 ), \u0022GET\u0022, null, null, cts.Token );\n\t\t\tif ( (int)response.StatusCode == 404 )\n\t\t\t{\n\t\t\t\t// Not a stop: a site without /v1/info (sboxlist.com has none) just is not clock-checked.\n\t\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: this site has no /v1/info; the clock is not checked\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar text = await response.Content.ReadAsStringAsync();\n\t\t\tvar json = JsonRead.Parse( text );\n\t\t\tvar serverTime = JsonRead.Long( json, \u0022serverTime\u0022 );\n\t\t\tif ( serverTime is long t ) ClockOffsetSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - t;\n\t\t\tLog.Info( $\u0022[sboxlist] {Config.SiteId}: info HTTP {(int)response.StatusCode}, site \u0027{JsonRead.Str( json, \u0022siteId\u0022 )}\u0027, clock difference {ClockOffsetSeconds?.ToString( \u00220\u0022 ) ?? \u0022?\u0022} s\u0022 );\n\t\t\tif ( ClockOffsetSeconds is double d \u0026\u0026 Math.Abs( d ) \u003E 60 )\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: this clock is {d:0} s off the site\u0027s; over 300 s every request is refused\u0022 );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Warning( $\u0022[sboxlist] {Config.SiteId}: info failed: {e.Message}\u0022 );\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tinfoBusy = false;\n\t\t}\n\t}\n\n\tpublic string Describe()\n\t{\n\t\tvar state = Disabled ? $\u0022STOPPED ({DisabledReason})\u0022 : HeartbeatAccepted ? \u0022online\u0022 : \u0022not accepted yet\u0022;\n\t\treturn $\u0022{Config.SiteId} [{Config.Auth}] {state}; last {LastRoute} HTTP {LastStatus}; votes {VotesReceived}, rewards {RewardsRun}; acks waiting {pendingAcks.Count}, joins waiting {joins.Count}\u0022\n\t\t\t\u002B (LastError.Length \u003E 0 ? $\u0022; last error: {LastError}\u0022 : \u0022\u0022);\n\t}\n\n\t// ---------------------------------------------------------------- helpers\n\n\tstatic bool Remember( HashSet\u003Cstring\u003E set, Queue\u003Cstring\u003E order, string id )\n\t{\n\t\tif ( !set.Add( id ) ) return false;\n\t\torder.Enqueue( id );\n\t\twhile ( order.Count \u003E 1000 ) set.Remove( order.Dequeue() );\n\t\treturn true;\n\t}\n\n\t/// \u003Csummary\u003EClips text to max characters without splitting surrogate pairs or keeping control/lone-surrogate characters.\u003C/summary\u003E\n\tinternal static string Clip( string value, int max )\n\t{\n\t\tif ( string.IsNullOrEmpty( value ) || max \u003C= 0 ) return \u0022\u0022;\n\t\tvar sb = new StringBuilder( Math.Min( value.Length, max ) );\n\t\tfor ( var i = 0; i \u003C value.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = value[i];\n\t\t\tif ( char.IsControl( c ) )\n\t\t\t{\n\t\t\t\tif ( sb.Length \u002B 1 \u003E max ) break;\n\t\t\t\tsb.Append( \u0027 \u0027 );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C value.Length \u0026\u0026 char.IsLowSurrogate( value[i \u002B 1] ) )\n\t\t\t{\n\t\t\t\tif ( sb.Length \u002B 2 \u003E max ) break;\n\t\t\t\tsb.Append( c ).Append( value[\u002B\u002Bi] );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( char.IsSurrogate( c ) )\n\t\t\t{\n\t\t\t\tif ( sb.Length \u002B 1 \u003E max ) break;\n\t\t\t\tsb.Append( \u0027 \u0027 );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( sb.Length \u002B 1 \u003E max ) break;\n\t\t\tsb.Append( c );\n\t\t}\n\t\treturn sb.ToString();\n\t}\n\n\t/// \u003Csummary\u003EValve Universe 1 AccountType 1 Individual SteamID64 (sboxlist.com protocol v1 STEAM_ID: 7656119 \u002B 10 digits).\u003C/summary\u003E\n\tinternal static bool IsIndividualSteamId( string value )\n\t{\n\t\tif ( value is null || value.Length != 17 || !value.StartsWith( \u00227656119\u0022 ) ) return false;\n\t\tforeach ( var c in value ) if ( c \u003C \u00270\u0027 || c \u003E \u00279\u0027 ) return false;\n\t\treturn true;\n\t}\n\n\t/// Protocol v1 join name rule: 1 to 32 code points, no NUL and no unpaired surrogate.\n\tinternal static bool FitsJoinName( string name )\n\t{\n\t\tif ( string.IsNullOrEmpty( name ) ) return false;\n\t\tvar codePoints = 0;\n\t\tfor ( var i = 0; i \u003C name.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = name[i];\n\t\t\tif ( c == \u0027\\0\u0027 ) return false;\n\t\t\tif ( char.IsHighSurrogate( c ) \u0026\u0026 i \u002B 1 \u003C name.Length \u0026\u0026 char.IsLowSurrogate( name[i \u002B 1] ) ) i\u002B\u002B;\n\t\t\telse if ( char.IsSurrogate( c ) ) return false;\n\t\t\tif ( \u002B\u002BcodePoints \u003E 32 ) return false;\n\t\t}\n\t\treturn true;\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistService.cs","FileName":"SboxlistService.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Put one of these in the scene the server loads (next to the NetworkHelper). It runs only on\n/// the host: it reads the config, sends heartbeats, polls for votes and asks for rewards when a\n/// player joins. Clients do nothing.\n/// \u003C/summary\u003E\npublic sealed class SboxlistService : Component, Component.INetworkListener\n{\n\tpublic const string Version = \u00221.0.0\u0022;\n\n\tpublic static SboxlistService Instance { get; private set; }\n\n\tpublic IReadOnlyList\u003CSiteClient\u003E Sites =\u003E sites;\n\n\treadonly List\u003CSiteClient\u003E sites = new();\n\tdouble startedAt;\n\tbool loaded;\n\n\tprotected override void OnStart()\n\t{\n\t\tInstance = this;\n\t\tstartedAt = RealTime.NowDouble;\n\t}\n\n\tprotected override void OnUpdate()\n\t{\n\t\tif ( !Networking.IsHost ) return;\n\n\t\tif ( !loaded )\n\t\t{\n\t\t\tloaded = true;\n\t\t\tReload();\n\t\t}\n\n\t\tforeach ( var site in sites )\n\t\t\tsite.Tick();\n\t}\n\n\tprotected override void OnDestroy()\n\t{\n\t\tif ( Instance == this ) Instance = null;\n\t}\n\n\tpublic void Reload()\n\t{\n\t\tvar previous = new List\u003CSiteClient\u003E( sites );\n\t\tsites.Clear();\n\t\tvar configs = SboxlistConfig.Load( out var source );\n\t\tLog.Info( $\u0022[sboxlist] {Version} config: {source}\u0022 );\n\t\tLog.Info( $\u0022[sboxlist] config file path: {SboxlistConfig.FullPath()}\u0022 );\n\n\t\tforeach ( var config in configs )\n\t\t{\n\t\t\t// A running site with the same identity keeps its state (pending acks and, through its server id, what it\n\t\t\t// has seen). Only the rewards setting can change in place. A stopped site starts again.\n\t\t\tvar kept = previous.FirstOrDefault( s =\u003E !s.Disabled \u0026\u0026 SameSite( s.Config, config ) );\n\t\t\tif ( kept is not null )\n\t\t\t{\n\t\t\t\tkept.Config.Rewards = config.Rewards;\n\t\t\t\tsites.Add( kept );\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvar site = new SiteClient( config, this );\n\t\t\tsites.Add( site );\n\t\t\tLog.Info( $\u0022[sboxlist] site {config.SiteId}: {config.BaseUrl} as {config.ServerId}, auth {config.Auth}, rewards {(config.Rewards ? \u0022on\u0022 : \u0022off\u0022)}\u0022 );\n\t\t\t_ = site.InfoAsync();\n\t\t}\n\n\t\tif ( sites.Count == 0 )\n\t\t\tLog.Warning( \u0022[sboxlist] no site configured; nothing will be sent\u0022 );\n\t}\n\n\tstatic bool SameSite( SiteConfig a, SiteConfig b ) =\u003E\n\t\ta.SiteId == b.SiteId \u0026\u0026 a.BaseUrl == b.BaseUrl \u0026\u0026 a.ServerId == b.ServerId \u0026\u0026 a.Token == b.Token \u0026\u0026 a.Auth == b.Auth;\n\n\t/// \u003Csummary\u003ECalled on the host when a player is fully in the game.\u003C/summary\u003E\n\tpublic void OnActive( Connection channel )\n\t{\n\t\tif ( !Networking.IsHost || channel is null ) return;\n\t\tif ( Application.IsDedicatedServer \u0026\u0026 channel.IsHost ) return;\n\t\tforeach ( var site in sites )\n\t\t\tsite.QueueJoin( channel, \u0022join\u0022 );\n\t}\n\n\tinternal int PlayerCount()\n\t{\n\t\tvar all = Connection.All;\n\t\tif ( all is null ) return 0;\n\t\treturn Application.IsDedicatedServer ? all.Count( c =\u003E !c.IsHost ) : all.Count;\n\t}\n\n\tinternal string MapName =\u003E Scene?.Name ?? \u0022\u0022;\n\n\tinternal long UptimeSeconds =\u003E (long)Math.Max( 0, RealTime.NowDouble - startedAt );\n\n\t/// \u003Csummary\u003EThe connected player a vote belongs to, by SteamID64 or by exact name.\u003C/summary\u003E\n\tinternal Connection FindPlayer( string identityKind, string identityKey )\n\t{\n\t\tvar all = Connection.All;\n\t\tif ( all is null || string.IsNullOrEmpty( identityKey ) ) return null;\n\n\t\tforeach ( var c in all )\n\t\t{\n\t\t\tif ( Application.IsDedicatedServer \u0026\u0026 c.IsHost ) continue;\n\t\t\tif ( identityKind == \u0022steam\u0022 \u0026\u0026 c.SteamId.ValueUnsigned.ToString( System.Globalization.CultureInfo.InvariantCulture ) == identityKey ) return c;\n\t\t\tif ( identityKind == \u0022name\u0022 \u0026\u0026 c.DisplayName == identityKey ) return c;\n\t\t}\n\n\t\treturn null;\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistCrypto.cs","FileName":"SboxlistCrypto.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Hashing for the protocol. Only SHA256 is on the s\u0026amp;box whitelist (HMACSHA256 and\n/// RandomNumberGenerator are not), so HMAC is built by hand (RFC 2104) and nonces come from Guid.\n/// \u003C/summary\u003E\npublic static class SboxlistCrypto\n{\n\tpublic static string Hex( byte[] bytes ) =\u003E Convert.ToHexString( bytes ).ToLowerInvariant();\n\n\tpublic static byte[] Sha256( byte[] data ) =\u003E SHA256.HashData( data );\n\n\tpublic static string Sha256Hex( byte[] data ) =\u003E Hex( Sha256( data ) );\n\n\t/// \u003Csummary\u003EHMAC-SHA256 from SHA256 alone: H((K0 ^ opad) || H((K0 ^ ipad) || message)).\u003C/summary\u003E\n\tpublic static byte[] HmacSha256( byte[] key, byte[] message )\n\t{\n\t\tconst int block = 64;\n\t\tvar k = key.Length \u003E block ? Sha256( key ) : key;\n\n\t\tvar inner = new byte[block \u002B message.Length];\n\t\tvar outer = new byte[block \u002B 32];\n\n\t\tfor ( var i = 0; i \u003C block; i\u002B\u002B )\n\t\t{\n\t\t\tvar b = i \u003C k.Length ? k[i] : (byte)0;\n\t\t\tinner[i] = (byte)(b ^ 0x36);\n\t\t\touter[i] = (byte)(b ^ 0x5c);\n\t\t}\n\n\t\tfor ( var i = 0; i \u003C message.Length; i\u002B\u002B )\n\t\t\tinner[block \u002B i] = message[i];\n\n\t\tvar innerHash = Sha256( inner );\n\t\tfor ( var i = 0; i \u003C 32; i\u002B\u002B )\n\t\t\touter[block \u002B i] = innerHash[i];\n\n\t\treturn Sha256( outer );\n\t}\n\n\t/// \u003Csummary\u003EA nonce only has to be unique: 32 hex characters from a new Guid.\u003C/summary\u003E\n\tpublic static string NewNonce() =\u003E Guid.NewGuid().ToString( \u0022N\u0022 );\n\n\t/// \u003Csummary\u003EThe HMAC key of variant B: the 32 bytes of sha256(token). The site stores the same.\u003C/summary\u003E\n\tpublic static byte[] KeyFromToken( string token ) =\u003E Sha256( Encoding.UTF8.GetBytes( token ) );\n\n\t/// \u003Csummary\u003EVariant B signature over \u0022sbl1\\n serverId \\n timestamp \\n nonce \\n hex(sha256(body))\u0022.\u003C/summary\u003E\n\tpublic static string Signature( byte[] key, string serverId, string timestamp, string nonce, byte[] body )\n\t{\n\t\tvar canonical = \u0022sbl1\\n\u0022 \u002B serverId \u002B \u0022\\n\u0022 \u002B timestamp \u002B \u0022\\n\u0022 \u002B nonce \u002B \u0022\\n\u0022 \u002B Sha256Hex( body );\n\t\treturn Hex( HmacSha256( key, Encoding.UTF8.GetBytes( canonical ) ) );\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistToastHud.cs","FileName":"SboxlistToastHud.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System.Collections.Generic;\nusing Sandbox;\nusing Sandbox.UI;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003E\n/// Optional ready-made on-screen toast HUD component. Add this component alongside SboxlistService\n/// (it automatically creates a ScreenPanel if none is on the GameObject) to show dark vote-reward\n/// toast banners in the top-right corner without writing custom UI code. Games with their own\n/// Razor HUD can omit this component and implement ISboxlistNotificationListener instead.\n/// \u003C/summary\u003E\npublic sealed class SboxlistToastHud : PanelComponent, ISboxlistNotificationListener\n{\n\tsealed class Entry\n\t{\n\t\tpublic string Text;\n\t\tpublic double ExpiresAt;\n\t}\n\n\t/// \u003Csummary\u003EHow many seconds each toast card stays on screen.\u003C/summary\u003E\n\t[Property] public float DisplaySeconds { get; set; } = 6.0f;\n\n\t/// \u003Csummary\u003EWhen true, suppresses the duplicate \u0022\u2605 ...\u0022 line in Sandbox.Platform.Chat for toasts.\u003C/summary\u003E\n\t[Property] public bool SuppressDefaultChat { get; set; } = false;\n\n\treadonly List\u003CEntry\u003E entries = new();\n\n\tprotected override void OnStart()\n\t{\n\t\tbase.OnStart();\n\t\tif ( !Application.IsDedicatedServer )\n\t\t\tComponents.GetOrCreate\u003CScreenPanel\u003E();\n\t}\n\n\tpublic void OnVoteNotification( VoteNotification notification )\n\t{\n\t\tif ( notification is null || notification.Kind != \u0022toast\u0022 ) return;\n\t\tif ( SuppressDefaultChat ) notification.Handled = true;\n\t\tif ( Application.IsDedicatedServer ) return;\n\n\t\tvar duration = DisplaySeconds \u003C 1f ? 1f : DisplaySeconds;\n\t\tentries.Add( new Entry { Text = \u0022\u2605 \u0022 \u002B notification.Text, ExpiresAt = RealTime.NowDouble \u002B duration } );\n\t\twhile ( entries.Count \u003E 5 ) entries.RemoveAt( 0 );\n\t\tRebuild();\n\t}\n\n\tprotected override void OnTreeFirstBuilt()\n\t{\n\t\tbase.OnTreeFirstBuilt();\n\t\tif ( Panel is null ) return;\n\t\tPanel.Style.Position = PositionMode.Absolute;\n\t\tPanel.Style.Top = 24;\n\t\tPanel.Style.Right = 24;\n\t\tPanel.Style.FlexDirection = FlexDirection.Column;\n\t\tPanel.Style.ZIndex = 1000;\n\t\tRebuild();\n\t}\n\n\tprotected override void OnUpdate()\n\t{\n\t\tbase.OnUpdate();\n\t\tif ( entries.Count == 0 ) return;\n\t\tvar now = RealTime.NowDouble;\n\t\tvar removed = false;\n\t\tfor ( var i = entries.Count - 1; i \u003E= 0; i-- )\n\t\t{\n\t\t\tif ( entries[i].ExpiresAt \u003C= now )\n\t\t\t{\n\t\t\t\tentries.RemoveAt( i );\n\t\t\t\tremoved = true;\n\t\t\t}\n\t\t}\n\t\tif ( removed ) Rebuild();\n\t}\n\n\tvoid Rebuild()\n\t{\n\t\tif ( Panel is null ) return;\n\t\tPanel.DeleteChildren( true );\n\t\tforeach ( var entry in entries )\n\t\t{\n\t\t\tvar card = Panel.AddChild\u003CLabel\u003E();\n\t\t\tcard.Text = entry.Text;\n\t\t\tcard.Style.BackgroundColor = new Color( 0.09f, 0.11f, 0.13f, 0.95f );\n\t\t\tcard.Style.FontColor = Color.White;\n\t\t\tcard.Style.FontSize = 16;\n\t\t\tcard.Style.FontWeight = 600;\n\t\t\tcard.Style.PaddingLeft = 14;\n\t\t\tcard.Style.PaddingRight = 14;\n\t\t\tcard.Style.PaddingTop = 10;\n\t\t\tcard.Style.PaddingBottom = 10;\n\t\t\tcard.Style.MarginBottom = 8;\n\t\t\tcard.Style.BorderLeftWidth = 4;\n\t\t\tcard.Style.BorderLeftColor = new Color( 0.31f, 0.27f, 0.90f );\n\t\t}\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"global using static Sandbox.Internal.GlobalGameNamespace;\r\nglobal using Microsoft.AspNetCore.Components;\r\nglobal using Microsoft.AspNetCore.Components.Rendering;\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonTitle\u0022, \u0022sboxlist\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022sboxlist\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022prioxystudios\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022prioxystudios.sboxlist\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002233\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineMinorVersion\u0022, \u00221\u0022 )]\r\n\r\n[assembly: System.Runtime.Versioning.TargetFramework( \u0022.NETCoreApp,Version=v9.0\u0022, FrameworkDisplayName = \u0022.NET 9.0\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022CompileTime\u0022, \u00222026-11-18T12:19:19.4208089Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.115.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.115.0\u0022)]"},{"Ident":"prioxystudios.sboxlist","Path":"Code/JsonRead.cs","FileName":"JsonRead.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System.Text.Json.Nodes;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003EReads fields from untrusted JSON without throwing. A wrong type reads as null.\u003C/summary\u003E\ninternal static class JsonRead\n{\n\tpublic static string Str( JsonNode node, string key )\n\t{\n\t\ttry { return node?[key]?.GetValue\u003Cstring\u003E(); }\n\t\tcatch { return null; }\n\t}\n\n\tpublic static long? Long( JsonNode node, string key )\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar value = node?[key];\n\t\t\tif ( value is null ) return null;\n\t\t\treturn value.GetValue\u003Clong\u003E();\n\t\t}\n\t\tcatch { return null; }\n\t}\n\n\tpublic static bool? Bool( JsonNode node, string key )\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar value = node?[key];\n\t\t\tif ( value is null ) return null;\n\t\t\treturn value.GetValue\u003Cbool\u003E();\n\t\t}\n\t\tcatch { return null; }\n\t}\n\n\tpublic static JsonNode Get( JsonNode node, string key )\n\t{\n\t\ttry { return node?[key]; }\n\t\tcatch { return null; }\n\t}\n\n\tpublic static JsonNode Parse( string text )\n\t{\n\t\ttry { return string.IsNullOrEmpty( text ) ? null : JsonNode.Parse( text ); }\n\t\tcatch { return null; }\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// One message of a poll or join answer. Protocol v1 (sboxlist.com) sends each message as JSON\n\t/// text, the v0.2 spec sends an object. Returns the object, or null for anything else.\n\t/// \u003C/summary\u003E\n\tpublic static JsonNode Message( JsonNode element ) =\u003E Message( element, out _ );\n\n\tpublic static JsonNode Message( JsonNode element, out int rawChars )\n\t{\n\t\trawChars = 0;\n\t\tif ( element is null ) return null;\n\t\tif ( element is JsonObject )\n\t\t{\n\t\t\trawChars = element.ToJsonString().Length;\n\t\t\treturn element;\n\t\t}\n\t\ttry\n\t\t{\n\t\t\tvar text = element.GetValue\u003Cstring\u003E();\n\t\t\tif ( text is null ) return null;\n\t\t\trawChars = text.Length;\n\t\t\treturn JsonNode.Parse( text ) as JsonObject;\n\t\t}\n\t\tcatch { return null; }\n\t}\n}\n"},{"Ident":"prioxystudios.sboxlist","Path":"Code/SboxlistConfig.cs","FileName":"SboxlistConfig.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":447884,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Text.Json.Nodes;\nusing Sandbox;\nusing static Sandbox.Internal.GlobalGameNamespace;\n\nnamespace Sboxlist;\n\n/// \u003Csummary\u003EOne server list this server is listed on (PROTOCOL.md section 7).\u003C/summary\u003E\npublic sealed class SiteConfig\n{\n\tpublic string SiteId { get; set; } = \u0022\u0022;\n\tpublic string BaseUrl { get; set; } = \u0022\u0022;\n\tpublic string ServerId { get; set; } = \u0022\u0022;\n\tpublic string Token { get; set; } = \u0022\u0022;\n\t/// \u003Csummary\u003Ehmac for sboxlist.com (protocol v1 accepts hmac only); bearer only for a site that accepts it.\u003C/summary\u003E\n\tpublic string Auth { get; set; } = \u0022hmac\u0022;\n\tpublic bool Rewards { get; set; } = true;\n}\n\n/// \u003Csummary\u003E\n/// Reads the site list. First choice: data/\u0026lt;org\u0026gt;/\u0026lt;package\u0026gt;/sboxlist.json on the server\u0027s own\n/// disk (FileSystem.Data). Fallback for one site: the hidden ConVars below, set from the start\n/// script (\u002Bsbl_base_url ... \u002Bsbl_server_id ... \u002Bsbl_token ...). The token is never put in a\n/// prefab, a scene or a published package.\n/// \u003C/summary\u003E\npublic static class SboxlistConfig\n{\n\tpublic const string FileName = \u0022sboxlist.json\u0022;\n\n\t[ConVar( \u0022sbl_base_url\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarBaseUrl { get; set; } = \u0022\u0022;\n\n\t[ConVar( \u0022sbl_server_id\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarServerId { get; set; } = \u0022\u0022;\n\n\t[ConVar( \u0022sbl_token\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarToken { get; set; } = \u0022\u0022;\n\n\t[ConVar( \u0022sbl_auth\u0022, ConVarFlags.Hidden )]\n\tpublic static string ConVarAuth { get; set; } = \u0022hmac\u0022;\n\n\t/// \u003Csummary\u003ELogs every request and answer (never the token).\u003C/summary\u003E\n\t[ConVar( \u0022sbl_debug\u0022 )]\n\tpublic static bool Debug { get; set; } = false;\n\n\tpublic static string FullPath()\n\t{\n\t\ttry { return FileSystem.Data.GetFullPath( FileName ); }\n\t\tcatch ( Exception e ) { return $\u0022(unknown: {e.Message})\u0022; }\n\t}\n\n\tpublic static List\u003CSiteConfig\u003E Load( out string source )\n\t{\n\t\tvar sites = new List\u003CSiteConfig\u003E();\n\n\t\tif ( FileSystem.Data.FileExists( FileName ) )\n\t\t{\n\t\t\tsource = FullPath();\n\t\t\tJsonNode root;\n\t\t\ttry\n\t\t\t{\n\t\t\t\troot = JsonNode.Parse( FileSystem.Data.ReadAllText( FileName ) );\n\t\t\t}\n\t\t\tcatch ( Exception e )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {source} is not valid JSON: {e.Message}\u0022 );\n\t\t\t\treturn sites;\n\t\t\t}\n\n\t\t\tif ( root?[\u0022sites\u0022] is JsonArray list )\n\t\t\t{\n\t\t\t\tforeach ( var item in list )\n\t\t\t\t{\n\t\t\t\t\tvar site = new SiteConfig\n\t\t\t\t\t{\n\t\t\t\t\t\tSiteId = JsonRead.Str( item, \u0022siteId\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tBaseUrl = JsonRead.Str( item, \u0022baseUrl\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tServerId = JsonRead.Str( item, \u0022serverId\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tToken = JsonRead.Str( item, \u0022token\u0022 ) ?? \u0022\u0022,\n\t\t\t\t\t\tAuth = JsonRead.Str( item, \u0022auth\u0022 ) ?? \u0022hmac\u0022,\n\t\t\t\t\t\tRewards = JsonRead.Bool( item, \u0022rewards\u0022 ) ?? true,\n\t\t\t\t\t};\n\t\t\t\t\tAddIfValid( sites, site );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] {source} has no \\\u0022sites\\\u0022 list\u0022 );\n\t\t\t}\n\n\t\t\tif ( JsonRead.Bool( root, \u0022debug\u0022 ) == true ) Debug = true;\n\t\t\treturn sites;\n\t\t}\n\n\t\tif ( !string.IsNullOrWhiteSpace( ConVarBaseUrl ) )\n\t\t{\n\t\t\tsource = \u0022ConVars sbl_base_url / sbl_server_id / sbl_token\u0022;\n\t\t\tAddIfValid( sites, new SiteConfig\n\t\t\t{\n\t\t\t\tSiteId = HostOf( ConVarBaseUrl ),\n\t\t\t\tBaseUrl = ConVarBaseUrl.Trim(),\n\t\t\t\tServerId = ConVarServerId.Trim(),\n\t\t\t\tToken = ConVarToken.Trim(),\n\t\t\t\tAuth = string.IsNullOrWhiteSpace( ConVarAuth ) ? \u0022hmac\u0022 : ConVarAuth.Trim(),\n\t\t\t\tRewards = true,\n\t\t\t} );\n\t\t\treturn sites;\n\t\t}\n\n\t\tsource = $\u0022nothing found (looked for {FullPath()} and the sbl_* ConVars)\u0022;\n\t\treturn sites;\n\t}\n\n\tstatic void AddIfValid( List\u003CSiteConfig\u003E sites, SiteConfig site )\n\t{\n\t\tsite.BaseUrl = site.BaseUrl.Trim().TrimEnd( \u0027/\u0027 );\n\t\tsite.Auth = site.Auth.Trim().ToLowerInvariant();\n\t\tif ( string.IsNullOrWhiteSpace( site.SiteId ) ) site.SiteId = HostOf( site.BaseUrl );\n\n\t\tvar problem = Problem( site );\n\t\tif ( problem is not null )\n\t\t{\n\t\t\tLog.Warning( $\u0022[sboxlist] site \u0027{site.SiteId}\u0027 skipped: {problem}\u0022 );\n\t\t\treturn;\n\t\t}\n\n\t\tvar warning = LocalhostWarning( site.BaseUrl );\n\t\tif ( warning is not null ) Log.Warning( $\u0022[sboxlist] site \u0027{site.SiteId}\u0027: {warning}\u0022 );\n\n\t\tforeach ( var existing in sites )\n\t\t{\n\t\t\tif ( existing.SiteId == site.SiteId )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022[sboxlist] site \u0027{site.SiteId}\u0027 is listed twice; the second one is skipped\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tsites.Add( site );\n\t}\n\n\t/// \u003Csummary\u003EThe reason a site is refused, or null. The site checks what it receives; this checks what the plugin is given.\u003C/summary\u003E\n\tstatic string Problem( SiteConfig s )\n\t{\n\t\tvar url = BaseUrlProblem( s.BaseUrl );\n\t\tif ( url is not null ) return url;\n\t\tif ( !IsSiteId( s.SiteId ) ) return \u0022siteId must be lowercase letters, digits, dots and dashes, starting with a letter or digit\u0022;\n\t\tif ( !IsIdent( s.ServerId, 1, 64 ) ) return \u0022serverId must be 1-64 of A-Z a-z 0-9 _ -\u0022;\n\t\tif ( !IsToken( s.Token ) ) return \u0022token must be sbs_ or sbt_ followed by 43 characters\u0022;\n\t\tif ( s.Auth != \u0022bearer\u0022 \u0026\u0026 s.Auth != \u0022hmac\u0022 ) return \u0022auth must be hmac or bearer\u0022;\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// https with a domain name (s\u0026amp;box refuses IP addresses), or http on localhost for tests.\n\t/// The port of a localhost address is only a warning, see LocalhostWarning.\n\t/// \u003C/summary\u003E\n\tinternal static string BaseUrlProblem( string url )\n\t{\n\t\tif ( string.IsNullOrEmpty( url ) ) return \u0022baseUrl must be a full URL\u0022;\n\t\tif ( !Uri.TryCreate( url, UriKind.Absolute, out var uri ) ) return \u0022baseUrl must be a full URL\u0022;\n\t\tif ( uri.Scheme == \u0022https\u0022 )\n\t\t\treturn IsDomainName( uri.Host ) ? null : \u0022baseUrl must name a domain, not an IP address\u0022;\n\t\tif ( uri.Scheme == \u0022http\u0022 \u0026\u0026 uri.Host == \u0022localhost\u0022 )\n\t\t\treturn null;\n\t\treturn \u0022baseUrl must start with https:// and name a domain (http is allowed for localhost only, for tests)\u0022;\n\t}\n\n\t/// \u003Csummary\u003Es\u0026amp;box allows localhost only on ports 80, 443, 8080 and 8443, unless the editor or server runs with -allowlocalhttp.\u003C/summary\u003E\n\tinternal static string LocalhostWarning( string url )\n\t{\n\t\tif ( !Uri.TryCreate( url, UriKind.Absolute, out var uri ) || uri.Scheme != \u0022http\u0022 || uri.Host != \u0022localhost\u0022 ) return null;\n\t\tif ( uri.Port == 80 || uri.Port == 443 || uri.Port == 8080 || uri.Port == 8443 ) return null;\n\t\treturn $\u0022s\u0026box refuses localhost port {uri.Port} unless the editor or server runs with -allowlocalhttp\u0022;\n\t}\n\n\t/// \u003Csummary\u003EA domain name has a dot, and is not an IPv4 address (digits and dots only) or an IPv6 literal.\u003C/summary\u003E\n\tstatic bool IsDomainName( string host )\n\t{\n\t\tif ( string.IsNullOrEmpty( host ) || host.Length \u003E 253 || host.IndexOf( \u0027.\u0027 ) \u003C 0 ) return false;\n\t\tvar letters = false;\n\t\tforeach ( var c in host )\n\t\t{\n\t\t\tif ( c == \u0027:\u0027 || c == \u0027[\u0027 || c == \u0027]\u0027 ) return false;\n\t\t\tif ( !(char.IsDigit( c ) || c == \u0027.\u0027) ) letters = true;\n\t\t}\n\t\treturn letters;\n\t}\n\n\t/// \u003Csummary\u003Esbs_ is the protocol v1 server secret prefix; sbt_ is the generic protocol token prefix (PROTOCOL.md section 4).\u003C/summary\u003E\n\tinternal static bool IsToken( string token )\n\t{\n\t\tif ( token is null || token.Length != 47 ) return false;\n\t\tif ( !(token.StartsWith( \u0022sbs_\u0022 ) || token.StartsWith( \u0022sbt_\u0022 )) ) return false;\n\t\treturn IsIdent( token.Substring( 4 ), 43, 43 );\n\t}\n\n\t/// \u003Csummary\u003EA site id: lowercase letters, digits, dots and dashes; at most 63 characters; starts with a letter or digit.\u003C/summary\u003E\n\tinternal static bool IsSiteId( string value )\n\t{\n\t\tif ( string.IsNullOrEmpty( value ) || value.Length \u003E 63 ) return false;\n\t\tfor ( var i = 0; i \u003C value.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar c = value[i];\n\t\t\tvar letterOrDigit = (c \u003E= \u0027a\u0027 \u0026\u0026 c \u003C= \u0027z\u0027) || (c \u003E= \u00270\u0027 \u0026\u0026 c \u003C= \u00279\u0027);\n\t\t\tif ( i == 0 ? !letterOrDigit : !(letterOrDigit || c == \u0027.\u0027 || c == \u0027-\u0027) ) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tinternal static bool IsIdent( string value, int min, int max )\n\t{\n\t\tif ( value is null || value.Length \u003C min || value.Length \u003E max ) return false;\n\t\tforeach ( var c in value )\n\t\t{\n\t\t\tvar ok = (c \u003E= \u0027a\u0027 \u0026\u0026 c \u003C= \u0027z\u0027) || (c \u003E= \u0027A\u0027 \u0026\u0026 c \u003C= \u0027Z\u0027) || (c \u003E= \u00270\u0027 \u0026\u0026 c \u003C= \u00279\u0027) || c == \u0027_\u0027 || c == \u0027-\u0027;\n\t\t\tif ( !ok ) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstatic string HostOf( string url )\n\t{\n\t\ttry { return new Uri( url.Trim() ).Host.ToLowerInvariant(); }\n\t\tcatch { return \u0022site\u0022; }\n\t}\n}\n"}]}