diff options
Diffstat (limited to 'src/main/java/com/aizistral/nochatreports')
13 files changed, 674 insertions, 188 deletions
diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java index c18be5d..5122741 100644 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java @@ -19,6 +19,7 @@ public final class NCRConfig { private static NCRConfigCommon common = null; private static NCRConfigClient client = null; private static NCRServerWhitelist whitelist = null; + private static NCRConfigEncryption encryption = null; private NCRConfig() { throw new IllegalStateException("Can't touch this"); @@ -38,6 +39,11 @@ public final class NCRConfig { return checkLoaded(() -> whitelist); } + @Environment(EnvType.CLIENT) + public static NCRConfigEncryption getEncryption() { + return checkLoaded(() -> encryption); + } + private static <T extends JSONConfig> T checkLoaded(Supplier<T> config) { if (config.get() == null) { load(); @@ -52,6 +58,7 @@ public final class NCRConfig { if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { client = JSONConfig.loadConfig(NCRConfigClient.class, NCRConfigClient::new, NCRConfigClient.FILE_NAME); whitelist = JSONConfig.loadConfig(NCRServerWhitelist.class, NCRServerWhitelist::new, NCRServerWhitelist.FILE_NAME); + encryption = JSONConfig.loadConfig(NCRConfigEncryption.class, NCRConfigEncryption::new, NCRConfigEncryption.FILE_NAME); } save(); @@ -63,6 +70,7 @@ public final class NCRConfig { if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { checkLoaded(() -> client).saveFile(); checkLoaded(() -> whitelist).saveFile(); + checkLoaded(() -> encryption).saveFile(); } Path readme = JSONConfig.CONFIG_DIR.resolve("NoChatReports/README.md"); diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java index 8c014f6..889d9b8 100644 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java @@ -6,8 +6,8 @@ import java.util.List; import java.util.Optional; import com.aizistral.nochatreports.core.ServerSafetyLevel; -import com.aizistral.nochatreports.encryption.AESChatEncryption; -import com.aizistral.nochatreports.encryption.ChatEncryption; +import com.aizistral.nochatreports.encryption.AESEncryptor; +import com.aizistral.nochatreports.encryption.Encryptor; import com.aizistral.nochatreports.gui.UnsafeServerScreen; import com.aizistral.nochatreports.mixins.client.MixinChatListener; import com.aizistral.nochatreports.mixins.client.MixinToastComponent; @@ -22,8 +22,7 @@ public final class NCRConfigClient extends JSONConfig { hideYellowChatIndicators = true, hideGrayChatIndicators = true, hideWarningToast = true, alwaysHideReportButton = false, disableTelemetry = true, showReloadButton = true, whitelistAllServers = false, verifiedIconEnabled = true, showNCRButton = true, - enableMod = true, enableChatEncryption = false; - protected String chatEncryptionKey = "", chatEncryptionAlgorithm = "AES+Base64"; + enableMod = true; protected int verifiedIconOffsetX = 0, verifiedIconOffsetY = 0; protected NCRConfigClient() { @@ -39,10 +38,6 @@ public final class NCRConfigClient extends JSONConfig { this.enableMod = !this.enableMod; } - public void toggleEncryption() { - this.enableChatEncryption = !this.enableChatEncryption; - } - /** * @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 @@ -205,43 +200,4 @@ public final class NCRConfigClient extends JSONConfig { return this.enableMod; } - /** - * @return Whether or not chat encryption is enabled. - */ - - public boolean enableChatEncryption() { - return this.enableChatEncryption; - } - - /** - * @return Current chat encryption algorithm. - */ - - public String chatEncryptionAlgorithm() { - return this.chatEncryptionAlgorithm; - } - - /** - * @return Base64-encoded AES encryption key (hopefully). - */ - - public String chatEncryptionKey() { - return this.chatEncryptionKey; - } - - /** - * @return Chat encryption, if such is enabled and user specified valid key in config. - */ - - public Optional<ChatEncryption> chatEncryption() { - if (!this.enableChatEncryption() || StringUtil.isNullOrEmpty(this.chatEncryptionKey)) - return Optional.empty(); - - try { - return Optional.of(new AESChatEncryption(this.chatEncryptionKey)); - } catch (InvalidKeyException ex) { - return Optional.empty(); - } - } - } diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java new file mode 100644 index 0000000..1c24bc4 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java @@ -0,0 +1,112 @@ +package com.aizistral.nochatreports.config; + +import java.security.InvalidKeyException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import com.aizistral.nochatreports.encryption.AESEncryptor; +import com.aizistral.nochatreports.encryption.Encryption; +import com.aizistral.nochatreports.encryption.Encryptor; +import com.aizistral.nochatreports.gui.UnsafeServerScreen; + +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.util.StringUtil; + +public class NCRConfigEncryption extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-Encryption.json"; + protected boolean skipWarning = false, enableEncryption = false; + protected String encryptionKey = Encryption.AES.getDefaultKey(), encryptionPassphrase = "", + algorithmName = Encryption.AES.getName(); + private transient Encryption algorithm; + private transient boolean isValid = false; + + 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().orElseThrow(() -> new RuntimeException("Invalid encryption algorithm specified in " + FILE_NAME + ": " + this.algorithmName)); + this.validate(); + } + + private void validate() { + this.isValid = this.algorithm.validateKey(this.encryptionKey); + } + + public void toggleEncryption() { + this.enableEncryption = !this.enableEncryption; + } + + public void setAlgorithm(Encryption encryption) { + this.algorithm = encryption; + 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 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 isEnabledAndValid() { + return this.isEnabled() && this.isValid(); + } + + public Encryption getAlgorithm() { + return this.algorithm; + } + + /** + * @return Chat encryptor, if encryption is enabled and user specified valid key in config. + */ + + public Optional<Encryptor<?>> 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/encryption/AESChatEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESChatEncryption.java deleted file mode 100644 index fd3b7e5..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/AESChatEncryption.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.nio.charset.StandardCharsets; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.KeyGenerator; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import net.minecraft.server.network.ServerLoginPacketListenerImpl; - -public class AESChatEncryption extends ChatEncryption { - private final SecretKey key; - private final Cipher encryptor, decryptor; - - public AESChatEncryption(String key) throws InvalidKeyException { - this(new SecretKeySpec(BASE64_DECODER.decode(key), "AES")); - } - - public AESChatEncryption(SecretKey key) throws InvalidKeyException { - try { - this.key = key; - - Cipher encryptor = Cipher.getInstance(this.key.getAlgorithm() + "/CFB8/NoPadding"); - encryptor.init(Cipher.ENCRYPT_MODE, this.key, new IvParameterSpec(key.getEncoded())); - this.encryptor = encryptor; - - Cipher decryptor = Cipher.getInstance(this.key.getAlgorithm() + "/CFB8/NoPadding"); - decryptor.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(key.getEncoded())); - this.decryptor = decryptor; - } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public String encrypt(String message) { - try { - return BASE64_ENCODER.encodeToString(this.encryptor.doFinal(message.getBytes())); - } catch (IllegalBlockSizeException | BadPaddingException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public String decrypt(String message) { - try { - return new String(this.decryptor.doFinal(BASE64_DECODER.decode(message)), StandardCharsets.UTF_8); - } catch (IllegalBlockSizeException | BadPaddingException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public String getAlgorithm() { - return this.key.getAlgorithm() + "+Base64"; - } - - @Override - public String getKey() { - return BASE64_ENCODER.encodeToString(this.key.getEncoded()); - } - - public static AESChatEncryption withRandomKey() { - try { - KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); - keyGenerator.init(128); - SecretKey key = keyGenerator.generateKey(); - - return new AESChatEncryption(key); - } catch (NoSuchAlgorithmException | InvalidKeyException ex) { - throw new RuntimeException(ex); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java new file mode 100644 index 0000000..a515dd0 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java @@ -0,0 +1,99 @@ +package com.aizistral.nochatreports.encryption; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Random; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +import net.minecraft.util.StringUtil; + +public class AESEncryption extends Encryption { + + @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; + } + + @Override + public String getName() { + return "AES/CFB8+Base64"; + } + + @Override + public String getID() { + return "aes_base64"; + } + + @Override + public AESEncryptor getProcessor(String key) throws InvalidKeyException { + return new AESEncryptor(key); + } + + @Override + public AESEncryptor 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/AESEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java new file mode 100644 index 0000000..5e24c22 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java @@ -0,0 +1,95 @@ +package com.aizistral.nochatreports.encryption; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Random; + +import javax.crypto.AEADBadTagException; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import net.minecraft.server.network.ServerLoginPacketListenerImpl; +import static com.aizistral.nochatreports.encryption.Encryption.*; +import static javax.crypto.Cipher.*; + +public class AESEncryptor extends Encryptor<AESEncryption> { + private final SecretKey key; + private final Cipher encryptor, decryptor; + + protected AESEncryptor(String key) throws InvalidKeyException { + this(new SecretKeySpec(decodeBinaryKey(key), "AES")); + } + + protected AESEncryptor(SecretKey key) throws InvalidKeyException { + try { + this.key = key; + + Cipher encryptor = Cipher.getInstance(this.key.getAlgorithm() + "/CFB8/NoPadding"); + encryptor.init(ENCRYPT_MODE, this.key, new IvParameterSpec(key.getEncoded())); + this.encryptor = encryptor; + + Cipher decryptor = Cipher.getInstance(this.key.getAlgorithm() + "/CFB8/NoPadding"); + decryptor.init(DECRYPT_MODE, this.key, new IvParameterSpec(key.getEncoded())); + 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 { + long nonce = RANDOM.nextLong(); + byte[] iv = new byte[16]; + new Random(nonce).nextBytes(iv); + + this.encryptor.init(ENCRYPT_MODE, this.key, new IvParameterSpec(iv)); + byte[] encrypted = this.encryptor.doFinal(message.getBytes()); + + return BASE64_ENCODER.encodeToString(ByteBuffer.allocate(encrypted.length + 8).putLong(nonce).put(encrypted).array()); + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { + throw new RuntimeException(ex); + } + } + + @Override + public String decrypt(String message) { + try { + ByteBuffer buffer = ByteBuffer.wrap(BASE64_DECODER.decode(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); + + this.decryptor.init(DECRYPT_MODE, this.key, new IvParameterSpec(iv)); + return new String(this.decryptor.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { + throw new RuntimeException(ex); + } + } + + @Override + public AESEncryption getAlgorithm() { + return AES; + } + + @Override + public String getKey() { + return encodeBinaryKey(this.key.getEncoded()); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/ChatEncryption.java b/src/main/java/com/aizistral/nochatreports/encryption/ChatEncryption.java deleted file mode 100644 index 44a50bc..0000000 --- a/src/main/java/com/aizistral/nochatreports/encryption/ChatEncryption.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.aizistral.nochatreports.encryption; - -import java.util.Base64; -import java.util.List; - -public abstract class ChatEncryption { - protected static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); - protected static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); - - protected ChatEncryption() { - // NO-OP - } - - public abstract String encrypt(String message); - - public abstract String decrypt(String message); - - public abstract String getAlgorithm(); - - public abstract String getKey(); - -} diff --git a/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java b/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java new file mode 100644 index 0000000..e356b1b --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java @@ -0,0 +1,47 @@ +package com.aizistral.nochatreports.encryption; + +import java.nio.ByteBuffer; +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<Encryption> REGISTERED = new ArrayList<>(); + protected static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); + protected static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); + + public static final AESEncryption AES = new AESEncryption(); + + protected Encryption() { + if (REGISTERED.stream().filter(e -> e.getID().equals(this.getID()) || e.getName().equals(this.getName())) + .findAny().isPresent()) + throw new IllegalStateException("Duplicate encryption algorithm registered! ID: " + this.getID() + + ", Name: " + this.getName()); + REGISTERED.add(this); + } + + 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 String getName(); + + public abstract String getID(); + + public abstract Encryptor<?> getProcessor(String key) throws InvalidKeyException; + + public abstract Encryptor<?> getRandomProcessor(); + + public static List<Encryption> 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 new file mode 100644 index 0000000..5683ad1 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/Encryptor.java @@ -0,0 +1,42 @@ +package com.aizistral.nochatreports.encryption; + +import java.security.InvalidKeyException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; + +public abstract class Encryptor<T extends Encryption> { + protected static final SecureRandom RANDOM = new SecureRandom(); + + 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 encodeBinaryKey(byte[] key) { + return Encryption.BASE64_ENCODER.encodeToString(key); + } + + protected static byte[] decodeBinaryKey(String key) throws InvalidKeyException { + try { + return Encryption.BASE64_DECODER.decode(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; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java b/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java index 77caf15..3aa41b9 100644 --- a/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java +++ b/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java @@ -1,13 +1,26 @@ package com.aizistral.nochatreports.gui; +import java.util.List; + +import org.spongepowered.include.com.google.common.base.Objects; + +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.config.NCRConfigEncryption; +import com.aizistral.nochatreports.encryption.Encryption; import com.mojang.blaze3d.platform.InputConstants; +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.ChatFormatting; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.Button; +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.components.TooltipAccessor; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.AbstractCommandBlockEditScreen; import net.minecraft.client.gui.screens.inventory.CommandBlockEditScreen; @@ -16,51 +29,186 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.FormattedText; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.StringUtil; import net.minecraft.world.level.BaseCommandBlock; +import net.minecraft.world.level.block.entity.CommandBlockEntity; @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 int FIELDS_Y_START = 40; + 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 int FIELDS_Y_START = 45; private final Screen previous; - protected EditBox keyField; - private MultiLineLabel keyDesc = MultiLineLabel.EMPTY; + private CustomEditBox keyField, passField; + private ImageButton validationIcon; + private CycleButton<Encryption> algorithmButton; + private MultiLineLabel keyDesc = MultiLineLabel.EMPTY, passDesc = MultiLineLabel.EMPTY; + private boolean settingPassKey = false; - protected EncryptionConfigScreen(Screen previous) { + public EncryptionConfigScreen(Screen previous) { super(CommonComponents.EMPTY); this.previous = previous; } + private NCRConfigEncryption getConfig() { + return NCRConfig.getEncryption(); + } + @Override protected void init() { + this.minecraft.keyboardHandler.setSendRepeatsToGui(true); + this.clearWidgets(); super.init(); int w = (int) (this.width * 0.7); - this.keyDesc = MultiLineLabel.create(this.font, Component.translatable("gui.nochatreports.encryption_config.key_desc"), w); - int i = (this.keyDesc.getLineCount() + 1) * this.getLineHeight(); + this.keyDesc = MultiLineLabel.create(this.font, KEY_DESC, w - 5); + int keyDescSpace = (this.keyDesc.getLineCount() + 1) * this.getLineHeight(); - w -= 6; + this.passDesc = MultiLineLabel.create(this.font, PASS_DESC, w - 5); + int passDescSpace = (this.passDesc.getLineCount() + 1) * this.getLineHeight(); - this.keyField = new EditBox(this.font, (this.width - w)/2, FIELDS_Y_START + i, w, 20, CommonComponents.EMPTY); - this.keyField.setMaxLength(32500); - this.keyField.setResponder(this::onEdited); + w -= 52; + + this.keyField = new CustomEditBox(this.font, (this.width - w)/2 - 2, FIELDS_Y_START + keyDescSpace - 16, + w, 18, CommonComponents.EMPTY); + this.keyField.setMaxLength(512); + this.keyField.setResponder(this::onKeyUpdate); this.addWidget(this.keyField); + + var button = new ImageButton(this.keyField.x + this.keyField.getWidth() - 15, this.keyField.y + 3, 12, + 12, 0, 0, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, (btn, poseStack, i, j) -> + this.renderTooltip(poseStack, this.minecraft.font.split(this.validationIcon.yTexStart == 0 + ? VALIDATION_OK : VALIDATION_FAILED, 250), i, j), Component.empty()); + button.active = false; + button.visible = true; + + this.addRenderableOnly(this.validationIcon = button); + + button = new ImageButton(this.keyField.x - 22, this.keyField.y - 0, 18, 18, 0, + 28, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, (btn, poseStack, i, j) -> + this.renderTooltip(poseStack, this.minecraft.font.split(CommonComponents.EMPTY, 250), i, j), + Component.empty()); + button.active = false; + button.visible = true; + + this.addRenderableOnly(button); + + button = new ImageButton(this.keyField.x + this.keyField.getWidth() + 4, this.keyField.y - 1, 23, 20, 41, + 24, 20, ENCRYPTION_ICONS, 64, 64, btn -> { + this.unfocusFields(); + this.keyField.setValue(this.algorithmButton.getValue().getRandomKey()); + }, (btn, poseStack, i, j) -> + this.renderTooltip(poseStack, this.minecraft.font.split(DICE_TOOLTIP, 250), i, j), + Component.empty()); + button.active = true; + button.visible = true; + + this.addRenderableWidget(button); + + w += 25; + + this.passField = new CustomEditBox(this.font, (this.width - w)/2 + 11, this.keyField.y + + this.keyField.getHeight() + passDescSpace + 10, w, 18, CommonComponents.EMPTY); + this.passField.setMaxLength(512); + this.passField.setResponder(this::onPassphraseUpdate); + this.addWidget(this.passField); + + button = new ImageButton(this.passField.x - 22, this.passField.y - 0, 18, 18, 0, + 46, 0, ENCRYPTION_ICONS, 64, 64, btn -> {}, (btn, poseStack, i, j) -> + this.renderTooltip(poseStack, this.minecraft.font.split(CommonComponents.EMPTY, 250), i, j), + Component.empty()); + button.active = false; + button.visible = true; + + this.addRenderableOnly(button); + + + this.addRenderableWidget(new Button(this.width / 2 + 4, this.passField.y + 42, 219, 20, + CommonComponents.GUI_DONE, btn -> { + this.onDone(); + this.onClose(); + })); + + CycleButton<Encryption> cycle = CycleButton.<Encryption>builder(value -> { + return Component.translatable("gui.nochatreports.encryption_config.algorithm", value.getName()); + }).withValues(Encryption.getRegistered()).displayOnlyValue().withInitialValue(this.getConfig() + .getAlgorithm()).withTooltip(value -> this.minecraft.font.split( + Component.translatable("algorithm.nochatreports." + value.getID()), 250)) + .create(this.width / 2 - 4 - 218, this.passField.y + 42, 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); - AbstractCommandBlockEditScreen.drawCenteredString(poseStack, this.font, Component.literal("Set command"), this.width / 2, 10, 0xFFFFFF); + Screen.drawCenteredString(poseStack, this.font, HEADER, this.width / 2, 16, 0xFFFFFF); - int k = (this.width - this.keyDesc.getWidth()) / 2; - this.keyDesc.renderLeftAligned(poseStack, k, FIELDS_Y_START, this.getLineHeight(), 0xFFFFFF); + this.keyDesc.renderLeftAligned(poseStack, this.keyField.x - 20, FIELDS_Y_START, this.getLineHeight(), 0xFFFFFF); this.keyField.render(poseStack, i, j, f); + + this.passDesc.renderLeftAligned(poseStack, this.passField.x - 20, this.keyField.y + this.keyField.getHeight() + 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.x + 4, + this.keyField.y + 5, 0x999999); + } + + if (!this.passField.active) { + Screen.drawString(poseStack, this.font, PASS_NOT_ALLOWED, this.passField.x + 4, + this.passField.y + 5, 0x999999); + RenderSystem.setShaderTexture(0, ENCRYPTION_ICONS); + RenderSystem.enableDepthTest(); + blit(poseStack, this.passField.x - 20, this.passField.y + 3, 50, 0, 14, 13, 64, 64); + } } - protected int getLineHeight() { + private int getLineHeight() { return this.font.lineHeight * 2; } @@ -69,12 +217,54 @@ public class EncryptionConfigScreen extends Screen { this.keyField.tick(); } - private void onEdited(String string) { - // TODO Validate + 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; + } } - protected void onDone() { - // NO-OP + 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.keyField.setValue(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()); } @Override @@ -82,5 +272,15 @@ public class EncryptionConfigScreen extends Screen { 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 index 6c6f8e0..f8ed618 100644 --- a/src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java +++ b/src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java @@ -22,11 +22,12 @@ public class EncryptionWarningScreen extends WarningScreen { 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 Component NARRATION = TITLE.copy().append("\n").append(CONTENT); + private static boolean sessionSeen = false; private final Screen previous; public EncryptionWarningScreen(Screen previous) { - super(TITLE, CONTENT, null, NARRATION); + super(TITLE, CONTENT, CHECK, NARRATION); this.previous = previous; } @@ -34,10 +35,19 @@ public class EncryptionWarningScreen extends WarningScreen { protected void initButtons(int i) { this.addRenderableWidget(new Button(this.width / 2 - 155, 100 + i, 150, 20, CommonComponents.GUI_PROCEED, button -> { this.minecraft.setScreen(new EncryptionConfigScreen(this.previous)); + if (this.stopShowing.selected()) { + NCRConfig.getEncryption().disableWarning(); + } + + sessionSeen = true; })); this.addRenderableWidget(new Button(this.width / 2 - 155 + 160, 100 + i, 150, 20, CommonComponents.GUI_BACK, button -> { this.minecraft.setScreen(this.previous); })); } + public static boolean seenOnThisSession() { + return sessionSeen; + } + } diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java index 088d28d..bbac7c9 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java @@ -9,7 +9,7 @@ import org.spongepowered.asm.mixin.injection.At.Shift; import com.aizistral.nochatreports.config.NCRConfig; import com.aizistral.nochatreports.config.NCRConfigClient; -import com.aizistral.nochatreports.encryption.ChatEncryption; +import com.aizistral.nochatreports.encryption.Encryptor; import net.minecraft.ChatFormatting; import net.minecraft.client.GuiMessage; @@ -32,7 +32,7 @@ public class MixinChatComponent { @ModifyVariable(method = "addRecentChat", at = @At("HEAD"), argsOnly = true) private String onAddRecentChat(String message) { if (!message.startsWith("/")) - return NCRConfig.getClient().chatEncryption().map(e -> e.decrypt(message)).orElse(message); + return NCRConfig.getEncryption().getEncryptor().map(e -> e.decrypt(message)).orElse(message); else return message; } @@ -46,7 +46,7 @@ public class MixinChatComponent { if (this.lastMessageEncrypted) { this.lastMessageEncrypted = false; Component tooltip = Component.empty().append(Component.translatable("tag.nochatreports.encrypted", - Component.literal(NCRConfig.getClient().chatEncryptionAlgorithm()) + Component.literal(NCRConfig.getEncryption().getAlgorithm().getName()) .withStyle(ChatFormatting.BOLD))).append(CommonComponents.NEW_LINE).append( Component.translatable("tag.nochatreports.encrypted_original", this.lastMessageOriginal)); @@ -61,11 +61,11 @@ public class MixinChatComponent { + "wrapComponents(Lnet/minecraft/network/chat/FormattedText;I" + "Lnet/minecraft/client/gui/Font;)Ljava/util/List;", ordinal = 0)) private FormattedText modifyGUIMessage(FormattedText msg) { - var optional = NCRConfig.getClient().chatEncryption(); + var optional = NCRConfig.getEncryption().getEncryptor(); if (optional.isEmpty()) return msg; - ChatEncryption encryption = optional.get(); + Encryptor<?> encryption = optional.get(); this.lastMessageOriginal = Component.Serializer.fromJson(Component.Serializer.toStableJson(((Component) msg))); ComponentContents contents = ((Component)msg).getContents(); diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java index 8ded5ab..64e594d 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java @@ -13,6 +13,7 @@ import com.aizistral.nochatreports.config.NCRConfig; import com.aizistral.nochatreports.config.NCRConfigClient; import com.aizistral.nochatreports.core.ServerSafetyLevel; import com.aizistral.nochatreports.core.ServerSafetyState; +import com.aizistral.nochatreports.gui.EncryptionConfigScreen; import com.aizistral.nochatreports.gui.EncryptionWarningScreen; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; @@ -55,7 +56,7 @@ public abstract class MixinChatScreen extends Screen { String message = info.getReturnValue(); if (!message.isEmpty() && !message.startsWith("/")) { - NCRConfig.getClient().chatEncryption().ifPresent(e -> + NCRConfig.getEncryption().getEncryptor().ifPresent(e -> info.setReturnValue(e.encrypt("#%" + message))); } } @@ -76,16 +77,30 @@ public abstract class MixinChatScreen extends Screen { this.addRenderableOnly(button); - button = new ImageButton(this.width - 48, this.height - 37, 20, 20, NCRConfig.getClient().enableChatEncryption() ? 0 : 20, + int xStart = !NCRConfig.getEncryption().isValid() ? 40 : (NCRConfig.getEncryption().isEnabled() ? 0 : 20); + + button = new ImageButton(this.width - 48, this.height - 37, 20, 20, xStart, 0, 20, ENCRYPTION_BUTTON, 64, 64, btn -> { - NCRConfig.getClient().toggleEncryption(); - ((ImageButton)btn).xTexStart = NCRConfig.getClient().enableChatEncryption() ? 0 : 20; - }, (btn, poseStack, i, j) -> - this.renderTooltip(poseStack, this.minecraft.font.split( - Component.translatable("gui.nochatreports.encryption_tooltip", Language.getInstance() - .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getClient() - .enableChatEncryption() ? "on" : "off")), 250), 250), i, j), - Component.empty()) { + if (NCRConfig.getEncryption().isValid()) { + NCRConfig.getEncryption().toggleEncryption(); + ((ImageButton)btn).xTexStart = NCRConfig.getEncryption().isEnabledAndValid() ? 0 : 20; + } else { + MixinChatScreen.this.openEncryptionConfig(); + } + }, (btn, poseStack, i, j) -> { + if (NCRConfig.getEncryption().isValid()) { + this.renderTooltip(poseStack, this.minecraft.font.split( + Component.translatable("gui.nochatreports.encryption_tooltip", Language.getInstance() + .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getEncryption() + .isEnabledAndValid() ? "on" : "off")), 250), 250), i, j); + } else { + this.renderTooltip(poseStack, this.minecraft.font.split( + Component.translatable("gui.nochatreports.encryption_tooltip_invalid", Language.getInstance() + .getOrDefault("gui.nochatreports.encryption_state_" + (NCRConfig.getEncryption() + .isEnabledAndValid() ? "on" : "off")), 250), 250), i, j); + + } + }, Component.empty()) { @Override public boolean mouseClicked(double x, double y, int i) { @@ -94,7 +109,7 @@ public abstract class MixinChatScreen extends Screen { if (i == 1 && this.clicked(x, y)) { this.playDownSound(Minecraft.getInstance().getSoundManager()); - Minecraft.getInstance().setScreen(new EncryptionWarningScreen(MixinChatScreen.this)); + MixinChatScreen.this.openEncryptionConfig(); return true; } @@ -108,6 +123,14 @@ public abstract class MixinChatScreen extends Screen { this.addRenderableWidget(button); } + private void openEncryptionConfig() { + if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled()) { + Minecraft.getInstance().setScreen(new EncryptionWarningScreen(this)); + } else { + Minecraft.getInstance().setScreen(new EncryptionConfigScreen(this)); + } + } + private int getXOffset(ServerSafetyLevel level) { return switch (level) { case SECURE -> 21; |
