Skip to content

Commit

Permalink
Make the npc prefix check less strict and more precise
Browse files Browse the repository at this point in the history
  • Loading branch information
Warriorrrr committed Nov 30, 2024
1 parent 6fc581d commit 24cf037
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;

import org.bukkit.NamespacedKey;
import org.bukkit.event.EventHandler;
Expand All @@ -29,9 +30,7 @@ public TownyLoginListener() {
public void onPlayerLogin(AsyncPlayerPreLoginEvent event) {

final String logInName = event.getName();
boolean disallowed = isServerAccount(logInName) || isGovernmentAccount(logInName);

disallowed |= logInName.toLowerCase(Locale.ROOT).startsWith(TownySettings.getNPCPrefix().toLowerCase(Locale.ROOT));
boolean disallowed = isServerAccount(logInName) || isGovernmentAccount(logInName) || isPossibleNPCName(logInName);

if (!disallowed)
return;
Expand All @@ -57,6 +56,20 @@ private boolean isNationBank(String logInName) {
return isDisallowedName(logInName, TownySettings.getNationAccountPrefix());
}

static boolean isPossibleNPCName(String loginName) {
final String npcPrefix = TownySettings.getNPCPrefix();
if (!loginName.toLowerCase(Locale.ROOT).startsWith(npcPrefix.toLowerCase(Locale.ROOT)))
return false;

final String sub = loginName.substring(npcPrefix.length());
if (sub.isEmpty())
return false;

// A npc name can only consist of npc prefix + digits
final Pattern onlyDigits = Pattern.compile("^\\d+$");
return onlyDigits.matcher(sub).find();
}

private boolean isDisallowedName(String logInName, String disallowedName) {
return logInName.startsWith(disallowedName) || logInName.startsWith(disallowedName.replace("-", "_"));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.palmergames.bukkit.towny.listeners;

import be.seeseemelk.mockbukkit.MockBukkit;
import com.palmergames.bukkit.towny.TownySettings;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import static com.palmergames.bukkit.towny.listeners.TownyLoginListener.isPossibleNPCName;
import static org.junit.jupiter.api.Assertions.*;

public class LoginListenerTests {
@BeforeAll
public static void init() {
MockBukkit.getOrCreateMock();
TownySettings.loadDefaultConfig();
}

@Test
void testNpcPrefix() {
final String npcPrefix = TownySettings.getNPCPrefix();

assertFalse(isPossibleNPCName(npcPrefix)); // The npc prefix itself is not a possible npc name
assertTrue(isPossibleNPCName(npcPrefix + "1"));
assertTrue(isPossibleNPCName(npcPrefix + "99999999"));

assertFalse(isPossibleNPCName(npcPrefix + "A"));
assertFalse(isPossibleNPCName(npcPrefix + "1A"));
assertFalse(isPossibleNPCName("name"));
}
}

0 comments on commit 24cf037

Please sign in to comment.