{"TotalCount":186,"Files":[{"Ident":"sboxcool.network-storage","Path":"Editor/ConfirmDialog.cs","FileName":"ConfirmDialog.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\nusing Editor;\r\n\r\n/// \u003Csummary\u003E\r\n/// Modal-style confirmation dialog with Overwrite/Cancel buttons.\r\n/// Use ConfirmDialog.Show(title, message, onConfirm) to display.\r\n/// \u003C/summary\u003E\r\npublic class ConfirmDialog : PaintedWindow\r\n{\r\n\tprivate readonly string _title;\r\n\tprivate readonly string _message;\r\n\tprivate readonly string _detail;\r\n\tprivate readonly Action _onConfirm;\r\n\tprivate Vector2 _mousePos;\r\n\r\n\tprivate ConfirmDialog( string title, string message, string detail, Action onConfirm )\r\n\t{\r\n\t\t_title = title;\r\n\t\t_message = message;\r\n\t\t_detail = detail;\r\n\t\t_onConfirm = onConfirm;\r\n\t\tTitle = title;\r\n\t\tSize = new Vector2( 420, string.IsNullOrEmpty( detail ) ? 180 : 240 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Show a confirmation dialog with Overwrite and Cancel buttons.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void Show( string title, string message, Action onConfirm, string detail = null )\r\n\t{\r\n\t\tvar dialog = new ConfirmDialog( title, message, detail, onConfirm );\r\n\t\tdialog.Show();\r\n\t}\r\n\r\n\tprotected override void OnContentPaint()\r\n\t{\r\n\t\tbase.OnContentPaint();\r\n\r\n\t\tvar pad = 20f;\r\n\t\tvar w = Width - pad * 2;\r\n\t\tvar y = 20f;\r\n\r\n\t\t// Title\r\n\t\tPaint.SetDefaultFont( size: 13, weight: 700 );\r\n\t\tPaint.SetPen( Color.White );\r\n\t\tPaint.DrawText( new Rect( pad, y, w, 22 ), _title, TextFlag.LeftCenter );\r\n\t\ty \u002B= 32;\r\n\r\n\t\t// Message\r\n\t\tPaint.SetDefaultFont( size: 10 );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( 0.85f ) );\r\n\r\n\t\t// Word-wrap the message manually\r\n\t\tvar words = _message.Split( \u0027 \u0027 );\r\n\t\tvar line = \u0022\u0022;\r\n\t\tforeach ( var word in words )\r\n\t\t{\r\n\t\t\tvar test = string.IsNullOrEmpty( line ) ? word : $\u0022{line} {word}\u0022;\r\n\t\t\tif ( test.Length * 6.5f \u003E w \u0026\u0026 !string.IsNullOrEmpty( line ) )\r\n\t\t\t{\r\n\t\t\t\tPaint.DrawText( new Rect( pad, y, w, 16 ), line, TextFlag.LeftCenter );\r\n\t\t\t\ty \u002B= 17;\r\n\t\t\t\tline = word;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tline = test;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif ( !string.IsNullOrEmpty( line ) )\r\n\t\t{\r\n\t\t\tPaint.DrawText( new Rect( pad, y, w, 16 ), line, TextFlag.LeftCenter );\r\n\t\t\ty \u002B= 20;\r\n\t\t}\r\n\r\n\t\t// Detail (smaller, dimmer)\r\n\t\tif ( !string.IsNullOrEmpty( _detail ) )\r\n\t\t{\r\n\t\t\ty \u002B= 4;\r\n\t\t\tPaint.SetDefaultFont( size: 9 );\r\n\t\t\tPaint.SetPen( Color.Orange.WithAlpha( 0.7f ) );\r\n\t\t\tPaint.DrawText( new Rect( pad, y, w, 14 ), _detail, TextFlag.LeftCenter );\r\n\t\t\ty \u002B= 22;\r\n\t\t}\r\n\r\n\t\ty \u002B= 8;\r\n\r\n\t\t// Buttons row\r\n\t\tvar btnH = 32f;\r\n\t\tvar btnW = ( w - 12 ) / 2;\r\n\r\n\t\t// Cancel button (left)\r\n\t\tvar cancelRect = new Rect( pad, y, btnW, btnH );\r\n\t\tvar cancelHovered = cancelRect.IsInside( _mousePos );\r\n\t\tPaint.SetBrush( Color.White.WithAlpha( cancelHovered ? 0.1f : 0.04f ) );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( cancelHovered ? 0.3f : 0.15f ) );\r\n\t\tPaint.DrawRect( cancelRect, 4 );\r\n\t\tPaint.SetDefaultFont( size: 11, weight: 600 );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( cancelHovered ? 0.9f : 0.6f ) );\r\n\t\tPaint.DrawText( cancelRect, \u0022Cancel\u0022, TextFlag.Center );\r\n\r\n\t\t// Overwrite button (right)\r\n\t\tvar overwriteRect = new Rect( pad \u002B btnW \u002B 12, y, btnW, btnH );\r\n\t\tvar overwriteHovered = overwriteRect.IsInside( _mousePos );\r\n\t\tPaint.SetBrush( Color.Red.WithAlpha( overwriteHovered ? 0.25f : 0.12f ) );\r\n\t\tPaint.SetPen( Color.Red.WithAlpha( overwriteHovered ? 0.6f : 0.3f ) );\r\n\t\tPaint.DrawRect( overwriteRect, 4 );\r\n\t\tPaint.SetDefaultFont( size: 11, weight: 700 );\r\n\t\tPaint.SetPen( Color.Red.WithAlpha( overwriteHovered ? 1f : 0.8f ) );\r\n\t\tPaint.DrawText( overwriteRect, \u0022Overwrite\u0022, TextFlag.Center );\r\n\r\n\t\t_cancelRect = cancelRect;\r\n\t\t_overwriteRect = overwriteRect;\r\n\t}\r\n\r\n\tprivate Rect _cancelRect;\r\n\tprivate Rect _overwriteRect;\r\n\r\n\tprotected override void OnContentMousePress( MouseEvent e )\r\n\t{\r\n\t\tbase.OnContentMousePress(e);\r\n\r\n\t\tif ( _cancelRect.IsInside( e.LocalPosition ) )\r\n\t\t{\r\n\t\t\tClose();\r\n\t\t}\r\n\t\telse if ( _overwriteRect.IsInside( e.LocalPosition ) )\r\n\t\t{\r\n\t\t\tClose();\r\n\t\t\t_onConfirm?.Invoke();\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void OnContentMouseMove( MouseEvent e )\r\n\t{\r\n\t\tbase.OnContentMouseMove(e);\r\n\t\t_mousePos = e.LocalPosition;\r\n\t\tUpdate();\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Editor/PaintedWindow.cs","FileName":"PaintedWindow.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":429205,"IsPrivate":false,"Code":"using Editor;\r\n\r\n/// \u003Csummary\u003E\r\n/// Standalone editor window whose content is rendered and interacted with through\r\n/// the window\u0027s central widget. Current s\u0026amp;box windows reserve their root widget\r\n/// for window chrome, so custom content must live on \u003Csee cref=\u0022Window.Canvas\u0022/\u003E.\r\n/// \u003C/summary\u003E\r\npublic abstract class PaintedWindow : Window\r\n{\r\n\tprivate readonly ContentWidget _content;\r\n\r\n\tprotected PaintedWindow()\r\n\t{\r\n\t\t_content = new ContentWidget( this );\r\n\t\tCanvas = _content;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Parent for native controls that must appear above the painted content.\r\n\t/// \u003C/summary\u003E\r\n\tprotected Widget Content =\u003E _content;\r\n\r\n\tpublic new float Width\r\n\t{\r\n\t\tget =\u003E _content.Width;\r\n\t\tset =\u003E base.Width = value;\r\n\t}\r\n\r\n\tpublic new float Height\r\n\t{\r\n\t\tget =\u003E _content.Height;\r\n\t\tset =\u003E base.Height = value;\r\n\t}\r\n\r\n\tpublic new bool MouseTracking\r\n\t{\r\n\t\tget =\u003E _content.MouseTracking;\r\n\t\tset\r\n\t\t{\r\n\t\t\tbase.MouseTracking = value;\r\n\t\t\t_content.MouseTracking = value;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic override void Update()\r\n\t{\r\n\t\tbase.Update();\r\n\t\t_content.Update();\r\n\t}\r\n\r\n\tprotected virtual void OnContentPaint()\r\n\t{\r\n\t}\r\n\r\n\tprotected virtual void OnContentMousePress( MouseEvent e )\r\n\t{\r\n\t}\r\n\r\n\tprotected virtual void OnContentMouseMove( MouseEvent e )\r\n\t{\r\n\t}\r\n\r\n\tprotected virtual void OnContentMouseWheel( WheelEvent e )\r\n\t{\r\n\t}\r\n\r\n\tprotected virtual void OnContentKeyPress( KeyEvent e )\r\n\t{\r\n\t}\r\n\r\n\tprivate sealed class ContentWidget : Widget\r\n\t{\r\n\t\tprivate readonly PaintedWindow _owner;\r\n\r\n\t\tpublic ContentWidget( PaintedWindow owner )\r\n\t\t{\r\n\t\t\t_owner = owner;\r\n\t\t\tMouseTracking = true;\r\n\t\t\tFocusMode = FocusMode.TabOrClickOrWheel;\r\n\t\t}\r\n\r\n\t\tprotected override void OnPaint()\r\n\t\t{\r\n\t\t\tbase.OnPaint();\r\n\t\t\t_owner.OnContentPaint();\r\n\t\t}\r\n\r\n\t\tprotected override void OnMousePress( MouseEvent e )\r\n\t\t{\r\n\t\t\tbase.OnMousePress( e );\r\n\t\t\t_owner.OnContentMousePress( e );\r\n\t\t}\r\n\r\n\t\tprotected override void OnMouseMove( MouseEvent e )\r\n\t\t{\r\n\t\t\tbase.OnMouseMove( e );\r\n\t\t\t_owner.OnContentMouseMove( e );\r\n\t\t}\r\n\r\n\t\tprotected override void OnMouseWheel( WheelEvent e )\r\n\t\t{\r\n\t\t\tbase.OnMouseWheel( e );\r\n\t\t\t_owner.OnContentMouseWheel( e );\r\n\t\t}\r\n\r\n\t\tprotected override void OnKeyPress( KeyEvent e )\r\n\t\t{\r\n\t\t\tbase.OnKeyPress( e );\r\n\t\t\t_owner.OnContentKeyPress( e );\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Code/Core/NetworkStorageRevisionConfig.cs","FileName":"NetworkStorageRevisionConfig.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"namespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// Opt-in configuration for revision enforcement features.\r\n/// All settings default to false \u2014 game code must explicitly opt in.\r\n/// \u003C/summary\u003E\r\npublic static class NetworkStorageRevisionConfig\r\n{\r\n\t/// \u003Csummary\u003EShow built-in warning UI when an outdated revision is detected.\u003C/summary\u003E\r\n\tpublic static bool EnableRevisionWarningUI { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Auto-disconnect the local client when the revision grace period has expired.\r\n\t/// DANGEROUS: test thoroughly before enabling in production.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static bool EnableAutoDisconnectHost { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Set \u003Csee cref=\u0022NetworkStorageRevisionHandler.BlockWrites\u0022/\u003E when running\r\n\t/// an outdated revision. Endpoint code should check this flag before performing writes.\r\n\t/// DANGEROUS: may cause data loss if callers ignore the flag.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static bool EnableBlockSavesOnOutdated { get; set; }\r\n\t\r\n\t// \u2500\u2500 Built-in Outdated Revision Window \u2500\u2500\r\n\t\r\n\t/// \u003Csummary\u003EEnable the entire outdated revision notification UI system.\u003C/summary\u003E\r\n\tpublic static bool EnableOutdatedUI { get; set; }\r\n\t\r\n\t/// \u003Csummary\u003EShow the built-in default warning window.\u003C/summary\u003E\r\n\tpublic static bool ShowDefaultWindow { get; set; }\r\n\t\r\n\t/// \u003Csummary\u003EOnly show the warning once per session.\u003C/summary\u003E\r\n\tpublic static bool ShowOnlyOnce { get; set; } = true;\r\n\t\r\n\t/// \u003Csummary\u003EGrace period override (seconds) before showing the warning. 0 = show immediately.\u003C/summary\u003E\r\n\tpublic static float GracePeriod { get; set; }\r\n\t\r\n\t/// \u003Csummary\u003EAuto-refresh the lobby list when revision is outdated.\u003C/summary\u003E\r\n\tpublic static bool AutoRefreshLobbyList { get; set; }\r\n\t\r\n\t/// \u003Csummary\u003EInterval in seconds between lobby list refreshes.\u003C/summary\u003E\r\n\tpublic static float LobbyRefreshInterval { get; set; } = 10f;\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Code/Endpoints/NetworkStorageProxySignature.cs","FileName":"NetworkStorageProxySignature.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Text;\r\n\r\nnamespace Sandbox;\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// Compute HMAC-SHA256 proxy signature scoped to project \u002B endpoint \u002B client.\r\n\t/// Must produce the same hex string as the backend\u0027s computeProxySignature().\r\n\t/// Format: HMAC-SHA256(apiKey, \u0022projectId:endpointSlug:clientSteamId:clientToken\u0022)\r\n\t///\r\n\t/// Uses a pure managed SHA-256 \u002B HMAC implementation because s\u0026amp;box\u0027s whitelist\r\n\t/// blocks System.Security.Cryptography.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static string ComputeProxySignature( string apiKey, string projectId, string endpointSlug, string clientSteamId, string clientToken )\r\n\t{\r\n\t\tvar data = $\u0022{projectId}:{endpointSlug}:{clientSteamId}:{clientToken}\u0022;\r\n\t\tvar keyBytes = Encoding.UTF8.GetBytes( apiKey );\r\n\t\tvar dataBytes = Encoding.UTF8.GetBytes( data );\r\n\t\tvar hash = HmacSha256( keyBytes, dataBytes );\r\n\r\n\t\tvar sb = new StringBuilder( hash.Length * 2 );\r\n\t\tforeach ( var b in hash )\r\n\t\t\tsb.Append( b.ToString( \u0022x2\u0022 ) );\r\n\t\treturn sb.ToString();\r\n\t}\r\n\r\n\tprivate static byte[] HmacSha256( byte[] key, byte[] message )\r\n\t{\r\n\t\tconst int blockSize = 64;\r\n\r\n\t\tif ( key.Length \u003E blockSize )\r\n\t\t\tkey = Sha256( key );\r\n\r\n\t\tvar paddedKey = new byte[blockSize];\r\n\t\tArray.Copy( key, paddedKey, key.Length );\r\n\r\n\t\tvar ipad = new byte[blockSize];\r\n\t\tvar opad = new byte[blockSize];\r\n\t\tfor ( int i = 0; i \u003C blockSize; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tipad[i] = (byte)(paddedKey[i] ^ 0x36);\r\n\t\t\topad[i] = (byte)(paddedKey[i] ^ 0x5c);\r\n\t\t}\r\n\r\n\t\tvar inner = new byte[blockSize \u002B message.Length];\r\n\t\tArray.Copy( ipad, 0, inner, 0, blockSize );\r\n\t\tArray.Copy( message, 0, inner, blockSize, message.Length );\r\n\t\tvar innerHash = Sha256( inner );\r\n\r\n\t\tvar outer = new byte[blockSize \u002B 32];\r\n\t\tArray.Copy( opad, 0, outer, 0, blockSize );\r\n\t\tArray.Copy( innerHash, 0, outer, blockSize, 32 );\r\n\t\treturn Sha256( outer );\r\n\t}\r\n\r\n\tprivate static readonly uint[] _sha256K = {\r\n\t\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\r\n\t\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\r\n\t\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\r\n\t\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\r\n\t\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\r\n\t\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\r\n\t\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\r\n\t\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\r\n\t};\r\n\r\n\tprivate static byte[] Sha256( byte[] data )\r\n\t{\r\n\t\tlong bitLen = (long)data.Length * 8;\r\n\t\tint padLen = (64 - (int)((data.Length \u002B 9) % 64)) % 64;\r\n\t\tvar msg = new byte[data.Length \u002B 1 \u002B padLen \u002B 8];\r\n\t\tArray.Copy( data, msg, data.Length );\r\n\t\tmsg[data.Length] = 0x80;\r\n\t\tfor ( int i = 0; i \u003C 8; i\u002B\u002B )\r\n\t\t\tmsg[msg.Length - 1 - i] = (byte)(bitLen \u003E\u003E (i * 8));\r\n\r\n\t\tuint h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;\r\n\t\tuint h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;\r\n\r\n\t\tvar w = new uint[64];\r\n\r\n\t\tfor ( int offset = 0; offset \u003C msg.Length; offset \u002B= 64 )\r\n\t\t{\r\n\t\t\tfor ( int i = 0; i \u003C 16; i\u002B\u002B )\r\n\t\t\t\tw[i] = (uint)(msg[offset \u002B i * 4] \u003C\u003C 24 | msg[offset \u002B i * 4 \u002B 1] \u003C\u003C 16 | msg[offset \u002B i * 4 \u002B 2] \u003C\u003C 8 | msg[offset \u002B i * 4 \u002B 3]);\r\n\r\n\t\t\tfor ( int i = 16; i \u003C 64; i\u002B\u002B )\r\n\t\t\t{\r\n\t\t\t\tvar s0 = RotR( w[i - 15], 7 ) ^ RotR( w[i - 15], 18 ) ^ (w[i - 15] \u003E\u003E 3);\r\n\t\t\t\tvar s1 = RotR( w[i - 2], 17 ) ^ RotR( w[i - 2], 19 ) ^ (w[i - 2] \u003E\u003E 10);\r\n\t\t\t\tw[i] = w[i - 16] \u002B s0 \u002B w[i - 7] \u002B s1;\r\n\t\t\t}\r\n\r\n\t\t\tuint a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;\r\n\r\n\t\t\tfor ( int i = 0; i \u003C 64; i\u002B\u002B )\r\n\t\t\t{\r\n\t\t\t\tvar S1 = RotR( e, 6 ) ^ RotR( e, 11 ) ^ RotR( e, 25 );\r\n\t\t\t\tvar ch = (e \u0026 f) ^ (~e \u0026 g);\r\n\t\t\t\tvar temp1 = h \u002B S1 \u002B ch \u002B _sha256K[i] \u002B w[i];\r\n\t\t\t\tvar S0 = RotR( a, 2 ) ^ RotR( a, 13 ) ^ RotR( a, 22 );\r\n\t\t\t\tvar maj = (a \u0026 b) ^ (a \u0026 c) ^ (b \u0026 c);\r\n\t\t\t\tvar temp2 = S0 \u002B maj;\r\n\r\n\t\t\t\th = g; g = f; f = e; e = d \u002B temp1;\r\n\t\t\t\td = c; c = b; b = a; a = temp1 \u002B temp2;\r\n\t\t\t}\r\n\r\n\t\t\th0 \u002B= a; h1 \u002B= b; h2 \u002B= c; h3 \u002B= d;\r\n\t\t\th4 \u002B= e; h5 \u002B= f; h6 \u002B= g; h7 \u002B= h;\r\n\t\t}\r\n\r\n\t\tvar result = new byte[32];\r\n\t\tWriteBE( result, 0, h0 ); WriteBE( result, 4, h1 );\r\n\t\tWriteBE( result, 8, h2 ); WriteBE( result, 12, h3 );\r\n\t\tWriteBE( result, 16, h4 ); WriteBE( result, 20, h5 );\r\n\t\tWriteBE( result, 24, h6 ); WriteBE( result, 28, h7 );\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate static uint RotR( uint x, int n ) =\u003E (x \u003E\u003E n) | (x \u003C\u003C (32 - n));\r\n\r\n\tprivate static void WriteBE( byte[] buf, int offset, uint val )\r\n\t{\r\n\t\tbuf[offset] = (byte)(val \u003E\u003E 24);\r\n\t\tbuf[offset \u002B 1] = (byte)(val \u003E\u003E 16);\r\n\t\tbuf[offset \u002B 2] = (byte)(val \u003E\u003E 8);\r\n\t\tbuf[offset \u002B 3] = (byte)val;\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Code/Endpoints/NetworkStorageSecureRandom.cs","FileName":"NetworkStorageSecureRandom.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Sandbox;\r\n\r\n// The only source of key, IV, nonce and OAEP seed bytes for encryption v2.\r\n// System.Security.Cryptography.RandomNumberGenerator is not on the s\u0026box whitelist.\r\n// Each 32-byte block is SHA-256(domain label || 32-bit counter || guid || guid || guid)\r\n// over fresh Guid.NewGuid() values, which are OS CSPRNG-backed (about 366 random bits per block).\r\ninternal static class NetworkStorageSecureRandom\r\n{\r\n\tprivate static readonly byte[] DomainLabel = Encoding.UTF8.GetBytes( \u0022sboxcool.network-storage.secure-random.v2\u0022 );\r\n\r\n\tinternal static byte[] Bytes( int count )\r\n\t{\r\n\t\tvar output = new byte[count];\r\n\t\tvar written = 0;\r\n\t\tfor ( uint counter = 0; written \u003C count; counter\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar digest = NetworkStorageSecuritySignature.Sha256( BlockInput( counter ) );\r\n\t\t\tvar take = Math.Min( digest.Length, count - written );\r\n\t\t\tArray.Copy( digest, 0, output, written, take );\r\n\t\t\twritten \u002B= take;\r\n\t\t}\r\n\t\treturn output;\r\n\t}\r\n\r\n\tprivate static byte[] BlockInput( uint counter )\r\n\t{\r\n\t\tvar input = new List\u003Cbyte\u003E( DomainLabel );\r\n\t\tinput.Add( (byte)(counter \u003E\u003E 24) );\r\n\t\tinput.Add( (byte)(counter \u003E\u003E 16) );\r\n\t\tinput.Add( (byte)(counter \u003E\u003E 8) );\r\n\t\tinput.Add( (byte)counter );\r\n\t\tfor ( var i = 0; i \u003C 3; i\u002B\u002B )\r\n\t\t\tinput.AddRange( Guid.NewGuid().ToByteArray() );\r\n\t\treturn input.ToArray();\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Core/NetworkStorageRawResponse.cs","FileName":"NetworkStorageRawResponse.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Net.Http;\r\nusing System.Text.Json;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// One server reply as received. A non-2xx status is data, not an exception: s\u0026amp;box exposes the status and body of\r\n/// every response, so the library reports the server\u0027s own error code instead of a generic HTTP failure.\r\n/// Status 0 means no response arrived; \u003Csee cref=\u0022TransportError\u0022/\u003E then holds the reason.\r\n/// \u003C/summary\u003E\r\ninternal sealed record RawReply( int Status, string Body, string TransportError, string RetryAfter )\r\n{\r\n\tpublic bool Ok =\u003E Status is \u003E= 200 and \u003C 300;\r\n}\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\t/// \u003Csummary\u003ESends a request with an optional JSON body. Never throws for an HTTP status.\u003C/summary\u003E\r\n\tinternal static Task\u003CRawReply\u003E SendRawAsync( string url, string method, object body, Dictionary\u003Cstring, string\u003E headers )\r\n\t{\r\n\t\tFunc\u003CHttpContent\u003E createContent = null;\r\n\t\tif ( body is not null ) createContent = () =\u003E Http.CreateJsonContent( body );\r\n\t\treturn SendRawContentAsync( url, method, createContent, headers );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Sends a request whose content is built per attempt. Adds correlation and write-idempotency tokens unless the\r\n\t/// caller set them; transport retries reuse the same headers and tokens.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static Task\u003CRawReply\u003E SendRawContentAsync( string url, string method, Func\u003CHttpContent\u003E createContent, Dictionary\u003Cstring, string\u003E headers )\r\n\t{\r\n\t\theaders ??= new Dictionary\u003Cstring, string\u003E();\r\n\t\tif ( !headers.ContainsKey( \u0022X-Correlation-ID\u0022 ) ) headers[\u0022X-Correlation-ID\u0022] = NewRequestToken();\r\n\t\tif ( method is \u0022POST\u0022 or \u0022PUT\u0022 or \u0022PATCH\u0022 or \u0022DELETE\u0022 \u0026\u0026 !headers.ContainsKey( \u0022Idempotency-Key\u0022 ) )\r\n\t\t\theaders[\u0022Idempotency-Key\u0022] = NewRequestToken();\r\n\t\treturn SendWithRetriesAsync( method, createContent, content =\u003E Http.RequestAsync( url, method, content, headers ) );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EA fresh opaque token for correlation ids and idempotency keys.\u003C/summary\u003E\r\n\tinternal static string NewRequestToken() =\u003E Guid.NewGuid().ToString( \u0022N\u0022 );\r\n\r\n\t/// \u003Csummary\u003EStatus text for a reply without a server error body, e.g. \u0022HTTP 413 RequestEntityTooLarge\u0022.\u003C/summary\u003E\r\n\tinternal static string HttpStatusMessage( int status ) =\u003E $\u0022HTTP {status} {(HttpStatusCode)status}\u0022;\r\n\r\n\t/// \u003Csummary\u003ETrue for an UPPER_SNAKE_CASE code such as \u003Cc\u003ERATE_LIMITED\u003C/c\u003E. Sentences are messages, not codes.\u003C/summary\u003E\r\n\tinternal static bool IsErrorCodeToken( string value )\r\n\t{\r\n\t\tif ( string.IsNullOrEmpty( value ) || value.Length \u003E 64 || value[0] \u003C \u0027A\u0027 || value[0] \u003E \u0027Z\u0027 ) return false;\r\n\t\tforeach ( var c in value )\r\n\t\t{\r\n\t\t\tif ( !((c \u003E= \u0027A\u0027 \u0026\u0026 c \u003C= \u0027Z\u0027) || (c \u003E= \u00270\u0027 \u0026\u0026 c \u003C= \u00279\u0027) || c == \u0027_\u0027) ) return false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Code and message for a failed reply. A JSON error keeps the server\u0027s own code. Otherwise a 429 is\r\n\t/// \u003Cc\u003ERATE_LIMITED\u003C/c\u003E and anything else gets \u003Cparamref name=\u0022fallbackCode\u0022/\u003E. Transport failures are \u003Cc\u003EREQUEST_FAILED\u003C/c\u003E.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static void ClassifyFailure( RawReply reply, string fallbackCode, out string code, out string message )\r\n\t{\r\n\t\tif ( reply.TransportError is not null )\r\n\t\t{\r\n\t\t\tcode = \u0022REQUEST_FAILED\u0022;\r\n\t\t\tmessage = reply.TransportError;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcode = ReadErrorCode( reply.Body ) ?? (reply.Status == 429 ? \u0022RATE_LIMITED\u0022 : fallbackCode);\r\n\t\tvar serverMessage = ReadErrorMessage( reply.Body );\r\n\t\tmessage = string.IsNullOrWhiteSpace( serverMessage ) ? HttpStatusMessage( reply.Status ) : serverMessage;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Records a failed reply under \u003Cparamref name=\u0022slug\u0022/\u003E. A reply carrying a server JSON error goes through\r\n\t/// \u003Csee cref=\u0022LogServerError\u0022/\u003E, so its code and side effects (auth invalidation, security config) match the envelope path.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static void RecordReplyFailure( string slug, RawReply reply, string fallbackCode )\r\n\t{\r\n\t\tif ( reply.TransportError is null \u0026\u0026 ReadErrorCode( reply.Body ) is not null )\r\n\t\t{\r\n\t\t\tusing var document = JsonDocument.Parse( reply.Body );\r\n\t\t\tLogServerError( slug, document.RootElement );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tClassifyFailure( reply, fallbackCode, out var code, out var message );\r\n\t\tRecordFailure( slug, code, message );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ELogs and records a failure that has no server JSON error body.\u003C/summary\u003E\r\n\tinternal static void RecordFailure( string slug, string code, string message )\r\n\t{\r\n\t\tif ( NetworkStorageLogConfig.LogErrors )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] {slug} FAILED - {code}: {message}\u0022 );\r\n\t\t\tNetLog.Error( slug, message );\r\n\t\t}\r\n\t\tRecordEndpointError( slug, code, message );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Reads a document reply verbatim. Any valid JSON value on a 2xx reply is the document. Nothing is unwrapped, and keys\r\n\t/// such as \u003Cc\u003Eok\u003C/c\u003E, \u003Cc\u003Eerror\u003C/c\u003E, \u003Cc\u003Ebody\u003C/c\u003E or \u003Cc\u003E_revisionStatus\u003C/c\u003E carry no meaning in stored data.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static bool TryReadRawDocument( RawReply reply, out JsonElement document, out string code, out string message )\r\n\t{\r\n\t\tdocument = default;\r\n\t\tif ( !reply.Ok )\r\n\t\t{\r\n\t\t\tClassifyFailure( reply, reply.Status == 404 ? \u0022NOT_FOUND\u0022 : \u0022REQUEST_FAILED\u0022, out code, out message );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif ( string.IsNullOrWhiteSpace( reply.Body ) )\r\n\t\t{\r\n\t\t\tcode = \u0022EMPTY_RESPONSE\u0022;\r\n\t\t\tmessage = \u0022Server returned an empty response.\u0022;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdocument = JsonSerializer.Deserialize\u003CJsonElement\u003E( reply.Body );\r\n\t\t}\r\n\t\tcatch ( JsonException )\r\n\t\t{\r\n\t\t\tvar trimmed = reply.Body.TrimStart();\r\n\t\t\tvar looksJson = trimmed.Length \u003E 0 \u0026\u0026 (trimmed[0] == \u0027{\u0027 || trimmed[0] == \u0027[\u0027);\r\n\t\t\tcode = looksJson ? \u0022INVALID_JSON\u0022 : \u0022INVALID_RESPONSE\u0022;\r\n\t\t\tmessage = \u0022Server returned a response that is not valid JSON.\u0022;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tcode = null;\r\n\t\tmessage = null;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True for a \u003Cc\u003ESECURITY_*\u003C/c\u003E refusal the server marks \u003Cc\u003EretrySafe\u003C/c\u003E: the request was refused before it ran, so the\r\n\t/// caller may refresh its security config and send again. A prefix match alone is not enough.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static bool IsRetrySafeSecurityRefusal( string body )\r\n\t{\r\n\t\tif ( string.IsNullOrEmpty( body ) ) return false;\r\n\t\tvar code = ReadErrorCode( body );\r\n\t\treturn code is not null \u0026\u0026 IsSecurityConfigMismatchCode( code )\r\n\t\t\t\u0026\u0026 ReadRoot( body, root =\u003E root.TryGetProperty( \u0022retrySafe\u0022, out var r ) \u0026\u0026 r.ValueKind == JsonValueKind.True, false );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Runs one event listener. A listener that throws is logged and the throw never reaches the request that raised the event.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static void InvokeSafely\u003CT\u003E( Action\u003CT\u003E handler, T value, string name )\r\n\t{\r\n\t\tif ( handler is null ) return;\r\n\t\ttry\r\n\t\t{\r\n\t\t\thandler( value );\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] {name} listener failed: {ex.Message}\u0022 );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EParameterless form of \u003Csee cref=\u0022InvokeSafely{T}(Action{T}, T, string)\u0022/\u003E.\u003C/summary\u003E\r\n\tinternal static void InvokeSafely( Action handler, string name )\r\n\t{\r\n\t\tif ( handler is null ) return;\r\n\t\ttry\r\n\t\t{\r\n\t\t\thandler();\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] {name} listener failed: {ex.Message}\u0022 );\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Core/NetworkStorageRevisionInit.cs","FileName":"NetworkStorageRevisionInit.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Text.Json;\r\nusing System.Collections.Generic;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// Result of the one-time revision init handshake with the backend.\r\n/// \u003C/summary\u003E\r\npublic struct RevisionInitResult\r\n{\r\n\t/// \u003Csummary\u003ETrue when the backend acknowledged the init successfully.\u003C/summary\u003E\r\n\tpublic bool Ok { get; set; }\r\n\r\n\t/// \u003Csummary\u003ETrue when the server reports a newer revision is available.\u003C/summary\u003E\r\n\tpublic bool IsOutdatedRevision { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe revision this client is running, if known.\u003C/summary\u003E\r\n\tpublic long? PlayerRevision { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe latest revision reported by the backend.\u003C/summary\u003E\r\n\tpublic long? CurrentRevision { get; set; }\r\n\r\n\t/// \u003Csummary\u003EHuman-readable status or warning message from the server.\u003C/summary\u003E\r\n\tpublic string Message { get; set; }\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// Sends a one-time revision-init packet at game startup so the backend\r\n/// knows which revision this client is running.\r\n/// Call once after \u003Csee cref=\u0022NetworkStorage.Configure\u0022/\u003E.\r\n/// \u003C/summary\u003E\r\npublic static class NetworkStorageRevisionInit\r\n{\r\n\t/// \u003Csummary\u003ECached result from the last successful \u003Csee cref=\u0022SendInitAsync\u0022/\u003E call.\u003C/summary\u003E\r\n\tpublic static RevisionInitResult? LastInitResult { get; private set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Send the revision init packet to the backend.\r\n\t/// Safe to call even when package/revision data is unavailable \u2014 the request\r\n\t/// proceeds without revision headers and the result reflects the gap.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static async Task\u003CRevisionInitResult\u003E SendInitAsync()\r\n\t{\r\n\t\tNetworkStorage.EnsureConfigured();\r\n\r\n\t\t// \u2500\u2500 Detect package info if not already done \u2500\u2500\r\n\t\tif ( !NetworkStoragePackageInfo.IsDetected )\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tawait NetworkStoragePackageInfo.DetectAsync();\r\n\t\t\t}\r\n\t\t\tcatch ( Exception ex )\r\n\t\t\t{\r\n\t\t\t\tLog.Warning( $\u0022[NetworkStorage] revision-init: package detection failed \u2014 {ex.Message}\u0022 );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// \u2500\u2500 Build request body \u2500\u2500\r\n\t\tvar clientType = NetworkStorage.GetClientType();\r\n\t\tvar revisionId = NetworkStoragePackageInfo.RuntimeRevisionId;\r\n\t\tvar body = new Dictionary\u003Cstring, object\u003E\r\n\t\t{\r\n\t\t\t{ \u0022projectId\u0022, NetworkStorage.ProjectId },\r\n\t\t\t{ \u0022clientType\u0022, clientType },\r\n\t\t\t{ \u0022networkStorageVersion\u0022, NetworkStorage.LibraryVersion },\r\n\t\t\t{ \u0022isPublishedGameBundle\u0022, NetworkStoragePackageInfo.IsPublishedGameBundle }\r\n\t\t};\r\n\r\n\t\tif ( !string.IsNullOrEmpty( NetworkStoragePackageInfo.PackageIdent ) )\r\n\t\t\tbody[\u0022packageIdent\u0022] = NetworkStoragePackageInfo.PackageIdent;\r\n\r\n\t\tif ( revisionId.HasValue )\r\n\t\t\tbody[\u0022revisionId\u0022] = revisionId.Value;\r\n\r\n\t\t// \u2500\u2500 Build headers \u2500\u2500\r\n\t\tvar headers = new Dictionary\u003Cstring, string\u003E\r\n\t\t{\r\n\t\t\t{ \u0022x-public-key\u0022, NetworkStorage.ApiKey ?? \u0022\u0022 },\r\n\t\t\t{ \u0022x-ns-library-version\u0022, NetworkStorage.LibraryVersion }\r\n\t\t};\r\n\r\n\t\tif ( revisionId.HasValue )\r\n\t\t\theaders[\u0022x-ns-revision-id\u0022] = revisionId.Value.ToString();\r\n\r\n\t\theaders[\u0022x-ns-client-type\u0022] = clientType;\r\n\r\n\t\t// \u2500\u2500 Send POST \u2500\u2500\r\n\t\tvar path = $\u0022/{NetworkStorage.ApiVersion}/manage/{Uri.EscapeDataString( NetworkStorage.ProjectId )}/revision-init\u0022;\r\n\t\tvar url = $\u0022{NetworkStorage.BaseUrl}{path}?apiKey={Uri.EscapeDataString( NetworkStorage.ApiKey ?? \u0022\u0022 )}\u0022;\r\n\t\tvar tag = \u0022revision-init\u0022;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif ( NetworkStorageLogConfig.LogRequests )\r\n\t\t\t\tLog.Info( $\u0022[NetworkStorage] {tag}: POST {NetworkStorage.ApiRoot}/manage/{NetworkStorage.ProjectId}/revision-init\u0022 );\r\n\r\n\t\t\tvar raw = await NetworkStorage.RequestStringAsync( url, \u0022POST\u0022, () =\u003E Http.CreateJsonContent( body ), headers );\r\n\r\n\t\t\tif ( NetworkStorageLogConfig.LogResponses )\r\n\t\t\t\tLog.Info( $\u0022[NetworkStorage] {tag} \u2192 {TruncateForLog( raw, 300 )}\u0022 );\r\n\r\n\t\t\tvar result = ParseInitResponse( raw, revisionId );\r\n\t\t\tLastInitResult = result;\r\n\r\n\t\t\tLog.Info( $\u0022[NetworkStorage] Game revision: {NetworkStoragePackageInfo.RuntimeRevisionId?.ToString() ?? \u0022unknown\u0022}, server latest: {result.CurrentRevision?.ToString() ?? \u0022unknown\u0022}, clientType={clientType}\u0022 );\r\n\r\n\t\t\tif ( result.IsOutdatedRevision )\r\n\t\t\t\tLog.Warning( $\u0022[NetworkStorage] Running outdated revision. {result.Message}\u0022 );\r\n\t\t\telse\r\n\t\t\t\tLog.Info( $\u0022[NetworkStorage] {tag}: ok={result.Ok} revision={result.PlayerRevision?.ToString() ?? \u0022unknown\u0022} message={result.Message ?? \u0022none\u0022}\u0022 );\r\n\t\t\treturn result;\r\n\t\t}\r\n\t\tcatch ( System.Net.Http.HttpRequestException httpEx )\r\n\t\t{\r\n\t\t\tvar status = httpEx.StatusCode.HasValue ? $\u0022{(int)httpEx.StatusCode.Value} {httpEx.StatusCode.Value}\u0022 : \u0022unknown\u0022;\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] {tag} FAILED \u2014 HTTP {status}\u0022 );\r\n\r\n\t\t\tvar fail = new RevisionInitResult\r\n\t\t\t{\r\n\t\t\t\tOk = false,\r\n\t\t\t\tIsOutdatedRevision = false,\r\n\t\t\t\tPlayerRevision = revisionId,\r\n\t\t\t\tCurrentRevision = null,\r\n\t\t\t\tMessage = $\u0022HTTP error: {status}\u0022\r\n\t\t\t};\r\n\t\t\tLastInitResult = fail;\r\n\t\t\treturn fail;\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] {tag} FAILED \u2014 {ex.Message}\u0022 );\r\n\r\n\t\t\tvar fail = new RevisionInitResult\r\n\t\t\t{\r\n\t\t\t\tOk = false,\r\n\t\t\t\tIsOutdatedRevision = false,\r\n\t\t\t\tPlayerRevision = revisionId,\r\n\t\t\t\tCurrentRevision = null,\r\n\t\t\t\tMessage = $\u0022Request failed: {ex.Message}\u0022\r\n\t\t\t};\r\n\t\t\tLastInitResult = fail;\r\n\t\t\treturn fail;\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Parse the backend revision-init response into a \u003Csee cref=\u0022RevisionInitResult\u0022/\u003E.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static RevisionInitResult ParseInitResponse( string raw, long? clientRevision )\r\n\t{\r\n\t\tif ( string.IsNullOrEmpty( raw ) )\r\n\t\t{\r\n\t\t\treturn new RevisionInitResult\r\n\t\t\t{\r\n\t\t\t\tOk = false,\r\n\t\t\t\tPlayerRevision = clientRevision,\r\n\t\t\t\tMessage = \u0022Server returned empty response\u0022\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tJsonElement json;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tjson = JsonSerializer.Deserialize\u003CJsonElement\u003E( raw );\r\n\t\t}\r\n\t\tcatch\r\n\t\t{\r\n\t\t\treturn new RevisionInitResult\r\n\t\t\t{\r\n\t\t\t\tOk = false,\r\n\t\t\t\tPlayerRevision = clientRevision,\r\n\t\t\t\tMessage = \u0022Server returned invalid JSON\u0022\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tvar ok = json.TryGetProperty( \u0022ok\u0022, out var okProp ) \u0026\u0026 okProp.ValueKind == JsonValueKind.True;\r\n\r\n\t\tlong? serverRevision = null;\r\n\t\tif ( json.TryGetProperty( \u0022currentRevisionId\u0022, out var crProp ) \u0026\u0026 crProp.TryGetInt64( out var crVal ) )\r\n\t\t\tserverRevision = crVal;\r\n\r\n\t\tvar isOutdated = false;\r\n\t\tif ( json.TryGetProperty( \u0022revisionOutdated\u0022, out var outdatedProp ) \u0026\u0026 outdatedProp.ValueKind == JsonValueKind.True )\r\n\t\t\tisOutdated = true;\r\n\t\telse if ( clientRevision.HasValue \u0026\u0026 serverRevision.HasValue \u0026\u0026 clientRevision.Value \u003C serverRevision.Value )\r\n\t\t\tisOutdated = true;\r\n\r\n\t\tstring message = null;\r\n\t\tif ( json.TryGetProperty( \u0022message\u0022, out var msgProp ) \u0026\u0026 msgProp.ValueKind == JsonValueKind.String )\r\n\t\t\tmessage = msgProp.GetString();\r\n\r\n\t\treturn new RevisionInitResult\r\n\t\t{\r\n\t\t\tOk = ok,\r\n\t\t\tIsOutdatedRevision = isOutdated,\r\n\t\t\tPlayerRevision = clientRevision,\r\n\t\t\tCurrentRevision = serverRevision,\r\n\t\t\tMessage = message\r\n\t\t};\r\n\t}\r\n\r\n\tprivate static string TruncateForLog( string s, int max = 120 )\r\n\t\t=\u003E s != null \u0026\u0026 s.Length \u003E max ? s[..max] \u002B \u0022...\u0022 : s ?? \u0022\u0022;\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Core/NetworkStorageRevisionOutdated.cs","FileName":"NetworkStorageRevisionOutdated.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Text.Json;\r\n\r\nnamespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// Why the revision was detected as outdated.\r\n/// \u003C/summary\u003E\r\npublic enum RevisionOutdatedReason\r\n{\r\n\t/// \u003Csummary\u003EDetected via the load-profile endpoint response.\u003C/summary\u003E\r\n\tLoadProfileDetected,\r\n\r\n\t/// \u003Csummary\u003ETriggered manually for testing (no backend required).\u003C/summary\u003E\r\n\tManualTest,\r\n\r\n\t/// \u003Csummary\u003ELobby metadata indicates a different revision.\u003C/summary\u003E\r\n\tLobbyMismatch,\r\n\r\n\t/// \u003Csummary\u003EGrace period expired, revision is now blocked.\u003C/summary\u003E\r\n\tGraceExpired\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// Data from the load-profile endpoint\u0027s revision block.\r\n/// Fires \u003Csee cref=\u0022NetworkStorage.OnRevisionOutdated\u0022/\u003E when\r\n/// the server reports the client\u0027s revision is outdated.\r\n/// \u003C/summary\u003E\r\npublic struct RevisionOutdatedData\r\n{\r\n\t/// \u003Csummary\u003ECreates a default instance.\u003C/summary\u003E\r\n\tpublic RevisionOutdatedData() { }\r\n\r\n\t/// \u003Csummary\u003EThe revision the client is running.\u003C/summary\u003E\r\n\tpublic long CurrentRevisionId { get; init; }\r\n\r\n\t/// \u003Csummary\u003EThe latest revision available on the server.\u003C/summary\u003E\r\n\tpublic long LatestRevisionId { get; init; }\r\n\r\n\t/// \u003Csummary\u003ETrue when the client revision is older than latest.\u003C/summary\u003E\r\n\tpublic bool RevisionOutdated { get; init; }\r\n\r\n\t/// \u003Csummary\u003ESeconds remaining in the grace period, or 0.\u003C/summary\u003E\r\n\tpublic int GraceSeconds { get; init; }\r\n\r\n\t/// \u003Csummary\u003EUnix timestamp when grace ends, or null.\u003C/summary\u003E\r\n\tpublic long? GraceEndsAtUnixSeconds { get; init; }\r\n\r\n\t/// \u003Csummary\u003EServer\u0027s current unix timestamp.\u003C/summary\u003E\r\n\tpublic long ServerUnixSeconds { get; init; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Source identifier describing where the detection came from.\r\n\t/// Typical values: \u0022load-profile\u0022, \u0022manual-test\u0022, \u0022lobby\u0022\r\n/// \u003C/summary\u003E\r\n\tpublic string Source { get; init; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Why this revision-outdated event was raised.\r\n\t/// \u003C/summary\u003E\r\n\tpublic RevisionOutdatedReason Reason { get; init; }\r\n\r\n\t// \u2500\u2500 Enforcement mode fields (from _revisionStatus API) \u2500\u2500\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The enforcement mode from the server. Defaults to ForceUpgrade for backward compatibility.\r\n\t/// \u003C/summary\u003E\r\n\tpublic RevisionEnforcementMode EnforcementMode { get; init; } = RevisionEnforcementMode.ForceUpgrade;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Custom message from the server to display to players.\r\n\t/// \u003C/summary\u003E\r\n\tpublic string Message { get; init; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// What action is currently required: \u0022warn\u0022, \u0022block_saves\u0022, \u0022block_all\u0022.\r\n\t/// \u003C/summary\u003E\r\n\tpublic string Action { get; init; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True when the grace period has expired (from server).\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool GraceExpired { get; init; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Minutes remaining in the grace period (from server), or null if no grace.\r\n\t/// \u003C/summary\u003E\r\n\tpublic int? GraceRemainingMinutes { get; init; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True if the server wants to show update options (Create/Join buttons).\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool ShowUpdateOptions { get; init; } = true;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True if popup should only show once per session.\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool ShowPopupOnce { get; init; } = true;\r\n\r\n\t/// \u003Csummary\u003ESeconds until grace expires (negative if already expired).\u003C/summary\u003E\r\n\tpublic int TimeRemaining\r\n\t{\r\n\t\tget\r\n\t\t{\r\n\t\t\tif ( !GraceEndsAtUnixSeconds.HasValue )\r\n\t\t\t\treturn 0;\r\n\t\t\tvar now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();\r\n\t\t\treturn (int)Math.Max( 0, GraceEndsAtUnixSeconds.Value - now );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETrue when the grace period has fully expired.\u003C/summary\u003E\r\n\tpublic bool IsGraceExpired\r\n\t{\r\n\t\tget\r\n\t\t{\r\n\t\t\tif ( !GraceEndsAtUnixSeconds.HasValue )\r\n\t\t\t\treturn false;\r\n\t\t\tvar now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();\r\n\t\t\treturn now \u003E= GraceEndsAtUnixSeconds.Value;\r\n\t\t}\r\n\t}\r\n\r\n\tinternal static RevisionOutdatedData? FromJson( JsonElement json )\r\n\t{\r\n\t\tif ( json.ValueKind != JsonValueKind.Object )\r\n\t\t\treturn null;\r\n\r\n\t\tif ( !json.TryGetProperty( \u0022revisionOutdated\u0022, out var outdated ) )\r\n\t\t\treturn null;\r\n\r\n\t\treturn new RevisionOutdatedData\r\n\t\t{\r\n\t\t\tCurrentRevisionId = json.TryGetProperty( \u0022currentRevisionId\u0022, out var cr ) \u0026\u0026 cr.ValueKind == JsonValueKind.Number ? cr.GetInt64() : 0,\r\n\t\t\tLatestRevisionId = json.TryGetProperty( \u0022latestRevisionId\u0022, out var lr ) \u0026\u0026 lr.ValueKind == JsonValueKind.Number ? lr.GetInt64() : 0,\r\n\t\t\tRevisionOutdated = outdated.ValueKind == JsonValueKind.True,\r\n\t\t\tGraceSeconds = json.TryGetProperty( \u0022graceSeconds\u0022, out var gs ) \u0026\u0026 gs.ValueKind == JsonValueKind.Number ? gs.GetInt32() : 0,\r\n\t\t\tGraceEndsAtUnixSeconds = json.TryGetProperty( \u0022graceEndsAtUnixSeconds\u0022, out var ge ) \u0026\u0026 ge.ValueKind == JsonValueKind.Number ? ge.GetInt64() : (long?)null,\r\n\t\t\tServerUnixSeconds = json.TryGetProperty( \u0022serverUnixSeconds\u0022, out var su ) \u0026\u0026 su.ValueKind == JsonValueKind.Number ? su.GetInt64() : DateTimeOffset.UtcNow.ToUnixTimeSeconds(),\r\n\t\t\tSource = \u0022load-profile\u0022,\r\n\t\t\tReason = RevisionOutdatedReason.LoadProfileDetected,\r\n\t\t};\r\n\t}\r\n\r\n\tinternal static RevisionOutdatedData? FromRevisionStatusJson( JsonElement json )\r\n\t{\r\n\t\tif ( json.ValueKind != JsonValueKind.Object )\r\n\t\t\treturn null;\r\n\r\n\t\tif ( !json.TryGetProperty( \u0022isOutdatedRevision\u0022, out var outdated ) )\r\n\t\t\treturn null;\r\n\r\n\t\tvar enforcementMode = RevisionEnforcementMode.ForceUpgrade;\r\n\t\tif ( json.TryGetProperty( \u0022enforcementMode\u0022, out var em ) \u0026\u0026 em.ValueKind == JsonValueKind.String \u0026\u0026 em.GetString() == \u0022allow_continue\u0022 )\r\n\t\t\tenforcementMode = RevisionEnforcementMode.AllowContinue;\r\n\r\n\t\tvar graceRemaining = json.TryGetProperty( \u0022graceRemainingMinutes\u0022, out var gr ) \u0026\u0026 gr.ValueKind == JsonValueKind.Number ? gr.GetInt32() : (int?)null;\r\n\t\tvar graceSeconds = graceRemaining.HasValue ? Math.Max( 0, graceRemaining.Value * 60 ) : 0;\r\n\t\tvar now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();\r\n\r\n\t\tvar showUpdateOptions = true;\r\n\t\tvar showPopupOnce = true;\r\n\t\tif ( json.TryGetProperty( \u0022policy\u0022, out var policy ) \u0026\u0026 policy.ValueKind == JsonValueKind.Object )\r\n\t\t{\r\n\t\t\tshowUpdateOptions = !policy.TryGetProperty( \u0022showUpdateOptions\u0022, out var suo ) || suo.ValueKind != JsonValueKind.False;\r\n\t\t\tshowPopupOnce = !policy.TryGetProperty( \u0022showPopupOnce\u0022, out var spo ) || spo.ValueKind != JsonValueKind.False;\r\n\t\t}\r\n\r\n\t\treturn new RevisionOutdatedData\r\n\t\t{\r\n\t\t\tCurrentRevisionId = json.TryGetProperty( \u0022playerRevision\u0022, out var pr ) \u0026\u0026 pr.ValueKind == JsonValueKind.Number ? pr.GetInt64() : 0,\r\n\t\t\tLatestRevisionId = json.TryGetProperty( \u0022currentRevision\u0022, out var cr ) \u0026\u0026 cr.ValueKind == JsonValueKind.Number ? cr.GetInt64() : 0,\r\n\t\t\tRevisionOutdated = outdated.ValueKind == JsonValueKind.True,\r\n\t\t\tGraceSeconds = graceSeconds,\r\n\t\t\tGraceEndsAtUnixSeconds = graceSeconds \u003E 0 ? now \u002B graceSeconds : null,\r\n\t\t\tServerUnixSeconds = now,\r\n\t\t\tSource = \u0022_revisionStatus\u0022,\r\n\t\t\tReason = json.TryGetProperty( \u0022graceExpired\u0022, out var ge ) \u0026\u0026 ge.ValueKind == JsonValueKind.True\r\n\t\t\t\t? RevisionOutdatedReason.GraceExpired\r\n\t\t\t\t: RevisionOutdatedReason.LoadProfileDetected,\r\n\t\t\tEnforcementMode = enforcementMode,\r\n\t\t\tMessage = json.TryGetProperty( \u0022message\u0022, out var message ) ? message.GetString() : null,\r\n\t\t\tAction = json.TryGetProperty( \u0022action\u0022, out var action ) ? action.GetString() : null,\r\n\t\t\tGraceExpired = json.TryGetProperty( \u0022graceExpired\u0022, out var expired ) \u0026\u0026 expired.ValueKind == JsonValueKind.True,\r\n\t\t\tGraceRemainingMinutes = graceRemaining,\r\n\t\t\tShowUpdateOptions = showUpdateOptions,\r\n\t\t\tShowPopupOnce = showPopupOnce\r\n\t\t};\r\n\t}\r\n}\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// Fired when the load-profile endpoint reports an outdated revision,\r\n\t/// or when \u003Csee cref=\u0022TestFireRevisionOutdated\u0022/\u003E is called.\r\n\t/// Subscribe to show custom in-game UI for revision warnings.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static event Action\u003CRevisionOutdatedData\u003E OnRevisionOutdated;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Called internally when a parsed server response contains a\r\n\t/// load-profile response contains a \u003Cc\u003Erevision\u003C/c\u003E block.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static void FireRevisionOutdated( RevisionOutdatedData data )\r\n\t{\r\n\t\tif ( data.RevisionOutdated )\r\n\t\t{\r\n\t\t\tNetworkStoragePackageInfo.UpdateFromRevisionBlock( data );\r\n\t\t\tInvokeSafely( OnRevisionOutdated, data, nameof( OnRevisionOutdated ) );\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Core/NetworkStorageRevisionUI.cs","FileName":"NetworkStorageRevisionUI.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Threading.Tasks;\r\nusing Sandbox.UI;\r\n\r\nnamespace Sandbox;\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// Open the outdated revision message panel.\r\n\t/// Requires a parent panel to attach to. If parent is null,\r\n\t/// a warning is logged and no UI is created, but the\r\n\t/// \u003Csee cref=\u0022OnRevisionOutdated\u0022/\u003E hook still fires.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void OpenRevisionOutdatedMessage( Panel parent = null )\r\n\t{\r\n\t\tNetworkStorageOutdatedUI.Open( parent );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Close the outdated revision message panel if it is open.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void CloseRevisionOutdatedMessage()\r\n\t{\r\n\t\tNetworkStorageOutdatedUI.Close();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Toggle the outdated revision message panel open/closed.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void ToggleRevisionOutdatedMessage( Panel parent = null )\r\n\t{\r\n\t\tif ( NetworkStorageOutdatedUI.IsOpen )\r\n\t\t{\r\n\t\t\tNetworkStorageOutdatedUI.Close();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tNetworkStorageOutdatedUI.Open( parent );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Refresh the lobby list to find lobbies running the latest revision.\r\n\t/// This is a stub \u2014 game code should override with actual lobby query logic\r\n\t/// by subscribing to \u003Csee cref=\u0022OnRefreshLobbyListRequested\u0022/\u003E.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static async Task RefreshRevisionLobbyListAsync()\r\n\t{\r\n\t\t// Fire the request \u2014 game code should handle this\r\n\t\tInvokeSafely( OnRefreshLobbyListRequested, nameof( OnRefreshLobbyListRequested ) );\r\n\r\n\t\t// Default implementation: log and return\r\n\t\tawait Task.CompletedTask;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Fired when \u003Csee cref=\u0022RefreshRevisionLobbyListAsync\u0022/\u003E is called.\r\n\t/// Game code should subscribe and perform the actual lobby refresh.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static event Action OnRefreshLobbyListRequested;\r\n\r\n\t// \u2500\u2500 Test / Debug APIs \u2500\u2500\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Simulate an outdated revision detection for testing.\r\n\t/// Creates a fake \u003Csee cref=\u0022RevisionOutdatedData\u0022/\u003E with\r\n\t/// \u003Cc\u003EReason = ManualTest\u003C/c\u003E and fires the full UI pipeline:\r\n\t/// - Updates \u003Csee cref=\u0022NetworkStoragePackageInfo\u0022/\u003E state\r\n\t/// - Fires \u003Csee cref=\u0022OnRevisionOutdated\u0022/\u003E for custom hooks\r\n\t/// - Opens the default message panel (if configured)\r\n\t///\r\n\t/// Does NOT require the backend to report a mismatch.\r\n\t/// Bypasses \u003Csee cref=\u0022RevisionSettings.ShowOnlyOnce\u0022/\u003E.\r\n\t/// Logs clearly that this is a test.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void TestShowRevisionOutdatedMessage( Panel parent = null )\r\n\t{\r\n\t\tLog.Warning( \u0022[NetworkStorage] TEST: Simulating outdated revision detection (no backend required)\u0022 );\r\n\r\n\t\tvar data = new RevisionOutdatedData\r\n\t\t{\r\n\t\t\tCurrentRevisionId = NetworkStoragePackageInfo.CurrentRevisionId ?? 1,\r\n\t\t\tLatestRevisionId = (NetworkStoragePackageInfo.CurrentRevisionId ?? 1) \u002B 1,\r\n\t\t\tRevisionOutdated = true,\r\n\t\t\tGraceSeconds = 120,\r\n\t\t\tGraceEndsAtUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds() \u002B 120,\r\n\t\t\tServerUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),\r\n\t\t\tSource = \u0022manual-test\u0022,\r\n\t\t\tReason = RevisionOutdatedReason.ManualTest,\r\n\t\t};\r\n\r\n\t\t// Update package info state\r\n\t\tNetworkStoragePackageInfo.UpdateFromRevisionBlock( data );\r\n\r\n\t\t// Fire the event for custom hooks\r\n\t\tInvokeSafely( OnRevisionOutdated, data, nameof( OnRevisionOutdated ) );\r\n\r\n\t\t// Open the default UI\r\n\t\tNetworkStorageOutdatedUI.ForceOpen( parent );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Fire the \u003Csee cref=\u0022OnRevisionOutdated\u0022/\u003E event with test data.\r\n\t/// Does NOT show the default UI \u2014 only fires the event so game code\r\n\t/// can test custom hooks without interference from the default panel.\r\n\t/// Logs clearly that this is a test.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void TestFireRevisionOutdated()\r\n\t{\r\n\t\tLog.Warning( \u0022[NetworkStorage] TEST: Firing OnRevisionOutdated event only (no UI)\u0022 );\r\n\r\n\t\tvar data = new RevisionOutdatedData\r\n\t\t{\r\n\t\t\tCurrentRevisionId = NetworkStoragePackageInfo.CurrentRevisionId ?? 1,\r\n\t\t\tLatestRevisionId = (NetworkStoragePackageInfo.CurrentRevisionId ?? 1) \u002B 1,\r\n\t\t\tRevisionOutdated = true,\r\n\t\t\tGraceSeconds = 120,\r\n\t\t\tGraceEndsAtUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds() \u002B 120,\r\n\t\t\tServerUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),\r\n\t\t\tSource = \u0022manual-test\u0022,\r\n\t\t\tReason = RevisionOutdatedReason.ManualTest,\r\n\t\t};\r\n\r\n\t\t// Fire the event only \u2014 no UI, no package info update\r\n\t\tInvokeSafely( OnRevisionOutdated, data, nameof( OnRevisionOutdated ) );\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Endpoints/NetworkStorageEncryptedEnvelope.cs","FileName":"NetworkStorageEncryptedEnvelope.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.Text.Json;\r\n\r\nnamespace Sandbox;\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\tprivate static Dictionary\u003Cstring, object\u003E CreateEncryptedEndpointEnvelope( string slug, Dictionary\u003Cstring, object\u003E payload, RuntimeAuthSession session )\r\n\t{\r\n\t\tvar envelope = new Dictionary\u003Cstring, object\u003E\r\n\t\t{\r\n\t\t\t[\u0022version\u0022] = \u00221\u0022,\r\n\t\t\t[\u0022algorithm\u0022] = \u0022aes-256-gcm\u002Bhmac-sha256\u0022,\r\n\t\t\t[\u0022projectId\u0022] = ProjectId,\r\n\t\t\t[\u0022nonce\u0022] = Base64UrlEncode( Encoding.UTF8.GetBytes( Guid.NewGuid().ToString( \u0022N\u0022 ) ) ),\r\n\t\t\t[\u0022publicKeyFingerprint\u0022] = PublicKeyFingerprint( ApiKey )\r\n\t\t};\r\n\t\tif ( session is not null )\r\n\t\t\tenvelope[\u0022sessionId\u0022] = session.Id;\r\n\t\telse\r\n\t\t\tenvelope[\u0022steamId\u0022] = Game.SteamId.ToString();\r\n\r\n\t\tvar iv = Guid.NewGuid().ToByteArray()[..12];\r\n\t\tenvelope[\u0022iv\u0022] = Base64UrlEncode( iv );\r\n\t\tvar key = Sha256( Encoding.UTF8.GetBytes( $\u0022sboxcool.network-storage.encrypted-request.v1\\0{ApiKey ?? \u0022\u0022}\\0{StableStringify( EnvelopeContext( envelope ) )}\u0022 ) );\r\n\t\tvar plaintext = Encoding.UTF8.GetBytes( JsonSerializer.Serialize( payload ) );\r\n\t\tvar aad = Encoding.UTF8.GetBytes( StableStringify( EnvelopeContext( envelope ) ) );\r\n\t\tvar (ciphertext, tag) = Aes256GcmEncrypt( key, iv, plaintext, aad );\r\n\r\n\t\tenvelope[\u0022tag\u0022] = Base64UrlEncode( tag );\r\n\t\tenvelope[\u0022encryptedPayload\u0022] = Base64UrlEncode( ciphertext );\r\n\t\tenvelope[\u0022signature\u0022] = ToHex( HmacSha256( Encoding.UTF8.GetBytes( ApiKey ?? \u0022\u0022 ), Encoding.UTF8.GetBytes( SignatureBinding( envelope ) ) ) );\r\n\t\treturn envelope;\r\n\t}\r\n\r\n\tprivate static Dictionary\u003Cstring, object\u003E EnvelopeContext( Dictionary\u003Cstring, object\u003E envelope )\r\n\t{\r\n\t\tvar identity = envelope.ContainsKey( \u0022sessionId\u0022 )\r\n\t\t\t? (\u0022session\u0022, Convert.ToString( envelope[\u0022sessionId\u0022] ) ?? \u0022\u0022)\r\n\t\t\t: (\u0022steam\u0022, Convert.ToString( envelope[\u0022steamId\u0022] ) ?? \u0022\u0022);\r\n\t\treturn new Dictionary\u003Cstring, object\u003E\r\n\t\t{\r\n\t\t\t[\u0022version\u0022] = Convert.ToString( envelope[\u0022version\u0022] ) ?? \u00221\u0022,\r\n\t\t\t[\u0022algorithm\u0022] = Convert.ToString( envelope[\u0022algorithm\u0022] ) ?? \u0022aes-256-gcm\u002Bhmac-sha256\u0022,\r\n\t\t\t[\u0022projectId\u0022] = Convert.ToString( envelope[\u0022projectId\u0022] ) ?? \u0022\u0022,\r\n\t\t\t[\u0022identityType\u0022] = identity.Item1,\r\n\t\t\t[\u0022identity\u0022] = identity.Item2,\r\n\t\t\t[\u0022nonce\u0022] = Convert.ToString( envelope[\u0022nonce\u0022] ) ?? \u0022\u0022,\r\n\t\t\t[\u0022publicKeyFingerprint\u0022] = Convert.ToString( envelope[\u0022publicKeyFingerprint\u0022] ) ?? \u0022\u0022\r\n\t\t};\r\n\t}\r\n\r\n\tprivate static string SignatureBinding( Dictionary\u003Cstring, object\u003E envelope )\r\n\t{\r\n\t\tvar binding = EnvelopeContext( envelope );\r\n\t\tbinding[\u0022iv\u0022] = Convert.ToString( envelope[\u0022iv\u0022] ) ?? \u0022\u0022;\r\n\t\tbinding[\u0022encryptedPayload\u0022] = Convert.ToString( envelope[\u0022encryptedPayload\u0022] ) ?? \u0022\u0022;\r\n\t\tbinding[\u0022tag\u0022] = Convert.ToString( envelope[\u0022tag\u0022] ) ?? \u0022\u0022;\r\n\t\treturn StableStringify( binding );\r\n\t}\r\n\r\n\tprivate static Dictionary\u003Cstring, object\u003E ObjectToDictionary( object input )\r\n\t{\r\n\t\tif ( input is Dictionary\u003Cstring, object\u003E existing )\r\n\t\t\treturn new Dictionary\u003Cstring, object\u003E( existing );\r\n\r\n\t\tvar json = JsonSerializer.Serialize( input ?? new { } );\r\n\t\treturn JsonSerializer.Deserialize\u003CDictionary\u003Cstring, object\u003E\u003E( json ) ?? new Dictionary\u003Cstring, object\u003E();\r\n\t}\r\n\r\n\tprivate static string PublicKeyFingerprint( string apiKey )\r\n\t\t=\u003E ToHex( Sha256( Encoding.UTF8.GetBytes( apiKey ?? \u0022\u0022 ) ) )[..32];\r\n\r\n\tprivate static string ReadServerMessage( JsonElement root, string fallback )\r\n\t{\r\n\t\tif ( root.TryGetProperty( \u0022message\u0022, out var message ) \u0026\u0026 message.ValueKind == JsonValueKind.String )\r\n\t\t\treturn message.GetString() ?? fallback;\r\n\t\tif ( root.TryGetProperty( \u0022error\u0022, out var error ) \u0026\u0026 error.ValueKind == JsonValueKind.Object \u0026\u0026\r\n\t\t\terror.TryGetProperty( \u0022message\u0022, out var nested ) \u0026\u0026 nested.ValueKind == JsonValueKind.String )\r\n\t\t\treturn nested.GetString() ?? fallback;\r\n\t\treturn fallback;\r\n\t}\r\n\r\n\tprivate static string StableStringify( object value )\r\n\t{\r\n\t\tvar sb = new StringBuilder();\r\n\t\tWriteStableJson( sb, value );\r\n\t\treturn sb.ToString();\r\n\t}\r\n\r\n\tprivate static void WriteStableJson( StringBuilder sb, object value )\r\n\t{\r\n\t\tif ( value is Dictionary\u003Cstring, object\u003E dict )\r\n\t\t{\r\n\t\t\tsb.Append( \u0027{\u0027 );\r\n\t\t\tvar keys = new List\u003Cstring\u003E( dict.Keys );\r\n\t\t\tkeys.Sort( StringComparer.Ordinal );\r\n\t\t\tfor ( var i = 0; i \u003C keys.Count; i\u002B\u002B )\r\n\t\t\t{\r\n\t\t\t\tif ( i \u003E 0 ) sb.Append( \u0027,\u0027 );\r\n\t\t\t\tWriteJsonString( sb, keys[i] );\r\n\t\t\t\tsb.Append( \u0027:\u0027 );\r\n\t\t\t\tWriteStableJson( sb, dict[keys[i]] );\r\n\t\t\t}\r\n\t\t\tsb.Append( \u0027}\u0027 );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif ( value is string stringValue )\r\n\t\t{\r\n\t\t\tWriteJsonString( sb, stringValue );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tsb.Append( JsonSerializer.Serialize( value ) );\r\n\t}\r\n\r\n\tprivate static void WriteJsonString( StringBuilder sb, string value )\r\n\t{\r\n\t\tsb.Append( \u0027\u0022\u0027 );\r\n\t\tforeach ( var ch in value ?? \u0022\u0022 )\r\n\t\t{\r\n\t\t\tswitch ( ch )\r\n\t\t\t{\r\n\t\t\t\tcase \u0027\u0022\u0027: sb.Append( \u0022\\\\\\\u0022\u0022 ); break;\r\n\t\t\t\tcase \u0027\\\\\u0027: sb.Append( \u0022\\\\\\\\\u0022 ); break;\r\n\t\t\t\tcase \u0027\\b\u0027: sb.Append( \u0022\\\\b\u0022 ); break;\r\n\t\t\t\tcase \u0027\\f\u0027: sb.Append( \u0022\\\\f\u0022 ); break;\r\n\t\t\t\tcase \u0027\\n\u0027: sb.Append( \u0022\\\\n\u0022 ); break;\r\n\t\t\t\tcase \u0027\\r\u0027: sb.Append( \u0022\\\\r\u0022 ); break;\r\n\t\t\t\tcase \u0027\\t\u0027: sb.Append( \u0022\\\\t\u0022 ); break;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tif ( ch \u003C \u0027 \u0027 )\r\n\t\t\t\t\t\tsb.Append( \u0022\\\\u\u0022 ).Append( ((int)ch).ToString( \u0022x4\u0022 ) );\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsb.Append( ch );\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tsb.Append( \u0027\u0022\u0027 );\r\n\t}\r\n\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Endpoints/NetworkStorageSigningKeyTrust.cs","FileName":"NetworkStorageSigningKeyTrust.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Text.Json;\r\n\r\nnamespace Sandbox;\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\t// Unpinned trust: the server signing key accepted for each API root, kept in the game\u0027s data folder so a restart\r\n\t// keeps it. It is local to this install; it is never synced or shipped.\r\n\tprivate const string SigningKeyTrustFile = \u0022network-storage-signing-key-trust.json\u0022;\r\n\r\n\t// Signing key accepted for an API root when no pin is configured.\r\n\tinternal sealed record TrustedSigningKey( string Fingerprint, byte[] Modulus, byte[] Exponent );\r\n\r\n\tprivate static Dictionary\u003Cstring, TrustedSigningKey\u003E _trustedSigningKeys;\r\n\r\n\tprivate static Dictionary\u003Cstring, TrustedSigningKey\u003E TrustedSigningKeys =\u003E _trustedSigningKeys ??= LoadSigningKeyTrust();\r\n\r\n\tprivate static Dictionary\u003Cstring, TrustedSigningKey\u003E LoadSigningKeyTrust()\r\n\t{\r\n\t\tvar keys = new Dictionary\u003Cstring, TrustedSigningKey\u003E();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif ( !FileSystem.Data.FileExists( SigningKeyTrustFile ) )\r\n\t\t\t\treturn keys;\r\n\r\n\t\t\tusing var doc = JsonDocument.Parse( FileSystem.Data.ReadAllText( SigningKeyTrustFile ) );\r\n\t\t\tforeach ( var entry in doc.RootElement.EnumerateObject() )\r\n\t\t\t{\r\n\t\t\t\t// A bad entry is skipped alone; the roots that are still valid keep their trust.\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tkeys[entry.Name] = ReadStoredSigningKey( entry.Value );\r\n\t\t\t\t}\r\n\t\t\t\tcatch ( Exception ex )\r\n\t\t\t\t{\r\n\t\t\t\t\tLog.Warning( $\u0022[NetworkStorage] ignoring unusable signing key trust entry for {entry.Name}: {ex.Message}\u0022 );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\t// An unreadable store is discarded, so the next config is trusted on first use again. The warning makes that visible.\r\n\t\t\tkeys.Clear();\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] ignoring unreadable signing key trust store {SigningKeyTrustFile}: {ex.Message}\u0022 );\r\n\t\t}\r\n\r\n\t\treturn keys;\r\n\t}\r\n\r\n\t// Reads one stored entry with the same size rule as TryReadSigningKey, so every key RememberTrustedSigningKey writes reads back.\r\n\tprivate static TrustedSigningKey ReadStoredSigningKey( JsonElement entry )\r\n\t{\r\n\t\tvar jwk = entry.GetProperty( \u0022publicKeyJwk\u0022 );\r\n\t\tvar modulus = NetworkStorageRsaKey.NormalizeSigningModulus( NetworkStorageSecuritySignature.Base64UrlDecode( jwk.GetProperty( \u0022n\u0022 ).GetString() ?? \u0022\u0022 ) );\r\n\t\tvar exponent = NetworkStorageSecuritySignature.Base64UrlDecode( jwk.GetProperty( \u0022e\u0022 ).GetString() ?? \u0022\u0022 );\r\n\t\tif ( modulus is null || exponent.Length == 0 )\r\n\t\t\tthrow new FormatException( \u0022not an RSA public key of at least 1024 bits\u0022 );\r\n\r\n\t\treturn new TrustedSigningKey( NetworkStorageRsaKey.Fingerprint( modulus, exponent ), modulus, exponent );\r\n\t}\r\n\r\n\t// Records the signing key trusted for an API root and writes the whole store. A failed write keeps the key for this session only.\r\n\tprivate static void RememberTrustedSigningKey( string apiRoot, TrustedSigningKey key )\r\n\t{\r\n\t\tTrustedSigningKeys[apiRoot] = key;\r\n\t\tSaveSigningKeyTrust();\r\n\t}\r\n\r\n\t// Forgets the signing key trusted for the current API root, so the next signed config is trusted on first use again.\r\n\t// Call it only after verifying the server identity: the next config is then accepted from whichever key it carries.\r\n\t// A game that must refuse a key change should ship a securityKeyFingerprint pin instead.\r\n\tpublic static void ResetSigningKeyTrust()\r\n\t{\r\n\t\tvar apiRoot = ApiRoot;\r\n\t\tif ( TrustedSigningKeys.Remove( apiRoot ) )\r\n\t\t\tSaveSigningKeyTrust();\r\n\r\n\t\tResetRuntimeSecurityConfig();\r\n\t\tLog.Warning( $\u0022[NetworkStorage] signing key trust for {apiRoot} was reset; the next security config is trusted on first use.\u0022 );\r\n\t}\r\n\r\n\tprivate static void SaveSigningKeyTrust()\r\n\t{\r\n\t\tvar store = new Dictionary\u003Cstring, object\u003E();\r\n\t\tforeach ( var (root, trusted) in TrustedSigningKeys )\r\n\t\t{\r\n\t\t\tstore[root] = new Dictionary\u003Cstring, object\u003E\r\n\t\t\t{\r\n\t\t\t\t[\u0022publicKeyJwk\u0022] = new Dictionary\u003Cstring, string\u003E\r\n\t\t\t\t{\r\n\t\t\t\t\t[\u0022kty\u0022] = \u0022RSA\u0022,\r\n\t\t\t\t\t[\u0022n\u0022] = Base64UrlEncode( trusted.Modulus ),\r\n\t\t\t\t\t[\u0022e\u0022] = Base64UrlEncode( trusted.Exponent )\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tFileSystem.Data.WriteAllText( SigningKeyTrustFile, JsonSerializer.Serialize( store ) );\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] could not save signing key trust to {SigningKeyTrustFile}: {ex.Message}. Trust changes last for this session only.\u0022 );\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Examples/SaveStateTrackerExample.cs","FileName":"SaveStateTrackerExample.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"// ============================================================\r\n// SaveStateTrackerExample.cs \u2014 Automatic save state management\r\n// Copy this into your game project\u0027s Code/ directory.\r\n// ============================================================\r\n\r\nusing System.Text.Json;\r\n\r\nnamespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// Example: Using SaveStateTracker for automatic state management.\r\n///\r\n/// SaveStateTracker wraps NetworkStorage.CallEndpoint() and tracks\r\n/// whether you\u0027re Idle, Saving, Saved, or in Error state. Use this\r\n/// to drive HUD indicators (spinner, checkmark, error icon).\r\n///\r\n/// It also provides CallAndApply() for the optimistic update pattern:\r\n/// apply locally \u2192 call server \u2192 revert if failed.\r\n/// \u003C/summary\u003E\r\npublic class SaveStateExample : Component\r\n{\r\n\tprivate readonly SaveStateTracker _tracker = new();\r\n\r\n\t// \u2500\u2500 Read these from your UI to show save status \u2500\u2500\r\n\tpublic SaveStateTracker.SaveState State =\u003E _tracker.State;\r\n\tpublic bool IsSaving =\u003E _tracker.IsBusy;\r\n\tpublic string LastError =\u003E _tracker.LastError;\r\n\tpublic TimeSince TimeSinceStateChange =\u003E _tracker.TimeSinceStateChange;\r\n\r\n\t// \u2500\u2500 Game state \u2500\u2500\r\n\t[Sync] public int Currency { get; set; }\r\n\tpublic Dictionary\u003Cstring, float\u003E Inventory { get; set; } = new();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Simple tracked call \u2014 just tracks Saving/Saved/Error state.\r\n\t/// \u003C/summary\u003E\r\n\tpublic async Task MineOre( string oreId, float kg )\r\n\t{\r\n\t\tvar result = await _tracker.Call( \u0022mine-ore\u0022, new { ore_id = oreId, kg } );\r\n\r\n\t\tif ( result.HasValue )\r\n\t\t{\r\n\t\t\t// Apply server response\r\n\t\t\tCurrency = JsonHelpers.GetInt( result.Value, \u0022currency\u0022, Currency );\r\n\t\t\tLog.Info( $\u0022Mined {kg}kg {oreId} \u2014 Currency: {Currency}\u0022 );\r\n\t\t}\r\n\t\t// If null, _tracker.State is already SaveState.Error\r\n\t\t// and _tracker.LastError has the message\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Full optimistic update pattern with auto-revert.\r\n\t/// CallAndApply does: applyOptimistic \u2192 call server \u2192 applyServer or revert.\r\n\t/// \u003C/summary\u003E\r\n\tpublic async Task SellOre( string oreId, float kg )\r\n\t{\r\n\t\tvar held = Inventory.GetValueOrDefault( oreId, 0f );\r\n\t\tvar actual = MathF.Min( kg, held );\r\n\t\tif ( actual \u003C= 0f ) return;\r\n\r\n\t\tvar prevCurrency = Currency;\r\n\t\tvar prevHeld = held;\r\n\r\n\t\tvar success = await _tracker.CallAndApply(\r\n\t\t\tslug: \u0022sell-ore\u0022,\r\n\t\t\tinput: new { ore_id = oreId, kg = actual },\r\n\r\n\t\t\t// 1. Optimistic local update (runs immediately)\r\n\t\t\tapplyOptimistic: () =\u003E\r\n\t\t\t{\r\n\t\t\t\tCurrency \u002B= (int)( actual * 10f ); // estimated value\r\n\t\t\t\tInventory[oreId] = held - actual;\r\n\t\t\t},\r\n\r\n\t\t\t// 2. Apply authoritative server response (runs on success)\r\n\t\t\tapplyServer: ( JsonElement data ) =\u003E\r\n\t\t\t{\r\n\t\t\t\tCurrency = JsonHelpers.GetInt( data, \u0022currency\u0022, Currency );\r\n\t\t\t\t// Server response is authoritative \u2014 override estimate\r\n\t\t\t},\r\n\r\n\t\t\t// 3. Revert (runs on failure)\r\n\t\t\trevert: () =\u003E\r\n\t\t\t{\r\n\t\t\t\tCurrency = prevCurrency;\r\n\t\t\t\tInventory[oreId] = prevHeld;\r\n\t\t\t\tLog.Warning( $\u0022Sell failed \u2014 reverted\u0022 );\r\n\t\t\t}\r\n\t\t);\r\n\r\n\t\tif ( success )\r\n\t\t\tLog.Info( $\u0022Sold {actual}kg {oreId} \u2014 Currency: {Currency}\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Example: Show save state in a Razor UI component.\r\n\t/// \u003C/summary\u003E\r\n\t// In your .razor file:\r\n\t//\r\n\t// @if ( SaveStateExample.Instance?.IsSaving == true )\r\n\t// {\r\n\t//     \u003Cdiv class=\u0022save-indicator saving\u0022\u003ESaving...\u003C/div\u003E\r\n\t// }\r\n\t// else if ( SaveStateExample.Instance?.State == SaveStateTracker.SaveState.Saved )\r\n\t// {\r\n\t//     \u003Cdiv class=\u0022save-indicator saved\u0022\u003ESaved\u003C/div\u003E\r\n\t// }\r\n\t// else if ( SaveStateExample.Instance?.State == SaveStateTracker.SaveState.Error )\r\n\t// {\r\n\t//     \u003Cdiv class=\u0022save-indicator error\u0022\u003E@SaveStateExample.Instance.LastError\u003C/div\u003E\r\n\t// }\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Storage/NetworkStorageOperation.cs","FileName":"NetworkStorageOperation.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System.Text.Json.Serialization;\r\n\r\nnamespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// A server-side document mutation for Network Storage collection records.\r\n/// Operations are applied by the backend against the current document, so callers\r\n/// can update counters and arrays without sending a full replacement document.\r\n/// \u003C/summary\u003E\r\npublic sealed class NetworkStorageOperation\r\n{\r\n\t[JsonPropertyName( \u0022op\u0022 )]\r\n\tpublic string Op { get; init; }\r\n\r\n\t[JsonPropertyName( \u0022path\u0022 )]\r\n\tpublic string Path { get; init; }\r\n\r\n\t[JsonPropertyName( \u0022value\u0022 )]\r\n\t[JsonIgnore( Condition = JsonIgnoreCondition.WhenWritingNull )]\r\n\tpublic object Value { get; init; }\r\n\r\n\t[JsonPropertyName( \u0022match\u0022 )]\r\n\t[JsonIgnore( Condition = JsonIgnoreCondition.WhenWritingNull )]\r\n\tpublic object Match { get; init; }\r\n\r\n\t[JsonPropertyName( \u0022source\u0022 )]\r\n\t[JsonIgnore( Condition = JsonIgnoreCondition.WhenWritingNull )]\r\n\tpublic string Source { get; init; }\r\n\r\n\t[JsonPropertyName( \u0022reason\u0022 )]\r\n\t[JsonIgnore( Condition = JsonIgnoreCondition.WhenWritingNull )]\r\n\tpublic string Reason { get; init; }\r\n\r\n\tpublic static NetworkStorageOperation Set( string path, object value, string source = null, string reason = null )\r\n\t\t=\u003E new() { Op = \u0022set\u0022, Path = path, Value = value, Source = source, Reason = reason };\r\n\r\n\tpublic static NetworkStorageOperation Increment( string path, double amount, string source = null, string reason = null )\r\n\t\t=\u003E new() { Op = \u0022inc\u0022, Path = path, Value = amount, Source = source, Reason = reason };\r\n\r\n\tpublic static NetworkStorageOperation Push( string path, object value )\r\n\t\t=\u003E new() { Op = \u0022push\u0022, Path = path, Value = value };\r\n\r\n\tpublic static NetworkStorageOperation Pull( string path, object match )\r\n\t\t=\u003E new() { Op = \u0022pull\u0022, Path = path, Match = match };\r\n\r\n\tpublic static NetworkStorageOperation Remove( string path, object value )\r\n\t\t=\u003E new() { Op = \u0022remove\u0022, Path = path, Value = value };\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"UnitTests/NetworkStorageHardeningTests.cs","FileName":"NetworkStorageHardeningTests.cs","PackageType":"library","CodeKind":"UnitTest","AssetVersionId":429205,"IsPrivate":false,"Code":"using System.Text.Json;\r\nusing System.Threading.Tasks;\r\nusing Sandbox;\r\n\r\n[TestClass]\r\npublic class NetworkStorageHardeningTests\r\n{\r\n\tprivate static JsonElement Parse( string json ) =\u003E JsonDocument.Parse( json ).RootElement.Clone();\r\n\r\n\t[TestMethod]\r\n\tpublic void ClassifyFailure_KeepsServerCodeAndMessage()\r\n\t{\r\n\t\tconst string body = \u0022{\\\u0022ok\\\u0022:false,\\\u0022error\\\u0022:\\\u0022ENDPOINT_ONLY\\\u0022,\\\u0022message\\\u0022:\\\u0022This collection can only be accessed through endpoints.\\\u0022}\u0022;\r\n\t\tNetworkStorage.ClassifyFailure( new RawReply( 403, body, null, null ), \u0022REQUEST_FAILED\u0022, out var code, out var message );\r\n\t\tAssert.AreEqual( \u0022ENDPOINT_ONLY\u0022, code );\r\n\t\tAssert.AreEqual( \u0022This collection can only be accessed through endpoints.\u0022, message );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void ClassifyFailure_NonJsonKeepsStatusInMessage()\r\n\t{\r\n\t\tNetworkStorage.ClassifyFailure( new RawReply( 413, \u0022\u0022, null, null ), \u0022HTTP_ERROR\u0022, out var code, out var message );\r\n\t\tAssert.AreEqual( \u0022HTTP_ERROR\u0022, code );\r\n\t\tAssert.AreEqual( \u0022HTTP 413 RequestEntityTooLarge\u0022, message );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void ClassifyFailure_RateLimitAndTransportFailures()\r\n\t{\r\n\t\tNetworkStorage.ClassifyFailure( new RawReply( 429, \u0022\u0022, null, null ), \u0022REQUEST_FAILED\u0022, out var code, out _ );\r\n\t\tAssert.AreEqual( \u0022RATE_LIMITED\u0022, code );\r\n\r\n\t\tNetworkStorage.ClassifyFailure( new RawReply( 0, null, \u0022Access to \u0027x\u0027 is not allowed.\u0022, null ), \u0022HTTP_ERROR\u0022, out code, out var message );\r\n\t\tAssert.AreEqual( \u0022REQUEST_FAILED\u0022, code );\r\n\t\tAssert.AreEqual( \u0022Access to \u0027x\u0027 is not allowed.\u0022, message );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void IsErrorCodeToken_AcceptsOnlyCodeShapedStrings()\r\n\t{\r\n\t\tAssert.IsTrue( NetworkStorage.IsErrorCodeToken( \u0022ENDPOINT_ONLY\u0022 ) );\r\n\t\tAssert.IsFalse( NetworkStorage.IsErrorCodeToken( \u0022just a string\u0022 ) );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void TryReadRawDocument_PassesDocumentsThroughVerbatim()\r\n\t{\r\n\t\t// Top-level arrays and envelope-shaped documents are returned as stored, never unwrapped.\r\n\t\tAssert.IsTrue( NetworkStorage.TryReadRawDocument( new RawReply( 200, \u0022[1,2]\u0022, null, null ), out var array, out _, out _ ) );\r\n\t\tAssert.AreEqual( JsonValueKind.Array, array.ValueKind );\r\n\r\n\t\tconst string envelope = \u0022{\\\u0022ok\\\u0022:true,\\\u0022body\\\u0022:{\\\u0022gold\\\u0022:5}}\u0022;\r\n\t\tAssert.IsTrue( NetworkStorage.TryReadRawDocument( new RawReply( 200, envelope, null, null ), out var document, out _, out _ ) );\r\n\t\tAssert.AreEqual( 5, document.GetProperty( \u0022body\u0022 ).GetProperty( \u0022gold\u0022 ).GetInt32() );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void TryReadRawDocument_ReportsStatusAndBodyFailures()\r\n\t{\r\n\t\tAssert.IsFalse( NetworkStorage.TryReadRawDocument( new RawReply( 404, \u0022\u0022, null, null ), out _, out var notFound, out _ ) );\r\n\t\tAssert.AreEqual( \u0022NOT_FOUND\u0022, notFound );\r\n\r\n\t\tAssert.IsFalse( NetworkStorage.TryReadRawDocument( new RawReply( 200, \u0022\u0022, null, null ), out _, out var empty, out _ ) );\r\n\t\tAssert.AreEqual( \u0022EMPTY_RESPONSE\u0022, empty );\r\n\r\n\t\tAssert.IsFalse( NetworkStorage.TryReadRawDocument( new RawReply( 200, \u0022{oops\u0022, null, null ), out _, out var invalid, out _ ) );\r\n\t\tAssert.AreEqual( \u0022INVALID_JSON\u0022, invalid );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void RateLimitDelaySeconds_ReadsFractionalBodySeconds()\r\n\t{\r\n\t\tAssert.AreEqual( 2.5, NetworkStorage.RateLimitDelaySeconds( null, \u0022{\\\u0022retryAfterSeconds\\\u0022:2.5}\u0022 ), 0.0 );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void IsRetrySafeSecurityRefusal_NeedsSecurityCodeAndRetrySafe()\r\n\t{\r\n\t\tAssert.IsTrue( NetworkStorage.IsRetrySafeSecurityRefusal( \u0022{\\\u0022ok\\\u0022:false,\\\u0022error\\\u0022:{\\\u0022code\\\u0022:\\\u0022SECURITY_CONFIG_STALE\\\u0022},\\\u0022retrySafe\\\u0022:true}\u0022 ) );\r\n\t\tAssert.IsFalse( NetworkStorage.IsRetrySafeSecurityRefusal( \u0022{\\\u0022ok\\\u0022:false,\\\u0022error\\\u0022:{\\\u0022code\\\u0022:\\\u0022SECURITY_CONFIG_STALE\\\u0022}}\u0022 ) );\r\n\t\tAssert.IsFalse( NetworkStorage.IsRetrySafeSecurityRefusal( \u0022{\\\u0022ok\\\u0022:false,\\\u0022error\\\u0022:{\\\u0022code\\\u0022:\\\u0022ENCRYPTED_REQUEST_STALE\\\u0022},\\\u0022retrySafe\\\u0022:true}\u0022 ) );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic void JsonHelpers_NeverThrowOnMismatchedValues()\r\n\t{\r\n\t\tvar doc = Parse( \u0022{\\\u0022f\\\u0022:2.5,\\\u0022big\\\u0022:99999999999,\\\u0022n\\\u0022:5,\\\u0022s\\\u0022:\\\u002212\\\u0022,\\\u0022b\\\u0022:true,\\\u0022o\\\u0022:{}}\u0022 );\r\n\t\tAssert.AreEqual( 7, JsonHelpers.GetInt( doc, \u0022f\u0022, 7 ) );\r\n\t\tAssert.AreEqual( 7, JsonHelpers.GetInt( doc, \u0022big\u0022, 7 ) );\r\n\t\tAssert.AreEqual( 12, JsonHelpers.GetInt( doc, \u0022s\u0022, 7 ) );\r\n\t\tAssert.AreEqual( \u00225\u0022, JsonHelpers.GetString( doc, \u0022n\u0022, \u0022fallback\u0022 ) );\r\n\t\tAssert.AreEqual( \u0022true\u0022, JsonHelpers.GetString( doc, \u0022b\u0022, \u0022fallback\u0022 ) );\r\n\t\tAssert.AreEqual( \u0022fallback\u0022, JsonHelpers.GetString( doc, \u0022o\u0022, \u0022fallback\u0022 ) );\r\n\t\tAssert.AreEqual( 7, JsonHelpers.GetInt( Parse( \u0022[1]\u0022 ), \u0022f\u0022, 7 ) );\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic async Task SendAsync_RefusesBadRequestsBeforeAnySend()\r\n\t{\r\n\t\tvar logErrors = NetworkStorageLogConfig.LogErrors;\r\n\t\tNetworkStorageLogConfig.LogErrors = false;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tAssert.AreEqual( \u0022INVALID_REQUEST\u0022, ( await NetworkStorage.SendAsync( null ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022USE_CALL_ENDPOINT\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/endpoints/x\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_PATH\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_PATH\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022storage\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_PATH\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/../storage\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_PATH\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/%2e%2e/storage\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022USE_CALL_ENDPOINT\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/%65ndpoints/x\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022UNSUPPORTED_PATH\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/%6Danage/x\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022UNSUPPORTED_PATH\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/manage/x\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_METHOD\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Method = \u0022TRACE\u0022, Path = \u0022/storage\u0022 } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_REQUEST\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/storage\u0022, Body = new { a = 1 } } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_REQUEST\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/storage\u0022, IdempotencyKey = new string( \u0027x\u0027, 129 ) } ) ).Code );\r\n\t\t\tAssert.AreEqual( \u0022INVALID_REQUEST\u0022, ( await NetworkStorage.SendAsync( new NetworkStorageRequest { Path = \u0022/storage\u0022, Query = new() { [\u0022apiKey\u0022] = \u0022x\u0022 } } ) ).Code );\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\tNetworkStorageLogConfig.LogErrors = logErrors;\r\n\t\t}\r\n\t}\r\n\r\n\t[TestMethod]\r\n\tpublic async Task CallEndpoint_InvalidReferenceIsReadableUnderItsCode()\r\n\t{\r\n\t\tAssert.IsNull( await NetworkStorage.CallEndpoint( \u0022\u0022 ) );\r\n\t\tAssert.IsTrue( NetworkStorage.TryGetLastEndpointError( \u0022INVALID_ENDPOINT\u0022, out var code, out _ ) );\r\n\t\tAssert.AreEqual( \u0022INVALID_ENDPOINT\u0022, code );\r\n\r\n\t\tconst string dashboardUrl = \u0022https://sboxcool.com/dashboard/projects/proj_x/endpoints/\u0022;\r\n\t\tAssert.IsNull( await NetworkStorage.CallEndpoint( dashboardUrl ) );\r\n\t\tAssert.IsTrue( NetworkStorage.TryGetLastEndpointError( dashboardUrl, out code, out _ ) );\r\n\t\tAssert.AreEqual( \u0022INVALID_ENDPOINT\u0022, code );\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"UnitTests/UnitTest.cs","FileName":"UnitTest.cs","PackageType":"library","CodeKind":"UnitTest","AssetVersionId":429205,"IsPrivate":false,"Code":"global using Microsoft.VisualStudio.TestTools.UnitTesting;\r\n\r\n[TestClass]\r\npublic class TestInit\r\n{\r\n\tpublic static Sandbox.TestAppSystem AppSystem;\r\n\r\n\t[AssemblyInitialize]\r\n\tpublic static void AssemblyInitialize( TestContext context )\r\n\t{\r\n\t\tAppSystem = new Sandbox.TestAppSystem();\r\n\t\tAppSystem.Init();\r\n\t}\r\n\r\n\t[AssemblyCleanup]\r\n\tpublic static void AssemblyCleanup()\r\n\t{\r\n\t\tAppSystem.Shutdown();\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Code/Core/NetworkStorageOutdatedUI.scss","FileName":"NetworkStorageOutdatedUI.scss","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"/* Outdated Revision Warning UI - Dual Mode Support */\r\n\r\n.ns-outdated-overlay {\r\n    position: absolute;\r\n    top: 0;\r\n    left: 0;\r\n    right: 0;\r\n    bottom: 0;\r\n    pointer-events: all;\r\n    background-color: rgba(0, 0, 0, 0.7);\r\n    z-index: 9999;\r\n    display: flex;\r\n    align-items: center;\r\n    justify-content: center;\r\n    backdrop-filter: blur(4px);\r\n}\r\n\r\n/* \u2500\u2500 Base Container \u2500\u2500 */\r\n.ns-outdated-container {\r\n    background-color: #1a1a2e;\r\n    border-radius: 12px;\r\n    padding: 24px 32px;\r\n    max-width: 420px;\r\n    min-width: 360px;\r\n    width: 90%;\r\n    display: flex;\r\n    flex-direction: column;\r\n    gap: 16px;\r\n}\r\n\r\n/* \u2500\u2500 Force Upgrade Mode: Warning styling \u2500\u2500 */\r\n.ns-outdated-container.force-upgrade {\r\n    border: 2px solid #f59e0b;\r\n    box-shadow: 0 8px 32px rgba(245, 158, 11, 0.25);\r\n}\r\n\r\n.ns-outdated-container.force-upgrade .ns-outdated-title {\r\n    color: #fbbf24;\r\n}\r\n\r\n.ns-outdated-container.force-upgrade .ns-outdated-countdown {\r\n    background-color: rgba(245, 158, 11, 0.15);\r\n    border: 1px solid rgba(245, 158, 11, 0.3);\r\n    color: #fbbf24;\r\n}\r\n\r\n.ns-outdated-container.force-upgrade .ns-outdated-countdown.expired {\r\n    background-color: rgba(239, 68, 68, 0.15);\r\n    border: 1px solid rgba(239, 68, 68, 0.3);\r\n    color: #fca5a5;\r\n}\r\n\r\n/* \u2500\u2500 Allow Continue Mode: Informational styling \u2500\u2500 */\r\n.ns-outdated-container.allow-continue {\r\n    border: 2px solid #3b82f6;\r\n    box-shadow: 0 8px 32px rgba(59, 130, 246, 0.25);\r\n}\r\n\r\n.ns-outdated-container.allow-continue .ns-outdated-title {\r\n    color: #60a5fa;\r\n}\r\n\r\n/* \u2500\u2500 Title \u2500\u2500 */\r\n.ns-outdated-title {\r\n    font-size: 18px;\r\n    font-weight: 700;\r\n    text-align: center;\r\n    text-transform: uppercase;\r\n    letter-spacing: 1px;\r\n}\r\n\r\n/* \u2500\u2500 Info Text \u2500\u2500 */\r\n.ns-outdated-info {\r\n    font-size: 14px;\r\n    color: #e2e8f0;\r\n    text-align: center;\r\n    line-height: 1.5;\r\n}\r\n\r\n/* \u2500\u2500 Countdown \u2500\u2500 */\r\n.ns-outdated-countdown {\r\n    font-size: 13px;\r\n    text-align: center;\r\n    padding: 12px 16px;\r\n    border-radius: 8px;\r\n    line-height: 1.4;\r\n    white-space: pre-line;\r\n}\r\n\r\n/* \u2500\u2500 Buttons Container \u2500\u2500 */\r\n.ns-outdated-buttons {\r\n    display: flex;\r\n    flex-direction: column;\r\n    gap: 10px;\r\n    margin-top: 4px;\r\n}\r\n\r\n/* \u2500\u2500 Continue Playing Button (Allow Continue primary) \u2500\u2500 */\r\n.ns-outdated-continue-btn {\r\n    background: linear-gradient(135deg, #3b82f6, #2563eb);\r\n    color: white;\r\n    border: none;\r\n    border-radius: 8px;\r\n    padding: 14px 24px;\r\n    font-size: 16px;\r\n    font-weight: 600;\r\n    cursor: pointer;\r\n    text-align: center;\r\n    transition: background 0.15s, transform 0.1s;\r\n}\r\n\r\n.ns-outdated-continue-btn:hover {\r\n    background: linear-gradient(135deg, #2563eb, #1d4ed8);\r\n    transform: translateY(-1px);\r\n}\r\n\r\n.ns-outdated-continue-btn:active {\r\n    transform: translateY(0);\r\n}\r\n\r\n/* \u2500\u2500 Divider (Or update to latest) \u2500\u2500 */\r\n.ns-outdated-divider {\r\n    display: flex;\r\n    align-items: center;\r\n    gap: 12px;\r\n    margin: 4px 0;\r\n}\r\n\r\n.ns-outdated-divider::before,\r\n.ns-outdated-divider::after {\r\n    content: \u0027\u0027;\r\n    flex: 1;\r\n    height: 1px;\r\n    background: rgba(148, 163, 184, 0.25);\r\n}\r\n\r\n.ns-outdated-divider Label {\r\n    color: #64748b;\r\n    font-size: 12px;\r\n    white-space: nowrap;\r\n}\r\n\r\n/* \u2500\u2500 Secondary Buttons (Create/Join) \u2500\u2500 */\r\n.ns-outdated-create-btn,\r\n.ns-outdated-join-btn {\r\n    background: rgba(148, 163, 184, 0.15);\r\n    color: #e2e8f0;\r\n    border: 1px solid rgba(148, 163, 184, 0.25);\r\n    border-radius: 8px;\r\n    padding: 12px 20px;\r\n    font-size: 14px;\r\n    font-weight: 600;\r\n    cursor: pointer;\r\n    text-align: center;\r\n    transition: background 0.15s, transform 0.1s;\r\n}\r\n\r\n.ns-outdated-create-btn:hover,\r\n.ns-outdated-join-btn:hover {\r\n    background: rgba(148, 163, 184, 0.25);\r\n    transform: translateY(-1px);\r\n}\r\n\r\n.ns-outdated-create-btn:active,\r\n.ns-outdated-join-btn:active {\r\n    transform: translateY(0);\r\n}\r\n\r\n/* \u2500\u2500 Dismiss Button (Force Upgrade only) \u2500\u2500 */\r\n.ns-outdated-dismiss-btn {\r\n    background-color: transparent;\r\n    color: #94a3b8;\r\n    border: none;\r\n    padding: 8px;\r\n    font-size: 13px;\r\n    cursor: pointer;\r\n    text-align: center;\r\n    transition: color 0.15s;\r\n}\r\n\r\n.ns-outdated-dismiss-btn:hover {\r\n    color: #e2e8f0;\r\n}\r\n\r\n/* \u2500\u2500 Hidden state \u2500\u2500 */\r\n.hidden {\r\n    display: none !important;\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Editor/MergeViewWindow.cs","FileName":"MergeViewWindow.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Sandbox;\r\nusing Editor;\r\n\r\n/// \u003Csummary\u003E\r\n/// Shows additive remote-only fields after a push or remote check so the user can\r\n/// review and pull those semantics into their local files.\r\n/// \u003C/summary\u003E\r\npublic class MergeViewWindow : PaintedWindow\r\n{\r\n\tpublic struct FieldDiff\r\n\t{\r\n\t\tpublic string Name;\r\n\t\tpublic string LocalValue;\r\n\t\tpublic string RemoteValue;\r\n\t\tpublic string Reason;\r\n\t\tpublic bool IsAdded;\r\n\t}\r\n\r\n\tprivate readonly string _resourceName;\r\n\tprivate readonly string _resourceType;\r\n\tprivate readonly List\u003CFieldDiff\u003E _addedFields;\r\n\tprivate readonly List\u003CFieldDiff\u003E _changedFields;\r\n\tprivate readonly Action _onMerge;\r\n\t// Optional inspect-only callback. When set, the window renders a\r\n\t// \u0022View Diff\u0022 button so reviewers can drill into the full local-vs-remote\r\n\t// content before deciding whether to pull. Useful when the additive-fields\r\n\t// summary keeps reappearing after pull/push/sync and the reviewer wants\r\n\t// to confirm what the classifier is actually seeing.\r\n\tprivate readonly Action _onViewDiff;\r\n\tprivate Vector2 _mousePos;\r\n\tprivate float _scroll;\r\n\tprivate Rect _cancelRect;\r\n\tprivate Rect _viewDiffRect;\r\n\tprivate Rect _mergeRect;\r\n\r\n\tprivate const float LineH = 16f;\r\n\tprivate const float FieldBlockH = 56f;\r\n\r\n\tprivate static readonly Dictionary\u003Cstring, string\u003E Explanations = new()\r\n\t{\r\n\t\t[\u0022rateLimits\u0022] = \u0022Rate limit configuration. Controls how many saves per time period are allowed.\u0022,\r\n\t\t[\u0022rateLimitAction\u0022] = \u0022Action when rate limit is exceeded. \u0027reject\u0027 returns an error, \u0027clamp\u0027 caps values.\u0022,\r\n\t\t[\u0022webhookOnRateLimit\u0022] = \u0022Discord webhook notification when a rate limit is triggered.\u0022,\r\n\t\t[\u0022version\u0022] = \u0022Collection API version. Set to v3 for all new collections.\u0022,\r\n\t\t[\u0022accessMode\u0022] = \u0022Controls whether the collection is publicly readable or endpoint-only.\u0022,\r\n\t\t[\u0022maxRecords\u0022] = \u0022Maximum number of records per player in this collection.\u0022,\r\n\t\t[\u0022allowRecordDelete\u0022] = \u0022Whether players can delete their own records.\u0022,\r\n\t\t[\u0022requireSaveVersion\u0022] = \u0022Version tracking for conflict detection on saves.\u0022,\r\n\t\t[\u0022collectionType\u0022] = \u0022Whether data is stored per-player or globally.\u0022,\r\n\t\t[\u0022input\u0022] = \u0022Input validation schema. Defines what parameters the endpoint accepts.\u0022,\r\n\t\t[\u0022description\u0022] = \u0022Human-readable description of this resource.\u0022,\r\n\t\t[\u0022notes\u0022] = \u0022Editor notes saved with this resource.\u0022,\r\n\t\t[\u0022builtIn\u0022] = \u0022System flag added by the remote project metadata.\u0022,\r\n\t\t[\u0022enabled\u0022] = \u0022Whether this resource is active.\u0022,\r\n\t};\r\n\r\n\tpublic MergeViewWindow( string resourceName, string resourceType,\r\n\t\tList\u003CFieldDiff\u003E addedFields, List\u003CFieldDiff\u003E changedFields,\r\n\t\tAction onMerge, Action onViewDiff = null )\r\n\t{\r\n\t\t_resourceName = resourceName;\r\n\t\t_resourceType = resourceType;\r\n\t\t_addedFields = addedFields;\r\n\t\t_changedFields = changedFields;\r\n\t\t_onMerge = onMerge;\r\n\t\t_onViewDiff = onViewDiff;\r\n\t\tTitle = $\u0022Pull Remote Semantics - {resourceName}\u0022;\r\n\r\n\t\tvar fieldCount = addedFields.Count \u002B changedFields.Count;\r\n\t\tSize = new Vector2( 540, Math.Min( 640, 260 \u002B fieldCount * FieldBlockH ) );\r\n\t\tMinimumSize = new Vector2( 420, 280 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Compare local and remote JSON to identify additive remote fields versus real content changes.\r\n\t/// Returns (addedFields, changedFields, isRemoteAdditiveOnly).\r\n\t/// \u003C/summary\u003E\r\n\tpublic static (List\u003CFieldDiff\u003E Added, List\u003CFieldDiff\u003E Changed, bool IsRemoteAdditiveOnly) AnalyzeDifferences(\r\n\t\tstring localJson, string remoteJson )\r\n\t{\r\n\t\tvar analysis = JsonDiffUtilities.Analyze( localJson, remoteJson );\r\n\r\n\t\treturn (\r\n\t\t\tanalysis.Added.Select( ToFieldDiff ).ToList(),\r\n\t\t\tanalysis.Changed.Select( ToFieldDiff ).ToList(),\r\n\t\t\tanalysis.IsRemoteAdditiveOnly\r\n\t\t);\r\n\t}\r\n\r\n\tprivate float ContentHeight =\u003E 180 \u002B ( _addedFields.Count \u002B _changedFields.Count ) * FieldBlockH \u002B 80;\r\n\tprivate float MaxScroll =\u003E Math.Max( 0, ContentHeight - Height \u002B 40 );\r\n\r\n\tprotected override void OnContentPaint()\r\n\t{\r\n\t\tbase.OnContentPaint();\r\n\r\n\t\tvar pad = 20f;\r\n\t\tvar w = Width - pad * 2;\r\n\t\tvar y = 20f - _scroll;\r\n\r\n\t\tPaint.SetDefaultFont( size: 13, weight: 700 );\r\n\t\tPaint.SetPen( Color.White );\r\n\t\tPaint.DrawText( new Rect( pad, y, w, 22 ), $\u0022Pull Remote Semantics - {_resourceName}\u0022, TextFlag.LeftCenter );\r\n\t\ty \u002B= 30;\r\n\r\n\t\tPaint.SetDefaultFont( size: 10 );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( 0.75f ) );\r\n\t\tDrawWrappedText( pad, ref y, w,\r\n\t\t\t$\u0022The remote version of this {_resourceType} contains additive fields only. \u0022 \u002B\r\n\t\t\t\u0022Your local content still matches what is stored remotely. Review the remote-only semantics below and pull them into your local files if you want to keep those additions locally.\u0022 );\r\n\t\ty \u002B= 12;\r\n\r\n\t\tPaint.SetDefaultFont( size: 9, weight: 600 );\r\n\t\tvar sx = pad;\r\n\t\tif ( _addedFields.Count \u003E 0 )\r\n\t\t{\r\n\t\t\tPaint.SetPen( Color.Green.WithAlpha( 0.8f ) );\r\n\t\t\tPaint.DrawText( new Rect( sx, y, 100, 14 ), $\u0022\u002B{_addedFields.Count} added\u0022, TextFlag.LeftCenter );\r\n\t\t\tsx \u002B= 80;\r\n\t\t}\r\n\t\tif ( _changedFields.Count \u003E 0 )\r\n\t\t{\r\n\t\t\tPaint.SetPen( Color.Yellow.WithAlpha( 0.8f ) );\r\n\t\t\tPaint.DrawText( new Rect( sx, y, 110, 14 ), $\u0022~{_changedFields.Count} changed\u0022, TextFlag.LeftCenter );\r\n\t\t}\r\n\t\ty \u002B= 22;\r\n\r\n\t\tPaint.SetPen( Color.White.WithAlpha( 0.1f ) );\r\n\t\tPaint.DrawLine( new Vector2( pad, y ), new Vector2( pad \u002B w, y ) );\r\n\t\ty \u002B= 8;\r\n\r\n\t\tif ( _addedFields.Count \u003E 0 )\r\n\t\t{\r\n\t\t\tPaint.SetDefaultFont( size: 9, weight: 700 );\r\n\t\t\tPaint.SetPen( Color.Green.WithAlpha( 0.7f ) );\r\n\t\t\tPaint.DrawText( new Rect( pad, y, w, 16 ), \u0022ADDED ON REMOTE\u0022, TextFlag.LeftCenter );\r\n\t\t\ty \u002B= 22;\r\n\r\n\t\t\tforeach ( var field in _addedFields )\r\n\t\t\t\tDrawFieldBlock( pad, w, ref y, field, Color.Green );\r\n\t\t}\r\n\r\n\t\tif ( _changedFields.Count \u003E 0 )\r\n\t\t{\r\n\t\t\tPaint.SetDefaultFont( size: 9, weight: 700 );\r\n\t\t\tPaint.SetPen( Color.Yellow.WithAlpha( 0.7f ) );\r\n\t\t\tPaint.DrawText( new Rect( pad, y, w, 16 ), \u0022DIFFERENT ON REMOTE\u0022, TextFlag.LeftCenter );\r\n\t\t\ty \u002B= 22;\r\n\r\n\t\t\tforeach ( var field in _changedFields )\r\n\t\t\t\tDrawFieldBlock( pad, w, ref y, field, Color.Yellow );\r\n\t\t}\r\n\r\n\t\ty \u002B= 16;\r\n\r\n\t\tPaint.SetPen( Color.White.WithAlpha( 0.1f ) );\r\n\t\tPaint.DrawLine( new Vector2( pad, y ), new Vector2( pad \u002B w, y ) );\r\n\t\ty \u002B= 12;\r\n\r\n\t\tvar btnH = 34f;\r\n\t\tvar gapW = 12f;\r\n\t\tvar showViewDiff = _onViewDiff != null;\r\n\r\n\t\t// Layout: Cancel | (View Diff)? | Pull Remote Semantics\r\n\t\t// View Diff is optional so the inspect-only callback stays opt-in for\r\n\t\t// callers that don\u0027t have YAML strings to hand over.\r\n\t\tvar cancelW = 80f;\r\n\t\tvar viewDiffW = showViewDiff ? 100f : 0f;\r\n\t\tvar viewDiffSlot = showViewDiff ? viewDiffW \u002B gapW : 0f;\r\n\t\tvar mergeW = w - cancelW - viewDiffSlot - gapW;\r\n\r\n\t\t_cancelRect = new Rect( pad, y, cancelW, btnH );\r\n\t\tvar cancelHovered = _cancelRect.IsInside( _mousePos );\r\n\t\tPaint.SetBrush( Color.White.WithAlpha( cancelHovered ? 0.1f : 0.04f ) );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( cancelHovered ? 0.3f : 0.15f ) );\r\n\t\tPaint.DrawRect( _cancelRect, 4 );\r\n\t\tPaint.SetDefaultFont( size: 11, weight: 600 );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( cancelHovered ? 0.9f : 0.6f ) );\r\n\t\tPaint.DrawText( _cancelRect, \u0022Cancel\u0022, TextFlag.Center );\r\n\r\n\t\tvar mergeX = pad \u002B cancelW \u002B gapW;\r\n\t\tif ( showViewDiff )\r\n\t\t{\r\n\t\t\t_viewDiffRect = new Rect( mergeX, y, viewDiffW, btnH );\r\n\t\t\tvar diffHovered = _viewDiffRect.IsInside( _mousePos );\r\n\t\t\tPaint.SetBrush( Color.Cyan.WithAlpha( diffHovered ? 0.18f : 0.06f ) );\r\n\t\t\tPaint.SetPen( Color.Cyan.WithAlpha( diffHovered ? 0.55f : 0.25f ) );\r\n\t\t\tPaint.DrawRect( _viewDiffRect, 4 );\r\n\t\t\tPaint.SetDefaultFont( size: 11, weight: 600 );\r\n\t\t\tPaint.SetPen( Color.Cyan.WithAlpha( diffHovered ? 1f : 0.75f ) );\r\n\t\t\tPaint.DrawText( _viewDiffRect, \u0022View Diff\u0022, TextFlag.Center );\r\n\t\t\tmergeX \u002B= viewDiffW \u002B gapW;\r\n\t\t}\r\n\r\n\t\t_mergeRect = new Rect( mergeX, y, mergeW, btnH );\r\n\t\tvar mergeHovered = _mergeRect.IsInside( _mousePos );\r\n\t\tPaint.SetBrush( Color.Green.WithAlpha( mergeHovered ? 0.25f : 0.12f ) );\r\n\t\tPaint.SetPen( Color.Green.WithAlpha( mergeHovered ? 0.6f : 0.3f ) );\r\n\t\tPaint.DrawRect( _mergeRect, 4 );\r\n\t\tPaint.SetDefaultFont( size: 11, weight: 700 );\r\n\t\tPaint.SetPen( Color.Green.WithAlpha( mergeHovered ? 1f : 0.85f ) );\r\n\t\tPaint.DrawText( _mergeRect, \u0022Pull Remote Semantics\u0022, TextFlag.Center );\r\n\t}\r\n\r\n\tprivate void DrawFieldBlock( float pad, float w, ref float y, FieldDiff field, Color accentColor )\r\n\t{\r\n\t\tPaint.SetBrush( accentColor.WithAlpha( 0.04f ) );\r\n\t\tPaint.SetPen( accentColor.WithAlpha( 0.12f ) );\r\n\t\tPaint.DrawRect( new Rect( pad, y, w, FieldBlockH - 6 ), 4 );\r\n\r\n\t\tPaint.SetDefaultFont( size: 10, weight: 600 );\r\n\t\tPaint.SetPen( accentColor.WithAlpha( 0.9f ) );\r\n\t\tvar prefix = field.IsAdded ? \u0022\u002B\u0022 : \u0022~\u0022;\r\n\t\tPaint.DrawText( new Rect( pad \u002B 10, y \u002B 4, w - 20, 16 ), $\u0022{prefix} {field.Name}\u0022, TextFlag.LeftCenter );\r\n\r\n\t\tPaint.SetDefaultFont( size: 9 );\r\n\t\tif ( field.IsAdded )\r\n\t\t{\r\n\t\t\tPaint.SetPen( Color.White.WithAlpha( 0.7f ) );\r\n\t\t\tPaint.DrawText( new Rect( pad \u002B 10, y \u002B 20, w - 20, 14 ), field.RemoteValue, TextFlag.LeftCenter );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tPaint.SetPen( Color.White.WithAlpha( 0.45f ) );\r\n\t\t\tvar valueText = $\u0022{field.LocalValue ?? \u0022null\u0022} -\u003E {field.RemoteValue}\u0022;\r\n\t\t\tPaint.DrawText( new Rect( pad \u002B 10, y \u002B 20, w - 20, 14 ), valueText, TextFlag.LeftCenter );\r\n\t\t}\r\n\r\n\t\tPaint.SetDefaultFont( size: 8 );\r\n\t\tPaint.SetPen( Color.White.WithAlpha( 0.4f ) );\r\n\t\tPaint.DrawText( new Rect( pad \u002B 10, y \u002B 34, w - 20, 12 ), field.Reason, TextFlag.LeftCenter );\r\n\r\n\t\ty \u002B= FieldBlockH;\r\n\t}\r\n\r\n\tprivate void DrawWrappedText( float x, ref float y, float maxW, string text )\r\n\t{\r\n\t\tvar words = text.Split( \u0027 \u0027 );\r\n\t\tvar line = \u0022\u0022;\r\n\t\tforeach ( var word in words )\r\n\t\t{\r\n\t\t\tvar test = string.IsNullOrEmpty( line ) ? word : $\u0022{line} {word}\u0022;\r\n\t\t\tif ( test.Length * 6.2f \u003E maxW \u0026\u0026 !string.IsNullOrEmpty( line ) )\r\n\t\t\t{\r\n\t\t\t\tPaint.DrawText( new Rect( x, y, maxW, 16 ), line, TextFlag.LeftCenter );\r\n\t\t\t\ty \u002B= 17;\r\n\t\t\t\tline = word;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tline = test;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif ( !string.IsNullOrEmpty( line ) )\r\n\t\t{\r\n\t\t\tPaint.DrawText( new Rect( x, y, maxW, 16 ), line, TextFlag.LeftCenter );\r\n\t\t\ty \u002B= 17;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void OnContentMousePress( MouseEvent e )\r\n\t{\r\n\t\tbase.OnContentMousePress(e);\r\n\r\n\t\tif ( _cancelRect.IsInside( e.LocalPosition ) )\r\n\t\t{\r\n\t\t\tClose();\r\n\t\t}\r\n\t\telse if ( _onViewDiff != null \u0026\u0026 _viewDiffRect.IsInside( e.LocalPosition ) )\r\n\t\t{\r\n\t\t\t// Inspect-only \u2014 keep the merge window open so the reviewer can\r\n\t\t\t// flip back and forth between the field summary and the full diff.\r\n\t\t\t_onViewDiff();\r\n\t\t}\r\n\t\telse if ( _mergeRect.IsInside( e.LocalPosition ) )\r\n\t\t{\r\n\t\t\tClose();\r\n\t\t\t_onMerge?.Invoke();\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void OnContentMouseMove( MouseEvent e )\r\n\t{\r\n\t\tbase.OnContentMouseMove(e);\r\n\t\t_mousePos = e.LocalPosition;\r\n\t\tUpdate();\r\n\t}\r\n\r\n\tprotected override void OnContentMouseWheel( WheelEvent e )\r\n\t{\r\n\t\tvar direction = e.Delta \u003E 0 ? -1 : 1;\r\n\t\t_scroll = Math.Clamp( _scroll \u002B direction * LineH * 3, 0, MaxScroll );\r\n\t\tUpdate();\r\n\t\te.Accept();\r\n\t}\r\n\r\n\tprotected override void OnContentKeyPress( KeyEvent e )\r\n\t{\r\n\t\tswitch ( e.Key )\r\n\t\t{\r\n\t\t\tcase KeyCode.Escape: Close(); break;\r\n\t\t\tcase KeyCode.Up: _scroll = Math.Max( 0, _scroll - LineH ); Update(); break;\r\n\t\t\tcase KeyCode.Down: _scroll = Math.Min( MaxScroll, _scroll \u002B LineH ); Update(); break;\r\n\t\t\tcase KeyCode.PageUp: _scroll = Math.Max( 0, _scroll - LineH * 10 ); Update(); break;\r\n\t\t\tcase KeyCode.PageDown: _scroll = Math.Min( MaxScroll, _scroll \u002B LineH * 10 ); Update(); break;\r\n\t\t\tdefault: base.OnContentKeyPress(e); break;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static FieldDiff ToFieldDiff( JsonDiffUtilities.FieldDifference diff )\r\n\t{\r\n\t\treturn new FieldDiff\r\n\t\t{\r\n\t\t\tName = diff.Path,\r\n\t\t\tLocalValue = diff.LocalValue,\r\n\t\t\tRemoteValue = diff.RemoteValue,\r\n\t\t\tReason = GetReason( diff.Path, diff.IsAdded ),\r\n\t\t\tIsAdded = diff.IsAdded\r\n\t\t};\r\n\t}\r\n\r\n\tprivate static string GetReason( string path, bool isAdded )\r\n\t{\r\n\t\tvar key = path?.Split( \u0027.\u0027 ).LastOrDefault() ?? \u0022\u0022;\r\n\t\tif ( Explanations.TryGetValue( key, out var explanation ) )\r\n\t\t\treturn explanation;\r\n\r\n\t\treturn isAdded\r\n\t\t\t? \u0022Present on remote but missing locally.\u0022\r\n\t\t\t: \u0022Value differs between local and remote.\u0022;\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Editor/SyncToolApi.cs","FileName":"SyncToolApi.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Concurrent;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nusing System.IO;\r\nusing System.Net.Http;\r\nusing System.Text;\r\nusing System.Text.Json;\r\nusing System.Threading.Tasks;\r\nusing Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// HTTP client for the Network Storage v3 management API.\r\n/// Used by the SyncTool editor window to push/pull game data.\r\n/// All requests are authenticated with the secret key from .env.\r\n/// \u003C/summary\u003E\r\npublic static class SyncToolApi\r\n{\r\n\t// Redirects are not followed: requests carry x-api-key, and a followed redirect could replay it to another host or to plain HTTP.\r\n\tprivate static readonly HttpClient _http = new( new HttpClientHandler { AllowAutoRedirect = false } ) { Timeout = TimeSpan.FromSeconds( 30 ) };\r\n\tprivate static readonly ConcurrentDictionary\u003Cstring, string\u003E _lastErrorMessagesByPath = new( StringComparer.OrdinalIgnoreCase );\r\n\tprivate static readonly ConcurrentDictionary\u003Cstring, ConcurrentDictionary\u003Cstring, string\u003E\u003E _lastResourceErrorMessagesByPath = new( StringComparer.OrdinalIgnoreCase );\r\n\tprivate static readonly Lazy\u003Cstring\u003E _libraryRevision = new( ReadLibraryRevision );\r\n\r\n\tprivate static void AddLibraryHeaders( HttpRequestMessage request )\r\n\t{\r\n\t\trequest.Headers.Add( \u0022x-ns-library-version\u0022, NetworkStorage.LibraryVersion );\r\n\t\trequest.Headers.Add( \u0022x-ns-client-type\u0022, \u0022editor\u0022 );\r\n\t\trequest.Headers.Add( \u0022X-Correlation-ID\u0022, Guid.NewGuid().ToString( \u0022N\u0022 ) );\r\n\t\tif ( request.Method == HttpMethod.Post || request.Method == HttpMethod.Put || request.Method == HttpMethod.Patch || request.Method == HttpMethod.Delete )\r\n\t\t\trequest.Headers.Add( \u0022Idempotency-Key\u0022, Guid.NewGuid().ToString( \u0022N\u0022 ) );\r\n\t\tif ( _libraryRevision.Value is { } libraryRevision )\r\n\t\t\trequest.Headers.Add( \u0022x-ns-library-revision\u0022, libraryRevision );\r\n\t}\r\n\r\n\tprivate static string ReadLibraryRevision()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar path = Path.Combine( SyncToolConfig.ProjectRoot, \u0022Libraries\u0022, \u0022sboxcool.network-storage\u0022, \u0022.version\u0022 );\r\n\t\t\tvar version = File.ReadAllText( path ).Trim();\r\n\t\t\tconst string prefix = \u00221.0.\u0022;\r\n\t\t\tif ( version.StartsWith( prefix, StringComparison.Ordinal )\r\n\t\t\t\t\u0026\u0026 long.TryParse( version[prefix.Length..], NumberStyles.None, CultureInfo.InvariantCulture, out var revision )\r\n\t\t\t\t\u0026\u0026 revision \u003E 0 )\r\n\t\t\t\treturn revision.ToString( CultureInfo.InvariantCulture );\r\n\t\t}\r\n\t\tcatch ( IOException ) { }\r\n\t\tcatch ( UnauthorizedAccessException ) { }\r\n\t\treturn null;\r\n\t}\r\n\tprivate static readonly JsonSerializerOptions _readOptions = new()\r\n\t{\r\n\t\tAllowTrailingCommas = true,\r\n\t\tPropertyNameCaseInsensitive = true,\r\n\t\tReadCommentHandling = JsonCommentHandling.Skip\r\n\t};\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Last error code from the server (e.g., \u0022KEY_UPGRADE_REQUIRED\u0022, \u0022FORBIDDEN\u0022).\r\n\t/// Reset on each request. Null if the last request succeeded or had no structured error.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static string LastErrorCode { get; private set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Last error message from the server.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static string LastErrorMessage { get; private set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Parsed body of the last refused request (non-success response). A refused push or preflight carries its\r\n\t/// per-resource diagnostics here. Reset on each request; null when the last request succeeded.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static JsonElement? LastErrorBody { get; private set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One-line summary of the most recent management request, e.g. \u0022PUT sync -\u003E 200 (42 ms)\u0022.\r\n\t/// Shown in the Sync Tool window so the user can see which request just went to which server.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static string LastRequestSummary { get; private set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Last error message for a specific management API path.\r\n\t/// Push All runs resource groups in parallel, so the global message can be\r\n\t/// cleared by a sibling request before the UI reads it.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static string GetLastErrorMessage( string path )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( path ) )\r\n\t\t\treturn null;\r\n\r\n\t\treturn _lastErrorMessagesByPath.TryGetValue( path, out var message ) ? message : null;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Last structured error message for a specific resource inside a failed batch request.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static string GetLastResourceErrorMessage( string path, string resourceId )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( path ) || string.IsNullOrWhiteSpace( resourceId ) )\r\n\t\t\treturn null;\r\n\r\n\t\treturn _lastResourceErrorMessagesByPath.TryGetValue( path, out var messages ) \u0026\u0026\r\n\t\t\tmessages.TryGetValue( resourceId, out var message )\r\n\t\t\t\t? message\r\n\t\t\t\t: null;\r\n\t}\r\n\r\n\tpublic static void ReportLocalError( string path, string message, Exception ex = null )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( path ) || string.IsNullOrWhiteSpace( message ) )\r\n\t\t\treturn;\r\n\r\n\t\tLastErrorCode = \u0022LOCAL_ERROR\u0022;\r\n\t\tLastErrorMessage = message;\r\n\t\t_lastErrorMessagesByPath[path] = message;\r\n\t\tif ( ex != null )\r\n\t\t\tLog.Warning( $\u0022[SyncTool] {path}: {message}\\n{ex}\u0022 );\r\n\t\telse\r\n\t\t\tLog.Warning( $\u0022[SyncTool] {path}: {message}\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Make an authenticated request to the management API.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static async Task\u003CJsonElement?\u003E Request( string method, string path, JsonElement? body = null, Dictionary\u003Cstring, string\u003E extraHeaders = null )\r\n\t{\r\n\t\tClearErrorStateForPath( path );\r\n\t\tLastErrorCode = null;\r\n\t\tLastErrorMessage = null;\r\n\t\tLastErrorBody = null;\r\n\r\n\t\tif ( !SyncToolConfig.IsValid )\r\n\t\t{\r\n\t\t\tLog.Warning( \u0022[SyncTool] Config not valid - load .env first\u0022 );\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif ( !SyncToolConfig.IsSecretSafeBaseUrl( SyncToolConfig.BaseUrl ) )\r\n\t\t{\r\n\t\t\tReportLocalError( path, SyncToolConfig.InsecureBaseUrlMessage );\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tvar url = $\u0022{SyncToolConfig.BaseUrl}/{SyncToolConfig.ApiVersion}/manage/{SyncToolConfig.ProjectId}/{path}\u0022;\r\n\r\n\t\tvar sk = SyncToolConfig.SecretKey ?? \u0022\u0022;\r\n\t\tvar pk = SyncToolConfig.PublicApiKey ?? \u0022\u0022;\r\n\t\tLog.Info( $\u0022[SyncTool] {method} {path}\u0022 );\r\n\t\tvar requestTimer = System.Diagnostics.Stopwatch.StartNew();\r\n\r\n\t\tvar request = new HttpRequestMessage( new HttpMethod( method ), url );\r\n\t\trequest.Headers.Add( \u0022x-api-key\u0022, sk );\r\n\t\trequest.Headers.Add( \u0022x-public-key\u0022, pk );\r\n\t\trequest.Headers.Add( \u0022User-Agent\u0022, \u0022SyncTool-sbox/2.0\u0022 );\r\n\t\tAddLibraryHeaders( request );\r\n\r\n\t\tif ( extraHeaders != null )\r\n\t\t{\r\n\t\t\tforeach ( var header in extraHeaders )\r\n\t\t\t\trequest.Headers.TryAddWithoutValidation( header.Key, header.Value );\r\n\t\t}\r\n\r\n\t\tif ( body.HasValue )\r\n\t\t{\r\n\t\t\tvar json = JsonSerializer.Serialize( body.Value );\r\n\t\t\trequest.Content = new StringContent( json, Encoding.UTF8, \u0022application/json\u0022 );\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar response = await _http.SendAsync( request );\r\n\t\t\tvar text = await response.Content.ReadAsStringAsync();\r\n\t\t\tLastRequestSummary = $\u0022{method} {path.Split( \u0027?\u0027 )[0]} -\u003E {(int)response.StatusCode} ({requestTimer.ElapsedMilliseconds} ms)\u0022;\r\n\r\n\t\t\tif ( !response.IsSuccessStatusCode )\r\n\t\t\t{\r\n\t\t\t\tLog.Warning( $\u0022[SyncTool] {method} {path}: HTTP {(int)response.StatusCode}\u0022 );\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tvar errJson = JsonSerializer.Deserialize\u003CJsonElement\u003E( text, _readOptions );\r\n\t\t\t\t\tif ( errJson.ValueKind == JsonValueKind.Object ) LastErrorBody = errJson;\r\n\t\t\t\t\tReadErrorFields( errJson, out var errCode, out var errMsg );\r\n\t\t\t\t\tLastErrorCode = errCode;\r\n\t\t\t\t\tLastErrorMessage = errMsg;\r\n\r\n\t\t\t\t\tCaptureStructuredErrors( path, errJson );\r\n\t\t\t\t\tLogStructuredErrors( path );\r\n\r\n\t\t\t\t\tif ( string.IsNullOrWhiteSpace( LastErrorMessage ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tLastErrorMessage = BuildStructuredErrorSummary( path, errJson )\r\n\t\t\t\t\t\t\t?? BuildStructuredErrorMessageFromBody( text, (int)response.StatusCode );\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif ( !string.IsNullOrWhiteSpace( LastErrorMessage ) )\r\n\t\t\t\t\t\t_lastErrorMessagesByPath[path] = LastErrorMessage;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\t_lastErrorMessagesByPath[path] = $\u0022HTTP {(int)response.StatusCode}\u0022;\r\n\r\n\t\t\t\t\t// Skip error window for 404/405 only for Sync endpoint fallback behavior.\r\n\t\t\t\t\t// Other 404/405 responses are meaningful and should remain visible.\r\n\t\t\t\t\tvar statusCode = (int)response.StatusCode;\r\n\t\t\t\t\tvar suppressWindow = string.Equals( path, \u0022sync\u0022, StringComparison.OrdinalIgnoreCase )\r\n\t\t\t\t\t\t\u0026\u0026 (statusCode == 404 || statusCode == 405);\r\n\t\t\t\t\tif ( ShouldShowErrorWindow() \u0026\u0026 !suppressWindow \u0026\u0026 (!string.IsNullOrEmpty( LastErrorCode ) || !string.IsNullOrEmpty( LastErrorMessage )) )\r\n\t\t\t\t\t\tEndpointErrorWindow.Show( path, errJson );\r\n\r\n\t\t\t\t\tif ( LastErrorCode == \u0022KEY_UPGRADE_REQUIRED\u0022 )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tLog.Warning( \u0022[SyncTool] Your secret key uses an old format. Generate a new one at sbox.cool.\u0022 );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if ( LastErrorCode == \u0022FORBIDDEN\u0022 )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tLog.Warning( $\u0022[SyncTool] Permission denied: {LastErrorMessage}\u0022 );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if ( LastErrorCode == \u0022COLLECTION_DELETE_WEBSITE_ONLY\u0022 )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tLog.Warning( \u0022[SyncTool] Collection definitions can only be deleted from the website dashboard after verification. Row/document deletion through the runtime API is still supported.\u0022 );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch\r\n\t\t\t\t{\r\n\t\t\t\t\tLastErrorMessage = BuildStructuredErrorMessageFromBody( text, (int)response.StatusCode );\r\n\t\t\t\t\t_lastErrorMessagesByPath[path] = LastErrorMessage;\r\n\t\t\t\t\tLog.Warning( $\u0022[SyncTool] -\u003E {LastErrorMessage}\u0022 );\r\n\t\t\t\t\tif ( ShouldShowErrorWindow() )\r\n\t\t\t\t\t\tMessageDialog.Show( $\u0022Sync Error: {path}\u0022, LastErrorMessage, text );\r\n\t\t\t\t}\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\r\n\t\t\tvar result = JsonSerializer.Deserialize\u003CJsonElement\u003E( text, _readOptions );\r\n\t\t\tLogStructuredWarnings( path, result );\r\n\r\n\t\t\t// Check for validation errors in successful HTTP responses (ok: false)\r\n\t\t\tif ( result.TryGetProperty( \u0022ok\u0022, out var okProp ) \u0026\u0026 okProp.ValueKind == JsonValueKind.False )\r\n\t\t\t{\r\n\t\t\t\tReadErrorFields( result, out var errCode, out var errMsg );\r\n\t\t\t\tLastErrorCode = errCode;\r\n\t\t\t\tLastErrorMessage = errMsg;\r\n\r\n\t\t\t\tCaptureStructuredErrors( path, result );\r\n\t\t\t\tLogStructuredErrors( path );\r\n\r\n\t\t\t\tif ( string.IsNullOrWhiteSpace( LastErrorMessage ) )\r\n\t\t\t\t\tLastErrorMessage = BuildStructuredErrorSummary( path, result );\r\n\r\n\t\t\t\t_lastErrorMessagesByPath[path] = LastErrorMessage ?? LastErrorCode ?? \u0022Validation failed\u0022;\r\n\r\n\t\t\t\t// Show error window when any structured validation failures are present.\r\n\t\t\t\tif ( ShouldShowErrorWindow() \u0026\u0026 ( !string.IsNullOrEmpty( LastErrorCode ) || !string.IsNullOrEmpty( LastErrorMessage ) ) )\r\n\t\t\t\t\tEndpointErrorWindow.Show( path, result );\r\n\t\t\t}\r\n\r\n\t\t\treturn result;\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tLastErrorMessage = ex.Message;\r\n\t\t\tLastRequestSummary = $\u0022{method} {path.Split( \u0027?\u0027 )[0]} -\u003E failed ({requestTimer.ElapsedMilliseconds} ms)\u0022;\r\n\t\t\t_lastErrorMessagesByPath[path] = ex.Message;\r\n\t\t\tLog.Warning( $\u0022[SyncTool] {method} {path}: {ex.Message}\u0022 );\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static Dictionary\u003Cstring, string\u003E NoCacheHeaders() =\u003E new()\r\n\t{\r\n\t\t[\u0022Cache-Control\u0022] = \u0022no-cache\u0022,\r\n\t\t[\u0022Pragma\u0022] = \u0022no-cache\u0022\r\n\t};\r\n\r\n\tprivate static string WithCacheBust( string path )\r\n\t{\r\n\t\tvar separator = path.Contains( \u0022?\u0022 ) ? \u0022\u0026\u0022 : \u0022?\u0022;\r\n\t\treturn $\u0022{path}{separator}_syncToolTs={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}\u0022;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EFetch current server endpoints (includes staged/next-revision endpoints).\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E GetEndpoints() =\u003E Request( \u0022GET\u0022, WithCacheBust( \u0022endpoints?includeStaged=true\u0022 ), null, NoCacheHeaders() );\r\n\r\n\t/// \u003Csummary\u003EFetch endpoints for a publish target.\u003C/summary\u003E\r\n\tpublic static async Task\u003CJsonElement?\u003E GetEndpointsForPublishTarget( string publishTarget )\r\n\t{\r\n\t\tvar result = await (string.Equals( publishTarget, \u0022next\u0022, StringComparison.OrdinalIgnoreCase )\r\n\t\t\t? Request( \u0022GET\u0022, WithCacheBust( \u0022endpoints?includeStaged=true\u0026revisionTarget=next\u0022 ), null, NoCacheHeaders() )\r\n\t\t\t: Request( \u0022GET\u0022, WithCacheBust( \u0022endpoints?revisionTarget=live\u0022 ), null, NoCacheHeaders() ));\r\n\t\treturn !result.HasValue || !string.Equals( publishTarget, \u0022next\u0022, StringComparison.OrdinalIgnoreCase )\r\n\t\t\t? result\r\n\t\t\t: FilterPayloadByRevisionTarget( result.Value, \u0022next\u0022, \u0022slug\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EPush endpoints to server.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushEndpoints( JsonElement data ) =\u003E Request( \u0022PUT\u0022, \u0022endpoints\u0022, data );\r\n\r\n\t/// \u003Csummary\u003EPush endpoints to server with publish-target support.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushEndpoints( JsonElement data, string publishTarget )\r\n\t{\r\n\t\tvar headers = publishTarget != \u0022live\u0022 ? new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = publishTarget } : null;\r\n\t\treturn Request( \u0022PUT\u0022, \u0022endpoints\u0022, data, headers );\r\n\t}\r\n \r\n\r\n\t/// \u003Csummary\u003EUpsert a single endpoint. Server handles merge.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PatchEndpoint( JsonElement data, string publishTarget = \u0022live\u0022 )\r\n\t{\r\n\t\tvar headers = publishTarget != \u0022live\u0022 ? new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = publishTarget } : null;\r\n\t\treturn Request( \u0022PATCH\u0022, \u0022endpoints\u0022, data, headers );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EUpsert a single collection. Server handles merge.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PatchCollection( JsonElement data, string publishTarget = \u0022live\u0022 )\r\n\t{\r\n\t\tvar headers = publishTarget != \u0022live\u0022 ? new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = publishTarget } : null;\r\n\t\treturn Request( \u0022PATCH\u0022, \u0022collections\u0022, data, headers );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EUpsert a single workflow. Server handles merge.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PatchWorkflow( JsonElement data )\r\n\t{\r\n\t\treturn Request( \u0022PATCH\u0022, \u0022workflows\u0022, data );\r\n\t}\r\n \t/// \u003Csummary\u003EPush endpoints to server asynchronously. Returns { jobId } immediately, processes in background.\u003C/summary\u003E\r\n \tpublic static Task\u003CJsonElement?\u003E PushEndpointsAsync( JsonElement data, string publishTarget = \u0022live\u0022 )\r\n \t{\r\n \t\tvar headers = new Dictionary\u003Cstring, string\u003E\r\n \t\t{\r\n \t\t\t[\u0022x-ns-publish-target\u0022] = publishTarget ?? \u0022live\u0022\r\n \t\t};\r\n \t\treturn Request( \u0022PUT\u0022, \u0022endpoints?async=true\u0022, data, headers );\r\n \t}\r\n \r\n \t/// \u003Csummary\u003EPoll async sync job status.\u003C/summary\u003E\r\n \tpublic static Task\u003CJsonElement?\u003E GetSyncJobStatus( string jobId )\r\n \t{\r\n \t\treturn Request( \u0022GET\u0022, $\u0022sync-jobs/{jobId}\u0022 );\r\n \t}\r\n\r\n\t/// \u003Csummary\u003EFetch current server collections (includes staged/next-revision collections).\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E GetCollections() =\u003E Request( \u0022GET\u0022, WithCacheBust( \u0022collections?includeStaged=true\u0022 ), null, NoCacheHeaders() );\r\n\r\n\t/// \u003Csummary\u003EFetch collections for a publish target.\u003C/summary\u003E\r\n\tpublic static async Task\u003CJsonElement?\u003E GetCollectionsForPublishTarget( string publishTarget )\r\n\t{\r\n\t\tvar result = await (string.Equals( publishTarget, \u0022next\u0022, StringComparison.OrdinalIgnoreCase )\r\n\t\t\t? Request( \u0022GET\u0022, WithCacheBust( \u0022collections?includeStaged=true\u0026revisionTarget=next\u0022 ), null, NoCacheHeaders() )\r\n\t\t\t: Request( \u0022GET\u0022, WithCacheBust( \u0022collections?revisionTarget=live\u0022 ), null, NoCacheHeaders() ));\r\n\t\treturn !result.HasValue || !string.Equals( publishTarget, \u0022next\u0022, StringComparison.OrdinalIgnoreCase )\r\n\t\t\t? result\r\n\t\t\t: FilterPayloadByRevisionTarget( result.Value, \u0022next\u0022, \u0022name\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EPush collection schemas to server.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushCollections( JsonElement data ) =\u003E Request( \u0022PUT\u0022, \u0022collections\u0022, data );\r\n\r\n\t/// \u003Csummary\u003EPush collection schemas to server with publish-target support.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushCollections( JsonElement data, string publishTarget )\r\n\t{\r\n\t\tvar headers = publishTarget != \u0022live\u0022 ? new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = publishTarget } : null;\r\n\t\treturn Request( \u0022PUT\u0022, \u0022collections\u0022, data, headers );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EFetch current server workflows.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E GetWorkflows() =\u003E Request( \u0022GET\u0022, WithCacheBust( \u0022workflows\u0022 ), null, NoCacheHeaders() );\r\n\r\n\t/// \u003Csummary\u003EPush workflows to server.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushWorkflows( JsonElement data ) =\u003E Request( \u0022PUT\u0022, \u0022workflows\u0022, data );\r\n\r\n\t/// \u003Csummary\u003EFetch read-only project settings used by the editor/runtime config.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E GetProjectSettings() =\u003E Request( \u0022GET\u0022, \u0022settings\u0022 );\r\n\r\n\t/// \u003Csummary\u003EFetch current server tests.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E GetTests() =\u003E Request( \u0022GET\u0022, \u0022tests\u0022 );\r\n\r\n\t/// \u003Csummary\u003EPush tests to server.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushTests( JsonElement data ) =\u003E Request( \u0022PUT\u0022, \u0022tests\u0022, data );\r\n\r\n \t/// \u003Csummary\u003EAsk backend compiler to canonicalize and safely upgrade one source file.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E UpgradeSource( JsonElement data ) =\u003E Request( \u0022POST\u0022, \u0022source-upgrade\u0022, data );\r\n\r\n\tprivate static Dictionary\u003Cstring, string\u003E PublishTargetHeaders( string publishTarget )\r\n\t{\r\n\t\tvar normalized = string.Equals( publishTarget, \u0022next\u0022, StringComparison.OrdinalIgnoreCase ) ? \u0022next\u0022 : \u0022live\u0022;\r\n\t\treturn new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = normalized };\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ERun a single test via dry-run.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E RunTest( JsonElement data, string publishTarget = \u0022live\u0022 ) =\u003E Request( \u0022POST\u0022, \u0022test-endpoint\u0022, data, PublishTargetHeaders( publishTarget ) );\r\n\r\n\t/// \u003Csummary\u003ERun all tests via dry-run.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E RunAllTests( JsonElement data, string publishTarget = \u0022live\u0022 ) =\u003E Request( \u0022POST\u0022, \u0022run-tests\u0022, data, PublishTargetHeaders( publishTarget ) );\r\n\r\n\t/// \u003Csummary\u003ESuggest tests for an endpoint.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E SuggestTests( JsonElement data ) =\u003E Request( \u0022POST\u0022, \u0022suggest-tests\u0022, data );\r\n\r\n\t/// \u003Csummary\u003EAuto-test one or all endpoints (no saved tests needed). Pass { slug } for one, {} for all.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E AutoTest( JsonElement data, string publishTarget = \u0022live\u0022 ) =\u003E Request( \u0022POST\u0022, \u0022auto-test\u0022, data, PublishTargetHeaders( publishTarget ) );\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Push all resources (endpoints, collections, workflows) in a single batch request.\r\n\t/// Server processes synchronously and returns combined results.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PushSync( JsonElement data, string publishTarget = \u0022live\u0022 )\r\n\t{\r\n\t\tvar headers = publishTarget != \u0022live\u0022 ? new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = publishTarget } : null;\r\n\t\treturn Request( \u0022PUT\u0022, \u0022sync\u0022, data, headers );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EValidate resources before pushing. Does not write server-side data.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E PreflightSync( JsonElement data, string publishTarget = \u0022live\u0022 )\r\n\t{\r\n\t\tvar headers = publishTarget != \u0022live\u0022 ? new Dictionary\u003Cstring, string\u003E { [\u0022x-ns-publish-target\u0022] = publishTarget } : null;\r\n\t\treturn Request( \u0022POST\u0022, \u0022sync/preflight\u0022, data, headers );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ESync package/revision info with backend.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E SyncPackageInfo( JsonElement data ) =\u003E Request( \u0022POST\u0022, \u0022package-sync\u0022, data );\r\n\r\n\t/// \u003Csummary\u003EFetch stored game-package/revision state from backend.\u003C/summary\u003E\r\n\tpublic static Task\u003CJsonElement?\u003E GetGamePackage() =\u003E Request( \u0022GET\u0022, \u0022game-package\u0022 );\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Validate credentials against the server.\r\n\t/// Sends secret key via x-api-key header and optionally public key via x-public-key header.\r\n\t/// Returns { ok, project, checks, permissions? }\r\n\t/// \u003C/summary\u003E\r\n\tpublic static async Task\u003CJsonElement?\u003E Validate( string publicKey = null )\r\n\t{\r\n\t\tLastErrorCode = null;\r\n\t\tLastErrorMessage = null;\r\n\r\n\t\tif ( !SyncToolConfig.IsValid )\r\n\t\t{\r\n\t\t\tLog.Warning( \u0022[SyncTool] Validate: config not valid\u0022 );\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif ( !SyncToolConfig.IsSecretSafeBaseUrl( SyncToolConfig.BaseUrl ) )\r\n\t\t{\r\n\t\t\tReportLocalError( \u0022validate\u0022, SyncToolConfig.InsecureBaseUrlMessage );\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tvar url = $\u0022{SyncToolConfig.BaseUrl}/{SyncToolConfig.ApiVersion}/manage/{SyncToolConfig.ProjectId}/validate\u0022;\r\n\t\tvar sk = SyncToolConfig.SecretKey ?? \u0022\u0022;\r\n\t\tvar pk = publicKey ?? \u0022\u0022;\r\n\r\n\t\tLog.Info( $\u0022[SyncTool] Validating credentials...\u0022 );\r\n\r\n\t\tvar request = new HttpRequestMessage( HttpMethod.Get, url );\r\n\t\trequest.Headers.Add( \u0022x-api-key\u0022, sk );\r\n\t\trequest.Headers.Add( \u0022User-Agent\u0022, \u0022SyncTool-sbox/2.0\u0022 );\r\n\t\tAddLibraryHeaders( request );\r\n\r\n\t\tif ( !string.IsNullOrEmpty( publicKey ) )\r\n\t\t\trequest.Headers.Add( \u0022x-public-key\u0022, publicKey );\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar response = await _http.SendAsync( request );\r\n\t\t\tvar text = await response.Content.ReadAsStringAsync();\r\n\r\n\t\t\tif ( !response.IsSuccessStatusCode )\r\n\t\t\t{\r\n\t\t\t\tvar status = (int)response.StatusCode;\r\n\t\t\t\tJsonElement errBody = default;\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\terrBody = JsonSerializer.Deserialize\u003CJsonElement\u003E( text, _readOptions );\r\n\t\t\t\t}\r\n\t\t\t\tcatch ( JsonException )\r\n\t\t\t\t{\r\n\t\t\t\t\t// Non-JSON error body: fall back to the HTTP status.\r\n\t\t\t\t}\r\n\r\n\t\t\t\tReadErrorFields( errBody, out var errCode, out var errMsg );\r\n\t\t\t\tLastErrorCode = errCode ?? $\u0022HTTP_{status}\u0022;\r\n\t\t\t\tLastErrorMessage = errMsg ?? $\u0022Server returned HTTP {status}\u0022;\r\n\t\t\t\tLog.Warning( $\u0022[SyncTool] Validate failed: HTTP {status} {LastErrorCode} - {LastErrorMessage}\u0022 );\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\r\n\t\t\tvar result = JsonSerializer.Deserialize\u003CJsonElement\u003E( text, _readOptions );\r\n\t\t\tif ( result.ValueKind != JsonValueKind.Object )\r\n\t\t\t{\r\n\t\t\t\tLastErrorMessage = \u0022Server returned an unexpected response.\u0022;\r\n\t\t\t\tLog.Warning( $\u0022[SyncTool] Validate: {LastErrorMessage}\u0022 );\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\r\n\t\t\tif ( result.TryGetProperty( \u0022error\u0022, out _ ) )\r\n\t\t\t{\r\n\t\t\t\tReadErrorFields( result, out var errCode, out var errMsg );\r\n\t\t\t\tLastErrorCode = errCode;\r\n\t\t\t\tLastErrorMessage = errMsg;\r\n\t\t\t\tLog.Warning( $\u0022[SyncTool] Validate error: {LastErrorCode} - {LastErrorMessage}\u0022 );\r\n\t\t\t}\r\n\r\n\t\t\treturn result;\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tLastErrorMessage = ex.Message;\r\n\t\t\tLog.Warning( $\u0022[SyncTool] Validate: {ex.Message}\u0022 );\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static bool ShouldShowErrorWindow()\r\n\t{\r\n\t\treturn SyncToolWindow.IsWindowOpen;\r\n\t}\r\n\r\n\tprivate static void ClearErrorStateForPath( string path )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( path ) )\r\n\t\t\treturn;\r\n\r\n\t\t_lastErrorMessagesByPath.TryRemove( path, out _ );\r\n\t\t_lastResourceErrorMessagesByPath.TryRemove( path, out _ );\r\n\r\n\t\tif ( string.Equals( path, \u0022sync\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t{\r\n\t\t\t_lastErrorMessagesByPath.TryRemove( \u0022endpoints\u0022, out _ );\r\n\t\t\t_lastErrorMessagesByPath.TryRemove( \u0022collections\u0022, out _ );\r\n\t\t\t_lastErrorMessagesByPath.TryRemove( \u0022workflows\u0022, out _ );\r\n\t\t\t_lastResourceErrorMessagesByPath.TryRemove( \u0022endpoints\u0022, out _ );\r\n\t\t\t_lastResourceErrorMessagesByPath.TryRemove( \u0022collections\u0022, out _ );\r\n\t\t\t_lastResourceErrorMessagesByPath.TryRemove( \u0022workflows\u0022, out _ );\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static string BuildStructuredErrorMessageFromBody( string body, int statusCode )\r\n\t{\r\n\t\tif ( statusCode == 404 || statusCode == 405 )\r\n\t\t\treturn $\u0022Backend route missing or unavailable (HTTP {statusCode}). The management API route may not be deployed on this backend.\u0022;\r\n\r\n\t\tvar detail = TruncateForLog( body, 500 );\r\n\t\treturn string.IsNullOrWhiteSpace( detail )\r\n\t\t\t? $\u0022HTTP {statusCode}\u0022\r\n\t\t\t: $\u0022HTTP {statusCode}: {detail}\u0022;\r\n\t}\r\n\r\n\tprivate static void CaptureStructuredErrors( string path, JsonElement payload )\r\n\t{\r\n\t\tvar entries = CollectStructuredResultEntries( path, payload );\r\n\t\tif ( entries.Count == 0 )\r\n\t\t\treturn;\r\n\r\n\t\tvar messagesByPath = new Dictionary\u003Cstring, ConcurrentDictionary\u003Cstring, string\u003E\u003E( StringComparer.OrdinalIgnoreCase );\r\n\t\tforeach ( var entry in entries )\r\n\t\t{\r\n\t\t\tvar item = entry.Item;\r\n\t\t\tif ( item.ValueKind != JsonValueKind.Object )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar itemOk = item.TryGetProperty( \u0022ok\u0022, out var ok ) \u0026\u0026 ok.ValueKind == JsonValueKind.True;\r\n\t\t\tif ( itemOk )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar resourceId = GetStringProperty( item, \u0022resourceId\u0022, \u0022slug\u0022, \u0022name\u0022, \u0022id\u0022 );\r\n\t\t\tif ( string.IsNullOrWhiteSpace( resourceId ) )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar detail = BuildStructuredErrorDetail( item );\r\n\t\t\tif ( string.IsNullOrWhiteSpace( detail ) )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif ( !messagesByPath.TryGetValue( entry.Path, out var messages ) )\r\n\t\t\t{\r\n\t\t\t\tmessages = new ConcurrentDictionary\u003Cstring, string\u003E( StringComparer.OrdinalIgnoreCase );\r\n\t\t\t\tmessagesByPath[entry.Path] = messages;\r\n\t\t\t}\r\n\t\t\tmessages[resourceId] = detail;\r\n\t\t}\r\n\r\n\t\tforeach ( var pair in messagesByPath )\r\n\t\t\t_lastResourceErrorMessagesByPath[pair.Key] = pair.Value;\r\n\t}\r\n\r\n\tprivate static void LogStructuredErrors( string path )\r\n\t{\r\n\t\tif ( !_lastResourceErrorMessagesByPath.TryGetValue( path, out var messages ) )\r\n\t\t\treturn;\r\n\r\n\t\tforeach ( var pair in messages )\r\n\t\t\tLog.Warning( $\u0022[SyncTool] {path}:{pair.Key} -\u003E {pair.Value}\u0022 );\r\n\t}\r\n\r\n\tprivate static string BuildStructuredErrorSummary( string path, JsonElement payload )\r\n\t{\r\n\t\tvar entries = CollectStructuredResultEntries( path, payload );\r\n\t\tforeach ( var entry in entries )\r\n\t\t{\r\n\t\t\tif ( entry.Item.TryGetProperty( \u0022ok\u0022, out var ok ) \u0026\u0026 ok.ValueKind == JsonValueKind.True )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar resourceId = GetStringProperty( entry.Item, \u0022resourceId\u0022, \u0022slug\u0022, \u0022name\u0022, \u0022id\u0022 );\r\n\t\t\tvar detail = BuildStructuredErrorDetail( entry.Item );\r\n\t\t\tif ( string.IsNullOrWhiteSpace( detail ) )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\treturn string.IsNullOrWhiteSpace( resourceId )\r\n\t\t\t\t? $\u0022{entry.Path}: {detail}\u0022\r\n\t\t\t\t: $\u0022{entry.Path}:{resourceId} {detail}\u0022;\r\n\t\t}\r\n\r\n\t\tvar message = GetStringProperty( payload, \u0022message\u0022, \u0022error\u0022 );\r\n\t\treturn string.IsNullOrWhiteSpace( message ) ? null : message;\r\n\t}\r\n\r\n\tprivate static JsonElement? FilterPayloadByRevisionTarget( JsonElement payload, string targetRevision, params string[] idKeys )\r\n\t{\r\n\t\tif ( !payload.TryGetProperty( \u0022data\u0022, out var data ) || data.ValueKind != JsonValueKind.Array )\r\n\t\t\treturn payload;\r\n\r\n\t\tvar targetItemsById = new Dictionary\u003Cstring, JsonElement\u003E( StringComparer.OrdinalIgnoreCase );\r\n\t\tvar hasTargetItems = false;\r\n\t\tforeach ( var item in data.EnumerateArray() )\r\n\t\t{\r\n\t\t\tif ( item.ValueKind != JsonValueKind.Object )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar resourceId = GetStringProperty( item, idKeys );\r\n\t\t\tif ( string.IsNullOrWhiteSpace( resourceId ) )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif ( item.TryGetProperty( \u0022revisionTarget\u0022, out var rev )\r\n\t\t\t\t\u0026\u0026 rev.ValueKind == JsonValueKind.String\r\n\t\t\t\t\u0026\u0026 string.Equals( rev.GetString(), targetRevision, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t{\r\n\t\t\t\ttargetItemsById[resourceId] = item;\r\n\t\t\t\thasTargetItems = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif ( !hasTargetItems )\r\n\t\t{\r\n\t\t\tvar deduped = new List\u003CJsonElement\u003E( data.GetArrayLength() );\r\n\t\t\tvar seenNoTarget = new HashSet\u003Cstring\u003E( StringComparer.OrdinalIgnoreCase );\r\n\t\t\tvar hasDuplicates = false;\r\n\t\t\tforeach ( var item in data.EnumerateArray() )\r\n\t\t\t{\r\n\t\t\t\tif ( item.ValueKind != JsonValueKind.Object )\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar resourceId = GetStringProperty( item, idKeys );\r\n\t\t\t\tif ( string.IsNullOrWhiteSpace( resourceId ) || !seenNoTarget.Add( resourceId ) )\r\n\t\t\t\t{\r\n\t\t\t\t\thasDuplicates = hasDuplicates || !string.IsNullOrWhiteSpace( resourceId );\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tdeduped.Add( item );\r\n\t\t\t}\r\n\r\n\t\t\tif ( hasDuplicates )\r\n\t\t\t{\r\n\t\t\t\tvar payloadObjNoTarget = JsonSerializer.Deserialize\u003CDictionary\u003Cstring, object\u003E\u003E( payload.GetRawText(), _readOptions );\r\n\t\t\t\tif ( payloadObjNoTarget != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tpayloadObjNoTarget[\u0022data\u0022] = deduped;\r\n\t\t\t\t\treturn JsonSerializer.Deserialize\u003CJsonElement\u003E( JsonSerializer.Serialize( payloadObjNoTarget ) );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar selected = new List\u003CJsonElement\u003E( data.GetArrayLength() );\r\n\t\tvar seen = new HashSet\u003Cstring\u003E( StringComparer.OrdinalIgnoreCase );\r\n\t\tforeach ( var item in data.EnumerateArray() )\r\n\t\t{\r\n\t\t\tif ( item.ValueKind != JsonValueKind.Object )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar resourceId = GetStringProperty( item, idKeys );\r\n\t\t\tif ( string.IsNullOrWhiteSpace( resourceId ) || seen.Contains( resourceId ) )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif ( targetItemsById.TryGetValue( resourceId, out var targetItem ) )\r\n\t\t\t\tselected.Add( targetItem );\r\n\t\t\telse\r\n\t\t\t\tselected.Add( item );\r\n\r\n\t\t\tseen.Add( resourceId );\r\n\t\t}\r\n\r\n\t\tvar payloadObj = JsonSerializer.Deserialize\u003CDictionary\u003Cstring, object\u003E\u003E( payload.GetRawText(), _readOptions );\r\n\t\tif ( payloadObj == null )\r\n\t\t\treturn payload;\r\n\r\n\t\tpayloadObj[\u0022data\u0022] = selected;\r\n\t\treturn JsonSerializer.Deserialize\u003CJsonElement\u003E( JsonSerializer.Serialize( payloadObj ) );\r\n\t}\r\n\r\n\tprivate static void LogStructuredWarnings( string path, JsonElement payload )\r\n\t{\r\n\t\tvar entries = CollectStructuredResultEntries( path, payload );\r\n\t\tforeach ( var entry in entries )\r\n\t\t{\r\n\t\t\tif ( entry.Item.ValueKind != JsonValueKind.Object )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif ( entry.Item.TryGetProperty( \u0022ok\u0022, out var ok ) \u0026\u0026 ok.ValueKind == JsonValueKind.False )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar resourceId = GetStringProperty( entry.Item, \u0022resourceId\u0022, \u0022slug\u0022, \u0022name\u0022, \u0022id\u0022 ) ?? \u0022(unknown)\u0022;\r\n\t\t\tif ( !entry.Item.TryGetProperty( \u0022diagnostics\u0022, out var diagnostics ) || diagnostics.ValueKind != JsonValueKind.Array )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tforeach ( var diagnostic in diagnostics.EnumerateArray() )\r\n\t\t\t{\r\n\t\t\t\tvar severity = GetStringProperty( diagnostic, \u0022severity\u0022 );\r\n\t\t\t\tif ( string.Equals( severity, \u0022error\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar formatted = FormatDiagnostic( diagnostic );\r\n\t\t\t\tif ( string.IsNullOrWhiteSpace( formatted ) )\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t// Only log warnings, skip info-level messages\r\n\t\t\t\tif ( !string.Equals( severity, \u0022info\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t\t\tLog.Warning( $\u0022[SyncTool] {entry.Path}:{resourceId} {severity} -\u003E {formatted}\u0022 );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static List\u003C(string Path, JsonElement Item)\u003E CollectStructuredResultEntries( string path, JsonElement payload )\r\n\t{\r\n\t\tvar entries = new List\u003C(string, JsonElement)\u003E();\r\n\t\tvar topLevel = GetStructuredResourceArray( payload );\r\n\t\tif ( topLevel.HasValue )\r\n\t\t{\r\n\t\t\tforeach ( var item in topLevel.Value.EnumerateArray() )\r\n\t\t\t\tentries.Add( ( path, item ) );\r\n\t\t}\r\n\r\n\t\tif ( !string.Equals( path, \u0022sync\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\treturn entries;\r\n\r\n\t\tforeach ( var section in new[] { \u0022endpoints\u0022, \u0022collections\u0022, \u0022workflows\u0022 } )\r\n\t\t{\r\n\t\t\tif ( !payload.TryGetProperty( section, out var sectionValue ) || sectionValue.ValueKind != JsonValueKind.Object )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif ( !sectionValue.TryGetProperty( \u0022results\u0022, out var sectionResults ) || sectionResults.ValueKind != JsonValueKind.Array )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tforeach ( var item in sectionResults.EnumerateArray() )\r\n\t\t\t\tentries.Add( ( section, item ) );\r\n\t\t}\r\n\r\n\t\treturn entries;\r\n\t}\r\n\r\n\tprivate static JsonElement? GetStructuredResourceArray( JsonElement payload )\r\n\t{\r\n\t\tforeach ( var key in new[] { \u0022results\u0022, \u0022resources\u0022, \u0022items\u0022 } )\r\n\t\t{\r\n\t\t\tif ( payload.TryGetProperty( key, out var value ) \u0026\u0026 value.ValueKind == JsonValueKind.Array )\r\n\t\t\t\treturn value;\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate static string BuildStructuredErrorDetail( JsonElement item )\r\n\t{\r\n\t\tvar parts = new List\u003Cstring\u003E();\r\n\t\tvar message = GetStringProperty( item, \u0022message\u0022 );\r\n\t\tvar error = GetStringProperty( item, \u0022error\u0022 );\r\n\t\tif ( !string.IsNullOrWhiteSpace( message ) \u0026\u0026\r\n\t\t\t!string.Equals( message, \u0022One or more endpoints failed validation.\u0022, StringComparison.OrdinalIgnoreCase ) \u0026\u0026\r\n\t\t\t!string.Equals( message, \u0022One or more collections failed validation.\u0022, StringComparison.OrdinalIgnoreCase ) \u0026\u0026\r\n\t\t\t!string.Equals( message, \u0022One or more workflows failed validation.\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t{\r\n\t\t\tparts.Add( message );\r\n\t\t}\r\n\t\telse if ( !string.IsNullOrWhiteSpace( error ) \u0026\u0026 !string.Equals( error, \u0022VALIDATION_FAILED\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t{\r\n\t\t\tparts.Add( error );\r\n\t\t}\r\n\r\n\t\tif ( item.TryGetProperty( \u0022diagnostics\u0022, out var diagnostics ) \u0026\u0026 diagnostics.ValueKind == JsonValueKind.Array )\r\n\t\t{\r\n\t\t\tforeach ( var diagnostic in diagnostics.EnumerateArray() )\r\n\t\t\t{\r\n\t\t\t\tvar formatted = FormatDiagnostic( diagnostic );\r\n\t\t\t\tif ( !string.IsNullOrWhiteSpace( formatted ) )\r\n\t\t\t\t\tparts.Add( formatted );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif ( parts.Count == 0 \u0026\u0026 item.TryGetProperty( \u0022errors\u0022, out var errors ) \u0026\u0026 errors.ValueKind == JsonValueKind.Array )\r\n\t\t{\r\n\t\t\tforeach ( var errorItem in errors.EnumerateArray() )\r\n\t\t\t{\r\n\t\t\t\tvar formatted = FormatDiagnostic( errorItem );\r\n\t\t\t\tif ( !string.IsNullOrWhiteSpace( formatted ) )\r\n\t\t\t\t\tparts.Add( formatted );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn parts.Count \u003E 0 ? string.Join( \u0022 | \u0022, parts ) : GetStringProperty( item, \u0022message\u0022, \u0022error\u0022 );\r\n\t}\r\n\r\n\tprivate static string FormatDiagnostic( JsonElement diagnostic )\r\n\t{\r\n\t\tif ( diagnostic.ValueKind == JsonValueKind.String )\r\n\t\t\treturn diagnostic.GetString();\r\n\r\n\t\tif ( diagnostic.ValueKind != JsonValueKind.Object )\r\n\t\t\treturn diagnostic.ToString();\r\n\r\n\t\tvar code = GetStringProperty( diagnostic, \u0022code\u0022, \u0022type\u0022, \u0022budgetCategory\u0022 );\r\n\t\tvar message = GetStringProperty( diagnostic, \u0022message\u0022, \u0022detail\u0022, \u0022reason\u0022, \u0022error\u0022 );\r\n\t\tvar head = !string.IsNullOrWhiteSpace( code ) \u0026\u0026 !string.IsNullOrWhiteSpace( message )\r\n\t\t\t? $\u0022{code}: {message}\u0022\r\n\t\t\t: !string.IsNullOrWhiteSpace( message ) ? message : code;\r\n\r\n\t\tvar context = new List\u003Cstring\u003E();\r\n\t\tvar sourcePath = GetStringProperty( diagnostic, \u0022sourcePath\u0022, \u0022path\u0022, \u0022file\u0022 );\r\n\t\tvar sourcePointer = GetStringProperty( diagnostic, \u0022sourcePointer\u0022 );\r\n\t\tif ( !string.IsNullOrWhiteSpace( sourcePath ) )\r\n\t\t{\r\n\t\t\tvar line = GetIntProperty( diagnostic, \u0022line\u0022, \u0022sourceLine\u0022 );\r\n\t\t\tvar column = GetIntProperty( diagnostic, \u0022column\u0022, \u0022sourceColumn\u0022 );\r\n\t\t\tvar location = sourcePath;\r\n\t\t\tif ( line.HasValue )\r\n\t\t\t\tlocation \u002B= column.HasValue ? $\u0022:{line}:{column}\u0022 : $\u0022:{line}\u0022;\r\n\t\t\tcontext.Add( location );\r\n\t\t}\r\n\t\telse if ( !string.IsNullOrWhiteSpace( sourcePointer ) )\r\n\t\t{\r\n\t\t\tcontext.Add( sourcePointer );\r\n\t\t}\r\n\r\n\t\tvar nodeId = GetStringProperty( diagnostic, \u0022nodeId\u0022, \u0022canonicalNode\u0022, \u0022stepId\u0022 );\r\n\t\tif ( !string.IsNullOrWhiteSpace( nodeId ) )\r\n\t\t\tcontext.Add( $\u0022node={nodeId}\u0022 );\r\n\r\n\t\tvar suggestion = GetStringProperty( diagnostic, \u0022suggestedFix\u0022, \u0022suggestion\u0022, \u0022fix\u0022 );\r\n\t\tif ( !string.IsNullOrWhiteSpace( suggestion ) )\r\n\t\t\tcontext.Add( $\u0022fix={suggestion}\u0022 );\r\n\r\n\t\tif ( string.IsNullOrWhiteSpace( head ) )\r\n\t\t\thead = diagnostic.ToString();\r\n\r\n\t\treturn context.Count \u003E 0 ? $\u0022{head} ({string.Join( \u0022, \u0022, context )})\u0022 : head;\r\n\t}\r\n\r\n\tprivate static string GetStringProperty( JsonElement element, params string[] keys )\r\n\t{\r\n\t\tif ( element.ValueKind != JsonValueKind.Object ) return null;\r\n\t\tforeach ( var key in keys )\r\n\t\t{\r\n\t\t\tif ( element.TryGetProperty( key, out var value ) \u0026\u0026 value.ValueKind == JsonValueKind.String )\r\n\t\t\t\treturn value.GetString();\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Reads the error code and message from a server error body. \u0060error\u0060 may be a string or an object with \u0060code\u0060;\r\n\t/// \u0060message\u0060 must be a string. Any other shape yields null instead of throwing.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static void ReadErrorFields( JsonElement body, out string code, out string message )\r\n\t{\r\n\t\tcode = null;\r\n\t\tmessage = null;\r\n\t\tif ( body.ValueKind != JsonValueKind.Object )\r\n\t\t\treturn;\r\n\r\n\t\tif ( body.TryGetProperty( \u0022error\u0022, out var error ) )\r\n\t\t{\r\n\t\t\tcode = error.ValueKind == JsonValueKind.String ? error.GetString()\r\n\t\t\t\t: error.ValueKind == JsonValueKind.Object ? GetStringProperty( error, \u0022code\u0022 )\r\n\t\t\t\t: null;\r\n\t\t\tmessage = GetStringProperty( error, \u0022message\u0022 );\r\n\t\t}\r\n\r\n\t\tmessage = GetStringProperty( body, \u0022message\u0022 ) ?? message;\r\n\t}\r\n\r\n\tprivate static int? GetIntProperty( JsonElement element, params string[] keys )\r\n\t{\r\n\t\tforeach ( var key in keys )\r\n\t\t{\r\n\t\t\tif ( !element.TryGetProperty( key, out var value ) || value.ValueKind != JsonValueKind.Number )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif ( value.TryGetInt32( out var number ) )\r\n\t\t\t\treturn number;\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate static string PrettyPrintJson( string text )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( text ) )\r\n\t\t\treturn text;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar parsed = JsonSerializer.Deserialize\u003CJsonElement\u003E( text, _readOptions );\r\n\t\t\treturn JsonSerializer.Serialize( parsed, new JsonSerializerOptions { WriteIndented = true } );\r\n\t\t}\r\n\t\tcatch\r\n\t\t{\r\n\t\t\treturn text;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static string TruncateForLog( string text, int maxLength )\r\n\t{\r\n\t\tif ( string.IsNullOrEmpty( text ) || text.Length \u003C= maxLength )\r\n\t\t\treturn text;\r\n\r\n\t\treturn $\u0022{text[..maxLength]}... (truncated, {text.Length} chars)\u0022;\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Auth/NetworkStorageDedicatedSecretLoaders.cs","FileName":"NetworkStorageDedicatedSecretLoaders.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Sandbox;\r\n\r\npublic static partial class NetworkStorage\r\n{\r\n\tprivate static readonly string[] UnsupportedDedicatedSecretLaunchKeys =\r\n\t{\r\n\t\t\u0022secret-key\u0022,\r\n\t\t\u0022secret_key\u0022,\r\n\t\t\u0022secretKey\u0022\r\n\t};\r\n\r\n\tprivate static void LoadDedicatedServerSecretKey()\r\n\t{\r\n\t\tif ( _dedicatedSecretLookupAttempted ) return;\r\n\t\t_dedicatedSecretLookupAttempted = true;\r\n\r\n\t\tif ( TryReadLaunchSecretKey( out _dedicatedServerSecretKey, out _dedicatedServerSecretKeySource ) )\r\n\t\t{\r\n\t\t\tLog.Info( $\u0022[NetworkStorage] Dedicated endpoint secret key loaded from {_dedicatedServerSecretKeySource} ({DescribeSecretKeyForLog( _dedicatedServerSecretKey )}).\u0022 );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t_dedicatedServerSecretKey = null;\r\n\t\t_dedicatedServerSecretKeySource = \u0022none\u0022;\r\n\t\t_dedicatedServerSecretKeyRejected = false;\r\n\t}\r\n\r\n\tprivate static bool TryReadLaunchSecretKey( out string secretKey, out string source )\r\n\t{\r\n\t\tsecretKey = null;\r\n\t\tsource = null;\r\n\r\n\t\tvar settings = LaunchArguments.GameSettings;\r\n\t\tif ( settings is null )\r\n\t\t{\r\n\t\t\t// Dedicated server launches can leave LaunchArguments.GameSettings empty;\r\n\t\t\t// the hidden ConVars below still receive \u002Bnetwork_storage_secret_key.\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tLogLaunchSettingsKeySummary( settings );\r\n\t\t\tWarnForUnsupportedSecretFlags( settings );\r\n\t\t\tif ( TryReadSecretFromSettings( settings, out secretKey, out source ) )\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\treturn TryReadSecretFromConsoleSystem( out secretKey, out source );\r\n\t}\r\n\r\n\tprivate static bool TryReadSecretFromSettings( IReadOnlyDictionary\u003Cstring, string\u003E settings, out string secretKey, out string source )\r\n\t{\r\n\t\tsecretKey = null;\r\n\t\tsource = null;\r\n\r\n\t\tforeach ( var supportedKey in DedicatedSecretLaunchKeys )\r\n\t\t{\r\n\t\t\tif ( TryGetLaunchSettingValue( settings, supportedKey, out var value, out var actualKey ) )\r\n\t\t\t\treturn TryAcceptDedicatedSecretValue( value, $\u0022launch flag \u002B{actualKey}\u0022, actualKey, out secretKey, out source );\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\tprivate static bool TryReadSecretFromConsoleSystem( out string secretKey, out string source )\r\n\t{\r\n\t\tsecretKey = null;\r\n\t\tsource = null;\r\n\r\n\t\tLog.Info( $\u0022[NetworkStorage] Probing ConsoleSystem for dedicated secret keys: {SupportedDedicatedSecretLaunchFlagsText}\u0022 );\r\n\t\tforeach ( var unsupported in UnsupportedDedicatedSecretLaunchKeys )\r\n\t\t\tWarnIfConsoleValuePresentForUnsupportedFlag( unsupported );\r\n\r\n\t\tforeach ( var supportedKey in DedicatedSecretLaunchKeys )\r\n\t\t{\r\n\t\t\tvar value = GetDedicatedSecretConVarValue( supportedKey );\r\n\t\t\tif ( string.IsNullOrWhiteSpace( value ) \u0026\u0026 !TryGetConsoleValue( supportedKey, out value ) )\r\n\t\t\t\tcontinue;\r\n\t\t\tif ( string.IsNullOrWhiteSpace( value ) )\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\treturn TryAcceptDedicatedSecretValue( value, $\u0022ConsoleSystem \u002B{supportedKey}\u0022, supportedKey, out secretKey, out source );\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\tprivate static string GetDedicatedSecretConVarValue( string key )\r\n\t{\r\n\t\treturn key switch\r\n\t\t{\r\n\t\t\t\u0022network-storage-secret-key\u0022 =\u003E NetworkStorageSecretKeyDashedConVar,\r\n\t\t\t\u0022network_storage_secret_key\u0022 =\u003E NetworkStorageSecretKeyConVar,\r\n\t\t\t\u0022sboxcool_secret_key\u0022 =\u003E SboxCoolSecretKeyConVar,\r\n\t\t\t\u0022networkStorageSecretKey\u0022 =\u003E NetworkStorageSecretKeyCamelConVar,\r\n\t\t\t\u0022sboxcoolSecretKey\u0022 =\u003E SboxCoolSecretKeyCamelConVar,\r\n\t\t\t\u0022nsSecretKey\u0022 =\u003E NsSecretKeyCamelConVar,\r\n\t\t\t\u0022ns_secret_key\u0022 =\u003E NsSecretKeyConVar,\r\n\t\t\t_ =\u003E null\r\n\t\t};\r\n\t}\r\n\r\n\tprivate static bool TryGetConsoleValue( string key, out string value )\r\n\t{\r\n\t\tvalue = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvalue = ConsoleSystem.GetValue( key, \u0022\u0022 );\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n\t\t\tif ( NetworkStorageLogConfig.LogConfig )\r\n\t\t\t\tLog.Warning( $\u0022[NetworkStorage] Could not read ConsoleSystem value \u002B{key}: {ex.Message}\u0022 );\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static void WarnIfConsoleValuePresentForUnsupportedFlag( string key )\r\n\t{\r\n\t\tif ( TryGetConsoleValue( key, out var value ) \u0026\u0026 !string.IsNullOrWhiteSpace( value ) )\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] Ignoring unsupported dedicated secret launch flag \u002B{key}. Supported flags: {SupportedDedicatedSecretLaunchFlagsText}\u0022 );\r\n\t}\r\n\r\n\tprivate static bool TryAcceptDedicatedSecretValue( string value, string sourceLabel, string key, out string secretKey, out string source )\r\n\t{\r\n\t\tsecretKey = null;\r\n\t\tsource = null;\r\n\t\tif ( string.IsNullOrWhiteSpace( value ) )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022[NetworkStorage] Dedicated secret launch flag \u002B{key} is present but empty.\u0022 );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tsecretKey = NormalizeSecretKey( value );\r\n\t\tsource = sourceLabel;\r\n\t\t_dedicatedServerSecretKeyRejected = false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tprivate static bool TryGetLaunchSettingValue( IReadOnlyDictionary\u003Cstring, string\u003E settings, string expectedKey, out string value, out string actualKey )\r\n\t{\r\n\t\tvalue = null;\r\n\t\tactualKey = null;\r\n\r\n\t\tforeach ( var pair in settings )\r\n\t\t{\r\n\t\t\tvar key = NormalizeLaunchSettingKey( pair.Key );\r\n\t\t\tif ( string.Equals( key, expectedKey, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t{\r\n\t\t\t\tvalue = pair.Value;\r\n\t\t\t\tactualKey = key;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\tprivate static void WarnForUnsupportedSecretFlags( IReadOnlyDictionary\u003Cstring, string\u003E settings )\r\n\t{\r\n\t\tforeach ( var pair in settings )\r\n\t\t\tWarnIfUnsupportedSecretFlag( NormalizeLaunchSettingKey( pair.Key ) );\r\n\t}\r\n\r\n\tprivate static void WarnIfUnsupportedSecretFlag( string key )\r\n\t{\r\n\t\tforeach ( var unsupported in UnsupportedDedicatedSecretLaunchKeys )\r\n\t\t{\r\n\t\t\tif ( string.Equals( key, unsupported, StringComparison.OrdinalIgnoreCase ) )\r\n\t\t\t{\r\n\t\t\t\tLog.Warning( $\u0022[NetworkStorage] Ignoring unsupported dedicated secret launch flag \u002B{key}. Supported flags: {SupportedDedicatedSecretLaunchFlagsText}\u0022 );\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static void LogLaunchSettingsKeySummary( IReadOnlyDictionary\u003Cstring, string\u003E settings )\r\n\t{\r\n\t\tvar sb = new StringBuilder();\r\n\t\tvar count = 0;\r\n\t\tforeach ( var pair in settings )\r\n\t\t\tAppendKeySummary( sb, NormalizeLaunchSettingKey( pair.Key ), ref count );\r\n\r\n\t\tvar keys = count == 0 ? \u0022(none)\u0022 : sb.ToString();\r\n\t\tLog.Info( $\u0022[NetworkStorage] Launch game setting keys visible to Network Storage: {keys}\u0022 );\r\n\t}\r\n\r\n\tprivate static void AppendKeySummary( StringBuilder sb, string key, ref int count )\r\n\t{\r\n\t\tif ( count \u003E 0 ) sb.Append( \u0022, \u0022 );\r\n\t\tif ( count \u003E= 24 )\r\n\t\t{\r\n\t\t\tsb.Append( \u0022...\u0022 );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tsb.Append( \u0027\u002B\u0027 ).Append( key );\r\n\t\tcount\u002B\u002B;\r\n\t}\r\n\r\n\tprivate static string NormalizeLaunchSettingKey( string key )\r\n\t{\r\n\t\tkey = (key ?? \u0022\u0022).Trim();\r\n\t\twhile ( key.StartsWith( \u0022\u002B\u0022, StringComparison.Ordinal ) || key.StartsWith( \u0022-\u0022, StringComparison.Ordinal ) )\r\n\t\t\tkey = key[1..];\r\n\t\treturn key;\r\n\t}\r\n\r\n\tprivate static string DescribeSecretKeyForLog( string secretKey )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( secretKey ) )\r\n\t\t\treturn \u0022empty\u0022;\r\n\r\n\t\tvar prefix = secretKey.StartsWith( \u0022sbox_sk_\u0022, StringComparison.Ordinal ) ? \u0022sbox_sk_\u0022 : \u0022non-standard-prefix\u0022;\r\n\t\treturn $\u0022{prefix}, length={secretKey.Length}\u0022;\r\n\t}\r\n}\r\n"},{"Ident":"sboxcool.network-storage","Path":"Code/Core/NetworkStorageBootstrap.cs","FileName":"NetworkStorageBootstrap.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":429205,"IsPrivate":false,"Code":"using System.Threading.Tasks;\r\n\r\nnamespace Sandbox;\r\n\r\n/// \u003Csummary\u003E\r\n/// Checks whether the editor assembly loaded after the Code assembly.\r\n/// Called from NetworkStorage.AutoConfigure() on first use.\r\n///\r\n/// Only warns in editor context when auto-configure fails \u2014 at runtime\r\n/// (published games) the client auto-configures from the credentials JSON\r\n/// and the editor is not available, so the warning is suppressed.\r\n/// \u003C/summary\u003E\r\ninternal static class NetworkStorageBootstrap\r\n{\r\n\tprivate static bool _checked;\r\n\r\n\tinternal static void CheckEditorOnce()\r\n\t{\r\n\t\tif ( _checked ) return;\r\n\t\t_checked = true;\r\n\r\n\t\t_ = CheckEditorAsync();\r\n\t}\r\n\r\n\tprivate static async Task CheckEditorAsync()\r\n\t{\r\n\t\tawait Task.Delay( 2000 );\r\n\r\n\t\t// If the client configured successfully (from credentials JSON or manual call),\r\n\t\t// no editor is needed \u2014 skip the warning. This is the normal path for published games.\r\n\t\tif ( NetworkStorage.IsConfigured )\r\n\t\t{\r\n\t\t\tNetworkStorageAnalyticsRuntime.EnsureCreated( \u0022bootstrap-check\u0022 );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// Only show editor hint when the editor assembly is expected but didn\u0027t load\r\n\t\tvar editorLoaded = TypeLibrary.GetType( \u0022SetupWindow\u0022 ) != null;\r\n\r\n\t\tif ( !editorLoaded \u0026\u0026 NetworkStorageLogConfig.LogConfig )\r\n\t\t{\r\n\t\t\tLog.Warning( \u0022\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u0022 );\r\n\t\t\tLog.Warning( \u0022[Network Storage] Not configured.\u0022 );\r\n\t\t\tLog.Warning( \u0022[Network Storage] If running in editor: restart to enable the Network Storage menu, then go to Editor \u2192 Network Storage \u2192 Setup\u0022 );\r\n\t\t\tLog.Warning( \u0022[Network Storage] If running published: ensure Assets/network-storage.credentials.json exists with projectId and publicKey\u0022 );\r\n\t\t\tLog.Warning( \u0022\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u0022 );\r\n\t\t}\r\n\t}\r\n}\r\n"}]}