From 0de301bfd62f3bb2f816dcaa292c494cae807af1 Mon Sep 17 00:00:00 2001 From: Aizistral Date: Mon, 2 Jan 2023 20:28:03 +0100 Subject: Figure this shit out, more or less --- .../com/aizistral/nochatreports/NoChatReports.java | 34 --- .../nochatreports/NoChatReportsClient.java | 105 -------- .../aizistral/nochatreports/common/NCRClient.java | 98 +++++++ .../aizistral/nochatreports/common/NCRCore.java | 50 ++++ .../nochatreports/common/config/JSONConfig.java | 106 ++++++++ .../common/config/ModMenuIntegration.java | 275 ++++++++++++++++++++ .../nochatreports/common/config/NCRConfig.java | 84 ++++++ .../common/config/NCRConfigClient.java | 207 +++++++++++++++ .../common/config/NCRConfigCommon.java | 74 ++++++ .../common/config/NCRConfigEncryption.java | 189 ++++++++++++++ .../common/config/NCRServerPreferences.java | 67 +++++ .../common/config/ServerAddressAdapter.java | 36 +++ .../nochatreports/common/core/EncryptionUtil.java | 76 ++++++ .../common/core/ServerDataExtension.java | 23 ++ .../common/core/ServerSafetyLevel.java | 69 +++++ .../common/core/ServerSafetyState.java | 105 ++++++++ .../nochatreports/common/core/SigningMode.java | 105 ++++++++ .../common/encryption/AESCFB8Encryption.java | 25 ++ .../common/encryption/AESCFB8Encryptor.java | 43 ++++ .../common/encryption/AESECBEncryption.java | 25 ++ .../common/encryption/AESECBEncryptor.java | 30 +++ .../common/encryption/AESEncryption.java | 93 +++++++ .../common/encryption/AESEncryptor.java | 113 ++++++++ .../common/encryption/AESGCMEncryption.java | 25 ++ .../common/encryption/AESGCMEncryptor.java | 37 +++ .../common/encryption/CaesarEncryption.java | 56 ++++ .../common/encryption/CaesarEncryptor.java | 70 +++++ .../common/encryption/Encryption.java | 59 +++++ .../nochatreports/common/encryption/Encryptor.java | 182 +++++++++++++ .../common/gui/AdaptiveWarningScreen.java | 78 ++++++ .../common/gui/AdvancedImageButton.java | 41 +++ .../nochatreports/common/gui/AdvancedTooltip.java | 183 +++++++++++++ .../nochatreports/common/gui/EncryptionButton.java | 40 +++ .../common/gui/EncryptionConfigScreen.java | 283 +++++++++++++++++++++ .../common/gui/EncryptionWarningScreen.java | 43 ++++ .../nochatreports/common/gui/FontHelper.java | 152 +++++++++++ .../nochatreports/common/gui/InvisibleButton.java | 24 ++ .../common/gui/RealmsWarningScreen.java | 42 +++ .../common/gui/TriageWarningScreen.java | 45 ++++ .../common/gui/UnsafeServerScreen.java | 58 +++++ .../common/mixins/client/MixinChatComponent.java | 75 ++++++ .../common/mixins/client/MixinChatListener.java | 117 +++++++++ .../mixins/client/MixinChatOptionsScreen.java | 42 +++ .../common/mixins/client/MixinChatScreen.java | 208 +++++++++++++++ .../mixins/client/MixinClientPacketListener.java | 41 +++ .../common/mixins/client/MixinConnectScreen.java | 44 ++++ .../common/mixins/client/MixinGuiMessageTag.java | 29 +++ .../mixins/client/MixinGuiMessageTagIcon.java | 47 ++++ .../mixins/client/MixinJoinMultiplayerScreen.java | 72 ++++++ .../common/mixins/client/MixinMinecraft.java | 47 ++++ .../mixins/client/MixinOnlineServerEntry.java | 64 +++++ .../common/mixins/client/MixinOptions.java | 43 ++++ .../common/mixins/client/MixinPlayerEntry.java | 51 ++++ .../common/mixins/client/MixinRealmsConnect.java | 34 +++ .../common/mixins/client/MixinRowHelper.java | 26 ++ .../common/mixins/client/MixinServerData.java | 46 ++++ .../mixins/client/MixinServerStatusPinger$1.java | 55 ++++ .../common/mixins/client/MixinTitleScreen.java | 31 +++ .../common/mixins/client/MixinToastComponent.java | 26 ++ .../client/MixinYggdrasilUserApiService.java | 29 +++ .../common/mixins/common/MixinServerStatus.java | 53 ++++ .../mixins/common/MixinServerStatusSerializer.java | 54 ++++ .../common/mixins/server/MixinDedicatedServer.java | 24 ++ .../common/mixins/server/MixinPlayerList.java | 24 ++ .../server/MixinServerGamePacketListenerImpl.java | 74 ++++++ .../mixins/server/MixinServerboundChatPacket.java | 26 ++ .../MixinServerboundChatSessionUpdatePacket.java | 36 +++ .../common/platform/PlatformProvider.java | 16 ++ .../common/platform/events/ClientEvents.java | 23 ++ .../common/platform/events/PlatformEvent.java | 37 +++ .../platform/events/particular/Disconnect.java | 11 + .../platform/events/particular/PlayReady.java | 11 + .../aizistral/nochatreports/config/JSONConfig.java | 111 -------- .../nochatreports/config/ModMenuIntegration.java | 276 -------------------- .../aizistral/nochatreports/config/NCRConfig.java | 90 ------- .../nochatreports/config/NCRConfigClient.java | 209 --------------- .../nochatreports/config/NCRConfigCommon.java | 77 ------ .../nochatreports/config/NCRConfigEncryption.java | 191 -------------- .../nochatreports/config/NCRServerPreferences.java | 74 ------ .../nochatreports/config/ServerAddressAdapter.java | 36 --- .../nochatreports/core/EncryptionUtil.java | 76 ------ .../nochatreports/core/ServerDataExtension.java | 23 -- .../nochatreports/core/ServerSafetyLevel.java | 73 ------ .../nochatreports/core/ServerSafetyState.java | 107 -------- .../aizistral/nochatreports/core/SigningMode.java | 108 -------- .../encryption/AESCFB8Encryption.java | 28 -- .../nochatreports/encryption/AESCFB8Encryptor.java | 47 ---- .../nochatreports/encryption/AESECBEncryption.java | 28 -- .../nochatreports/encryption/AESECBEncryptor.java | 34 --- .../nochatreports/encryption/AESEncryption.java | 95 ------- .../nochatreports/encryption/AESEncryptor.java | 111 -------- .../nochatreports/encryption/AESGCMEncryption.java | 28 -- .../nochatreports/encryption/AESGCMEncryptor.java | 41 --- .../nochatreports/encryption/CaesarEncryption.java | 59 ----- .../nochatreports/encryption/CaesarEncryptor.java | 74 ------ .../nochatreports/encryption/Encryption.java | 66 ----- .../nochatreports/encryption/Encryptor.java | 184 -------------- .../nochatreports/fabric/NoChatReports.java | 35 +++ .../nochatreports/fabric/NoChatReportsClient.java | 22 ++ .../fabric/mixins/MixinMinecraft.java | 20 ++ .../nochatreports/gui/AdaptiveWarningScreen.java | 83 ------ .../nochatreports/gui/AdvancedImageButton.java | 41 --- .../nochatreports/gui/AdvancedTooltip.java | 178 ------------- .../nochatreports/gui/EncryptionButton.java | 44 ---- .../nochatreports/gui/EncryptionConfigScreen.java | 280 -------------------- .../nochatreports/gui/EncryptionWarningScreen.java | 45 ---- .../aizistral/nochatreports/gui/FontHelper.java | 152 ----------- .../nochatreports/gui/InvisibleButton.java | 23 -- .../nochatreports/gui/RealmsWarningScreen.java | 43 ---- .../nochatreports/gui/TriageWarningScreen.java | 49 ---- .../nochatreports/gui/UnsafeServerScreen.java | 71 ------ .../mixins/client/MixinChatComponent.java | 73 ------ .../mixins/client/MixinChatListener.java | 116 --------- .../mixins/client/MixinChatOptionsScreen.java | 47 ---- .../mixins/client/MixinChatScreen.java | 218 ---------------- .../mixins/client/MixinClientPacketListener.java | 39 --- .../mixins/client/MixinConnectScreen.java | 43 ---- .../mixins/client/MixinGuiMessageTag.java | 28 -- .../mixins/client/MixinGuiMessageTagIcon.java | 47 ---- .../mixins/client/MixinJoinMultiplayerScreen.java | 87 ------- .../mixins/client/MixinMinecraft.java | 48 ---- .../mixins/client/MixinOnlineServerEntry.java | 62 ----- .../nochatreports/mixins/client/MixinOptions.java | 44 ---- .../mixins/client/MixinPlayerEntry.java | 57 ----- .../mixins/client/MixinRealmsConnect.java | 34 --- .../mixins/client/MixinRowHelper.java | 30 --- .../mixins/client/MixinServerData.java | 46 ---- .../mixins/client/MixinServerStatusPinger$1.java | 57 ----- .../mixins/client/MixinTitleScreen.java | 29 --- .../mixins/client/MixinToastComponent.java | 26 -- .../client/MixinYggdrasilUserApiService.java | 33 --- .../mixins/common/MixinServerStatus.java | 53 ---- .../mixins/common/MixinServerStatusSerializer.java | 54 ---- .../mixins/server/MixinDedicatedServer.java | 24 -- .../mixins/server/MixinPlayerList.java | 24 -- .../server/MixinServerGamePacketListenerImpl.java | 74 ------ .../mixins/server/MixinServerboundChatPacket.java | 26 -- .../MixinServerboundChatSessionUpdatePacket.java | 36 --- 138 files changed, 4904 insertions(+), 4849 deletions(-) delete mode 100644 src/main/java/com/aizistral/nochatreports/NoChatReports.java delete mode 100644 src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/NCRClient.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/NCRCore.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/JSONConfig.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/ModMenuIntegration.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/NCRConfig.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/NCRConfigClient.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/NCRConfigCommon.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/NCRConfigEncryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/NCRServerPreferences.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/config/ServerAddressAdapter.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/core/EncryptionUtil.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/core/ServerDataExtension.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyLevel.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyState.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/core/SigningMode.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/Encryption.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/encryption/Encryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/AdaptiveWarningScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/AdvancedImageButton.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/AdvancedTooltip.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/EncryptionButton.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/EncryptionConfigScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/EncryptionWarningScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/FontHelper.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/InvisibleButton.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/RealmsWarningScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/TriageWarningScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/gui/UnsafeServerScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatComponent.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatListener.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatOptionsScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinClientPacketListener.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinConnectScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTag.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTagIcon.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinJoinMultiplayerScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinMinecraft.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOnlineServerEntry.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOptions.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinPlayerEntry.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRealmsConnect.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRowHelper.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerData.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerStatusPinger$1.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinTitleScreen.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinToastComponent.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinYggdrasilUserApiService.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatus.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatusSerializer.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinDedicatedServer.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinPlayerList.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerGamePacketListenerImpl.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatPacket.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatSessionUpdatePacket.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/platform/PlatformProvider.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/platform/events/ClientEvents.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/platform/events/PlatformEvent.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/platform/events/particular/Disconnect.java create mode 100644 src/main/java/com/aizistral/nochatreports/common/platform/events/particular/PlayReady.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/JSONConfig.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/ModMenuIntegration.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/NCRConfig.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/NCRServerPreferences.java delete mode 100644 src/main/java/com/aizistral/nochatreports/config/ServerAddressAdapter.java delete mode 100644 src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java delete mode 100644 src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java delete mode 100644 src/main/java/com/aizistral/nochatreports/core/ServerSafetyLevel.java delete mode 100644 src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java delete mode 100644 src/main/java/com/aizistral/nochatreports/core/SigningMode.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryptor.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryptor.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryptor.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryptor.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/Encryption.java delete mode 100644 src/main/java/com/aizistral/nochatreports/encryption/Encryptor.java create mode 100644 src/main/java/com/aizistral/nochatreports/fabric/NoChatReports.java create mode 100644 src/main/java/com/aizistral/nochatreports/fabric/NoChatReportsClient.java create mode 100644 src/main/java/com/aizistral/nochatreports/fabric/mixins/MixinMinecraft.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/AdaptiveWarningScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/AdvancedImageButton.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/AdvancedTooltip.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/FontHelper.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/InvisibleButton.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/RealmsWarningScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/TriageWarningScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatListener.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatOptionsScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientPacketListener.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTag.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTagIcon.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinJoinMultiplayerScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinMinecraft.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinRowHelper.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerStatusPinger$1.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinTitleScreen.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinToastComponent.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/client/MixinYggdrasilUserApiService.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatus.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatusSerializer.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/server/MixinDedicatedServer.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayerList.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java delete mode 100644 src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatSessionUpdatePacket.java (limited to 'src/main/java/com/aizistral/nochatreports') diff --git a/src/main/java/com/aizistral/nochatreports/NoChatReports.java b/src/main/java/com/aizistral/nochatreports/NoChatReports.java deleted file mode 100644 index 584e8ac..0000000 --- a/src/main/java/com/aizistral/nochatreports/NoChatReports.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.aizistral.nochatreports; - -import net.fabricmc.api.ModInitializer; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; -import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.aizistral.nochatreports.config.NCRConfig; - -import java.nio.charset.Charset; - -/** - * Common initializer for the mod. Some networking and config setup here. - * @author Aizistral - */ - -public final class NoChatReports implements ModInitializer { - public static final Logger LOGGER = LogManager.getLogger(); - - @Override - public void onInitialize() { - LOGGER.info("KONNICHIWA ZA WARUDO!"); - LOGGER.info("Default JVM text encoding is: " + Charset.defaultCharset().displayName()); - - NCRConfig.load(); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java b/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java deleted file mode 100644 index 2fa7ecf..0000000 --- a/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.aizistral.nochatreports; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerDataExtension; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.core.SigningMode; - -import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; -import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.ChatScreen; -import net.minecraft.client.gui.screens.telemetry.TelemetryInfoScreen; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.client.multiplayer.ProfileKeyPairManager; -import net.minecraft.network.chat.Component; - -/** - * Client initializer for the mod. Some networking setup here, as well as few screen-related events. - * @author Aizistral - */ - -@Environment(EnvType.CLIENT) -public final class NoChatReportsClient implements ClientModInitializer { - private static boolean signingKeysPresent = false; - - @Override - public void onInitializeClient() { - NoChatReports.LOGGER.info("Client initialization..."); - - ClientPlayConnectionEvents.JOIN.register(this::onPlayReady); - ClientPlayConnectionEvents.DISCONNECT.register(this::onDisconnect); - } - - private void onDisconnect(ClientPacketListener handler, Minecraft client) { - if (!NCRConfig.getClient().enableMod()) - return; - - if (NCRConfig.getCommon().enableDebugLog()) { - NoChatReports.LOGGER.info("Disconnected from server, resetting safety state!"); - } - - ServerSafetyState.reset(); - } - - private void onPlayReady(ClientPacketListener handler, PacketSender sender, Minecraft client) { - if (!NCRConfig.getClient().enableMod()) - return; - - client.execute(() -> { - if (!client.isLocalServer()) { - if (ServerSafetyState.isOnRealms()) { - // NO-OP - } else if (!handler.getConnection().isEncrypted()) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.SECURE); - } else if (client.getCurrentServer() instanceof ServerDataExtension ext && - ext.preventsChatReports()) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.SECURE); - } else if (NCRConfig.getServerPreferences().hasMode(ServerSafetyState.getLastServer(), - SigningMode.ALWAYS)) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); - ServerSafetyState.setAllowChatSigning(true); - } else { - ServerSafetyState.updateCurrent(ServerSafetyLevel.UNKNOWN); - } - } else { - ServerSafetyState.updateCurrent(ServerSafetyLevel.SINGLEPLAYER); - } - - if (NCRConfig.getCommon().enableDebugLog()) { - NoChatReports.LOGGER.info("Sucessfully connected to server, safety state: {}", ServerSafetyState.getCurrent()); - } - - if (NCRConfig.getClient().demandOnServer() && !ServerSafetyState.getCurrent().isSecure()) { - handler.getConnection().disconnect(Component.translatable("disconnect.nochatreports.client")); - } - }); - } - - public static boolean areSigningKeysPresent() { - return signingKeysPresent; - } - - public static void setSigningKeysPresent(boolean present) { - signingKeysPresent = present; - } - - public static void resendLastChatMessage() { - var mc = Minecraft.getInstance(); - var chatScr = mc.screen instanceof ChatScreen chat ? chat : null; - - if (chatScr == null) { - chatScr = new ChatScreen(""); - chatScr.init(mc, mc.getWindow().getGuiScaledWidth(), mc.getWindow().getGuiScaledHeight()); - } - - chatScr.handleChatInput(NCRConfig.getEncryption().getLastMessage(), false); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/common/NCRClient.java b/src/main/java/com/aizistral/nochatreports/common/NCRClient.java new file mode 100644 index 0000000..524cfe0 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/NCRClient.java @@ -0,0 +1,98 @@ +package com.aizistral.nochatreports.common; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerDataExtension; +import com.aizistral.nochatreports.common.core.ServerSafetyLevel; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.aizistral.nochatreports.common.core.SigningMode; +import com.aizistral.nochatreports.common.platform.PlatformProvider; +import com.aizistral.nochatreports.common.platform.events.ClientEvents; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.chat.Component; + +@Environment(EnvType.CLIENT) +public class NCRClient { + private static boolean signingKeysPresent = false; + + private NCRClient() { + throw new IllegalStateException("Can't touch this"); + } + + static void setup() { + NCRCore.LOGGER.info("Client initialization..."); + + ClientEvents.DISCONNECT.register(NCRClient::onDisconnect); + ClientEvents.PLAY_READY.register(NCRClient::onPlayReady); + } + + private static void onDisconnect(Minecraft client) { + if (!NCRConfig.getClient().enableMod()) + return; + + if (NCRConfig.getCommon().enableDebugLog()) { + NCRCore.LOGGER.info("Disconnected from server, resetting safety state!"); + } + + ServerSafetyState.reset(); + } + + private static void onPlayReady(ClientPacketListener handler, Minecraft client) { + if (!NCRConfig.getClient().enableMod()) + return; + + client.execute(() -> { + if (!client.isLocalServer()) { + if (ServerSafetyState.isOnRealms()) { + // NO-OP + } else if (!handler.getConnection().isEncrypted()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.SECURE); + } else if (client.getCurrentServer() instanceof ServerDataExtension ext && + ext.preventsChatReports()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.SECURE); + } else if (NCRConfig.getServerPreferences().hasMode(ServerSafetyState.getLastServer(), + SigningMode.ALWAYS)) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); + ServerSafetyState.setAllowChatSigning(true); + } else { + ServerSafetyState.updateCurrent(ServerSafetyLevel.UNKNOWN); + } + } else { + ServerSafetyState.updateCurrent(ServerSafetyLevel.SINGLEPLAYER); + } + + if (NCRConfig.getCommon().enableDebugLog()) { + NCRCore.LOGGER.info("Sucessfully connected to server, safety state: {}", ServerSafetyState.getCurrent()); + } + + if (NCRConfig.getClient().demandOnServer() && !ServerSafetyState.getCurrent().isSecure()) { + handler.getConnection().disconnect(Component.translatable("disconnect.nochatreports.client")); + } + }); + } + + public static boolean areSigningKeysPresent() { + return signingKeysPresent; + } + + public static void setSigningKeysPresent(boolean present) { + signingKeysPresent = present; + } + + public static void resendLastChatMessage() { + var mc = Minecraft.getInstance(); + var chatScr = mc.screen instanceof ChatScreen chat ? chat : null; + + if (chatScr == null) { + chatScr = new ChatScreen(""); + chatScr.init(mc, mc.getWindow().getGuiScaledWidth(), mc.getWindow().getGuiScaledHeight()); + } + + chatScr.handleChatInput(NCRConfig.getEncryption().getLastMessage(), false); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/NCRCore.java b/src/main/java/com/aizistral/nochatreports/common/NCRCore.java new file mode 100644 index 0000000..257835b --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/NCRCore.java @@ -0,0 +1,50 @@ +package com.aizistral.nochatreports.common; + +import java.nio.charset.Charset; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.platform.PlatformProvider; +import com.google.common.base.Preconditions; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; + +public class NCRCore { + public static final Logger LOGGER = LogManager.getLogger(); + private static PlatformProvider provider = null; + + private NCRCore() { + throw new IllegalStateException("Can't touch this"); + } + + public static PlatformProvider getProvider() { + return provider; + } + + public static void awaken(PlatformProvider platformProvider) { + Preconditions.checkArgument(provider == null, "NCRCore already awake"); + provider = platformProvider; + + setup(); + + if (provider.getEnvironment() == EnvType.CLIENT) { + clientSetup(); + } + } + + private static void setup() { + LOGGER.info("KONNICHIWA ZA WARUDO!"); + LOGGER.info("Default JVM text encoding is: " + Charset.defaultCharset().displayName()); + + NCRConfig.load(); + } + + @Environment(EnvType.CLIENT) + private static void clientSetup() { + NCRClient.setup(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/JSONConfig.java b/src/main/java/com/aizistral/nochatreports/common/config/JSONConfig.java new file mode 100644 index 0000000..258b340 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/JSONConfig.java @@ -0,0 +1,106 @@ +package com.aizistral.nochatreports.common.config; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.function.Supplier; + +import com.aizistral.nochatreports.common.NCRCore; +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import net.fabricmc.api.EnvType; +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +public abstract class JSONConfig { + protected static final Path CONFIG_DIR = NCRCore.getProvider().getConfigDir(); + protected static final Gson GSON = createGson(); + + protected final String fileName; + protected final Path filePath; + + protected JSONConfig(String file) { + this.fileName = file; + this.filePath = CONFIG_DIR.resolve(this.fileName); + } + + public Path getFile() { + return this.filePath; + } + + public void saveFile() { + NCRCore.LOGGER.info("Writing config file {}...", this.fileName); + writeFile(this.fileName, this); + } + + protected void uponLoad() { + // NO-OP + } + + public abstract JSONConfig getDefault(); + + public static T loadConfig(Class configClass, Supplier freshInstance, String fileName) { + NCRCore.LOGGER.info("Reading config file {}...", fileName); + T config = readFile(fileName, configClass).orElseGet(freshInstance); + config.uponLoad(); + return config; + } + + private static Optional readFile(String fileName, Class configClass) { + Path file = CONFIG_DIR.resolve(fileName); + + if (!Files.isRegularFile(file)) + return Optional.empty(); + + try (BufferedReader reader = Files.newBufferedReader(file)) { + return Optional.of(GSON.fromJson(reader, configClass)); + } catch (Exception ex) { + NCRCore.LOGGER.fatal("Could not read config file: {}", file); + NCRCore.LOGGER.fatal("This likely indicates the file is corrupted. " + + "You can try deleting it to fix this problem. Full stacktrace below:"); + ex.printStackTrace(); + return null; + } + } + + private static void writeFile(String fileName, T config) { + Path file = CONFIG_DIR.resolve(fileName); + + try { + Files.createDirectories(file.getParent()); + try (BufferedWriter writer = Files.newBufferedWriter(file)) { + GSON.toJson(config, writer); + } + } catch (Exception ex) { + NCRCore.LOGGER.fatal("Could not write config file: {}", file); + throw new RuntimeException(ex); + } + } + + private static Gson createGson() { + GsonBuilder builder = new GsonBuilder(); + builder.setPrettyPrinting(); + builder.setExclusionStrategies(new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getDeclaringClass() == JSONConfig.class; + } + + @Override + public boolean shouldSkipClass(Class theClass) { + return false; + } + }); + + if (NCRCore.getProvider().getEnvironment() == EnvType.CLIENT) { + builder.registerTypeAdapter(ServerAddress.class, ServerAddressAdapter.INSTANCE); + } + + return builder.create(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/ModMenuIntegration.java b/src/main/java/com/aizistral/nochatreports/common/config/ModMenuIntegration.java new file mode 100644 index 0000000..2fda1fa --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/ModMenuIntegration.java @@ -0,0 +1,275 @@ +//package com.aizistral.nochatreports.common.config; +// +//import java.util.Arrays; +//import java.util.List; +//import java.util.stream.Stream; +// +//import com.aizistral.nochatreports.common.core.ServerSafetyState; +//import com.aizistral.nochatreports.common.core.SigningMode; +//import com.aizistral.nochatreports.common.gui.FontHelper; +//import com.terraformersmc.modmenu.api.ConfigScreenFactory; +//import com.terraformersmc.modmenu.api.ModMenuApi; +// +//import me.shedaniel.clothconfig2.api.ConfigBuilder; +//import me.shedaniel.clothconfig2.api.ConfigCategory; +//import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; +//import net.fabricmc.api.EnvType; +//import net.fabricmc.api.Environment; +//import net.minecraft.ChatFormatting; +//import net.minecraft.client.Minecraft; +//import net.minecraft.locale.Language; +//import net.minecraft.network.chat.ClickEvent; +//import net.minecraft.network.chat.Component; +//import net.minecraft.network.chat.HoverEvent; +// +///** +// * Implementation of ModMenu and ClothConfig support for the mod. +// * @author MODKILLER1001 +// */ +// +//// TODO We need to move this into fabric package +//@Environment(EnvType.CLIENT) +//public final class ModMenuIntegration implements ModMenuApi { +// +// private String translateKey(String key) { +// return Language.getInstance().getOrDefault(key); +// } +// +// private Component[] wrapTooltip(String text) { +// List list = FontHelper.wrap(Minecraft.getInstance().font, text, 250); +// Component[] tooltip = new Component[list.size()]; +// +// for (int i = 0; i < list.size(); i++) { +// tooltip[i] = Component.literal(list.get(i)); +// } +// +// return tooltip; +// } +// +// private Component[] makeTooltip(String key) { +// return this.wrapTooltip(this.translateKey(key)); +// } +// +// @Override +// public ConfigScreenFactory getModConfigScreenFactory() { +// return screen -> { +// +// // Get the previous screen +// ConfigBuilder builder = ConfigBuilder.create() +// .setParentScreen(Minecraft.getInstance().screen) +// .setTitle(Component.translatable("configuration.NoChatReports.config")); +// +// // Set category +// ConfigCategory client = builder.getOrCreateCategory(Component.translatable("configuration.NoChatReports.category.client")); +// ConfigCategory lan = builder.getOrCreateCategory(Component.translatable("configuration.NoChatReports.category.lan")); +// +// ConfigEntryBuilder entryBuilder = builder.entryBuilder(); +// +// // Set an option for enableMod +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.enableMod"), NCRConfig.getClient().enableMod) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.enableMod.tooltip")) +// .setSaveConsumer(newValue -> ServerSafetyState.scheduleResetAction(() -> { +// NCRConfig.getClient().enableMod = newValue; +// NCRConfig.getClient().saveFile(); +// })) +// .build()); +// +// // Set an option for showNCRButton +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showNCRButton"), NCRConfig.getClient().showNCRButton) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.showNCRButton.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().showNCRButton = newValue) +// .build()); +// +// +// String signingTooltip = this.translateKey("option.NoChatReports.defaultSigningMode.tooltip") +// + "\n "; +// +// for (SigningMode mode : SigningMode.values()) { +// if (mode.isSelectableGlobally()) { +// signingTooltip += "\n\n"; +// signingTooltip += ChatFormatting.AQUA; +// signingTooltip += ChatFormatting.BOLD; +// signingTooltip += ChatFormatting.UNDERLINE; +// signingTooltip += this.translateKey(mode.getNameKey()); +// signingTooltip += ChatFormatting.RESET; +// signingTooltip += "\n"; +// signingTooltip += this.translateKey(mode.getTooltipKey()); +// } +// } +// +// // Dropdown for defaultSigningMode +// client.addEntry( +// entryBuilder.startStringDropdownMenu(Component.translatable("option.NoChatReports.defaultSigningMode"), +// NCRConfig.getClient().defaultSigningMode.getName().getString()) +// .setTooltip(this.wrapTooltip(signingTooltip)) +// .setDefaultValue(SigningMode.PROMPT.getName().getString()) +// .setSelections(Stream.of(SigningMode.values()).filter(SigningMode::isSelectableGlobally) +// .map(mode -> mode.getName().getString()).toList()) +// .setSaveConsumer(newValue -> { +// NCRConfig.getClient().defaultSigningMode = Arrays.stream(SigningMode.values()) +// .filter(mode -> mode.getName().getString().equals(newValue)) +// .findFirst().get(); +// }) +// .setSuggestionMode(false) +// .build() +// ); +// +// // Set an option for showReloadButton +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showReloadButton"), NCRConfig.getClient().showReloadButton) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.showReloadButton.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().showReloadButton = newValue) +// .build()); +// +// // Set an option for verifiedIconEnabled +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.verifiedIconEnabled"), NCRConfig.getClient().verifiedIconEnabled) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.verifiedIconEnabled.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().verifiedIconEnabled = newValue) +// .build()); +// +// // Set an option for verifiedIconOffsetX +// client.addEntry(entryBuilder.startIntField(Component.translatable("option.NoChatReports.verifiedIconOffsetX"), NCRConfig.getClient().verifiedIconOffsetX) +// .setDefaultValue(0) +// .setTooltip(this.makeTooltip("option.NoChatReports.verifiedIconOffsetX.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().verifiedIconOffsetX = newValue) +// .build()); +// +// // Set an option for verifiedIconOffsetY +// client.addEntry(entryBuilder.startIntField(Component.translatable("option.NoChatReports.verifiedIconOffsetY"), NCRConfig.getClient().verifiedIconOffsetY) +// .setDefaultValue(0) +// .setTooltip(this.makeTooltip("option.NoChatReports.verifiedIconOffsetY.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().verifiedIconOffsetY = newValue) +// .build()); +// +// // Warning for showEncryptionButton +// client.addEntry(entryBuilder.startTextDescription(Component.translatable("gui.NoChatReports.showEncryptionButtonWarning")) +// .build()); +// +// // Set an option for showEncryptionButton +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showEncryptionButton"), NCRConfig.getEncryption().showEncryptionButton) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.showEncryptionButton.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getEncryption().showEncryptionButton = newValue) +// .build()); +// +// // Set an option for showEncryptionIndicators +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showEncryptionIndicators"), NCRConfig.getEncryption().showEncryptionIndicators) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.showEncryptionIndicators.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getEncryption().showEncryptionIndicators = newValue) +// .build()); +// +// // Set an option for showServerSafety +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showServerSafety"), NCRConfig.getClient().showServerSafety) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.showServerSafety.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().showServerSafety = newValue) +// .build()); +// +// // Add link for documentation for showServerSafety +// client.addEntry(entryBuilder.startTextDescription(Component.translatable("option.NoChatReports.showServerSafety.moreInfo") +// .withStyle(s -> s +// .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/Configuration-Files/#option-showserversafety"))).withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/Configuration-Files/#option-showserversafety")))) +// .build()); +// +// // Set an option for hideInsecureMessageIndicators +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideInsecureMessageIndicators"), NCRConfig.getClient().hideInsecureMessageIndicators) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.hideInsecureMessageIndicators.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().hideInsecureMessageIndicators = newValue) +// .build()); +// +// // Set an option for hideModifiedMessageIndicators +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideModifiedMessageIndicators"), NCRConfig.getClient().hideModifiedMessageIndicators) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.hideModifiedMessageIndicators.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().hideModifiedMessageIndicators = newValue) +// .build()); +// +// // Set an option for hideSystemMessageIndicators +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideSystemMessageIndicators"), NCRConfig.getClient().hideSystemMessageIndicators) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.hideSystemMessageIndicators.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().hideSystemMessageIndicators = newValue) +// .build()); +// +// // Set an option for hideWarningToast +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideWarningToast"), NCRConfig.getClient().hideWarningToast) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.hideWarningToast.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().hideWarningToast = newValue) +// .build()); +// +// // Set an option for hideSigningRequestMessage +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideSigningRequestMessage"), NCRConfig.getClient().hideSigningRequestMessage) +// .setDefaultValue(false) +// .setTooltip(this.makeTooltip("option.NoChatReports.hideSigningRequestMessage.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().hideSigningRequestMessage = newValue) +// .build()); +// +// // Set an option for alwaysHideReportButton +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.alwaysHideReportButton"), NCRConfig.getClient().alwaysHideReportButton) +// .setDefaultValue(false) +// .setTooltip(this.makeTooltip("option.NoChatReports.alwaysHideReportButton.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().alwaysHideReportButton = newValue) +// .build()); +// +// // Set an option for demandOnServer +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.demandOnServer"), NCRConfig.getClient().demandOnServer) +// .setDefaultValue(false) +// .setTooltip(this.makeTooltip("option.NoChatReports.demandOnServer.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().demandOnServer = newValue) +// .build()); +// +// // Set an option for enableDebugLog +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.enableDebugLog"), NCRConfig.getCommon().enableDebugLog) +// .setDefaultValue(false) +// .setTooltip(this.makeTooltip("option.NoChatReports.enableDebugLog.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getCommon().enableDebugLog = newValue) +// .build()); +// +// // Set an option for disableTelemetry +// client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.disableTelemetry"), NCRConfig.getClient().disableTelemetry) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.disableTelemetry.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getClient().disableTelemetry = newValue) +// .build()); +// +// // Set an option for demandOnClient +// lan.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.demandOnClient"), NCRConfig.getCommon().demandOnClient) +// .setDefaultValue(false) +// .setTooltip(this.makeTooltip("option.NoChatReports.demandOnClient.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getCommon().demandOnClient = newValue) +// .build()); +// +// // Set an option for demandOnClientMessage +// lan.addEntry(entryBuilder.startStrField(Component.translatable("option.NoChatReports.demandOnClientMessage"), NCRConfig.getCommon().demandOnClientMessage) +// .setDefaultValue(NCRConfig.getCommon().demandOnClientMessage) +// .setTooltip(this.makeTooltip("option.NoChatReports.demandOnClientMessage.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getCommon().demandOnClientMessage = newValue) +// .build()); +// +// // Set an option for convertToGameMessage +// lan.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.convertToGameMessage"), NCRConfig.getCommon().convertToGameMessage) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.convertToGameMessage.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getCommon().convertToGameMessage = newValue) +// .build()); +// +// // Set an option for addQueryData +// lan.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.addQueryData"), NCRConfig.getCommon().addQueryData) +// .setDefaultValue(true) +// .setTooltip(this.makeTooltip("option.NoChatReports.addQueryData.tooltip")) +// .setSaveConsumer(newValue -> NCRConfig.getCommon().addQueryData = newValue) +// .build()); +// +// // Save config +// builder.setSavingRunnable(NCRConfig::save); +// return builder.build(); +// }; +// } +// +//} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/common/config/NCRConfig.java b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfig.java new file mode 100644 index 0000000..01c33fa --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfig.java @@ -0,0 +1,84 @@ +package com.aizistral.nochatreports.common.config; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Supplier; + +import com.aizistral.nochatreports.common.NCRCore; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; + +public final class NCRConfig { + private static NCRConfigCommon common = null; + private static NCRConfigClient client = null; + private static NCRServerPreferences serverPreferences = null; + private static NCRConfigEncryption encryption = null; + + private NCRConfig() { + throw new IllegalStateException("Can't touch this"); + } + + public static NCRConfigCommon getCommon() { + return checkLoaded(() -> common); + } + + @Environment(EnvType.CLIENT) + public static NCRConfigClient getClient() { + return checkLoaded(() -> client); + } + + @Environment(EnvType.CLIENT) + public static NCRServerPreferences getServerPreferences() { + return checkLoaded(() -> serverPreferences); + } + + @Environment(EnvType.CLIENT) + public static NCRConfigEncryption getEncryption() { + return checkLoaded(() -> encryption); + } + + private static T checkLoaded(Supplier config) { + if (config.get() == null) { + load(); + } + + return config.get(); + } + + public static void load() { + common = JSONConfig.loadConfig(NCRConfigCommon.class, NCRConfigCommon::new, NCRConfigCommon.FILE_NAME); + + if (NCRCore.getProvider().getEnvironment() == EnvType.CLIENT) { + client = JSONConfig.loadConfig(NCRConfigClient.class, NCRConfigClient::new, NCRConfigClient.FILE_NAME); + serverPreferences = JSONConfig.loadConfig(NCRServerPreferences.class, NCRServerPreferences::new, NCRServerPreferences.FILE_NAME); + encryption = JSONConfig.loadConfig(NCRConfigEncryption.class, NCRConfigEncryption::new, NCRConfigEncryption.FILE_NAME); + } + + save(); + } + + public static void save() { + checkLoaded(() -> common).saveFile(); + + if (NCRCore.getProvider().getEnvironment() == EnvType.CLIENT) { + checkLoaded(() -> client).saveFile(); + checkLoaded(() -> serverPreferences).saveFile(); + checkLoaded(() -> encryption).saveFile(); + } + + Path readme = JSONConfig.CONFIG_DIR.resolve("NoChatReports/README.md"); + try { + Files.writeString(readme, """ + # No Chat Reports + You can find updated documentation of configuration files on the wiki: + https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/Configuration-Files + """, StandardCharsets.UTF_8); + } catch (Exception ex) { + NCRCore.LOGGER.fatal("Could not write README file: {}", readme); + throw new RuntimeException(ex); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigClient.java b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigClient.java new file mode 100644 index 0000000..30db481 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigClient.java @@ -0,0 +1,207 @@ +package com.aizistral.nochatreports.common.config; + +import com.aizistral.nochatreports.common.core.ServerSafetyLevel; +import com.aizistral.nochatreports.common.core.SigningMode; +import com.aizistral.nochatreports.common.mixins.client.MixinChatListener; +import com.aizistral.nochatreports.common.mixins.client.MixinToastComponent; + +public final class NCRConfigClient extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-Client.json"; + + protected SigningMode defaultSigningMode = SigningMode.PROMPT; + protected boolean enableMod = true, showNCRButton = true, showReloadButton = true, + verifiedIconEnabled = true, showServerSafety = true, hideInsecureMessageIndicators = true, + hideModifiedMessageIndicators = true, hideSystemMessageIndicators = true, + hideWarningToast = true, hideSigningRequestMessage = false, alwaysHideReportButton = false, + skipRealmsWarning = false, disableTelemetry = true, removeTelemetryButton = true, + demandOnServer = false; + protected int verifiedIconOffsetX = 0, verifiedIconOffsetY = 0; + + protected NCRConfigClient() { + super(FILE_NAME); + } + + @Override + public NCRConfigClient getDefault() { + return new NCRConfigClient(); + } + + public void toggleMod() { + this.enableMod = !this.enableMod; + } + + /** + * @return True if client with No Chat Reports installed should demand that mod is present on + * every server that it tries to join. In that case client will not be able to join servers that + * don't have the mod installed. Servers without the mod can still provide varying degrees of + * safety, which {@link ServerSafetyLevel} and respective icon in bottom-right corner of the chat + * screen is designed to indicate.

+ * + * This is false by default. + */ + + public boolean demandOnServer() { + return this.demandOnServer; + } + + /** + * @return True if current {@link ServerSafetyLevel} should be indicated on client by an icon in + * the bottom-right corner of chat screen.

+ * + * This is true by default. + */ + + public boolean showServerSafety() { + return this.showServerSafety; + } + + /** + * @return True if vanilla's unsigned messages trust indicator should be removed.

+ * + * This is true by default. + * + * @see MixinChatListener#onEvaluateTrustLevel + */ + + public boolean hideInsecureMessageIndicators() { + return this.hideInsecureMessageIndicators; + } + + /** + * @return True if vanilla's modified/hidden messages trust indicator should be removed.

+ * + * This is true by default. + * + * @see MixinChatListener#onEvaluateTrustLevel + */ + + public boolean hideModifiedMessageIndicators() { + return this.hideModifiedMessageIndicators; + } + + /** + * @return True if vanilla's system messages trust indicator should be removed.

+ * + * This is true by default. + * + * @see com.aizistral.nochatreports.common.mixins.client.MixinGuiMessageTag#onSystem + */ + + public boolean hideSystemMessageIndicators() { + return this.hideSystemMessageIndicators; + } + + /** + * @return True if "Chat messages can't be verified" toast should be removed.

+ * + * This is true by default. + * + * @see MixinToastComponent#onAddToast + */ + + public boolean hideWarningToast() { + return this.hideWarningToast; + } + + /** + * @return True if reporting buttons should always be hidden from social interactions screen, + * instead of simply being disabled.

+ * + * This is false by default. + */ + + public boolean alwaysHideReportButton() { + return this.alwaysHideReportButton; + } + + /** + * @return True if sending telemetry to Mojang should be disabled.

+ * + * This is true by default. + */ + + public boolean disableTelemetry() { + return this.disableTelemetry; + } + + /** + * @return True if the configuration reload button should be displayed in multiplayer screen. + *

+ * + * This is true by default. + */ + + public boolean showReloadButton() { + return this.showReloadButton; + } + + /** + * @return True if "Safe Server" icon should be displayed in multiplayer menu for servers that + * declare themselves as preventing chat reports.

+ * + * This is true by default. + */ + + public boolean verifiedIconEnabled() { + return this.verifiedIconEnabled; + } + + + /** + * @return X offset for "Safe Server" icon in multiplayer menu. + */ + + public int getVerifiedIconOffsetX() { + return 16 + this.verifiedIconOffsetX; + } + + /** + * @return Y offset for "Safe Server" icon in multiplayer menu. + */ + + public int getVerifiedIconOffsetY() { + return 12 + this.verifiedIconOffsetY; + } + + /** + * @return True if button to disable/enable entire mod should be displayed in + * multiplayer menu. + */ + + public boolean showNCRButton() { + return this.showNCRButton; + } + + /** + * @return Whether or not No Chat Reports should provide networking-related functionality. + */ + + public boolean enableMod() { + return this.enableMod; + } + + /** + * @return Whether warning on entering Realms screen should not be displayed. + */ + + public boolean skipRealmsWarning() { + return this.skipRealmsWarning; + } + + public void setSkipRealmsWarning(boolean skipRealmsWarning) { + this.skipRealmsWarning = skipRealmsWarning; + } + + public boolean hideSigningRequestMessage() { + return this.hideSigningRequestMessage; + } + + public SigningMode defaultSigningMode() { + return this.defaultSigningMode; + } + + public boolean removeTelemetryButton() { + return this.removeTelemetryButton; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigCommon.java b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigCommon.java new file mode 100644 index 0000000..9242d90 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigCommon.java @@ -0,0 +1,74 @@ +package com.aizistral.nochatreports.common.config; + +public final class NCRConfigCommon extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-Common.json"; + + protected String demandOnClientMessage = "You do not have No Chat Reports, and this server is" + + " configured to require it on client!"; + protected boolean demandOnClient = false, convertToGameMessage = true, + addQueryData = true, enableDebugLog = false; + + protected NCRConfigCommon() { + super(FILE_NAME); + } + + @Override + public NCRConfigCommon getDefault() { + return new NCRConfigCommon(); + } + + /** + * @return True if server with No Chat Reports installed should demand that mod is present on + * every client that tries to join. Mod's installation on client is optional otherwise.

+ * + * This is false by default. + */ + + public boolean demandOnClient() { + return this.demandOnClient; + } + + /** + * @return Disconnect message that should be shown to client if demandOnClient is + * true and it tries to join without No Chat Reports installed. + */ + + public String demandOnClientMessage() { + return this.demandOnClientMessage; + } + + /** + * @return True if server should convert all player messages to system messages. System messages + * do not feature signatures and look completely identical in the chat, with exception of gray line + * next to them added in pre-release 3. They are also unselectable for chat reporting.

+ * + * This is false by default. + */ + + public boolean convertToGameMessage() { + return this.convertToGameMessage; + } + + /** + * @return True if mod should log some additional information about its activity and message + * signatures. Generally only useful for debugging.

+ * + * This is false by default. + */ + + public boolean enableDebugLog() { + return this.enableDebugLog; + } + + /** + * @return True if server should include extra query data to help clients know that your server + * is secure.

+ * + * This is true by default. + */ + + public boolean addQueryData() { + return this.addQueryData; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigEncryption.java b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigEncryption.java new file mode 100644 index 0000000..a876c91 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/NCRConfigEncryption.java @@ -0,0 +1,189 @@ +package com.aizistral.nochatreports.common.config; + +import java.security.InvalidKeyException; +import java.util.List; +import java.util.Optional; + +import com.aizistral.nochatreports.common.encryption.Encryption; +import com.aizistral.nochatreports.common.encryption.Encryptor; + +public class NCRConfigEncryption extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-Encryption.json"; + protected boolean skipWarning = false, enableEncryption = false, encryptPublic = true, + showEncryptionButton = true, showEncryptionIndicators = true; + protected String encryptionKey = Encryption.AES_CFB8.getDefaultKey(), encryptionPassphrase = "", + algorithmName = Encryption.AES_CFB8.getName(); + protected List encryptableCommands = List.of("msg:1", "w:1", "whisper:1", "tell:1", "r:0", "dm:1", + "me:0", "m:1", "t:1", "pm:1", "emsg:1", "epm:1", "etell:1", "ewhisper:1"); + private transient Encryption algorithm; + private transient boolean isValid = false; + private transient String lastMessage = "???"; + + protected NCRConfigEncryption() { + super(FILE_NAME); + } + + @Override + public NCRConfigEncryption getDefault() { + return new NCRConfigEncryption(); + } + + @Override + protected void uponLoad() { + this.algorithm = Encryption.getRegistered().stream().filter(e -> e.getName().equals(this.algorithmName)) + .findFirst().orElse(Encryption.AES_CFB8); + this.validate(); + } + + private void validate() { + this.isValid = this.algorithm.validateKey(this.encryptionKey); + } + + public void toggleEncryption() { + this.enableEncryption = !this.enableEncryption; + this.saveFile(); + } + + public void setAlgorithm(Encryption encryption) { + this.algorithm = encryption; + this.algorithmName = encryption.getName(); + this.validate(); + this.saveFile(); + } + + public void setEncryptionKey(String key) { + this.encryptionKey = key; + this.validate(); + this.saveFile(); + } + + public void setEncryptionPassphrase(String pass) { + this.encryptionPassphrase = pass; + this.saveFile(); + } + + public void setEncryptPublic(boolean encryptPublic) { + this.encryptPublic = encryptPublic; + this.saveFile(); + } + + public void disableWarning() { + this.skipWarning = true; + } + + public boolean isWarningDisabled() { + return this.skipWarning; + } + + public boolean isEnabled() { + return this.enableEncryption; + } + + public String getEncryptionKey() { + return this.encryptionKey; + } + + public String getEncryptionPassphrase() { + return this.encryptionPassphrase; + } + + public boolean isValid() { + return this.isValid; + } + + public boolean shouldEncryptPublic() { + return this.encryptPublic; + } + + public boolean showEncryptionIndicators() { + return this.showEncryptionIndicators; + } + + public boolean isEnabledAndValid() { + return this.isEnabled() && this.isValid(); + } + + public Encryption getAlgorithm() { + return this.algorithm; + } + + public boolean shouldEncrypt(String message) { + return this.isEnabledAndValid() && this.getEncryptionStartIndex(message) != -1; + } + + public boolean showEncryptionButton() { + return this.showEncryptionButton; + } + + public int getEncryptionStartIndex(String message) { + if (!message.startsWith("/")) + return this.encryptPublic ? 0 : -1; + else { + for (String rule : this.encryptableCommands) { + String[] splat = rule.split(":"); + + if (splat.length != 2) + throw new IllegalArgumentException("Invalid encryptable command definition: " + rule + + ", in file: " + FILE_NAME); + + String cmd = splat[0]; + String args = splat[1]; + int argnum = 0; + + try { + argnum = Integer.valueOf(args); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Invalid encryptable command definition: " + rule + + ", in file: " + FILE_NAME); + } + + String prefix = "/(" + cmd + "|.*:" + cmd + ") .*"; + if (message.matches(prefix)) { + splat = message.split(" ", 2); + char[] array = splat[1].toCharArray(); + + for (int i = 0; i < array.length; i++) { + char ch = array[i]; + if (argnum > 0) { + if (ch == ' ') { + argnum--; + } + continue; + } else { + int index = i + splat[0].length() + 1; + return index < message.length() ? index : -1; + } + } + } else { + continue; + } + } + + return -1; + } + } + + public void setLastMessage(String lastMessage) { + this.lastMessage = lastMessage; + } + + public String getLastMessage() { + return this.lastMessage; + } + + /** + * @return Chat encryptor, if encryption is enabled and user specified valid key in config. + */ + + public Optional> getEncryptor() { + if (!this.isEnabledAndValid()) + return Optional.empty(); + + try { + return Optional.of(this.algorithm.getProcessor(this.encryptionKey)); + } catch (InvalidKeyException ex) { + throw new RuntimeException(ex); // shouldn't happen due to prior validation + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/NCRServerPreferences.java b/src/main/java/com/aizistral/nochatreports/common/config/NCRServerPreferences.java new file mode 100644 index 0000000..77b12c1 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/NCRServerPreferences.java @@ -0,0 +1,67 @@ +package com.aizistral.nochatreports.common.config; + +import java.util.HashMap; + +import org.jetbrains.annotations.Nullable; + +import com.aizistral.nochatreports.common.NCRClient; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.aizistral.nochatreports.common.core.SigningMode; + +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +public class NCRServerPreferences extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-ServerPreferences.json"; + protected HashMap signingModes = new HashMap<>(); + + protected NCRServerPreferences() { + super(FILE_NAME); + } + + @Override + public NCRServerPreferences getDefault() { + return new NCRServerPreferences(); + } + + public SigningMode getModeRaw(@Nullable ServerAddress address) { + return this.signingModes.get(address); + } + + public SigningMode getModeUnresolved(@Nullable ServerAddress address) { + if (!NCRClient.areSigningKeysPresent()) + return SigningMode.NEVER_FORCED; + else if (ServerSafetyState.isInSingleplayer()) + return SigningMode.NEVER; + else if (ServerSafetyState.isOnRealms()) + return SigningMode.ALWAYS; + else if (address == null) + return SigningMode.DEFAULT; + + SigningMode mode = this.getModeRaw(address); + return mode != null ? mode : SigningMode.DEFAULT; + } + + public SigningMode getMode(@Nullable ServerAddress address) { + return this.getModeUnresolved(address).resolve(); + } + + public boolean hasMode(@Nullable ServerAddress address, SigningMode mode) { + return this.getMode(address) == mode; + } + + public boolean hasModeCurrent(SigningMode mode) { + return this.hasMode(ServerSafetyState.getLastServer(), mode); + } + + public void setMode(@Nullable ServerAddress address, @Nullable SigningMode mode) { + if (address == null) + return; + + if (mode == null || mode == SigningMode.DEFAULT) { + this.signingModes.remove(address); + } else { + this.signingModes.put(address, mode); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/config/ServerAddressAdapter.java b/src/main/java/com/aizistral/nochatreports/common/config/ServerAddressAdapter.java new file mode 100644 index 0000000..21a2d9a --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/config/ServerAddressAdapter.java @@ -0,0 +1,36 @@ +package com.aizistral.nochatreports.common.config; + +import java.io.IOException; + +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +@Environment(EnvType.CLIENT) +public class ServerAddressAdapter extends TypeAdapter { + public static final ServerAddressAdapter INSTANCE = new ServerAddressAdapter(); + + private ServerAddressAdapter() { + // NO-OP + } + + @Override + public ServerAddress read(JsonReader reader) throws IOException { + String string = reader.nextString(); + + if (!ServerAddress.isValidAddress(string)) + throw new IOException("Incorrect server address format: " + string); + + return ServerAddress.parseString(string); + } + + @Override + public void write(JsonWriter writer, ServerAddress address) throws IOException { + writer.value(address.toString()); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/core/EncryptionUtil.java b/src/main/java/com/aizistral/nochatreports/common/core/EncryptionUtil.java new file mode 100644 index 0000000..842dc86 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/core/EncryptionUtil.java @@ -0,0 +1,76 @@ +package com.aizistral.nochatreports.common.core; + +import java.util.Optional; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.encryption.Encryptor; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentContents; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.contents.LiteralContents; +import net.minecraft.network.chat.contents.TranslatableContents; + +public class EncryptionUtil { + + public static Optional tryDecrypt(Component component) { + var optional = NCRConfig.getEncryption().getEncryptor(); + if (optional.isEmpty()) + return Optional.empty(); + + Encryptor encryption = optional.get(); + Component copy = recreate(component); + ComponentContents contents = copy.getContents(); + + return Optional.ofNullable(tryDecrypt(copy, encryption) ? copy : null); + } + + public static boolean tryDecrypt(Component component, Encryptor encryptor) { + boolean decryptedSiblings = false; + for (Component sibling : component.getSiblings()) { + if (tryDecrypt(sibling, encryptor)) { + decryptedSiblings = true; + } + } + + if (component.getContents() instanceof LiteralContents literal) { + var decrypted = tryDecrypt(literal.text(), encryptor); + + if (decrypted.isPresent()) { + ((MutableComponent)component).contents = new LiteralContents(decrypted.get()); + return true; + } + } else if (component.getContents() instanceof TranslatableContents translatable) { + for (Object arg : translatable.args) { + if (arg instanceof MutableComponent mutable) { + if (tryDecrypt(mutable, encryptor)) { + decryptedSiblings = true; + } + } + } + } + + return decryptedSiblings; + } + + public static Optional tryDecrypt(String message, Encryptor encryptor) { + try { + String[] splat = message.contains(" ") ? message.split(" ") : new String[] { message }; + String decryptable = splat[splat.length-1]; + + String decrypted = encryptor.decrypt(decryptable); + + if (decrypted.startsWith("#%")) + return Optional.of(message.substring(0, message.length() - decryptable.length()) + decrypted.substring(2, decrypted.length())); + else + return Optional.empty(); + } catch (Exception ex) { + return Optional.empty(); + } + } + + public static Component recreate(Component component) { + return Component.Serializer.fromJson(Component.Serializer.toStableJson(component)); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/core/ServerDataExtension.java b/src/main/java/com/aizistral/nochatreports/common/core/ServerDataExtension.java new file mode 100644 index 0000000..6b6e26f --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/core/ServerDataExtension.java @@ -0,0 +1,23 @@ +package com.aizistral.nochatreports.common.core; + +import com.aizistral.nochatreports.common.mixins.client.MixinServerData; +import com.aizistral.nochatreports.common.mixins.common.MixinServerStatus; + +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.network.protocol.status.ServerStatus; + +/** + * Implemented by {@link MixinServerStatus} on {@link ServerStatus} class and {@link MixinServerData} + * on {@link ServerData} class. + * + * @author fxmorin (original implementation) + * @author Aizistral (current version) + */ + +public interface ServerDataExtension { + + public boolean preventsChatReports(); + + public void setPreventsChatReports(boolean prevents); + +} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyLevel.java b/src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyLevel.java new file mode 100644 index 0000000..81e3517 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyLevel.java @@ -0,0 +1,69 @@ +package com.aizistral.nochatreports.common.core; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; + +/** + * Represents the level of "safety" of the given server, in the eyes of the client. + * Current level is updated dynamically and can be obtained using {@link ServerSafetyState#getCurrent()}. + * @author Aizistral + */ + +public enum ServerSafetyLevel { + + /** + * For servers that have No Chat Reports or something of similar purpose installed, and make + * verifiable effort to remove cryptographic signature from every player message they relay. + */ + SECURE, + + /** + * For singleplayer specifically. Pretty much identical to {@link #SECURE} since client needs + * NCR installed on it to display any safety level to begin with. + */ + SINGLEPLAYER, + + + /** + * For servers that do not make any effort to remove signatures from chat messages themselves, + * but do not prohibit players from sending unsigned messages. To protect the player falls fully + * on the client of respective player in such case, and vanilla client will not do that. + */ + UNINTRUSIVE, + + /** + * For servers that have enforce-secure-profile enabled, or enforce signed messages + * through some other means. Users of this mod can choose to play on those servers regardless + * after being informed of danger, but there is very little mod will be able to do to protect + * them in such case. + */ + + INSECURE, + + /** + * For Realms specifically, as these are a whole new level of unsafe. + */ + + REALMS, + + /** + * Reserved for when mod is toggled mid-session and cannot evaluate safety status. + */ + + UNKNOWN, + + /** + * Transient status for when evaluation of safety level is not yet complete for current server. + */ + + UNDEFINED; + + public MutableComponent getTooltip() { + return Component.translatable("gui.nochatreports.safety_status." + this.name().toLowerCase()); + } + + public boolean isSecure() { + return this == SECURE || this == SINGLEPLAYER; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyState.java b/src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyState.java new file mode 100644 index 0000000..366811f --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/core/ServerSafetyState.java @@ -0,0 +1,105 @@ +package com.aizistral.nochatreports.common.core; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.jetbrains.annotations.Nullable; + +import com.aizistral.nochatreports.common.gui.UnsafeServerScreen; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +/** + * All this global state is questionable, but we have to... + * @author Aizistral + */ + +@Environment(EnvType.CLIENT) +public final class ServerSafetyState { + private static final List RESET_ACTIONS = new ArrayList<>(); + private static final List SIGNING_ACTIONS = new ArrayList<>(); + private static final AtomicBoolean ALLOW_CHAT_SIGNING = new AtomicBoolean(false); + private volatile static ServerSafetyLevel current = ServerSafetyLevel.UNDEFINED; + private volatile static ServerAddress lastServer = null; + + public static void updateCurrent(ServerSafetyLevel level) { + current = level; + } + + public static ServerSafetyLevel getCurrent() { + return current; + } + + public static boolean allowChatSigning() { + return ALLOW_CHAT_SIGNING.get(); + } + + public static CompletableFuture setAllowChatSigning(boolean allow) { + if (ALLOW_CHAT_SIGNING.compareAndSet(!allow, allow)) { + if (Minecraft.getInstance().player != null) { + var connection = Minecraft.getInstance().player.connection; + + if (allow && connection.chatSession == null) + return Minecraft.getInstance().getProfileKeyPairManager().prepareKeyPair() + .thenAcceptAsync(optional -> optional.ifPresent(profileKeyPair -> { + connection.setKeyPair(profileKeyPair); + SIGNING_ACTIONS.forEach(Runnable::run); + SIGNING_ACTIONS.clear(); + }), Minecraft.getInstance()); + } + } + + return CompletableFuture.completedFuture(null); + } + + public static void toggleChatSigning() { + setAllowChatSigning(!ALLOW_CHAT_SIGNING.get()); + } + + public static boolean isOnRealms() { + return current == ServerSafetyLevel.REALMS; + } + + public static boolean isInSingleplayer() { + return current == ServerSafetyLevel.SINGLEPLAYER; + } + + public static boolean isDetermined() { + return current != ServerSafetyLevel.UNINTRUSIVE && current != ServerSafetyLevel.UNDEFINED + && current != ServerSafetyLevel.UNKNOWN; + } + + @Nullable + public static ServerAddress getLastServer() { + return lastServer; + } + + public static void setLastServer(@Nullable ServerAddress address) { + lastServer = address; + } + + public static void scheduleResetAction(Runnable action) { + RESET_ACTIONS.add(action); + } + + public static void scheduleSigningAction(Runnable action) { + SIGNING_ACTIONS.add(action); + } + + public static void reset() { + lastServer = null; + current = ServerSafetyLevel.UNDEFINED; + ALLOW_CHAT_SIGNING.set(false); + UnsafeServerScreen.setHideThisSession(false); + + RESET_ACTIONS.forEach(Runnable::run); + RESET_ACTIONS.clear(); + SIGNING_ACTIONS.clear(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/core/SigningMode.java b/src/main/java/com/aizistral/nochatreports/common/core/SigningMode.java new file mode 100644 index 0000000..51e3d91 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/core/SigningMode.java @@ -0,0 +1,105 @@ +package com.aizistral.nochatreports.common.core; + +import org.jetbrains.annotations.Nullable; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; + +/** + * Signing modes control how NCR behaves with respect to chat signing. + * These can be enabled globally or per-server. + * + * @author Aizistral + */ + +public enum SigningMode { + + /** + * Special value that indicates signing behavior should be controlled by overarching + * configuration. + */ + DEFAULT, + + /** + * Never sign any messages, ignore server demands. + */ + NEVER, + + /** + * Always sign messages, regardless of whether the server asked to. + */ + ALWAYS, + + /** + * Don't sign by default, if server refuses to accept unsigned message - show GUI + * prompt which allows the user to enable signing or ignore server warnings for one + * session. + */ + PROMPT, + + /** + * Don't sign by default, if server refuses to accept unsigned message - immediately + * enable signing for one session and re-send that message. + */ + ON_DEMAND, + + /** + * Same as {@link SigningMode#NEVER}, but additionally indicates that signing cannot be + * turned on at all for some reason (i.e. missing keys or offline account). + */ + NEVER_FORCED; + + public String getNameKey() { + return "gui.nochatreports.signing_mode." + this.name().toLowerCase(); + } + + public MutableComponent getName() { + if (this != DEFAULT) + return Component.translatable(this.getNameKey()); + else + return Component.translatable(this.getNameKey(), NCRConfig.getClient().defaultSigningMode().getName()); + } + + public String getTooltipKey() { + return "gui.nochatreports.signing_mode." + this.name().toLowerCase() + ".tooltip"; + } + + public MutableComponent getTooltip() { + return Component.translatable(this.getTooltipKey()); + } + + public SigningMode next() { + SigningMode result = null; + + if (this.ordinal() == values().length - 1) { + result = values()[0]; + } else { + result = values()[this.ordinal() + 1]; + } + + return result.isSelectable() ? result : result.next(); + } + + public SigningMode resolve() { + return switch(this) { + case DEFAULT -> NCRConfig.getClient().defaultSigningMode(); + case NEVER_FORCED -> NEVER; + default -> this; + }; + } + + public boolean isSelectable() { + return this != NEVER_FORCED; + } + + public boolean isSelectableGlobally() { + return this.isSelectable() && this != DEFAULT; + } + + public static SigningMode nullable(@Nullable SigningMode mode) { + return mode == null ? DEFAULT : mode; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryption.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryption.java new file mode 100644 index 0000000..9908ec8 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryption.java @@ -0,0 +1,25 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; + +public class AESCFB8Encryption extends AESEncryption { + + protected AESCFB8Encryption() { + super("CFB8", "NoPadding", true); + } + + @Override + public AESCFB8Encryptor getProcessor(String key) throws InvalidKeyException { + return new AESCFB8Encryptor(key); + } + + @Override + public AESCFB8Encryptor getRandomProcessor() { + try { + return this.getProcessor(this.getRandomKey()); + } catch (InvalidKeyException ex) { + throw new RuntimeException(ex); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryptor.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryptor.java new file mode 100644 index 0000000..682cb91 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESCFB8Encryptor.java @@ -0,0 +1,43 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.nio.ByteBuffer; +import java.security.InvalidKeyException; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Random; + +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; + +import net.minecraft.util.Tuple; + +public class AESCFB8Encryptor extends AESEncryptor { + + protected AESCFB8Encryptor(String key) throws InvalidKeyException { + super(key, Encryption.AES_CFB8); + } + + protected AESCFB8Encryptor(SecretKey key, String mode, String padding, boolean iv) throws InvalidKeyException { + super(key, Encryption.AES_CFB8); + } + + @Override + protected Tuple generateIV() throws UnsupportedOperationException { + long nonce = RANDOM.nextLong(); + byte[] iv = new byte[16]; + new Random(nonce).nextBytes(iv); + return new Tuple<>(new IvParameterSpec(iv), ByteBuffer.allocate(8).putLong(nonce).array()); + } + + @Override + protected Tuple splitIV(byte[] message) throws UnsupportedOperationException { + ByteBuffer buffer = ByteBuffer.wrap(message); + int size = buffer.capacity(); + long nonce = buffer.getLong(); + byte[] encrypted = new byte[size - 8]; + buffer.get(encrypted); + byte[] iv = new byte[16]; + new Random(nonce).nextBytes(iv); + return new Tuple<>(new IvParameterSpec(iv), encrypted); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryption.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryption.java new file mode 100644 index 0000000..1c12c51 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryption.java @@ -0,0 +1,25 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; + +public class AESECBEncryption extends AESEncryption { + + protected AESECBEncryption() { + super("ECB", "PKCS5Padding", false); + } + + @Override + public AESECBEncryptor getProcessor(String key) throws InvalidKeyException { + return new AESECBEncryptor(key); + } + + @Override + public AESECBEncryptor getRandomProcessor() { + try { + return this.getProcessor(this.getRandomKey()); + } catch (InvalidKeyException ex) { + throw new RuntimeException(ex); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryptor.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryptor.java new file mode 100644 index 0000000..aa1f864 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESECBEncryptor.java @@ -0,0 +1,30 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.SecretKey; + +import net.minecraft.util.Tuple; + +public class AESECBEncryptor extends AESEncryptor { + + protected AESECBEncryptor(String key) throws InvalidKeyException { + super(key, Encryption.AES_ECB); + } + + protected AESECBEncryptor(SecretKey key, String mode, String padding, boolean iv) throws InvalidKeyException { + super(key, Encryption.AES_ECB); + } + + @Override + protected Tuple generateIV() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + protected Tuple splitIV(byte[] message) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryption.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryption.java new file mode 100644 index 0000000..91cd92a --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryption.java @@ -0,0 +1,93 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Random; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +import net.minecraft.util.StringUtil; + +public abstract class AESEncryption extends Encryption { + private final String mode, padding; + private final boolean requiresIV; + + protected AESEncryption(String mode, String padding, boolean requiresIV) { + super("aes_" + mode.toLowerCase() + "_base64", "AES/" + mode + "+Base64"); + this.mode = mode; + this.padding = padding; + this.requiresIV = requiresIV; + } + + @Override + public String getRandomKey() { + try { + KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); + keyGenerator.init(128); + SecretKey key = keyGenerator.generateKey(); + + return BASE64_ENCODER.encodeToString(key.getEncoded()); + } catch (NoSuchAlgorithmException ex) { + throw new RuntimeException(ex); + } + } + + @Override + public String getDefaultKey() { + return "blfrngArk3chG6wzncOZ5A=="; + } + + @Override + public boolean supportsPassphrases() { + return true; + } + + @Override + public String getPassphraseKey(String passphrase) { + try { + byte[] salt = new byte[16]; + new Random(1738389128127L).nextBytes(salt); + + KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt, 65536, 128); // AES-128 + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] key = factory.generateSecret(spec).getEncoded(); + + return BASE64_ENCODER.encodeToString(new SecretKeySpec(key, "AES").getEncoded()); + } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { + throw new RuntimeException(ex); + } + } + + @Override + public boolean validateKey(String key) { + if (StringUtil.isNullOrEmpty(key)) + return false; + + try { + this.getProcessor(key); + } catch (InvalidKeyException ex) { + return false; + } + + return true; + } + + public String getMode() { + return this.mode; + } + + public String getPadding() { + return this.padding; + } + + public boolean requiresIV() { + return this.requiresIV; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryptor.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryptor.java new file mode 100644 index 0000000..7e71d91 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESEncryptor.java @@ -0,0 +1,113 @@ +package com.aizistral.nochatreports.common.encryption; + +import static javax.crypto.Cipher.DECRYPT_MODE; +import static javax.crypto.Cipher.ENCRYPT_MODE; + +import java.nio.ByteBuffer; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.AEADBadTagException; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import net.minecraft.util.Tuple; + +public abstract class AESEncryptor extends Encryptor { + private final T encryption; + private final SecretKey key; + private final Cipher encryptor, decryptor; + private final boolean useIV; + + protected AESEncryptor(String key, T encryption) throws InvalidKeyException { + this(new SecretKeySpec(decodeBinaryKey(key), "AES"), encryption); + } + + protected AESEncryptor(SecretKey key, T encryption) throws InvalidKeyException { + this.encryption = encryption; + this.useIV = encryption.requiresIV(); + String mode = encryption.getMode(); + String padding = encryption.getPadding(); + + try { + this.key = key; + + Cipher encryptor = Cipher.getInstance(this.key.getAlgorithm() + "/" + mode + "/" + padding); + if (this.useIV) { + encryptor.init(ENCRYPT_MODE, this.key, this.generateIV().getA()); + } else { + encryptor.init(ENCRYPT_MODE, this.key); + + } + this.encryptor = encryptor; + + Cipher decryptor = Cipher.getInstance(this.key.getAlgorithm() + "/" + mode + "/" + padding); + if (this.useIV) { + decryptor.init(DECRYPT_MODE, this.key, this.generateIV().getA()); + } else { + decryptor.init(DECRYPT_MODE, this.key); + } + this.decryptor = decryptor; + } catch (NoSuchAlgorithmException | NoSuchPaddingException ex) { + throw new RuntimeException(ex); + } catch (InvalidAlgorithmParameterException ex) { + throw new InvalidKeyException(ex); + } + } + + @Override + public String encrypt(String message) { + try { + if (this.useIV) { + var tuple = this.generateIV(); + + this.encryptor.init(ENCRYPT_MODE, this.key, tuple.getA()); + byte[] encrypted = this.encryptor.doFinal(toBytes(message)); + + return encodeBase64R(ByteBuffer.allocate(encrypted.length + tuple.getB().length).put(tuple.getB()) + .put(encrypted).array()); + } else + return encodeBase64R(this.encryptor.doFinal(toBytes(message))); + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { + throw new RuntimeException(ex); + } + } + + @Override + public String decrypt(String message) { + try { + if (this.useIV) { + var tuple = this.splitIV(decodeBase64RBytes(message)); + + this.decryptor.init(DECRYPT_MODE, this.key, tuple.getA()); + return fromBytes(this.decryptor.doFinal(tuple.getB())); + } else + return fromBytes(this.decryptor.doFinal(decodeBase64RBytes(message))); + } catch (AEADBadTagException ex) { + return "???"; + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { + throw new RuntimeException(ex); + } + } + + @Override + public String getKey() { + return encodeBinaryKey(this.key.getEncoded()); + } + + @Override + public T getAlgorithm() { + return this.encryption; + } + + protected abstract Tuple generateIV() throws UnsupportedOperationException; + + protected abstract Tuple splitIV(byte[] message) throws UnsupportedOperationException; + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryption.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryption.java new file mode 100644 index 0000000..d94b6fc --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryption.java @@ -0,0 +1,25 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; + +public class AESGCMEncryption extends AESEncryption { + + protected AESGCMEncryption() { + super("GCM", "NoPadding", true); + } + + @Override + public AESGCMEncryptor getProcessor(String key) throws InvalidKeyException { + return new AESGCMEncryptor(key); + } + + @Override + public AESGCMEncryptor getRandomProcessor() { + try { + return this.getProcessor(this.getRandomKey()); + } catch (InvalidKeyException ex) { + throw new RuntimeException(ex); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryptor.java b/src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryptor.java new file mode 100644 index 0000000..f91a0ab --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/AESGCMEncryptor.java @@ -0,0 +1,37 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.nio.ByteBuffer; +import java.security.InvalidKeyException; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; + +import net.minecraft.util.Tuple; + +public class AESGCMEncryptor extends AESEncryptor { + + protected AESGCMEncryptor(String key) throws InvalidKeyException { + super(key, Encryption.AES_GCM); + } + + protected AESGCMEncryptor(SecretKey key) throws InvalidKeyException { + super(key, Encryption.AES_GCM); + } + + @Override + protected Tuple generateIV() throws UnsupportedOperationException { + byte[] iv = new byte[12]; + RANDOM.nextBytes(iv); + return new Tuple<>(new GCMParameterSpec(96, iv), iv); + } + + @Override + protected Tuple splitIV(byte[] message) throws UnsupportedOperationException { + byte[] iv = new byte[12]; + byte[] msg = new byte[message.length - 12]; + ByteBuffer.wrap(message).get(iv).get(msg); + return new Tuple<>(new GCMParameterSpec(96, iv), msg); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryption.java b/src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryption.java new file mode 100644 index 0000000..27a1261 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryption.java @@ -0,0 +1,56 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; +import java.security.SecureRandom; + +public class CaesarEncryption extends Encryption { + + protected CaesarEncryption() { + super("caesar", "Caesar"); + } + + @Override + public String getRandomKey() { + return String.valueOf(1 + new SecureRandom().nextInt(1024)); + } + + @Override + public String getDefaultKey() { + return "3"; + } + + @Override + public boolean supportsPassphrases() { + return false; + } + + @Override + public String getPassphraseKey(String passphrase) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public boolean validateKey(String key) { + try { + int value = Integer.valueOf(key); + return value > 0 && value < 1025; + } catch (NumberFormatException ex) { + return false; + } + } + + @Override + public CaesarEncryptor getProcessor(String key) throws InvalidKeyException { + return new CaesarEncryptor(key); + } + + @Override + public CaesarEncryptor getRandomProcessor() { + try { + return this.getProcessor(this.getRandomKey()); + } catch (InvalidKeyException ex) { + throw new RuntimeException(ex); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryptor.java b/src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryptor.java new file mode 100644 index 0000000..7eb8010 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/CaesarEncryptor.java @@ -0,0 +1,70 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; + +public class CaesarEncryptor extends Encryptor { + private static final char PARAGRAPH = '\u00a7', PARAGRAPH_PLACEHOLDER = '\uffef', + DELETE = '\u007f', DELETE_PLACEHOLDER = '\ufff0'; + private final int shift; + + protected CaesarEncryptor(int shift) throws InvalidKeyException { + if (!Encryption.CAESAR.validateKey(String.valueOf(shift))) + throw new InvalidKeyException(); + this.shift = shift; + } + + protected CaesarEncryptor(String key) throws InvalidKeyException { + this.shift = fromString(key); + } + + @Override + public String encrypt(String message) { + char[] chars = ensureUTF8(message).toCharArray(); + + for (int i = 0; i < chars.length; i++) { + chars[i] = (char) (chars[i] + this.shift); + + if (chars[i] == PARAGRAPH) { + chars[i] = PARAGRAPH_PLACEHOLDER; + } else if (chars[i] == DELETE) { + chars[i] = DELETE_PLACEHOLDER; + } + } + + return new String(chars); + } + + @Override + public String decrypt(String message) { + char[] chars = ensureUTF8(message).toCharArray(); + + for (int i = 0; i < chars.length; i++) { + if (chars[i] == PARAGRAPH_PLACEHOLDER) { + chars[i] = PARAGRAPH; + } else if (chars[i] == DELETE_PLACEHOLDER) { + chars[i] = DELETE; + } + + chars[i] = (char) (chars[i] - this.shift); + } + + return new String(chars); + } + + @Override + public CaesarEncryption getAlgorithm() { + return Encryption.CAESAR; + } + + @Override + public String getKey() { + return String.valueOf(this.shift); + } + + private static int fromString(String key) throws InvalidKeyException { + if (!Encryption.CAESAR.validateKey(key)) + throw new InvalidKeyException(key); + return Integer.valueOf(key); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/Encryption.java b/src/main/java/com/aizistral/nochatreports/common/encryption/Encryption.java new file mode 100644 index 0000000..259d89d --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/Encryption.java @@ -0,0 +1,59 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.security.InvalidKeyException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; + +public abstract class Encryption { + private static final List REGISTERED = new ArrayList<>(); + protected static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); + protected static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); + + public static final AESCFB8Encryption AES_CFB8 = new AESCFB8Encryption(); + public static final AESGCMEncryption AES_GCM = new AESGCMEncryption(); + public static final AESECBEncryption AES_ECB = new AESECBEncryption(); + public static final CaesarEncryption CAESAR = new CaesarEncryption(); + + private final String id, name; + + protected Encryption(String id, String name) { + this.id = id; + this.name = name; + + if (REGISTERED.stream().filter(e -> e.getID().equals(id) || e.getName().equals(name)) + .findAny().isPresent()) + throw new IllegalStateException("Duplicate encryption algorithm registered! ID: " + this.getID() + + ", Name: " + this.getName()); + + REGISTERED.add(this); + } + + public String getID() { + return this.id; + } + + public String getName() { + return this.name; + } + + public abstract String getRandomKey(); + + public abstract String getDefaultKey(); + + public abstract boolean supportsPassphrases(); + + public abstract String getPassphraseKey(String passphrase) throws UnsupportedOperationException; + + public abstract boolean validateKey(String key); + + public abstract Encryptor getProcessor(String key) throws InvalidKeyException; + + public abstract Encryptor getRandomProcessor(); + + public static List getRegistered() { + return Collections.unmodifiableList(REGISTERED); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/encryption/Encryptor.java b/src/main/java/com/aizistral/nochatreports/common/encryption/Encryptor.java new file mode 100644 index 0000000..61718a4 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/encryption/Encryptor.java @@ -0,0 +1,182 @@ +package com.aizistral.nochatreports.common.encryption; + +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.SecureRandom; +import java.util.Arrays; + +import it.unimi.dsi.fastutil.chars.Char2CharArrayMap; +import it.unimi.dsi.fastutil.chars.Char2CharMap; +import it.unimi.dsi.fastutil.chars.Char2CharMaps; + +public abstract class Encryptor { + protected static final SecureRandom RANDOM = new SecureRandom(); + protected static final Char2CharMap BASE64R_SHIFTS = createBase64RShifts(); + protected static final Char2CharMap BASE64R_SHIFTS_REVERSE = createBase64RShiftsReverse(); + + protected Encryptor() { + // NO-OP + } + + public abstract String encrypt(String message); + + public abstract String decrypt(String message); + + public abstract T getAlgorithm(); + + public abstract String getKey(); + + protected static String shiftBase64R(String string) { + char[] chars = ensureUTF8(string).toCharArray(); + + for (int i = 0; i < chars.length; i++) { + chars[i] = BASE64R_SHIFTS.get(chars[i]); + } + + return new String(chars); + } + + protected static String unshiftBase64R(String string) { + char[] chars = ensureUTF8(string).toCharArray(); + + for (int i = 0; i < chars.length; i++) { + chars[i] = BASE64R_SHIFTS_REVERSE.get(chars[i]); + } + + return new String(chars); + } + + protected static byte[] toBytes(String string) { + return string.getBytes(StandardCharsets.UTF_8); + } + + protected static String fromBytes(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + protected static String ensureUTF8(String string) { + return fromBytes(toBytes(string)); + } + + protected static String encodeBase64R(String string) { + return encodeBase64R(toBytes(string)); + } + + protected static String encodeBase64R(byte[] bytes) { + return shiftBase64R(fromBytes(Encryption.BASE64_ENCODER.encode(bytes))); + } + + protected static byte[] encodeBase64RBytes(String string) { + return toBytes(encodeBase64R(toBytes(string))); + } + + protected static String decodeBase64R(String string) { + return fromBytes(decodeBase64RBytes(string)); + } + + protected static byte[] decodeBase64RBytes(String string) { + return Encryption.BASE64_DECODER.decode(toBytes(unshiftBase64R(string))); + } + + protected static String encodeBinaryKey(byte[] key) { + return fromBytes(Encryption.BASE64_ENCODER.encode(key)); + } + + protected static byte[] decodeBinaryKey(String key) throws InvalidKeyException { + try { + return Encryption.BASE64_DECODER.decode(toBytes(key)); + } catch (Exception ex) { + throw new InvalidKeyException(ex); + } + } + + protected static byte[] mergeBytes(byte[] array1, byte[] array2) { + byte[] result = Arrays.copyOf(array1, array1.length + array2.length); + System.arraycopy(array2, 0, result, array1.length, array2.length); + return result; + } + + private static Char2CharMap createBase64RShiftsReverse() { + Char2CharMap map = createBase64RShifts(); + Char2CharMap reverse = new Char2CharArrayMap(64); + + for (char ch : map.keySet()) { + reverse.put(map.get(ch), ch); + } + + return Char2CharMaps.unmodifiable(reverse); + } + + private static Char2CharMap createBase64RShifts() { + Char2CharMap map = new Char2CharArrayMap(64); + + map.put('A', '!'); + map.put('B', '"'); + map.put('C', '#'); + map.put('D', '$'); + map.put('E', '%'); + map.put('F', '¼'); + map.put('G', '\''); + map.put('H', '('); + map.put('I', ')'); + map.put('J', ','); + map.put('K', '-'); + map.put('L', '.'); + map.put('M', ':'); + map.put('N', ';'); + map.put('O', '<'); + map.put('P', '='); + map.put('Q', '>'); + map.put('R', '?'); + map.put('S', '@'); + map.put('T', '['); + map.put('U', '\\'); + map.put('V', ']'); + map.put('W', '^'); + map.put('X', '_'); + map.put('Y', '`'); + map.put('Z', '{'); + map.put('a', '|'); + map.put('b', '}'); + map.put('c', '~'); + map.put('d', '¡'); + map.put('e', '¢'); + map.put('f', '£'); + map.put('g', '¤'); + map.put('h', '¥'); + map.put('i', '¦'); + map.put('j', '¨'); + map.put('k', '©'); + map.put('l', 'ª'); + map.put('m', '«'); + map.put('n', '¬'); + map.put('o', '®'); + map.put('p', '¯'); + map.put('q', '°'); + map.put('r', '±'); + map.put('s', '²'); + map.put('t', '³'); + map.put('u', 'µ'); + map.put('v', '¶'); + map.put('w', '·'); + map.put('x', '×'); + map.put('y', '¹'); + map.put('z', 'º'); + map.put('0', '0'); + map.put('1', '1'); + map.put('2', '2'); + map.put('3', '3'); + map.put('4', '4'); + map.put('5', '5'); + map.put('6', '6'); + map.put('7', '7'); + map.put('8', '8'); + map.put('9', '9'); + map.put('+', '+'); + map.put('/', '»'); + map.put('=', '¿'); + + return Char2CharMaps.unmodifiable(map); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/AdaptiveWarningScreen.java b/src/main/java/com/aizistral/nochatreports/common/gui/AdaptiveWarningScreen.java new file mode 100644 index 0000000..931645c --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/AdaptiveWarningScreen.java @@ -0,0 +1,78 @@ +package com.aizistral.nochatreports.common.gui; + +import org.jetbrains.annotations.Nullable; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.gui.components.Checkbox; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +public abstract class AdaptiveWarningScreen extends Screen { + private final Component title; + private final Component content; + private final Component narration; + @Nullable + protected final Screen previous; + @Nullable + private final Component check; + @Nullable + protected Checkbox stopShowing = null; + protected MultiLineLabel message = MultiLineLabel.EMPTY; + + public AdaptiveWarningScreen(Component title, Component content, @Nullable Component check, + @Nullable Screen previous) { + super(title); + this.title = title; + this.content = content; + this.check = check; + this.narration = this.title.copy().append("\n").append(this.content); + this.previous = previous; + } + + @Override + protected void init() { + this.clearWidgets(); + super.init(); + this.message = MultiLineLabel.create(this.font, this.content, this.width - (this.hugeGUI() ? 65 : 100)); + int i = (this.message.getLineCount() + 1) * this.getLineHeight(); + if (this.check != null) { + int checkY = this.hugeGUI() ? 27 : 76; + int j = this.font.width(this.check); + + if (this.check != null) { + this.stopShowing = new Checkbox(this.width / 2 - j / 2 - 8, checkY + i, j + 24, 20, this.check, false); + this.addRenderableWidget(this.stopShowing); + } + } + this.initButtons(i + (this.hugeGUI() ? 55 : 100)); + } + + protected abstract void initButtons(int y); + + @Override + public void render(PoseStack poseStack, int i, int j, float f) { + this.renderBackground(poseStack); + this.renderTitle(poseStack); + int k = this.width / 2 - this.message.getWidth() / 2; + this.message.renderLeftAligned(poseStack, k, this.hugeGUI() ? 35 : 70, this.getLineHeight(), 0xFFFFFF); + super.render(poseStack, i, j, f); + } + + private void renderTitle(PoseStack poseStack) { + drawString(poseStack, this.font, this.title, 25, this.hugeGUI() ? 15 : 30, 0xFFFFFF); + } + + private boolean hugeGUI() { + return this.height <= 1080 / 4; + } + + protected int getLineHeight() { + if (this.hugeGUI()) + return (int) (this.minecraft.font.lineHeight * 1.5) + 1; + else + return this.minecraft.font.lineHeight * 2; + } + +} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/AdvancedImageButton.java b/src/main/java/com/aizistral/nochatreports/common/gui/AdvancedImageButton.java new file mode 100644 index 0000000..6d4cd1a --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/AdvancedImageButton.java @@ -0,0 +1,41 @@ +package com.aizistral.nochatreports.common.gui; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.gui.components.ImageButton; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +@Environment(EnvType.CLIENT) +public class AdvancedImageButton extends ImageButton { + protected final Screen parent; + + public AdvancedImageButton(int x, int y, int xSize, int ySize, int xTexStart, int yTexStart, int yStateDiff, + ResourceLocation texture, int textureWidth, int textureHeight, OnPress onPress, Component name, + Screen parent) { + super(x, y, xSize, ySize, xTexStart, yTexStart, yStateDiff, texture, textureWidth, textureHeight, onPress, name); + this.parent = parent; + } + + @Override + public void updateTooltip() { + if (this.tooltip instanceof AdvancedTooltip tooltip && tooltip.hasCustomRender()) + return; + + super.updateTooltip(); + } + + @Override + public void renderButton(PoseStack poseStack, int mouseX, int mouseY, float delta) { + super.renderButton(poseStack, mouseX, mouseY, delta); + + if (this.isHovered) + if (this.tooltip instanceof AdvancedTooltip tooltip && tooltip.hasCustomRender()) { + tooltip.doCustomRender(this.parent, poseStack, mouseX, mouseY); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/AdvancedTooltip.java b/src/main/java/com/aizistral/nochatreports/common/gui/AdvancedTooltip.java new file mode 100644 index 0000000..e3de67f --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/AdvancedTooltip.java @@ -0,0 +1,183 @@ +package com.aizistral.nochatreports.common.gui; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; + +@Environment(EnvType.CLIENT) +public class AdvancedTooltip extends Tooltip { + @Nullable + protected Supplier supplier; + protected int maxWidth = MAX_WIDTH; + protected boolean renderWithoutGap = false; + + public AdvancedTooltip(Component message, @Nullable Component narration) { + super(message, narration); + } + + public AdvancedTooltip(Component message) { + this(message, message); + } + + public AdvancedTooltip(Supplier message) { + this(message.get()); + this.supplier = message; + } + + public AdvancedTooltip setMaxWidth(int maxWidth) { + this.maxWidth = maxWidth; + return this; + } + + public AdvancedTooltip setRenderWithoutGap(boolean render) { + this.renderWithoutGap = render; + return this; + } + + public Component getMessage() { + return this.supplier != null ? this.supplier.get() : this.message; + } + + @Override + public List toCharSequence(Minecraft minecraft) { + if (this.supplier == null) { + if (this.cachedTooltip == null) { + this.cachedTooltip = splitTooltip(minecraft, this.getMessage(), this.maxWidth); + } + return this.cachedTooltip; + } else + return splitTooltip(minecraft, this.getMessage(), this.maxWidth); + } + + public boolean hasCustomRender() { + return this.renderWithoutGap; + } + + public void doCustomRender(Screen screen, PoseStack poseStack, int x, int y) { + if (this.renderWithoutGap) { + this.renderTooltipNoGap(screen, poseStack, splitTooltip(screen.minecraft, this.getMessage(), this.maxWidth), x, y); + } else + throw new UnsupportedOperationException("This tooltip doesn't support custom render!"); + } + + public static List splitTooltip(Minecraft minecraft, Component component, int maxWidth) { + return minecraft.font.split(component, maxWidth); + } + + protected void renderTooltipNoGap(Screen screen, PoseStack poseStack, List list, int x, int y) { + this.renderTooltipInternalNoGap(screen, poseStack, list.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), x, y); + } + + protected void renderTooltipInternalNoGap(Screen screen, PoseStack poseStack, List list, int x, int y) { + ClientTooltipComponent clientTooltipComponent2; + int v; + int m; + if (list.isEmpty()) + return; + int k = 0; + int l = list.size() == 1 ? -2 : -2; + for (ClientTooltipComponent clientTooltipComponent : list) { + m = clientTooltipComponent.getWidth(screen.font); + if (m > k) { + k = m; + } + l += clientTooltipComponent.getHeight(); + } + int n = x + 12; + int o = y - 12; + m = k; + int p = l; + if (n + k > screen.width) { + n -= 28 + k; + } + if (o + p + 6 > screen.height) { + o = screen.height - p - 6; + } + if (y - p - 8 < 0) { + o = y + 8; + } + poseStack.pushPose(); + int q = -267386864; + int r = 0x505000FF; + int s = 1344798847; + int t = 400; + float f = screen.itemRenderer.blitOffset; + screen.itemRenderer.blitOffset = 400.0f; + Tesselator tesselator = Tesselator.getInstance(); + BufferBuilder bufferBuilder = tesselator.getBuilder(); + RenderSystem.setShader(GameRenderer::getPositionColorShader); + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + Matrix4f matrix4f = poseStack.last().pose(); + fillGradient(matrix4f, bufferBuilder, n - 3, o - 4, n + m + 3, o - 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, n - 3, o + p + 3, n + m + 3, o + p + 4, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, n - 3, o - 3, n + m + 3, o + p + 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, n - 4, o - 3, n - 3, o + p + 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, n + m + 3, o - 3, n + m + 4, o + p + 3, 400, -267386864, -267386864); + fillGradient(matrix4f, bufferBuilder, n - 3, o - 3 + 1, n - 3 + 1, o + p + 3 - 1, 400, 0x505000FF, 1344798847); + fillGradient(matrix4f, bufferBuilder, n + m + 2, o - 3 + 1, n + m + 3, o + p + 3 - 1, 400, 0x505000FF, 1344798847); + fillGradient(matrix4f, bufferBuilder, n - 3, o - 3, n + m + 3, o - 3 + 1, 400, 0x505000FF, 0x505000FF); + fillGradient(matrix4f, bufferBuilder, n - 3, o + p + 2, n + m + 3, o + p + 3, 400, 1344798847, 1344798847); + RenderSystem.enableDepthTest(); + RenderSystem.disableTexture(); + RenderSystem.enableBlend(); + RenderSystem.defaultBlendFunc(); + BufferUploader.drawWithShader(bufferBuilder.end()); + RenderSystem.disableBlend(); + RenderSystem.enableTexture(); + MultiBufferSource.BufferSource bufferSource = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder()); + poseStack.translate(0.0, 0.0, 400.0); + int u = o; + for (v = 0; v < list.size(); ++v) { + clientTooltipComponent2 = list.get(v); + clientTooltipComponent2.renderText(screen.font, n, u, matrix4f, bufferSource); + u += clientTooltipComponent2.getHeight() /*+ (v == 0 ? 2 : 0)*/; + } + bufferSource.endBatch(); + poseStack.popPose(); + u = o; + for (v = 0; v < list.size(); ++v) { + clientTooltipComponent2 = list.get(v); + clientTooltipComponent2.renderImage(screen.font, n, u, poseStack, screen.itemRenderer, 400); + u += clientTooltipComponent2.getHeight() + (v == 0 ? 2 : 0); + } + screen.itemRenderer.blitOffset = f; + } + + protected static void fillGradient(Matrix4f matrix4f, BufferBuilder bufferBuilder, int i, int j, int k, int l, int m, int n, int o) { + float f = (n >> 24 & 0xFF) / 255.0f; + float g = (n >> 16 & 0xFF) / 255.0f; + float h = (n >> 8 & 0xFF) / 255.0f; + float p = (n & 0xFF) / 255.0f; + float q = (o >> 24 & 0xFF) / 255.0f; + float r = (o >> 16 & 0xFF) / 255.0f; + float s = (o >> 8 & 0xFF) / 255.0f; + float t = (o & 0xFF) / 255.0f; + bufferBuilder.vertex(matrix4f, k, j, m).color(g, h, p, f).endVertex(); + bufferBuilder.vertex(matrix4f, i, j, m).color(g, h, p, f).endVertex(); + bufferBuilder.vertex(matrix4f, i, l, m).color(r, s, t, q).endVertex(); + bufferBuilder.vertex(matrix4f, k, l, m).color(r, s, t, q).endVertex(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionButton.java b/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionButton.java new file mode 100644 index 0000000..44d286f --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionButton.java @@ -0,0 +1,40 @@ +package com.aizistral.nochatreports.common.gui; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +public class EncryptionButton extends AdvancedImageButton { + + public EncryptionButton(int x, int y, int xSize, int ySize, int xTexStart, int yTexStart, int yStateDiff, + ResourceLocation texture, int textureWidth, int textureHeight, OnPress onPress, Component name, Screen parent) { + super(x, y, xSize, ySize, xTexStart, yTexStart, yStateDiff, texture, textureWidth, textureHeight, onPress, name, parent); + } + + @Override + public boolean mouseClicked(double x, double y, int i) { + if (!this.active || !this.visible) + return false; + + if (i == 1 && this.clicked(x, y)) { + this.playDownSound(Minecraft.getInstance().getSoundManager()); + this.openEncryptionConfig(); + return true; + } + + return super.mouseClicked(x, y, i); + } + + public void openEncryptionConfig() { + if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled() + && !NCRConfig.getEncryption().isEnabledAndValid()) { + Minecraft.getInstance().setScreen(new EncryptionWarningScreen(this.parent)); + } else { + Minecraft.getInstance().setScreen(new EncryptionConfigScreen(this.parent)); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionConfigScreen.java b/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionConfigScreen.java new file mode 100644 index 0000000..c0cdb47 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionConfigScreen.java @@ -0,0 +1,283 @@ +package com.aizistral.nochatreports.common.gui; + +import java.util.Objects; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.config.NCRConfigEncryption; +import com.aizistral.nochatreports.common.encryption.Encryption; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.Checkbox; +import net.minecraft.client.gui.components.CycleButton; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.ImageButton; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.StringUtil; + +@Environment(EnvType.CLIENT) +public class EncryptionConfigScreen extends Screen { + private static final ResourceLocation ENCRYPTION_ICONS = new ResourceLocation("nochatreports", "textures/gui/encryption_gui_icons.png"); + private static final Component HEADER = Component.translatable("gui.nochatreports.encryption_config.header"); + private static final Component KEY_DESC = Component.translatable("gui.nochatreports.encryption_config.key_desc"); + private static final Component PASS_DESC = Component.translatable("gui.nochatreports.encryption_config.passphrase_desc"); + private static final Component VALIDATION_OK = Component.translatable("gui.nochatreports.encryption_config.validation_ok"); + private static final Component VALIDATION_FAILED = Component.translatable("gui.nochatreports.encryption_config.validation_failed"); + private static final Component DICE_TOOLTIP = Component.translatable("gui.nochatreports.encryption_config.dice_tooltip"); + private static final Component PASS_NOT_ALLOWED = Component.translatable("gui.nochatreports.encryption_config.pass_not_allowed"); + private static final Component ENCRYPT_PUBLIC = Component.translatable("gui.nochatreports.encryption_config.encrypt_public"); + + private static final int FIELDS_Y_START = 45; + private final Screen previous; + private CustomEditBox keyField, passField; + private ImageButton validationIcon; + private CycleButton algorithmButton; + private MultiLineLabel keyDesc = MultiLineLabel.EMPTY, passDesc = MultiLineLabel.EMPTY; + protected Checkbox encryptPublicCheck; + private boolean settingPassKey = false; + + public EncryptionConfigScreen(Screen previous) { + super(CommonComponents.EMPTY); + this.previous = previous; + } + + private NCRConfigEncryption getConfig() { + return NCRConfig.getEncryption(); + } + + @Override + protected void init() { + this.clearWidgets(); + super.init(); + + int w = (int) (this.width * (this.hugeGUI() ? 0.9 : 0.7)); + + this.keyDesc = MultiLineLabel.create(this.font, KEY_DESC, w - 5); + int keyDescSpace = (this.keyDesc.getLineCount() + 1) * this.getLineHeight(); + + this.passDesc = MultiLineLabel.create(this.font, PASS_DESC, w - 5); + int passDescSpace = (this.passDesc.getLineCount() + 1) * this.getLineHeight(); + + w -= 52; + + this.keyField = new CustomEditBox(this.font, (this.width - w)/2 - 2, (this.hugeGUI() ? 25 : FIELDS_Y_START) + keyDescSpace - 15, + w, 18, CommonComponents.EMPTY); + this.keyField.setMaxLength(512); + this.keyField.setResponder(this::onKeyUpdate); + this.addWidget(this.keyField); + + var button = new AdvancedImageButton(this.keyField.getX() + this.keyField.getWidth() - 15, this.keyField.getY() + 3, 12, + 12, 0, 0, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, Component.empty(), this); + button.setTooltip(new AdvancedTooltip(() -> this.validationIcon != null && + this.validationIcon.yTexStart == 0 ? VALIDATION_OK : VALIDATION_FAILED).setMaxWidth(250)); + button.active = false; + button.visible = true; + + this.addRenderableOnly(this.validationIcon = button); + + button = new AdvancedImageButton(this.keyField.getX() - 22, this.keyField.getY() - 0, 18, 18, 0, + 28, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, Component.empty(), this); + button.active = false; + button.visible = true; + + this.addRenderableOnly(button); + + button = new AdvancedImageButton(this.keyField.getX() + this.keyField.getWidth() + 4, this.keyField.getY() - 1, 23, 20, 41, + 24, 20, ENCRYPTION_ICONS, 64, 64, btn -> { + this.unfocusFields(); + this.keyField.setValue(this.algorithmButton.getValue().getRandomKey()); + }, Component.empty(), this); + button.setTooltip(new AdvancedTooltip(DICE_TOOLTIP).setMaxWidth(250)); + button.active = true; + button.visible = true; + + this.addRenderableWidget(button); + + w += 25; + + this.passField = new CustomEditBox(this.font, (this.width - w)/2 + 11, this.keyField.getY() + + this.keyField.getHeight() + passDescSpace + (this.hugeGUI() ? -3 : 13), w, 18, CommonComponents.EMPTY); + this.passField.setMaxLength(512); + this.passField.setResponder(this::onPassphraseUpdate); + this.addWidget(this.passField); + + button = new AdvancedImageButton(this.passField.getX() - 22, this.passField.getY() - 0, 18, 18, 0, + 46, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, Component.empty(), this); + button.active = false; + button.visible = true; + + this.addRenderableOnly(button); + + int checkWidth = this.font.width(ENCRYPT_PUBLIC); + this.encryptPublicCheck = new Checkbox(this.width / 2 - checkWidth / 2 - 8, this.passField.getY() + 24, checkWidth + 24, 20, + ENCRYPT_PUBLIC, NCRConfig.getEncryption().shouldEncryptPublic()); + this.addRenderableWidget(this.encryptPublicCheck); + + this.addRenderableWidget(Button.builder(CommonComponents.GUI_DONE, btn -> { + this.onDone(); + this.onClose(); + }).pos(this.width / 2 + 4, this.passField.getY() + 48).size(219, 20).build()); + + CycleButton cycle = CycleButton.builder(value -> { + return Component.translatable("gui.nochatreports.encryption_config.algorithm", + Component.translatable("algorithm.nochatreports." + value.getID() + ".name")); + }).withValues(Encryption.getRegistered()).displayOnlyValue().withInitialValue(this.getConfig() + .getAlgorithm()).withTooltip(value -> new AdvancedTooltip(Component.translatable( + "algorithm.nochatreports." + value.getID())).setMaxWidth(250)) + .create(this.width / 2 - 4 - 218, this.passField.getY() + 48, 218, 20, CommonComponents.EMPTY, + (cycleButton, value) -> { + this.unfocusFields(); + this.onAlgorithmUpdate(value); + }); + + this.addRenderableWidget(this.algorithmButton = cycle); + + this.onAlgorithmUpdate(this.algorithmButton.getValue()); + + if (!StringUtil.isNullOrEmpty(this.getConfig().getEncryptionPassphrase())) { + this.passField.setValue(this.getConfig().getEncryptionPassphrase()); + } else if (!StringUtil.isNullOrEmpty(this.getConfig().getEncryptionKey())) { + if (!Objects.equals(this.getConfig().getEncryptionKey(), this.algorithmButton.getValue() + .getDefaultKey())) { + this.keyField.setValue(this.getConfig().getEncryptionKey()); + } else { + this.keyField.setValue(""); + } + } + } + + @Override + public void render(PoseStack poseStack, int i, int j, float f) { + if (!this.passField.isActive()) { + if (this.passField.isFocused()) { + this.passField.setFocused(false); + } + this.passField.setEditable(false); + } + + this.renderBackground(poseStack); + Screen.drawCenteredString(poseStack, this.font, HEADER, this.width / 2, this.hugeGUI() ? 8 : 16, 0xFFFFFF); + + this.keyDesc.renderLeftAligned(poseStack, this.keyField.getX() - 20, (this.hugeGUI() ? 25 : FIELDS_Y_START), this.getLineHeight(), 0xFFFFFF); + + this.keyField.render(poseStack, i, j, f); + + this.passDesc.renderLeftAligned(poseStack, this.passField.getX() - 20, this.keyField.getY() + this.keyField.getHeight() + (this.hugeGUI() ? 12 : 28), + this.getLineHeight(), 0xFFFFFF); + + this.passField.render(poseStack, i, j, f); + + // if (this.algorithmButton != null && this.algorithmButton.isMouseOver(i, j)) { + // this.renderTooltip(poseStack, this.algorithmButton.getTooltip(), i, j); + // } + + super.render(poseStack, i, j, f); + + if (StringUtil.isNullOrEmpty(this.keyField.getValue()) && !this.keyField.isFocused()) { + Screen.drawString(poseStack, this.font, + Component.translatable("gui.nochatreports.encryption_config.default_key", + this.algorithmButton.getValue().getDefaultKey()), this.keyField.getX() + 4, + this.keyField.getY() + 5, 0x999999); + } + + if (!this.passField.active) { + Screen.drawString(poseStack, this.font, PASS_NOT_ALLOWED, this.passField.getX() + 4, + this.passField.getY() + 5, 0x999999); + RenderSystem.setShaderTexture(0, ENCRYPTION_ICONS); + RenderSystem.enableDepthTest(); + blit(poseStack, this.passField.getX() - 20, this.passField.getY() + 3, 50, 0, 14, 13, 64, 64); + } + } + + private int getLineHeight() { + if (this.hugeGUI()) + return (int) (this.minecraft.font.lineHeight * 1.5) + 1; + else + return this.minecraft.font.lineHeight * 2; + } + + @Override + public void tick() { + this.keyField.tick(); + } + + private void onKeyUpdate(String key) { + if (!this.settingPassKey) { + this.passField.setValue(""); + } + + if (!StringUtil.isNullOrEmpty(key)) { + this.validationIcon.yTexStart = this.algorithmButton.getValue().validateKey(key) ? 0 : 12; + } else { + this.validationIcon.yTexStart = 0; + } + } + + private void onPassphraseUpdate(String pass) { + Encryption encryption = this.algorithmButton.getValue(); + + this.settingPassKey = true; + if (!StringUtil.isNullOrEmpty(pass)) { + if (encryption.supportsPassphrases()) { + this.keyField.setValue(encryption.getPassphraseKey(pass)); + } + } else { + this.onKeyUpdate(this.keyField.getValue()); + } + this.settingPassKey = false; + } + + private void onAlgorithmUpdate(Encryption encryption) { + if (!encryption.supportsPassphrases()) { + this.passField.setFocused(false); + this.passField.setEditable(this.passField.active = false); + this.onKeyUpdate(this.keyField.getValue()); + } else { + this.passField.setEditable(this.passField.active = true); + this.onPassphraseUpdate(this.passField.getValue()); + } + } + + private void unfocusFields() { + this.keyField.setFocused(false); + this.passField.setFocused(false); + } + + private void onDone() { + var config = NCRConfig.getEncryption(); + var encryption = this.algorithmButton.getValue(); + config.setAlgorithm(encryption); + config.setEncryptionKey(!StringUtil.isNullOrEmpty(this.keyField.getValue()) ? this.keyField.getValue() + : encryption.getDefaultKey()); + config.setEncryptPublic(this.encryptPublicCheck.selected()); + } + + private boolean hugeGUI() { + return this.height <= 1080 / 4; + } + + @Override + public void onClose() { + this.minecraft.setScreen(this.previous); + } + + private static class CustomEditBox extends EditBox { + public CustomEditBox(Font font, int i, int j, int k, int l, Component component) { + super(font, i, j, k, l, component); + } + + @Override + public void setFocused(boolean bl) { + super.setFocused(bl); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionWarningScreen.java b/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionWarningScreen.java new file mode 100644 index 0000000..954c6f3 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/EncryptionWarningScreen.java @@ -0,0 +1,43 @@ +package com.aizistral.nochatreports.common.gui; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +@Environment(EnvType.CLIENT) +public class EncryptionWarningScreen extends TriageWarningScreen { + private static final Component TITLE = Component.translatable("gui.nochatreports.encryption_warning.header").withStyle(ChatFormatting.BOLD); + private static final Component CONTENT = Component.translatable("gui.nochatreports.encryption_warning.contents"); + private static final Component CHECK = Component.translatable("gui.nochatreports.encryption_warning.check"); + private static final String WIKI_LINK = "https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/To-Encrypt-or-Not-to-Encrypt"; + private static boolean sessionSeen = false; + + public EncryptionWarningScreen(Screen previous) { + super(TITLE, CONTENT, CHECK, WIKI_LINK, previous); + } + + @Override + protected void onProceed(Button button) { + this.minecraft.setScreen(new EncryptionConfigScreen(this.previous)); + if (this.stopShowing.selected()) { + NCRConfig.getEncryption().disableWarning(); + } + + sessionSeen = true; + } + + @Override + protected void onBack(Button button) { + this.minecraft.setScreen(this.previous); + } + + public static boolean seenOnThisSession() { + return sessionSeen; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/FontHelper.java b/src/main/java/com/aizistral/nochatreports/common/gui/FontHelper.java new file mode 100644 index 0000000..044dcc8 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/FontHelper.java @@ -0,0 +1,152 @@ +package com.aizistral.nochatreports.common.gui; + +import java.util.Arrays; +import java.util.List; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.gui.Font; +import net.minecraft.util.FormattedCharSequence; + +/** + * I couldn't find a way to properly convert {@link FormattedCharSequence} back into + * normal string. Lol. + * + * @author Aizistral + */ + +@Environment(EnvType.CLIENT) +public final class FontHelper { + + private FontHelper() { + throw new IllegalStateException("Can't touch this"); + } + + /** + * Breaks a string into a list of pieces that will fit a specified width. + */ + + public static List wrap(Font font, String str, int wrapWidth) { + return Arrays.asList(wrapFormattedStringToWidth(font, str, wrapWidth).split("\n")); + } + + /** + * Inserts newline and formatting into a string to wrap it within the specified + * width. + */ + + private static String wrapFormattedStringToWidth(Font font, String str, int wrapWidth) { + int j = sizeStringToWidth(font, str, wrapWidth); + + if (str.length() <= j) + return str; + else { + String s1 = str.substring(0, j); + char c0 = str.charAt(j); + boolean flag = c0 == 32 || c0 == 10; + String s2 = getFormatFromString(s1) + str.substring(j + (flag ? 1 : 0)); + return s1 + "\n" + wrapFormattedStringToWidth(font, s2, wrapWidth); + } + } + + /** + * Determines how many characters from the string will fit into the specified + * width. + */ + + private static int sizeStringToWidth(Font font, String str, int wrapWidth) { + int j = str.length(); + int k = 0; + int l = 0; + int i1 = -1; + + for (boolean flag = false; l < j; ++l) { + char c0 = str.charAt(l); + + switch (c0) { + case 10: + --l; + break; + case 167: + if (l < j - 1) { + ++l; + char c1 = str.charAt(l); + + if (c1 != 108 && c1 != 76) { + if (c1 == 114 || c1 == 82 || isFormatColor(c1)) { + flag = false; + } + } else { + flag = true; + } + } + + break; + case 32: + i1 = l; + default: + k += font.width(String.valueOf(c0)); + + if (flag) { + ++k; + } + } + + if (c0 == 10) { + ++l; + i1 = l; + break; + } + + if (k > wrapWidth) { + break; + } + } + + return l != j && i1 != -1 && i1 < l ? i1 : l; + } + + /** + * Checks if the char code is a hexadecimal character, used to set colour. + */ + + private static boolean isFormatColor(char colorChar) { + return colorChar >= 48 && colorChar <= 57 || colorChar >= 97 && colorChar <= 102 + || colorChar >= 65 && colorChar <= 70; + } + + /** + * Checks if the char code is O-K...lLrRk-o... used to set special formatting. + */ + + private static boolean isFormatSpecial(char formatChar) { + return formatChar >= 107 && formatChar <= 111 || formatChar >= 75 && formatChar <= 79 || formatChar == 114 + || formatChar == 82; + } + + /** + * Digests a string for nonprinting formatting characters then returns a string + * containing only that formatting. + */ + + private static String getFormatFromString(String text) { + String s1 = ""; + int i = -1; + int j = text.length(); + + while ((i = text.indexOf(167, i + 1)) != -1) { + if (i < j - 1) { + char c0 = text.charAt(i + 1); + + if (isFormatColor(c0)) { + s1 = "\u00a7" + c0; + } else if (isFormatSpecial(c0)) { + s1 = s1 + "\u00a7" + c0; + } + } + } + + return s1; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/InvisibleButton.java b/src/main/java/com/aizistral/nochatreports/common/gui/InvisibleButton.java new file mode 100644 index 0000000..78cba5a --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/InvisibleButton.java @@ -0,0 +1,24 @@ +package com.aizistral.nochatreports.common.gui; + +import java.util.function.Supplier; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.gui.components.Button; +import net.minecraft.network.chat.Component; + +@Environment(EnvType.CLIENT) +public class InvisibleButton extends Button { + + public InvisibleButton() { + super(0, 0, 20, 20, Component.empty(), btn -> {}, Supplier::get); + } + + @Override + public void render(PoseStack poseStack, int i, int j, float f) { + // NO-OP + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/RealmsWarningScreen.java b/src/main/java/com/aizistral/nochatreports/common/gui/RealmsWarningScreen.java new file mode 100644 index 0000000..74dee15 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/RealmsWarningScreen.java @@ -0,0 +1,42 @@ +package com.aizistral.nochatreports.common.gui; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +public class RealmsWarningScreen extends TriageWarningScreen { + private static final Component TITLE = Component.translatable("gui.nochatreports.realms_warning.header").withStyle(ChatFormatting.BOLD); + private static final Component CONTENT = Component.translatable("gui.nochatreports.realms_warning.contents"); + private static final Component CHECK = Component.translatable("gui.nochatreports.realms_warning.check"); + private static final String WIKI_LINK = "https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/The-Realms-Question"; + private static boolean sessionSeen = false; + private final Screen realms; + + public RealmsWarningScreen(Screen previous, Screen realms) { + super(TITLE, CONTENT, CHECK, WIKI_LINK, previous); + this.realms = realms; + } + + @Override + protected void onProceed(Button button) { + this.minecraft.setScreen(this.realms); + if (this.stopShowing.selected()) { + NCRConfig.getClient().setSkipRealmsWarning(true); + } + + sessionSeen = true; + } + + @Override + protected void onBack(Button button) { + this.minecraft.setScreen(null); + } + + public static boolean shouldShow() { + return !sessionSeen && !NCRConfig.getClient().skipRealmsWarning(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/TriageWarningScreen.java b/src/main/java/com/aizistral/nochatreports/common/gui/TriageWarningScreen.java new file mode 100644 index 0000000..c47b14a --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/TriageWarningScreen.java @@ -0,0 +1,45 @@ +package com.aizistral.nochatreports.common.gui; + +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.ConfirmLinkScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; + +public abstract class TriageWarningScreen extends AdaptiveWarningScreen { + private final String wikiLink; + + public TriageWarningScreen(Component title, Component content, Component check, String wikiLink, Screen previous) { + super(title, content, check, previous); + this.wikiLink = wikiLink; + } + + @Override + protected void initButtons(int y) { + int offset = 28; + + this.addRenderableWidget(Button.builder(CommonComponents.GUI_PROCEED, this::onProceed) + .pos(this.width / 2 - 260 + offset, y).size(150, 20).build()); + + this.addRenderableWidget(Button.builder(Component.translatable("gui.nochatreports.encryption_warning.learn_more"), button -> { + Minecraft.getInstance().setScreen(new ConfirmLinkScreen(agree -> { + if (agree) { + Util.getPlatform().openUri(this.wikiLink); + } + + Minecraft.getInstance().setScreen(this); + }, this.wikiLink, true)); + }).pos(this.width / 2 - 100 + offset, y).size(150, 20).build()); + + + this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, this::onBack) + .pos(this.width / 2 + 60 + offset, y).size(150, 20).build()); + } + + protected abstract void onProceed(Button button); + + protected abstract void onBack(Button button); + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/gui/UnsafeServerScreen.java b/src/main/java/com/aizistral/nochatreports/common/gui/UnsafeServerScreen.java new file mode 100644 index 0000000..239b23b --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/gui/UnsafeServerScreen.java @@ -0,0 +1,58 @@ +package com.aizistral.nochatreports.common.gui; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyState; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +@Environment(EnvType.CLIENT) +public final class UnsafeServerScreen extends AdaptiveWarningScreen { + private static final Component TITLE = Component.translatable("gui.nochatreports.signing_required.header").withStyle(ChatFormatting.BOLD); + private static final Component CONTENT = Component.translatable("gui.nochatreports.signing_required.contents"); + private static final Component CHECK = Component.translatable("gui.nochatreports.signing_required.check"); + private static final Component NARRATION = TITLE.copy().append("\n").append(CONTENT); + private static boolean hideThisSession = false; + + public UnsafeServerScreen(Screen previous) { + super(TITLE, CONTENT, CHECK, previous); + } + + @Override + protected void initButtons(int i) { + this.addRenderableWidget(Button.builder(Component.translatable("gui.nochatreports.signing_required.allow_signing"), + button -> { + ServerSafetyState.setAllowChatSigning(true); + this.minecraft.setScreen(this.previous); + }).bounds(this.width / 2 - 155, i, 150, 20) + .build()); + + this.addRenderableWidget(Button.builder(Component.translatable("gui.nochatreports.signing_required.cancel"), + button -> { + if (this.stopShowing.selected()) { + hideThisSession = true; + } + this.minecraft.setScreen(this.previous); + }).bounds(this.width / 2 - 155 + 160, i, 150, 20).build()); + } + + private void resendLastMessage() { + if (this.previous instanceof ChatScreen chat) { + chat.handleChatInput(NCRConfig.getEncryption().getLastMessage(), false); + } + } + + public static void setHideThisSession(boolean hide) { + hideThisSession = hide; + } + + public static boolean hideThisSession() { + return hideThisSession; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatComponent.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatComponent.java new file mode 100644 index 0000000..273ea57 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatComponent.java @@ -0,0 +1,75 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.At.Shift; + +import com.aizistral.nochatreports.common.NCRCore; +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.EncryptionUtil; + +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +import net.minecraft.ChatFormatting; +import net.minecraft.client.GuiMessageTag; +import net.minecraft.client.gui.components.ChatComponent; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; + +@Mixin(ChatComponent.class) +public class MixinChatComponent { + private static final GuiMessageTag.Icon ENCRYPTED_ICON = GuiMessageTag.Icon.valueOf("CHAT_NCR_ENCRYPTED"); + private boolean lastMessageEncrypted; + private Component lastMessageOriginal; + + @ModifyVariable(method = "addRecentChat", at = @At("HEAD"), argsOnly = true) + private String onAddRecentChat(String message) { + if (NCRConfig.getEncryption().isEnabledAndValid()) + return NCRConfig.getEncryption().getLastMessage(); + else + return message; + } + + @ModifyVariable(method = "addMessage(Lnet/minecraft/network/chat/Component;" + + "Lnet/minecraft/network/chat/MessageSignature;ILnet/minecraft/client/GuiMessageTag;Z)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/components/ComponentRenderUtils;" + + "wrapComponents(Lnet/minecraft/network/chat/FormattedText;ILnet/minecraft/client/gui/Font;" + + ")Ljava/util/List;", ordinal = 0, shift = Shift.AFTER), argsOnly = true) + private synchronized GuiMessageTag modifyGUITag(GuiMessageTag tag) { + if (!NCRConfig.getEncryption().showEncryptionIndicators() || !this.lastMessageEncrypted) + return tag; + + this.lastMessageEncrypted = false; + Component tooltip = Component.empty().append(Component.translatable("tag.nochatreports.encrypted", + Component.literal(NCRConfig.getEncryption().getAlgorithm().getName()) + .withStyle(ChatFormatting.BOLD))).append(CommonComponents.NEW_LINE).append( + Component.translatable("tag.nochatreports.encrypted_original", + this.lastMessageOriginal)); + + return new GuiMessageTag(0x8B3EC7, ENCRYPTED_ICON, tooltip, "Encrypted"); + } + + @ModifyArg(index = 0, method = "addMessage(Lnet/minecraft/network/chat/Component;" + + "Lnet/minecraft/network/chat/MessageSignature;ILnet/minecraft/client/GuiMessageTag;Z)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/components/ComponentRenderUtils;" + + "wrapComponents(Lnet/minecraft/network/chat/FormattedText;I" + + "Lnet/minecraft/client/gui/Font;)Ljava/util/List;", ordinal = 0)) + private FormattedText modifyGUIMessage(FormattedText msg) { + if (NCRConfig.getCommon().enableDebugLog()) { + NCRCore.LOGGER.info("Adding chat message, structure: " + + Component.Serializer.toStableJson((Component) msg)); + } + + var decrypted = EncryptionUtil.tryDecrypt((Component) msg); + + decrypted.ifPresentOrElse(component -> { + this.lastMessageOriginal = EncryptionUtil.recreate((Component) msg); + this.lastMessageEncrypted = true; + }, () -> this.lastMessageEncrypted = false); + + return this.lastMessageEncrypted ? decrypted.get() : msg; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatListener.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatListener.java new file mode 100644 index 0000000..f0a6d8c --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatListener.java @@ -0,0 +1,117 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.NCRClient; +import com.aizistral.nochatreports.common.NCRCore; +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.EncryptionUtil; +import com.aizistral.nochatreports.common.core.ServerSafetyLevel; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.aizistral.nochatreports.common.core.SigningMode; +import com.aizistral.nochatreports.common.gui.UnsafeServerScreen; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.multiplayer.chat.ChatListener; +import net.minecraft.client.multiplayer.chat.ChatTrustLevel; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.PlayerChatMessage; +import net.minecraft.network.chat.contents.TranslatableContents; + +@Mixin(ChatListener.class) +public class MixinChatListener { + + @Shadow + private boolean isSenderLocalPlayer(UUID uuid) { + throw new IllegalStateException("@Shadow transformation failed. Should never happen."); + } + + @Inject(method = "handleSystemMessage", at = @At("HEAD"), cancellable = true) + private void onHandleSystemMessage(Component message, boolean overlay, CallbackInfo info) { + if (message instanceof MutableComponent mutable && message.getContents() instanceof TranslatableContents translatable) { + if (translatable.getKey().equals("chat.disabled.missingProfileKey")) { + mutable.contents = new TranslatableContents("chat.nochatreports.disabled.signing_requested"); + + if (!ServerSafetyState.isOnRealms()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); + } + + if (UnsafeServerScreen.hideThisSession() || ServerSafetyState.allowChatSigning()) + return; + + if (NCRConfig.getServerPreferences().hasModeCurrent(SigningMode.ON_DEMAND)) { + ServerSafetyState.scheduleSigningAction(NCRClient::resendLastChatMessage); + ServerSafetyState.setAllowChatSigning(true); + + if (NCRConfig.getClient().hideSigningRequestMessage()) { + info.cancel(); + } + + return; + } + + if (NCRConfig.getServerPreferences().hasModeCurrent(SigningMode.PROMPT)) { + Minecraft.getInstance().setScreen(new UnsafeServerScreen(Minecraft.getInstance().screen + instanceof ChatScreen chat ? chat : new ChatScreen(""))); + + if (NCRConfig.getClient().hideSigningRequestMessage()) { + info.cancel(); + } + } + } + } + } + + /** + * @reason Removes "Not Secure" and "Modified" statuses of chat messages. They ultimately + * serve no purpose but to annoy the user and scare them away from servers that actually + * try to protect them by stripping message signatures. + * @author Aizistral + */ + + @Inject(method = "evaluateTrustLevel", at = @At("HEAD"), cancellable = true) + private void onEvaluateTrustLevel(PlayerChatMessage playerChatMessage, Component component, Instant instant, CallbackInfoReturnable info) { + if (this.isSenderLocalPlayer(playerChatMessage.sender())) { + info.setReturnValue(ChatTrustLevel.SECURE); + } else { + if (playerChatMessage.hasSignature() && ServerSafetyState.getCurrent() == ServerSafetyLevel.SECURE) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); + } + + var evaluate = ChatTrustLevel.evaluate(playerChatMessage, component, instant); + + if (evaluate == ChatTrustLevel.NOT_SECURE && NCRConfig.getClient().hideInsecureMessageIndicators()) { + info.setReturnValue(ChatTrustLevel.SECURE); + } else if (evaluate == ChatTrustLevel.MODIFIED && NCRConfig.getClient().hideModifiedMessageIndicators()) { + info.setReturnValue(ChatTrustLevel.SECURE); + } + } + + // Debug never dies + if (NCRConfig.getCommon().enableDebugLog()) { + NCRCore.LOGGER.info("Received message: {}, from: {}, signature: {}", + Component.Serializer.toStableJson(playerChatMessage.unsignedContent()), + playerChatMessage.link().sender(), + Base64.getEncoder().encodeToString(playerChatMessage.signature() != null ? playerChatMessage.signature().bytes() : new byte[0])); + } + } + + @ModifyVariable(method = "narrateChatMessage(Lnet/minecraft/network/chat/ChatType$Bound;" + + "Lnet/minecraft/network/chat/Component;)V", at = @At("HEAD"), argsOnly = true) + private Component decryptNarratedMessage(Component msg) { + return EncryptionUtil.tryDecrypt(msg).orElse(msg); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatOptionsScreen.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatOptionsScreen.java new file mode 100644 index 0000000..24e5fad --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatOptionsScreen.java @@ -0,0 +1,42 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.util.Optional; + +import org.spongepowered.asm.mixin.Mixin; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +import net.minecraft.client.gui.screens.ChatOptionsScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.SimpleOptionsSubScreen; +import net.minecraft.network.chat.Component; + +/** + * Mixin responsible for graying out "Only Show Secure Chat" option. + * + * @author Kevinthegreat (original implementation) + * @author Aizistral (current version) + */ + +@Mixin(ChatOptionsScreen.class) +public class MixinChatOptionsScreen extends SimpleOptionsSubScreen { + + public MixinChatOptionsScreen(Screen screen, Options options, Component component, OptionInstance... optionInstances) { + super(screen, options, component, optionInstances); + throw new IllegalStateException("Can't touch this"); + } + + @Override + protected void init() { + super.init(); + + if (NCRConfig.getClient().enableMod()) { + Optional.ofNullable(this.list.findOption(Minecraft.getInstance().options.onlyShowSecureChat())) + .ifPresent(option -> option.active = false); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatScreen.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatScreen.java new file mode 100644 index 0000000..46e9ebd --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinChatScreen.java @@ -0,0 +1,208 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.NCRClient; +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyLevel; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.aizistral.nochatreports.common.core.SigningMode; +import com.aizistral.nochatreports.common.gui.AdvancedImageButton; +import com.aizistral.nochatreports.common.gui.AdvancedTooltip; +import com.aizistral.nochatreports.common.gui.EncryptionButton; +import com.aizistral.nochatreports.common.gui.EncryptionWarningScreen; + +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.ImageButton; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; + +/** + * This is responsible for adding safety status indicator to the bottom-right corner of chat screen. + * @author Aizistral + */ + +@Mixin(ChatScreen.class) +public abstract class MixinChatScreen extends Screen { + private static final ResourceLocation CHAT_STATUS_ICONS = new ResourceLocation("nochatreports", "textures/gui/chat_status_icons_extended.png"); + private static final ResourceLocation ENCRYPTION_BUTTON = new ResourceLocation("nochatreports", "textures/gui/encryption_toggle_button.png"); + private ImageButton safetyStatusButton; + + protected MixinChatScreen() { + super(null); + throw new IllegalStateException("Can't touch this"); + } + + @Inject(method = "handleChatInput", at = @At("HEAD"), cancellable = true) + public void handleChatInput(String string, boolean bl, CallbackInfoReturnable info) { + if (NCRConfig.getServerPreferences().hasModeCurrent(SigningMode.ALWAYS) && !ServerSafetyState.allowChatSigning()) { + if (this.minecraft.getConnection().getConnection().isEncrypted()) { + if (!this.normalizeChatMessage(string).isEmpty()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); + ServerSafetyState.scheduleSigningAction(NCRClient::resendLastChatMessage); + ServerSafetyState.setAllowChatSigning(true); + info.setReturnValue(true); + } + } + } + } + + @Inject(method = "normalizeChatMessage", at = @At("RETURN"), cancellable = true) + public void onBeforeMessage(String original, CallbackInfoReturnable info) { + String message = info.getReturnValue(); + NCRConfig.getEncryption().setLastMessage(message); + + if (!message.isEmpty() && !Screen.hasControlDown() && NCRConfig.getEncryption().shouldEncrypt(message)) { + NCRConfig.getEncryption().getEncryptor().ifPresent(e -> { + int index = NCRConfig.getEncryption().getEncryptionStartIndex(message); + String noencrypt = message.substring(0, index); + String encrypt = message.substring(index, message.length()); + + if (encrypt.length() > 0) { + info.setReturnValue(noencrypt + e.encrypt("#%" + encrypt)); + } + }); + } + } + + @Inject(method = "init", at = @At("HEAD")) + private void onInit(CallbackInfo info) { + int buttonX = this.width - 23; + + if (NCRConfig.getClient().showServerSafety() && NCRConfig.getClient().enableMod()) { + this.safetyStatusButton = new AdvancedImageButton(buttonX, this.height - 37, 20, 20, this.getXOffset(), + 0, 20, CHAT_STATUS_ICONS, 128, 128, btn -> { + if (!NCRClient.areSigningKeysPresent()) + return; + + var address = ServerSafetyState.getLastServer(); + + if (address != null) { + var preferences = NCRConfig.getServerPreferences(); + preferences.setMode(address, preferences.getModeUnresolved(address).next()); + preferences.saveFile(); + } + }, Component.empty(), this); + this.safetyStatusButton.setTooltip(new AdvancedTooltip(() -> { + MutableComponent tooltip = this.getSafetyLevel().getTooltip(); + + if (ServerSafetyState.allowChatSigning()) { + tooltip = Component.translatable("gui.nochatreports.safety_status.insecure_signing"); + } else if (ServerSafetyState.isInSingleplayer()) + return tooltip; + + ServerAddress address = ServerSafetyState.getLastServer(); + SigningMode mode = NCRConfig.getServerPreferences().getModeUnresolved(address); + String signing = "gui.nochatreports.signing_status."; + + if (!this.minecraft.getConnection().getConnection().isEncrypted()) { + signing += "disabled_offline"; + } else if (ServerSafetyState.getCurrent() == ServerSafetyLevel.REALMS) { + signing += "allowed_realms"; + } else if (mode.resolve() == SigningMode.ALWAYS) { + if (ServerSafetyState.allowChatSigning()) { + signing += "allowed"; + } else { + signing += "disabled_allowance_pending"; + } + } else if (ServerSafetyState.allowChatSigning()) { + signing += "allowed_session"; + } else { + signing += "disabled"; + } + + tooltip.append("\n\n"); + tooltip.append(Component.translatable(signing)); + + if (ServerSafetyState.isOnRealms()) + return tooltip; + + tooltip.append("\n\n"); + tooltip.append(Component.translatable("gui.nochatreports.safety_status_button.controls")); + tooltip.append("\n\n"); + tooltip.append(Component.translatable("gui.nochatreports.signing_mode", + mode.getName().withStyle(ChatFormatting.BOLD, ChatFormatting.AQUA))); + tooltip.append("\n"); + tooltip.append((mode == SigningMode.DEFAULT ? mode.resolve() : mode).getTooltip()); + + return tooltip; + }).setMaxWidth(250).setRenderWithoutGap(true)); + + this.addRenderableWidget(this.safetyStatusButton); + buttonX -= 25; + } + + if (!NCRConfig.getEncryption().showEncryptionButton()) + return; + + int xStart = !NCRConfig.getEncryption().isValid() ? 40 : (NCRConfig.getEncryption().isEnabled() ? 0 : 20); + + var button = new EncryptionButton(buttonX, this.height - 37, 20, 20, xStart, + 0, 20, ENCRYPTION_BUTTON, 64, 64, btn -> { + if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled() + && !NCRConfig.getEncryption().isEnabled()) { + Minecraft.getInstance().setScreen(new EncryptionWarningScreen(this)); + } else if (NCRConfig.getEncryption().isValid()) { + NCRConfig.getEncryption().toggleEncryption(); + ((EncryptionButton)btn).xTexStart = NCRConfig.getEncryption().isEnabledAndValid() ? 0 : 20; + } else { + ((EncryptionButton)btn).openEncryptionConfig(); + } + }, Component.empty(), this); + button.setTooltip(new AdvancedTooltip(() -> { + if (NCRConfig.getEncryption().isValid()) + return Component.translatable("gui.nochatreports.encryption_tooltip", Language.getInstance() + .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getEncryption() + .isEnabledAndValid() ? "on" : "off"))); + else + return Component.translatable("gui.nochatreports.encryption_tooltip_invalid", Language.getInstance() + .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getEncryption() + .isEnabledAndValid() ? "on" : "off"))); + }).setMaxWidth(250)); + button.active = true; + button.visible = true; + + this.addRenderableWidget(button); + } + + @Inject(method = "tick", at = @At("RETURN")) + private void onTick(CallbackInfo info) { + if (this.safetyStatusButton != null) { + this.safetyStatusButton.xTexStart = this.getXOffset(); + } + } + + private ServerSafetyLevel getSafetyLevel() { + return ServerSafetyState.getCurrent(); + } + + private int getXOffset() { + return this.getXOffset(this.getSafetyLevel()); + } + + private int getXOffset(ServerSafetyLevel level) { + return switch (level) { + case SECURE, SINGLEPLAYER -> 21; + case UNINTRUSIVE -> 42; + case INSECURE -> 0; + case REALMS -> 63; + case UNKNOWN -> 84; + case UNDEFINED -> 105; + }; + } + + @Shadow + public abstract String normalizeChatMessage(String string); + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinClientPacketListener.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinClientPacketListener.java new file mode 100644 index 0000000..1074931 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinClientPacketListener.java @@ -0,0 +1,41 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.core.ServerSafetyLevel; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.mojang.brigadier.ParseResults; + +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.network.chat.SignableCommand; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; +import net.minecraft.network.protocol.game.ServerboundChatPacket; + +@Mixin(ClientPacketListener.class) +public abstract class MixinClientPacketListener { + + @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;)V", at = @At("HEAD")) + private void onSend(Packet packet, CallbackInfo info) { + if (!ServerSafetyState.allowChatSigning() && !ServerSafetyState.isDetermined()) { + if (packet instanceof ServerboundChatPacket chat) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); // asume unintrusive until further notice + } else if (packet instanceof ServerboundChatCommandPacket command) { + if (!SignableCommand.of(this.parseCommand(command.command())).arguments().isEmpty()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); + } + } + } + } + + @Shadow + private ParseResults parseCommand(String command) { + throw new IllegalStateException("@Shadow transformation failed"); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinConnectScreen.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinConnectScreen.java new file mode 100644 index 0000000..8f94138 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinConnectScreen.java @@ -0,0 +1,44 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.NCRCore; +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyState; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.ConnectScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +@Mixin(ConnectScreen.class) +public class MixinConnectScreen { + + /** + * @reason Intercept initiation of any new server connection. This way we can keep track of which + * server client currently tries to connect to. + * @author Aizistral + */ + + @Inject(method = "startConnecting", at = @At("HEAD")) + private static void onStartConnecting(Screen screen, Minecraft minecraft, ServerAddress serverAddress, + @Nullable ServerData serverData, CallbackInfo info) { + if (!NCRConfig.getClient().enableMod()) + return; + + ServerSafetyState.reset(); + ServerSafetyState.setLastServer(serverAddress); + + if (NCRConfig.getCommon().enableDebugLog()) { + NCRCore.LOGGER.info("Connecting to: {}", + serverAddress.getHost() + ":" + serverAddress.getPort()); + NCRCore.LOGGER.info("Server Data IP: {}", serverData != null ? serverData.ip : "null"); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTag.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTag.java new file mode 100644 index 0000000..9b7fac5 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTag.java @@ -0,0 +1,29 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.client.GuiMessageTag; + +@Mixin(GuiMessageTag.class) +public class MixinGuiMessageTag { + + /** + * @reason Remove gray bar as indication besides system messages, if mod is configured + * respectively. The mod can convert all player messages to system messages when + * installed on server, so we don't need that most of the time. + * @author Aizistral + */ + + @Inject(method = { "system", "systemSinglePlayer" }, at = @At("HEAD"), cancellable = true) + private static void onSystem(CallbackInfoReturnable info) { + if (NCRConfig.getClient().hideSystemMessageIndicators()) { + info.setReturnValue(null); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTagIcon.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTagIcon.java new file mode 100644 index 0000000..2f6e656 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinGuiMessageTagIcon.java @@ -0,0 +1,47 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.util.Arrays; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Invoker; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.GuiMessageTag; +import net.minecraft.client.GuiMessageTag.Icon; +import net.minecraft.client.gui.GuiComponent; +import net.minecraft.resources.ResourceLocation; + +@Mixin(GuiMessageTag.Icon.class) +public abstract class MixinGuiMessageTagIcon { + private static final ResourceLocation TEXTURE_NCR = new ResourceLocation("nochatreports", "textures/gui/encrypted_tag.png"); + @Shadow(aliases = "field_39768") @Mutable static Icon[] $VALUES; + + @Invoker("") + static Icon create(String name, int ordinal, int u, int v, int width, int height) { + throw new IllegalStateException("Invoker transformation failed"); + } + + @Inject(method = "draw", at = @At("HEAD"), cancellable = true) + public void onDraw(PoseStack stack, int x, int y, CallbackInfo info) { + if (((Icon)(Object)this).name().equals("CHAT_NCR_ENCRYPTED")) { + RenderSystem.setShaderTexture(0, TEXTURE_NCR); + GuiComponent.blit(stack, x, y, 0, 0, 9, 9, 9, 9); + info.cancel(); + } + } + + static { + var ordinal = $VALUES.length; + var values = Arrays.copyOf($VALUES, ordinal + 1); + values[ordinal] = create("CHAT_NCR_ENCRYPTED", ordinal, 9, 0, 9, 9); + $VALUES = values; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinJoinMultiplayerScreen.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinJoinMultiplayerScreen.java new file mode 100644 index 0000000..4f99934 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinJoinMultiplayerScreen.java @@ -0,0 +1,72 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.aizistral.nochatreports.common.gui.AdvancedImageButton; +import com.aizistral.nochatreports.common.gui.AdvancedTooltip; + +import net.minecraft.client.gui.components.ImageButton; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +/** + * This is responsible for adding config reload button to server selection menu. + * @author Aizistral + */ + +@Mixin(JoinMultiplayerScreen.class) +public abstract class MixinJoinMultiplayerScreen extends Screen { + private static final ResourceLocation RELOAD_TEXTURE = new ResourceLocation("nochatreports", "textures/gui/config_reload_button.png"), + TOGGLE_TEXTURE = new ResourceLocation("nochatreports", "textures/gui/ncr_toggle_button.png"); + private static final Component RELOAD_TOOLTIP = Component.translatable("gui.nochatreports.reload_config_tooltip"); + + protected MixinJoinMultiplayerScreen() { + super(null); + throw new IllegalStateException("Can't touch this"); + } + + @Inject(method = "init", at = @At("HEAD")) + private void onInit(CallbackInfo info) { + if (NCRConfig.getClient().showReloadButton()) { + var button = new AdvancedImageButton(this.width/2 + 158, this.height - 52, 20, 20, 0, 0, 20, + RELOAD_TEXTURE, 64, 64, btn -> NCRConfig.load(), CommonComponents.EMPTY, this); + button.setTooltip(new AdvancedTooltip(RELOAD_TOOLTIP).setMaxWidth(250).setRenderWithoutGap(true)); + button.active = true; + button.visible = true; + this.addRenderableWidget(button); + } + + if (NCRConfig.getClient().showNCRButton()) { + var button = new AdvancedImageButton(this.width/2 + 158, this.height - 28, 20, 20, + NCRConfig.getClient().enableMod() ? 0 : 20, 0, 20, TOGGLE_TEXTURE, 64, 64, + btn -> { + NCRConfig.getClient().toggleMod(); + boolean enabled = NCRConfig.getClient().enableMod(); + + if (enabled) { + ((ImageButton)btn).xTexStart = 0; + } else { + ((ImageButton)btn).xTexStart = 20; + } + + ServerSafetyState.reset(); + }, Component.translatable("gui.nochatreports.ncr_toggle"), this); + button.setTooltip(new AdvancedTooltip(() -> Component.translatable("gui.nochatreports.ncr_toggle_tooltip", + Language.getInstance().getOrDefault("gui.nochatreports.ncr_state_" + (NCRConfig.getClient() + .enableMod() ? "on" : "off")))).setMaxWidth(250)); + button.active = true; + button.visible = true; + this.addRenderableWidget(button); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinMinecraft.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinMinecraft.java new file mode 100644 index 0000000..ca36de9 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinMinecraft.java @@ -0,0 +1,47 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.NCRClient; +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyState; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.main.GameConfig; +import net.minecraft.client.multiplayer.ProfileKeyPairManager; + +@Mixin(Minecraft.class) +public class MixinMinecraft { + @Shadow @Final + private ProfileKeyPairManager profileKeyPairManager; + + @Inject(method = "(Lnet/minecraft/client/main/GameConfig;)V", at = @At("RETURN")) + private void onConstructed(GameConfig config, CallbackInfo info) { + NCRClient.setSigningKeysPresent(this.profileKeyPairManager.prepareKeyPair() + .join().isPresent()); + } + + @Inject(method = "getProfileKeyPairManager", at = @At("HEAD"), cancellable = true) + private void onGetProfileKeyPairManager(CallbackInfoReturnable info) { + if (!NCRConfig.getClient().enableMod()) + return; + + if (!ServerSafetyState.allowChatSigning()) { + info.setReturnValue(ProfileKeyPairManager.EMPTY_KEY_MANAGER); + } + } + + @Inject(method = "allowsTelemetry", at = @At("HEAD"), cancellable = true) + private void onAllowsTelemetry(CallbackInfoReturnable info) { + if (NCRConfig.getClient().disableTelemetry()) { + info.setReturnValue(false); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOnlineServerEntry.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOnlineServerEntry.java new file mode 100644 index 0000000..b90e9b1 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOnlineServerEntry.java @@ -0,0 +1,64 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.util.ArrayList; +import java.util.stream.Collectors; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerDataExtension; +import com.aizistral.nochatreports.common.gui.FontHelper; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiComponent; +import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; +import net.minecraft.client.gui.screens.multiplayer.ServerSelectionList; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +@Mixin(ServerSelectionList.OnlineServerEntry.class) +public abstract class MixinOnlineServerEntry extends ServerSelectionList.Entry { + private static final ResourceLocation VERIFIED_ICON = new ResourceLocation("nochatreports", "textures/gui/verified_server.png"); + + @Shadow @Final + private JoinMultiplayerScreen screen; + @Shadow @Final + private Minecraft minecraft; + @Shadow @Final + private ServerData serverData; + + @Inject(method = "render", at = @At("RETURN")) + private void onRender(PoseStack poseStack, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f, CallbackInfo info) { + if (!NCRConfig.getClient().verifiedIconEnabled()) + return; + + if (this.serverData.ping >= 0 && ((ServerDataExtension) this.serverData).preventsChatReports()) { + int xOffset = NCRConfig.getClient().getVerifiedIconOffsetX(), + yOffset = NCRConfig.getClient().getVerifiedIconOffsetY(); + + RenderSystem.setShaderTexture(0, VERIFIED_ICON); + RenderSystem.enableBlend(); + GuiComponent.blit(poseStack, k + l - 35 + xOffset, j - 1 + yOffset, 0.0f, 0.0f, 14, 14, 14, 14); + RenderSystem.disableBlend(); + + int t = n - k; + int u = o - j; + if (t >= l - 35 + xOffset && t <= l - 22 + xOffset && u >= 0 + yOffset && u <= 11 + yOffset) { + this.screen.setToolTip(FontHelper.wrap(this.minecraft.font, Language.getInstance() + .getOrDefault("gui.nochatreports.verified_server"), 250).stream() + .map(Component::literal).collect(Collectors.toCollection(() -> + new ArrayList()))); + } + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOptions.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOptions.java new file mode 100644 index 0000000..e2ffe8c --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinOptions.java @@ -0,0 +1,43 @@ + +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.google.common.collect.ImmutableList; +import com.mojang.serialization.Codec; + +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +import net.minecraft.network.chat.Component; + +@Mixin(Options.class) +public class MixinOptions { + private static final Component SECURE_CHAT_TOOLTIP = Component.translatable("gui.nochatreports.secure_chat"); + private OptionInstance alternativeOption; + + /** + * @reason Disable secure chat option, since it will not work anyways. + * @author Aizistral + */ + + @Inject(method = "onlyShowSecureChat", at = @At("RETURN"), cancellable = true) + private void onlyShowSecureChat(CallbackInfoReturnable> cir) { + if (!NCRConfig.getClient().enableMod()) + return; + + if (this.alternativeOption == null) { + this.alternativeOption = new OptionInstance<>("options.onlyShowSecureChat", + OptionInstance.cachedConstantTooltip(SECURE_CHAT_TOOLTIP), + OptionInstance.BOOLEAN_TO_STRING, + new OptionInstance.Enum<>(ImmutableList.of(Boolean.FALSE), Codec.BOOL), + false, value -> {}); + } + + cir.setReturnValue(this.alternativeOption); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinPlayerEntry.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinPlayerEntry.java new file mode 100644 index 0000000..6f4b091 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinPlayerEntry.java @@ -0,0 +1,51 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.util.UUID; +import java.util.function.Supplier; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.aizistral.nochatreports.common.gui.AdvancedImageButton; +import com.aizistral.nochatreports.common.gui.InvisibleButton; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.client.gui.screens.social.PlayerEntry; +import net.minecraft.client.gui.screens.social.SocialInteractionsScreen; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +@Mixin(PlayerEntry.class) +public class MixinPlayerEntry { + private static final Component NCR_BUTTON_TOOLTIP = Component.translatable("gui.nochatreports.no_reporting"); + @Shadow @Final private static ResourceLocation REPORT_BUTTON_LOCATION; + @Shadow private Button reportButton; + + /** + * @reason Disable (or hide if configured respectively) chat report button on client. + * @author Aizistral + */ + + @Inject(method = "", at = @At("RETURN")) + private void onConstructed(Minecraft minecraft, SocialInteractionsScreen screen, UUID uuid, String name, Supplier skinGetter, boolean reportable, CallbackInfo info) { + if (NCRConfig.getClient().alwaysHideReportButton()) { + this.reportButton = new InvisibleButton(); + this.reportButton.active = this.reportButton.visible = false; + } else if (ServerSafetyState.getCurrent().isSecure() && this.reportButton != null) { + this.reportButton = new AdvancedImageButton(0, 0, 20, 20, 0, 0, 20, REPORT_BUTTON_LOCATION, 64, 64, + button -> {}, Component.translatable("gui.socialInteractions.report"), screen); + this.reportButton.setTooltip(Tooltip.create(NCR_BUTTON_TOOLTIP)); + this.reportButton.setTooltipDelay(10); + this.reportButton.active = false; + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRealmsConnect.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRealmsConnect.java new file mode 100644 index 0000000..a6f16ef --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRealmsConnect.java @@ -0,0 +1,34 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerSafetyLevel; +import com.aizistral.nochatreports.common.core.ServerSafetyState; +import com.mojang.realmsclient.dto.RealmsServer; + +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.realms.RealmsConnect; + +@Mixin(RealmsConnect.class) +public class MixinRealmsConnect { + + /** + * @reason Always treat Realms servers as insecure, there is nothing we can do about them. + * @author Aizistral + */ + + @Inject(method = "connect", at = @At("HEAD")) + private void onConnect(RealmsServer realmsServer, ServerAddress serverAddress, CallbackInfo info) { + if (!NCRConfig.getClient().enableMod()) + return; + + ServerSafetyState.reset(); + ServerSafetyState.updateCurrent(ServerSafetyLevel.REALMS); + ServerSafetyState.setAllowChatSigning(true); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRowHelper.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRowHelper.java new file mode 100644 index 0000000..2efd6c2 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinRowHelper.java @@ -0,0 +1,26 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.GridWidget; +import net.minecraft.client.gui.screens.OptionsScreen; + +@Mixin(GridWidget.RowHelper.class) +public abstract class MixinRowHelper { + + @Inject(method = "addChild(Lnet/minecraft/client/gui/components/AbstractWidget;)" + + "Lnet/minecraft/client/gui/components/AbstractWidget;", at = @At("HEAD"), cancellable = true) + private void onAddChild(AbstractWidget widget, CallbackInfoReturnable info) { + if (NCRConfig.getClient().disableTelemetry() && NCRConfig.getClient().removeTelemetryButton()) + if (OptionsScreen.TELEMETRY.equals(widget.getMessage())) { + info.setReturnValue(widget); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerData.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerData.java new file mode 100644 index 0000000..095cf7f --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerData.java @@ -0,0 +1,46 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; + +import com.aizistral.nochatreports.common.core.ServerDataExtension; + +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.nbt.CompoundTag; + +/** + * Adds "preventsChatReports" property to {@link ServerData} and handles it during serialization to + * and deserialization from NBT-tag. + * + * @author fxmorin (original implementation) + * @author Aizistral (current version) + */ + +@Mixin(ServerData.class) +public class MixinServerData implements ServerDataExtension { + private boolean preventsChatReports; + + @Override + public boolean preventsChatReports() { + return this.preventsChatReports; + } + + @Override + public void setPreventsChatReports(boolean prevents) { + this.preventsChatReports = prevents; + } + + @Inject(method = "write", at = @At("RETURN")) + private void onWrite(CallbackInfoReturnable info) { + info.getReturnValue().putBoolean("preventsChatReports", this.preventsChatReports); + } + + @Inject(method = "read", locals = LocalCapture.CAPTURE_FAILSOFT, at = @At("RETURN")) + private static void onRead(CompoundTag tag, CallbackInfoReturnable info, ServerData data) { + ((ServerDataExtension)data).setPreventsChatReports(tag.getBoolean("preventsChatReports")); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerStatusPinger$1.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerStatusPinger$1.java new file mode 100644 index 0000000..a6cfaa2 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinServerStatusPinger$1.java @@ -0,0 +1,55 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.lang.reflect.Field; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.NCRCore; +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerDataExtension; + +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.network.protocol.status.ClientboundStatusResponsePacket; +import net.minecraft.network.protocol.status.ServerStatus; + +@Mixin(targets = "net/minecraft/client/multiplayer/ServerStatusPinger$1") +public class MixinServerStatusPinger$1 { + private static final Field SERVER_DATA_FIELD; + + static { + // We use reflection here because Mixin's AP dies when trying to process @Shadow of this lol + try { + Class pinger = Class.forName("net.minecraft.client.multiplayer.ServerStatusPinger$1"); + SERVER_DATA_FIELD = pinger.getDeclaredField("val$p_105460_"); + SERVER_DATA_FIELD.setAccessible(true); + } catch (Exception ex) { + throw new RuntimeException("Reflection failed in MixinServerStatusPinger$1", ex); + } + } + + /** + * @reason Ensure "preventsChatReports" property is transferred from {@link ServerStatus} to + * {@link ServerData} when handling status response. + * @author fxmorin (original implementation) + * @author Aizistral (current version) + */ + + @Inject(method = "handleStatusResponse(Lnet/minecraft/network/protocol/status/ClientboundStatusResponsePacket;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/status/ServerStatus;getPlayers()Lnet/minecraft/network/protocol/status/ServerStatus$Players;", ordinal = 0, shift = At.Shift.BEFORE)) + private void getNoChatReports(ClientboundStatusResponsePacket packet, CallbackInfo info) { + try { + boolean preventsReports = ((ServerDataExtension) packet.getStatus()).preventsChatReports(); + ((ServerDataExtension) SERVER_DATA_FIELD.get(this)).setPreventsChatReports(preventsReports); + + if (NCRConfig.getCommon().enableDebugLog()) { + NCRCore.LOGGER.info("Received status response packet from server, preventsChatReports: {}", + preventsReports); + } + } catch (IllegalArgumentException | IllegalAccessException ex) { + throw new RuntimeException("Failed to get ServerData field via reflection", ex); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinTitleScreen.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinTitleScreen.java new file mode 100644 index 0000000..240620d --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinTitleScreen.java @@ -0,0 +1,31 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.gui.RealmsWarningScreen; +import com.mojang.realmsclient.RealmsMainScreen; + +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.network.chat.CommonComponents; + +@Mixin(TitleScreen.class) +public class MixinTitleScreen extends Screen { + + protected MixinTitleScreen() { + super(CommonComponents.EMPTY); + throw new IllegalStateException("Can't touch this"); + } + + @Inject(method = "realmsButtonClicked", at = @At("HEAD"), cancellable = true) + private void onRealmsButtonClicked(CallbackInfo info) { + if (RealmsWarningScreen.shouldShow()) { + this.minecraft.setScreen(new RealmsWarningScreen(new TitleScreen(), new RealmsMainScreen(this))); + info.cancel(); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinToastComponent.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinToastComponent.java new file mode 100644 index 0000000..1d098e0 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinToastComponent.java @@ -0,0 +1,26 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.client.gui.components.toasts.SystemToast; +import net.minecraft.client.gui.components.toasts.SystemToast.SystemToastIds; +import net.minecraft.client.gui.components.toasts.Toast; +import net.minecraft.client.gui.components.toasts.ToastComponent; + +@Mixin(ToastComponent.class) +public class MixinToastComponent { + + @Inject(method = "addToast", at = @At("HEAD"), cancellable = true) + private void onAddToast(Toast toast, CallbackInfo info) { + if (NCRConfig.getClient().hideWarningToast()) + if (toast instanceof SystemToast sys && sys.getToken() == SystemToastIds.UNSECURE_SERVER_WARNING) { + info.cancel(); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinYggdrasilUserApiService.java b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinYggdrasilUserApiService.java new file mode 100644 index 0000000..1c9ffd8 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/client/MixinYggdrasilUserApiService.java @@ -0,0 +1,29 @@ +package com.aizistral.nochatreports.common.mixins.client; + +import java.util.concurrent.Executor; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.mojang.authlib.minecraft.TelemetrySession; +import com.mojang.authlib.yggdrasil.YggdrasilUserApiService; + +@Mixin(value = YggdrasilUserApiService.class, remap = false) +public class MixinYggdrasilUserApiService { + + /** + * @reason Privacy. + * @author Aizistral + */ + + @Inject(method = "newTelemetrySession", at = @At("HEAD"), cancellable = true) + private void onCreateTelemetrySession(Executor executor, CallbackInfoReturnable info) { + if (NCRConfig.getClient().disableTelemetry()) { + info.setReturnValue(TelemetrySession.DISABLED); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatus.java b/src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatus.java new file mode 100644 index 0000000..41563a5 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatus.java @@ -0,0 +1,53 @@ +package com.aizistral.nochatreports.common.mixins.common; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerDataExtension; + +import net.minecraft.network.protocol.status.ServerStatus; + +@Mixin(ServerStatus.class) +public class MixinServerStatus implements ServerDataExtension { + + /** + * Special additional variable that allows the client to know whether server prevents chat reports + * upon pinging it. + */ + + private boolean preventsChatReports; + + /** + * @reason Spoof the value of "enforcesSecureChat" in case conversion to system messages is enabled. + * There is no way for client to verify the value of the option in such case, so that's one less + * annoying warning. + * @author Aizistral + */ + + @Inject(method = "enforcesSecureChat", at = @At("HEAD"), cancellable = true) + public void onSecureChatCheck(CallbackInfoReturnable info) { + if (NCRConfig.getCommon().convertToGameMessage()) { + info.setReturnValue(true); + } + } + + @Override + public boolean preventsChatReports() { + var self = (ServerStatus) (Object) this; + + if (self.getVersion() != null && self.getVersion().getProtocol() < 759 + && self.getVersion().getProtocol() > 0) + return true; + + return this.preventsChatReports; + } + + @Override + public void setPreventsChatReports(boolean prevents) { + this.preventsChatReports = prevents; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatusSerializer.java b/src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatusSerializer.java new file mode 100644 index 0000000..300c047 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/common/MixinServerStatusSerializer.java @@ -0,0 +1,54 @@ +package com.aizistral.nochatreports.common.mixins.common; + +import java.lang.reflect.Type; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; + +import com.aizistral.nochatreports.common.config.NCRConfig; +import com.aizistral.nochatreports.common.core.ServerDataExtension; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; + +import net.minecraft.network.protocol.status.ServerStatus; +import net.minecraft.util.GsonHelper; + +/** + * Handles "preventsChatReports" property during serialization and deserialization of {@link ServerStatus}. + * + * @author fxmorin (original implementation) + * @author Aizistral (current version) + */ + +@Mixin(ServerStatus.Serializer.class) +public class MixinServerStatusSerializer { + + @Inject(method = "serialize(Lnet/minecraft/network/protocol/status/ServerStatus;" + + "Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;", + at = @At("RETURN")) + private void onSerialize(ServerStatus serverStatus, Type type, JsonSerializationContext context, + CallbackInfoReturnable info) { + if (!NCRConfig.getCommon().addQueryData()) + return; + + ((JsonObject) info.getReturnValue()).addProperty("preventsChatReports", true); + } + + @Inject(method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;" + + "Lcom/google/gson/JsonDeserializationContext;)" + + "Lnet/minecraft/network/protocol/status/ServerStatus;", + locals = LocalCapture.CAPTURE_FAILSOFT, at = @At("RETURN")) + private void onDeserialize(JsonElement element, Type type, JsonDeserializationContext context, + CallbackInfoReturnable info, JsonObject json, ServerStatus status) { + if (!json.has("preventsChatReports")) + return; + + ((ServerDataExtension) status).setPreventsChatReports(GsonHelper.getAsBoolean(json, "preventsChatReports")); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinDedicatedServer.java b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinDedicatedServer.java new file mode 100644 index 0000000..7ece057 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinDedicatedServer.java @@ -0,0 +1,24 @@ +package com.aizistral.nochatreports.common.mixins.server; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import net.minecraft.server.dedicated.DedicatedServer; + +@Mixin(DedicatedServer.class) +public class MixinDedicatedServer { + + /** + * @reason If mod is installed on server - it does the exact opposite of what this option is + * designed to enforce, so there's no reason to have it enabled. + * @author Aizistral + */ + + @Inject(method = "enforceSecureProfile", at = @At("RETURN"), cancellable = true) + private void onEnforceSecureProfile(CallbackInfoReturnable cir) { + cir.setReturnValue(false); + } + +} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinPlayerList.java b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinPlayerList.java new file mode 100644 index 0000000..9de6d81 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinPlayerList.java @@ -0,0 +1,24 @@ +package com.aizistral.nochatreports.common.mixins.server; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import net.minecraft.network.chat.PlayerChatMessage; +import net.minecraft.server.players.PlayerList; + +@Mixin(PlayerList.class) +public class MixinPlayerList { + + /** + * @reason Remove "Not Secure" mark in server chat logs. + * @author Aizistral + */ + + @Inject(method = "verifyChatTrusted", at = @At("HEAD"), cancellable = true) + private void onVerifyChatTrusted(PlayerChatMessage playerChatMessage, CallbackInfoReturnable info) { + info.setReturnValue(true); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerGamePacketListenerImpl.java b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerGamePacketListenerImpl.java new file mode 100644 index 0000000..01232e7 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerGamePacketListenerImpl.java @@ -0,0 +1,74 @@ +package com.aizistral.nochatreports.common.mixins.server; + +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.NCRCore; +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.network.PacketSendListener; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; +import net.minecraft.network.protocol.game.ClientboundSystemChatPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.server.network.ServerPlayerConnection; + +@Mixin(ServerGamePacketListenerImpl.class) +public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerConnection { + @Shadow + public ServerPlayer player; + + /** + * @reason Convert player message to system message if mod is configured respectively. + * This allows to circumvent signature check on client, as it only checks player messages. + * @author JFronny (original implementation) + * @author Aizistral + */ + + @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;)V", at = @At("HEAD"), cancellable = true) + private void onSend(Packet packet, CallbackInfo info) { + if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { + NCRCore.LOGGER.info("Sending message: {}", chat.unsignedContent() != null ? chat.unsignedContent() + : chat.body().content()); + } + + if (NCRConfig.getCommon().convertToGameMessage()) { + if (packet instanceof ClientboundPlayerChatPacket chat) { + packet = new ClientboundSystemChatPacket(chat.chatType().resolve(this.player.level.registryAccess()) + .get().decorate(chat.unsignedContent() != null ? chat.unsignedContent() + : Component.literal(chat.body().content())), false); + + info.cancel(); + this.send(packet); + } + } + } + + /** + * @reason Ensure conversion works regardless of which send method is used. + * @author Aizistral + */ + + @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;Lnet/minecraft/network/PacketSendListener;)V", + at = @At("HEAD"), cancellable = true) + private void onSend(Packet packet, @Nullable PacketSendListener packetSendListener, CallbackInfo info) { + if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { + NCRCore.LOGGER.info("Sending message: {}", chat.unsignedContent() != null ? chat.unsignedContent() + : chat.body().content()); + } + + if (NCRConfig.getCommon().convertToGameMessage()) { + if (packet instanceof ClientboundPlayerChatPacket chat && packetSendListener != null) { + info.cancel(); + ((ServerGamePacketListenerImpl) (Object) this).send(chat); + } + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatPacket.java b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatPacket.java new file mode 100644 index 0000000..bf25d92 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatPacket.java @@ -0,0 +1,26 @@ +package com.aizistral.nochatreports.common.mixins.server; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import net.minecraft.network.chat.MessageSignature; +import net.minecraft.network.protocol.game.ServerboundChatPacket; + +@Mixin(ServerboundChatPacket.class) +public class MixinServerboundChatPacket { + + /** + * @reason Strip signatures before relaying messages to other clients, if they arrive signed + * This is important for mod to be able to operate in server-only mode without + * {@link NCRConfigLegacy#convertToGameMessage()} enabled. + * @author Aizistral + */ + + @Inject(method = "signature", at = @At("RETURN"), cancellable = true) + private void onGetSignature(CallbackInfoReturnable info) { + info.setReturnValue(null); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatSessionUpdatePacket.java b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatSessionUpdatePacket.java new file mode 100644 index 0000000..d69e495 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/mixins/server/MixinServerboundChatSessionUpdatePacket.java @@ -0,0 +1,36 @@ +package com.aizistral.nochatreports.common.mixins.server; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.config.NCRConfig; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundChatSessionUpdatePacket; +import net.minecraft.server.network.ServerGamePacketListenerImpl; + +@Mixin(ServerboundChatSessionUpdatePacket.class) +public class MixinServerboundChatSessionUpdatePacket { + + /** + * @reason Ignore chat sessions from client, since we throw away signatures anyways. + * @author Aizistral + */ + + @Inject(method = "handle", at = @At("HEAD"), cancellable = true) + private void onHandle(ServerGamePacketListener listener, CallbackInfo info) { + var impl = (ServerGamePacketListenerImpl) listener; + + if (!impl.getPlayer().getServer().isSingleplayerOwner(impl.getPlayer().getGameProfile())) { + if (NCRConfig.getCommon().demandOnClient()) { + impl.disconnect(Component.literal(NCRConfig.getCommon().demandOnClientMessage())); + } + } + + info.cancel(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/platform/PlatformProvider.java b/src/main/java/com/aizistral/nochatreports/common/platform/PlatformProvider.java new file mode 100644 index 0000000..5dc064e --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/platform/PlatformProvider.java @@ -0,0 +1,16 @@ +package com.aizistral.nochatreports.common.platform; + +import java.io.File; +import java.nio.file.Path; + +import net.fabricmc.api.EnvType; + +public interface PlatformProvider { + + public EnvType getEnvironment(); + + public Path getMinecraftDir(); + + public Path getConfigDir(); + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/platform/events/ClientEvents.java b/src/main/java/com/aizistral/nochatreports/common/platform/events/ClientEvents.java new file mode 100644 index 0000000..aaf34e2 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/platform/events/ClientEvents.java @@ -0,0 +1,23 @@ +package com.aizistral.nochatreports.common.platform.events; + +import java.util.Collection; +import java.util.function.Function; + +import com.aizistral.nochatreports.common.platform.events.particular.Disconnect; +import com.aizistral.nochatreports.common.platform.events.particular.PlayReady; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; + +@Environment(EnvType.CLIENT) +public class ClientEvents { + public static final PlatformEvent PLAY_READY = PlatformEvent.create(callbacks -> + (handler, client) -> callbacks.forEach(callback -> callback.handle(handler, client))); + + public static final PlatformEvent DISCONNECT = PlatformEvent.create(callbacks -> + client -> callbacks.forEach(callback -> callback.handle(client))); + + private ClientEvents() { + throw new IllegalStateException("Can't touch this"); + } +} diff --git a/src/main/java/com/aizistral/nochatreports/common/platform/events/PlatformEvent.java b/src/main/java/com/aizistral/nochatreports/common/platform/events/PlatformEvent.java new file mode 100644 index 0000000..2902f35 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/platform/events/PlatformEvent.java @@ -0,0 +1,37 @@ +package com.aizistral.nochatreports.common.platform.events; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Function; + +public class PlatformEvent { + private final Collection callbacks; + private final Function, T> invokerFactory; + private volatile T invoker; + + private PlatformEvent(Function, T> invokerFactory) { + this.callbacks = new LinkedList<>(); + this.invokerFactory = invokerFactory; + } + + public T invoker() { + return this.invoker; + } + + public void register(T callback) { + this.callbacks.add(callback); + this.update(); + } + + private void update() { + this.invoker = this.invokerFactory.apply(this.callbacks); + } + + static PlatformEvent create(Function, T> invokerFactory) { + return new PlatformEvent<>(invokerFactory); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/common/platform/events/particular/Disconnect.java b/src/main/java/com/aizistral/nochatreports/common/platform/events/particular/Disconnect.java new file mode 100644 index 0000000..efa1a0d --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/platform/events/particular/Disconnect.java @@ -0,0 +1,11 @@ +package com.aizistral.nochatreports.common.platform.events.particular; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; + +@Environment(EnvType.CLIENT) +public interface Disconnect { + public void handle(Minecraft client); +} diff --git a/src/main/java/com/aizistral/nochatreports/common/platform/events/particular/PlayReady.java b/src/main/java/com/aizistral/nochatreports/common/platform/events/particular/PlayReady.java new file mode 100644 index 0000000..9ebbf65 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/common/platform/events/particular/PlayReady.java @@ -0,0 +1,11 @@ +package com.aizistral.nochatreports.common.platform.events.particular; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; + +@Environment(EnvType.CLIENT) +public interface PlayReady { + public void handle(ClientPacketListener handler, Minecraft client); +} diff --git a/src/main/java/com/aizistral/nochatreports/config/JSONConfig.java b/src/main/java/com/aizistral/nochatreports/config/JSONConfig.java deleted file mode 100644 index 6f5f488..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/JSONConfig.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.aizistral.nochatreports.config; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Optional; -import java.util.function.Supplier; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.JSONConfig; -import com.aizistral.nochatreports.config.ServerAddressAdapter; -import com.google.gson.ExclusionStrategy; -import com.google.gson.FieldAttributes; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; - -import net.fabricmc.api.EnvType; -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.multiplayer.resolver.ServerAddress; - -public abstract class JSONConfig { - protected static final Path CONFIG_DIR = FabricLoader.getInstance().getConfigDir(); - protected static final Gson GSON = createGson(); - - protected final String fileName; - protected final Path filePath; - - protected JSONConfig(String file) { - this.fileName = file; - this.filePath = CONFIG_DIR.resolve(this.fileName); - } - - public Path getFile() { - return this.filePath; - } - - public void saveFile() { - NoChatReports.LOGGER.info("Writing config file {}...", this.fileName); - writeFile(this.fileName, this); - } - - protected void uponLoad() { - // NO-OP - } - - public abstract JSONConfig getDefault(); - - public static T loadConfig(Class configClass, Supplier freshInstance, String fileName) { - NoChatReports.LOGGER.info("Reading config file {}...", fileName); - T config = readFile(fileName, configClass).orElseGet(freshInstance); - config.uponLoad(); - return config; - } - - private static Optional readFile(String fileName, Class configClass) { - Path file = CONFIG_DIR.resolve(fileName); - - if (!Files.isRegularFile(file)) - return Optional.empty(); - - try (BufferedReader reader = Files.newBufferedReader(file)) { - return Optional.of(GSON.fromJson(reader, configClass)); - } catch (Exception ex) { - NoChatReports.LOGGER.fatal("Could not read config file: {}", file); - NoChatReports.LOGGER.fatal("This likely indicates the file is corrupted. " - + "You can try deleting it to fix this problem. Full stacktrace below:"); - ex.printStackTrace(); - return null; - } - } - - private static void writeFile(String fileName, T config) { - Path file = CONFIG_DIR.resolve(fileName); - - try { - Files.createDirectories(file.getParent()); - try (BufferedWriter writer = Files.newBufferedWriter(file)) { - GSON.toJson(config, writer); - } - } catch (Exception ex) { - NoChatReports.LOGGER.fatal("Could not write config file: {}", file); - throw new RuntimeException(ex); - } - } - - private static Gson createGson() { - GsonBuilder builder = new GsonBuilder(); - builder.setPrettyPrinting(); - builder.setExclusionStrategies(new ExclusionStrategy() { - @Override - public boolean shouldSkipField(FieldAttributes field) { - return field.getDeclaringClass() == JSONConfig.class; - } - - @Override - public boolean shouldSkipClass(Class theClass) { - return false; - } - }); - - if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { - builder.registerTypeAdapter(ServerAddress.class, ServerAddressAdapter.INSTANCE); - } - - return builder.create(); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/config/ModMenuIntegration.java b/src/main/java/com/aizistral/nochatreports/config/ModMenuIntegration.java deleted file mode 100644 index 6163a88..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/ModMenuIntegration.java +++ /dev/null @@ -1,276 +0,0 @@ -package com.aizistral.nochatreports.config; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.core.SigningMode; -import com.aizistral.nochatreports.gui.FontHelper; -import com.terraformersmc.modmenu.api.ConfigScreenFactory; -import com.terraformersmc.modmenu.api.ModMenuApi; -import me.shedaniel.clothconfig2.api.ConfigBuilder; -import me.shedaniel.clothconfig2.api.ConfigCategory; -import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.locale.Language; -import net.minecraft.network.chat.ClickEvent; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.HoverEvent; -import net.minecraft.network.chat.MutableComponent; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -/** - * Implementation of ModMenu and ClothConfig support for the mod. - * - * @author MODKILLER1001 - */ - -@Environment(EnvType.CLIENT) -public final class ModMenuIntegration implements ModMenuApi { - - private String translateKey(String key) { - return Language.getInstance().getOrDefault(key); - } - - private Component[] wrapTooltip(String text) { - List list = FontHelper.wrap(Minecraft.getInstance().font, text, 250); - Component[] tooltip = new Component[list.size()]; - - for (int i = 0; i < list.size(); i++) { - tooltip[i] = Component.literal(list.get(i)); - } - - return tooltip; - } - - private Component[] makeTooltip(String key) { - return this.wrapTooltip(this.translateKey(key)); - } - - @Override - public ConfigScreenFactory getModConfigScreenFactory() { - return screen -> { - - // Get the previous screen - ConfigBuilder builder = ConfigBuilder.create() - .setParentScreen(Minecraft.getInstance().screen) - .setTitle(Component.translatable("configuration.NoChatReports.config")); - - // Set category - ConfigCategory client = builder.getOrCreateCategory(Component.translatable("configuration.NoChatReports.category.client")); - ConfigCategory lan = builder.getOrCreateCategory(Component.translatable("configuration.NoChatReports.category.lan")); - - ConfigEntryBuilder entryBuilder = builder.entryBuilder(); - - // Set an option for enableMod - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.enableMod"), NCRConfig.getClient().enableMod) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.enableMod.tooltip")) - .setSaveConsumer(newValue -> ServerSafetyState.scheduleResetAction(() -> { - NCRConfig.getClient().enableMod = newValue; - NCRConfig.getClient().saveFile(); - })) - .build()); - - // Set an option for showNCRButton - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showNCRButton"), NCRConfig.getClient().showNCRButton) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.showNCRButton.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().showNCRButton = newValue) - .build()); - - - String signingTooltip = this.translateKey("option.NoChatReports.defaultSigningMode.tooltip") - + "\n "; - - for (SigningMode mode : SigningMode.values()) { - if (mode.isSelectableGlobally()) { - signingTooltip += "\n\n"; - signingTooltip += ChatFormatting.AQUA; - signingTooltip += ChatFormatting.BOLD; - signingTooltip += ChatFormatting.UNDERLINE; - signingTooltip += this.translateKey(mode.getNameKey()); - signingTooltip += ChatFormatting.RESET; - signingTooltip += "\n"; - signingTooltip += this.translateKey(mode.getTooltipKey()); - } - } - - // Dropdown for defaultSigningMode - client.addEntry( - entryBuilder.startStringDropdownMenu(Component.translatable("option.NoChatReports.defaultSigningMode"), - NCRConfig.getClient().defaultSigningMode.getName().getString()) - .setTooltip(this.wrapTooltip(signingTooltip)) - .setDefaultValue(SigningMode.PROMPT.getName().getString()) - .setSelections(Stream.of(SigningMode.values()).filter(SigningMode::isSelectableGlobally) - .map(mode -> mode.getName().getString()).toList()) - .setSaveConsumer(newValue -> { - NCRConfig.getClient().defaultSigningMode = Arrays.stream(SigningMode.values()) - .filter(mode -> mode.getName().getString().equals(newValue)) - .findFirst().get(); - }) - .setSuggestionMode(false) - .build() - ); - - // Set an option for showReloadButton - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showReloadButton"), NCRConfig.getClient().showReloadButton) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.showReloadButton.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().showReloadButton = newValue) - .build()); - - // Set an option for verifiedIconEnabled - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.verifiedIconEnabled"), NCRConfig.getClient().verifiedIconEnabled) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.verifiedIconEnabled.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().verifiedIconEnabled = newValue) - .build()); - - // Set an option for verifiedIconOffsetX - client.addEntry(entryBuilder.startIntField(Component.translatable("option.NoChatReports.verifiedIconOffsetX"), NCRConfig.getClient().verifiedIconOffsetX) - .setDefaultValue(0) - .setTooltip(this.makeTooltip("option.NoChatReports.verifiedIconOffsetX.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().verifiedIconOffsetX = newValue) - .build()); - - // Set an option for verifiedIconOffsetY - client.addEntry(entryBuilder.startIntField(Component.translatable("option.NoChatReports.verifiedIconOffsetY"), NCRConfig.getClient().verifiedIconOffsetY) - .setDefaultValue(0) - .setTooltip(this.makeTooltip("option.NoChatReports.verifiedIconOffsetY.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().verifiedIconOffsetY = newValue) - .build()); - - // Warning for showEncryptionButton - client.addEntry(entryBuilder.startTextDescription(Component.translatable("gui.NoChatReports.showEncryptionButtonWarning")) - .build()); - - // Set an option for showEncryptionButton - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showEncryptionButton"), NCRConfig.getEncryption().showEncryptionButton) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.showEncryptionButton.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getEncryption().showEncryptionButton = newValue) - .build()); - - // Set an option for showEncryptionIndicators - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showEncryptionIndicators"), NCRConfig.getEncryption().showEncryptionIndicators) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.showEncryptionIndicators.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getEncryption().showEncryptionIndicators = newValue) - .build()); - - // Set an option for showServerSafety - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.showServerSafety"), NCRConfig.getClient().showServerSafety) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.showServerSafety.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().showServerSafety = newValue) - .build()); - - // Add link for documentation for showServerSafety - client.addEntry(entryBuilder.startTextDescription(Component.translatable("option.NoChatReports.showServerSafety.moreInfo") - .withStyle(s -> s - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/Configuration-Files/#option-showserversafety"))).withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/Configuration-Files/#option-showserversafety")))) - .build()); - - // Set an option for hideInsecureMessageIndicators - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideInsecureMessageIndicators"), NCRConfig.getClient().hideInsecureMessageIndicators) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.hideInsecureMessageIndicators.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().hideInsecureMessageIndicators = newValue) - .build()); - - // Set an option for hideModifiedMessageIndicators - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideModifiedMessageIndicators"), NCRConfig.getClient().hideModifiedMessageIndicators) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.hideModifiedMessageIndicators.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().hideModifiedMessageIndicators = newValue) - .build()); - - // Set an option for hideSystemMessageIndicators - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideSystemMessageIndicators"), NCRConfig.getClient().hideSystemMessageIndicators) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.hideSystemMessageIndicators.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().hideSystemMessageIndicators = newValue) - .build()); - - // Set an option for hideWarningToast - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideWarningToast"), NCRConfig.getClient().hideWarningToast) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.hideWarningToast.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().hideWarningToast = newValue) - .build()); - - // Set an option for hideSigningRequestMessage - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.hideSigningRequestMessage"), NCRConfig.getClient().hideSigningRequestMessage) - .setDefaultValue(false) - .setTooltip(this.makeTooltip("option.NoChatReports.hideSigningRequestMessage.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().hideSigningRequestMessage = newValue) - .build()); - - // Set an option for alwaysHideReportButton - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.alwaysHideReportButton"), NCRConfig.getClient().alwaysHideReportButton) - .setDefaultValue(false) - .setTooltip(this.makeTooltip("option.NoChatReports.alwaysHideReportButton.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().alwaysHideReportButton = newValue) - .build()); - - // Set an option for demandOnServer - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.demandOnServer"), NCRConfig.getClient().demandOnServer) - .setDefaultValue(false) - .setTooltip(this.makeTooltip("option.NoChatReports.demandOnServer.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().demandOnServer = newValue) - .build()); - - // Set an option for enableDebugLog - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.enableDebugLog"), NCRConfig.getCommon().enableDebugLog) - .setDefaultValue(false) - .setTooltip(this.makeTooltip("option.NoChatReports.enableDebugLog.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getCommon().enableDebugLog = newValue) - .build()); - - // Set an option for disableTelemetry - client.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.disableTelemetry"), NCRConfig.getClient().disableTelemetry) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.disableTelemetry.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getClient().disableTelemetry = newValue) - .build()); - - // Set an option for demandOnClient - lan.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.demandOnClient"), NCRConfig.getCommon().demandOnClient) - .setDefaultValue(false) - .setTooltip(this.makeTooltip("option.NoChatReports.demandOnClient.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getCommon().demandOnClient = newValue) - .build()); - - // Set an option for demandOnClientMessage - lan.addEntry(entryBuilder.startStrField(Component.translatable("option.NoChatReports.demandOnClientMessage"), NCRConfig.getCommon().demandOnClientMessage) - .setDefaultValue(NCRConfig.getCommon().demandOnClientMessage) - .setTooltip(this.makeTooltip("option.NoChatReports.demandOnClientMessage.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getCommon().demandOnClientMessage = newValue) - .build()); - - // Set an option for convertToGameMessage - lan.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.convertToGameMessage"), NCRConfig.getCommon().convertToGameMessage) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.convertToGameMessage.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getCommon().convertToGameMessage = newValue) - .build()); - - // Set an option for addQueryData - lan.addEntry(entryBuilder.startBooleanToggle(Component.translatable("option.NoChatReports.addQueryData"), NCRConfig.getCommon().addQueryData) - .setDefaultValue(true) - .setTooltip(this.makeTooltip("option.NoChatReports.addQueryData.tooltip")) - .setSaveConsumer(newValue -> NCRConfig.getCommon().addQueryData = newValue) - .build()); - - // Save config - builder.setSavingRunnable(NCRConfig::save); - return builder.build(); - }; - } - -} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java deleted file mode 100644 index 5a1137f..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.aizistral.nochatreports.config; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.JSONConfig; -import com.aizistral.nochatreports.config.NCRConfigClient; -import com.aizistral.nochatreports.config.NCRConfigCommon; -import com.aizistral.nochatreports.config.NCRConfigEncryption; -import com.aizistral.nochatreports.config.NCRServerPreferences; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.loader.api.FabricLoader; - -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.function.Supplier; - -public final class NCRConfig { - private static NCRConfigCommon common = null; - private static NCRConfigClient client = null; - private static NCRServerPreferences serverPreferences = null; - private static NCRConfigEncryption encryption = null; - - private NCRConfig() { - throw new IllegalStateException("Can't touch this"); - } - - public static NCRConfigCommon getCommon() { - return checkLoaded(() -> common); - } - - @Environment(EnvType.CLIENT) - public static NCRConfigClient getClient() { - return checkLoaded(() -> client); - } - - @Environment(EnvType.CLIENT) - public static NCRServerPreferences getServerPreferences() { - return checkLoaded(() -> serverPreferences); - } - - @Environment(EnvType.CLIENT) - public static NCRConfigEncryption getEncryption() { - return checkLoaded(() -> encryption); - } - - private static T checkLoaded(Supplier config) { - if (config.get() == null) { - load(); - } - - return config.get(); - } - - public static void load() { - common = JSONConfig.loadConfig(NCRConfigCommon.class, NCRConfigCommon::new, NCRConfigCommon.FILE_NAME); - - if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { - client = JSONConfig.loadConfig(NCRConfigClient.class, NCRConfigClient::new, NCRConfigClient.FILE_NAME); - serverPreferences = JSONConfig.loadConfig(NCRServerPreferences.class, NCRServerPreferences::new, NCRServerPreferences.FILE_NAME); - encryption = JSONConfig.loadConfig(NCRConfigEncryption.class, NCRConfigEncryption::new, NCRConfigEncryption.FILE_NAME); - } - - save(); - } - - public static void save() { - checkLoaded(() -> common).saveFile(); - - if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { - checkLoaded(() -> client).saveFile(); - checkLoaded(() -> serverPreferences).saveFile(); - checkLoaded(() -> encryption).saveFile(); - } - - Path readme = JSONConfig.CONFIG_DIR.resolve("NoChatReports/README.md"); - try { - Files.writeString(readme, """ - # No Chat Reports - You can find updated documentation of configuration files on the wiki: - https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/Configuration-Files - """, StandardCharsets.UTF_8); - } catch (Exception ex) { - NoChatReports.LOGGER.fatal("Could not write README file: {}", readme); - throw new RuntimeException(ex); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java deleted file mode 100644 index 800deaf..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java +++ /dev/null @@ -1,209 +0,0 @@ -package com.aizistral.nochatreports.config; - -import com.aizistral.nochatreports.config.JSONConfig; -import com.aizistral.nochatreports.config.NCRConfigClient; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.SigningMode; -import com.aizistral.nochatreports.mixins.client.MixinChatListener; -import com.aizistral.nochatreports.mixins.client.MixinToastComponent; - -public final class NCRConfigClient extends JSONConfig { - protected static final String FILE_NAME = "NoChatReports/NCR-Client.json"; - - protected SigningMode defaultSigningMode = SigningMode.PROMPT; - protected boolean enableMod = true, showNCRButton = true, showReloadButton = true, - verifiedIconEnabled = true, showServerSafety = true, hideInsecureMessageIndicators = true, - hideModifiedMessageIndicators = true, hideSystemMessageIndicators = true, - hideWarningToast = true, hideSigningRequestMessage = false, alwaysHideReportButton = false, - skipRealmsWarning = false, disableTelemetry = true, removeTelemetryButton = true, - demandOnServer = false; - protected int verifiedIconOffsetX = 0, verifiedIconOffsetY = 0; - - protected NCRConfigClient() { - super(FILE_NAME); - } - - @Override - public NCRConfigClient getDefault() { - return new NCRConfigClient(); - } - - public void toggleMod() { - this.enableMod = !this.enableMod; - } - - /** - * @return True if client with No Chat Reports installed should demand that mod is present on - * every server that it tries to join. In that case client will not be able to join servers that - * don't have the mod installed. Servers without the mod can still provide varying degrees of - * safety, which {@link ServerSafetyLevel} and respective icon in bottom-right corner of the chat - * screen is designed to indicate.

- * - * This is false by default. - */ - - public boolean demandOnServer() { - return this.demandOnServer; - } - - /** - * @return True if current {@link ServerSafetyLevel} should be indicated on client by an icon in - * the bottom-right corner of chat screen.

- * - * This is true by default. - */ - - public boolean showServerSafety() { - return this.showServerSafety; - } - - /** - * @return True if vanilla's unsigned messages trust indicator should be removed.

- * - * This is true by default. - * - * @see MixinChatListener#onEvaluateTrustLevel - */ - - public boolean hideInsecureMessageIndicators() { - return this.hideInsecureMessageIndicators; - } - - /** - * @return True if vanilla's modified/hidden messages trust indicator should be removed.

- * - * This is true by default. - * - * @see MixinChatListener#onEvaluateTrustLevel - */ - - public boolean hideModifiedMessageIndicators() { - return this.hideModifiedMessageIndicators; - } - - /** - * @return True if vanilla's system messages trust indicator should be removed.

- * - * This is true by default. - * - * @see com.aizistral.nochatreports.mixins.client.MixinGuiMessageTag#onSystem - */ - - public boolean hideSystemMessageIndicators() { - return this.hideSystemMessageIndicators; - } - - /** - * @return True if "Chat messages can't be verified" toast should be removed.

- * - * This is true by default. - * - * @see MixinToastComponent#onAddToast - */ - - public boolean hideWarningToast() { - return this.hideWarningToast; - } - - /** - * @return True if reporting buttons should always be hidden from social interactions screen, - * instead of simply being disabled.

- * - * This is false by default. - */ - - public boolean alwaysHideReportButton() { - return this.alwaysHideReportButton; - } - - /** - * @return True if sending telemetry to Mojang should be disabled.

- * - * This is true by default. - */ - - public boolean disableTelemetry() { - return this.disableTelemetry; - } - - /** - * @return True if the configuration reload button should be displayed in multiplayer screen. - *

- * - * This is true by default. - */ - - public boolean showReloadButton() { - return this.showReloadButton; - } - - /** - * @return True if "Safe Server" icon should be displayed in multiplayer menu for servers that - * declare themselves as preventing chat reports.

- * - * This is true by default. - */ - - public boolean verifiedIconEnabled() { - return this.verifiedIconEnabled; - } - - - /** - * @return X offset for "Safe Server" icon in multiplayer menu. - */ - - public int getVerifiedIconOffsetX() { - return 16 + this.verifiedIconOffsetX; - } - - /** - * @return Y offset for "Safe Server" icon in multiplayer menu. - */ - - public int getVerifiedIconOffsetY() { - return 12 + this.verifiedIconOffsetY; - } - - /** - * @return True if button to disable/enable entire mod should be displayed in - * multiplayer menu. - */ - - public boolean showNCRButton() { - return this.showNCRButton; - } - - /** - * @return Whether or not No Chat Reports should provide networking-related functionality. - */ - - public boolean enableMod() { - return this.enableMod; - } - - /** - * @return Whether warning on entering Realms screen should not be displayed. - */ - - public boolean skipRealmsWarning() { - return this.skipRealmsWarning; - } - - public void setSkipRealmsWarning(boolean skipRealmsWarning) { - this.skipRealmsWarning = skipRealmsWarning; - } - - public boolean hideSigningRequestMessage() { - return this.hideSigningRequestMessage; - } - - public SigningMode defaultSigningMode() { - return this.defaultSigningMode; - } - - public boolean removeTelemetryButton() { - return this.removeTelemetryButton; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java deleted file mode 100644 index 861f57d..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.aizistral.nochatreports.config; - -import com.aizistral.nochatreports.config.JSONConfig; -import com.aizistral.nochatreports.config.NCRConfigCommon; - -public final class NCRConfigCommon extends JSONConfig { - protected static final String FILE_NAME = "NoChatReports/NCR-Common.json"; - - protected String demandOnClientMessage = "You do not have No Chat Reports, and this server is" - + " configured to require it on client!"; - protected boolean demandOnClient = false, convertToGameMessage = true, - addQueryData = true, enableDebugLog = false; - - protected NCRConfigCommon() { - super(FILE_NAME); - } - - @Override - public NCRConfigCommon getDefault() { - return new NCRConfigCommon(); - } - - /** - * @return True if server with No Chat Reports installed should demand that mod is present on - * every client that tries to join. Mod's installation on client is optional otherwise.

- * - * This is false by default. - */ - - public boolean demandOnClient() { - return this.demandOnClient; - } - - /** - * @return Disconnect message that should be shown to client if demandOnClient is - * true and it tries to join without No Chat Reports installed. - */ - - public String demandOnClientMessage() { - return this.demandOnClientMessage; - } - - /** - * @return True if server should convert all player messages to system messages. System messages - * do not feature signatures and look completely identical in the chat, with exception of gray line - * next to them added in pre-release 3. They are also unselectable for chat reporting.

- * - * This is false by default. - */ - - public boolean convertToGameMessage() { - return this.convertToGameMessage; - } - - /** - * @return True if mod should log some additional information about its activity and message - * signatures. Generally only useful for debugging.

- * - * This is false by default. - */ - - public boolean enableDebugLog() { - return this.enableDebugLog; - } - - /** - * @return True if server should include extra query data to help clients know that your server - * is secure.

- * - * This is true by default. - */ - - public boolean addQueryData() { - return this.addQueryData; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java deleted file mode 100644 index 6cd4f0a..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.aizistral.nochatreports.config; - -import com.aizistral.nochatreports.config.JSONConfig; -import com.aizistral.nochatreports.config.NCRConfigEncryption; -import com.aizistral.nochatreports.encryption.Encryption; -import com.aizistral.nochatreports.encryption.Encryptor; - -import java.security.InvalidKeyException; -import java.util.List; -import java.util.Optional; - -public class NCRConfigEncryption extends JSONConfig { - protected static final String FILE_NAME = "NoChatReports/NCR-Encryption.json"; - protected boolean skipWarning = false, enableEncryption = false, encryptPublic = true, - showEncryptionButton = true, showEncryptionIndicators = true; - protected String encryptionKey = Encryption.AES_CFB8.getDefaultKey(), encryptionPassphrase = "", - algorithmName = Encryption.AES_CFB8.getName(); - protected List encryptableCommands = List.of("msg:1", "w:1", "whisper:1", "tell:1", "r:0", "dm:1", - "me:0", "m:1", "t:1", "pm:1", "emsg:1", "epm:1", "etell:1", "ewhisper:1"); - private transient Encryption algorithm; - private transient boolean isValid = false; - private transient String lastMessage = "???"; - - protected NCRConfigEncryption() { - super(FILE_NAME); - } - - @Override - public NCRConfigEncryption getDefault() { - return new NCRConfigEncryption(); - } - - @Override - protected void uponLoad() { - this.algorithm = Encryption.getRegistered().stream().filter(e -> e.getName().equals(this.algorithmName)) - .findFirst().orElse(Encryption.AES_CFB8); - this.validate(); - } - - private void validate() { - this.isValid = this.algorithm.validateKey(this.encryptionKey); - } - - public void toggleEncryption() { - this.enableEncryption = !this.enableEncryption; - this.saveFile(); - } - - public void setAlgorithm(Encryption encryption) { - this.algorithm = encryption; - this.algorithmName = encryption.getName(); - this.validate(); - this.saveFile(); - } - - public void setEncryptionKey(String key) { - this.encryptionKey = key; - this.validate(); - this.saveFile(); - } - - public void setEncryptionPassphrase(String pass) { - this.encryptionPassphrase = pass; - this.saveFile(); - } - - public void setEncryptPublic(boolean encryptPublic) { - this.encryptPublic = encryptPublic; - this.saveFile(); - } - - public void disableWarning() { - this.skipWarning = true; - } - - public boolean isWarningDisabled() { - return this.skipWarning; - } - - public boolean isEnabled() { - return this.enableEncryption; - } - - public String getEncryptionKey() { - return this.encryptionKey; - } - - public String getEncryptionPassphrase() { - return this.encryptionPassphrase; - } - - public boolean isValid() { - return this.isValid; - } - - public boolean shouldEncryptPublic() { - return this.encryptPublic; - } - - public boolean showEncryptionIndicators() { - return this.showEncryptionIndicators; - } - - public boolean isEnabledAndValid() { - return this.isEnabled() && this.isValid(); - } - - public Encryption getAlgorithm() { - return this.algorithm; - } - - public boolean shouldEncrypt(String message) { - return this.isEnabledAndValid() && this.getEncryptionStartIndex(message) != -1; - } - - public boolean showEncryptionButton() { - return this.showEncryptionButton; - } - - public int getEncryptionStartIndex(String message) { - if (!message.startsWith("/")) - return this.encryptPublic ? 0 : -1; - else { - for (String rule : this.encryptableCommands) { - String[] splat = rule.split(":"); - - if (splat.length != 2) - throw new IllegalArgumentException("Invalid encryptable command definition: " + rule - + ", in file: " + FILE_NAME); - - String cmd = splat[0]; - String args = splat[1]; - int argnum = 0; - - try { - argnum = Integer.valueOf(args); - } catch (NumberFormatException ex) { - throw new IllegalArgumentException("Invalid encryptable command definition: " + rule - + ", in file: " + FILE_NAME); - } - - String prefix = "/(" + cmd + "|.*:" + cmd + ") .*"; - if (message.matches(prefix)) { - splat = message.split(" ", 2); - char[] array = splat[1].toCharArray(); - - for (int i = 0; i < array.length; i++) { - char ch = array[i]; - if (argnum > 0) { - if (ch == ' ') { - argnum--; - } - continue; - } else { - int index = i + splat[0].length() + 1; - return index < message.length() ? index : -1; - } - } - } else { - continue; - } - } - - return -1; - } - } - - public void setLastMessage(String lastMessage) { - this.lastMessage = lastMessage; - } - - public String getLastMessage() { - return this.lastMessage; - } - - /** - * @return Chat encryptor, if encryption is enabled and user specified valid key in config. - */ - - public Optional> getEncryptor() { - if (!this.isEnabledAndValid()) - return Optional.empty(); - - try { - return Optional.of(this.algorithm.getProcessor(this.encryptionKey)); - } catch (InvalidKeyException ex) { - throw new RuntimeException(ex); // shouldn't happen due to prior validation - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRServerPreferences.java b/src/main/java/com/aizistral/nochatreports/config/NCRServerPreferences.java deleted file mode 100644 index 81ad97f..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/NCRServerPreferences.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.aizistral.nochatreports.config; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - -import com.aizistral.nochatreports.NoChatReportsClient; -import com.aizistral.nochatreports.config.JSONConfig; -import com.aizistral.nochatreports.config.NCRServerPreferences; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.core.SigningMode; -import com.aizistral.nochatreports.gui.UnsafeServerScreen; - -import net.minecraft.client.multiplayer.resolver.ServerAddress; - -public class NCRServerPreferences extends JSONConfig { - protected static final String FILE_NAME = "NoChatReports/NCR-ServerPreferences.json"; - protected HashMap signingModes = new HashMap<>(); - - protected NCRServerPreferences() { - super(FILE_NAME); - } - - @Override - public NCRServerPreferences getDefault() { - return new NCRServerPreferences(); - } - - public SigningMode getModeRaw(@Nullable ServerAddress address) { - return this.signingModes.get(address); - } - - public SigningMode getModeUnresolved(@Nullable ServerAddress address) { - if (!NoChatReportsClient.areSigningKeysPresent()) - return SigningMode.NEVER_FORCED; - else if (ServerSafetyState.isInSingleplayer()) - return SigningMode.NEVER; - else if (ServerSafetyState.isOnRealms()) - return SigningMode.ALWAYS; - else if (address == null) - return SigningMode.DEFAULT; - - SigningMode mode = this.getModeRaw(address); - return mode != null ? mode : SigningMode.DEFAULT; - } - - public SigningMode getMode(@Nullable ServerAddress address) { - return this.getModeUnresolved(address).resolve(); - } - - public boolean hasMode(@Nullable ServerAddress address, SigningMode mode) { - return this.getMode(address) == mode; - } - - public boolean hasModeCurrent(SigningMode mode) { - return this.hasMode(ServerSafetyState.getLastServer(), mode); - } - - public void setMode(@Nullable ServerAddress address, @Nullable SigningMode mode) { - if (address == null) - return; - - if (mode == null || mode == SigningMode.DEFAULT) { - this.signingModes.remove(address); - } else { - this.signingModes.put(address, mode); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/config/ServerAddressAdapter.java b/src/main/java/com/aizistral/nochatreports/config/ServerAddressAdapter.java deleted file mode 100644 index 8d63bd1..0000000 --- a/src/main/java/com/aizistral/nochatreports/config/ServerAddressAdapter.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.aizistral.nochatreports.config; - -import com.aizistral.nochatreports.config.ServerAddressAdapter; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.multiplayer.resolver.ServerAddress; - -import java.io.IOException; - -@Environment(EnvType.CLIENT) -public class ServerAddressAdapter extends TypeAdapter { - public static final ServerAddressAdapter INSTANCE = new ServerAddressAdapter(); - - private ServerAddressAdapter() { - // NO-OP - } - - @Override - public ServerAddress read(JsonReader reader) throws IOException { - String string = reader.nextString(); - - if (!ServerAddress.isValidAddress(string)) - throw new IOException("Incorrect server address format: " + string); - - return ServerAddress.parseString(string); - } - - @Override - public void write(JsonWriter writer, ServerAddress address) throws IOException { - writer.value(address.toString()); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java b/src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java deleted file mode 100644 index a614bba..0000000 --- a/src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.aizistral.nochatreports.core; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.encryption.Encryptor; - -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.ComponentContents; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.contents.LiteralContents; -import net.minecraft.network.chat.contents.TranslatableContents; - -import java.util.Optional; - -public class EncryptionUtil { - - public static Optional tryDecrypt(Component component) { - var optional = NCRConfig.getEncryption().getEncryptor(); - if (optional.isEmpty()) - return Optional.empty(); - - Encryptor encryption = optional.get(); - Component copy = recreate(component); - ComponentContents contents = copy.getContents(); - - return Optional.ofNullable(tryDecrypt(copy, encryption) ? copy : null); - } - - public static boolean tryDecrypt(Component component, Encryptor encryptor) { - boolean decryptedSiblings = false; - for (Component sibling : component.getSiblings()) { - if (tryDecrypt(sibling, encryptor)) { - decryptedSiblings = true; - } - } - - if (component.getContents() instanceof LiteralContents literal) { - var decrypted = tryDecrypt(literal.text(), encryptor); - - if (decrypted.isPresent()) { - ((MutableComponent)component).contents = new LiteralContents(decrypted.get()); - return true; - } - } else if (component.getContents() instanceof TranslatableContents translatable) { - for (Object arg : translatable.args) { - if (arg instanceof MutableComponent mutable) { - if (tryDecrypt(mutable, encryptor)) { - decryptedSiblings = true; - } - } - } - } - - return decryptedSiblings; - } - - public static Optional tryDecrypt(String message, Encryptor encryptor) { - try { - String[] splat = message.contains(" ") ? message.split(" ") : new String[] { message }; - String decryptable = splat[splat.length-1]; - - String decrypted = encryptor.decrypt(decryptable); - - if (decrypted.startsWith("#%")) - return Optional.of(message.substring(0, message.length() - decryptable.length()) + decrypted.substring(2, decrypted.length())); - else - return Optional.empty(); - } catch (Exception ex) { - return Optional.empty(); - } - } - - public static Component recreate(Component component) { - return Component.Serializer.fromJson(Component.Serializer.toStableJson(component)); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java b/src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java deleted file mode 100644 index a92ea52..0000000 --- a/src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.aizistral.nochatreports.core; - -import com.aizistral.nochatreports.mixins.client.MixinServerData; -import com.aizistral.nochatreports.mixins.common.MixinServerStatus; - -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.network.protocol.status.ServerStatus; - -/** - * Implemented by {@link MixinServerStatus} on {@link ServerStatus} class and {@link MixinServerData} - * on {@link ServerData} class. - * - * @author fxmorin (original implementation) - * @author Aizistral (current version) - */ - -public interface ServerDataExtension { - - public boolean preventsChatReports(); - - public void setPreventsChatReports(boolean prevents); - -} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyLevel.java b/src/main/java/com/aizistral/nochatreports/core/ServerSafetyLevel.java deleted file mode 100644 index 817f192..0000000 --- a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyLevel.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.aizistral.nochatreports.core; - -import com.aizistral.nochatreports.core.ServerSafetyState; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; - -/** - * Represents the level of "safety" of the given server, in the eyes of the client. - * Current level is updated dynamically and can be obtained using {@link ServerSafetyState#getCurrent()}. - * @author Aizistral - */ - -public enum ServerSafetyLevel { - - /** - * For servers that have No Chat Reports or something of similar purpose installed, and make - * verifiable effort to remove cryptographic signature from every player message they relay. - */ - SECURE, - - /** - * For singleplayer specifically. Pretty much identical to {@link #SECURE} since client needs - * NCR installed on it to display any safety level to begin with. - */ - SINGLEPLAYER, - - - /** - * For servers that do not make any effort to remove signatures from chat messages themselves, - * but do not prohibit players from sending unsigned messages. To protect the player falls fully - * on the client of respective player in such case, and vanilla client will not do that. - */ - UNINTRUSIVE, - - /** - * For servers that have enforce-secure-profile enabled, or enforce signed messages - * through some other means. Users of this mod can choose to play on those servers regardless - * after being informed of danger, but there is very little mod will be able to do to protect - * them in such case. - */ - - INSECURE, - - /** - * For Realms specifically, as these are a whole new level of unsafe. - */ - - REALMS, - - /** - * Reserved for when mod is toggled mid-session and cannot evaluate safety status. - */ - - UNKNOWN, - - /** - * Transient status for when evaluation of safety level is not yet complete for current server. - */ - - UNDEFINED; - - public MutableComponent getTooltip() { - return Component.translatable("gui.nochatreports.safety_status." + this.name().toLowerCase()); - } - - public boolean isSecure() { - return this == SECURE || this == SINGLEPLAYER; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java b/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java deleted file mode 100644 index 73b08ad..0000000 --- a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.aizistral.nochatreports.core; - -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.gui.UnsafeServerScreen; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.resolver.ServerAddress; -import net.minecraft.network.chat.LocalChatSession; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.jetbrains.annotations.Nullable; - -/** - * All this global state is questionable, but we have to... - * @author Aizistral - */ - -@Environment(EnvType.CLIENT) -public final class ServerSafetyState { - private static final List RESET_ACTIONS = new ArrayList<>(); - private static final List SIGNING_ACTIONS = new ArrayList<>(); - private static final AtomicBoolean ALLOW_CHAT_SIGNING = new AtomicBoolean(false); - private volatile static ServerSafetyLevel current = ServerSafetyLevel.UNDEFINED; - private volatile static ServerAddress lastServer = null; - - public static void updateCurrent(ServerSafetyLevel level) { - current = level; - } - - public static ServerSafetyLevel getCurrent() { - return current; - } - - public static boolean allowChatSigning() { - return ALLOW_CHAT_SIGNING.get(); - } - - public static CompletableFuture setAllowChatSigning(boolean allow) { - if (ALLOW_CHAT_SIGNING.compareAndSet(!allow, allow)) { - if (Minecraft.getInstance().player != null) { - var connection = Minecraft.getInstance().player.connection; - - if (allow && connection.chatSession == null) - return Minecraft.getInstance().getProfileKeyPairManager().prepareKeyPair() - .thenAcceptAsync(optional -> optional.ifPresent(profileKeyPair -> { - connection.setKeyPair(profileKeyPair); - SIGNING_ACTIONS.forEach(Runnable::run); - SIGNING_ACTIONS.clear(); - }), Minecraft.getInstance()); - } - } - - return CompletableFuture.completedFuture(null); - } - - public static void toggleChatSigning() { - setAllowChatSigning(!ALLOW_CHAT_SIGNING.get()); - } - - public static boolean isOnRealms() { - return current == ServerSafetyLevel.REALMS; - } - - public static boolean isInSingleplayer() { - return current == ServerSafetyLevel.SINGLEPLAYER; - } - - public static boolean isDetermined() { - return current != ServerSafetyLevel.UNINTRUSIVE && current != ServerSafetyLevel.UNDEFINED - && current != ServerSafetyLevel.UNKNOWN; - } - - @Nullable - public static ServerAddress getLastServer() { - return lastServer; - } - - public static void setLastServer(@Nullable ServerAddress address) { - lastServer = address; - } - - public static void scheduleResetAction(Runnable action) { - RESET_ACTIONS.add(action); - } - - public static void scheduleSigningAction(Runnable action) { - SIGNING_ACTIONS.add(action); - } - - public static void reset() { - lastServer = null; - current = ServerSafetyLevel.UNDEFINED; - ALLOW_CHAT_SIGNING.set(false); - UnsafeServerScreen.setHideThisSession(false); - - RESET_ACTIONS.forEach(Runnable::run); - RESET_ACTIONS.clear(); - SIGNING_ACTIONS.clear(); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/core/SigningMode.java b/src/main/java/com/aizistral/nochatreports/core/SigningMode.java deleted file mode 100644 index 32b6dba..0000000 --- a/src/main/java/com/aizistral/nochatreports/core/SigningMode.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.aizistral.nochatreports.core; - -import org.jetbrains.annotations.Nullable; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.SigningMode; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; - -/** - * Signing modes control how NCR behaves with respect to chat signing. - * These can be enabled globally or per-server. - * - * @author Aizistral - */ - -public enum SigningMode { - - /** - * Special value that indicates signing behavior should be controlled by overarching - * configuration. - */ - DEFAULT, - - /** - * Never sign any messages, ignore server demands. - */ - NEVER, - - /** - * Always sign messages, regardless of whether the server asked to. - */ - ALWAYS, - - /** - * Don't sign by default, if server refuses to accept unsigned message - show GUI - * prompt which allows the user to enable signing or ignore server warnings for one - * session. - */ - PROMPT, - - /** - * Don't sign by default, if server refuses to accept unsigned message - immediately - * enable signing for one session and re-send that message. - */ - ON_DEMAND, - - /** - * Same as {@link SigningMode#NEVER}, but additionally indicates that signing cannot be - * turned on at all for some reason (i.e. missing keys or offline account). - */ - NEVER_FORCED; - - public String getNameKey() { - return "gui.nochatreports.signing_mode." + this.name().toLowerCase(); - } - - public MutableComponent getName() { - if (this != DEFAULT) - return Component.translatable(this.getNameKey()); - else - return Component.translatable(this.getNameKey(), NCRConfig.getClient().defaultSigningMode().getName()); - } - - public String getTooltipKey() { - return "gui.nochatreports.signing_mode." + this.name().toLowerCase() + ".tooltip"; - } - - public MutableComponent getTooltip() { - return Component.translatable(this.getTooltipKey()); - } - - public SigningMode next() { - SigningMode result = null; - - if (this.ordinal() == values().length - 1) { - result = values()[0]; - } else { - result = values()[this.ordinal() + 1]; - } - - return result.isSelectable() ? result : result.next(); - } - - public SigningMode resolve() { - return switch(this) { - case DEFAULT -> NCRConfig.getClient().defaultSigningMode(); - case NEVER_FORCED -> NEVER; - default -> this; - }; - } - - public boolean isSelectable() { - return this != NEVER_FORCED; - } - - public boolean isSelectableGlobally() { - return this.isSelectable() && this != DEFAULT; - } - - public static SigningMode nullable(@Nullable SigningMode mode) { - return mode == null ? DEFAULT : mode; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java deleted file mode 100644 index 197f753..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.security.InvalidKeyException; - -import com.aizistral.nochatreports.encryption.AESCFB8Encryptor; -import com.aizistral.nochatreports.encryption.AESEncryption; - -public class AESCFB8Encryption extends AESEncryption { - - protected AESCFB8Encryption() { - super("CFB8", "NoPadding", true); - } - - @Override - public AESCFB8Encryptor getProcessor(String key) throws InvalidKeyException { - return new AESCFB8Encryptor(key); - } - - @Override - public AESCFB8Encryptor getRandomProcessor() { - try { - return this.getProcessor(this.getRandomKey()); - } catch (InvalidKeyException ex) { - throw new RuntimeException(ex); - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryptor.java deleted file mode 100644 index c4f045d..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryptor.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import net.minecraft.util.Tuple; - -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; - -import com.aizistral.nochatreports.encryption.AESCFB8Encryption; -import com.aizistral.nochatreports.encryption.AESEncryptor; -import com.aizistral.nochatreports.encryption.Encryption; - -import java.nio.ByteBuffer; -import java.security.InvalidKeyException; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Random; - -public class AESCFB8Encryptor extends AESEncryptor { - - protected AESCFB8Encryptor(String key) throws InvalidKeyException { - super(key, Encryption.AES_CFB8); - } - - protected AESCFB8Encryptor(SecretKey key, String mode, String padding, boolean iv) throws InvalidKeyException { - super(key, Encryption.AES_CFB8); - } - - @Override - protected Tuple generateIV() throws UnsupportedOperationException { - long nonce = RANDOM.nextLong(); - byte[] iv = new byte[16]; - new Random(nonce).nextBytes(iv); - return new Tuple<>(new IvParameterSpec(iv), ByteBuffer.allocate(8).putLong(nonce).array()); - } - - @Override - protected Tuple splitIV(byte[] message) throws UnsupportedOperationException { - ByteBuffer buffer = ByteBuffer.wrap(message); - int size = buffer.capacity(); - long nonce = buffer.getLong(); - byte[] encrypted = new byte[size - 8]; - buffer.get(encrypted); - byte[] iv = new byte[16]; - new Random(nonce).nextBytes(iv); - return new Tuple<>(new IvParameterSpec(iv), encrypted); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryption.java deleted file mode 100644 index 5c4216a..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryption.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.security.InvalidKeyException; - -import com.aizistral.nochatreports.encryption.AESECBEncryptor; -import com.aizistral.nochatreports.encryption.AESEncryption; - -public class AESECBEncryption extends AESEncryption { - - protected AESECBEncryption() { - super("ECB", "PKCS5Padding", false); - } - - @Override - public AESECBEncryptor getProcessor(String key) throws InvalidKeyException { - return new AESECBEncryptor(key); - } - - @Override - public AESECBEncryptor getRandomProcessor() { - try { - return this.getProcessor(this.getRandomKey()); - } catch (InvalidKeyException ex) { - throw new RuntimeException(ex); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryptor.java deleted file mode 100644 index d12051a..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryptor.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import net.minecraft.util.Tuple; - -import javax.crypto.SecretKey; - -import com.aizistral.nochatreports.encryption.AESECBEncryption; -import com.aizistral.nochatreports.encryption.AESEncryptor; -import com.aizistral.nochatreports.encryption.Encryption; - -import java.security.InvalidKeyException; -import java.security.spec.AlgorithmParameterSpec; - -public class AESECBEncryptor extends AESEncryptor { - - protected AESECBEncryptor(String key) throws InvalidKeyException { - super(key, Encryption.AES_ECB); - } - - protected AESECBEncryptor(SecretKey key, String mode, String padding, boolean iv) throws InvalidKeyException { - super(key, Encryption.AES_ECB); - } - - @Override - protected Tuple generateIV() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - protected Tuple splitIV(byte[] message) throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java deleted file mode 100644 index 84145d2..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import net.minecraft.util.StringUtil; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; - -import com.aizistral.nochatreports.encryption.Encryption; - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.util.Random; - -public abstract class AESEncryption extends Encryption { - private final String mode, padding; - private final boolean requiresIV; - - protected AESEncryption(String mode, String padding, boolean requiresIV) { - super("aes_" + mode.toLowerCase() + "_base64", "AES/" + mode + "+Base64"); - this.mode = mode; - this.padding = padding; - this.requiresIV = requiresIV; - } - - @Override - public String getRandomKey() { - try { - KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); - keyGenerator.init(128); - SecretKey key = keyGenerator.generateKey(); - - return BASE64_ENCODER.encodeToString(key.getEncoded()); - } catch (NoSuchAlgorithmException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public String getDefaultKey() { - return "blfrngArk3chG6wzncOZ5A=="; - } - - @Override - public boolean supportsPassphrases() { - return true; - } - - @Override - public String getPassphraseKey(String passphrase) { - try { - byte[] salt = new byte[16]; - new Random(1738389128127L).nextBytes(salt); - - KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt, 65536, 128); // AES-128 - SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - byte[] key = factory.generateSecret(spec).getEncoded(); - - return BASE64_ENCODER.encodeToString(new SecretKeySpec(key, "AES").getEncoded()); - } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public boolean validateKey(String key) { - if (StringUtil.isNullOrEmpty(key)) - return false; - - try { - this.getProcessor(key); - } catch (InvalidKeyException ex) { - return false; - } - - return true; - } - - public String getMode() { - return this.mode; - } - - public String getPadding() { - return this.padding; - } - - public boolean requiresIV() { - return this.requiresIV; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java deleted file mode 100644 index cfde341..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import net.minecraft.util.Tuple; - -import javax.crypto.*; -import javax.crypto.spec.SecretKeySpec; - -import com.aizistral.nochatreports.encryption.AESEncryption; -import com.aizistral.nochatreports.encryption.Encryptor; - -import java.nio.ByteBuffer; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.spec.AlgorithmParameterSpec; - -import static javax.crypto.Cipher.DECRYPT_MODE; -import static javax.crypto.Cipher.ENCRYPT_MODE; - -public abstract class AESEncryptor extends Encryptor { - private final T encryption; - private final SecretKey key; - private final Cipher encryptor, decryptor; - private final boolean useIV; - - protected AESEncryptor(String key, T encryption) throws InvalidKeyException { - this(new SecretKeySpec(decodeBinaryKey(key), "AES"), encryption); - } - - protected AESEncryptor(SecretKey key, T encryption) throws InvalidKeyException { - this.encryption = encryption; - this.useIV = encryption.requiresIV(); - String mode = encryption.getMode(); - String padding = encryption.getPadding(); - - try { - this.key = key; - - Cipher encryptor = Cipher.getInstance(this.key.getAlgorithm() + "/" + mode + "/" + padding); - if (this.useIV) { - encryptor.init(ENCRYPT_MODE, this.key, this.generateIV().getA()); - } else { - encryptor.init(ENCRYPT_MODE, this.key); - - } - this.encryptor = encryptor; - - Cipher decryptor = Cipher.getInstance(this.key.getAlgorithm() + "/" + mode + "/" + padding); - if (this.useIV) { - decryptor.init(DECRYPT_MODE, this.key, this.generateIV().getA()); - } else { - decryptor.init(DECRYPT_MODE, this.key); - } - this.decryptor = decryptor; - } catch (NoSuchAlgorithmException | NoSuchPaddingException ex) { - throw new RuntimeException(ex); - } catch (InvalidAlgorithmParameterException ex) { - throw new InvalidKeyException(ex); - } - } - - @Override - public String encrypt(String message) { - try { - if (this.useIV) { - var tuple = this.generateIV(); - - this.encryptor.init(ENCRYPT_MODE, this.key, tuple.getA()); - byte[] encrypted = this.encryptor.doFinal(toBytes(message)); - - return encodeBase64R(ByteBuffer.allocate(encrypted.length + tuple.getB().length).put(tuple.getB()) - .put(encrypted).array()); - } else - return encodeBase64R(this.encryptor.doFinal(toBytes(message))); - } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public String decrypt(String message) { - try { - if (this.useIV) { - var tuple = this.splitIV(decodeBase64RBytes(message)); - - this.decryptor.init(DECRYPT_MODE, this.key, tuple.getA()); - return fromBytes(this.decryptor.doFinal(tuple.getB())); - } else - return fromBytes(this.decryptor.doFinal(decodeBase64RBytes(message))); - } catch (AEADBadTagException ex) { - return "???"; - } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public String getKey() { - return encodeBinaryKey(this.key.getEncoded()); - } - - @Override - public T getAlgorithm() { - return this.encryption; - } - - protected abstract Tuple generateIV() throws UnsupportedOperationException; - - protected abstract Tuple splitIV(byte[] message) throws UnsupportedOperationException; - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryption.java deleted file mode 100644 index edb5eb4..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryption.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.security.InvalidKeyException; - -import com.aizistral.nochatreports.encryption.AESEncryption; -import com.aizistral.nochatreports.encryption.AESGCMEncryptor; - -public class AESGCMEncryption extends AESEncryption { - - protected AESGCMEncryption() { - super("GCM", "NoPadding", true); - } - - @Override - public AESGCMEncryptor getProcessor(String key) throws InvalidKeyException { - return new AESGCMEncryptor(key); - } - - @Override - public AESGCMEncryptor getRandomProcessor() { - try { - return this.getProcessor(this.getRandomKey()); - } catch (InvalidKeyException ex) { - throw new RuntimeException(ex); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryptor.java deleted file mode 100644 index c2f5450..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryptor.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import net.minecraft.util.Tuple; - -import javax.crypto.SecretKey; -import javax.crypto.spec.GCMParameterSpec; - -import com.aizistral.nochatreports.encryption.AESEncryptor; -import com.aizistral.nochatreports.encryption.AESGCMEncryption; -import com.aizistral.nochatreports.encryption.Encryption; - -import java.nio.ByteBuffer; -import java.security.InvalidKeyException; -import java.security.spec.AlgorithmParameterSpec; - -public class AESGCMEncryptor extends AESEncryptor { - - protected AESGCMEncryptor(String key) throws InvalidKeyException { - super(key, Encryption.AES_GCM); - } - - protected AESGCMEncryptor(SecretKey key) throws InvalidKeyException { - super(key, Encryption.AES_GCM); - } - - @Override - protected Tuple generateIV() throws UnsupportedOperationException { - byte[] iv = new byte[12]; - RANDOM.nextBytes(iv); - return new Tuple<>(new GCMParameterSpec(96, iv), iv); - } - - @Override - protected Tuple splitIV(byte[] message) throws UnsupportedOperationException { - byte[] iv = new byte[12]; - byte[] msg = new byte[message.length - 12]; - ByteBuffer.wrap(message).get(iv).get(msg); - return new Tuple<>(new GCMParameterSpec(96, iv), msg); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryption.java deleted file mode 100644 index 5ea07d7..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryption.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.security.InvalidKeyException; -import java.security.SecureRandom; - -import com.aizistral.nochatreports.encryption.CaesarEncryptor; -import com.aizistral.nochatreports.encryption.Encryption; - -public class CaesarEncryption extends Encryption { - - protected CaesarEncryption() { - super("caesar", "Caesar"); - } - - @Override - public String getRandomKey() { - return String.valueOf(1 + new SecureRandom().nextInt(1024)); - } - - @Override - public String getDefaultKey() { - return "3"; - } - - @Override - public boolean supportsPassphrases() { - return false; - } - - @Override - public String getPassphraseKey(String passphrase) throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public boolean validateKey(String key) { - try { - int value = Integer.valueOf(key); - return value > 0 && value < 1025; - } catch (NumberFormatException ex) { - return false; - } - } - - @Override - public CaesarEncryptor getProcessor(String key) throws InvalidKeyException { - return new CaesarEncryptor(key); - } - - @Override - public CaesarEncryptor getRandomProcessor() { - try { - return this.getProcessor(this.getRandomKey()); - } catch (InvalidKeyException ex) { - throw new RuntimeException(ex); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryptor.java deleted file mode 100644 index ada6a66..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryptor.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.security.InvalidKeyException; - -import com.aizistral.nochatreports.encryption.CaesarEncryption; -import com.aizistral.nochatreports.encryption.Encryption; -import com.aizistral.nochatreports.encryption.Encryptor; - -public class CaesarEncryptor extends Encryptor { - private static final char PARAGRAPH = '\u00a7', PARAGRAPH_PLACEHOLDER = '\uffef', - DELETE = '\u007f', DELETE_PLACEHOLDER = '\ufff0'; - private final int shift; - - protected CaesarEncryptor(int shift) throws InvalidKeyException { - if (!Encryption.CAESAR.validateKey(String.valueOf(shift))) - throw new InvalidKeyException(); - this.shift = shift; - } - - protected CaesarEncryptor(String key) throws InvalidKeyException { - this.shift = fromString(key); - } - - @Override - public String encrypt(String message) { - char[] chars = ensureUTF8(message).toCharArray(); - - for (int i = 0; i < chars.length; i++) { - chars[i] = (char) (chars[i] + this.shift); - - if (chars[i] == PARAGRAPH) { - chars[i] = PARAGRAPH_PLACEHOLDER; - } else if (chars[i] == DELETE) { - chars[i] = DELETE_PLACEHOLDER; - } - } - - return new String(chars); - } - - @Override - public String decrypt(String message) { - char[] chars = ensureUTF8(message).toCharArray(); - - for (int i = 0; i < chars.length; i++) { - if (chars[i] == PARAGRAPH_PLACEHOLDER) { - chars[i] = PARAGRAPH; - } else if (chars[i] == DELETE_PLACEHOLDER) { - chars[i] = DELETE; - } - - chars[i] = (char) (chars[i] - this.shift); - } - - return new String(chars); - } - - @Override - public CaesarEncryption getAlgorithm() { - return Encryption.CAESAR; - } - - @Override - public String getKey() { - return String.valueOf(this.shift); - } - - private static int fromString(String key) throws InvalidKeyException { - if (!Encryption.CAESAR.validateKey(key)) - throw new InvalidKeyException(key); - return Integer.valueOf(key); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java b/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java deleted file mode 100644 index e9e2248..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.security.InvalidKeyException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Collections; -import java.util.List; - -import com.aizistral.nochatreports.encryption.AESCFB8Encryption; -import com.aizistral.nochatreports.encryption.AESECBEncryption; -import com.aizistral.nochatreports.encryption.AESGCMEncryption; -import com.aizistral.nochatreports.encryption.CaesarEncryption; -import com.aizistral.nochatreports.encryption.Encryption; -import com.aizistral.nochatreports.encryption.Encryptor; - -public abstract class Encryption { - private static final List REGISTERED = new ArrayList<>(); - protected static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); - protected static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); - - public static final AESCFB8Encryption AES_CFB8 = new AESCFB8Encryption(); - public static final AESGCMEncryption AES_GCM = new AESGCMEncryption(); - public static final AESECBEncryption AES_ECB = new AESECBEncryption(); - public static final CaesarEncryption CAESAR = new CaesarEncryption(); - - private final String id, name; - - protected Encryption(String id, String name) { - this.id = id; - this.name = name; - - if (REGISTERED.stream().filter(e -> e.getID().equals(id) || e.getName().equals(name)) - .findAny().isPresent()) - throw new IllegalStateException("Duplicate encryption algorithm registered! ID: " + this.getID() + - ", Name: " + this.getName()); - - REGISTERED.add(this); - } - - public String getID() { - return this.id; - } - - public String getName() { - return this.name; - } - - public abstract String getRandomKey(); - - public abstract String getDefaultKey(); - - public abstract boolean supportsPassphrases(); - - public abstract String getPassphraseKey(String passphrase) throws UnsupportedOperationException; - - public abstract boolean validateKey(String key); - - public abstract Encryptor getProcessor(String key) throws InvalidKeyException; - - public abstract Encryptor getRandomProcessor(); - - public static List getRegistered() { - return Collections.unmodifiableList(REGISTERED); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/Encryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/Encryptor.java deleted file mode 100644 index 346db89..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/Encryptor.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import it.unimi.dsi.fastutil.chars.Char2CharArrayMap; -import it.unimi.dsi.fastutil.chars.Char2CharMap; -import it.unimi.dsi.fastutil.chars.Char2CharMaps; - -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.SecureRandom; -import java.util.Arrays; - -import com.aizistral.nochatreports.encryption.Encryption; - -public abstract class Encryptor { - protected static final SecureRandom RANDOM = new SecureRandom(); - protected static final Char2CharMap BASE64R_SHIFTS = createBase64RShifts(); - protected static final Char2CharMap BASE64R_SHIFTS_REVERSE = createBase64RShiftsReverse(); - - protected Encryptor() { - // NO-OP - } - - public abstract String encrypt(String message); - - public abstract String decrypt(String message); - - public abstract T getAlgorithm(); - - public abstract String getKey(); - - protected static String shiftBase64R(String string) { - char[] chars = ensureUTF8(string).toCharArray(); - - for (int i = 0; i < chars.length; i++) { - chars[i] = BASE64R_SHIFTS.get(chars[i]); - } - - return new String(chars); - } - - protected static String unshiftBase64R(String string) { - char[] chars = ensureUTF8(string).toCharArray(); - - for (int i = 0; i < chars.length; i++) { - chars[i] = BASE64R_SHIFTS_REVERSE.get(chars[i]); - } - - return new String(chars); - } - - protected static byte[] toBytes(String string) { - return string.getBytes(StandardCharsets.UTF_8); - } - - protected static String fromBytes(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - - protected static String ensureUTF8(String string) { - return fromBytes(toBytes(string)); - } - - protected static String encodeBase64R(String string) { - return encodeBase64R(toBytes(string)); - } - - protected static String encodeBase64R(byte[] bytes) { - return shiftBase64R(fromBytes(Encryption.BASE64_ENCODER.encode(bytes))); - } - - protected static byte[] encodeBase64RBytes(String string) { - return toBytes(encodeBase64R(toBytes(string))); - } - - protected static String decodeBase64R(String string) { - return fromBytes(decodeBase64RBytes(string)); - } - - protected static byte[] decodeBase64RBytes(String string) { - return Encryption.BASE64_DECODER.decode(toBytes(unshiftBase64R(string))); - } - - protected static String encodeBinaryKey(byte[] key) { - return fromBytes(Encryption.BASE64_ENCODER.encode(key)); - } - - protected static byte[] decodeBinaryKey(String key) throws InvalidKeyException { - try { - return Encryption.BASE64_DECODER.decode(toBytes(key)); - } catch (Exception ex) { - throw new InvalidKeyException(ex); - } - } - - protected static byte[] mergeBytes(byte[] array1, byte[] array2) { - byte[] result = Arrays.copyOf(array1, array1.length + array2.length); - System.arraycopy(array2, 0, result, array1.length, array2.length); - return result; - } - - private static Char2CharMap createBase64RShiftsReverse() { - Char2CharMap map = createBase64RShifts(); - Char2CharMap reverse = new Char2CharArrayMap(64); - - for (char ch : map.keySet()) { - reverse.put(map.get(ch), ch); - } - - return Char2CharMaps.unmodifiable(reverse); - } - - private static Char2CharMap createBase64RShifts() { - Char2CharMap map = new Char2CharArrayMap(64); - - map.put('A', '!'); - map.put('B', '"'); - map.put('C', '#'); - map.put('D', '$'); - map.put('E', '%'); - map.put('F', '¼'); - map.put('G', '\''); - map.put('H', '('); - map.put('I', ')'); - map.put('J', ','); - map.put('K', '-'); - map.put('L', '.'); - map.put('M', ':'); - map.put('N', ';'); - map.put('O', '<'); - map.put('P', '='); - map.put('Q', '>'); - map.put('R', '?'); - map.put('S', '@'); - map.put('T', '['); - map.put('U', '\\'); - map.put('V', ']'); - map.put('W', '^'); - map.put('X', '_'); - map.put('Y', '`'); - map.put('Z', '{'); - map.put('a', '|'); - map.put('b', '}'); - map.put('c', '~'); - map.put('d', '¡'); - map.put('e', '¢'); - map.put('f', '£'); - map.put('g', '¤'); - map.put('h', '¥'); - map.put('i', '¦'); - map.put('j', '¨'); - map.put('k', '©'); - map.put('l', 'ª'); - map.put('m', '«'); - map.put('n', '¬'); - map.put('o', '®'); - map.put('p', '¯'); - map.put('q', '°'); - map.put('r', '±'); - map.put('s', '²'); - map.put('t', '³'); - map.put('u', 'µ'); - map.put('v', '¶'); - map.put('w', '·'); - map.put('x', '×'); - map.put('y', '¹'); - map.put('z', 'º'); - map.put('0', '0'); - map.put('1', '1'); - map.put('2', '2'); - map.put('3', '3'); - map.put('4', '4'); - map.put('5', '5'); - map.put('6', '6'); - map.put('7', '7'); - map.put('8', '8'); - map.put('9', '9'); - map.put('+', '+'); - map.put('/', '»'); - map.put('=', '¿'); - - return Char2CharMaps.unmodifiable(map); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/fabric/NoChatReports.java b/src/main/java/com/aizistral/nochatreports/fabric/NoChatReports.java new file mode 100644 index 0000000..2092a78 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/fabric/NoChatReports.java @@ -0,0 +1,35 @@ +package com.aizistral.nochatreports.fabric; + +import java.nio.file.Path; + +import com.aizistral.nochatreports.common.NCRCore; +import com.aizistral.nochatreports.common.platform.PlatformProvider; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.loader.api.FabricLoader; + +public class NoChatReports implements ModInitializer, PlatformProvider { + + @Override + public void onInitialize() { + NCRCore.awaken(this); + } + + @Override + public EnvType getEnvironment() { + return FabricLoader.getInstance().getEnvironmentType(); + } + + @Override + public Path getMinecraftDir() { + return FabricLoader.getInstance().getGameDir(); + } + + @Override + public Path getConfigDir() { + return FabricLoader.getInstance().getConfigDir(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/fabric/NoChatReportsClient.java b/src/main/java/com/aizistral/nochatreports/fabric/NoChatReportsClient.java new file mode 100644 index 0000000..2ae4236 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/fabric/NoChatReportsClient.java @@ -0,0 +1,22 @@ +package com.aizistral.nochatreports.fabric; + +import com.aizistral.nochatreports.common.platform.events.ClientEvents; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; + +@Environment(EnvType.CLIENT) +public class NoChatReportsClient implements ClientModInitializer { + + @Override + public void onInitializeClient() { + ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> + ClientEvents.PLAY_READY.invoker().handle(handler, client)); + + ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> + ClientEvents.DISCONNECT.invoker().handle(client)); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/fabric/mixins/MixinMinecraft.java b/src/main/java/com/aizistral/nochatreports/fabric/mixins/MixinMinecraft.java new file mode 100644 index 0000000..aa573c2 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/fabric/mixins/MixinMinecraft.java @@ -0,0 +1,20 @@ +package com.aizistral.nochatreports.fabric.mixins; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.aizistral.nochatreports.common.NCRCore; + +import net.minecraft.client.Minecraft; + +@Mixin(Minecraft.class) +public class MixinMinecraft { + + @Inject(method = "run", at = @At("HEAD")) + private void onRun(CallbackInfo info) { + NCRCore.LOGGER.info("Game entered main loop!"); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/gui/AdaptiveWarningScreen.java b/src/main/java/com/aizistral/nochatreports/gui/AdaptiveWarningScreen.java deleted file mode 100644 index 898b1f5..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/AdaptiveWarningScreen.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import org.jetbrains.annotations.Nullable; - -import com.mojang.blaze3d.vertex.PoseStack; - -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.Checkbox; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.screens.ConfirmLinkScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -public abstract class AdaptiveWarningScreen extends Screen { - private final Component title; - private final Component content; - private final Component narration; - @Nullable - protected final Screen previous; - @Nullable - private final Component check; - @Nullable - protected Checkbox stopShowing = null; - protected MultiLineLabel message = MultiLineLabel.EMPTY; - - public AdaptiveWarningScreen(Component title, Component content, @Nullable Component check, - @Nullable Screen previous) { - super(title); - this.title = title; - this.content = content; - this.check = check; - this.narration = this.title.copy().append("\n").append(this.content); - this.previous = previous; - } - - @Override - protected void init() { - this.clearWidgets(); - super.init(); - this.message = MultiLineLabel.create(this.font, this.content, this.width - (this.hugeGUI() ? 65 : 100)); - int i = (this.message.getLineCount() + 1) * this.getLineHeight(); - if (this.check != null) { - int checkY = this.hugeGUI() ? 27 : 76; - int j = this.font.width(this.check); - - if (this.check != null) { - this.stopShowing = new Checkbox(this.width / 2 - j / 2 - 8, checkY + i, j + 24, 20, this.check, false); - this.addRenderableWidget(this.stopShowing); - } - } - this.initButtons(i + (this.hugeGUI() ? 55 : 100)); - } - - protected abstract void initButtons(int y); - - @Override - public void render(PoseStack poseStack, int i, int j, float f) { - this.renderBackground(poseStack); - this.renderTitle(poseStack); - int k = this.width / 2 - this.message.getWidth() / 2; - this.message.renderLeftAligned(poseStack, k, this.hugeGUI() ? 35 : 70, this.getLineHeight(), 0xFFFFFF); - super.render(poseStack, i, j, f); - } - - private void renderTitle(PoseStack poseStack) { - drawString(poseStack, this.font, this.title, 25, this.hugeGUI() ? 15 : 30, 0xFFFFFF); - } - - private boolean hugeGUI() { - return this.height <= 1080 / 4; - } - - protected int getLineHeight() { - if (this.hugeGUI()) - return (int) (this.minecraft.font.lineHeight * 1.5) + 1; - else - return this.minecraft.font.lineHeight * 2; - } - -} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/gui/AdvancedImageButton.java b/src/main/java/com/aizistral/nochatreports/gui/AdvancedImageButton.java deleted file mode 100644 index 25f6d54..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/AdvancedImageButton.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.gui.AdvancedTooltip; -import com.mojang.blaze3d.vertex.PoseStack; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.components.ImageButton; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; - -@Environment(EnvType.CLIENT) -public class AdvancedImageButton extends ImageButton { - protected final Screen parent; - - public AdvancedImageButton(int x, int y, int xSize, int ySize, int xTexStart, int yTexStart, int yStateDiff, - ResourceLocation texture, int textureWidth, int textureHeight, OnPress onPress, Component name, - Screen parent) { - super(x, y, xSize, ySize, xTexStart, yTexStart, yStateDiff, texture, textureWidth, textureHeight, onPress, name); - this.parent = parent; - } - - @Override - public void updateTooltip() { - if (this.tooltip instanceof AdvancedTooltip tooltip && tooltip.hasCustomRender()) - return; - - super.updateTooltip(); - } - - @Override - public void renderButton(PoseStack poseStack, int mouseX, int mouseY, float delta) { - super.renderButton(poseStack, mouseX, mouseY, delta); - - if (this.isHovered) - if (this.tooltip instanceof AdvancedTooltip tooltip && tooltip.hasCustomRender()) { - tooltip.doCustomRender(this.parent, poseStack, mouseX, mouseY); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/AdvancedTooltip.java b/src/main/java/com/aizistral/nochatreports/gui/AdvancedTooltip.java deleted file mode 100644 index 0dddb9c..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/AdvancedTooltip.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.gui.AdvancedTooltip; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.network.chat.Component; -import net.minecraft.util.FormattedCharSequence; - -import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; - -import java.util.List; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -@Environment(EnvType.CLIENT) -public class AdvancedTooltip extends Tooltip { - @Nullable - protected Supplier supplier; - protected int maxWidth = MAX_WIDTH; - protected boolean renderWithoutGap = false; - - public AdvancedTooltip(Component message, @Nullable Component narration) { - super(message, narration); - } - - public AdvancedTooltip(Component message) { - this(message, message); - } - - public AdvancedTooltip(Supplier message) { - this(message.get()); - this.supplier = message; - } - - public AdvancedTooltip setMaxWidth(int maxWidth) { - this.maxWidth = maxWidth; - return this; - } - - public AdvancedTooltip setRenderWithoutGap(boolean render) { - this.renderWithoutGap = render; - return this; - } - - public Component getMessage() { - return this.supplier != null ? this.supplier.get() : this.message; - } - - @Override - public List toCharSequence(Minecraft minecraft) { - if (this.supplier == null) { - if (this.cachedTooltip == null) { - this.cachedTooltip = splitTooltip(minecraft, this.getMessage(), this.maxWidth); - } - return this.cachedTooltip; - } else - return splitTooltip(minecraft, this.getMessage(), this.maxWidth); - } - - public boolean hasCustomRender() { - return this.renderWithoutGap; - } - - public void doCustomRender(Screen screen, PoseStack poseStack, int x, int y) { - if (this.renderWithoutGap) { - this.renderTooltipNoGap(screen, poseStack, splitTooltip(screen.minecraft, this.getMessage(), this.maxWidth), x, y); - } else - throw new UnsupportedOperationException("This tooltip doesn't support custom render!"); - } - - public static List splitTooltip(Minecraft minecraft, Component component, int maxWidth) { - return minecraft.font.split(component, maxWidth); - } - - protected void renderTooltipNoGap(Screen screen, PoseStack poseStack, List list, int x, int y) { - this.renderTooltipInternalNoGap(screen, poseStack, list.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), x, y); - } - - protected void renderTooltipInternalNoGap(Screen screen, PoseStack poseStack, List list, int x, int y) { - ClientTooltipComponent clientTooltipComponent2; - int v; - int m; - if (list.isEmpty()) - return; - int k = 0; - int l = list.size() == 1 ? -2 : -2; - for (ClientTooltipComponent clientTooltipComponent : list) { - m = clientTooltipComponent.getWidth(screen.font); - if (m > k) { - k = m; - } - l += clientTooltipComponent.getHeight(); - } - int n = x + 12; - int o = y - 12; - m = k; - int p = l; - if (n + k > screen.width) { - n -= 28 + k; - } - if (o + p + 6 > screen.height) { - o = screen.height - p - 6; - } - if (y - p - 8 < 0) { - o = y + 8; - } - poseStack.pushPose(); - int q = -267386864; - int r = 0x505000FF; - int s = 1344798847; - int t = 400; - float f = screen.itemRenderer.blitOffset; - screen.itemRenderer.blitOffset = 400.0f; - Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tesselator.getBuilder(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - Matrix4f matrix4f = poseStack.last().pose(); - fillGradient(matrix4f, bufferBuilder, n - 3, o - 4, n + m + 3, o - 3, 400, -267386864, -267386864); - fillGradient(matrix4f, bufferBuilder, n - 3, o + p + 3, n + m + 3, o + p + 4, 400, -267386864, -267386864); - fillGradient(matrix4f, bufferBuilder, n - 3, o - 3, n + m + 3, o + p + 3, 400, -267386864, -267386864); - fillGradient(matrix4f, bufferBuilder, n - 4, o - 3, n - 3, o + p + 3, 400, -267386864, -267386864); - fillGradient(matrix4f, bufferBuilder, n + m + 3, o - 3, n + m + 4, o + p + 3, 400, -267386864, -267386864); - fillGradient(matrix4f, bufferBuilder, n - 3, o - 3 + 1, n - 3 + 1, o + p + 3 - 1, 400, 0x505000FF, 1344798847); - fillGradient(matrix4f, bufferBuilder, n + m + 2, o - 3 + 1, n + m + 3, o + p + 3 - 1, 400, 0x505000FF, 1344798847); - fillGradient(matrix4f, bufferBuilder, n - 3, o - 3, n + m + 3, o - 3 + 1, 400, 0x505000FF, 0x505000FF); - fillGradient(matrix4f, bufferBuilder, n - 3, o + p + 2, n + m + 3, o + p + 3, 400, 1344798847, 1344798847); - RenderSystem.enableDepthTest(); - RenderSystem.disableTexture(); - RenderSystem.enableBlend(); - RenderSystem.defaultBlendFunc(); - BufferUploader.drawWithShader(bufferBuilder.end()); - RenderSystem.disableBlend(); - RenderSystem.enableTexture(); - MultiBufferSource.BufferSource bufferSource = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder()); - poseStack.translate(0.0, 0.0, 400.0); - int u = o; - for (v = 0; v < list.size(); ++v) { - clientTooltipComponent2 = list.get(v); - clientTooltipComponent2.renderText(screen.font, n, u, matrix4f, bufferSource); - u += clientTooltipComponent2.getHeight() /*+ (v == 0 ? 2 : 0)*/; - } - bufferSource.endBatch(); - poseStack.popPose(); - u = o; - for (v = 0; v < list.size(); ++v) { - clientTooltipComponent2 = list.get(v); - clientTooltipComponent2.renderImage(screen.font, n, u, poseStack, screen.itemRenderer, 400); - u += clientTooltipComponent2.getHeight() + (v == 0 ? 2 : 0); - } - screen.itemRenderer.blitOffset = f; - } - - protected static void fillGradient(Matrix4f matrix4f, BufferBuilder bufferBuilder, int i, int j, int k, int l, int m, int n, int o) { - float f = (n >> 24 & 0xFF) / 255.0f; - float g = (n >> 16 & 0xFF) / 255.0f; - float h = (n >> 8 & 0xFF) / 255.0f; - float p = (n & 0xFF) / 255.0f; - float q = (o >> 24 & 0xFF) / 255.0f; - float r = (o >> 16 & 0xFF) / 255.0f; - float s = (o >> 8 & 0xFF) / 255.0f; - float t = (o & 0xFF) / 255.0f; - bufferBuilder.vertex(matrix4f, k, j, m).color(g, h, p, f).endVertex(); - bufferBuilder.vertex(matrix4f, i, j, m).color(g, h, p, f).endVertex(); - bufferBuilder.vertex(matrix4f, i, l, m).color(r, s, t, q).endVertex(); - bufferBuilder.vertex(matrix4f, k, l, m).color(r, s, t, q).endVertex(); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java b/src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java deleted file mode 100644 index 9303c18..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.gui.AdvancedImageButton; -import com.aizistral.nochatreports.gui.EncryptionConfigScreen; -import com.aizistral.nochatreports.gui.EncryptionWarningScreen; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.ImageButton; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; - -public class EncryptionButton extends AdvancedImageButton { - - public EncryptionButton(int x, int y, int xSize, int ySize, int xTexStart, int yTexStart, int yStateDiff, - ResourceLocation texture, int textureWidth, int textureHeight, OnPress onPress, Component name, Screen parent) { - super(x, y, xSize, ySize, xTexStart, yTexStart, yStateDiff, texture, textureWidth, textureHeight, onPress, name, parent); - } - - @Override - public boolean mouseClicked(double x, double y, int i) { - if (!this.active || !this.visible) - return false; - - if (i == 1 && this.clicked(x, y)) { - this.playDownSound(Minecraft.getInstance().getSoundManager()); - this.openEncryptionConfig(); - return true; - } - - return super.mouseClicked(x, y, i); - } - - public void openEncryptionConfig() { - if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled() - && !NCRConfig.getEncryption().isEnabledAndValid()) { - Minecraft.getInstance().setScreen(new EncryptionWarningScreen(this.parent)); - } else { - Minecraft.getInstance().setScreen(new EncryptionConfigScreen(this.parent)); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java b/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java deleted file mode 100644 index 89fa174..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java +++ /dev/null @@ -1,280 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.config.NCRConfigEncryption; -import com.aizistral.nochatreports.encryption.Encryption; -import com.aizistral.nochatreports.gui.AdvancedImageButton; -import com.aizistral.nochatreports.gui.AdvancedTooltip; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.components.*; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.AnvilScreen; -import net.minecraft.client.gui.screens.inventory.CommandBlockEditScreen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.StringUtil; -import org.spongepowered.include.com.google.common.base.Objects; - -@Environment(EnvType.CLIENT) -public class EncryptionConfigScreen extends Screen { - private static final ResourceLocation ENCRYPTION_ICONS = new ResourceLocation("nochatreports", "textures/gui/encryption_gui_icons.png"); - private static final Component HEADER = Component.translatable("gui.nochatreports.encryption_config.header"); - private static final Component KEY_DESC = Component.translatable("gui.nochatreports.encryption_config.key_desc"); - private static final Component PASS_DESC = Component.translatable("gui.nochatreports.encryption_config.passphrase_desc"); - private static final Component VALIDATION_OK = Component.translatable("gui.nochatreports.encryption_config.validation_ok"); - private static final Component VALIDATION_FAILED = Component.translatable("gui.nochatreports.encryption_config.validation_failed"); - private static final Component DICE_TOOLTIP = Component.translatable("gui.nochatreports.encryption_config.dice_tooltip"); - private static final Component PASS_NOT_ALLOWED = Component.translatable("gui.nochatreports.encryption_config.pass_not_allowed"); - private static final Component ENCRYPT_PUBLIC = Component.translatable("gui.nochatreports.encryption_config.encrypt_public"); - - private static final int FIELDS_Y_START = 45; - private final Screen previous; - private CustomEditBox keyField, passField; - private ImageButton validationIcon; - private CycleButton algorithmButton; - private MultiLineLabel keyDesc = MultiLineLabel.EMPTY, passDesc = MultiLineLabel.EMPTY; - protected Checkbox encryptPublicCheck; - private boolean settingPassKey = false; - - public EncryptionConfigScreen(Screen previous) { - super(CommonComponents.EMPTY); - this.previous = previous; - } - - private NCRConfigEncryption getConfig() { - return NCRConfig.getEncryption(); - } - - @Override - protected void init() { - this.clearWidgets(); - super.init(); - - int w = (int) (this.width * (this.hugeGUI() ? 0.9 : 0.7)); - - this.keyDesc = MultiLineLabel.create(this.font, KEY_DESC, w - 5); - int keyDescSpace = (this.keyDesc.getLineCount() + 1) * this.getLineHeight(); - - this.passDesc = MultiLineLabel.create(this.font, PASS_DESC, w - 5); - int passDescSpace = (this.passDesc.getLineCount() + 1) * this.getLineHeight(); - - w -= 52; - - this.keyField = new CustomEditBox(this.font, (this.width - w)/2 - 2, (this.hugeGUI() ? 25 : FIELDS_Y_START) + keyDescSpace - 15, - w, 18, CommonComponents.EMPTY); - this.keyField.setMaxLength(512); - this.keyField.setResponder(this::onKeyUpdate); - this.addWidget(this.keyField); - - var button = new AdvancedImageButton(this.keyField.getX() + this.keyField.getWidth() - 15, this.keyField.getY() + 3, 12, - 12, 0, 0, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, Component.empty(), this); - button.setTooltip(new AdvancedTooltip(() -> this.validationIcon != null && - this.validationIcon.yTexStart == 0 ? VALIDATION_OK : VALIDATION_FAILED).setMaxWidth(250)); - button.active = false; - button.visible = true; - - this.addRenderableOnly(this.validationIcon = button); - - button = new AdvancedImageButton(this.keyField.getX() - 22, this.keyField.getY() - 0, 18, 18, 0, - 28, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, Component.empty(), this); - button.active = false; - button.visible = true; - - this.addRenderableOnly(button); - - button = new AdvancedImageButton(this.keyField.getX() + this.keyField.getWidth() + 4, this.keyField.getY() - 1, 23, 20, 41, - 24, 20, ENCRYPTION_ICONS, 64, 64, btn -> { - this.unfocusFields(); - this.keyField.setValue(this.algorithmButton.getValue().getRandomKey()); - }, Component.empty(), this); - button.setTooltip(new AdvancedTooltip(DICE_TOOLTIP).setMaxWidth(250)); - button.active = true; - button.visible = true; - - this.addRenderableWidget(button); - - w += 25; - - this.passField = new CustomEditBox(this.font, (this.width - w)/2 + 11, this.keyField.getY() + - this.keyField.getHeight() + passDescSpace + (this.hugeGUI() ? -3 : 13), w, 18, CommonComponents.EMPTY); - this.passField.setMaxLength(512); - this.passField.setResponder(this::onPassphraseUpdate); - this.addWidget(this.passField); - - button = new AdvancedImageButton(this.passField.getX() - 22, this.passField.getY() - 0, 18, 18, 0, - 46, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, Component.empty(), this); - button.active = false; - button.visible = true; - - this.addRenderableOnly(button); - - int checkWidth = this.font.width(ENCRYPT_PUBLIC); - this.encryptPublicCheck = new Checkbox(this.width / 2 - checkWidth / 2 - 8, this.passField.getY() + 24, checkWidth + 24, 20, - ENCRYPT_PUBLIC, NCRConfig.getEncryption().shouldEncryptPublic()); - this.addRenderableWidget(this.encryptPublicCheck); - - this.addRenderableWidget(Button.builder(CommonComponents.GUI_DONE, btn -> { - this.onDone(); - this.onClose(); - }).pos(this.width / 2 + 4, this.passField.getY() + 48).size(219, 20).build()); - - CycleButton cycle = CycleButton.builder(value -> { - return Component.translatable("gui.nochatreports.encryption_config.algorithm", - Component.translatable("algorithm.nochatreports." + value.getID() + ".name")); - }).withValues(Encryption.getRegistered()).displayOnlyValue().withInitialValue(this.getConfig() - .getAlgorithm()).withTooltip(value -> new AdvancedTooltip(Component.translatable( - "algorithm.nochatreports." + value.getID())).setMaxWidth(250)) - .create(this.width / 2 - 4 - 218, this.passField.getY() + 48, 218, 20, CommonComponents.EMPTY, - (cycleButton, value) -> { - this.unfocusFields(); - this.onAlgorithmUpdate(value); - }); - - this.addRenderableWidget(this.algorithmButton = cycle); - - this.onAlgorithmUpdate(this.algorithmButton.getValue()); - - if (!StringUtil.isNullOrEmpty(this.getConfig().getEncryptionPassphrase())) { - this.passField.setValue(this.getConfig().getEncryptionPassphrase()); - } else if (!StringUtil.isNullOrEmpty(this.getConfig().getEncryptionKey())) { - if (!Objects.equal(this.getConfig().getEncryptionKey(), this.algorithmButton.getValue() - .getDefaultKey())) { - this.keyField.setValue(this.getConfig().getEncryptionKey()); - } else { - this.keyField.setValue(""); - } - } - } - - @Override - public void render(PoseStack poseStack, int i, int j, float f) { - if (!this.passField.isActive()) { - if (this.passField.isFocused()) { - this.passField.setFocused(false); - } - this.passField.setEditable(false); - } - - this.renderBackground(poseStack); - Screen.drawCenteredString(poseStack, this.font, HEADER, this.width / 2, this.hugeGUI() ? 8 : 16, 0xFFFFFF); - - this.keyDesc.renderLeftAligned(poseStack, this.keyField.getX() - 20, (this.hugeGUI() ? 25 : FIELDS_Y_START), this.getLineHeight(), 0xFFFFFF); - - this.keyField.render(poseStack, i, j, f); - - this.passDesc.renderLeftAligned(poseStack, this.passField.getX() - 20, this.keyField.getY() + this.keyField.getHeight() + (this.hugeGUI() ? 12 : 28), - this.getLineHeight(), 0xFFFFFF); - - this.passField.render(poseStack, i, j, f); - - // if (this.algorithmButton != null && this.algorithmButton.isMouseOver(i, j)) { - // this.renderTooltip(poseStack, this.algorithmButton.getTooltip(), i, j); - // } - - super.render(poseStack, i, j, f); - - if (StringUtil.isNullOrEmpty(this.keyField.getValue()) && !this.keyField.isFocused()) { - Screen.drawString(poseStack, this.font, - Component.translatable("gui.nochatreports.encryption_config.default_key", - this.algorithmButton.getValue().getDefaultKey()), this.keyField.getX() + 4, - this.keyField.getY() + 5, 0x999999); - } - - if (!this.passField.active) { - Screen.drawString(poseStack, this.font, PASS_NOT_ALLOWED, this.passField.getX() + 4, - this.passField.getY() + 5, 0x999999); - RenderSystem.setShaderTexture(0, ENCRYPTION_ICONS); - RenderSystem.enableDepthTest(); - blit(poseStack, this.passField.getX() - 20, this.passField.getY() + 3, 50, 0, 14, 13, 64, 64); - } - } - - private int getLineHeight() { - if (this.hugeGUI()) - return (int) (this.minecraft.font.lineHeight * 1.5) + 1; - else - return this.minecraft.font.lineHeight * 2; - } - - @Override - public void tick() { - this.keyField.tick(); - } - - private void onKeyUpdate(String key) { - if (!this.settingPassKey) { - this.passField.setValue(""); - } - - if (!StringUtil.isNullOrEmpty(key)) { - this.validationIcon.yTexStart = this.algorithmButton.getValue().validateKey(key) ? 0 : 12; - } else { - this.validationIcon.yTexStart = 0; - } - } - - private void onPassphraseUpdate(String pass) { - Encryption encryption = this.algorithmButton.getValue(); - - this.settingPassKey = true; - if (!StringUtil.isNullOrEmpty(pass)) { - if (encryption.supportsPassphrases()) { - this.keyField.setValue(encryption.getPassphraseKey(pass)); - } - } else { - this.onKeyUpdate(this.keyField.getValue()); - } - this.settingPassKey = false; - } - - private void onAlgorithmUpdate(Encryption encryption) { - if (!encryption.supportsPassphrases()) { - this.passField.setFocused(false); - this.passField.setEditable(this.passField.active = false); - this.onKeyUpdate(this.keyField.getValue()); - } else { - this.passField.setEditable(this.passField.active = true); - this.onPassphraseUpdate(this.passField.getValue()); - } - } - - private void unfocusFields() { - this.keyField.setFocused(false); - this.passField.setFocused(false); - } - - private void onDone() { - var config = NCRConfig.getEncryption(); - var encryption = this.algorithmButton.getValue(); - config.setAlgorithm(encryption); - config.setEncryptionKey(!StringUtil.isNullOrEmpty(this.keyField.getValue()) ? this.keyField.getValue() - : encryption.getDefaultKey()); - config.setEncryptPublic(this.encryptPublicCheck.selected()); - } - - private boolean hugeGUI() { - return this.height <= 1080 / 4; - } - - @Override - public void onClose() { - this.minecraft.setScreen(this.previous); - } - - private static class CustomEditBox extends EditBox { - public CustomEditBox(Font font, int i, int j, int k, int l, Component component) { - super(font, i, j, k, l, component); - } - - @Override - public void setFocused(boolean bl) { - super.setFocused(bl); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java b/src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java deleted file mode 100644 index 0c1b9f3..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.gui.EncryptionConfigScreen; -import com.aizistral.nochatreports.gui.TriageWarningScreen; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -@Environment(EnvType.CLIENT) -public class EncryptionWarningScreen extends TriageWarningScreen { - private static final Component TITLE = Component.translatable("gui.nochatreports.encryption_warning.header").withStyle(ChatFormatting.BOLD); - private static final Component CONTENT = Component.translatable("gui.nochatreports.encryption_warning.contents"); - private static final Component CHECK = Component.translatable("gui.nochatreports.encryption_warning.check"); - private static final String WIKI_LINK = "https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/To-Encrypt-or-Not-to-Encrypt"; - private static boolean sessionSeen = false; - - public EncryptionWarningScreen(Screen previous) { - super(TITLE, CONTENT, CHECK, WIKI_LINK, previous); - } - - @Override - protected void onProceed(Button button) { - this.minecraft.setScreen(new EncryptionConfigScreen(this.previous)); - if (this.stopShowing.selected()) { - NCRConfig.getEncryption().disableWarning(); - } - - sessionSeen = true; - } - - @Override - protected void onBack(Button button) { - this.minecraft.setScreen(this.previous); - } - - public static boolean seenOnThisSession() { - return sessionSeen; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/FontHelper.java b/src/main/java/com/aizistral/nochatreports/gui/FontHelper.java deleted file mode 100644 index a0a1638..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/FontHelper.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import java.util.Arrays; -import java.util.List; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.Font; -import net.minecraft.util.FormattedCharSequence; - -/** - * I couldn't find a way to properly convert {@link FormattedCharSequence} back into - * normal string. Lol. - * - * @author Aizistral - */ - -@Environment(EnvType.CLIENT) -public final class FontHelper { - - private FontHelper() { - throw new IllegalStateException("Can't touch this"); - } - - /** - * Breaks a string into a list of pieces that will fit a specified width. - */ - - public static List wrap(Font font, String str, int wrapWidth) { - return Arrays.asList(wrapFormattedStringToWidth(font, str, wrapWidth).split("\n")); - } - - /** - * Inserts newline and formatting into a string to wrap it within the specified - * width. - */ - - private static String wrapFormattedStringToWidth(Font font, String str, int wrapWidth) { - int j = sizeStringToWidth(font, str, wrapWidth); - - if (str.length() <= j) - return str; - else { - String s1 = str.substring(0, j); - char c0 = str.charAt(j); - boolean flag = c0 == 32 || c0 == 10; - String s2 = getFormatFromString(s1) + str.substring(j + (flag ? 1 : 0)); - return s1 + "\n" + wrapFormattedStringToWidth(font, s2, wrapWidth); - } - } - - /** - * Determines how many characters from the string will fit into the specified - * width. - */ - - private static int sizeStringToWidth(Font font, String str, int wrapWidth) { - int j = str.length(); - int k = 0; - int l = 0; - int i1 = -1; - - for (boolean flag = false; l < j; ++l) { - char c0 = str.charAt(l); - - switch (c0) { - case 10: - --l; - break; - case 167: - if (l < j - 1) { - ++l; - char c1 = str.charAt(l); - - if (c1 != 108 && c1 != 76) { - if (c1 == 114 || c1 == 82 || isFormatColor(c1)) { - flag = false; - } - } else { - flag = true; - } - } - - break; - case 32: - i1 = l; - default: - k += font.width(String.valueOf(c0)); - - if (flag) { - ++k; - } - } - - if (c0 == 10) { - ++l; - i1 = l; - break; - } - - if (k > wrapWidth) { - break; - } - } - - return l != j && i1 != -1 && i1 < l ? i1 : l; - } - - /** - * Checks if the char code is a hexadecimal character, used to set colour. - */ - - private static boolean isFormatColor(char colorChar) { - return colorChar >= 48 && colorChar <= 57 || colorChar >= 97 && colorChar <= 102 - || colorChar >= 65 && colorChar <= 70; - } - - /** - * Checks if the char code is O-K...lLrRk-o... used to set special formatting. - */ - - private static boolean isFormatSpecial(char formatChar) { - return formatChar >= 107 && formatChar <= 111 || formatChar >= 75 && formatChar <= 79 || formatChar == 114 - || formatChar == 82; - } - - /** - * Digests a string for nonprinting formatting characters then returns a string - * containing only that formatting. - */ - - private static String getFormatFromString(String text) { - String s1 = ""; - int i = -1; - int j = text.length(); - - while ((i = text.indexOf(167, i + 1)) != -1) { - if (i < j - 1) { - char c0 = text.charAt(i + 1); - - if (isFormatColor(c0)) { - s1 = "\u00a7" + c0; - } else if (isFormatSpecial(c0)) { - s1 = s1 + "\u00a7" + c0; - } - } - } - - return s1; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/InvisibleButton.java b/src/main/java/com/aizistral/nochatreports/gui/InvisibleButton.java deleted file mode 100644 index 1ec6af2..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/InvisibleButton.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.components.Button; -import net.minecraft.network.chat.Component; - -import java.util.function.Supplier; - -@Environment(EnvType.CLIENT) -public class InvisibleButton extends Button { - - public InvisibleButton() { - super(0, 0, 20, 20, Component.empty(), btn -> {}, Supplier::get); - } - - @Override - public void render(PoseStack poseStack, int i, int j, float f) { - // NO-OP - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/RealmsWarningScreen.java b/src/main/java/com/aizistral/nochatreports/gui/RealmsWarningScreen.java deleted file mode 100644 index 86120a4..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/RealmsWarningScreen.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.gui.TriageWarningScreen; - -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -public class RealmsWarningScreen extends TriageWarningScreen { - private static final Component TITLE = Component.translatable("gui.nochatreports.realms_warning.header").withStyle(ChatFormatting.BOLD); - private static final Component CONTENT = Component.translatable("gui.nochatreports.realms_warning.contents"); - private static final Component CHECK = Component.translatable("gui.nochatreports.realms_warning.check"); - private static final String WIKI_LINK = "https://github.com/Aizistral-Studios/No-Chat-Reports/wiki/The-Realms-Question"; - private static boolean sessionSeen = false; - private final Screen realms; - - public RealmsWarningScreen(Screen previous, Screen realms) { - super(TITLE, CONTENT, CHECK, WIKI_LINK, previous); - this.realms = realms; - } - - @Override - protected void onProceed(Button button) { - this.minecraft.setScreen(this.realms); - if (this.stopShowing.selected()) { - NCRConfig.getClient().setSkipRealmsWarning(true); - } - - sessionSeen = true; - } - - @Override - protected void onBack(Button button) { - this.minecraft.setScreen(null); - } - - public static boolean shouldShow() { - return !sessionSeen && !NCRConfig.getClient().skipRealmsWarning(); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/TriageWarningScreen.java b/src/main/java/com/aizistral/nochatreports/gui/TriageWarningScreen.java deleted file mode 100644 index 03e31f9..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/TriageWarningScreen.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.gui.AdaptiveWarningScreen; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.Checkbox; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.screens.ConfirmLinkScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -public abstract class TriageWarningScreen extends AdaptiveWarningScreen { - private final String wikiLink; - - public TriageWarningScreen(Component title, Component content, Component check, String wikiLink, Screen previous) { - super(title, content, check, previous); - this.wikiLink = wikiLink; - } - - @Override - protected void initButtons(int y) { - int offset = 28; - - this.addRenderableWidget(Button.builder(CommonComponents.GUI_PROCEED, this::onProceed) - .pos(this.width / 2 - 260 + offset, y).size(150, 20).build()); - - this.addRenderableWidget(Button.builder(Component.translatable("gui.nochatreports.encryption_warning.learn_more"), button -> { - Minecraft.getInstance().setScreen(new ConfirmLinkScreen(agree -> { - if (agree) { - Util.getPlatform().openUri(this.wikiLink); - } - - Minecraft.getInstance().setScreen(this); - }, this.wikiLink, true)); - }).pos(this.width / 2 - 100 + offset, y).size(150, 20).build()); - - - this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, this::onBack) - .pos(this.width / 2 + 60 + offset, y).size(150, 20).build()); - } - - protected abstract void onProceed(Button button); - - protected abstract void onBack(Button button); - -} diff --git a/src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java b/src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java deleted file mode 100644 index 20c5604..0000000 --- a/src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.aizistral.nochatreports.gui; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.NoChatReportsClient; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.gui.AdaptiveWarningScreen; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.ChatFormatting; -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.screens.ChatScreen; -import net.minecraft.client.gui.screens.ConfirmLinkScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.TitleScreen; -import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; -import net.minecraft.client.gui.screens.multiplayer.SafetyScreen; -import net.minecraft.client.gui.screens.multiplayer.WarningScreen; -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.client.multiplayer.resolver.ServerAddress; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -@Environment(EnvType.CLIENT) -public final class UnsafeServerScreen extends AdaptiveWarningScreen { - private static final Component TITLE = Component.translatable("gui.nochatreports.signing_required.header").withStyle(ChatFormatting.BOLD); - private static final Component CONTENT = Component.translatable("gui.nochatreports.signing_required.contents"); - private static final Component CHECK = Component.translatable("gui.nochatreports.signing_required.check"); - private static final Component NARRATION = TITLE.copy().append("\n").append(CONTENT); - private static boolean hideThisSession = false; - - public UnsafeServerScreen(Screen previous) { - super(TITLE, CONTENT, CHECK, previous); - } - - @Override - protected void initButtons(int i) { - this.addRenderableWidget(Button.builder(Component.translatable("gui.nochatreports.signing_required.allow_signing"), - button -> { - ServerSafetyState.setAllowChatSigning(true); - this.minecraft.setScreen(this.previous); - }).bounds(this.width / 2 - 155, i, 150, 20) - .build()); - - this.addRenderableWidget(Button.builder(Component.translatable("gui.nochatreports.signing_required.cancel"), - button -> { - if (this.stopShowing.selected()) { - hideThisSession = true; - } - this.minecraft.setScreen(this.previous); - }).bounds(this.width / 2 - 155 + 160, i, 150, 20).build()); - } - - private void resendLastMessage() { - if (this.previous instanceof ChatScreen chat) { - chat.handleChatInput(NCRConfig.getEncryption().getLastMessage(), false); - } - } - - public static void setHideThisSession(boolean hide) { - hideThisSession = hide; - } - - public static boolean hideThisSession() { - return hideThisSession; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java deleted file mode 100644 index 0238320..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.EncryptionUtil; - -import net.minecraft.ChatFormatting; -import net.minecraft.client.GuiMessageTag; -import net.minecraft.client.gui.components.ChatComponent; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.FormattedText; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.At.Shift; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.ModifyVariable; - -@Mixin(ChatComponent.class) -public class MixinChatComponent { - private static final GuiMessageTag.Icon ENCRYPTED_ICON = GuiMessageTag.Icon.valueOf("CHAT_NCR_ENCRYPTED"); - private boolean lastMessageEncrypted; - private Component lastMessageOriginal; - - @ModifyVariable(method = "addRecentChat", at = @At("HEAD"), argsOnly = true) - private String onAddRecentChat(String message) { - if (NCRConfig.getEncryption().isEnabledAndValid()) - return NCRConfig.getEncryption().getLastMessage(); - else - return message; - } - - @ModifyVariable(method = "addMessage(Lnet/minecraft/network/chat/Component;" - + "Lnet/minecraft/network/chat/MessageSignature;ILnet/minecraft/client/GuiMessageTag;Z)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/components/ComponentRenderUtils;" - + "wrapComponents(Lnet/minecraft/network/chat/FormattedText;ILnet/minecraft/client/gui/Font;" - + ")Ljava/util/List;", ordinal = 0, shift = Shift.AFTER), argsOnly = true) - private synchronized GuiMessageTag modifyGUITag(GuiMessageTag tag) { - if (!NCRConfig.getEncryption().showEncryptionIndicators() || !this.lastMessageEncrypted) - return tag; - - this.lastMessageEncrypted = false; - Component tooltip = Component.empty().append(Component.translatable("tag.nochatreports.encrypted", - Component.literal(NCRConfig.getEncryption().getAlgorithm().getName()) - .withStyle(ChatFormatting.BOLD))).append(CommonComponents.NEW_LINE).append( - Component.translatable("tag.nochatreports.encrypted_original", - this.lastMessageOriginal)); - - return new GuiMessageTag(0x8B3EC7, ENCRYPTED_ICON, tooltip, "Encrypted"); - } - - @ModifyArg(index = 0, method = "addMessage(Lnet/minecraft/network/chat/Component;" - + "Lnet/minecraft/network/chat/MessageSignature;ILnet/minecraft/client/GuiMessageTag;Z)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/components/ComponentRenderUtils;" - + "wrapComponents(Lnet/minecraft/network/chat/FormattedText;I" - + "Lnet/minecraft/client/gui/Font;)Ljava/util/List;", ordinal = 0)) - private FormattedText modifyGUIMessage(FormattedText msg) { - if (NCRConfig.getCommon().enableDebugLog()) { - NoChatReports.LOGGER.info("Adding chat message, structure: " + - Component.Serializer.toStableJson((Component) msg)); - } - - var decrypted = EncryptionUtil.tryDecrypt((Component) msg); - - decrypted.ifPresentOrElse(component -> { - this.lastMessageOriginal = EncryptionUtil.recreate((Component) msg); - this.lastMessageEncrypted = true; - }, () -> this.lastMessageEncrypted = false); - - return this.lastMessageEncrypted ? decrypted.get() : msg; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatListener.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatListener.java deleted file mode 100644 index 675e642..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatListener.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.NoChatReportsClient; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.EncryptionUtil; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.core.SigningMode; -import com.aizistral.nochatreports.gui.UnsafeServerScreen; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.ChatScreen; -import net.minecraft.client.multiplayer.chat.ChatListener; -import net.minecraft.client.multiplayer.chat.ChatTrustLevel; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.PlayerChatMessage; -import net.minecraft.network.chat.contents.TranslatableContents; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.time.Instant; -import java.util.Base64; -import java.util.UUID; - -@Mixin(ChatListener.class) -public class MixinChatListener { - - @Shadow - private boolean isSenderLocalPlayer(UUID uuid) { - throw new IllegalStateException("@Shadow transformation failed. Should never happen."); - } - - @Inject(method = "handleSystemMessage", at = @At("HEAD"), cancellable = true) - private void onHandleSystemMessage(Component message, boolean overlay, CallbackInfo info) { - if (message instanceof MutableComponent mutable && message.getContents() instanceof TranslatableContents translatable) { - if (translatable.getKey().equals("chat.disabled.missingProfileKey")) { - mutable.contents = new TranslatableContents("chat.nochatreports.disabled.signing_requested"); - - if (!ServerSafetyState.isOnRealms()) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); - } - - if (UnsafeServerScreen.hideThisSession() || ServerSafetyState.allowChatSigning()) - return; - - if (NCRConfig.getServerPreferences().hasModeCurrent(SigningMode.ON_DEMAND)) { - ServerSafetyState.scheduleSigningAction(NoChatReportsClient::resendLastChatMessage); - ServerSafetyState.setAllowChatSigning(true); - - if (NCRConfig.getClient().hideSigningRequestMessage()) { - info.cancel(); - } - - return; - } - - if (NCRConfig.getServerPreferences().hasModeCurrent(SigningMode.PROMPT)) { - Minecraft.getInstance().setScreen(new UnsafeServerScreen(Minecraft.getInstance().screen - instanceof ChatScreen chat ? chat : new ChatScreen(""))); - - if (NCRConfig.getClient().hideSigningRequestMessage()) { - info.cancel(); - } - } - } - } - } - - /** - * @reason Removes "Not Secure" and "Modified" statuses of chat messages. They ultimately - * serve no purpose but to annoy the user and scare them away from servers that actually - * try to protect them by stripping message signatures. - * @author Aizistral - */ - - @Inject(method = "evaluateTrustLevel", at = @At("HEAD"), cancellable = true) - private void onEvaluateTrustLevel(PlayerChatMessage playerChatMessage, Component component, Instant instant, CallbackInfoReturnable info) { - if (this.isSenderLocalPlayer(playerChatMessage.sender())) { - info.setReturnValue(ChatTrustLevel.SECURE); - } else { - if (playerChatMessage.hasSignature() && ServerSafetyState.getCurrent() == ServerSafetyLevel.SECURE) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); - } - - var evaluate = ChatTrustLevel.evaluate(playerChatMessage, component, instant); - - if (evaluate == ChatTrustLevel.NOT_SECURE && NCRConfig.getClient().hideInsecureMessageIndicators()) { - info.setReturnValue(ChatTrustLevel.SECURE); - } else if (evaluate == ChatTrustLevel.MODIFIED && NCRConfig.getClient().hideModifiedMessageIndicators()) { - info.setReturnValue(ChatTrustLevel.SECURE); - } - } - - // Debug never dies - if (NCRConfig.getCommon().enableDebugLog()) { - NoChatReports.LOGGER.info("Received message: {}, from: {}, signature: {}", - Component.Serializer.toStableJson(playerChatMessage.unsignedContent()), - playerChatMessage.link().sender(), - Base64.getEncoder().encodeToString(playerChatMessage.signature() != null ? playerChatMessage.signature().bytes() : new byte[0])); - } - } - - @ModifyVariable(method = "narrateChatMessage(Lnet/minecraft/network/chat/ChatType$Bound;" - + "Lnet/minecraft/network/chat/Component;)V", at = @At("HEAD"), argsOnly = true) - private Component decryptNarratedMessage(Component msg) { - return EncryptionUtil.tryDecrypt(msg).orElse(msg); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatOptionsScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatOptionsScreen.java deleted file mode 100644 index 9fff6d9..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatOptionsScreen.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import java.util.List; -import java.util.Optional; - -import org.jetbrains.annotations.NotNull; -import org.spongepowered.asm.mixin.Mixin; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.mojang.blaze3d.vertex.PoseStack; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.OptionInstance; -import net.minecraft.client.Options; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.screens.ChatOptionsScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.SimpleOptionsSubScreen; -import net.minecraft.network.chat.Component; -import net.minecraft.util.FormattedCharSequence; - -/** - * Mixin responsible for graying out "Only Show Secure Chat" option. - * - * @author Kevinthegreat (original implementation) - * @author Aizistral (current version) - */ - -@Mixin(ChatOptionsScreen.class) -public class MixinChatOptionsScreen extends SimpleOptionsSubScreen { - - public MixinChatOptionsScreen(Screen screen, Options options, Component component, OptionInstance... optionInstances) { - super(screen, options, component, optionInstances); - throw new IllegalStateException("Can't touch this"); - } - - @Override - protected void init() { - super.init(); - - if (NCRConfig.getClient().enableMod()) { - Optional.ofNullable(this.list.findOption(Minecraft.getInstance().options.onlyShowSecureChat())) - .ifPresent(option -> option.active = false); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java deleted file mode 100644 index 18b673e..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java +++ /dev/null @@ -1,218 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.NoChatReportsClient; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.core.SigningMode; -import com.aizistral.nochatreports.gui.AdvancedImageButton; -import com.aizistral.nochatreports.gui.AdvancedTooltip; -import com.aizistral.nochatreports.gui.EncryptionButton; -import com.aizistral.nochatreports.gui.EncryptionWarningScreen; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; - -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.ImageButton; -import net.minecraft.client.gui.screens.ChatScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import net.minecraft.client.multiplayer.resolver.ServerAddress; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.locale.Language; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.FormattedCharSequence; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * This is responsible for adding safety status indicator to the bottom-right corner of chat screen. - * @author Aizistral - */ - -@Mixin(ChatScreen.class) -public abstract class MixinChatScreen extends Screen { - private static final ResourceLocation CHAT_STATUS_ICONS = new ResourceLocation("nochatreports", "textures/gui/chat_status_icons_extended.png"); - private static final ResourceLocation ENCRYPTION_BUTTON = new ResourceLocation("nochatreports", "textures/gui/encryption_toggle_button.png"); - private ImageButton safetyStatusButton; - - protected MixinChatScreen() { - super(null); - throw new IllegalStateException("Can't touch this"); - } - - @Inject(method = "handleChatInput", at = @At("HEAD"), cancellable = true) - public void handleChatInput(String string, boolean bl, CallbackInfoReturnable info) { - if (NCRConfig.getServerPreferences().hasModeCurrent(SigningMode.ALWAYS) && !ServerSafetyState.allowChatSigning()) { - if (this.minecraft.getConnection().getConnection().isEncrypted()) { - if (!this.normalizeChatMessage(string).isEmpty()) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); - ServerSafetyState.scheduleSigningAction(NoChatReportsClient::resendLastChatMessage); - ServerSafetyState.setAllowChatSigning(true); - info.setReturnValue(true); - } - } - } - } - - @Inject(method = "normalizeChatMessage", at = @At("RETURN"), cancellable = true) - public void onBeforeMessage(String original, CallbackInfoReturnable info) { - String message = info.getReturnValue(); - NCRConfig.getEncryption().setLastMessage(message); - - if (!message.isEmpty() && !Screen.hasControlDown() && NCRConfig.getEncryption().shouldEncrypt(message)) { - NCRConfig.getEncryption().getEncryptor().ifPresent(e -> { - int index = NCRConfig.getEncryption().getEncryptionStartIndex(message); - String noencrypt = message.substring(0, index); - String encrypt = message.substring(index, message.length()); - - if (encrypt.length() > 0) { - info.setReturnValue(noencrypt + e.encrypt("#%" + encrypt)); - } - }); - } - } - - @Inject(method = "init", at = @At("HEAD")) - private void onInit(CallbackInfo info) { - int buttonX = this.width - 23; - - if (NCRConfig.getClient().showServerSafety() && NCRConfig.getClient().enableMod()) { - this.safetyStatusButton = new AdvancedImageButton(buttonX, this.height - 37, 20, 20, this.getXOffset(), - 0, 20, CHAT_STATUS_ICONS, 128, 128, btn -> { - if (!NoChatReportsClient.areSigningKeysPresent()) - return; - - var address = ServerSafetyState.getLastServer(); - - if (address != null) { - var preferences = NCRConfig.getServerPreferences(); - preferences.setMode(address, preferences.getModeUnresolved(address).next()); - preferences.saveFile(); - } - }, Component.empty(), this); - this.safetyStatusButton.setTooltip(new AdvancedTooltip(() -> { - MutableComponent tooltip = this.getSafetyLevel().getTooltip(); - - if (ServerSafetyState.allowChatSigning()) { - tooltip = Component.translatable("gui.nochatreports.safety_status.insecure_signing"); - } else if (ServerSafetyState.isInSingleplayer()) - return tooltip; - - ServerAddress address = ServerSafetyState.getLastServer(); - SigningMode mode = NCRConfig.getServerPreferences().getModeUnresolved(address); - String signing = "gui.nochatreports.signing_status."; - - if (!this.minecraft.getConnection().getConnection().isEncrypted()) { - signing += "disabled_offline"; - } else if (ServerSafetyState.getCurrent() == ServerSafetyLevel.REALMS) { - signing += "allowed_realms"; - } else if (mode.resolve() == SigningMode.ALWAYS) { - if (ServerSafetyState.allowChatSigning()) { - signing += "allowed"; - } else { - signing += "disabled_allowance_pending"; - } - } else if (ServerSafetyState.allowChatSigning()) { - signing += "allowed_session"; - } else { - signing += "disabled"; - } - - tooltip.append("\n\n"); - tooltip.append(Component.translatable(signing)); - - if (ServerSafetyState.isOnRealms()) - return tooltip; - - tooltip.append("\n\n"); - tooltip.append(Component.translatable("gui.nochatreports.safety_status_button.controls")); - tooltip.append("\n\n"); - tooltip.append(Component.translatable("gui.nochatreports.signing_mode", - mode.getName().withStyle(ChatFormatting.BOLD, ChatFormatting.AQUA))); - tooltip.append("\n"); - tooltip.append((mode == SigningMode.DEFAULT ? mode.resolve() : mode).getTooltip()); - - return tooltip; - }).setMaxWidth(250).setRenderWithoutGap(true)); - - this.addRenderableWidget(this.safetyStatusButton); - buttonX -= 25; - } - - if (!NCRConfig.getEncryption().showEncryptionButton()) - return; - - int xStart = !NCRConfig.getEncryption().isValid() ? 40 : (NCRConfig.getEncryption().isEnabled() ? 0 : 20); - - var button = new EncryptionButton(buttonX, this.height - 37, 20, 20, xStart, - 0, 20, ENCRYPTION_BUTTON, 64, 64, btn -> { - if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled() - && !NCRConfig.getEncryption().isEnabled()) { - Minecraft.getInstance().setScreen(new EncryptionWarningScreen(this)); - } else if (NCRConfig.getEncryption().isValid()) { - NCRConfig.getEncryption().toggleEncryption(); - ((EncryptionButton)btn).xTexStart = NCRConfig.getEncryption().isEnabledAndValid() ? 0 : 20; - } else { - ((EncryptionButton)btn).openEncryptionConfig(); - } - }, Component.empty(), this); - button.setTooltip(new AdvancedTooltip(() -> { - if (NCRConfig.getEncryption().isValid()) - return Component.translatable("gui.nochatreports.encryption_tooltip", Language.getInstance() - .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getEncryption() - .isEnabledAndValid() ? "on" : "off"))); - else - return Component.translatable("gui.nochatreports.encryption_tooltip_invalid", Language.getInstance() - .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getEncryption() - .isEnabledAndValid() ? "on" : "off"))); - }).setMaxWidth(250)); - button.active = true; - button.visible = true; - - this.addRenderableWidget(button); - } - - @Inject(method = "tick", at = @At("RETURN")) - private void onTick(CallbackInfo info) { - if (this.safetyStatusButton != null) { - this.safetyStatusButton.xTexStart = this.getXOffset(); - } - } - - private ServerSafetyLevel getSafetyLevel() { - return ServerSafetyState.getCurrent(); - } - - private int getXOffset() { - return this.getXOffset(this.getSafetyLevel()); - } - - private int getXOffset(ServerSafetyLevel level) { - return switch (level) { - case SECURE, SINGLEPLAYER -> 21; - case UNINTRUSIVE -> 42; - case INSECURE -> 0; - case REALMS -> 63; - case UNKNOWN -> 84; - case UNDEFINED -> 105; - }; - } - - @Shadow - public abstract String normalizeChatMessage(String string); - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientPacketListener.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientPacketListener.java deleted file mode 100644 index 2d3e697..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientPacketListener.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.mojang.brigadier.ParseResults; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.commands.SharedSuggestionProvider; -import net.minecraft.network.chat.SignableCommand; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; -import net.minecraft.network.protocol.game.ServerboundChatPacket; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(ClientPacketListener.class) -public abstract class MixinClientPacketListener { - - @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;)V", at = @At("HEAD")) - private void onSend(Packet packet, CallbackInfo info) { - if (!ServerSafetyState.allowChatSigning() && !ServerSafetyState.isDetermined()) { - if (packet instanceof ServerboundChatPacket chat) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); // asume unintrusive until further notice - } else if (packet instanceof ServerboundChatCommandPacket command) { - if (!SignableCommand.of(this.parseCommand(command.command())).arguments().isEmpty()) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); - } - } - } - } - - @Shadow - private ParseResults parseCommand(String command) { - throw new IllegalStateException("@Shadow transformation failed"); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java deleted file mode 100644 index 73ec799..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyState; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.ConnectScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.client.multiplayer.resolver.ServerAddress; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(ConnectScreen.class) -public class MixinConnectScreen { - - /** - * @reason Intercept initiation of any new server connection. This way we can keep track of which - * server client currently tries to connect to. - * @author Aizistral - */ - - @Inject(method = "startConnecting", at = @At("HEAD")) - private static void onStartConnecting(Screen screen, Minecraft minecraft, ServerAddress serverAddress, - @Nullable ServerData serverData, CallbackInfo info) { - if (!NCRConfig.getClient().enableMod()) - return; - - ServerSafetyState.reset(); - ServerSafetyState.setLastServer(serverAddress); - - if (NCRConfig.getCommon().enableDebugLog()) { - NoChatReports.LOGGER.info("Connecting to: {}", - serverAddress.getHost() + ":" + serverAddress.getPort()); - NoChatReports.LOGGER.info("Server Data IP: {}", serverData != null ? serverData.ip : "null"); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTag.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTag.java deleted file mode 100644 index 969afd0..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTag.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import net.minecraft.client.GuiMessageTag; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.aizistral.nochatreports.config.NCRConfig; - -@Mixin(GuiMessageTag.class) -public class MixinGuiMessageTag { - - /** - * @reason Remove gray bar as indication besides system messages, if mod is configured - * respectively. The mod can convert all player messages to system messages when - * installed on server, so we don't need that most of the time. - * @author Aizistral - */ - - @Inject(method = { "system", "systemSinglePlayer" }, at = @At("HEAD"), cancellable = true) - private static void onSystem(CallbackInfoReturnable info) { - if (NCRConfig.getClient().hideSystemMessageIndicators()) { - info.setReturnValue(null); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTagIcon.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTagIcon.java deleted file mode 100644 index 6ef1488..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTagIcon.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import java.util.Arrays; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.gen.Invoker; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; - -import net.minecraft.client.GuiMessageTag; -import net.minecraft.client.GuiMessageTag.Icon; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.resources.ResourceLocation; - -@Mixin(GuiMessageTag.Icon.class) -public abstract class MixinGuiMessageTagIcon { - private static final ResourceLocation TEXTURE_NCR = new ResourceLocation("nochatreports", "textures/gui/encrypted_tag.png"); - @Shadow(aliases = "field_39768") @Mutable static Icon[] $VALUES; - - @Invoker("") - static Icon create(String name, int ordinal, int u, int v, int width, int height) { - throw new IllegalStateException("Invoker transformation failed"); - } - - @Inject(method = "draw", at = @At("HEAD"), cancellable = true) - public void onDraw(PoseStack stack, int x, int y, CallbackInfo info) { - if (((Icon)(Object)this).name().equals("CHAT_NCR_ENCRYPTED")) { - RenderSystem.setShaderTexture(0, TEXTURE_NCR); - GuiComponent.blit(stack, x, y, 0, 0, 9, 9, 9, 9); - info.cancel(); - } - } - - static { - var ordinal = $VALUES.length; - var values = Arrays.copyOf($VALUES, ordinal + 1); - values[ordinal] = create("CHAT_NCR_ENCRYPTED", ordinal, 9, 0, 9, 9); - $VALUES = values; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinJoinMultiplayerScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinJoinMultiplayerScreen.java deleted file mode 100644 index cf5f6be..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinJoinMultiplayerScreen.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import java.util.List; -import java.util.stream.Collectors; - -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.gui.AdvancedImageButton; -import com.aizistral.nochatreports.gui.AdvancedTooltip; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.BufferUploader; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.Tesselator; -import com.mojang.blaze3d.vertex.VertexFormat; - -import net.minecraft.client.gui.components.ImageButton; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.locale.Language; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.FormattedCharSequence; - -/** - * This is responsible for adding config reload button to server selection menu. - * @author Aizistral - */ - -@Mixin(JoinMultiplayerScreen.class) -public abstract class MixinJoinMultiplayerScreen extends Screen { - private static final ResourceLocation RELOAD_TEXTURE = new ResourceLocation("nochatreports", "textures/gui/config_reload_button.png"), - TOGGLE_TEXTURE = new ResourceLocation("nochatreports", "textures/gui/ncr_toggle_button.png"); - private static final Component RELOAD_TOOLTIP = Component.translatable("gui.nochatreports.reload_config_tooltip"); - - protected MixinJoinMultiplayerScreen() { - super(null); - throw new IllegalStateException("Can't touch this"); - } - - @Inject(method = "init", at = @At("HEAD")) - private void onInit(CallbackInfo info) { - if (NCRConfig.getClient().showReloadButton()) { - var button = new AdvancedImageButton(this.width/2 + 158, this.height - 52, 20, 20, 0, 0, 20, - RELOAD_TEXTURE, 64, 64, btn -> NCRConfig.load(), CommonComponents.EMPTY, this); - button.setTooltip(new AdvancedTooltip(RELOAD_TOOLTIP).setMaxWidth(250).setRenderWithoutGap(true)); - button.active = true; - button.visible = true; - this.addRenderableWidget(button); - } - - if (NCRConfig.getClient().showNCRButton()) { - var button = new AdvancedImageButton(this.width/2 + 158, this.height - 28, 20, 20, - NCRConfig.getClient().enableMod() ? 0 : 20, 0, 20, TOGGLE_TEXTURE, 64, 64, - btn -> { - NCRConfig.getClient().toggleMod(); - boolean enabled = NCRConfig.getClient().enableMod(); - - if (enabled) { - ((ImageButton)btn).xTexStart = 0; - } else { - ((ImageButton)btn).xTexStart = 20; - } - - ServerSafetyState.reset(); - }, Component.translatable("gui.nochatreports.ncr_toggle"), this); - button.setTooltip(new AdvancedTooltip(() -> Component.translatable("gui.nochatreports.ncr_toggle_tooltip", - Language.getInstance().getOrDefault("gui.nochatreports.ncr_state_" + (NCRConfig.getClient() - .enableMod() ? "on" : "off")))).setMaxWidth(250)); - button.active = true; - button.visible = true; - this.addRenderableWidget(button); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinMinecraft.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinMinecraft.java deleted file mode 100644 index c6dc485..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinMinecraft.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.aizistral.nochatreports.NoChatReportsClient; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.mojang.authlib.minecraft.TelemetrySession; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.main.GameConfig; -import net.minecraft.client.multiplayer.ProfileKeyPairManager; - -@Mixin(Minecraft.class) -public class MixinMinecraft { - @Shadow @Final - private ProfileKeyPairManager profileKeyPairManager; - - @Inject(method = "(Lnet/minecraft/client/main/GameConfig;)V", at = @At("RETURN")) - private void onConstructed(GameConfig config, CallbackInfo info) { - NoChatReportsClient.setSigningKeysPresent(this.profileKeyPairManager.prepareKeyPair() - .join().isPresent()); - } - - @Inject(method = "getProfileKeyPairManager", at = @At("HEAD"), cancellable = true) - private void onGetProfileKeyPairManager(CallbackInfoReturnable info) { - if (!NCRConfig.getClient().enableMod()) - return; - - if (!ServerSafetyState.allowChatSigning()) { - info.setReturnValue(ProfileKeyPairManager.EMPTY_KEY_MANAGER); - } - } - - @Inject(method = "allowsTelemetry", at = @At("HEAD"), cancellable = true) - private void onAllowsTelemetry(CallbackInfoReturnable info) { - if (NCRConfig.getClient().disableTelemetry()) { - info.setReturnValue(false); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java deleted file mode 100644 index 0798ba1..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerDataExtension; -import com.aizistral.nochatreports.gui.FontHelper; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; -import net.minecraft.client.gui.screens.multiplayer.ServerSelectionList; -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.locale.Language; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.ArrayList; -import java.util.stream.Collectors; - -@Mixin(ServerSelectionList.OnlineServerEntry.class) -public abstract class MixinOnlineServerEntry extends ServerSelectionList.Entry { - private static final ResourceLocation VERIFIED_ICON = new ResourceLocation("nochatreports", "textures/gui/verified_server.png"); - - @Shadow @Final - private JoinMultiplayerScreen screen; - @Shadow @Final - private Minecraft minecraft; - @Shadow @Final - private ServerData serverData; - - @Inject(method = "render", at = @At("RETURN")) - private void onRender(PoseStack poseStack, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f, CallbackInfo info) { - if (!NCRConfig.getClient().verifiedIconEnabled()) - return; - - if (this.serverData.ping >= 0 && ((ServerDataExtension) this.serverData).preventsChatReports()) { - int xOffset = NCRConfig.getClient().getVerifiedIconOffsetX(), - yOffset = NCRConfig.getClient().getVerifiedIconOffsetY(); - - RenderSystem.setShaderTexture(0, VERIFIED_ICON); - RenderSystem.enableBlend(); - GuiComponent.blit(poseStack, k + l - 35 + xOffset, j - 1 + yOffset, 0.0f, 0.0f, 14, 14, 14, 14); - RenderSystem.disableBlend(); - - int t = n - k; - int u = o - j; - if (t >= l - 35 + xOffset && t <= l - 22 + xOffset && u >= 0 + yOffset && u <= 11 + yOffset) { - this.screen.setToolTip(FontHelper.wrap(this.minecraft.font, Language.getInstance() - .getOrDefault("gui.nochatreports.verified_server"), 250).stream() - .map(Component::literal).collect(Collectors.toCollection(() -> - new ArrayList()))); - } - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java deleted file mode 100644 index 7064ed6..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java +++ /dev/null @@ -1,44 +0,0 @@ - -package com.aizistral.nochatreports.mixins.client; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.google.common.collect.ImmutableList; -import com.mojang.serialization.Codec; - -import net.minecraft.client.OptionInstance; -import net.minecraft.client.Options; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -@Mixin(Options.class) -public class MixinOptions { - private static final Component SECURE_CHAT_TOOLTIP = Component.translatable("gui.nochatreports.secure_chat"); - private OptionInstance alternativeOption; - - /** - * @reason Disable secure chat option, since it will not work anyways. - * @author Aizistral - */ - - @Inject(method = "onlyShowSecureChat", at = @At("RETURN"), cancellable = true) - private void onlyShowSecureChat(CallbackInfoReturnable> cir) { - if (!NCRConfig.getClient().enableMod()) - return; - - if (this.alternativeOption == null) { - this.alternativeOption = new OptionInstance<>("options.onlyShowSecureChat", - OptionInstance.cachedConstantTooltip(SECURE_CHAT_TOOLTIP), - OptionInstance.BOOLEAN_TO_STRING, - new OptionInstance.Enum<>(ImmutableList.of(Boolean.FALSE), Codec.BOOL), - false, value -> {}); - } - - cir.setReturnValue(this.alternativeOption); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java deleted file mode 100644 index 59348f1..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import java.util.List; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.function.Supplier; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.aizistral.nochatreports.gui.AdvancedImageButton; -import com.aizistral.nochatreports.gui.InvisibleButton; -import com.mojang.blaze3d.vertex.PoseStack; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.ImageButton; -import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.client.gui.screens.social.PlayerEntry; -import net.minecraft.client.gui.screens.social.SocialInteractionsScreen; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.FormattedCharSequence; - -@Mixin(PlayerEntry.class) -public class MixinPlayerEntry { - private static final Component NCR_BUTTON_TOOLTIP = Component.translatable("gui.nochatreports.no_reporting"); - @Shadow @Final private static ResourceLocation REPORT_BUTTON_LOCATION; - @Shadow private Button reportButton; - - /** - * @reason Disable (or hide if configured respectively) chat report button on client. - * @author Aizistral - */ - - @Inject(method = "", at = @At("RETURN")) - private void onConstructed(Minecraft minecraft, SocialInteractionsScreen screen, UUID uuid, String name, Supplier skinGetter, boolean reportable, CallbackInfo info) { - if (NCRConfig.getClient().alwaysHideReportButton()) { - this.reportButton = new InvisibleButton(); - this.reportButton.active = this.reportButton.visible = false; - } else if (ServerSafetyState.getCurrent().isSecure() && this.reportButton != null) { - this.reportButton = new AdvancedImageButton(0, 0, 20, 20, 0, 0, 20, REPORT_BUTTON_LOCATION, 64, 64, - button -> {}, Component.translatable("gui.socialInteractions.report"), screen); - this.reportButton.setTooltip(Tooltip.create(NCR_BUTTON_TOOLTIP)); - this.reportButton.setTooltipDelay(10); - this.reportButton.active = false; - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java deleted file mode 100644 index 7bcb9a8..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.core.ServerSafetyState; -import com.mojang.realmsclient.dto.RealmsServer; - -import net.minecraft.client.multiplayer.resolver.ServerAddress; -import net.minecraft.realms.RealmsConnect; - -@Mixin(RealmsConnect.class) -public class MixinRealmsConnect { - - /** - * @reason Always treat Realms servers as insecure, there is nothing we can do about them. - * @author Aizistral - */ - - @Inject(method = "connect", at = @At("HEAD")) - private void onConnect(RealmsServer realmsServer, ServerAddress serverAddress, CallbackInfo info) { - if (!NCRConfig.getClient().enableMod()) - return; - - ServerSafetyState.reset(); - ServerSafetyState.updateCurrent(ServerSafetyLevel.REALMS); - ServerSafetyState.setAllowChatSigning(true); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRowHelper.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRowHelper.java deleted file mode 100644 index 1c1958b..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRowHelper.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.aizistral.nochatreports.config.NCRConfig; - -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.GridWidget; -import net.minecraft.client.gui.screens.OptionsScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -@Mixin(GridWidget.RowHelper.class) -public abstract class MixinRowHelper { - - @Inject(method = "addChild(Lnet/minecraft/client/gui/components/AbstractWidget;)" - + "Lnet/minecraft/client/gui/components/AbstractWidget;", at = @At("HEAD"), cancellable = true) - private void onAddChild(AbstractWidget widget, CallbackInfoReturnable info) { - if (NCRConfig.getClient().disableTelemetry() && NCRConfig.getClient().removeTelemetryButton()) - if (OptionsScreen.TELEMETRY.equals(widget.getMessage())) { - info.setReturnValue(widget); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java deleted file mode 100644 index b311e43..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import com.aizistral.nochatreports.core.ServerDataExtension; - -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.nbt.CompoundTag; - -/** - * Adds "preventsChatReports" property to {@link ServerData} and handles it during serialization to - * and deserialization from NBT-tag. - * - * @author fxmorin (original implementation) - * @author Aizistral (current version) - */ - -@Mixin(ServerData.class) -public class MixinServerData implements ServerDataExtension { - private boolean preventsChatReports; - - @Override - public boolean preventsChatReports() { - return this.preventsChatReports; - } - - @Override - public void setPreventsChatReports(boolean prevents) { - this.preventsChatReports = prevents; - } - - @Inject(method = "write", at = @At("RETURN")) - private void onWrite(CallbackInfoReturnable info) { - info.getReturnValue().putBoolean("preventsChatReports", this.preventsChatReports); - } - - @Inject(method = "read", locals = LocalCapture.CAPTURE_FAILSOFT, at = @At("RETURN")) - private static void onRead(CompoundTag tag, CallbackInfoReturnable info, ServerData data) { - ((ServerDataExtension)data).setPreventsChatReports(tag.getBoolean("preventsChatReports")); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerStatusPinger$1.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerStatusPinger$1.java deleted file mode 100644 index fb0d66b..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerStatusPinger$1.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import java.lang.reflect.Field; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerDataExtension; - -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.network.protocol.status.ClientboundStatusResponsePacket; -import net.minecraft.network.protocol.status.ServerStatus; - -@Mixin(targets = "net/minecraft/client/multiplayer/ServerStatusPinger$1") -public class MixinServerStatusPinger$1 { - private static final Field SERVER_DATA_FIELD; - - static { - // We use reflection here because Mixin's AP dies when trying to process @Shadow of this lol - try { - Class pinger = Class.forName("net.minecraft.client.multiplayer.ServerStatusPinger$1"); - SERVER_DATA_FIELD = pinger.getDeclaredField("val$p_105460_"); - SERVER_DATA_FIELD.setAccessible(true); - } catch (Exception ex) { - throw new RuntimeException("Reflection failed in MixinServerStatusPinger$1", ex); - } - } - - /** - * @reason Ensure "preventsChatReports" property is transferred from {@link ServerStatus} to - * {@link ServerData} when handling status response. - * @author fxmorin (original implementation) - * @author Aizistral (current version) - */ - - @Inject(method = "handleStatusResponse(Lnet/minecraft/network/protocol/status/ClientboundStatusResponsePacket;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/status/ServerStatus;getPlayers()Lnet/minecraft/network/protocol/status/ServerStatus$Players;", ordinal = 0, shift = At.Shift.BEFORE)) - private void getNoChatReports(ClientboundStatusResponsePacket packet, CallbackInfo info) { - try { - boolean preventsReports = ((ServerDataExtension) packet.getStatus()).preventsChatReports(); - ((ServerDataExtension) SERVER_DATA_FIELD.get(this)).setPreventsChatReports(preventsReports); - - if (NCRConfig.getCommon().enableDebugLog()) { - NoChatReports.LOGGER.info("Received status response packet from server, preventsChatReports: {}", - preventsReports); - } - } catch (IllegalArgumentException | IllegalAccessException ex) { - throw new RuntimeException("Failed to get ServerData field via reflection", ex); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinTitleScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinTitleScreen.java deleted file mode 100644 index 859743d..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinTitleScreen.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import com.aizistral.nochatreports.gui.RealmsWarningScreen; -import com.mojang.realmsclient.RealmsMainScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.TitleScreen; -import net.minecraft.network.chat.CommonComponents; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(TitleScreen.class) -public class MixinTitleScreen extends Screen { - - protected MixinTitleScreen() { - super(CommonComponents.EMPTY); - throw new IllegalStateException("Can't touch this"); - } - - @Inject(method = "realmsButtonClicked", at = @At("HEAD"), cancellable = true) - private void onRealmsButtonClicked(CallbackInfo info) { - if (RealmsWarningScreen.shouldShow()) { - this.minecraft.setScreen(new RealmsWarningScreen(new TitleScreen(), new RealmsMainScreen(this))); - info.cancel(); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinToastComponent.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinToastComponent.java deleted file mode 100644 index 601ccef..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinToastComponent.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.config.NCRConfig; - -import net.minecraft.client.gui.components.toasts.SystemToast; -import net.minecraft.client.gui.components.toasts.SystemToast.SystemToastIds; -import net.minecraft.client.gui.components.toasts.Toast; -import net.minecraft.client.gui.components.toasts.ToastComponent; - -@Mixin(ToastComponent.class) -public class MixinToastComponent { - - @Inject(method = "addToast", at = @At("HEAD"), cancellable = true) - private void onAddToast(Toast toast, CallbackInfo info) { - if (NCRConfig.getClient().hideWarningToast()) - if (toast instanceof SystemToast sys && sys.getToken() == SystemToastIds.UNSECURE_SERVER_WARNING) { - info.cancel(); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinYggdrasilUserApiService.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinYggdrasilUserApiService.java deleted file mode 100644 index 2bd51c6..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinYggdrasilUserApiService.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.aizistral.nochatreports.mixins.client; - -import java.util.concurrent.Executor; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.mojang.authlib.minecraft.TelemetrySession; -import com.mojang.authlib.minecraft.UserApiService; -import com.mojang.authlib.yggdrasil.YggdrasilUserApiService; - -import net.minecraft.client.telemetry.ClientTelemetryManager; - -@Mixin(value = YggdrasilUserApiService.class, remap = false) -public class MixinYggdrasilUserApiService { - - /** - * @reason Privacy. - * @author Aizistral - */ - - @Inject(method = "newTelemetrySession", at = @At("HEAD"), cancellable = true) - private void onCreateTelemetrySession(Executor executor, CallbackInfoReturnable info) { - if (NCRConfig.getClient().disableTelemetry()) { - info.setReturnValue(TelemetrySession.DISABLED); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatus.java b/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatus.java deleted file mode 100644 index ebe1fbb..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatus.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.aizistral.nochatreports.mixins.common; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerDataExtension; - -import net.minecraft.network.protocol.status.ServerStatus; - -@Mixin(ServerStatus.class) -public class MixinServerStatus implements ServerDataExtension { - - /** - * Special additional variable that allows the client to know whether server prevents chat reports - * upon pinging it. - */ - - private boolean preventsChatReports; - - /** - * @reason Spoof the value of "enforcesSecureChat" in case conversion to system messages is enabled. - * There is no way for client to verify the value of the option in such case, so that's one less - * annoying warning. - * @author Aizistral - */ - - @Inject(method = "enforcesSecureChat", at = @At("HEAD"), cancellable = true) - public void onSecureChatCheck(CallbackInfoReturnable info) { - if (NCRConfig.getCommon().convertToGameMessage()) { - info.setReturnValue(true); - } - } - - @Override - public boolean preventsChatReports() { - var self = (ServerStatus) (Object) this; - - if (self.getVersion() != null && self.getVersion().getProtocol() < 759 - && self.getVersion().getProtocol() > 0) - return true; - - return this.preventsChatReports; - } - - @Override - public void setPreventsChatReports(boolean prevents) { - this.preventsChatReports = prevents; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatusSerializer.java b/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatusSerializer.java deleted file mode 100644 index f8a9009..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatusSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.aizistral.nochatreports.mixins.common; - -import java.lang.reflect.Type; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import com.aizistral.nochatreports.config.NCRConfig; -import com.aizistral.nochatreports.core.ServerDataExtension; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; - -import net.minecraft.network.protocol.status.ServerStatus; -import net.minecraft.util.GsonHelper; - -/** - * Handles "preventsChatReports" property during serialization and deserialization of {@link ServerStatus}. - * - * @author fxmorin (original implementation) - * @author Aizistral (current version) - */ - -@Mixin(ServerStatus.Serializer.class) -public class MixinServerStatusSerializer { - - @Inject(method = "serialize(Lnet/minecraft/network/protocol/status/ServerStatus;" + - "Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;", - at = @At("RETURN")) - private void onSerialize(ServerStatus serverStatus, Type type, JsonSerializationContext context, - CallbackInfoReturnable info) { - if (!NCRConfig.getCommon().addQueryData()) - return; - - ((JsonObject) info.getReturnValue()).addProperty("preventsChatReports", true); - } - - @Inject(method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;" + - "Lcom/google/gson/JsonDeserializationContext;)" + - "Lnet/minecraft/network/protocol/status/ServerStatus;", - locals = LocalCapture.CAPTURE_FAILSOFT, at = @At("RETURN")) - private void onDeserialize(JsonElement element, Type type, JsonDeserializationContext context, - CallbackInfoReturnable info, JsonObject json, ServerStatus status) { - if (!json.has("preventsChatReports")) - return; - - ((ServerDataExtension) status).setPreventsChatReports(GsonHelper.getAsBoolean(json, "preventsChatReports")); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinDedicatedServer.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinDedicatedServer.java deleted file mode 100644 index 75a1b7b..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinDedicatedServer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.aizistral.nochatreports.mixins.server; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import net.minecraft.server.dedicated.DedicatedServer; - -@Mixin(DedicatedServer.class) -public class MixinDedicatedServer { - - /** - * @reason If mod is installed on server - it does the exact opposite of what this option is - * designed to enforce, so there's no reason to have it enabled. - * @author Aizistral - */ - - @Inject(method = "enforceSecureProfile", at = @At("RETURN"), cancellable = true) - private void onEnforceSecureProfile(CallbackInfoReturnable cir) { - cir.setReturnValue(false); - } - -} \ No newline at end of file diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayerList.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayerList.java deleted file mode 100644 index 6cbafe2..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayerList.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.aizistral.nochatreports.mixins.server; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import net.minecraft.network.chat.PlayerChatMessage; -import net.minecraft.server.players.PlayerList; - -@Mixin(PlayerList.class) -public class MixinPlayerList { - - /** - * @reason Remove "Not Secure" mark in server chat logs. - * @author Aizistral - */ - - @Inject(method = "verifyChatTrusted", at = @At("HEAD"), cancellable = true) - private void onVerifyChatTrusted(PlayerChatMessage playerChatMessage, CallbackInfoReturnable info) { - info.setReturnValue(true); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java deleted file mode 100644 index 395f317..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.aizistral.nochatreports.mixins.server; - -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.config.NCRConfig; - -import net.minecraft.network.PacketSendListener; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; -import net.minecraft.network.protocol.game.ClientboundSystemChatPacket; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.server.network.ServerPlayerConnection; - -@Mixin(ServerGamePacketListenerImpl.class) -public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerConnection { - @Shadow - public ServerPlayer player; - - /** - * @reason Convert player message to system message if mod is configured respectively. - * This allows to circumvent signature check on client, as it only checks player messages. - * @author JFronny (original implementation) - * @author Aizistral - */ - - @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;)V", at = @At("HEAD"), cancellable = true) - private void onSend(Packet packet, CallbackInfo info) { - if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { - NoChatReports.LOGGER.info("Sending message: {}", chat.unsignedContent() != null ? chat.unsignedContent() - : chat.body().content()); - } - - if (NCRConfig.getCommon().convertToGameMessage()) { - if (packet instanceof ClientboundPlayerChatPacket chat) { - packet = new ClientboundSystemChatPacket(chat.chatType().resolve(this.player.level.registryAccess()) - .get().decorate(chat.unsignedContent() != null ? chat.unsignedContent() - : Component.literal(chat.body().content())), false); - - info.cancel(); - this.send(packet); - } - } - } - - /** - * @reason Ensure conversion works regardless of which send method is used. - * @author Aizistral - */ - - @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;Lnet/minecraft/network/PacketSendListener;)V", - at = @At("HEAD"), cancellable = true) - private void onSend(Packet packet, @Nullable PacketSendListener packetSendListener, CallbackInfo info) { - if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { - NoChatReports.LOGGER.info("Sending message: {}", chat.unsignedContent() != null ? chat.unsignedContent() - : chat.body().content()); - } - - if (NCRConfig.getCommon().convertToGameMessage()) { - if (packet instanceof ClientboundPlayerChatPacket chat && packetSendListener != null) { - info.cancel(); - ((ServerGamePacketListenerImpl) (Object) this).send(chat); - } - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java deleted file mode 100644 index 44b3284..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.aizistral.nochatreports.mixins.server; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import net.minecraft.network.chat.MessageSignature; -import net.minecraft.network.protocol.game.ServerboundChatPacket; - -@Mixin(ServerboundChatPacket.class) -public class MixinServerboundChatPacket { - - /** - * @reason Strip signatures before relaying messages to other clients, if they arrive signed - * This is important for mod to be able to operate in server-only mode without - * {@link NCRConfigLegacy#convertToGameMessage()} enabled. - * @author Aizistral - */ - - @Inject(method = "signature", at = @At("RETURN"), cancellable = true) - private void onGetSignature(CallbackInfoReturnable info) { - info.setReturnValue(null); - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatSessionUpdatePacket.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatSessionUpdatePacket.java deleted file mode 100644 index d88a2eb..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatSessionUpdatePacket.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.aizistral.nochatreports.mixins.server; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.aizistral.nochatreports.config.NCRConfig; - -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ServerGamePacketListener; -import net.minecraft.network.protocol.game.ServerboundChatSessionUpdatePacket; -import net.minecraft.server.network.ServerGamePacketListenerImpl; - -@Mixin(ServerboundChatSessionUpdatePacket.class) -public class MixinServerboundChatSessionUpdatePacket { - - /** - * @reason Ignore chat sessions from client, since we throw away signatures anyways. - * @author Aizistral - */ - - @Inject(method = "handle", at = @At("HEAD"), cancellable = true) - private void onHandle(ServerGamePacketListener listener, CallbackInfo info) { - var impl = (ServerGamePacketListenerImpl) listener; - - if (!impl.getPlayer().getServer().isSingleplayerOwner(impl.getPlayer().getGameProfile())) { - if (NCRConfig.getCommon().demandOnClient()) { - impl.disconnect(Component.literal(NCRConfig.getCommon().demandOnClientMessage())); - } - } - - info.cancel(); - } - -} -- cgit v1.2.3