Minor clean up

This commit is contained in:
games647
2024-05-21 15:09:28 +02:00
parent f50004f50d
commit 6005f0db44
21 changed files with 52 additions and 52 deletions

View File

@ -25,7 +25,7 @@ jobs:
if: ${{ github.event.workflow_run.conclusion == 'success' }} if: ${{ github.event.workflow_run.conclusion == 'success' }}
permissions: permissions:
# Only allow write for security, then all others default to read only # Only allow 'write' permission for security, then all others default to read only
security-events: write security-events: write
strategy: strategy:

View File

@ -80,7 +80,7 @@ public abstract class ToggleCommand implements CommandExecutor {
plugin.getBungeeManager().sendPluginMessage((PluginMessageRecipient) invoker, message); plugin.getBungeeManager().sendPluginMessage((PluginMessageRecipient) invoker, message);
} else { } else {
Optional<? extends Player> optPlayer = Bukkit.getServer().getOnlinePlayers().stream().findFirst(); Optional<? extends Player> optPlayer = Bukkit.getServer().getOnlinePlayers().stream().findFirst();
if (!optPlayer.isPresent()) { if (optPlayer.isEmpty()) {
plugin.getLog().info("No player online to send a plugin message to the proxy"); plugin.getLog().info("No player online to send a plugin message to the proxy");
return; return;
} }

View File

@ -58,8 +58,8 @@ import java.time.Instant;
import java.util.Arrays; import java.util.Arrays;
import java.util.Base64; import java.util.Base64;
import java.util.Base64.Encoder; import java.util.Base64.Encoder;
import java.util.Random;
import java.util.UUID; import java.util.UUID;
import java.util.random.RandomGenerator;
/** /**
* Encryption and decryption minecraft util for connection between servers * Encryption and decryption minecraft util for connection between servers
@ -116,7 +116,7 @@ final class EncryptionUtil {
* @param random random generator * @param random random generator
* @return a token with 4 bytes long * @return a token with 4 bytes long
*/ */
public static byte[] generateVerifyToken(Random random) { public static byte[] generateVerifyToken(RandomGenerator random) {
byte[] token = new byte[VERIFY_TOKEN_LENGTH]; byte[] token = new byte[VERIFY_TOKEN_LENGTH];
random.nextBytes(token); random.nextBytes(token);
return token; return token;

View File

@ -204,7 +204,7 @@ public class ProtocolLibListener extends PacketAdapter {
Either<byte[], ?> either = packet.getSpecificModifier(Either.class).read(0); Either<byte[], ?> either = packet.getSpecificModifier(Either.class).read(0);
if (clientPublicKey == null) { if (clientPublicKey == null) {
Optional<byte[]> left = either.left(); Optional<byte[]> left = either.left();
if (!left.isPresent()) { if (left.isEmpty()) {
plugin.getLog().error("No verify token sent if requested without player signed key {}", sender); plugin.getLog().error("No verify token sent if requested without player signed key {}", sender);
return false; return false;
} }
@ -212,7 +212,7 @@ public class ProtocolLibListener extends PacketAdapter {
return EncryptionUtil.verifyNonce(expectedToken, keyPair.getPrivate(), left.get()); return EncryptionUtil.verifyNonce(expectedToken, keyPair.getPrivate(), left.get());
} else { } else {
Optional<?> optSignatureData = either.right(); Optional<?> optSignatureData = either.right();
if (!optSignatureData.isPresent()) { if (optSignatureData.isEmpty()) {
plugin.getLog().error("No signature given to sent player signing key {}", sender); plugin.getLog().error("No signature given to sent player signing key {}", sender);
return false; return false;
} }

View File

@ -60,7 +60,7 @@ class EncryptionUtilTest {
@Test @Test
void testVerifyToken() { void testVerifyToken() {
val random = ThreadLocalRandom.current(); @SuppressWarnings("SharedThreadLocalRandom") val random = ThreadLocalRandom.current();
byte[] token = EncryptionUtil.generateVerifyToken(random); byte[] token = EncryptionUtil.generateVerifyToken(random);
assertAll( assertAll(

View File

@ -50,6 +50,10 @@ import java.util.Base64;
public class ResourceLoader { public class ResourceLoader {
private ResourceLoader() {
// Utility
}
public static RSAPrivateKey parsePrivateKey(String keySpec) public static RSAPrivateKey parsePrivateKey(String keySpec)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
try ( try (

View File

@ -125,7 +125,7 @@
<dependency> <dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
<version>4.0.3</version> <version>5.1.0</version>
<exclusions> <exclusions>
<!-- HikariCP uses an old version of this API that has a typo in the service interface --> <!-- HikariCP uses an old version of this API that has a typo in the service interface -->
<!-- We will use the api provided by the jdk14 dependency --> <!-- We will use the api provided by the jdk14 dependency -->

View File

@ -26,7 +26,7 @@
package com.github.games647.fastlogin.core.hooks; package com.github.games647.fastlogin.core.hooks;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Random; import java.util.random.RandomGenerator;
import java.util.stream.IntStream; import java.util.stream.IntStream;
public class DefaultPasswordGenerator<P> implements PasswordGenerator<P> { public class DefaultPasswordGenerator<P> implements PasswordGenerator<P> {
@ -35,7 +35,7 @@ public class DefaultPasswordGenerator<P> implements PasswordGenerator<P> {
private static final char[] PASSWORD_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" private static final char[] PASSWORD_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
.toCharArray(); .toCharArray();
private final Random random = new SecureRandom(); private final RandomGenerator random = new SecureRandom();
@Override @Override
public String getRandomPassword(P player) { public String getRandomPassword(P player) {

View File

@ -59,16 +59,13 @@ public class FloodgateService extends BedrockService<FloodgatePlayer> {
*/ */
public boolean isValidFloodgateConfigString(String key) { public boolean isValidFloodgateConfigString(String key) {
String value = core.getConfig().get(key).toString().toLowerCase(Locale.ENGLISH); String value = core.getConfig().get(key).toString().toLowerCase(Locale.ENGLISH);
switch (value) { return switch (value) {
case "true": case "true", "linked", "false", "no-conflict" -> true;
case "linked": default -> {
case "false":
case "no-conflict":
return true;
default:
core.getPlugin().getLog().error("Invalid value detected for {} in FastLogin/config.yml.", key); core.getPlugin().getLog().error("Invalid value detected for {} in FastLogin/config.yml.", key);
return false; yield false;
} }
};
} }
@Override @Override

View File

@ -163,12 +163,12 @@ public class FastLoginCore<P extends C, C, T extends PlatformPlugin<C>> {
Action action = Action.Ignore; Action action = Action.Ignore;
switch (botSection.getString("action", "ignore")) { switch (botSection.getString("action", "ignore")) {
case "ignore":
action = Action.Ignore;
break;
case "block": case "block":
action = Action.Block; action = Action.Block;
break; break;
case "ignore":
action = Action.Ignore;
break;
default: default:
plugin.getLog().warn("Invalid anti bot action - defaulting to ignore"); plugin.getLog().warn("Invalid anti bot action - defaulting to ignore");
} }

View File

@ -70,17 +70,12 @@ public enum FloodgateState {
*/ */
public static FloodgateState fromInt(int num) { public static FloodgateState fromInt(int num) {
// using Enum.values()[i] is expensive as per https://stackoverflow.com/a/8762387/9767089 // using Enum.values()[i] is expensive as per https://stackoverflow.com/a/8762387/9767089
switch (num) { return switch (num) {
case 0: case 0 -> FloodgateState.FALSE;
return FloodgateState.FALSE; case 1 -> FloodgateState.TRUE;
case 1: case 2 -> FloodgateState.LINKED;
return FloodgateState.TRUE; case 3 -> FloodgateState.NOT_MIGRATED;
case 2: default -> null;
return FloodgateState.LINKED; };
case 3:
return FloodgateState.NOT_MIGRATED;
default:
return null;
}
} }
} }

View File

@ -109,7 +109,7 @@ public abstract class JoinManagement<P extends C, C, S extends LoginSource> {
premiumUUID = core.getResolver().findProfile(username); premiumUUID = core.getResolver().findProfile(username);
} }
if (!premiumUUID.isPresent() if (premiumUUID.isEmpty()
|| (!isNameChanged(source, username, premiumUUID.get()) || (!isNameChanged(source, username, premiumUUID.get())
&& !isUsernameAvailable(source, username, profile))) { && !isUsernameAvailable(source, username, profile))) {
//nothing detected the player as premium -> start a cracked session //nothing detected the player as premium -> start a cracked session

View File

@ -29,7 +29,7 @@ import java.net.InetSocketAddress;
public interface LoginSource { public interface LoginSource {
void enableOnlinemode() throws Exception; void enableOnlinemode();
void kick(String message); void kick(String message);

View File

@ -32,9 +32,12 @@ import org.slf4j.Logger;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.regex.Pattern;
public interface PlatformPlugin<C> { public interface PlatformPlugin<C> {
Pattern PATTERN = Pattern.compile("%nl%");
String getName(); String getName();
Path getPluginFolder(); Path getPluginFolder();
@ -48,7 +51,7 @@ public interface PlatformPlugin<C> {
boolean isPluginInstalled(String name); boolean isPluginInstalled(String name);
default void sendMultiLineMessage(C receiver, String message) { default void sendMultiLineMessage(C receiver, String message) {
for (String line : message.split("%nl%")) { for (String line : PATTERN.split(message)) {
sendMessage(receiver, line); sendMessage(receiver, line);
} }
} }

View File

@ -168,11 +168,10 @@ public class StoredProfile extends Profile {
return true; return true;
} }
if (!(o instanceof StoredProfile)) { if (!(o instanceof StoredProfile that)) {
return false; return false;
} }
StoredProfile that = (StoredProfile) o;
if (!super.equals(o)) { if (!super.equals(o)) {
return false; return false;
} }

View File

@ -27,13 +27,13 @@ package com.github.games647.fastlogin.core.hooks;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals;
class DefaultPasswordGeneratorTest { class DefaultPasswordGeneratorTest {
@Test @Test
void smokeTestPassword() { void smokeTestPassword() {
PasswordGenerator<?> passwordGenerator = new DefaultPasswordGenerator<>(); PasswordGenerator<?> passwordGenerator = new DefaultPasswordGenerator<>();
assertTrue(passwordGenerator.getRandomPassword(null).length() == 8); assertEquals(8, passwordGenerator.getRandomPassword(null).length());
} }
} }

View File

@ -27,6 +27,7 @@ package com.github.games647.fastlogin.velocity;
import com.github.games647.fastlogin.core.shared.LoginSource; import com.github.games647.fastlogin.core.shared.LoginSource;
import com.velocitypowered.api.event.connection.PreLoginEvent; import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.event.connection.PreLoginEvent.PreLoginComponentResult;
import com.velocitypowered.api.proxy.InboundConnection; import com.velocitypowered.api.proxy.InboundConnection;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
@ -46,17 +47,17 @@ public class VelocityLoginSource implements LoginSource {
@Override @Override
public void enableOnlinemode() { public void enableOnlinemode() {
preLoginEvent.setResult(PreLoginEvent.PreLoginComponentResult.forceOnlineMode()); preLoginEvent.setResult(PreLoginComponentResult.forceOnlineMode());
} }
@Override @Override
public void kick(String message) { public void kick(String message) {
if (message == null) { if (message == null) {
preLoginEvent.setResult(PreLoginEvent.PreLoginComponentResult.denied( preLoginEvent.setResult(PreLoginComponentResult.denied(
Component.text("Kicked").color(NamedTextColor.WHITE)) Component.text("Kicked").color(NamedTextColor.WHITE))
); );
} else { } else {
preLoginEvent.setResult(PreLoginEvent.PreLoginComponentResult.denied( preLoginEvent.setResult(PreLoginComponentResult.denied(
LegacyComponentSerializer.legacyAmpersand().deserialize(message)) LegacyComponentSerializer.legacyAmpersand().deserialize(message))
); );
} }

View File

@ -29,11 +29,12 @@ import com.github.games647.fastlogin.core.shared.LoginSession;
import com.github.games647.fastlogin.core.shared.event.FastLoginAutoLoginEvent; import com.github.games647.fastlogin.core.shared.event.FastLoginAutoLoginEvent;
import com.github.games647.fastlogin.core.storage.StoredProfile; import com.github.games647.fastlogin.core.storage.StoredProfile;
import com.velocitypowered.api.event.ResultedEvent; import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.event.ResultedEvent.GenericResult;
import java.util.Objects; import java.util.Objects;
public class VelocityFastLoginAutoLoginEvent public class VelocityFastLoginAutoLoginEvent
implements FastLoginAutoLoginEvent, ResultedEvent<ResultedEvent.GenericResult> { implements FastLoginAutoLoginEvent, ResultedEvent<GenericResult> {
private final LoginSession session; private final LoginSession session;
private final StoredProfile profile; private final StoredProfile profile;

View File

@ -46,7 +46,6 @@ import com.velocitypowered.api.event.player.ServerConnectedEvent;
import com.velocitypowered.api.proxy.InboundConnection; import com.velocitypowered.api.proxy.InboundConnection;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.util.GameProfile;
import com.velocitypowered.api.util.GameProfile.Property; import com.velocitypowered.api.util.GameProfile.Property;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
@ -130,9 +129,9 @@ public class ConnectListener {
} }
} }
private List<GameProfile.Property> removeSkin(Collection<Property> oldProperties) { private List<Property> removeSkin(Collection<Property> oldProperties) {
List<GameProfile.Property> newProperties = new ArrayList<>(oldProperties.size()); List<Property> newProperties = new ArrayList<>(oldProperties.size());
for (GameProfile.Property property : oldProperties) { for (Property property : oldProperties) {
if (!"textures".equals(property.getName())) { if (!"textures".equals(property.getName())) {
newProperties.add(property); newProperties.add(property);
} }

View File

@ -38,6 +38,7 @@ import com.google.common.io.ByteStreams;
import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PluginMessageEvent; import com.velocitypowered.api.event.connection.PluginMessageEvent;
import com.velocitypowered.api.event.connection.PluginMessageEvent.ForwardResult;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ServerConnection; import com.velocitypowered.api.proxy.ServerConnection;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier; import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
@ -69,7 +70,7 @@ public class PluginMessageListener {
//the client shouldn't be able to read the messages in order to know something about server internal states //the client shouldn't be able to read the messages in order to know something about server internal states
//moreover the client shouldn't be able to fake a running premium check by sending the result message //moreover the client shouldn't be able to fake a running premium check by sending the result message
pluginMessageEvent.setResult(PluginMessageEvent.ForwardResult.handled()); pluginMessageEvent.setResult(ForwardResult.handled());
if (!(pluginMessageEvent.getSource() instanceof ServerConnection)) { if (!(pluginMessageEvent.getSource() instanceof ServerConnection)) {
//check if the message is sent from the server //check if the message is sent from the server

View File

@ -55,8 +55,8 @@ public class FloodgateAuthTask
core.getPlugin().getSession().put(player.getRemoteAddress(), session); core.getPlugin().getSession().put(player.getRemoteAddress(), session);
// enable auto login based on the value of 'autoLoginFloodgate' in config.yml // enable auto login based on the value of 'autoLoginFloodgate' in config.yml
boolean forcedOnlineMode = autoLoginFloodgate.equals("true") boolean forcedOnlineMode = "true".equals(autoLoginFloodgate)
|| (autoLoginFloodgate.equals("linked") && isLinked); || ("linked".equals(autoLoginFloodgate) && isLinked);
// delay sending force command, because Paper will process the login event asynchronously // delay sending force command, because Paper will process the login event asynchronously
// In this case it means that the force command (plugin message) is already received and processed while // In this case it means that the force command (plugin message) is already received and processed while