From 6e8b34745abe2ad5ca69d0430d6f3cdba7d31e72 Mon Sep 17 00:00:00 2001 From: D1GQ <83262852+D1GQ@users.noreply.github.com> Date: Mon, 2 Mar 2026 19:05:01 -0600 Subject: [PATCH 01/11] Move installation header Yeah that's not supposed to be on the top XD --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 50e2f15..652339d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ -Here's the updated guide with clear instructions for downloading the correct zip file and extracting it, as well as replacing the DLL if you've previously installed the mod: - # ♻ BetterAmongUs ♻ A client-sided mod that enhances the experience for the popular game Among Us! @@ -16,6 +14,7 @@ A client-sided mod that enhances the experience for the popular game Among Us! ## Installation +Here's the updated guide with clear instructions for downloading the correct zip file and extracting it, as well as replacing the DLL if you've previously installed the mod, as this has been requested to be updated multiple times... ### For First-Time Installation: From ae8d53372debc857cd02f5483526471972afb2d7 Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Mon, 16 Mar 2026 17:40:09 +0000 Subject: [PATCH 02/11] Fixed crash issues by adding null checks --- src/Mono/PlayerInfoDisplay.cs | 27 +++++++++---- .../Gameplay/Player/PlayerControlPatch.cs | 4 +- src/Patches/Gameplay/UI/GameSummaryPatch.cs | 4 ++ src/Patches/Gameplay/UI/MeetingHudPatch.cs | 38 ++++++++++++++----- 4 files changed, 55 insertions(+), 18 deletions(-) diff --git a/src/Mono/PlayerInfoDisplay.cs b/src/Mono/PlayerInfoDisplay.cs index 8f28427..4fa73e6 100644 --- a/src/Mono/PlayerInfoDisplay.cs +++ b/src/Mono/PlayerInfoDisplay.cs @@ -146,7 +146,14 @@ internal class PlayerInfoDisplay : MonoBehaviour /// private void UpdatePlayerInfo() { - if (_player?.Data == null) return; + if (_player == null) return; + if (_player.Data == null) return; + + if (_nameText == null) return; + if (_cachedTranslations == null) return; + + if (_sbTag == null || _sbTagTop == null || _sbTagBottom == null) return; + if (_topText == null || _bottomText == null || _infoText == null) return; var betterData = _player.BetterData(); @@ -169,19 +176,19 @@ internal class PlayerInfoDisplay : MonoBehaviour string friendCode = ValidateFriendCode(out string friendCodeColor); + if (DataManager.Settings == null || DataManager.Settings.Gameplay == null) + return; + if (DataManager.Settings.Gameplay.StreamerMode) - { platform = _cachedTranslations.PlatformHidden; - } if (!_player.IsInShapeshift()) - { SetPlayerOutline(_sbTag); - } if (GameState.IsInGame && GameState.IsLobby && !GameState.IsFreePlay) { SetLobbyInfo(ref newName, betterData, _sbTag); + _sbTagTop.Append($"{platform}+++") .Append($"Lv: {_player.Data.PlayerLevel + 1}+++"); @@ -196,15 +203,21 @@ internal class PlayerInfoDisplay : MonoBehaviour { if (_player.IsImpostorTeammate()) newName = newName.ToColor(Colors.ImpostorRed); + _player.RawSetName(newName); } else { var targetData = Utils.PlayerDataFromPlayerId(_player.shapeshiftTargetPlayerId); - var name = targetData.BetterData()?.RealName ?? targetData.PlayerName; + if (targetData == null) return; + + var betterTargetData = targetData.BetterData(); + string name = betterTargetData != null ? betterTargetData.RealName : targetData.PlayerName; + if (_player.IsImpostorTeammate()) name = name.ToColor(Colors.ImpostorRed); - if (targetData != null) _player.RawSetName(name); + + _player.RawSetName(name); } UpdateTextIfChanged(_topText, _sbTagTop, ref _lastTopText); diff --git a/src/Patches/Gameplay/Player/PlayerControlPatch.cs b/src/Patches/Gameplay/Player/PlayerControlPatch.cs index d0d53ab..9171e31 100644 --- a/src/Patches/Gameplay/Player/PlayerControlPatch.cs +++ b/src/Patches/Gameplay/Player/PlayerControlPatch.cs @@ -54,7 +54,9 @@ internal static class PlayerControlPatch [HarmonyPostfix] private static void PlayerControl_MurderPlayer_Postfix(PlayerControl __instance, PlayerControl target) { - if (target == null) return; + // Check for null references + if (__instance == null || target == null || target.Data == null || __instance.Data == null) + return; // Log kill event with player names and roles Logger_.LogPrivate($"{__instance.Data.PlayerName} Has killed {target.Data.PlayerName} as {__instance.Data.RoleType.GetRoleName()}", "EventLog"); diff --git a/src/Patches/Gameplay/UI/GameSummaryPatch.cs b/src/Patches/Gameplay/UI/GameSummaryPatch.cs index 2eb808d..a60c8c4 100644 --- a/src/Patches/Gameplay/UI/GameSummaryPatch.cs +++ b/src/Patches/Gameplay/UI/GameSummaryPatch.cs @@ -16,6 +16,10 @@ internal static class GameSummaryPatch [HarmonyPostfix] private static void EndGameManager_SetEverythingUp_Postfix(EndGameManager __instance) { + // Check for null references + if (__instance == null) + return; + LogGameEnd(); if (!BAUModdedSupportFlags.HasFlag(BAUModdedSupportFlags.Disable_EndGameSummary)) diff --git a/src/Patches/Gameplay/UI/MeetingHudPatch.cs b/src/Patches/Gameplay/UI/MeetingHudPatch.cs index 86a3230..08ea552 100644 --- a/src/Patches/Gameplay/UI/MeetingHudPatch.cs +++ b/src/Patches/Gameplay/UI/MeetingHudPatch.cs @@ -15,23 +15,32 @@ internal static class MeetingHudPatch [HarmonyPostfix] private static void MeetingHud_Start_Postfix(MeetingHud __instance) { + if (__instance == null || __instance.playerStates == null) return; + foreach (var pva in __instance.playerStates) { + if (pva == null) continue; + var target = Utils.PlayerFromPlayerId(pva.TargetPlayerId); + if (target == null) continue; + pva.gameObject.AddComponent().Init(target, pva); } if (!GameState.IsOnlineGame) return; // Add host icon to meeting hud - __instance.ProceedButton.gameObject.transform.localPosition = new(-2.5f, 2.2f, 0); - __instance.ProceedButton.gameObject.GetComponent().enabled = false; - __instance.ProceedButton.GetComponent().enabled = false; - __instance.HostIcon.enabled = true; - __instance.HostIcon.gameObject.SetActive(true); - __instance.ProceedButton.gameObject.SetActive(true); - MeetingHud.Instance.ProceedButton.DestroyTextTranslators(); - UpdateHostIcon(); + if (__instance.ProceedButton != null && __instance.HostIcon != null) + { + __instance.ProceedButton.gameObject.transform.localPosition = new(-2.5f, 2.2f, 0); + __instance.ProceedButton.gameObject.GetComponent().enabled = false; + __instance.ProceedButton.GetComponent().enabled = false; + __instance.HostIcon.enabled = true; + __instance.HostIcon.gameObject.SetActive(true); + __instance.ProceedButton.gameObject.SetActive(true); + UpdateHostIcon(); + MeetingHud.Instance.ProceedButton.DestroyTextTranslators(); + } Logger_.LogHeader("Meeting Has Started"); } @@ -39,9 +48,18 @@ internal static class MeetingHudPatch internal static void UpdateHostIcon() { if (MeetingHud.Instance == null) return; + if (GameData.Instance == null) return; - PlayerMaterial.SetColors(GameData.Instance.GetHost().Color, MeetingHud.Instance.HostIcon); - MeetingHud.Instance.ProceedButton.gameObject.GetComponentInChildren().text = string.Format(Translator.GetString("HostInMeeting"), GameData.Instance.GetHost().BetterData().RealName); + var host = GameData.Instance.GetHost(); + if (host == null || host.BetterData() == null) return; + + var hostColor = host.Color; + var hostRealName = host.BetterData().RealName; + + if (MeetingHud.Instance.HostIcon == null || MeetingHud.Instance.ProceedButton == null) return; + + PlayerMaterial.SetColors(hostColor, MeetingHud.Instance.HostIcon); + MeetingHud.Instance.ProceedButton.gameObject.GetComponentInChildren().text = string.Format(Translator.GetString("HostInMeeting"), hostRealName); } internal static float timeOpen = 0f; From caa1caa6464109a0fb49ea09d4f64832d0029dc2 Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Mon, 16 Mar 2026 17:53:07 +0000 Subject: [PATCH 03/11] Fix errors in PrivateLobbyPatch and ChatCommandsPatch --- src/Patches/Client/PrivateLobbyPatch.cs | 10 ++++++---- src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs | 5 ++++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Patches/Client/PrivateLobbyPatch.cs b/src/Patches/Client/PrivateLobbyPatch.cs index f7d7854..8b04f21 100644 --- a/src/Patches/Client/PrivateLobbyPatch.cs +++ b/src/Patches/Client/PrivateLobbyPatch.cs @@ -126,9 +126,11 @@ internal static class PrivateLobbyPatch button.enabled = false; // Change inactive sprite to cyan color to indicate locked state - var sprite = __instance.HostPrivateButton.transform.Find("Inactive").GetComponent(); - sprite?.color = new(0.35f, 1, 1, 1); + var sprite = __instance.HostPrivateButton.transform.Find("Inactive")?.GetComponent(); + if (sprite != null) + { + sprite.color = new Color(0.35f, 1f, 1f, 1f); // Corrected color assignment + } } } - } -} \ No newline at end of file + } \ No newline at end of file diff --git a/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs index d4f1abe..dcee2be 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs @@ -225,7 +225,10 @@ internal static class ChatCommandsPatch { for (int i = 1; i < typedParts.Length && i <= closestCommand.Arguments.Length; i++) { - closestCommand.Arguments[i - 1]?.Arg = typedParts[i]; + if (closestCommand.Arguments[i - 1] != null) + { + closestCommand.Arguments[i - 1].Arg = typedParts[i]; // Safe assignment + } } } From 4252422a9385c9634ffdbd84ba8410eaf1c0404c Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Mon, 16 Mar 2026 17:55:09 +0000 Subject: [PATCH 04/11] Fix syntax error in PrivateLobbyPatch, whoops. --- src/Patches/Client/PrivateLobbyPatch.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Patches/Client/PrivateLobbyPatch.cs b/src/Patches/Client/PrivateLobbyPatch.cs index 8b04f21..bdef56c 100644 --- a/src/Patches/Client/PrivateLobbyPatch.cs +++ b/src/Patches/Client/PrivateLobbyPatch.cs @@ -133,4 +133,5 @@ internal static class PrivateLobbyPatch } } } - } \ No newline at end of file + } +} \ No newline at end of file From c4baa42a23dcb47fef8e3f07a9b1a10b8b9c15d1 Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Mon, 16 Mar 2026 18:09:02 +0000 Subject: [PATCH 05/11] Fix Linux crypto + chat crash + handshake init --- src/Data/SharedSecretExchange.cs | 63 +++++++++-------------- src/Mono/ExtendedPlayerInfo.cs | 24 +++++---- src/Patches/Gameplay/UI/Chat/ChatPatch.cs | 35 ++++++------- 3 files changed, 56 insertions(+), 66 deletions(-) diff --git a/src/Data/SharedSecretExchange.cs b/src/Data/SharedSecretExchange.cs index eea7937..2ce7a60 100644 --- a/src/Data/SharedSecretExchange.cs +++ b/src/Data/SharedSecretExchange.cs @@ -3,58 +3,53 @@ using System.Security.Cryptography; namespace BetterAmongUs.Data; -/// -/// Handles secure key exchange using Elliptic Curve Diffie-Hellman (ECDH) for establishing shared secrets. -/// internal sealed class SharedSecretExchange { private readonly ECDiffieHellman dh; private byte[] publicKey; private int tempKey; private byte[] sharedSecret = []; + private bool cryptoDisabled; - /// - /// Initializes a new instance of the SharedSecretExchange class with a new ECDH key pair. - /// internal SharedSecretExchange() { - dh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); - publicKey = dh.ExportSubjectPublicKeyInfo(); + try + { + dh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); + publicKey = dh.ExportSubjectPublicKeyInfo(); + } + catch (Exception ex) + { + Logger_.Error("ECDH unavailable, disabling secure handshake: " + ex.Message); + cryptoDisabled = true; + dh = null; + publicKey = []; + } + var random = new Random(); tempKey = random.Next(); } - /// - /// Gets the public key for key exchange. - /// - /// The public key in SubjectPublicKeyInfo format. internal byte[] GetPublicKey() { + if (cryptoDisabled) return []; return publicKey; } - /// - /// Gets the temporary key used for initial communication. - /// - /// A random integer used as a temporary key. internal int GetTempKey() { return tempKey; } - /// - /// Gets the established shared secret. - /// - /// The shared secret byte array. - internal byte[] GetSharedSecret() => sharedSecret; + internal byte[] GetSharedSecret() + { + if (cryptoDisabled) return []; + return sharedSecret; + } - /// - /// Generates a shared secret using another party's public key. - /// - /// The other party's public key in SubjectPublicKeyInfo format. - /// The shared secret byte array, or an empty array if generation fails. internal byte[] GenerateSharedSecret(byte[] otherPartyPublicKey) { + if (cryptoDisabled) return []; if (sharedSecret.Length > 0) return sharedSecret; try @@ -68,19 +63,15 @@ internal sealed class SharedSecretExchange } catch (Exception ex) { - Logger_.Error($"Error generating shared secret: {ex.Message}"); + Logger_.Error("Error generating shared secret: " + ex.Message); return []; } } - /// - /// Gets a numeric hash of the shared secret for verification purposes. - /// - /// A 32-bit integer hash of the shared secret, or 0 if no shared secret exists. internal int GetSharedSecretHash() { - if (sharedSecret.Length == 0) - return 0; + if (cryptoDisabled) return 0; + if (sharedSecret.Length == 0) return 0; using SHA256 sha256 = SHA256.Create(); byte[] hashBytes = sha256.ComputeHash(sharedSecret); @@ -88,14 +79,8 @@ internal sealed class SharedSecretExchange return Math.Abs(numericHash); } - /// - /// Gets a value indicating whether the key exchange data has been cleared for security. - /// internal bool HasBeenCleared { get; private set; } - /// - /// Clears all sensitive key exchange data for security purposes. - /// internal void ClearData() { if (HasBeenCleared) return; diff --git a/src/Mono/ExtendedPlayerInfo.cs b/src/Mono/ExtendedPlayerInfo.cs index 7e7cf10..e306bd5 100644 --- a/src/Mono/ExtendedPlayerInfo.cs +++ b/src/Mono/ExtendedPlayerInfo.cs @@ -15,17 +15,19 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension - /// Gets or sets the base NetworkedPlayerInfo instance. - /// public NetworkedPlayerInfo? BaseMono { get; set; } - /// - /// Gets the NetworkedPlayerInfo instance. - /// internal NetworkedPlayerInfo? _Data => BaseMono; private bool hasSet = false; @@ -47,7 +49,11 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension [HideFromIl2Cpp] - internal HandshakeHandler HandshakeHandler { get; } + internal HandshakeHandler? HandshakeHandler { get; } /// /// Gets the player ID. diff --git a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs index c9d3d91..f2942bf 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs @@ -134,28 +134,33 @@ internal static class ChatPatch private static void ChatController_SetChatBubbleName_Postfix(ChatController __instance, ChatBubble bubble, NetworkedPlayerInfo playerInfo, bool isDead, bool didVote) { if (didVote) return; + if (bubble == null) return; + if (bubble.NameText == null) return; + if (playerInfo == null) return; + + var sourcePlayer = playerInfo.Object; + if (sourcePlayer == null) return; + if (PlayerControl.LocalPlayer == null) return; StringBuilder sbTag = new(); StringBuilder sbInfo = new(); - var sourcePlayer = playerInfo.Object; string hashPuid = Utils.GetHashPuid(sourcePlayer); string friendCode = playerInfo.FriendCode; string playerName = playerInfo.BetterData()?.RealName ?? "???"; - // Format role display with team color string Role = $"{sourcePlayer.GetRoleName()}+++"; - // In lobby, show player tags instead of roles if (GameState.IsLobby && !GameState.IsFreePlay) { Role = ""; - // Show BAU user tag - if (sourcePlayer.IsLocalPlayer() || sourcePlayer.BetterData().IsBetterUser) - sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), sourcePlayer.BetterData().IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); + var betterData = sourcePlayer.BetterData(); + if (betterData == null) return; + + if (sourcePlayer.IsLocalPlayer() || betterData.IsBetterUser) + sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); - // Show mod-specific tags based on player data if (BetterDataManager.BetterDataFile.SickoData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) sbTag.Append($"{Translator.GetString("Player.SickoUser")}+++"); else if (BetterDataManager.BetterDataFile.AUMData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) @@ -166,7 +171,6 @@ internal static class ChatPatch sbTag.Append($"{Translator.GetString("Player.KnownCheater")}+++"); } - // Hide roles from alive players (unless same team) if (!sourcePlayer.IsImpostorTeammate()) { if (PlayerControl.LocalPlayer.IsAlive() && !sourcePlayer.IsLocalPlayer()) @@ -175,23 +179,19 @@ internal static class ChatPatch } } - // Show role for dead players or if local player is Guardian Angel if (PlayerControl.LocalPlayer.Is(RoleTypes.GuardianAngel) && !sourcePlayer.IsAlive() || !PlayerControl.LocalPlayer.Is(RoleTypes.GuardianAngel)) { sbTag.Append(Role); } - // Format tags with separators sbInfo.Append(""); - for (int i = 0; i < sbTag.ToString().Split("+++").Length; i++) + var parts = sbTag.ToString().Split("+++"); + for (int i = 0; i < parts.Length; i++) { - if (!string.IsNullOrEmpty(sbTag.ToString().Split("+++")[i])) + if (!string.IsNullOrEmpty(parts[i])) { - if (i < sbTag.ToString().Split("+++").Length) - { - sbInfo.Append(sbTag.ToString().Split("+++")[i]); - } - if (i != sbTag.ToString().Split("+++").Length - 2) + sbInfo.Append(parts[i]); + if (i != parts.Length - 2) { sbInfo.Append(" - "); } @@ -199,7 +199,6 @@ internal static class ChatPatch } sbInfo.Append(""); - // Position tags before local player name, after other players' names bool flag = sourcePlayer.IsLocalPlayer(); if (flag) { From a162297997675013858f44118fcfa1cd401707c2 Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Tue, 17 Mar 2026 09:57:38 +0000 Subject: [PATCH 06/11] Added linux comaptibility! Added null safety and cross-platform behaviour, improved BetterUser handshake. --- src/Data/SharedSecretExchange.cs | 67 +++++++++++-- src/Modules/HandshakeHandler.cs | 74 +++----------- src/Mono/ExtendedPlayerInfo.cs | 7 +- src/Mono/PlayerInfoDisplay.cs | 20 +++- src/Patches/Client/PrivateLobbyPatch.cs | 2 +- src/Patches/Gameplay/UI/Chat/ChatPatch.cs | 112 ++++++++-------------- 6 files changed, 131 insertions(+), 151 deletions(-) diff --git a/src/Data/SharedSecretExchange.cs b/src/Data/SharedSecretExchange.cs index 2ce7a60..87115dd 100644 --- a/src/Data/SharedSecretExchange.cs +++ b/src/Data/SharedSecretExchange.cs @@ -11,23 +11,40 @@ internal sealed class SharedSecretExchange private byte[] sharedSecret = []; private bool cryptoDisabled; + internal bool CryptoAvailable => !cryptoDisabled; + internal bool UseFallback { get; set; } + + private int? remoteTempKey; + internal SharedSecretExchange() { try { - dh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); + dh = ECDiffieHellman.Create(); + dh.GenerateKey(ECCurve.NamedCurves.nistP256); publicKey = dh.ExportSubjectPublicKeyInfo(); } catch (Exception ex) { - Logger_.Error("ECDH unavailable, disabling secure handshake: " + ex.Message); + Logger_.Error("ECDH unavailable, using fallback handshake: " + ex.Message); cryptoDisabled = true; dh = null; publicKey = []; } - var random = new Random(); - tempKey = random.Next(); + tempKey = GenerateSecureTempKey(); + } + + private static int GenerateSecureTempKey() + { + byte[] buffer = new byte[4]; + RandomNumberGenerator.Fill(buffer); + return Math.Abs(BitConverter.ToInt32(buffer, 0)); + } + + internal void SetRemoteTempKey(int key) + { + remoteTempKey = key; } internal byte[] GetPublicKey() @@ -43,21 +60,32 @@ internal sealed class SharedSecretExchange internal byte[] GetSharedSecret() { - if (cryptoDisabled) return []; return sharedSecret; } internal byte[] GenerateSharedSecret(byte[] otherPartyPublicKey) { - if (cryptoDisabled) return []; if (sharedSecret.Length > 0) return sharedSecret; + if (cryptoDisabled || UseFallback) + { + if (!remoteTempKey.HasValue) + return []; + + sharedSecret = DeriveFallbackSecret(tempKey, remoteTempKey.Value); + return sharedSecret; + } + try { - using ECDiffieHellman otherPartyDH = ECDiffieHellman.Create(); - otherPartyDH.ImportSubjectPublicKeyInfo(otherPartyPublicKey, out _); + using var otherPartyDH = ECDiffieHellman.Create(); + if (otherPartyPublicKey == null || otherPartyPublicKey.Length == 0) + return []; + + otherPartyDH.ImportSubjectPublicKeyInfo(otherPartyPublicKey, out _); sharedSecret = dh.DeriveKeyMaterial(otherPartyDH.PublicKey); + dh.Dispose(); return sharedSecret; } @@ -70,15 +98,34 @@ internal sealed class SharedSecretExchange internal int GetSharedSecretHash() { - if (cryptoDisabled) return 0; if (sharedSecret.Length == 0) return 0; using SHA256 sha256 = SHA256.Create(); byte[] hashBytes = sha256.ComputeHash(sharedSecret); - int numericHash = BitConverter.ToInt32(hashBytes, 0); + + int numericHash = (hashBytes[0] << 24) | + (hashBytes[1] << 16) | + (hashBytes[2] << 8) | + hashBytes[3]; + return Math.Abs(numericHash); } + private static byte[] DeriveFallbackSecret(int local, int remote) + { + using SHA256 sha256 = SHA256.Create(); + + int a = local < remote ? local : remote; + int b = local < remote ? remote : local; + + byte[] buffer = new byte[8]; + + Buffer.BlockCopy(BitConverter.GetBytes(a), 0, buffer, 0, 4); + Buffer.BlockCopy(BitConverter.GetBytes(b), 0, buffer, 4, 4); + + return sha256.ComputeHash(buffer); + } + internal bool HasBeenCleared { get; private set; } internal void ClearData() diff --git a/src/Modules/HandshakeHandler.cs b/src/Modules/HandshakeHandler.cs index 275a9bf..2c47867 100644 --- a/src/Modules/HandshakeHandler.cs +++ b/src/Modules/HandshakeHandler.cs @@ -11,9 +11,6 @@ using UnityEngine; namespace BetterAmongUs.Modules; -/// -/// Handles the secure handshake process between BetterAmongUs clients using Diffie-Hellman key exchange. -/// internal sealed class HandshakeHandler { [HideFromIl2Cpp] @@ -25,17 +22,11 @@ internal sealed class HandshakeHandler [HideFromIl2Cpp] private ExtendedPlayerInfo extendedData { get; } - /// - /// Initiates the wait period before sending the secret to another player. - /// internal void WaitSendSecretToPlayer() { extendedData.StartCoroutine(CoWaitSendSecretToPlayer()); } - /// - /// Coroutine that waits for player initialization before sending the secret. - /// private IEnumerator CoWaitSendSecretToPlayer() { if (!BAUPlugin.SendBetterRpc.Value) yield break; @@ -45,14 +36,11 @@ internal sealed class HandshakeHandler if (GameState.IsFreePlay) yield break; yield return null; } - yield return new WaitForSeconds(1f); + yield return new WaitForSeconds(1f); SendSecretToPlayer(); } - /// - /// Resends the secret to the player if not already verified. - /// internal void ResendSecretToPlayer() { if (!BAUPlugin.SendBetterRpc.Value) return; @@ -62,61 +50,47 @@ internal sealed class HandshakeHandler SendSecretToPlayer(); } - /// - /// Sends the local client's public key and temporary key to another player. - /// - // Local client sends to client private void SendSecretToPlayer() { if (extendedData._Data.Object.IsLocalPlayer()) return; if (HasSendSharedSecret) return; HasSendSharedSecret = true; + RPC.SendCustomRpcPacked(CustomRPC.SendSecretToPlayer, writer => { + writer.Write(SharedSecret.CryptoAvailable); writer.WriteBytes(SharedSecret.GetPublicKey()); writer.Write(SharedSecret.GetTempKey()); }, extendedData._Data.ClientId); } - /// - /// Handles receiving a secret from another player and generates a shared secret. - /// - /// MessageReader containing the sender's public key and temporary key. - // Client receives from local client internal void HandleSecretFromSender(MessageReader reader) { if (extendedData._Data?.Object?.IsLocalPlayer() == true) return; + bool senderSupportsCrypto = reader.ReadBoolean(); byte[] sendersPublicKey = reader.ReadBytes(); int tempKey = reader.ReadInt32(); - // Logger.Log($"Received public key ({sendersPublicKey.Length} bytes) from {_Data.PlayerName}"); + SharedSecret.UseFallback = !senderSupportsCrypto; + SharedSecret.SetRemoteTempKey(tempKey); byte[] secret = SharedSecret.GenerateSharedSecret(sendersPublicKey); - if (secret.Length == 0) - { - // Logger.Error("Failed to generate shared secret!"); - return; - } + if (secret.Length == 0) return; + extendedData.IsBetterUser = true; + TryHandlePendingVerificationData(); SendSecretHashToSender(tempKey, extendedData._Data.ClientId); ResendSecretToPlayer(); } - /// - /// Sends the hash of the generated shared secret back to the original sender for verification. - /// - /// The temporary key received from the sender. - /// The client ID of the sender. - // Client sends back to local client private void SendSecretHashToSender(int tempKey, int senderClientId) { if (!BAUPlugin.SendBetterRpc.Value) return; int hash = SharedSecret.GetSharedSecretHash(); - // Logger.Log($"Sending secret hash: {hash} (tempKey: {tempKey})"); RPC.SendCustomRpcPacked(CustomRPC.CheckSecretHashFromPlayer, writer => { @@ -125,47 +99,30 @@ internal sealed class HandshakeHandler }, senderClientId); } - /// - /// Handles receiving a secret hash from another player for verification. - /// - /// MessageReader containing the temporary key and hash. internal void HandleSecretHashFromPlayer(MessageReader reader) { int tempKey = reader.ReadInt32(); int receivedHash = reader.ReadInt32(); + _pendingVerificationData = (tempKey, receivedHash); TryHandlePendingVerificationData(); } - /// - /// Attempts to verify pending handshake data if all required information is available. - /// internal void TryHandlePendingVerificationData() { - if (_pendingVerificationData?.tempKey == null || _pendingVerificationData?.receivedHash == null) return; + if (!_pendingVerificationData.HasValue) return; if (SharedSecret.GetSharedSecret().Length == 0) return; - var tempKey = _pendingVerificationData?.tempKey; - var receivedHash = _pendingVerificationData?.receivedHash; + var data = _pendingVerificationData.Value; - // Logger.Log($"Received hash check: TempKey={tempKey} (ours={SharedSecret.GetTempKey()}), Hash={receivedHash} (ours={SharedSecret.GetSharedSecretHash()})"); - - if (tempKey != SharedSecret.GetTempKey()) - { - // Logger.Warning($"Invalid tempKey from {_Data.PlayerName}"); + if (data.tempKey != SharedSecret.GetTempKey()) return; - } extendedData.IsBetterUser = true; - if (receivedHash == SharedSecret.GetSharedSecretHash()) + if (data.receivedHash == SharedSecret.GetSharedSecretHash()) { extendedData.IsVerifiedBetterUser = true; - // Logger.Log($"Verified player: {_Data.PlayerName}"); - } - else - { - // Logger.Warning($"Hash mismatch from {_Data.PlayerName}"); } _pendingVerificationData = null; @@ -174,8 +131,5 @@ internal sealed class HandshakeHandler private (int tempKey, int receivedHash)? _pendingVerificationData = null; private bool HasSendSharedSecret { get; set; } - /// - /// Gets the SharedSecretExchange instance for secure key exchange. - /// internal SharedSecretExchange SharedSecret { get; set; } = new(); } \ No newline at end of file diff --git a/src/Mono/ExtendedPlayerInfo.cs b/src/Mono/ExtendedPlayerInfo.cs index e306bd5..ac638d1 100644 --- a/src/Mono/ExtendedPlayerInfo.cs +++ b/src/Mono/ExtendedPlayerInfo.cs @@ -17,7 +17,7 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension= ExtendedAntiCheatInfo.MAX_RPC_SENT && !flag) { - BetterNotificationManager.NotifyCheat(_Data.Object, + BetterNotificationManager.NotifyCheat( + _Data.Object, Translator.GetString("AntiCheat.Reason.RPCSentPS"), Translator.GetString("AntiCheat.UnauthorizedAction") ); + Logger_.LogCheat($"{_Data.Object.BetterData().RealName} {AntiCheatInfo.RPCSentPS} Sent."); } timeAccumulator += time; + if (timeAccumulator >= 0.25f - 0.005 * AntiCheatInfo.RPCSentPS) { AntiCheatInfo.RPCSentPS -= 1; diff --git a/src/Mono/PlayerInfoDisplay.cs b/src/Mono/PlayerInfoDisplay.cs index 4fa73e6..9878b44 100644 --- a/src/Mono/PlayerInfoDisplay.cs +++ b/src/Mono/PlayerInfoDisplay.cs @@ -374,11 +374,8 @@ internal class PlayerInfoDisplay : MonoBehaviour } /// - /// Sets lobby-specific information. + /// Sets in-game specific information. /// - /// Reference to the player's name. - /// Extended player data. - /// StringBuilder for tag text. [HideFromIl2Cpp] private void SetLobbyInfo(ref string newName, ExtendedPlayerInfo betterData, StringBuilder sbTag) { @@ -389,10 +386,23 @@ internal class PlayerInfoDisplay : MonoBehaviour if ((_player.IsLocalPlayer() || betterData.IsBetterUser) && !GameState.IsInGamePlay) { - string verificationSymbol = betterData.IsVerifiedBetterUser || _player.IsLocalPlayer() ? "✓ " : ""; + string verificationSymbol; + + if (betterData.HandshakeHandler.SharedSecret.UseFallback) + { + // Fallback path (Linux or crypto unavailable) + verificationSymbol = betterData.IsVerifiedBetterUser ? "(Linux) ✓ " : "(Linux) "; + } + else + { + // Normal ECDH path + verificationSymbol = betterData.IsVerifiedBetterUser || _player.IsLocalPlayer() ? "✓ " : ""; + } + sbTag.AppendFormat("{1}{0}+++", _cachedTranslations.BetterUser, verificationSymbol); } + sbTag.Append($"ID: {_player.PlayerId}+++"); } diff --git a/src/Patches/Client/PrivateLobbyPatch.cs b/src/Patches/Client/PrivateLobbyPatch.cs index bdef56c..102050e 100644 --- a/src/Patches/Client/PrivateLobbyPatch.cs +++ b/src/Patches/Client/PrivateLobbyPatch.cs @@ -129,7 +129,7 @@ internal static class PrivateLobbyPatch var sprite = __instance.HostPrivateButton.transform.Find("Inactive")?.GetComponent(); if (sprite != null) { - sprite.color = new Color(0.35f, 1f, 1f, 1f); // Corrected color assignment + sprite.color = new Color(0.35f, 1f, 1f, 1f); } } } diff --git a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs index f2942bf..f307558 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs @@ -21,8 +21,6 @@ internal static class ChatPatch internal static void ClearChat() { if (!HudManager.InstanceExists) return; - - // Clear all chat bubbles HudManager.Instance.Chat.chatBubblePool.ReclaimAll(); } @@ -30,7 +28,6 @@ internal static class ChatPatch { if (!HudManager.InstanceExists) return; - // Clear only player chat bubbles (keep command bubbles) foreach (var obj in HudManager.Instance.Chat.chatBubblePool.activeChildren.ToArray()) { var chatBubble = obj.GetComponent(); @@ -40,6 +37,7 @@ internal static class ChatPatch HudManager.Instance.Chat.chatBubblePool.Reclaim(chatBubble); } } + HudManager.Instance.Chat.AlignAllBubbles(); } @@ -47,7 +45,6 @@ internal static class ChatPatch { if (!HudManager.InstanceExists) return; - // Clear only command chat bubbles (keep player chat) foreach (var obj in HudManager.Instance.Chat.chatBubblePool.activeChildren.ToArray()) { var chatBubble = obj.GetComponent(); @@ -57,14 +54,14 @@ internal static class ChatPatch HudManager.Instance.Chat.chatBubblePool.Reclaim(chatBubble); } } + HudManager.Instance.Chat.AlignAllBubbles(); } [HarmonyPatch(typeof(ChatController), nameof(ChatController.Toggle))] [HarmonyPostfix] - private static void ChatController_Toggle_Postfix(/*ChatController __instance*/) + private static void ChatController_Toggle_Postfix() { - // Apply chat theme when chat is opened/closed SetChatTheme(); } @@ -73,52 +70,45 @@ internal static class ChatPatch [HarmonyPriority(Priority.First)] private static void ChatController_Update_Prefix(ChatController __instance) { - // Apply dark/light theme to chat input field if (BAUPlugin.ChatDarkMode.Value) { - // Free chat color __instance.freeChatField.background.color = new Color32(40, 40, 40, byte.MaxValue); __instance.freeChatField.textArea.compoText.Color(Color.white); __instance.freeChatField.textArea.outputText.color = Color.white; } else { - // Free chat color __instance.freeChatField.background.color = new Color32(255, 255, 255, byte.MaxValue); __instance.freeChatField.textArea.compoText.Color(Color.black); __instance.freeChatField.textArea.outputText.color = Color.black; } - // Ctrl+X to cut text to clipboard if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.X)) { ClipboardHelper.PutClipboardString(__instance.freeChatField.textArea.text); __instance.freeChatField.textArea.SetText(""); } - // Up arrow for chat history navigation if (Input.GetKeyDown(KeyCode.UpArrow) && ChatHistory.Any()) { CurrentHistorySelection = Mathf.Clamp(--CurrentHistorySelection, 0, ChatHistory.Count - 1); __instance.freeChatField.textArea.SetText(ChatHistory[CurrentHistorySelection]); } - // Down arrow for chat history navigation if (Input.GetKeyDown(KeyCode.DownArrow) && ChatHistory.Any()) { CurrentHistorySelection++; if (CurrentHistorySelection < ChatHistory.Count) __instance.freeChatField.textArea.SetText(ChatHistory[CurrentHistorySelection]); - else __instance.freeChatField.textArea.SetText(""); + else + __instance.freeChatField.textArea.SetText(""); } } - // Log chat messages to console [HarmonyPatch(typeof(ChatController), nameof(ChatController.AddChat))] [HarmonyPostfix] private static void ChatController_AddChat_Postfix(ChatController __instance, PlayerControl sourcePlayer, string chatText) { - // Log chat publicly if player is alive, privately if dead if (sourcePlayer.IsAlive() || !PlayerControl.LocalPlayer.IsAlive()) { Logger_.Log($"{sourcePlayer.Data.PlayerName} -> {chatText}", "ChatLog"); @@ -134,13 +124,11 @@ internal static class ChatPatch private static void ChatController_SetChatBubbleName_Postfix(ChatController __instance, ChatBubble bubble, NetworkedPlayerInfo playerInfo, bool isDead, bool didVote) { if (didVote) return; - if (bubble == null) return; - if (bubble.NameText == null) return; - if (playerInfo == null) return; + if (bubble == null || bubble.NameText == null || playerInfo == null) return; var sourcePlayer = playerInfo.Object; - if (sourcePlayer == null) return; - if (PlayerControl.LocalPlayer == null) return; + var localPlayer = PlayerControl.LocalPlayer; + if (sourcePlayer == null || localPlayer == null) return; StringBuilder sbTag = new(); StringBuilder sbInfo = new(); @@ -159,7 +147,13 @@ internal static class ChatPatch if (betterData == null) return; if (sourcePlayer.IsLocalPlayer() || betterData.IsBetterUser) - sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); + { + sbTag.AppendFormat( + "{1}{0}+++", + Translator.GetString("Player.BetterUser"), + betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : "" + ); + } if (BetterDataManager.BetterDataFile.SickoData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) sbTag.Append($"{Translator.GetString("Player.SickoUser")}+++"); @@ -173,41 +167,34 @@ internal static class ChatPatch if (!sourcePlayer.IsImpostorTeammate()) { - if (PlayerControl.LocalPlayer.IsAlive() && !sourcePlayer.IsLocalPlayer()) - { + if (localPlayer.IsAlive() && !sourcePlayer.IsLocalPlayer()) Role = ""; - } } - if (PlayerControl.LocalPlayer.Is(RoleTypes.GuardianAngel) && !sourcePlayer.IsAlive() || !PlayerControl.LocalPlayer.Is(RoleTypes.GuardianAngel)) + if ((localPlayer.Is(RoleTypes.GuardianAngel) && !sourcePlayer.IsAlive()) || !localPlayer.Is(RoleTypes.GuardianAngel)) { sbTag.Append(Role); } sbInfo.Append(""); var parts = sbTag.ToString().Split("+++"); + for (int i = 0; i < parts.Length; i++) { - if (!string.IsNullOrEmpty(parts[i])) - { - sbInfo.Append(parts[i]); - if (i != parts.Length - 2) - { - sbInfo.Append(" - "); - } - } + if (string.IsNullOrEmpty(parts[i])) continue; + + sbInfo.Append(parts[i]); + + if (i != parts.Length - 2) + sbInfo.Append(" - "); } + sbInfo.Append(""); - bool flag = sourcePlayer.IsLocalPlayer(); - if (flag) - { - playerName = $"{sbInfo} " + playerName; - } + if (sourcePlayer.IsLocalPlayer()) + playerName = sbInfo + " " + playerName; else - { - playerName += $" {sbInfo}"; - } + playerName += " " + sbInfo; bubble.NameText.SetText(playerName); } @@ -225,63 +212,51 @@ internal static class ChatPatch if (BAUPlugin.ChatDarkMode.Value) { - // Quick chat color chat.quickChatField.background.color = new Color32(40, 40, 40, byte.MaxValue); chat.quickChatField.text.color = Color.white; - // Icons chat.quickChatButton.transform.Find("QuickChatIcon").GetComponent().color = new Color(0.5f, 0.5f, 0.5f, 1f); chat.openKeyboardButton.transform.Find("OpenKeyboardIcon").GetComponent().color = new Color(0.5f, 0.5f, 0.5f, 1f); } else { - // Quick chat color chat.quickChatField.background.color = new Color32(255, 255, 255, byte.MaxValue); chat.quickChatField.text.color = Color.black; - // Icons chat.quickChatButton.transform.Find("QuickChatIcon").GetComponent().color = new Color(1f, 1f, 1f, 1f); chat.openKeyboardButton.transform.Find("OpenKeyboardIcon").GetComponent().color = new Color(1f, 1f, 1f, 1f); } - // Apply theme to all existing chat bubbles foreach (var item in HudManager.Instance.Chat.chatBubblePool.activeChildren.SelectIl2Cpp(c => c.GetComponent())) { SetChatPoolTheme(item); } } - // Apply theme to individual chat bubble internal static ChatBubble SetChatPoolTheme(ChatBubble asChatBubble) { - ChatBubble chatBubble = asChatBubble; + var chatBubble = asChatBubble; if (BAUPlugin.ChatDarkMode.Value) { - chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 1f); + chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = Color.white; chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(0.15f, 0.15f, 0.15f, 1f); - // Make dead player chat bubbles more transparent - if (chatBubble.transform.Find("PoolablePlayer/xMark") != null) + var mark = chatBubble.transform.Find("PoolablePlayer/xMark"); + if (mark != null && mark.GetComponentInChildren(true).enabled) { - if (chatBubble.transform.Find("PoolablePlayer/xMark").GetComponentInChildren(true).enabled == true) - { - chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(0.15f, 0.15f, 0.15f, 0.5f); - } + chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(0.15f, 0.15f, 0.15f, 0.5f); } } else { - chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = new Color(0f, 0f, 0f, 1f); - chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 1f); + chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = Color.black; + chatBubble.transform.Find("Background").GetComponentInChildren(true).color = Color.white; - // Make dead player chat bubbles more transparent - if (chatBubble.transform.Find("PoolablePlayer/xMark") != null) + var mark = chatBubble.transform.Find("PoolablePlayer/xMark"); + if (mark != null && mark.GetComponentInChildren(true).enabled) { - if (chatBubble.transform.Find("PoolablePlayer/xMark").GetComponentInChildren(true).enabled == true) - { - chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 0.5f); - } + chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 0.5f); } } @@ -292,7 +267,6 @@ internal static class ChatPatch [HarmonyPostfix] private static void FreeChatInputField_Awake_Postfix(FreeChatInputField __instance) { - // Enable extended character support for chat __instance.textArea.allowAllCharacters = true; __instance.textArea.AllowSymbols = true; __instance.textArea.AllowPaste = true; @@ -305,7 +279,6 @@ internal static class ChatPatch [HarmonyPostfix] private static void FreeChatInputField_UpdateCharCount_Postfix(FreeChatInputField __instance) { - // Update character counter with color coding int length = __instance.textArea.text.Length; __instance.charCountText.text = string.Format("{0}/118", length); __instance.charCountText.color = GetCharColor(length); @@ -313,14 +286,7 @@ internal static class ChatPatch private static Color GetCharColor(int length) { - // Color gradient: green -> yellow -> red as text length increases - Color[] colorGradient = - [ - Color.green, - Color.yellow, - Color.red - ]; - + Color[] colorGradient = [Color.green, Color.yellow, Color.red]; (float min, float max) lerpRange = (0f, 117f); return colorGradient.LerpColor(lerpRange, length); } From abc7427a8d1ba2877bafed805f546ebbf6b6f52d Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Tue, 17 Mar 2026 10:14:47 +0000 Subject: [PATCH 07/11] Removed linux Identifier --- src/Mono/PlayerInfoDisplay.cs | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/src/Mono/PlayerInfoDisplay.cs b/src/Mono/PlayerInfoDisplay.cs index 9878b44..95d0fc8 100644 --- a/src/Mono/PlayerInfoDisplay.cs +++ b/src/Mono/PlayerInfoDisplay.cs @@ -379,30 +379,13 @@ internal class PlayerInfoDisplay : MonoBehaviour [HideFromIl2Cpp] private void SetLobbyInfo(ref string newName, ExtendedPlayerInfo betterData, StringBuilder sbTag) { - if (betterData == null) return; - - if (_player.IsHost() && BAUPlugin.LobbyPlayerInfo.Value) - newName = _player.GetPlayerNameAndColor(); - if ((_player.IsLocalPlayer() || betterData.IsBetterUser) && !GameState.IsInGamePlay) { - string verificationSymbol; - - if (betterData.HandshakeHandler.SharedSecret.UseFallback) - { - // Fallback path (Linux or crypto unavailable) - verificationSymbol = betterData.IsVerifiedBetterUser ? "(Linux) ✓ " : "(Linux) "; - } - else - { - // Normal ECDH path - verificationSymbol = betterData.IsVerifiedBetterUser || _player.IsLocalPlayer() ? "✓ " : ""; - } + string verificationSymbol = betterData.IsVerifiedBetterUser || _player.IsLocalPlayer() ? "✓ " : ""; sbTag.AppendFormat("{1}{0}+++", _cachedTranslations.BetterUser, verificationSymbol); } - sbTag.Append($"ID: {_player.PlayerId}+++"); } From 3b4953bddfad3fbbb542c8dc52bbfc2044e8de03 Mon Sep 17 00:00:00 2001 From: DeveloperNyx Date: Tue, 17 Mar 2026 10:25:09 +0000 Subject: [PATCH 08/11] Fixed removal of comments --- src/Patches/Client/PrivateLobbyPatch.cs | 2 +- src/Patches/Gameplay/UI/Chat/ChatPatch.cs | 42 +++++++++++++---------- 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/Patches/Client/PrivateLobbyPatch.cs b/src/Patches/Client/PrivateLobbyPatch.cs index 102050e..55e4a08 100644 --- a/src/Patches/Client/PrivateLobbyPatch.cs +++ b/src/Patches/Client/PrivateLobbyPatch.cs @@ -129,7 +129,7 @@ internal static class PrivateLobbyPatch var sprite = __instance.HostPrivateButton.transform.Find("Inactive")?.GetComponent(); if (sprite != null) { - sprite.color = new Color(0.35f, 1f, 1f, 1f); + sprite.color = new Color(0.35f, 1f, 1f, 1f); // Corrected colour assignment } } } diff --git a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs index f307558..a76ddfd 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs @@ -21,6 +21,8 @@ internal static class ChatPatch internal static void ClearChat() { if (!HudManager.InstanceExists) return; + + // Clear all chat bubbles HudManager.Instance.Chat.chatBubblePool.ReclaimAll(); } @@ -28,6 +30,7 @@ internal static class ChatPatch { if (!HudManager.InstanceExists) return; + // Clear only player chat bubbles (keep command bubbles) foreach (var obj in HudManager.Instance.Chat.chatBubblePool.activeChildren.ToArray()) { var chatBubble = obj.GetComponent(); @@ -37,14 +40,13 @@ internal static class ChatPatch HudManager.Instance.Chat.chatBubblePool.Reclaim(chatBubble); } } - HudManager.Instance.Chat.AlignAllBubbles(); } internal static void ClearCommands() { if (!HudManager.InstanceExists) return; - + // Clear only command chat bubbles (keep player chat) foreach (var obj in HudManager.Instance.Chat.chatBubblePool.activeChildren.ToArray()) { var chatBubble = obj.GetComponent(); @@ -54,7 +56,6 @@ internal static class ChatPatch HudManager.Instance.Chat.chatBubblePool.Reclaim(chatBubble); } } - HudManager.Instance.Chat.AlignAllBubbles(); } @@ -62,6 +63,7 @@ internal static class ChatPatch [HarmonyPostfix] private static void ChatController_Toggle_Postfix() { + // Apply chat theme when chat is opened/closed SetChatTheme(); } @@ -70,45 +72,48 @@ internal static class ChatPatch [HarmonyPriority(Priority.First)] private static void ChatController_Update_Prefix(ChatController __instance) { + // Apply dark/light theme to chat input field if (BAUPlugin.ChatDarkMode.Value) { + // Free chat color __instance.freeChatField.background.color = new Color32(40, 40, 40, byte.MaxValue); __instance.freeChatField.textArea.compoText.Color(Color.white); __instance.freeChatField.textArea.outputText.color = Color.white; } else { + // Free chat color __instance.freeChatField.background.color = new Color32(255, 255, 255, byte.MaxValue); __instance.freeChatField.textArea.compoText.Color(Color.black); __instance.freeChatField.textArea.outputText.color = Color.black; } - + // Ctrl+x to cut text to clipboard if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.X)) { ClipboardHelper.PutClipboardString(__instance.freeChatField.textArea.text); __instance.freeChatField.textArea.SetText(""); } - + // Up arrow for chat history navigation if (Input.GetKeyDown(KeyCode.UpArrow) && ChatHistory.Any()) { CurrentHistorySelection = Mathf.Clamp(--CurrentHistorySelection, 0, ChatHistory.Count - 1); __instance.freeChatField.textArea.SetText(ChatHistory[CurrentHistorySelection]); } - + // Down arrow for chat history navigation if (Input.GetKeyDown(KeyCode.DownArrow) && ChatHistory.Any()) { CurrentHistorySelection++; if (CurrentHistorySelection < ChatHistory.Count) __instance.freeChatField.textArea.SetText(ChatHistory[CurrentHistorySelection]); - else - __instance.freeChatField.textArea.SetText(""); + else __instance.freeChatField.textArea.SetText(""); } } - + // Log chat messages to console [HarmonyPatch(typeof(ChatController), nameof(ChatController.AddChat))] [HarmonyPostfix] private static void ChatController_AddChat_Postfix(ChatController __instance, PlayerControl sourcePlayer, string chatText) { + // Log chat publicly if player is alive, privately if dead if (sourcePlayer.IsAlive() || !PlayerControl.LocalPlayer.IsAlive()) { Logger_.Log($"{sourcePlayer.Data.PlayerName} -> {chatText}", "ChatLog"); @@ -148,11 +153,7 @@ internal static class ChatPatch if (sourcePlayer.IsLocalPlayer() || betterData.IsBetterUser) { - sbTag.AppendFormat( - "{1}{0}+++", - Translator.GetString("Player.BetterUser"), - betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : "" - ); + sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); } if (BetterDataManager.BetterDataFile.SickoData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) @@ -212,27 +213,29 @@ internal static class ChatPatch if (BAUPlugin.ChatDarkMode.Value) { + // Quick chat color chat.quickChatField.background.color = new Color32(40, 40, 40, byte.MaxValue); chat.quickChatField.text.color = Color.white; - + // Icons chat.quickChatButton.transform.Find("QuickChatIcon").GetComponent().color = new Color(0.5f, 0.5f, 0.5f, 1f); chat.openKeyboardButton.transform.Find("OpenKeyboardIcon").GetComponent().color = new Color(0.5f, 0.5f, 0.5f, 1f); } else { + // Quick chat color chat.quickChatField.background.color = new Color32(255, 255, 255, byte.MaxValue); chat.quickChatField.text.color = Color.black; - + // Icons chat.quickChatButton.transform.Find("QuickChatIcon").GetComponent().color = new Color(1f, 1f, 1f, 1f); chat.openKeyboardButton.transform.Find("OpenKeyboardIcon").GetComponent().color = new Color(1f, 1f, 1f, 1f); } - + // Apply theme to all existing chat bubbles foreach (var item in HudManager.Instance.Chat.chatBubblePool.activeChildren.SelectIl2Cpp(c => c.GetComponent())) { SetChatPoolTheme(item); } } - + // Apply theme to individual chat bubble internal static ChatBubble SetChatPoolTheme(ChatBubble asChatBubble) { var chatBubble = asChatBubble; @@ -267,6 +270,7 @@ internal static class ChatPatch [HarmonyPostfix] private static void FreeChatInputField_Awake_Postfix(FreeChatInputField __instance) { + // Enable extended character support for chat __instance.textArea.allowAllCharacters = true; __instance.textArea.AllowSymbols = true; __instance.textArea.AllowPaste = true; @@ -279,6 +283,7 @@ internal static class ChatPatch [HarmonyPostfix] private static void FreeChatInputField_UpdateCharCount_Postfix(FreeChatInputField __instance) { + // Update character counter with color coding int length = __instance.textArea.text.Length; __instance.charCountText.text = string.Format("{0}/118", length); __instance.charCountText.color = GetCharColor(length); @@ -286,6 +291,7 @@ internal static class ChatPatch private static Color GetCharColor(int length) { + // Color gradient: green -> yellow -> red as text length increases Color[] colorGradient = [Color.green, Color.yellow, Color.red]; (float min, float max) lerpRange = (0f, 117f); return colorGradient.LerpColor(lerpRange, length); From 17fed3cb0737af6399526b8face92fd6b46ac997 Mon Sep 17 00:00:00 2001 From: D1GQ <83262852+D1GQ@users.noreply.github.com> Date: Tue, 17 Mar 2026 14:10:39 -0500 Subject: [PATCH 09/11] Add back xml to SharedSecretExchange --- src/Data/SharedSecretExchange.cs | 56 +++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/Data/SharedSecretExchange.cs b/src/Data/SharedSecretExchange.cs index 87115dd..c208b2d 100644 --- a/src/Data/SharedSecretExchange.cs +++ b/src/Data/SharedSecretExchange.cs @@ -3,6 +3,9 @@ using System.Security.Cryptography; namespace BetterAmongUs.Data; +/// +/// Handles secure key exchange using Elliptic Curve Diffie-Hellman (ECDH) for establishing shared secrets. +/// internal sealed class SharedSecretExchange { private readonly ECDiffieHellman dh; @@ -11,11 +14,21 @@ internal sealed class SharedSecretExchange private byte[] sharedSecret = []; private bool cryptoDisabled; + /// + /// Gets a value indicating whether cryptographic operations are available. + /// internal bool CryptoAvailable => !cryptoDisabled; + + /// + /// Gets or sets a value indicating whether to use the fallback key exchange mechanism. + /// internal bool UseFallback { get; set; } private int? remoteTempKey; + /// + /// Initializes a new instance of the SharedSecretExchange class with a new ECDH key pair. + /// internal SharedSecretExchange() { try @@ -35,6 +48,10 @@ internal sealed class SharedSecretExchange tempKey = GenerateSecureTempKey(); } + /// + /// Generates a cryptographically secure random temporary key. + /// + /// A random positive integer used as a temporary key. private static int GenerateSecureTempKey() { byte[] buffer = new byte[4]; @@ -42,27 +59,48 @@ internal sealed class SharedSecretExchange return Math.Abs(BitConverter.ToInt32(buffer, 0)); } + /// + /// Sets the temporary key received from the remote party. + /// + /// The temporary key from the remote party. internal void SetRemoteTempKey(int key) { remoteTempKey = key; } + /// + /// Gets the public key for key exchange. + /// + /// The public key in SubjectPublicKeyInfo format, or an empty array if cryptography is disabled. internal byte[] GetPublicKey() { if (cryptoDisabled) return []; return publicKey; } + /// + /// Gets the temporary key used for initial communication. + /// + /// A random integer used as a temporary key. internal int GetTempKey() { return tempKey; } + /// + /// Gets the established shared secret. + /// + /// The shared secret byte array. internal byte[] GetSharedSecret() { return sharedSecret; } + /// + /// Generates a shared secret using another party's public key. + /// + /// The other party's public key in SubjectPublicKeyInfo format. + /// The shared secret byte array, or an empty array if generation fails. internal byte[] GenerateSharedSecret(byte[] otherPartyPublicKey) { if (sharedSecret.Length > 0) return sharedSecret; @@ -96,6 +134,10 @@ internal sealed class SharedSecretExchange } } + /// + /// Gets a numeric hash of the shared secret for verification purposes. + /// + /// A 32-bit integer hash of the shared secret, or 0 if no shared secret exists. internal int GetSharedSecretHash() { if (sharedSecret.Length == 0) return 0; @@ -111,6 +153,12 @@ internal sealed class SharedSecretExchange return Math.Abs(numericHash); } + /// + /// Derives a fallback shared secret using temporary keys when ECDH is unavailable. + /// + /// The local temporary key. + /// The remote temporary key. + /// A 256-bit hash derived from the ordered temporary keys. private static byte[] DeriveFallbackSecret(int local, int remote) { using SHA256 sha256 = SHA256.Create(); @@ -126,8 +174,14 @@ internal sealed class SharedSecretExchange return sha256.ComputeHash(buffer); } + /// + /// Gets a value indicating whether the key exchange data has been cleared for security. + /// internal bool HasBeenCleared { get; private set; } + /// + /// Clears all sensitive key exchange data for security purposes. + /// internal void ClearData() { if (HasBeenCleared) return; @@ -136,4 +190,4 @@ internal sealed class SharedSecretExchange tempKey = 0; sharedSecret = []; } -} \ No newline at end of file +} From 62b6e328d56768ee3ba4f15f2aa98fd0f5e42b7d Mon Sep 17 00:00:00 2001 From: D1GQ <83262852+D1GQ@users.noreply.github.com> Date: Tue, 17 Mar 2026 14:20:19 -0500 Subject: [PATCH 10/11] Add xml back to HandshakeHandler --- src/Modules/HandshakeHandler.cs | 60 +++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/src/Modules/HandshakeHandler.cs b/src/Modules/HandshakeHandler.cs index 3bd3889..2db7f3b 100644 --- a/src/Modules/HandshakeHandler.cs +++ b/src/Modules/HandshakeHandler.cs @@ -1,4 +1,4 @@ -using BepInEx.Unity.IL2CPP.Utils; +using BepInEx.Unity.IL2CPP.Utils; using BetterAmongUs.Data; using BetterAmongUs.Data.Config; using BetterAmongUs.Enums; @@ -12,6 +12,9 @@ using UnityEngine; namespace BetterAmongUs.Modules; +/// +/// Handles the secure handshake process between BetterAmongUs clients using Diffie-Hellman key exchange. +/// internal sealed class HandshakeHandler { [HideFromIl2Cpp] @@ -23,11 +26,17 @@ internal sealed class HandshakeHandler [HideFromIl2Cpp] private ExtendedPlayerInfo extendedData { get; } + /// + /// Initiates the wait period before sending the secret to another player. + /// internal void WaitSendSecretToPlayer() { extendedData.StartCoroutine(CoWaitSendSecretToPlayer()); } + /// + /// Coroutine that waits for player initialization before sending the secret. + /// private IEnumerator CoWaitSendSecretToPlayer() { if (!BAUConfigs.SendBetterRpc.Value) yield break; @@ -42,6 +51,9 @@ internal sealed class HandshakeHandler SendSecretToPlayer(); } + /// + /// Resends the secret to the player if not already verified. + /// internal void ResendSecretToPlayer() { if (!BAUConfigs.SendBetterRpc.Value) return; @@ -51,6 +63,10 @@ internal sealed class HandshakeHandler SendSecretToPlayer(); } + /// + /// Sends the local client's public key and temporary key to another player. + /// + // Local client sends to client private void SendSecretToPlayer() { if (extendedData._Data.Object.IsLocalPlayer()) return; @@ -66,6 +82,11 @@ internal sealed class HandshakeHandler }, extendedData._Data.ClientId); } + /// + /// Handles receiving a secret from another player and generates a shared secret. + /// + /// MessageReader containing the sender's public key and temporary key. + // Client receives from local client internal void HandleSecretFromSender(MessageReader reader) { if (extendedData._Data?.Object?.IsLocalPlayer() == true) return; @@ -74,11 +95,17 @@ internal sealed class HandshakeHandler byte[] sendersPublicKey = reader.ReadBytes(); int tempKey = reader.ReadInt32(); + // Logger.Log($"Received public key ({sendersPublicKey.Length} bytes) from {_Data.PlayerName}"); + SharedSecret.UseFallback = !senderSupportsCrypto; SharedSecret.SetRemoteTempKey(tempKey); byte[] secret = SharedSecret.GenerateSharedSecret(sendersPublicKey); - if (secret.Length == 0) return; + if (secret.Length == 0) + { + // Logger.Error("Failed to generate shared secret!"); + return; + } extendedData.IsBetterUser = true; @@ -87,11 +114,18 @@ internal sealed class HandshakeHandler ResendSecretToPlayer(); } + /// + /// Sends the hash of the generated shared secret back to the original sender for verification. + /// + /// The temporary key received from the sender. + /// The client ID of the sender. + // Client sends back to local client private void SendSecretHashToSender(int tempKey, int senderClientId) { if (!BAUConfigs.SendBetterRpc.Value) return; int hash = SharedSecret.GetSharedSecretHash(); + // Logger.Log($"Sending secret hash: {hash} (tempKey: {tempKey})"); RPC.SendCustomRpcPacked(CustomRPC.CheckSecretHashFromPlayer, writer => { @@ -100,6 +134,10 @@ internal sealed class HandshakeHandler }, senderClientId); } + /// + /// Handles receiving a secret hash from another player for verification. + /// + /// MessageReader containing the temporary key and hash. internal void HandleSecretHashFromPlayer(MessageReader reader) { int tempKey = reader.ReadInt32(); @@ -109,6 +147,9 @@ internal sealed class HandshakeHandler TryHandlePendingVerificationData(); } + /// + /// Attempts to verify pending handshake data if all required information is available. + /// internal void TryHandlePendingVerificationData() { if (!_pendingVerificationData.HasValue) return; @@ -116,14 +157,24 @@ internal sealed class HandshakeHandler var data = _pendingVerificationData.Value; + // Logger.Log($"Received hash check: TempKey={data.tempKey} (ours={SharedSecret.GetTempKey()}), Hash={data.receivedHash} (ours={SharedSecret.GetSharedSecretHash()})"); + if (data.tempKey != SharedSecret.GetTempKey()) + { + // Logger.Warning($"Invalid tempKey from {extendedData._Data?.PlayerName}"); return; + } extendedData.IsBetterUser = true; if (data.receivedHash == SharedSecret.GetSharedSecretHash()) { extendedData.IsVerifiedBetterUser = true; + // Logger.Log($"Verified player: {extendedData._Data?.PlayerName}"); + } + else + { + // Logger.Warning($"Hash mismatch from {extendedData._Data?.PlayerName}"); } _pendingVerificationData = null; @@ -132,5 +183,8 @@ internal sealed class HandshakeHandler private (int tempKey, int receivedHash)? _pendingVerificationData = null; private bool HasSendSharedSecret { get; set; } + /// + /// Gets the SharedSecretExchange instance for secure key exchange. + /// internal SharedSecretExchange SharedSecret { get; set; } = new(); -} \ No newline at end of file +} From ba57b7c43edc549e45883f4c7a634f3f6ba046d8 Mon Sep 17 00:00:00 2001 From: D1GQ <83262852+D1GQ@users.noreply.github.com> Date: Tue, 17 Mar 2026 14:32:06 -0500 Subject: [PATCH 11/11] Add comments back --- src/Patches/Gameplay/UI/Chat/ChatPatch.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs index 7c6b57e..f17f4dc 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs @@ -143,8 +143,10 @@ internal static class ChatPatch string friendCode = playerInfo.FriendCode; string playerName = playerInfo.BetterData()?.RealName ?? "???"; + // Format role display with team color string Role = $"{sourcePlayer.GetRoleName()}+++"; + // In lobby, show player tags instead of roles if (GameState.IsLobby && !GameState.IsFreePlay) { Role = ""; @@ -152,11 +154,13 @@ internal static class ChatPatch var betterData = sourcePlayer.BetterData(); if (betterData == null) return; + // Show BAU user tag if (sourcePlayer.IsLocalPlayer() || betterData.IsBetterUser) { sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); } + // Show mod-specific tags based on player data if (BetterDataManager.BetterDataFile.SickoData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) sbTag.Append($"{Translator.GetString("Player.SickoUser")}+++"); else if (BetterDataManager.BetterDataFile.AUMData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) @@ -167,17 +171,20 @@ internal static class ChatPatch sbTag.Append($"{Translator.GetString("Player.KnownCheater")}+++"); } + // Hide roles from alive players (unless same team) if (!sourcePlayer.IsImpostorTeammate()) { if (localPlayer.IsAlive() && !sourcePlayer.IsLocalPlayer()) Role = ""; } + // Show role for dead players or if local player is Guardian Angel if ((localPlayer.Is(RoleTypes.GuardianAngel) && !sourcePlayer.IsAlive()) || !localPlayer.Is(RoleTypes.GuardianAngel)) { sbTag.Append(Role); } + // Format tags with separators sbInfo.Append(""); var parts = sbTag.ToString().Split("+++"); @@ -193,6 +200,7 @@ internal static class ChatPatch sbInfo.Append(""); + // Position tags before local player name, after other players' names if (sourcePlayer.IsLocalPlayer()) playerName = sbInfo + " " + playerName; else @@ -297,4 +305,4 @@ internal static class ChatPatch (float min, float max) lerpRange = (0f, 117f); return colorGradient.LerpColor(lerpRange, length); } -} \ No newline at end of file +}