diff options
| author | Aizistral | 2022-10-28 23:28:51 +0200 |
|---|---|---|
| committer | Aizistral | 2022-10-28 23:28:51 +0200 |
| commit | b3933542bedd59a3c6c7cf064fa31bde18fbb3c6 (patch) | |
| tree | 664d8c9bcb97812020dcbffe41933dbbd4deb9ee /src/main/java | |
| parent | 36630841dde3db73881fd818107a25df52a35f0b (diff) | |
Restore parity with Fabric branch
Target version 1.19.2-v1.13.10, commit: https://github.com/Aizistral-Studios/No-Chat-Reports/commit/205917c003270449593ff3f1b7ad39b33381db4b
Diffstat (limited to 'src/main/java')
60 files changed, 3365 insertions, 476 deletions
diff --git a/src/main/java/com/aizistral/nochatreports/NoChatReports.java b/src/main/java/com/aizistral/nochatreports/NoChatReports.java index f597740..1d5f054 100644 --- a/src/main/java/com/aizistral/nochatreports/NoChatReports.java +++ b/src/main/java/com/aizistral/nochatreports/NoChatReports.java @@ -1,11 +1,12 @@ package com.aizistral.nochatreports; +import java.nio.charset.Charset; import java.util.function.Predicate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import com.aizistral.nochatreports.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; import net.minecraft.network.protocol.login.ServerboundHelloPacket; import net.minecraft.resources.ResourceLocation; @@ -26,6 +27,7 @@ import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.event.EventNetworkChannel; import net.minecraftforge.network.simple.SimpleChannel; +import net.minecraftforge.server.ServerLifecycleHooks; @Mod(NoChatReports.MODID) public class NoChatReports { @@ -37,6 +39,9 @@ public class NoChatReports { private static boolean detectedOnClient = false, detectedOnServer = false; public NoChatReports() { + LOGGER.info("KONNICHIWA ZA WARUDO!"); + LOGGER.info("Default JVM text encoding is: " + Charset.defaultCharset().displayName()); + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); @@ -44,8 +49,7 @@ public class NoChatReports { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onLoadComplete); MinecraftForge.EVENT_BUS.register(this); - - NoReportsConfig.loadConfig(); + NCRConfig.load(); } private void onLoadComplete(FMLLoadCompleteEvent event) { @@ -56,12 +60,18 @@ public class NoChatReports { channel = NetworkRegistry.ChannelBuilder.named(new ResourceLocation(MODID, "main")) .networkProtocolVersion(() -> PTC_VERSION) .clientAcceptedVersions(version -> { + if (!NCRConfig.getClient().enableMod()) + return true; + detectedOnServer = !isAbsentOrVanilla(version); - return NoReportsConfig.demandsOnServer() ? PTC_VERSION.equals(version) : true; + return NCRConfig.getClient().demandOnServer() ? PTC_VERSION.equals(version) : true; }) .serverAcceptedVersions(version -> { + if (ServerLifecycleHooks.getCurrentServer().isSingleplayer()) + return true; + detectedOnClient = !isAbsentOrVanilla(version); - return NoReportsConfig.demandsOnClient() ? PTC_VERSION.equals(version) : true; + return NCRConfig.getCommon().demandOnClient() ? PTC_VERSION.equals(version) : true; }) .simpleChannel(); } diff --git a/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java b/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java index a326a04..27cdb64 100644 --- a/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java +++ b/src/main/java/com/aizistral/nochatreports/NoChatReportsClient.java @@ -2,13 +2,16 @@ package com.aizistral.nochatreports; import java.util.List; -import com.aizistral.nochatreports.core.NoReportsConfig; +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.gui.AwaitConnectionScreen; import com.aizistral.nochatreports.gui.UnsafeServerScreen; import com.aizistral.nochatreports.mixins.client.AccessorDisconnectedScreen; import com.google.common.collect.ImmutableList; +import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.ConnectScreen; import net.minecraft.client.gui.screens.DisconnectedScreen; @@ -16,6 +19,7 @@ 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.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -33,6 +37,12 @@ public class NoChatReportsClient { "multiplayer.disconnect.invalid_public_key_signature", "multiplayer.disconnect.invalid_public_key" ); + private static final List<String> STRING_DISCONNECT_REASONS = ImmutableList.of( + "A secure profile is required to join this server.", + "Secure profile expired.", + "Secure profile invalid." + ); + private static final Component CONNECT_FAILED_NCR = Component.translatable("connect.failed"); private static boolean screenOverride = false; private NoChatReportsClient() { @@ -45,60 +55,113 @@ public class NoChatReportsClient { Minecraft client = Minecraft.getInstance(); Screen screen = event.getScreen(); + if (!NCRConfig.getClient().enableMod()) + return; + if (screen instanceof AccessorDisconnectedScreen dsc) { - if (screenOverride) + if (screenOverride || ServerSafetyState.isOnServer() || screen.getTitle() == CONNECT_FAILED_NCR) return; screenOverride = true; - if (dsc.getReason().getContents() instanceof TranslatableContents contents) { + var disconnectReason = dsc.getReason(); + + if (disconnectReason != null) { + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Disconnected with reason {}, reconnect count: {}", + Component.Serializer.toStableJson(disconnectReason), ServerSafetyState.getReconnectCount()); + } + if (ServerSafetyState.allowsUnsafeServer()) { screen = new DisconnectedScreen(new JoinMultiplayerScreen(new TitleScreen()), - CommonComponents.CONNECT_FAILED, dsc.getReason()); + CONNECT_FAILED_NCR, dsc.getReason()); client.setScreen(screen); screenOverride = false; return; - } else if (KEY_DISCONNECT_REASONS.contains(contents.getKey())) { - if (ServerSafetyState.getLastConnectedServer() != null) { - if (!NoReportsConfig.isWhitelistedServer(ServerSafetyState.getLastConnectedServer())) { + } else if (STRING_DISCONNECT_REASONS.contains(disconnectReason.getString()) + || (disconnectReason.getContents() instanceof TranslatableContents translatable && + KEY_DISCONNECT_REASONS.contains(translatable.getKey()))) { + if (ServerSafetyState.getLastServerAddress() != null) { + if (!NCRConfig.getServerWhitelist().isWhitelisted(ServerSafetyState.getLastServerAddress())) { + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Server {} evaluated as unsafe and is not whitelisted, displaying warning screen.", + ServerSafetyState.getLastServerAddress().getHost() + ":" + ServerSafetyState.getLastServerAddress().getPort()); + } + client.setScreen(new UnsafeServerScreen()); } else { + NCRConfig.getClient().updateSigningCheck(ServerSafetyState.getLastServerAddress()); + if (ServerSafetyState.getReconnectCount() <= 0) { ServerSafetyState.setAllowsUnsafeServer(true); - reconnectLastServer(); + client.setScreen(new AwaitConnectionScreen(new JoinMultiplayerScreen(new TitleScreen()))); + screenOverride = false; + return; } else { ServerSafetyState.setReconnectCount(0); + screenOverride = false; + return; } } } } } screenOverride = false; + } else if (screen instanceof JoinMultiplayerScreen) { + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Initialized JoinMultiplayerScreen screen, resetting safety state!"); + } + + ServerSafetyState.reset(); } } @OnlyIn(Dist.CLIENT) public static void onDisconnect(Minecraft client) { - client.execute(ServerSafetyState::reset); + if (!NCRConfig.getClient().enableMod()) + return; + + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Disconnected from server, resetting safety state!"); + } + + ServerSafetyState.reset(); + ServerSafetyState.setDisconnectMillis(Util.getMillis()); } @SubscribeEvent @OnlyIn(Dist.CLIENT) - public static void onJoin(ClientPlayerNetworkEvent.LoggingIn event) { + public static void onPlayReady(ClientPlayerNetworkEvent.LoggingIn event) { Minecraft client = Minecraft.getInstance(); + if (!NCRConfig.getClient().enableMod()) + return; + client.execute(() -> { ServerSafetyState.setReconnectCount(0); + ServerSafetyState.setOnServer(true); if (!client.isLocalServer()) { boolean canSend = NoChatReports.isDetectedOnServer(); - if (canSend) { + if (ServerSafetyState.getCurrent() == ServerSafetyLevel.REALMS) { + // NO-OP + } else if (canSend) { ServerSafetyState.updateCurrent(ServerSafetyLevel.SECURE); + } else if (ServerSafetyState.forceSignedMessages()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); } else { - ServerSafetyState.updateCurrent(ServerSafetyState.forceSignedMessages() ? - ServerSafetyLevel.INSECURE : ServerSafetyLevel.UNINTRUSIVE); + if (ServerSafetyState.getLastServerData() instanceof ServerDataExtension ext + && ext.preventsChatReports()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.SECURE); + } else { + ServerSafetyState.updateCurrent(ServerSafetyLevel.UNINTRUSIVE); + } } } + + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Sucessfully connected to server, safety state: {}, reconnect count reset.", ServerSafetyState.getCurrent()); + } }); } @@ -106,7 +169,7 @@ public class NoChatReportsClient { public static void reconnectLastServer() { ServerSafetyState.setReconnectCount(ServerSafetyState.getReconnectCount() + 1); ConnectScreen.startConnecting(new JoinMultiplayerScreen(new TitleScreen()), Minecraft.getInstance(), - ServerSafetyState.getLastConnectedServer(), null); + ServerSafetyState.getLastServerAddress(), ServerSafetyState.getLastServerData()); } diff --git a/src/main/java/com/aizistral/nochatreports/config/JSONConfig.java b/src/main/java/com/aizistral/nochatreports/config/JSONConfig.java new file mode 100644 index 0000000..e92a067 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/JSONConfig.java @@ -0,0 +1,93 @@ +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.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import net.minecraftforge.fml.loading.FMLPaths; + +public abstract class JSONConfig { + protected static final Path CONFIG_DIR = FMLPaths.CONFIGDIR.get(); + protected static final Gson GSON = new GsonBuilder().setPrettyPrinting() + .setExclusionStrategies(new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getDeclaringClass() == JSONConfig.class; + } + + @Override + public boolean shouldSkipClass(Class<?> theClass) { + return false; + } + }).create(); + + 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 extends JSONConfig> T loadConfig(Class<T> configClass, Supplier<T> freshInstance, String fileName) { + NoChatReports.LOGGER.info("Reading config file {}...", fileName); + T config = readFile(fileName, configClass).orElseGet(freshInstance); + config.uponLoad(); + return config; + } + + private static <T extends JSONConfig> Optional<T> readFile(String fileName, Class<T> 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 (IOException ex) { + NoChatReports.LOGGER.fatal("Could not read config file: {}", file); + ex.printStackTrace(); + return null; + } + } + + private static <T> 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); + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java new file mode 100644 index 0000000..e87421d --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfig.java @@ -0,0 +1,89 @@ +package com.aizistral.nochatreports.config; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.function.Supplier; + +import javax.annotation.Nullable; + +import com.aizistral.nochatreports.NoChatReports; + +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.fml.loading.FMLEnvironment; + +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"); + } + + public static NCRConfigCommon getCommon() { + return checkLoaded(() -> common); + } + + @OnlyIn(Dist.CLIENT) + public static NCRConfigClient getClient() { + return checkLoaded(() -> client); + } + + @OnlyIn(Dist.CLIENT) + public static NCRServerWhitelist getServerWhitelist() { + return checkLoaded(() -> whitelist); + } + + @OnlyIn(Dist.CLIENT) + public static NCRConfigEncryption getEncryption() { + return checkLoaded(() -> encryption); + } + + private static <T extends JSONConfig> T checkLoaded(Supplier<T> config) { + if (config.get() == null) { + load(); + } + + return config.get(); + } + + public static void load() { + common = JSONConfig.loadConfig(NCRConfigCommon.class, NCRConfigCommon::new, NCRConfigCommon.FILE_NAME); + + if (FMLEnvironment.dist == Dist.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(); + } + + public static void save() { + checkLoaded(() -> common).saveFile(); + + if (FMLEnvironment.dist == Dist.CLIENT) { + checkLoaded(() -> client).saveFile(); + checkLoaded(() -> whitelist).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 new file mode 100644 index 0000000..9c4414c --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfigClient.java @@ -0,0 +1,253 @@ +package com.aizistral.nochatreports.config; + +import java.security.InvalidKeyException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.aizistral.nochatreports.core.ServerSafetyLevel; +import com.aizistral.nochatreports.encryption.AESCFB8Encryptor; +import com.aizistral.nochatreports.encryption.Encryptor; +import com.aizistral.nochatreports.gui.UnsafeServerScreen; + +import net.minecraft.Util; +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.util.StringUtil; + +public final class NCRConfigClient extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-Client.json"; + + protected boolean demandOnServer = false, showServerSafety = true, hideRedChatIndicators = true, + hideYellowChatIndicators = true, hideGrayChatIndicators = true, hideWarningToast = true, + alwaysHideReportButton = false, disableTelemetry = true, showReloadButton = true, + whitelistAllServers = false, verifiedIconEnabled = true, showNCRButton = true, + enableMod = true, skipRealmsWarning = false; + protected int verifiedIconOffsetX = 0, verifiedIconOffsetY = 0, reconnectAwaitSeconds = 4, + postDisconnectAwaitSeconds = 10, signingCheckDelaySeconds = 43200; + + protected Map<String, Long> serverSigningChecks = new HashMap<>(); + + 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.<br><br> + * + * 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.<br><br> + * + * This is true by default. + */ + + public boolean showServerSafety() { + return this.showServerSafety; + } + + /** + * @return True if vanilla's unsigned messages trust indicator should be removed.<br><br> + * + * This is true by default. + * + * @see MixinChatListener#onEvaluateTrustLevel + */ + + public boolean hideRedChatIndicators() { + return this.hideRedChatIndicators; + } + + /** + * @return True if vanilla's modified/hidden messages trust indicator should be removed.<br><br> + * + * This is true by default. + * + * @see MixinChatListener#onEvaluateTrustLevel + */ + + public boolean hideYellowChatIndicators() { + return this.hideYellowChatIndicators; + } + + /** + * @return True if vanilla's system messages trust indicator should be removed.<br><br> + * + * This is true by default. + * + * @see com.aizistral.nochatreports.mixins.client.MixinGuiMessageTag#onSystem + */ + + public boolean hideGrayChatIndicators() { + return this.hideGrayChatIndicators; + } + + /** + * @return True if "Chat messages can't be verified" toast should be removed.<br><br> + * + * 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.<br><br> + * + * This is false by default. + */ + + public boolean alwaysHideReportButton() { + return this.alwaysHideReportButton; + } + + /** + * @return True if sending telemetry to Mojang should be disabled.<br><br> + * + * This is true by default. + */ + + public boolean disableTelemetry() { + return this.disableTelemetry; + } + + /** + * @return True if the configuration reload button should be displayed in multiplayer screen. + * <br><br> + * + * This is true by default. + */ + + public boolean showReloadButton() { + return this.showReloadButton; + } + + /** + * @return True if the full-screen warning should be skipped for servers that require chat signing, + * letting users simply join the server. Because of that, servers will no longer be added to the + * whitelist.<br><br> + * + * This is false by default. + */ + + public boolean whitelistAllServers() { + return this.whitelistAllServers; + } + + /** + * @return True if "Safe Server" icon should be displayed in multiplayer menu for servers that + * declare themselves as preventing chat reports.<br><br> + * + * 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 How many seconds No Chat Reports should wait before attemting automatic reconnects. + * @see <a href="https://github.com/Aizistral-Studios/No-Chat-Reports/issues/190">Issue #190</a> + */ + + public int getReconnectAwaitSeconds() { + return this.reconnectAwaitSeconds; + } + + /** + * @return Same as <code>reconnectAwaitSeconds</code>, but countdown starts when user disconnects + * from server. If this delay is greater than <code>reconnectAwaitSeconds</code> then it will apply. + */ + + public int getPostDisconnectAwaitSeconds() { + return this.postDisconnectAwaitSeconds; + } + + /** + * @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 doSigningCheck(ServerAddress serverAddress) { + String server = serverAddress.getHost() + ":" + serverAddress.getPort(); + + if (!this.serverSigningChecks.containsKey(server)) + return true; + else + return Instant.now().getEpochSecond() - this.serverSigningChecks.get(server) >= this.signingCheckDelaySeconds; + } + + public void updateSigningCheck(ServerAddress serverAddress) { + String server = serverAddress.getHost() + ":" + serverAddress.getPort(); + this.serverSigningChecks.put(server, Instant.now().getEpochSecond()); + this.saveFile(); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java new file mode 100644 index 0000000..7aa0322 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfigCommon.java @@ -0,0 +1,79 @@ +package com.aizistral.nochatreports.config; + +import java.util.ArrayList; +import java.util.List; + +import com.google.common.base.Preconditions; + +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 = true, enableDebugLog = false, convertToGameMessage = false, + addQueryData = true; + + 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.<br><br> + * + * This is false by default. + */ + + public boolean demandOnClient() { + return this.demandOnClient; + } + + /** + * @return Disconnect message that should be shown to client if <code>demandOnClient</code> 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.<br><br> + * + * 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.<br><br> + * + * 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.<br><br> + * + * 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 new file mode 100644 index 0000000..9cf7671 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java @@ -0,0 +1,197 @@ +package com.aizistral.nochatreports.config; + +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import com.aizistral.nochatreports.encryption.AESCFB8Encryptor; +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.network.chat.Component; +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, encryptPublic = true, + showEncryptionButton = true, showEncryptionIndicators = true; + protected String encryptionKey = Encryption.AES_CFB8.getDefaultKey(), encryptionPassphrase = "", + algorithmName = Encryption.AES_CFB8.getName(); + protected List<String> 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<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/config/NCRServerWhitelist.java b/src/main/java/com/aizistral/nochatreports/config/NCRServerWhitelist.java new file mode 100644 index 0000000..5d36cf5 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/config/NCRServerWhitelist.java @@ -0,0 +1,49 @@ +package com.aizistral.nochatreports.config; + +import java.util.ArrayList; +import java.util.List; + +import com.aizistral.nochatreports.gui.UnsafeServerScreen; + +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +public class NCRServerWhitelist extends JSONConfig { + protected static final String FILE_NAME = "NoChatReports/NCR-ServerWhitelist.json"; + protected static final List<String> DEFAULT_WHITELISTED_SERVERS = new ArrayList<>(); + protected List<String> whitelistedServers = DEFAULT_WHITELISTED_SERVERS; + + protected NCRServerWhitelist() { + super(FILE_NAME); + } + + @Override + public NCRServerWhitelist getDefault() { + return new NCRServerWhitelist(); + } + + /** + * @return Current list of whitelisted unsafe servers. Used on client to remember which servers + * user disabled unsafety warnings for.<br><br> + * + * This is empty by default. + * + * @see UnsafeServerScreen + */ + + public List<String> getList() { + return this.whitelistedServers; + } + + /** + * @param address Address of the server to be check. + * @return Whether this server is in the whitelist of unsafe servers, as returned by + * {@link #getList()}. + * @see UnsafeServerScreen + */ + + public boolean isWhitelisted(ServerAddress address) { + return NCRConfig.getClient().whitelistAllServers() || + this.getList().contains(address.getHost() + ":" + address.getPort()); + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java b/src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java new file mode 100644 index 0000000..6eecd07 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/core/EncryptionUtil.java @@ -0,0 +1,86 @@ +package com.aizistral.nochatreports.core; + +import java.util.Optional; + +import javax.annotation.Nullable; + +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; + +public class EncryptionUtil { + + public static Optional<Component> 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(); + boolean decryptedSomething = false; + + if (contents instanceof TranslatableContents translatable) { + for (Object arg : translatable.args) { + if (arg instanceof MutableComponent mutable + && mutable.getContents() instanceof LiteralContents literal) { + var decrypted = tryDecrypt(literal.text(), encryption); + if (decrypted.isPresent()) { + mutable.contents = new LiteralContents(decrypted.get()); + decryptedSomething = true; + } + } + } + } else { + decryptedSomething = tryDecrypt(copy, encryption); + } + + return Optional.ofNullable(decryptedSomething ? 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; + } + } + + return decryptedSiblings; + } + + public static Optional<String> 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/NoReportsConfig.java b/src/main/java/com/aizistral/nochatreports/core/NoReportsConfig.java deleted file mode 100644 index 4fda0d6..0000000 --- a/src/main/java/com/aizistral/nochatreports/core/NoReportsConfig.java +++ /dev/null @@ -1,283 +0,0 @@ -package com.aizistral.nochatreports.core; - -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.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - -import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.gui.UnsafeServerScreen; -import com.aizistral.nochatreports.mixins.client.MixinChatListener; -import com.aizistral.nochatreports.mixins.client.MixinToastComponent; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; -import com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService; - -import net.minecraft.client.multiplayer.chat.ChatTrustLevel; -import net.minecraft.client.multiplayer.resolver.ServerAddress; -import net.minecraft.util.Tuple; -import net.minecraftforge.fml.loading.FMLPaths; - -/** - * Simple implementation of JSON-config for the mod. Can be loaded at any time and does not depend - * on modloader-specific API. The only disadvantage is that we don't get to comment options.<br><br> - * - * For now, the config file is called <code>NoChatReports.json</code> and is located in default config - * folder. In the future this should be separated into client and server configs. - * - * @author Aizistral - */ - -public class NoReportsConfig { - private static final Path CONFIG_FILE = FMLPaths.CONFIGDIR.get().resolve("NoChatReports.json"); - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - private static NoReportsConfig INSTANCE; - private boolean demandOnClient = true, demandOnServer = false, enableDebugLog = false, - convertToGameMessage = false, showServerSafety = true, hideRedChatIndicators = true, - hideYellowChatIndicators = true, hideGrayChatIndicators = true, hideWarningToast = true, - alwaysHideReportButton = false, disableTelemetry = true, showReloadButton = true, - whitelistAllServers = false; - private List<String> whitelistedServers; - - private static NoReportsConfig getInstance() { - if (INSTANCE == null) { - loadConfig(); - } - - return INSTANCE; - } - - /** - * Loads (or reloads) the config from local file, or creates default one if that fails. - * Re-searializes validated {@link #INSTANCE} object back into the file. - */ - - public static void loadConfig() { - NoChatReports.LOGGER.info(INSTANCE == null ? "Loading config..." : "Reloading config..."); - - INSTANCE = readFile(); - - if (INSTANCE == null) { - INSTANCE = new NoReportsConfig(); - } - - if (INSTANCE.whitelistedServers == null) { - INSTANCE.whitelistedServers = new ArrayList<>(); - } - - writeFile(INSTANCE); - } - - /** - * Writes current config instance into local file. - */ - - public static void saveConfig() { - if (INSTANCE != null) { - writeFile(INSTANCE); - } - } - - @Nullable - private static NoReportsConfig readFile() { - if (!Files.isRegularFile(CONFIG_FILE)) - return null; - - try (BufferedReader reader = Files.newBufferedReader(CONFIG_FILE)) { - return GSON.fromJson(reader, NoReportsConfig.class); - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } - - private static void writeFile(NoReportsConfig instance) { - try (BufferedWriter writer = Files.newBufferedWriter(CONFIG_FILE)) { - GSON.toJson(instance, writer); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - /** - * @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.<br><br> - * - * This is false by default. - */ - - public static boolean demandsOnClient() { - return getInstance().demandOnClient; - } - - /** - * @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.<br><br> - * - * This is false by default. - */ - - public static boolean demandsOnServer() { - return getInstance().demandOnServer; - } - - /** - * @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.<br><br> - * - * This is false by default. - */ - - public static boolean convertToGameMessage() { - return getInstance().convertToGameMessage; - } - - /** - * @return True if current {@link ServerSafetyLevel} should be indicated on client by an icon in - * the bottom-right corner of chat screen.<br><br> - * - * This is true by default. - */ - - public static boolean showServerSafety() { - return getInstance().showServerSafety; - } - - /** - * @return Current list of whitelisted unsafe servers. Used on client to remember which servers - * user disabled unsafety warnings for.<br><br> - * - * This is empty by default. - * - * @see UnsafeServerScreen - */ - - public static List<String> getWhitelistedServers() { - return getInstance().whitelistedServers; - } - - /** - * @param address Address of the server to be check. - * @return Whether this server is in the whitelist of unsafe servers, as returned by - * {@link #getWhitelistedServers()}. - * @see UnsafeServerScreen - */ - - public static boolean isWhitelistedServer(ServerAddress address) { - return getWhitelistedServers().contains(address.getHost() + ":" + address.getPort()); - } - - /** - * @return True if vanilla's unsigned messages trust indicator should be removed.<br><br> - * - * This is true by default. - * - * @see MixinChatListener#onEvaluateTrustLevel - */ - - public static boolean hideRedChatIndicators() { - return getInstance().hideRedChatIndicators; - } - - /** - * @return True if vanilla's modified/hidden messages trust indicator should be removed.<br><br> - * - * This is true by default. - * - * @see MixinChatListener#onEvaluateTrustLevel - */ - - public static boolean hideYellowChatIndicators() { - return getInstance().hideYellowChatIndicators; - } - - /** - * @return True if vanilla's system messages trust indicator should be removed.<br><br> - * - * This is true by default. - * - * @see com.aizistral.nochatreports.mixins.client.MixinGuiMessageTag#onSystem - */ - - public static boolean hideGrayChatIndicators() { - return getInstance().hideGrayChatIndicators; - } - - /** - * @return True if "Chat messages can't be verified" toast should be removed.<br><br> - * - * This is true by default. - * - * @see MixinToastComponent#onAddToast - */ - - public static boolean hideWarningToast() { - return getInstance().hideWarningToast; - } - - /** - * @return True if mod should log some additional information about its activity and message - * signatures. Generally only useful for debugging.<br><br> - * - * This is false by default. - */ - - public static boolean isDebugLogEnabled() { - return getInstance().enableDebugLog; - } - - /** - * @return True if reporting buttons should always be hidden from social interactions screen, - * instead of simply being disabled.<br><br> - * - * This is false by default. - */ - - public static boolean alwaysHideReportButton() { - return getInstance().alwaysHideReportButton; - } - - /** - * @return True if sending telemetry to Mojang should be disabled.<br><br> - * - * This is true by default. - */ - - public static boolean disableTelemetry() { - return getInstance().disableTelemetry; - } - - /** - * @return True if the configuration reload button should be displayed in multiplayer screen. - * <br><br> - * - * This is true by default. - */ - - public static boolean showReloadButton() { - return getInstance().showReloadButton; - } - - /** - * @return True if the full-screen warning should be skipped for servers that require chat signing, - * letting users simply join the server. Because of that, servers will no longer be added to the whitelist. - * <br><br> - * - * This is false by default. - */ - - public static boolean whitelistAllServers() { - return getInstance().whitelistAllServers; - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java b/src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java new file mode 100644 index 0000000..4841830 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/core/ServerDataExtension.java @@ -0,0 +1,20 @@ +package com.aizistral.nochatreports.core; + +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 index dba4038..9af7e04 100644 --- a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyLevel.java +++ b/src/main/java/com/aizistral/nochatreports/core/ServerSafetyLevel.java @@ -1,8 +1,7 @@ package com.aizistral.nochatreports.core; -import com.aizistral.nochatreports.NoChatReports; +import com.aizistral.nochatreports.config.NCRConfig; -import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.network.chat.Component; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -39,15 +38,29 @@ public enum ServerSafetyLevel { 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. */ - UNKNOWN; + UNDEFINED; @OnlyIn(Dist.CLIENT) public Component getTooltip() { - if(NoReportsConfig.whitelistAllServers() && this.equals(ServerSafetyLevel.INSECURE)) + if (NCRConfig.getClient().whitelistAllServers() && this.equals(ServerSafetyLevel.INSECURE)) return Component.translatable("gui.nochatreports.status_insecure_whitelist_all_servers"); - return Component.translatable("gui.nochatreports.status_" + this.name().toLowerCase()); + else + return Component.translatable("gui.nochatreports.status_" + this.name().toLowerCase()); } + } diff --git a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java b/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java index f7a0658..99e5f4a 100644 --- a/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java +++ b/src/main/java/com/aizistral/nochatreports/core/ServerSafetyState.java @@ -1,10 +1,14 @@ package com.aizistral.nochatreports.core; -import java.util.HashMap; -import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; +import com.aizistral.nochatreports.NoChatReports; +import com.aizistral.nochatreports.config.NCRConfig; + import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.multiplayer.resolver.ServerAddress; import net.minecraftforge.api.distmarker.Dist; @@ -16,11 +20,14 @@ import net.minecraftforge.api.distmarker.OnlyIn; */ @OnlyIn(Dist.CLIENT) -public class ServerSafetyState { - private static ServerSafetyLevel current = ServerSafetyLevel.UNKNOWN; - private static ServerAddress lastConnectedServer = null; - private static boolean allowUnsafeServer = false, sessionRequestedKey = false; - private static int reconnectCount = 0; +public final class ServerSafetyState { + private static ServerSafetyLevel current = ServerSafetyLevel.UNDEFINED; + private static ServerAddress lastServerAddress = null; + private static ServerData lastServerData = null; + private static AtomicBoolean allowUnsafeServer = new AtomicBoolean(false), + sessionRequestedKey = new AtomicBoolean(false), isOnServer = new AtomicBoolean(false); + private static AtomicInteger reconnectCount = new AtomicInteger(0); + private static AtomicLong disconnectMillis = new AtomicLong(0); public static void updateCurrent(ServerSafetyLevel level) { current = level; @@ -31,19 +38,24 @@ public class ServerSafetyState { } public static boolean allowsUnsafeServer() { - return current != ServerSafetyLevel.SECURE ? allowUnsafeServer : false; + return current != ServerSafetyLevel.SECURE ? allowUnsafeServer.get() : false; } public static void setAllowsUnsafeServer(boolean allows) { - allowUnsafeServer = allows; + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Set allowUnsafeServer to: " + allows + ", value set in stacktrace:"); + NoChatReports.LOGGER.catching(new RuntimeException().fillInStackTrace()); + } + + allowUnsafeServer.set(allows); } public static void setSessionRequestedKey(boolean requested) { - sessionRequestedKey = requested; + sessionRequestedKey.set(requested); } public static boolean sessionRequestedKey() { - return current != ServerSafetyLevel.SECURE ? sessionRequestedKey : false; + return current != ServerSafetyLevel.SECURE ? sessionRequestedKey.get() : false; } public static boolean forceSignedMessages() { @@ -51,25 +63,53 @@ public class ServerSafetyState { } @Nullable - public static ServerAddress getLastConnectedServer() { - return lastConnectedServer; + public static ServerAddress getLastServerAddress() { + return lastServerAddress; } - public static void setLastConnectedServer(@Nullable ServerAddress address) { - lastConnectedServer = address; + @Nullable + public static ServerData getLastServerData() { + return lastServerData; + } + + public static void setLastConnectedServer(@Nullable ServerAddress address, @Nullable ServerData data) { + lastServerAddress = address; + lastServerData = data; } public static int getReconnectCount() { - return reconnectCount; + return reconnectCount.get(); } public static void setReconnectCount(int count) { - reconnectCount = count; + reconnectCount.set(count); + } + + public static long getDisconnectMillis() { + return disconnectMillis.get(); + } + + public static void setDisconnectMillis(long millis) { + disconnectMillis.set(millis); + } + + public static boolean isOnServer() { + return isOnServer.get(); + } + + public static void setOnServer(boolean on) { + isOnServer.set(on); } public static void reset() { - current = ServerSafetyLevel.UNKNOWN; - allowUnsafeServer = sessionRequestedKey = false; + current = ServerSafetyLevel.UNDEFINED; + allowUnsafeServer.set(false); + sessionRequestedKey.set(false); + isOnServer.set(false); + + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("allowUnsafeServer: {}", allowUnsafeServer.get()); + } } } diff --git a/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java b/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java new file mode 100644 index 0000000..77adf4c --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryption.java @@ -0,0 +1,40 @@ +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 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 new file mode 100644 index 0000000..5b32891 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESCFB8Encryptor.java @@ -0,0 +1,58 @@ +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.security.spec.AlgorithmParameterSpec; +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 net.minecraft.util.Tuple; + +import static com.aizistral.nochatreports.encryption.Encryption.*; +import static javax.crypto.Cipher.*; + +public class AESCFB8Encryptor extends AESEncryptor<AESCFB8Encryption> { + + 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<AlgorithmParameterSpec, byte[]> 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<AlgorithmParameterSpec, byte[]> 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 new file mode 100644 index 0000000..359d509 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryption.java @@ -0,0 +1,25 @@ +package com.aizistral.nochatreports.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/encryption/AESECBEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryptor.java new file mode 100644 index 0000000..bffc960 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESECBEncryptor.java @@ -0,0 +1,33 @@ +package com.aizistral.nochatreports.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 AESECBEncryptor extends AESEncryptor<AESECBEncryption> { + + 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<AlgorithmParameterSpec, byte[]> generateIV() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + protected Tuple<AlgorithmParameterSpec, byte[]> 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 new file mode 100644 index 0000000..f7c53cd --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryption.java @@ -0,0 +1,96 @@ +package com.aizistral.nochatreports.encryption; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Optional; +import java.util.Random; + +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; +import net.minecraft.util.Tuple; + +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 new file mode 100644 index 0000000..d7ec841 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESEncryptor.java @@ -0,0 +1,121 @@ +package com.aizistral.nochatreports.encryption; + +import static com.aizistral.nochatreports.encryption.Encryption.AES_CFB8; +import static com.aizistral.nochatreports.encryption.Encryption.BASE64_DECODER; +import static com.aizistral.nochatreports.encryption.Encryption.BASE64_ENCODER; +import static javax.crypto.Cipher.DECRYPT_MODE; +import static javax.crypto.Cipher.ENCRYPT_MODE; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Random; + +import javax.annotation.Nullable; +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.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import net.minecraft.SharedConstants; +import net.minecraft.util.Tuple; + +public abstract class AESEncryptor<T extends AESEncryption> extends Encryptor<T> { + 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<AlgorithmParameterSpec, byte[]> generateIV() throws UnsupportedOperationException; + + protected abstract Tuple<AlgorithmParameterSpec, byte[]> 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 new file mode 100644 index 0000000..f50ec85 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryption.java @@ -0,0 +1,25 @@ +package com.aizistral.nochatreports.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/encryption/AESGCMEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryptor.java new file mode 100644 index 0000000..3d11a36 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/AESGCMEncryptor.java @@ -0,0 +1,38 @@ +package com.aizistral.nochatreports.encryption; + +import java.nio.ByteBuffer; +import java.security.InvalidKeyException; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; + +import net.minecraft.util.Tuple; + +public class AESGCMEncryptor extends AESEncryptor<AESGCMEncryption> { + + 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<AlgorithmParameterSpec, byte[]> generateIV() throws UnsupportedOperationException { + byte[] iv = new byte[12]; + RANDOM.nextBytes(iv); + return new Tuple<>(new GCMParameterSpec(96, iv), iv); + } + + @Override + protected Tuple<AlgorithmParameterSpec, byte[]> 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 new file mode 100644 index 0000000..16536bc --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryption.java @@ -0,0 +1,56 @@ +package com.aizistral.nochatreports.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/encryption/CaesarEncryptor.java b/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryptor.java new file mode 100644 index 0000000..8ed8cfe --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/CaesarEncryptor.java @@ -0,0 +1,74 @@ +package com.aizistral.nochatreports.encryption; + +import java.security.InvalidKeyException; + +import com.aizistral.nochatreports.NoChatReports; + +import net.minecraft.SharedConstants; + +public class CaesarEncryptor extends Encryptor<CaesarEncryption> { + 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 new file mode 100644 index 0000000..826f521 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/Encryption.java @@ -0,0 +1,60 @@ +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 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<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..c257aff --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/encryption/Encryptor.java @@ -0,0 +1,186 @@ +package com.aizistral.nochatreports.encryption; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Map; + +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<T extends Encryption> { + 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/gui/AwaitConnectionScreen.java b/src/main/java/com/aizistral/nochatreports/gui/AwaitConnectionScreen.java new file mode 100644 index 0000000..0727c00 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/AwaitConnectionScreen.java @@ -0,0 +1,82 @@ +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.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.Util; +import net.minecraft.client.GameNarrator; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.ConnectScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +public class AwaitConnectionScreen extends Screen { + private final Screen parent; + private boolean aborted = false; + private long millisAwaiting = 0; + + public AwaitConnectionScreen(Screen parent) { + super(GameNarrator.NO_TITLE); + this.parent = parent; + } + + @Override + protected void init() { + this.clearWidgets(); + this.millisAwaiting = Util.getMillis(); + + this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120 + 12, 200, 20, CommonComponents.GUI_CANCEL, button -> { + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Aborted reconnect await!"); + } + + this.aborted = true; + this.minecraft.setScreen(this.parent); + ServerSafetyState.reset(); + })); + } + + @Override + public void tick() { + if (!this.aborted) + if (this.getRemainingTime() <= 0) { + this.aborted = true; + NoChatReportsClient.reconnectLastServer(); + } + } + + @Override + public void render(PoseStack poseStack, int i, int j, float f) { + this.renderBackground(poseStack); + Component status = Component.translatable("nochatreports.connect.await", (this.getRemainingTime()) / 1000L); + ConnectScreen.drawCenteredString(poseStack, this.font, Component.translatable("nochatreports.connect.nokey_rejected"), this.width / 2, this.height / 2 - 50, 0xFFFFFF); + ConnectScreen.drawCenteredString(poseStack, this.font, status, this.width / 2, this.height / 2 - 36, 0xFFFFFF); + super.render(poseStack, i, j, f); + } + + private long getRemainingTime() { + long current = Util.getMillis(); + long disconnect = ServerSafetyState.getDisconnectMillis(); + + if (current - disconnect <= this.getDisconnectAwaitTime() + 100L) + return this.getDisconnectAwaitTime() - (current - disconnect); + else + return this.getAwaitTime() - (current - this.millisAwaiting); + } + + private long getDisconnectAwaitTime() { + return NCRConfig.getClient().getPostDisconnectAwaitSeconds() * 1000L; + } + + private long getAwaitTime() { + return NCRConfig.getClient().getReconnectAwaitSeconds() * 1000L; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java b/src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java new file mode 100644 index 0000000..ad58e59 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/EncryptionButton.java @@ -0,0 +1,45 @@ +package com.aizistral.nochatreports.gui; + +import com.aizistral.nochatreports.config.NCRConfig; + +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 ImageButton { + private final Screen parent; + + public EncryptionButton(int x, int y, int xSize, int ySize, int xTexStart, int yTexStart, int yStateDiff, + ResourceLocation texture, int textureWidth, int textureHeight, OnPress onPress, OnTooltip onTooltip, + Component name, Screen parent) { + super(x, y, xSize, ySize, xTexStart, yTexStart, yStateDiff, texture, textureWidth, textureHeight, onPress, + onTooltip, name); + this.parent = 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 new file mode 100644 index 0000000..0776b23 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java @@ -0,0 +1,301 @@ +package com.aizistral.nochatreports.gui; + +import java.util.List; +import java.util.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.minecraft.ChatFormatting; +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.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; +import net.minecraft.network.chat.CommonComponents; +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; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +@OnlyIn(Dist.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<Encryption> 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.minecraft.keyboardHandler.setSendRepeatsToGui(true); + 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 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 + (this.hugeGUI() ? -3 : 13), 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); + + int checkWidth = this.font.width(ENCRYPT_PUBLIC); + this.encryptPublicCheck = new Checkbox(this.width / 2 - checkWidth / 2 - 8, this.passField.y + 24, checkWidth + 24, 20, + ENCRYPT_PUBLIC, NCRConfig.getEncryption().shouldEncryptPublic()); + this.addRenderableWidget(this.encryptPublicCheck); + + this.addRenderableWidget(new Button(this.width / 2 + 4, this.passField.y + 48, 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", + Component.translatable("algorithm.nochatreports." + value.getID() + ".name")); + }).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 + 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.x - 20, (this.hugeGUI() ? 25 : 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() + (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.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); + } + } + + 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.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()); + 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 new file mode 100644 index 0000000..9b21101 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/EncryptionWarningScreen.java @@ -0,0 +1,60 @@ +package com.aizistral.nochatreports.gui; + +import org.jetbrains.annotations.Nullable; + +import com.aizistral.nochatreports.NoChatReportsClient; +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.core.ServerSafetyState; +import com.mojang.blaze3d.vertex.PoseStack; + +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.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.client.gui.screens.TitleScreen; +import net.minecraft.client.gui.screens.inventory.CommandBlockEditScreen; +import net.minecraft.client.gui.screens.multiplayer.WarningScreen; +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + + +@OnlyIn(Dist.CLIENT) +public class EncryptionWarningScreen extends ExtendedWarningScreen { + 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/ExtendedWarningScreen.java b/src/main/java/com/aizistral/nochatreports/gui/ExtendedWarningScreen.java new file mode 100644 index 0000000..39a7b86 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/ExtendedWarningScreen.java @@ -0,0 +1,97 @@ +package com.aizistral.nochatreports.gui; + +import com.aizistral.nochatreports.config.NCRConfig; +import com.mojang.blaze3d.vertex.PoseStack; + +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.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 ExtendedWarningScreen extends Screen { + private final Component TITLE; + private final Component CONTENT; + private final Component CHECK; + private final Component NARRATION; + private final String WIKI_LINK; + protected final Screen previous; + protected MultiLineLabel message = MultiLineLabel.EMPTY; + protected Checkbox stopShowing = null; + + public ExtendedWarningScreen(Component title, Component content, Component check, String wikiLink, Screen previous) { + super(title); + this.TITLE = title; + this.CONTENT = content; + this.CHECK = check; + this.WIKI_LINK = wikiLink; + 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); + 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); + } + + private void initButtons(int i) { + int offset = 28; + int buttonY = this.hugeGUI() ? 55 : 100; + + this.addRenderableWidget(new Button(this.width / 2 - 260 + offset, buttonY + i, 150, 20, CommonComponents.GUI_PROCEED, this::onProceed)); + this.addRenderableWidget(new Button(this.width / 2 - 100 + offset, buttonY + i, 150, 20, Component.translatable("gui.nochatreports.encryption_warning.learn_more"), button -> { + Minecraft.getInstance().setScreen(new ConfirmLinkScreen(agree -> { + if (agree) { + Util.getPlatform().openUri(this.WIKI_LINK); + } + + Minecraft.getInstance().setScreen(this); + }, this.WIKI_LINK, true)); + })); + this.addRenderableWidget(new Button(this.width / 2 + 60 + offset, buttonY + i, 150, 20, CommonComponents.GUI_BACK, this::onBack)); + } + + protected abstract void onProceed(Button button); + + protected abstract void onBack(Button button); + + @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; + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/gui/FontHelper.java b/src/main/java/com/aizistral/nochatreports/gui/FontHelper.java new file mode 100644 index 0000000..84f11b4 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/FontHelper.java @@ -0,0 +1,153 @@ +package com.aizistral.nochatreports.gui; + +import java.util.Arrays; +import java.util.List; + +import net.minecraft.client.gui.Font; +import net.minecraft.util.FormattedCharSequence; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +/** + * I couldn't find a way to properly convert {@link FormattedCharSequence} back into + * normal string. Lol. + * + * @author Aizistral + */ + + +@OnlyIn(Dist.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<String> 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/RealmsWarningScreen.java b/src/main/java/com/aizistral/nochatreports/gui/RealmsWarningScreen.java new file mode 100644 index 0000000..29f4d5d --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/gui/RealmsWarningScreen.java @@ -0,0 +1,50 @@ +package com.aizistral.nochatreports.gui; + +import org.jetbrains.annotations.Nullable; + +import com.aizistral.nochatreports.config.NCRConfig; + +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.ConfirmLinkScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.client.gui.screens.multiplayer.WarningScreen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; + +public class RealmsWarningScreen extends ExtendedWarningScreen { + 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/UnsafeServerScreen.java b/src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java index 9780e41..e568231 100644 --- a/src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java +++ b/src/main/java/com/aizistral/nochatreports/gui/UnsafeServerScreen.java @@ -1,19 +1,16 @@ package com.aizistral.nochatreports.gui; -import javax.print.attribute.standard.MediaSize.NA; - +import com.aizistral.nochatreports.NoChatReports; import com.aizistral.nochatreports.NoChatReportsClient; -import com.aizistral.nochatreports.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; import com.aizistral.nochatreports.core.ServerSafetyState; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.screens.ConnectScreen; 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.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; @@ -32,7 +29,7 @@ import net.minecraftforge.api.distmarker.OnlyIn; */ @OnlyIn(Dist.CLIENT) -public class UnsafeServerScreen extends WarningScreen { +public final class UnsafeServerScreen extends WarningScreen { private static final Component TITLE = Component.translatable("gui.nochatreports.unsafe_server.header").withStyle(ChatFormatting.BOLD); private static final Component CONTENT = Component.translatable("gui.nochatreports.unsafe_server.contents"); private static final Component CHECK = Component.translatable("gui.nochatreports.unsafe_server.check"); @@ -48,16 +45,21 @@ public class UnsafeServerScreen extends WarningScreen { @Override protected void initButtons(int i) { this.addRenderableWidget(new Button(this.width / 2 - 155, 100 + i, 150, 20, CommonComponents.GUI_PROCEED, button -> { - ServerAddress address = ServerSafetyState.getLastConnectedServer(); + ServerAddress address = ServerSafetyState.getLastServerAddress(); if (address != null) { if (this.stopShowing.selected()) { - NoReportsConfig.getWhitelistedServers().add(address.getHost() + ":" + address.getPort()); - NoReportsConfig.saveConfig(); + NCRConfig.getServerWhitelist().getList().add(address.getHost() + ":" + address.getPort()); + NCRConfig.getServerWhitelist().saveFile(); + } + + if (NCRConfig.getCommon().enableDebugLog()) { + NoChatReports.LOGGER.info("Proceeding with unsafe connection to {}, added to whitelist: {}", + address.getHost() + ":" + address.getPort(), this.stopShowing.selected()); } ServerSafetyState.setAllowsUnsafeServer(true); - NoChatReportsClient.reconnectLastServer(); + this.minecraft.setScreen(new AwaitConnectionScreen(this.joinMultiplayer)); } })); this.addRenderableWidget(new Button(this.width / 2 - 155 + 160, 100 + i, 150, 20, CommonComponents.GUI_BACK, button -> { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java new file mode 100644 index 0000000..cad93cd --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java @@ -0,0 +1,84 @@ +package com.aizistral.nochatreports.mixins.client; + +import javax.annotation.Nullable; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyArgs; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.At.Shift; + +import com.aizistral.nochatreports.NoChatReports; +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.config.NCRConfigClient; +import com.aizistral.nochatreports.core.EncryptionUtil; +import com.aizistral.nochatreports.encryption.Encryptor; + +import net.minecraft.ChatFormatting; +import net.minecraft.client.GuiMessage; +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.ComponentContents; +import net.minecraft.network.chat.FormattedText; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.contents.LiteralContents; +import net.minecraft.network.chat.contents.TranslatableContents; + +@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 index 654d44a..3cbd89a 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatListener.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatListener.java @@ -8,12 +8,15 @@ 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.ModifyVariable; +import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.core.EncryptionUtil; +import net.minecraft.client.GuiMessageTag; import net.minecraft.client.multiplayer.PlayerInfo; import net.minecraft.client.multiplayer.chat.ChatListener; import net.minecraft.client.multiplayer.chat.ChatTrustLevel; @@ -49,16 +52,16 @@ public class MixinChatListener { return; } - if (evaluate == ChatTrustLevel.NOT_SECURE && NoReportsConfig.hideRedChatIndicators()) { + if (evaluate == ChatTrustLevel.NOT_SECURE && NCRConfig.getClient().hideRedChatIndicators()) { info.setReturnValue(ChatTrustLevel.SECURE); } else if ((evaluate == ChatTrustLevel.FILTERED || evaluate == ChatTrustLevel.MODIFIED) - && NoReportsConfig.hideYellowChatIndicators()) { + && NCRConfig.getClient().hideYellowChatIndicators()) { info.setReturnValue(ChatTrustLevel.SECURE); } } // Debug never dies - if (NoReportsConfig.isDebugLogEnabled()) { + if (NCRConfig.getCommon().enableDebugLog()) { NoChatReports.LOGGER.info("Received message: {}, from: {}, signature: {}", Component.Serializer.toStableJson(playerChatMessage.serverContent()), playerChatMessage.signer().profileId(), @@ -66,4 +69,10 @@ public class MixinChatListener { } } + @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 index aecaaec..6b3d0f5 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatOptionsScreen.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatOptionsScreen.java @@ -1,6 +1,13 @@ package com.aizistral.nochatreports.mixins.client; +import java.util.List; + +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; @@ -10,10 +17,6 @@ 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; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.List; @Mixin(ChatOptionsScreen.class) public class MixinChatOptionsScreen extends SimpleOptionsSubScreen { @@ -41,6 +44,10 @@ public class MixinChatOptionsScreen extends SimpleOptionsSubScreen { @Override protected void init() { super.init(); + + if (!NCRConfig.getClient().enableMod()) + return; + this.secureChatTooltip = Minecraft.getInstance().font.split(Component.translatable("gui.nochatreport.secureChat"), 200); this.onlyShowSecureChat = this.list.findOption(Minecraft.getInstance().options.onlyShowSecureChat()); @@ -58,8 +65,12 @@ public class MixinChatOptionsScreen extends SimpleOptionsSubScreen { @Override public void render(@NotNull PoseStack poseStack, int x, int y, float f) { super.render(poseStack, x, y, f); + + if (!NCRConfig.getClient().enableMod()) + return; + if (this.onlyShowSecureChat != null && this.onlyShowSecureChat.visible && x >= (double) this.onlyShowSecureChat.x && y >= (double) this.onlyShowSecureChat.y && x < (double) (this.onlyShowSecureChat.x + this.onlyShowSecureChat.getWidth()) && y < (double) (this.onlyShowSecureChat.y + this.onlyShowSecureChat.getHeight())) { this.renderTooltip(poseStack, this.secureChatTooltip, x, y); } } -} +}
\ No newline at end of file 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 f0b4b34..7b69957 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java @@ -7,10 +7,15 @@ 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 org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import com.aizistral.nochatreports.core.NoReportsConfig; -import com.aizistral.nochatreports.core.ServerSafetyState; +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.EncryptionButton; +import com.aizistral.nochatreports.gui.EncryptionConfigScreen; +import com.aizistral.nochatreports.gui.EncryptionWarningScreen; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; @@ -20,15 +25,14 @@ import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.math.Matrix4f; -import net.minecraft.client.OptionInstance; -import net.minecraft.client.OptionInstance.TooltipSupplierFactory; -import net.minecraft.client.gui.components.Button; +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.renderer.GameRenderer; import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.locale.Language; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; @@ -40,35 +44,94 @@ import net.minecraft.util.FormattedCharSequence; @Mixin(ChatScreen.class) public abstract class MixinChatScreen extends Screen { - private static final ResourceLocation CHAT_STATUS_ICONS = new ResourceLocation("nochatreports", "textures/gui/chat_status_icons.png"); + 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"); protected MixinChatScreen() { super(null); throw new IllegalStateException("Can't touch this"); } + @Inject(method = "normalizeChatMessage", at = @At("RETURN"), cancellable = true) + public void onBeforeMessage(String original, CallbackInfoReturnable<String> 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) { - if (!NoReportsConfig.showServerSafety()) + int buttonX = this.width - 23; + + if (NCRConfig.getClient().showServerSafety() && NCRConfig.getClient().enableMod()) { + ServerSafetyLevel trust = this.minecraft.isLocalServer() ? ServerSafetyLevel.SECURE : ServerSafetyState.getCurrent(); + + var button = new ImageButton(buttonX, this.height - 37, 20, 20, this.getXOffset(trust), + 0, 20, CHAT_STATUS_ICONS, 128, 128, btn -> {}, (btn, poseStack, i, j) -> + this.renderTooltipNoGap(poseStack, this.minecraft.font.split(trust.getTooltip(), 250), i, j), + Component.empty()); + button.active = false; + button.visible = true; + + this.addRenderableOnly(button); + buttonX -= 25; + } + + if (!NCRConfig.getEncryption().showEncryptionButton()) return; - ServerSafetyLevel trust = this.minecraft.isLocalServer() ? ServerSafetyLevel.SECURE : ServerSafetyState.getCurrent(); + 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(); + } + }, (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); - var button = new ImageButton(this.width - 23, this.height - 37, 20, 20, this.getXOffset(trust), - 0, 20, CHAT_STATUS_ICONS, 64, 64, btn -> {}, (btn, poseStack, i, j) -> - this.renderTooltipNoGap(poseStack, this.minecraft.font.split(trust.getTooltip(), 250), i, j), - Component.translatable("gui.socialInteractions.report")); - button.active = false; + } + }, Component.empty(), this); + button.active = true; button.visible = true; - this.addRenderableOnly(button); + this.addRenderableWidget(button); } private int getXOffset(ServerSafetyLevel level) { return switch (level) { case SECURE -> 21; - case UNINTRUSIVE, UNKNOWN -> 42; + case UNINTRUSIVE -> 42; case INSECURE -> 0; + case REALMS -> 63; + case UNKNOWN -> 84; + case UNDEFINED -> 105; }; } @@ -83,7 +146,7 @@ public abstract class MixinChatScreen extends Screen { if (list.isEmpty()) return; int k = 0; - int l = list.size() == 1 ? -2 : 0; + int l = list.size() == 1 ? -2 : -2; for (ClientTooltipComponent clientTooltipComponent : list) { m = clientTooltipComponent.getWidth(this.font); if (m > k) { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientTelemetryManager.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientTelemetryManager.java index dc6f0e0..efbd9ed 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientTelemetryManager.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientTelemetryManager.java @@ -1,17 +1,17 @@ package com.aizistral.nochatreports.mixins.client; -import com.aizistral.nochatreports.core.NoReportsConfig; -import com.mojang.authlib.minecraft.TelemetrySession; -import com.mojang.authlib.minecraft.UserApiService; - -import net.minecraft.client.ClientTelemetryManager; - import java.util.concurrent.Executor; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import com.aizistral.nochatreports.config.NCRConfig; +import com.mojang.authlib.minecraft.TelemetrySession; +import com.mojang.authlib.minecraft.UserApiService; + +import net.minecraft.client.ClientTelemetryManager; + @Mixin(ClientTelemetryManager.class) public class MixinClientTelemetryManager { @@ -24,7 +24,7 @@ public class MixinClientTelemetryManager { + "newTelemetrySession(Ljava/util/concurrent/Executor;)Lcom/mojang/authlib/minecraft/TelemetrySession;", remap = false)) private TelemetrySession onCreateTelemetrySession(UserApiService service, Executor executor) { - if (NoReportsConfig.disableTelemetry()) + if (NCRConfig.getClient().disableTelemetry()) return TelemetrySession.DISABLED; else return service.newTelemetrySession(executor); diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientboundHelloPacket.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientboundHelloPacket.java index dfb94ad..82df5af 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientboundHelloPacket.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinClientboundHelloPacket.java @@ -4,8 +4,8 @@ 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 org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import com.aizistral.nochatreports.config.NCRConfig; import com.aizistral.nochatreports.core.ServerSafetyLevel; import com.aizistral.nochatreports.core.ServerSafetyState; @@ -24,6 +24,9 @@ public class MixinClientboundHelloPacket { @Inject(method = "handle", at = @At("HEAD")) private void onHandle(ClientLoginPacketListener listener, CallbackInfo info) { + if (!NCRConfig.getClient().enableMod()) + return; + ServerSafetyState.setSessionRequestedKey(true); } diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java index 6b3fcf1..947729d 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinConnectScreen.java @@ -7,7 +7,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.aizistral.nochatreports.NoChatReports; -import com.aizistral.nochatreports.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.config.NCRConfigClient; import com.aizistral.nochatreports.core.ServerSafetyLevel; import com.aizistral.nochatreports.core.ServerSafetyState; @@ -29,13 +30,23 @@ public class MixinConnectScreen { @Inject(method = "startConnecting", at = @At("HEAD")) private static void onStartConnecting(Screen screen, Minecraft minecraft, ServerAddress serverAddress, @Nullable ServerData serverData, CallbackInfo info) { - ServerSafetyState.updateCurrent(ServerSafetyLevel.UNKNOWN); // just to be 100% sure - ServerSafetyState.setLastConnectedServer(serverAddress); + if (!NCRConfig.getClient().enableMod()) + return; - if (NoReportsConfig.isDebugLogEnabled()) { + ServerSafetyState.updateCurrent(ServerSafetyLevel.UNDEFINED); // just to be 100% sure + ServerSafetyState.setLastConnectedServer(serverAddress, serverData); + + if (NCRConfig.getServerWhitelist().isWhitelisted(serverAddress)) { + if (!NCRConfig.getClient().doSigningCheck(serverAddress)) { + ServerSafetyState.setAllowsUnsafeServer(true); + } + } + + if (NCRConfig.getCommon().enableDebugLog()) { NoChatReports.LOGGER.info("Connecting to: {}, will expose public key: {}", serverAddress.getHost() + ":" + serverAddress.getPort(), ServerSafetyState.allowsUnsafeServer()); + 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 index 1edcf7e..1c18c61 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTag.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTag.java @@ -5,9 +5,12 @@ 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.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; +import net.minecraft.ChatFormatting; import net.minecraft.client.GuiMessageTag; +import net.minecraft.client.GuiMessageTag.Icon; +import net.minecraft.network.chat.Component; @Mixin(GuiMessageTag.class) public class MixinGuiMessageTag { @@ -21,7 +24,7 @@ public class MixinGuiMessageTag { @Inject(method = "system", at = @At("HEAD"), cancellable = true) private static void onSystem(CallbackInfoReturnable<GuiMessageTag> info) { - if (NoReportsConfig.hideGrayChatIndicators()) { + if (NCRConfig.getClient().hideGrayChatIndicators()) { 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 new file mode 100644 index 0000000..7c130bd --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinGuiMessageTagIcon.java @@ -0,0 +1,47 @@ +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", remap = false) @Mutable static Icon[] $VALUES; + + @Invoker("<init>") + 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 index e9f6395..61fa83a 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinJoinMultiplayerScreen.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinJoinMultiplayerScreen.java @@ -8,7 +8,8 @@ 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.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.core.ServerSafetyState; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; @@ -24,6 +25,7 @@ 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.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; @@ -35,8 +37,9 @@ import net.minecraft.util.FormattedCharSequence; @Mixin(JoinMultiplayerScreen.class) public abstract class MixinJoinMultiplayerScreen extends Screen { - private static final ResourceLocation RELOAD_TEXTURE = new ResourceLocation("nochatreports", "textures/gui/config_reload_button.png"); - private static final Component RELOAD_TOOLTIP = Component.translatable("gui.nochatrepords.reload_config_tooltip"); + 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); @@ -45,16 +48,42 @@ public abstract class MixinJoinMultiplayerScreen extends Screen { @Inject(method = "init", at = @At("HEAD")) private void onInit(CallbackInfo info) { - if (!NoReportsConfig.showReloadButton()) - return; + if (NCRConfig.getClient().showReloadButton()) { + var button = new ImageButton(this.width/2 + 158, this.height - 52, 20, 20, 0, 0, 20, + RELOAD_TEXTURE, 64, 64, btn -> NCRConfig.load(), (btn, poseStack, i, j) -> + this.renderTooltipNoGap(poseStack, this.minecraft.font.split(RELOAD_TOOLTIP, 250), i, j), + Component.translatable("gui.nochatreports.reload_config")); + button.active = true; + button.visible = true; + this.addRenderableWidget(button); + } + + if (NCRConfig.getClient().showNCRButton()) { + var button = new ImageButton(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(); - var button = new ImageButton(this.width/2 + 158, this.height - 52, 20, 20, 0, 0, 20, RELOAD_TEXTURE, - 64, 64, btn -> NoReportsConfig.loadConfig(), (btn, poseStack, i, j) -> - this.renderTooltipNoGap(poseStack, this.minecraft.font.split(RELOAD_TOOLTIP, 250), i, j), - Component.translatable("gui.nochatrepords.reload_config")); - button.active = true; - button.visible = true; - this.addRenderableWidget(button); + if (enabled) { + ((ImageButton)btn).xTexStart = 0; + } else { + ((ImageButton)btn).xTexStart = 20; + } + + ServerSafetyState.reset(); + }, (btn, poseStack, i, j) -> this.renderTooltip(poseStack, + this.minecraft.font.split( + Component.translatable("gui.nochatreports.ncr_toggle_tooltip", + Language.getInstance() + .getOrDefault("gui.nochatreports.ncr_state_" + + (NCRConfig.getClient().enableMod() + ? "on" : "off"))), 250), i, j), + Component.translatable("gui.nochatreports.ncr_toggle")); + button.active = true; + button.visible = true; + this.addRenderableWidget(button); + } } protected void renderTooltipNoGap(PoseStack poseStack, List<? extends FormattedCharSequence> list, int i, int j) { @@ -68,7 +97,7 @@ public abstract class MixinJoinMultiplayerScreen extends Screen { if (list.isEmpty()) return; int k = 0; - int l = list.size() == 1 ? -2 : 0; + int l = list.size() == 1 ? -2 : -2; for (ClientTooltipComponent clientTooltipComponent : list) { m = clientTooltipComponent.getWidth(this.font); if (m > k) { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinLocalPlayer.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinLocalPlayer.java index 57ce4bb..9e43d68 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinLocalPlayer.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinLocalPlayer.java @@ -1,10 +1,16 @@ package com.aizistral.nochatreports.mixins.client; -import com.aizistral.nochatreports.core.NoReportsConfig; +import javax.annotation.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.CallbackInfoReturnable; + +import com.aizistral.nochatreports.config.NCRConfig; import com.aizistral.nochatreports.core.ServerSafetyState; import com.mojang.brigadier.ParseResults; -import net.minecraft.Util; import net.minecraft.client.player.LocalPlayer; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.commands.arguments.ArgumentSignatures; @@ -13,17 +19,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.LastSeenMessages; import net.minecraft.network.chat.MessageSignature; import net.minecraft.network.chat.MessageSigner; -import net.minecraft.util.Crypt; -import net.minecraft.util.Crypt.SaltSignaturePair; - -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 java.time.Instant; - -import javax.annotation.Nullable; @Mixin(LocalPlayer.class) public class MixinLocalPlayer { @@ -36,6 +31,9 @@ public class MixinLocalPlayer { @Inject(method = "signMessage", at = @At("HEAD"), cancellable = true) private void onSignMessage(MessageSigner signer, ChatMessageContent message, LastSeenMessages messages, CallbackInfoReturnable<MessageSignature> info) { + if (!NCRConfig.getClient().enableMod()) + return; + if (!ServerSafetyState.forceSignedMessages()) { info.setReturnValue(MessageSignature.EMPTY); } @@ -48,6 +46,9 @@ public class MixinLocalPlayer { @Inject(method = "signCommandArguments", at = @At("HEAD"), cancellable = true) private void onSignCommand(MessageSigner signer, ParseResults<SharedSuggestionProvider> results, @Nullable Component component, LastSeenMessages messages, CallbackInfoReturnable<ArgumentSignatures> info) { + if (!NCRConfig.getClient().enableMod()) + return; + if (!ServerSafetyState.forceSignedMessages()) { info.setReturnValue(ArgumentSignatures.EMPTY); } diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java new file mode 100644 index 0000000..5090b6c --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOnlineServerEntry.java @@ -0,0 +1,69 @@ +package com.aizistral.nochatreports.mixins.client; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +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.NoChatReports; +import com.aizistral.nochatreports.NoChatReportsClient; +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 net.minecraft.util.Tuple; + +@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<Component>()))); + } + } + } + +} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java index 3c26b86..8bbdbfb 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinOptions.java @@ -1,16 +1,19 @@ 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; -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; @Mixin(Options.class) public class MixinOptions { @@ -23,6 +26,9 @@ public class MixinOptions { @Inject(method = "onlyShowSecureChat", at = @At("RETURN"), cancellable = true) private void onlyShowSecureChat(CallbackInfoReturnable<OptionInstance<Boolean>> cir) { + if (!NCRConfig.getClient().enableMod()) + return; + if (this.alternativeOption == null) { this.alternativeOption = new OptionInstance<>("options.onlyShowSecureChat", OptionInstance.cachedConstantTooltip(Component.translatable("gui.nochatreport.secureChat")), diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java index 4610f4d..03ae009 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinPlayerEntry.java @@ -12,7 +12,7 @@ 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.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; import com.aizistral.nochatreports.core.ServerSafetyLevel; import com.aizistral.nochatreports.core.ServerSafetyState; import com.mojang.blaze3d.vertex.PoseStack; @@ -20,11 +20,9 @@ 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.screens.reporting.ChatReportScreen; 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.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; @@ -47,7 +45,7 @@ public class MixinPlayerEntry { @Inject(method = "<init>", at = @At("RETURN")) private void onConstructed(Minecraft minecraft, SocialInteractionsScreen socialInteractionsScreen, UUID uUID, String string, Supplier<ResourceLocation> supplier, boolean reportable, CallbackInfo info) { - if (NoReportsConfig.alwaysHideReportButton()) { + if (NCRConfig.getClient().alwaysHideReportButton()) { this.reportButton = new Button(0, 0, 20, 20, Component.empty(), button -> {}) { @Override public void render(PoseStack poseStack, int i, int j, float f) { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinProfileKeyPairManager.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinProfileKeyPairManager.java index 70fa9fa..407a7ed 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinProfileKeyPairManager.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinProfileKeyPairManager.java @@ -1,16 +1,21 @@ package com.aizistral.nochatreports.mixins.client; -import com.aizistral.nochatreports.core.ServerSafetyState; -import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl; -import net.minecraft.client.multiplayer.ProfileKeyPairManager; -import net.minecraft.util.Signer; -import net.minecraft.world.entity.player.ProfilePublicKey; +import java.util.Optional; + import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Group; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import java.util.Optional; +import com.aizistral.nochatreports.config.NCRConfig; +import com.aizistral.nochatreports.core.ServerSafetyState; +import com.mojang.authlib.yggdrasil.response.KeyPairResponse; + +import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl; +import net.minecraft.client.multiplayer.ProfileKeyPairManager; +import net.minecraft.util.Signer; +import net.minecraft.world.entity.player.ProfilePublicKey; @Mixin(ProfileKeyPairManager.class) public class MixinProfileKeyPairManager { @@ -23,6 +28,9 @@ public class MixinProfileKeyPairManager { @Inject(method = "profilePublicKey", at = @At("HEAD"), cancellable = true) private void onProfilePublicKey(CallbackInfoReturnable<Optional<ProfilePublicKey>> info) { + if (!NCRConfig.getClient().enableMod()) + return; + if (!ServerSafetyState.allowsUnsafeServer()) { info.setReturnValue(Optional.empty()); } @@ -34,14 +42,35 @@ public class MixinProfileKeyPairManager { * @author Aizistral */ + @Group(min = 1, max = 2) @Inject(method = "parsePublicKey", at = @At("HEAD"), cancellable = true) - private static void onProfilePublicKeyData(CallbackInfoReturnable<Optional<ProfilePublicKey.Data>> info) { + private static void onParsePublicKey(KeyPairResponse response, CallbackInfoReturnable<ProfilePublicKey.Data> info) { + if (!NCRConfig.getClient().enableMod()) + return; + if (!ServerSafetyState.allowsUnsafeServer()) { info.setReturnValue(null); } } /** + * @reason Accomplishes the same thing as {@link #onParsePublicKey(KeyPairResponse, CallbackInfoReturnable)}, + * but only in 1.19.1. + * @author Aizistral + */ + + @Group(min = 1, max = 2) + @Inject(method = { "profilePublicKeyData", "method_43784" }, at = @At("HEAD"), cancellable = true, remap = false) + private void onProfilePublicKeyData(CallbackInfoReturnable<Optional<ProfilePublicKey.Data>> info) { + if (!NCRConfig.getClient().enableMod()) + return; + + if (!ServerSafetyState.allowsUnsafeServer()) { + info.setReturnValue(Optional.empty()); + } + } + + /** * @reason Prevent client from trying to produce signature in * {@link ClientHandshakePacketListenerImpl#handleHello}. * @author Aizistral @@ -49,6 +78,9 @@ public class MixinProfileKeyPairManager { @Inject(method = "signer", at = @At("HEAD"), cancellable = true) private void onSigner(CallbackInfoReturnable<Optional<Signer>> info) { + if (!NCRConfig.getClient().enableMod()) + return; + if (!ServerSafetyState.allowsUnsafeServer()) { info.setReturnValue(null); } diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java index 9d8a3a5..5fd58dd 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinRealmsConnect.java @@ -5,6 +5,7 @@ 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; @@ -22,8 +23,11 @@ public class MixinRealmsConnect { @Inject(method = "connect", at = @At("HEAD")) private void onConnect(RealmsServer realmsServer, ServerAddress serverAddress, CallbackInfo info) { - ServerSafetyState.setLastConnectedServer(serverAddress); - ServerSafetyState.updateCurrent(ServerSafetyLevel.INSECURE); + if (!NCRConfig.getClient().enableMod()) + return; + + ServerSafetyState.setLastConnectedServer(serverAddress, null); + ServerSafetyState.updateCurrent(ServerSafetyLevel.REALMS); ServerSafetyState.setAllowsUnsafeServer(true); } diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java new file mode 100644 index 0000000..b311e43 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerData.java @@ -0,0 +1,46 @@ +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<CompoundTag> info) { + info.getReturnValue().putBoolean("preventsChatReports", this.preventsChatReports); + } + + @Inject(method = "read", locals = LocalCapture.CAPTURE_FAILSOFT, at = @At("RETURN")) + private static void onRead(CompoundTag tag, CallbackInfoReturnable<ServerData> 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 new file mode 100644 index 0000000..fb0d66b --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinServerStatusPinger$1.java @@ -0,0 +1,57 @@ +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 new file mode 100644 index 0000000..39fe9e0 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinTitleScreen.java @@ -0,0 +1,32 @@ +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.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 net.minecraft.network.chat.Component; + +@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 index 36cfe7e..601ccef 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinToastComponent.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinToastComponent.java @@ -5,7 +5,7 @@ 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.core.NoReportsConfig; +import com.aizistral.nochatreports.config.NCRConfig; import net.minecraft.client.gui.components.toasts.SystemToast; import net.minecraft.client.gui.components.toasts.SystemToast.SystemToastIds; @@ -17,7 +17,7 @@ public class MixinToastComponent { @Inject(method = "addToast", at = @At("HEAD"), cancellable = true) private void onAddToast(Toast toast, CallbackInfo info) { - if (NoReportsConfig.hideWarningToast()) + 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/common/MixinServerStatus.java b/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatus.java new file mode 100644 index 0000000..9268092 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatus.java @@ -0,0 +1,47 @@ +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<Boolean> info) { + if (NCRConfig.getCommon().convertToGameMessage()) { + info.setReturnValue(true); + } + } + + @Override + public boolean preventsChatReports() { + 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 new file mode 100644 index 0000000..f8a9009 --- /dev/null +++ b/src/main/java/com/aizistral/nochatreports/mixins/common/MixinServerStatusSerializer.java @@ -0,0 +1,54 @@ +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<JsonElement> 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<ServerStatus> 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 index 2ec92b7..75a1b7b 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinDedicatedServer.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinDedicatedServer.java @@ -1,11 +1,12 @@ package com.aizistral.nochatreports.mixins.server; -import net.minecraft.server.dedicated.DedicatedServer; 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 { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayer.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayer.java index 780d93c..1065a5a 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayer.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinPlayer.java @@ -1,14 +1,13 @@ package com.aizistral.nochatreports.mixins.server; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.entity.player.ProfilePublicKey; 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 org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.ProfilePublicKey; + @Mixin(Player.class) public class MixinPlayer { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java index 2226193..c6fcbe0 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java @@ -1,11 +1,16 @@ package com.aizistral.nochatreports.mixins.server; -import com.aizistral.nochatreports.core.NoReportsConfig; +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.core.Registry; import net.minecraft.network.PacketSendListener; -import net.minecraft.network.chat.ChatTypeDecoration; -import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientboundPlayerChatHeaderPacket; import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; @@ -14,13 +19,6 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -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; - @Mixin(ServerGamePacketListenerImpl.class) public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerConnection { @Shadow @@ -35,14 +33,17 @@ public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerC @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;)V", at = @At("HEAD"), cancellable = true) private void onSend(Packet<?> packet, CallbackInfo info) { - if (NoReportsConfig.convertToGameMessage()) { + if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { + NoChatReports.LOGGER.info("Sending message: {}", chat.message().serverContent()); + } + + if (NCRConfig.getCommon().convertToGameMessage()) { if (packet instanceof ClientboundPlayerChatHeaderPacket) { info.cancel(); } else if (packet instanceof ClientboundPlayerChatPacket chat) { packet = new ClientboundSystemChatPacket(chat.chatType().resolve(this.player.level.registryAccess()) .get().decorate(chat.message().serverContent()), false); - info.cancel(); this.send(packet); } @@ -57,7 +58,11 @@ public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerC @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 (NoReportsConfig.convertToGameMessage()) { + if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { + NoChatReports.LOGGER.info("Sending message: {}", chat.message().serverContent()); + } + + if (NCRConfig.getCommon().convertToGameMessage()) { if (packet instanceof ClientboundPlayerChatHeaderPacket) { info.cancel(); } else if (packet instanceof ClientboundPlayerChatPacket chat && packetSendListener != null) { diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerStatus.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerStatus.java deleted file mode 100644 index 3a544d3..0000000 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerStatus.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.aizistral.nochatreports.mixins.server; - -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.core.NoReportsConfig; - -import net.minecraft.network.protocol.game.ClientboundServerDataPacket; -import net.minecraft.network.protocol.status.ServerStatus; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; - -@Mixin(ServerStatus.class) -public class MixinServerStatus { - - @Inject(method = "enforcesSecureChat", at = @At("HEAD"), cancellable = true) - public void onSecureChatCheck(CallbackInfoReturnable<Boolean> info) { - if (NoReportsConfig.convertToGameMessage()) { - info.setReturnValue(true); - } - } - -} diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java index 15cca37..d9332c1 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerboundChatPacket.java @@ -1,18 +1,12 @@ package com.aizistral.nochatreports.mixins.server; -import net.minecraft.Util; -import net.minecraft.network.chat.MessageSignature; -import net.minecraft.network.protocol.game.ServerboundChatPacket; -import net.minecraft.util.Crypt.SaltSignaturePair; - 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.core.NoReportsConfig; - -import java.util.UUID; +import net.minecraft.network.chat.MessageSignature; +import net.minecraft.network.protocol.game.ServerboundChatPacket; @Mixin(ServerboundChatPacket.class) public class MixinServerboundChatPacket { @@ -20,7 +14,7 @@ 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 NoReportsConfig#convertToGameMessage()} enabled. + * {@link NCRConfigLegacy#convertToGameMessage()} enabled. * @author Aizistral */ |
