Decompiled source of JgDev Valheim DevCommandsGuard v1.0.0

plugins/JgDev_Valheim_DevCommandsGuard.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("JgDev_Valheim_DevCommandsGuard")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("JgDev_Valheim_DevCommandsGuard")]
[assembly: AssemblyTitle("JgDev_Valheim_DevCommandsGuard")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace JgDev.Valheim.DevCommandsGuard
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "JgDev_Valheim_DevCommandsGuard";

		public const string PLUGIN_NAME = "JgDev_Valheim_DevCommandsGuard";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace DevCommandsGuard
{
	[BepInPlugin("info.jgdev.valheim.devcommandsguard", "JgDev_Valheim_DevCommandsGuard", "1.0.0")]
	public class DevCommandsGuardPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "info.jgdev.valheim.devcommandsguard";

		public const string PluginName = "JgDev_Valheim_DevCommandsGuard";

		public const string PluginVersion = "1.0.0";

		internal static DevCommandsGuardPlugin Instance = null;

		internal static ManualLogSource Log = null;

		internal static ConfigEntry<bool> RejectClientsWithDevCommands = null;

		internal static ConfigEntry<bool> RejectClientsWithoutPlugin = null;

		internal static ConfigEntry<string> CustomTagFormat = null;

		internal static ConfigEntry<string> CustomTagColor = null;

		internal const string RpcClientHandshake = "DCG_ClientHandshake";

		internal const string RpcServerSyncState = "DCG_ServerSyncState";

		internal const string RpcAdminCommand = "DCG_AdminCommand";

		internal const string RpcAdminCommandFeedback = "DCG_AdminCommandFeedback";

		internal const string ZdoDebugOrGodKey = "DCG_DebugOrGod";

		internal const string ZdoIsAdminKey = "DCG_IsAdmin";

		internal static readonly HashSet<string> HandshakedPeers = new HashSet<string>();

		internal static readonly HashSet<string> RejectedPeers = new HashSet<string>();

		internal static readonly Dictionary<string, (bool HasConsoleArg, bool HasDevCommands)> PeerClientStates = new Dictionary<string, (bool, bool)>();

		internal static bool LocalHasConsoleArg;

		internal static bool SynchronizedAdmin;

		internal static string ActiveTagFormat = "[DEV] {name}";

		internal static string ActiveTagColor = "red";

		private readonly Harmony _harmony = new Harmony("info.jgdev.valheim.devcommandsguard");

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			RejectClientsWithDevCommands = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "RejectClientsWithDevCommands", true, "If true, rejects connections from non-admin clients launched with -console or with devcommands enabled.");
			RejectClientsWithoutPlugin = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "RejectClientsWithoutPlugin", true, "If true, rejects connections from non-admin clients that do not have DevCommandsGuard installed.");
			CustomTagFormat = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "TagFormat", "[DEV] {name}", "Tag format for non-admin players with debugmode or god mode enabled. Use {name} as placeholder for the player's name.");
			CustomTagColor = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "TagColor", "red", "Color of the overhead tag name (e.g. red, #FF0000, yellow, orange) for non-admin players with debugmode or god mode enabled.");
			ActiveTagFormat = CustomTagFormat.Value;
			ActiveTagColor = CustomTagColor.Value;
			RejectClientsWithDevCommands.SettingChanged += delegate
			{
				EnforceActiveConnections();
			};
			RejectClientsWithoutPlugin.SettingChanged += delegate
			{
				EnforceActiveConnections();
			};
			CustomTagFormat.SettingChanged += delegate
			{
				BroadcastConfigToAllClients();
			};
			CustomTagColor.SettingChanged += delegate
			{
				BroadcastConfigToAllClients();
			};
			LocalHasConsoleArg = HasConsoleCommandLineArg();
			Log.LogInfo((object)string.Format("{0} {1} loaded. Local -console arg: {2}", "JgDev_Valheim_DevCommandsGuard", "1.0.0", LocalHasConsoleArg));
			_harmony.PatchAll();
		}

		private void OnDestroy()
		{
			_harmony.UnpatchSelf();
		}

		internal static bool HasConsoleCommandLineArg()
		{
			try
			{
				return Environment.GetCommandLineArgs().Any((string a) => string.Equals(a, "-console", StringComparison.OrdinalIgnoreCase));
			}
			catch
			{
				return false;
			}
		}

		internal static bool IsPeerAdmin(ZNet znet, ZNetPeer peer)
		{
			if ((Object)(object)znet == (Object)null || peer?.m_socket == null)
			{
				return false;
			}
			string hostName = peer.m_socket.GetHostName();
			if (znet.m_adminList != null)
			{
				return znet.ListContainsId(znet.m_adminList, hostName);
			}
			return false;
		}

		internal static bool IsLocalAdmin()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			if (ZNet.instance.IsServer())
			{
				return true;
			}
			return SynchronizedAdmin;
		}

		internal static void BroadcastConfigToAllClients()
		{
			ActiveTagFormat = CustomTagFormat.Value;
			ActiveTagColor = CustomTagColor.Value;
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady())
				{
					bool flag = IsPeerAdmin(ZNet.instance, peer);
					peer.m_rpc.Invoke("DCG_ServerSyncState", new object[3] { flag, CustomTagFormat.Value, CustomTagColor.Value });
				}
			}
		}

		internal static int EnforceActiveConnections()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return 0;
			}
			int num = 0;
			foreach (ZNetPeer item in ZNet.instance.GetPeers().ToList())
			{
				if (item?.m_socket == null || IsPeerAdmin(ZNet.instance, item))
				{
					continue;
				}
				string endPointString = item.m_socket.GetEndPointString();
				(bool, bool) value;
				if (RejectClientsWithoutPlugin.Value && !HandshakedPeers.Contains(endPointString))
				{
					Log.LogWarning((object)("Disconnecting active non-admin peer " + endPointString + ": missing JgDev_Valheim_DevCommandsGuard plugin."));
					ZRpc rpc = item.m_rpc;
					if (rpc != null)
					{
						rpc.Invoke("Error", new object[1] { 3 });
					}
					ZNet.instance.Disconnect(item);
					num++;
				}
				else if (RejectClientsWithDevCommands.Value && PeerClientStates.TryGetValue(endPointString, out value) && (value.Item1 || value.Item2))
				{
					Log.LogWarning((object)$"Disconnecting active non-admin peer {endPointString} (consoleArg={value.Item1}, devCommands={value.Item2}).");
					RejectedPeers.Add(endPointString);
					ZRpc rpc2 = item.m_rpc;
					if (rpc2 != null)
					{
						rpc2.Invoke("Error", new object[1] { 5 });
					}
					ZNet.instance.Disconnect(item);
					num++;
				}
			}
			return num;
		}

		internal static string ExecuteAdminConfigCommand(string[] args, out bool changed)
		{
			changed = false;
			if (args.Length == 0 || string.Equals(args[0], "status", StringComparison.OrdinalIgnoreCase))
			{
				return $"[DCG] RejectClientsWithDevCommands={RejectClientsWithDevCommands.Value}, " + $"RejectClientsWithoutPlugin={RejectClientsWithoutPlugin.Value}, " + "TagFormat=\"" + CustomTagFormat.Value + "\", TagColor=\"" + CustomTagColor.Value + "\"";
			}
			string text = args[0].ToLowerInvariant();
			switch (text)
			{
			case "reject":
			case "rejectdev":
			case "devcommands":
			{
				bool flag = ((args.Length > 1) ? ParseBool(args[1], !RejectClientsWithDevCommands.Value) : (!RejectClientsWithDevCommands.Value));
				RejectClientsWithDevCommands.Value = flag;
				((BaseUnityPlugin)Instance).Config.Save();
				int num2 = (flag ? EnforceActiveConnections() : 0);
				changed = true;
				return $"[DCG] RejectClientsWithDevCommands set to {flag} (saved, disconnected {num2} non-admin peer(s)).";
			}
			case "rejectmissing":
			case "requireplugin":
			{
				bool flag2 = ((args.Length > 1) ? ParseBool(args[1], !RejectClientsWithoutPlugin.Value) : (!RejectClientsWithoutPlugin.Value));
				RejectClientsWithoutPlugin.Value = flag2;
				((BaseUnityPlugin)Instance).Config.Save();
				int num3 = (flag2 ? EnforceActiveConnections() : 0);
				changed = true;
				return $"[DCG] RejectClientsWithoutPlugin set to {flag2} (saved, disconnected {num3} non-admin peer(s)).";
			}
			case "tagcolor":
			case "color":
				if (args.Length < 2)
				{
					return "Usage: dcg tagcolor <color>";
				}
				CustomTagColor.Value = args[1];
				((BaseUnityPlugin)Instance).Config.Save();
				BroadcastConfigToAllClients();
				changed = true;
				return "[DCG] TagColor set to \"" + CustomTagColor.Value + "\" (saved).";
			case "tag":
			case "tagformat":
				if (args.Length < 2)
				{
					return "Usage: dcg tagformat <format with {name}>";
				}
				CustomTagFormat.Value = string.Join(" ", args.Skip(1));
				((BaseUnityPlugin)Instance).Config.Save();
				BroadcastConfigToAllClients();
				changed = true;
				return "[DCG] TagFormat set to \"" + CustomTagFormat.Value + "\" (saved).";
			default:
			{
				if (ParseBoolExact(text, out var result))
				{
					RejectClientsWithDevCommands.Value = result;
					((BaseUnityPlugin)Instance).Config.Save();
					int num = (result ? EnforceActiveConnections() : 0);
					changed = true;
					return $"[DCG] RejectClientsWithDevCommands set to {result} (saved, disconnected {num} non-admin peer(s)).";
				}
				return "Usage: dcg [status | reject <on|off> | requireplugin <on|off> | tagcolor <color> | tagformat <format>]";
			}
			}
		}

		private static bool ParseBool(string input, bool fallback)
		{
			if (!ParseBoolExact(input, out var result))
			{
				return fallback;
			}
			return result;
		}

		private static bool ParseBoolExact(string input, out bool result)
		{
			switch (input.ToLowerInvariant())
			{
			case "1":
			case "on":
			case "enabled":
			case "yes":
			case "true":
			case "enable":
				result = true;
				return true;
			case "0":
			case "no":
			case "disable":
			case "off":
			case "false":
			case "disabled":
				result = false;
				return true;
			default:
				result = false;
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet))]
	internal static class ZNetPatches
	{
		[HarmonyPatch("OnNewConnection")]
		[HarmonyPostfix]
		private static void OnNewConnection_Postfix(ZNet __instance, ZNetPeer peer)
		{
			if (__instance.IsServer())
			{
				peer.m_rpc.Register<bool, bool>("DCG_ClientHandshake", (Action<ZRpc, bool, bool>)delegate(ZRpc rpc, bool hasConsoleArg, bool hasDevCommands)
				{
					OnServerReceiveHandshake(__instance, peer, hasConsoleArg, hasDevCommands);
				});
				peer.m_rpc.Register<string>("DCG_AdminCommand", (Action<ZRpc, string>)delegate(ZRpc rpc, string commandLine)
				{
					OnServerReceiveAdminCommand(__instance, peer, commandLine);
				});
				return;
			}
			peer.m_rpc.Register<bool, string, string>("DCG_ServerSyncState", (Action<ZRpc, bool, string, string>)delegate(ZRpc rpc, bool isAdmin, string tagFormat, string tagColor)
			{
				DevCommandsGuardPlugin.SynchronizedAdmin = isAdmin;
				DevCommandsGuardPlugin.ActiveTagFormat = (string.IsNullOrEmpty(tagFormat) ? "{name}" : tagFormat);
				DevCommandsGuardPlugin.ActiveTagColor = (string.IsNullOrEmpty(tagColor) ? "red" : tagColor);
			});
			peer.m_rpc.Register<string>("DCG_AdminCommandFeedback", (Action<ZRpc, string>)delegate(ZRpc rpc, string message)
			{
				Console instance = Console.instance;
				if (instance != null)
				{
					instance.Print(message);
				}
			});
		}

		[HarmonyPatch("RPC_ClientHandshake")]
		[HarmonyPostfix]
		private static void RPC_ClientHandshake_Postfix(ZNet __instance, ZRpc rpc)
		{
			if (!__instance.IsServer())
			{
				bool localHasConsoleArg = DevCommandsGuardPlugin.LocalHasConsoleArg;
				bool flag = (Object)(object)Console.instance != (Object)null && ((Terminal)Console.instance).IsCheatsEnabled();
				rpc.Invoke("DCG_ClientHandshake", new object[2] { localHasConsoleArg, flag });
			}
		}

		private static void OnServerReceiveHandshake(ZNet znet, ZNetPeer peer, bool hasConsoleArg, bool hasDevCommands)
		{
			string endPointString = peer.m_socket.GetEndPointString();
			DevCommandsGuardPlugin.HandshakedPeers.Add(endPointString);
			DevCommandsGuardPlugin.PeerClientStates[endPointString] = (hasConsoleArg, hasDevCommands);
			bool flag = DevCommandsGuardPlugin.IsPeerAdmin(znet, peer);
			peer.m_rpc.Invoke("DCG_ServerSyncState", new object[3]
			{
				flag,
				DevCommandsGuardPlugin.CustomTagFormat.Value,
				DevCommandsGuardPlugin.CustomTagColor.Value
			});
			if (!flag && DevCommandsGuardPlugin.RejectClientsWithDevCommands.Value && (hasConsoleArg || hasDevCommands))
			{
				DevCommandsGuardPlugin.Log.LogWarning((object)$"Rejecting non-admin peer {endPointString} (consoleArg={hasConsoleArg}, devCommands={hasDevCommands})");
				DevCommandsGuardPlugin.RejectedPeers.Add(endPointString);
				peer.m_rpc.Invoke("Error", new object[1] { 5 });
				znet.Disconnect(peer);
			}
		}

		private static void OnServerReceiveAdminCommand(ZNet znet, ZNetPeer peer, string commandLine)
		{
			if (!DevCommandsGuardPlugin.IsPeerAdmin(znet, peer))
			{
				peer.m_rpc.Invoke("DCG_AdminCommandFeedback", new object[1] { "[DCG] Permission denied: you are not a server admin." });
				return;
			}
			bool changed;
			string text = DevCommandsGuardPlugin.ExecuteAdminConfigCommand((commandLine ?? string.Empty).Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries), out changed);
			DevCommandsGuardPlugin.Log.LogInfo((object)("Admin " + peer.m_socket.GetHostName() + " executed dcg: " + text));
			peer.m_rpc.Invoke("DCG_AdminCommandFeedback", new object[1] { text });
		}

		[HarmonyPatch("SendPeerInfo")]
		[HarmonyPrefix]
		private static bool SendPeerInfo_Prefix(ZNet __instance, ZRpc rpc)
		{
			if (!__instance.IsServer())
			{
				return true;
			}
			ZNetPeer peer = __instance.GetPeer(rpc);
			if (peer == null)
			{
				return true;
			}
			string endPointString = peer.m_socket.GetEndPointString();
			bool flag = DevCommandsGuardPlugin.IsPeerAdmin(__instance, peer);
			if (!flag && DevCommandsGuardPlugin.RejectedPeers.Contains(endPointString))
			{
				return false;
			}
			if (!flag && DevCommandsGuardPlugin.RejectClientsWithoutPlugin.Value && !DevCommandsGuardPlugin.HandshakedPeers.Contains(endPointString))
			{
				DevCommandsGuardPlugin.Log.LogWarning((object)("Rejecting non-admin peer " + endPointString + ": missing JgDev_Valheim_DevCommandsGuard handshake."));
				rpc.Invoke("Error", new object[1] { 3 });
				__instance.Disconnect(peer);
				return false;
			}
			return true;
		}

		[HarmonyPatch("Disconnect")]
		[HarmonyPostfix]
		private static void Disconnect_Postfix(ZNetPeer peer)
		{
			if (peer?.m_socket != null)
			{
				string endPointString = peer.m_socket.GetEndPointString();
				DevCommandsGuardPlugin.HandshakedPeers.Remove(endPointString);
				DevCommandsGuardPlugin.RejectedPeers.Remove(endPointString);
				DevCommandsGuardPlugin.PeerClientStates.Remove(endPointString);
			}
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal static class TerminalPatches
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			internal void <InitTerminal_Postfix>b__0_0(ConsoleEventArgs args)
			{
				if (args?.Args == null)
				{
					return;
				}
				string[] array = args.Args.Skip(1).ToArray();
				if ((Object)(object)ZNet.instance == (Object)null)
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("[DCG] Must be connected to a world/server.");
					}
				}
				else if (ZNet.instance.IsServer())
				{
					bool changed;
					string text = DevCommandsGuardPlugin.ExecuteAdminConfigCommand(array, out changed);
					Terminal context2 = args.Context;
					if (context2 != null)
					{
						context2.AddString(text);
					}
				}
				else if (!DevCommandsGuardPlugin.IsLocalAdmin())
				{
					Terminal context3 = args.Context;
					if (context3 != null)
					{
						context3.AddString("[DCG] Permission denied: you are not a server admin.");
					}
				}
				else
				{
					ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
					if (serverPeer != null)
					{
						serverPeer.m_rpc.Invoke("DCG_AdminCommand", new object[1] { string.Join(" ", array) });
					}
				}
			}
		}

		[HarmonyPatch("InitTerminal")]
		[HarmonyPostfix]
		private static void InitTerminal_Postfix()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			try
			{
				if (Terminal.commands != null && Terminal.commands.ContainsKey("dcg"))
				{
					return;
				}
				object obj = <>c.<>9__0_0;
				if (obj == null)
				{
					ConsoleEvent val = delegate(ConsoleEventArgs args)
					{
						if (args?.Args != null)
						{
							string[] array2 = args.Args.Skip(1).ToArray();
							if ((Object)(object)ZNet.instance == (Object)null)
							{
								Terminal context = args.Context;
								if (context != null)
								{
									context.AddString("[DCG] Must be connected to a world/server.");
								}
							}
							else if (ZNet.instance.IsServer())
							{
								bool changed;
								string text2 = DevCommandsGuardPlugin.ExecuteAdminConfigCommand(array2, out changed);
								Terminal context2 = args.Context;
								if (context2 != null)
								{
									context2.AddString(text2);
								}
							}
							else if (!DevCommandsGuardPlugin.IsLocalAdmin())
							{
								Terminal context3 = args.Context;
								if (context3 != null)
								{
									context3.AddString("[DCG] Permission denied: you are not a server admin.");
								}
							}
							else
							{
								ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
								if (serverPeer != null)
								{
									serverPeer.m_rpc.Invoke("DCG_AdminCommand", new object[1] { string.Join(" ", array2) });
								}
							}
						}
					};
					<>c.<>9__0_0 = val;
					obj = (object)val;
				}
				ConsoleEvent val2 = (ConsoleEvent)obj;
				string text = "DevCommandsGuard admin config: dcg [status | reject <on|off> | requireplugin <on|off> | tagcolor <color> | tagformat <format>]";
				ConstructorInfo[] constructors = typeof(ConsoleCommand).GetConstructors();
				foreach (ConstructorInfo constructorInfo in constructors)
				{
					ParameterInfo[] parameters = constructorInfo.GetParameters();
					if (parameters.Length >= 3 && parameters[0].ParameterType == typeof(string) && parameters[1].ParameterType == typeof(string) && parameters[2].ParameterType == typeof(ConsoleEvent))
					{
						object[] array = new object[parameters.Length];
						array[0] = "dcg";
						array[1] = text;
						array[2] = val2;
						for (int num2 = 3; num2 < parameters.Length; num2++)
						{
							array[num2] = (parameters[num2].HasDefaultValue ? parameters[num2].DefaultValue : (parameters[num2].ParameterType.IsValueType ? Activator.CreateInstance(parameters[num2].ParameterType) : null));
						}
						constructorInfo.Invoke(array);
						break;
					}
				}
			}
			catch (Exception arg)
			{
				DevCommandsGuardPlugin.Log.LogError((object)$"Failed to register dcg terminal command: {arg}");
			}
		}

		[HarmonyPatch("TryRunCommand")]
		[HarmonyPostfix]
		private static void TryRunCommand_Postfix(string text)
		{
			try
			{
				if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
				{
					return;
				}
				if (!string.IsNullOrWhiteSpace(text))
				{
					string text2 = text.Trim();
					if ((text2.Equals("dcg", StringComparison.OrdinalIgnoreCase) || text2.StartsWith("dcg ", StringComparison.OrdinalIgnoreCase)) && (Terminal.commands == null || !Terminal.commands.ContainsKey("dcg")))
					{
						string[] value = text2.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray();
						if (!DevCommandsGuardPlugin.IsLocalAdmin())
						{
							Console instance = Console.instance;
							if (instance != null)
							{
								instance.Print("[DCG] Permission denied: you are not a server admin.");
							}
						}
						else
						{
							ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
							if (serverPeer != null)
							{
								serverPeer.m_rpc.Invoke("DCG_AdminCommand", new object[1] { string.Join(" ", value) });
							}
						}
					}
				}
				ZNetPeer serverPeer2 = ZNet.instance.GetServerPeer();
				if (serverPeer2 != null && (Object)(object)Console.instance != (Object)null && ((Terminal)Console.instance).IsCheatsEnabled())
				{
					serverPeer2.m_rpc.Invoke("DCG_ClientHandshake", new object[2]
					{
						DevCommandsGuardPlugin.LocalHasConsoleArg,
						true
					});
				}
			}
			catch (Exception arg)
			{
				DevCommandsGuardPlugin.Log.LogError((object)$"Error in TryRunCommand_Postfix: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(Player), "FixedUpdate")]
	internal static class PlayerStatePatches
	{
		private static readonly Dictionary<long, Color[]> OriginalColors = new Dictionary<long, Color[]>();

		private static void Postfix(Player __instance)
		{
			if ((Object)(object)((Character)__instance).m_nview == (Object)null || !((Character)__instance).m_nview.IsValid())
			{
				return;
			}
			ZDO zDO = ((Character)__instance).m_nview.GetZDO();
			if (zDO == null)
			{
				return;
			}
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && ((Character)__instance).m_nview.IsOwner())
			{
				bool flag = ((Character)__instance).InGodMode() || __instance.InDebugFlyMode() || Player.m_debugMode;
				bool flag2 = DevCommandsGuardPlugin.IsLocalAdmin();
				if (zDO.GetBool("DCG_DebugOrGod", false) != flag)
				{
					zDO.Set("DCG_DebugOrGod", flag);
				}
				if (zDO.GetBool("DCG_IsAdmin", false) != flag2)
				{
					zDO.Set("DCG_IsAdmin", flag2);
				}
			}
			bool highlight = zDO.GetBool("DCG_DebugOrGod", false) && !zDO.GetBool("DCG_IsAdmin", false) && DevCommandsGuardPlugin.IsLocalAdmin();
			ApplyModelHighlight(__instance, ((ZDOID)(ref zDO.m_uid)).ID, highlight);
		}

		private static void ApplyModelHighlight(Player player, long id, bool highlight)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			Renderer[] componentsInChildren = ((Component)player).GetComponentsInChildren<Renderer>();
			if (componentsInChildren == null || componentsInChildren.Length == 0)
			{
				return;
			}
			if (highlight)
			{
				Renderer[] array;
				if (!OriginalColors.ContainsKey(id))
				{
					List<Color> list = new List<Color>();
					array = componentsInChildren;
					for (int i = 0; i < array.Length; i++)
					{
						Material[] materials = array[i].materials;
						foreach (Material val in materials)
						{
							list.Add(val.HasProperty("_Color") ? val.color : Color.white);
						}
					}
					OriginalColors[id] = list.ToArray();
				}
				array = componentsInChildren;
				for (int i = 0; i < array.Length; i++)
				{
					Material[] materials = array[i].materials;
					foreach (Material val2 in materials)
					{
						if (val2.HasProperty("_Color"))
						{
							val2.color = Color.red;
						}
						if (val2.HasProperty("_EmissionColor"))
						{
							val2.EnableKeyword("_EMISSION");
							val2.SetColor("_EmissionColor", Color.red * 0.6f);
						}
					}
				}
			}
			else
			{
				if (!OriginalColors.TryGetValue(id, out var value))
				{
					return;
				}
				int num = 0;
				Renderer[] array = componentsInChildren;
				for (int i = 0; i < array.Length; i++)
				{
					Material[] materials = array[i].materials;
					foreach (Material val3 in materials)
					{
						if (val3.HasProperty("_Color") && num < value.Length)
						{
							val3.color = value[num];
						}
						if (val3.HasProperty("_EmissionColor"))
						{
							val3.SetColor("_EmissionColor", Color.black);
						}
						num++;
					}
				}
				OriginalColors.Remove(id);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "GetHoverName")]
	internal static class PlayerHoverNamePatch
	{
		private static void Postfix(Player __instance, ref string __result)
		{
			if (!((Object)(object)((Character)__instance).m_nview == (Object)null) && ((Character)__instance).m_nview.IsValid())
			{
				ZDO zDO = ((Character)__instance).m_nview.GetZDO();
				if (zDO != null && zDO.GetBool("DCG_DebugOrGod", false) && !zDO.GetBool("DCG_IsAdmin", false) && !string.IsNullOrEmpty(__result) && !__result.StartsWith("<color=", StringComparison.Ordinal))
				{
					string text = (string.IsNullOrEmpty(DevCommandsGuardPlugin.ActiveTagFormat) ? "{name}" : DevCommandsGuardPlugin.ActiveTagFormat);
					string text2 = (string.IsNullOrEmpty(DevCommandsGuardPlugin.ActiveTagColor) ? "red" : DevCommandsGuardPlugin.ActiveTagColor);
					string text3 = (text.Contains("{name}") ? text.Replace("{name}", __result) : (text + " " + __result));
					__result = "<color=" + text2 + ">" + text3 + "</color>";
				}
			}
		}
	}
}