Decompiled source of RememberPassword v1.1.0

plugins/RememberPassword.dll

Decompiled 5 hours ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using GUIFramework;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[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("RememberPassword")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+fdb2e1c2f78509a6910ed80aaa5a0feae17b47cc")]
[assembly: AssemblyProduct("RememberPassword")]
[assembly: AssemblyTitle("RememberPassword")]
[assembly: AssemblyVersion("1.1.0.0")]
[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 RememberPassword
{
	internal sealed class PasswordAttempt
	{
		private readonly string savedPassword;

		private bool submittedSavedPassword;

		internal bool HasSavedPassword => !string.IsNullOrEmpty(savedPassword);

		internal string PasswordToSave { get; private set; }

		internal PasswordAttempt(string savedPassword)
		{
			this.savedPassword = savedPassword;
		}

		internal string Submit(string password, bool remember)
		{
			if (HasSavedPassword && !submittedSavedPassword && string.IsNullOrEmpty(password))
			{
				submittedSavedPassword = true;
				return savedPassword;
			}
			if (remember && !string.IsNullOrEmpty(password))
			{
				PasswordToSave = password;
			}
			return password;
		}

		internal string RejectedPassword(bool incorrectPassword)
		{
			if (!incorrectPassword || !submittedSavedPassword)
			{
				return null;
			}
			return savedPassword;
		}
	}
	internal sealed class PasswordStore
	{
		private readonly string directory;

		private readonly Action<string> warn;

		internal PasswordStore(string directory, Action<string> warn)
		{
			this.directory = directory;
			this.warn = warn;
		}

		internal string Read(string server)
		{
			try
			{
				byte[] array = KeyFor(server);
				byte[] bytes = ProtectedData.Unprotect(File.ReadAllBytes(PathFor(array)), array, (DataProtectionScope)0);
				return Encoding.UTF8.GetString(bytes);
			}
			catch (Exception ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException)
			{
				return null;
			}
			catch (Exception ex2) when (IsStorageError(ex2))
			{
				warn("Couldn't read the saved server password (" + ex2.GetType().Name + ").");
				return null;
			}
		}

		internal void Save(string server, string password)
		{
			string text = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".tmp");
			try
			{
				byte[] array = KeyFor(server);
				byte[] bytes = ProtectedData.Protect(Encoding.UTF8.GetBytes(password), array, (DataProtectionScope)0);
				string text2 = PathFor(array);
				Directory.CreateDirectory(directory);
				File.WriteAllBytes(text, bytes);
				if (File.Exists(text2))
				{
					File.Replace(text, text2, null);
				}
				else
				{
					File.Move(text, text2);
				}
			}
			catch (Exception ex) when (IsStorageError(ex))
			{
				warn("Couldn't save the server password (" + ex.GetType().Name + ").");
			}
			finally
			{
				DeleteFile(text);
			}
		}

		internal bool Forget(string server)
		{
			return DeleteFile(PathFor(KeyFor(server)));
		}

		private bool DeleteFile(string path)
		{
			try
			{
				File.Delete(path);
				return true;
			}
			catch (DirectoryNotFoundException)
			{
				return true;
			}
			catch (Exception ex2) when (IsStorageError(ex2))
			{
				warn("Couldn't remove the password file (" + ex2.GetType().Name + ").");
				return false;
			}
		}

		private static byte[] KeyFor(string server)
		{
			using SHA256 sHA = SHA256.Create();
			return sHA.ComputeHash(Encoding.UTF8.GetBytes(server));
		}

		private string PathFor(byte[] key)
		{
			return Path.Combine(directory, BitConverter.ToString(key).Replace("-", "") + ".bin");
		}

		private static bool IsStorageError(Exception error)
		{
			if (!(error is IOException) && !(error is UnauthorizedAccessException) && !(error is CryptographicException) && !(error is PlatformNotSupportedException) && !(error is DllNotFoundException))
			{
				return error is EntryPointNotFoundException;
			}
			return true;
		}
	}
	[BepInPlugin("fr.romaindurand.rememberpassword", "RememberPassword", "1.1.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class Attempt
		{
			internal readonly ZNet Network;

			internal readonly ZRpc Rpc;

			internal readonly string Server;

			internal readonly PasswordAttempt Password;

			internal readonly GuiInputField Input;

			internal readonly Toggle Checkbox;

			internal readonly Navigation OriginalNavigation;

			internal Attempt(ZNet network, ZRpc rpc, string server, PasswordAttempt password, GuiInputField input = null, Toggle checkbox = null)
			{
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				Network = network;
				Rpc = rpc;
				Server = server;
				Password = password;
				Input = input;
				Checkbox = checkbox;
				if (Object.op_Implicit((Object)(object)input))
				{
					OriginalNavigation = ((Selectable)input).navigation;
					Navigation originalNavigation = OriginalNavigation;
					((Navigation)(ref originalNavigation)).mode = (Mode)4;
					((Navigation)(ref originalNavigation)).selectOnDown = (Selectable)(object)checkbox;
					((Selectable)input).navigation = originalNavigation;
				}
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "TransitionToMainScene")]
		private static class MenuStyle
		{
			private static void Prefix(FejdStartup __instance)
			{
				Toggle val = __instance.m_samePlatformOnlyToggleJoinPanel;
				if (!Object.op_Implicit((Object)(object)val))
				{
					val = __instance.m_crossplayServerToggle;
				}
				instance.checkboxStyle.CaptureStyle(val);
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_ClientHandshake")]
		private static class PasswordDialog
		{
			private static void Prefix(ZNet __instance, ZRpc __0, ref bool __1, string ___m_serverPlayFabPlayerId, ulong ___m_serverSteamID, string ___m_serverHost, int ___m_serverHostPort)
			{
				if (__instance.IsServer())
				{
					return;
				}
				instance.CloseAttempt();
				if (!__1 || !string.IsNullOrEmpty(FejdStartup.ServerPassword))
				{
					return;
				}
				string text = ServerIdentity.FromConnection(___m_serverPlayFabPlayerId, ___m_serverSteamID, ___m_serverHost, ___m_serverHostPort);
				if (text != null)
				{
					PasswordAttempt passwordAttempt = new PasswordAttempt(instance.store.Read(text));
					if (passwordAttempt.HasSavedPassword)
					{
						instance.attempt = new Attempt(__instance, __0, text, passwordAttempt);
						__1 = false;
					}
					else
					{
						instance.OpenPrompt(__instance, __0, text, passwordAttempt);
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "SendPeerInfo")]
		private static class PasswordSubmitted
		{
			private static void Prefix(ZNet __instance, ZRpc __0, ref string __1)
			{
				Attempt attempt = instance.attempt;
				if (attempt != null && (Object)(object)attempt.Network == (Object)(object)__instance && attempt.Rpc == __0)
				{
					__1 = attempt.Password.Submit(__1, Object.op_Implicit((Object)(object)attempt.Checkbox) && attempt.Checkbox.isOn);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static class ConnectionAccepted
		{
			private static void Postfix(ZNet __instance, ZRpc __0)
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Invalid comparison between Unknown and I4
				Attempt attempt = instance.attempt;
				if (attempt != null && !((Object)(object)attempt.Network != (Object)(object)__instance) && attempt.Rpc == __0 && (int)ZNet.GetConnectionStatus() == 2)
				{
					if (attempt.Password.PasswordToSave != null)
					{
						instance.store.Save(attempt.Server, attempt.Password.PasswordToSave);
					}
					instance.CloseAttempt();
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_Error")]
		private static class ConnectionRejected
		{
			private static void Postfix(ZNet __instance, ZRpc __0, int __1)
			{
				Attempt attempt = instance.attempt;
				if (attempt != null && !((Object)(object)attempt.Network != (Object)(object)__instance) && attempt.Rpc == __0)
				{
					string text = attempt.Password.RejectedPassword(__1 == 6);
					if (text != null && instance.store.Read(attempt.Server) == text)
					{
						instance.store.Forget(attempt.Server);
					}
					instance.CloseAttempt();
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		private static class ConnectionClosed
		{
			private static void Prefix(ZNet __instance)
			{
				if ((Object)(object)instance.attempt?.Network == (Object)(object)__instance)
				{
					instance.CloseAttempt();
				}
			}
		}

		private const string Guid = "fr.romaindurand.rememberpassword";

		private const string Version = "1.1.0";

		private static Plugin instance;

		private readonly RememberCheckbox checkboxStyle = new RememberCheckbox();

		private Harmony harmony;

		private PasswordStore store;

		private Attempt attempt;

		private void Awake()
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"RememberPassword {((BaseUnityPlugin)this).Info.Metadata.Version} loaded ({((BaseUnityPlugin)this).Info.Metadata.GUID}).");
			if (Environment.OSVersion.Platform != PlatformID.Win32NT)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"RememberPassword requires Windows to protect saved passwords.");
				return;
			}
			store = new PasswordStore(Path.Combine(Paths.ConfigPath, "fr.romaindurand.rememberpassword"), delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)message);
			});
			instance = this;
			harmony = new Harmony("fr.romaindurand.rememberpassword");
			harmony.PatchAll(typeof(Plugin).Assembly);
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			CloseAttempt();
			instance = null;
		}

		private void OpenPrompt(ZNet network, ZRpc rpc, string server, PasswordAttempt password)
		{
			if (!Object.op_Implicit((Object)(object)network.m_passwordDialog))
			{
				return;
			}
			GuiInputField input = ((Component)network.m_passwordDialog).GetComponentInChildren<GuiInputField>(true);
			if (Object.op_Implicit((Object)(object)input) && Object.op_Implicit((Object)(object)((TMP_InputField)input).textComponent))
			{
				string caption = ((Localization.instance.GetSelectedLanguage() == "French") ? "Mémoriser le mot de passe" : "Remember password");
				Toggle val = checkboxStyle.Create(input, caption);
				val.SetIsOnWithoutNotify(false);
				((UnityEvent<bool>)(object)val.onValueChanged).AddListener((UnityAction<bool>)delegate
				{
					input.ActivateInputField();
				});
				attempt = new Attempt(network, rpc, server, password, input, val);
			}
		}

		private void CloseAttempt()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (attempt != null)
			{
				if (Object.op_Implicit((Object)(object)attempt.Input))
				{
					((Selectable)attempt.Input).navigation = attempt.OriginalNavigation;
				}
				if (Object.op_Implicit((Object)(object)attempt.Checkbox))
				{
					((Component)attempt.Checkbox).gameObject.SetActive(false);
					Object.Destroy((Object)(object)((Component)attempt.Checkbox).gameObject);
				}
				attempt = null;
			}
		}
	}
	internal sealed class RememberCheckbox
	{
		private Sprite boxSprite;

		private Sprite markSprite;

		private Type boxType;

		private Type markType;

		private ColorBlock colors = ColorBlock.defaultColorBlock;

		internal void CaptureStyle(Toggle nativeToggle)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)nativeToggle))
			{
				colors = ((Selectable)nativeToggle).colors;
				Graphic targetGraphic = ((Selectable)nativeToggle).targetGraphic;
				Image val = (Image)(object)((targetGraphic is Image) ? targetGraphic : null);
				if (val != null)
				{
					boxSprite = val.sprite;
					boxType = val.type;
				}
				Graphic graphic = nativeToggle.graphic;
				Image val2 = (Image)(object)((graphic is Image) ? graphic : null);
				if (val2 != null)
				{
					markSprite = val2.sprite;
					markType = val2.type;
				}
			}
		}

		internal Toggle Create(GuiInputField input, string caption)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = AddRect("RememberPassword", ((Component)input).transform);
			val.anchorMin = Vector2.zero;
			val.anchorMax = Vector2.right;
			val.pivot = new Vector2(0.5f, 1f);
			val.anchoredPosition = new Vector2(0f, -8f);
			val.sizeDelta = new Vector2(0f, 32f);
			((Graphic)((Component)val).gameObject.AddComponent<Image>()).color = Color.clear;
			RectTransform val2 = AddRect("Background", (Transform)(object)val);
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0f, 0.5f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.pivot = new Vector2(0f, 0.5f);
			val2.sizeDelta = new Vector2(22f, 22f);
			Image val4 = ((Component)val2).gameObject.AddComponent<Image>();
			val4.sprite = boxSprite;
			val4.type = boxType;
			((Graphic)val4).color = (Color)(Object.op_Implicit((Object)(object)boxSprite) ? Color.white : new Color(0.22f, 0.18f, 0.13f));
			((Graphic)val4).raycastTarget = false;
			RectTransform obj = AddRect("Checkmark", (Transform)(object)val2);
			obj.anchorMin = Vector2.zero;
			obj.anchorMax = Vector2.one;
			obj.sizeDelta = (Vector2)(Object.op_Implicit((Object)(object)markSprite) ? Vector2.zero : new Vector2(-8f, -8f));
			Image val5 = ((Component)obj).gameObject.AddComponent<Image>();
			val5.sprite = markSprite;
			val5.type = markType;
			((Graphic)val5).color = (Color)(Object.op_Implicit((Object)(object)markSprite) ? Color.white : new Color(0.96f, 0.76f, 0.4f));
			((Graphic)val5).raycastTarget = false;
			RectTransform obj2 = AddRect("Label", (Transform)(object)val);
			obj2.anchorMin = Vector2.zero;
			obj2.anchorMax = Vector2.one;
			obj2.offsetMin = new Vector2(32f, 0f);
			obj2.offsetMax = Vector2.zero;
			TextMeshProUGUI obj3 = ((Component)obj2).gameObject.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj3).font = ((TMP_InputField)input).textComponent.font;
			((TMP_Text)obj3).fontSharedMaterial = ((TMP_InputField)input).textComponent.fontSharedMaterial;
			((Graphic)obj3).color = ((Graphic)((TMP_InputField)input).textComponent).color;
			((TMP_Text)obj3).fontSize = Mathf.Min(((TMP_InputField)input).textComponent.fontSize, 24f);
			((TMP_Text)obj3).alignment = (TextAlignmentOptions)4097;
			((Graphic)obj3).raycastTarget = false;
			((TMP_Text)obj3).text = caption;
			Toggle obj4 = ((Component)val).gameObject.AddComponent<Toggle>();
			((Selectable)obj4).targetGraphic = (Graphic)(object)val4;
			obj4.graphic = (Graphic)(object)val5;
			((Selectable)obj4).colors = colors;
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)4;
			((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)input;
			((Selectable)obj4).navigation = navigation;
			return obj4;
		}

		private static RectTransform AddRect(string name, Transform parent)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
			((Transform)val).SetParent(parent, false);
			return val;
		}
	}
	internal static class ServerIdentity
	{
		internal static string FromConnection(string playFabId, ulong steamId, string host, int port)
		{
			if (!string.IsNullOrEmpty(playFabId))
			{
				return "playfab:" + playFabId;
			}
			if (steamId != 0L)
			{
				return "steam:" + steamId.ToString(CultureInfo.InvariantCulture);
			}
			if (string.IsNullOrWhiteSpace(host) || port < 1 || port > 65535)
			{
				return null;
			}
			host = host.Trim();
			host = ((!IPAddress.TryParse(host.Trim('[', ']'), out IPAddress address)) ? host.ToLowerInvariant() : (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString());
			return "address:[" + host + "]:" + port.ToString(CultureInfo.InvariantCulture);
		}
	}
}