From 1e2f116b6f24e55292909310b9e525e90d8dd6c6 Mon Sep 17 00:00:00 2001 From: Theo Gastinel Date: Sun, 11 Oct 2026 00:23:22 +0200 Subject: [PATCH] GastinelClaims 1.1.1 : pseudos avec caractere non tapable (guillemet) vises sans ce caractere, ambiguite annoncee Co-Authored-By: Claude Sonnet 5.5 --- README.md | 3 +- gradle.properties | 2 +- .../com/gastinelclaims/ClaimCommands.java | 107 ++++++++++++--- .../gastinelclaims/core/PseudoMatcher.java | 123 ++++++++++++++++++ .../resources/META-INF/neoforge.mods.toml | 2 +- .../core/PseudoMatcherTest.java | 123 ++++++++++++++++++ 6 files changed, 336 insertions(+), 24 deletions(-) create mode 100644 src/main/java/com/gastinelclaims/core/PseudoMatcher.java create mode 100644 src/test/java/com/gastinelclaims/core/PseudoMatcherTest.java diff --git a/README.md b/README.md index e9680c9..1ea64d9 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Protection de terrains par chunk pour NeoForge 1.21.1 (21.1.234). **Mod côté s - `/claim info` : à qui est le chunk + claims restants. - `/unclaim` : libère le chunk courant s'il est à toi. - `/friend`, `/friend add `, `/friend unadd ` : un ami a accès à tous tes claims. Le pseudo doit être connu du serveur (en ligne ou déjà venu). Stocké par UUID. +- **Pseudos spéciaux (depuis 1.1.1)** : un pseudo avec un caractère non tapable (ex. `gabybou201"`) se vise sans ce caractère (`/friend add gabybou201`). Ordre : pseudo exact, puis forme normalisée (minuscules, hors `[A-Za-z0-9_]` retiré) parmi les joueurs en ligne, puis `usercache.json`. Un seul compte correspond -> utilisé (UUID du vrai profil, vrai pseudo affiché). Plusieurs -> refus avec la liste des candidats (jamais de choix au hasard). Tab propose la forme sans guillemet. Logique pure : `core/PseudoMatcher.java` (tests `PseudoMatcherTest`). ## Config `config/gastinelclaims-server.toml` : `maxClaimsParJoueur = 25`. @@ -23,7 +24,7 @@ Casser/poser des blocs, clic droit sur un bloc (coffres, portes, leviers, bouton - Lave/eau qui coule d'un chunk voisin, flèches/projectiles sur les cadres, dispensers : non bloqués. ## Build (sur cornafserver, pas sur le PC) -Copier le dossier puis `sh build-sur-cornafserver.sh` (conteneur `eclipse-temurin:21-jdk` jetable, cache Gradle dans `~/.cache/gastinelclaims-gradle`). Lance les tests JUnit puis produit `build/libs/gastinelclaims-neoforge-1.21.1-1.1.0.jar`. +Copier le dossier puis `sh build-sur-cornafserver.sh` (conteneur `eclipse-temurin:21-jdk` jetable, cache Gradle dans `~/.cache/gastinelclaims-gradle`). Lance les tests JUnit puis produit `build/libs/gastinelclaims-neoforge-1.21.1-1.1.1.jar`. ## Zones protégées (depuis 1.1.0) — spawn incassable Module séparé de `/claim` (fichiers `ZonesProtegees.java`, `ZoneEvents.java`, `mixin/`, `core/ZonesConfig.java`). Une zone se cumule avec les claims et passe avant eux (priorité `HIGHEST`) ; `/claim` n'est pas modifié. diff --git a/gradle.properties b/gradle.properties index c585e38..2084c91 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,7 @@ org.gradle.jvmargs=-Xmx2G org.gradle.parallel=true -mod_version=1.1.0 +mod_version=1.1.1 mod_group_id=com.gastinelclaims mod_id=gastinelclaims diff --git a/src/main/java/com/gastinelclaims/ClaimCommands.java b/src/main/java/com/gastinelclaims/ClaimCommands.java index cb8a819..b20858b 100644 --- a/src/main/java/com/gastinelclaims/ClaimCommands.java +++ b/src/main/java/com/gastinelclaims/ClaimCommands.java @@ -2,6 +2,11 @@ package com.gastinelclaims; import com.gastinelclaims.core.ChunkKey; import com.gastinelclaims.core.ClaimRegistry; +import com.gastinelclaims.core.PseudoMatcher; +import com.gastinelclaims.core.PseudoMatcher.Profil; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import com.mojang.authlib.GameProfile; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; @@ -16,6 +21,9 @@ import net.minecraft.server.level.ServerPlayer; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.neoforge.event.RegisterCommandsEvent; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -39,11 +47,11 @@ public final class ClaimCommands { .then(Commands.literal("add") .then(Commands.argument("pseudo", StringArgumentType.word()) .suggests((ctx, b) -> SharedSuggestionProvider.suggest( - ctx.getSource().getServer().getPlayerNames(), b)) + PseudoMatcher.suggestions(List.of(ctx.getSource().getServer().getPlayerNames())), b)) .executes(ctx -> addFriend(ctx, StringArgumentType.getString(ctx, "pseudo"))))) .then(Commands.literal("unadd") .then(Commands.argument("pseudo", StringArgumentType.word()) - .suggests((ctx, b) -> SharedSuggestionProvider.suggest(friendNames(ctx), b)) + .suggests((ctx, b) -> SharedSuggestionProvider.suggest(PseudoMatcher.suggestions(friendNames(ctx)), b)) .executes(ctx -> removeFriend(ctx, StringArgumentType.getString(ctx, "pseudo")))))); } @@ -117,20 +125,31 @@ public final class ClaimCommands { private static int addFriend(CommandContext ctx, String name) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); - Optional target = resolve(p.server, name); - if (target.isEmpty()) { - fail(ctx, "Joueur inconnu du serveur : " + name + "."); + PseudoMatcher.Resultat res = chercher(p.server, name); + if (res.statut() == PseudoMatcher.Statut.AMBIGU) { + fail(ctx, PseudoMatcher.messageAmbigu(name, res.candidats())); return 0; } + Profil target = res.profil(); + if (target == null) { + // Aucun profil connu : comportement d'origine (profil hors-ligne créé par le cache du serveur). + Optional g = p.server.getProfileCache() == null ? Optional.empty() + : p.server.getProfileCache().get(name); + if (g.isEmpty()) { + fail(ctx, "Joueur inconnu du serveur : " + name + "."); + return 0; + } + target = new Profil(g.get().getId(), g.get().getName()); + } ClaimsData data = ClaimsData.get(p.server); - switch (data.registry().addFriend(p.getUUID(), target.get().getId())) { + switch (data.registry().addFriend(p.getUUID(), target.id())) { case OK -> { data.setDirty(); - ok(ctx, target.get().getName() + " a maintenant accès à tous tes claims."); + ok(ctx, target.nom() + " a maintenant accès à tous tes claims."); return 1; } case SELF -> fail(ctx, "Tu ne peux pas t'ajouter toi-même."); - case ALREADY -> fail(ctx, target.get().getName() + " est déjà ton ami."); + case ALREADY -> fail(ctx, target.nom() + " est déjà ton ami."); default -> { } } return 0; @@ -140,30 +159,76 @@ public final class ClaimCommands { ServerPlayer p = ctx.getSource().getPlayerOrException(); ClaimsData data = ClaimsData.get(p.server); // On cherche d'abord dans la liste d'amis (marche même si le cache de profils a oublié le pseudo) - UUID friend = null; - for (UUID u : data.registry().friendsOf(p.getUUID())) { - if (nameOf(p.server, u).equalsIgnoreCase(name)) { friend = u; break; } + List amis = new ArrayList<>(); + for (UUID u : data.registry().friendsOf(p.getUUID())) amis.add(new Profil(u, nameOf(p.server, u))); + PseudoMatcher.Resultat res = PseudoMatcher.resoudreParmi(name, amis); + if (res.statut() == PseudoMatcher.Statut.AMBIGU) { + fail(ctx, PseudoMatcher.messageAmbigu(name, res.candidats())); + return 0; } - if (friend == null) { - friend = resolve(p.server, name).map(GameProfile::getId).orElse(null); + UUID friend = null; + String affiche = name; + if (res.trouve()) { + friend = res.profil().id(); + affiche = res.profil().nom(); + } else { + PseudoMatcher.Resultat glob = chercher(p.server, name); + if (glob.statut() == PseudoMatcher.Statut.AMBIGU) { + fail(ctx, PseudoMatcher.messageAmbigu(name, glob.candidats())); + return 0; + } + if (glob.trouve()) { + friend = glob.profil().id(); + affiche = glob.profil().nom(); + } else if (p.server.getProfileCache() != null) { + friend = p.server.getProfileCache().get(name).map(GameProfile::getId).orElse(null); + } } if (friend == null || data.registry().removeFriend(p.getUUID(), friend) != ClaimRegistry.FriendResult.OK) { - fail(ctx, name + " n'est pas dans ta liste d'amis."); + fail(ctx, affiche + " n'est pas dans ta liste d'amis."); return 0; } data.setDirty(); - ok(ctx, name + " n'a plus accès à tes claims."); + ok(ctx, affiche + " n'a plus accès à tes claims."); return 1; } // --- Utilitaires --- - /** Pseudo -> profil : joueur en ligne, sinon cache de profils du serveur (joueurs déjà venus). */ - private static Optional resolve(MinecraftServer server, String name) { - ServerPlayer online = server.getPlayerList().getPlayerByName(name); - if (online != null) return Optional.of(online.getGameProfile()); - if (server.getProfileCache() == null) return Optional.empty(); - return server.getProfileCache().get(name); + /** + * Pseudo tapé -> profil : joueurs en ligne d'abord, sinon cache de profils (usercache.json, joueurs déjà venus). + * Tolérant aux caractères non tapables (guillemet...) ; ambigu si plusieurs comptes ressemblent à la saisie. + */ + private static PseudoMatcher.Resultat chercher(MinecraftServer server, String saisie) { + List enLigne = new ArrayList<>(); + for (ServerPlayer sp : server.getPlayerList().getPlayers()) { + enLigne.add(new Profil(sp.getUUID(), sp.getGameProfile().getName())); + } + return PseudoMatcher.resoudre(saisie, enLigne, profilsDuCache(server)); + } + + /** Lit usercache.json (écrit par le serveur à chaque ajout) ; liste vide en cas de problème. */ + private static List profilsDuCache(MinecraftServer server) { + List out = new ArrayList<>(); + try { + java.nio.file.Path f = server.getFile("usercache.json"); + if (!Files.isRegularFile(f)) return out; + try (Reader r = Files.newBufferedReader(f, StandardCharsets.UTF_8)) { + JsonElement root = JsonParser.parseReader(r); + if (!root.isJsonArray()) return out; + JsonArray arr = root.getAsJsonArray(); + for (JsonElement e : arr) { + if (!e.isJsonObject() || !e.getAsJsonObject().has("name") || !e.getAsJsonObject().has("uuid")) continue; + try { + out.add(new Profil(UUID.fromString(e.getAsJsonObject().get("uuid").getAsString()), + e.getAsJsonObject().get("name").getAsString())); + } catch (RuntimeException ignored) { } + } + } + } catch (Exception ex) { + GastinelClaims.LOGGER.warn("[GastinelClaims] usercache.json illisible : {}", ex.toString()); + } + return out; } public static String nameOf(MinecraftServer server, UUID uuid) { diff --git a/src/main/java/com/gastinelclaims/core/PseudoMatcher.java b/src/main/java/com/gastinelclaims/core/PseudoMatcher.java new file mode 100644 index 0000000..506b67d --- /dev/null +++ b/src/main/java/com/gastinelclaims/core/PseudoMatcher.java @@ -0,0 +1,123 @@ +package com.gastinelclaims.core; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Résolution tolérante d'un pseudo tapé en commande (logique pure, sans Minecraft). + * + * Problème : un pseudo hors-ligne peut contenir des caractères qu'un argument {@code word()} ne sait pas + * taper (ex. {@code gabybou201"}). Règle : on compare d'abord le pseudo exact (sans tenir compte de la casse), + * puis les formes normalisées (minuscules, tout ce qui n'est pas [A-Za-z0-9_] retiré). + * Sécurité : si la forme normalisée correspond à PLUSIEURS comptes différents (UUID différents), on ne choisit + * jamais : le résultat est AMBIGU et la liste des candidats est annoncée. L'UUID retenu est toujours celui du + * vrai profil trouvé, jamais un UUID recalculé à partir du texte tapé. + * + * Ordre : joueurs en ligne d'abord ; le cache de profils (usercache) n'est consulté que si aucun joueur en ligne + * ne correspond. + */ +public final class PseudoMatcher { + + public record Profil(UUID id, String nom) { } + + public enum Statut { TROUVE, AMBIGU, INCONNU } + + /** approximatif : vrai si le pseudo tapé diffère du vrai pseudo (match par forme normalisée). */ + public record Resultat(Statut statut, Profil profil, List candidats, boolean approximatif) { + public boolean trouve() { return statut == Statut.TROUVE; } + } + + private static final Resultat INCONNU = new Resultat(Statut.INCONNU, null, List.of(), false); + + /** Minuscules, caractères hors [A-Za-z0-9_] retirés. */ + public static String normaliser(String s) { + if (s == null) return ""; + StringBuilder sb = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_') sb.append(c); + else if (c >= 'A' && c <= 'Z') sb.append((char) (c + 32)); + } + return sb.toString(); + } + + /** Forme tapable dans un argument word() de Brigadier : [0-9A-Za-z_.+-] seulement. */ + public static String tapable(String nom) { + if (nom == null) return ""; + StringBuilder sb = new StringBuilder(nom.length()); + for (int i = 0; i < nom.length(); i++) { + char c = nom.charAt(i); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == '_' || c == '.' || c == '+' || c == '-') sb.append(c); + } + return sb.toString(); + } + + /** Suggestions (tab) : formes tapables, sans doublon, ordre conservé, sans entrée vide. */ + public static List suggestions(Collection noms) { + LinkedHashSet out = new LinkedHashSet<>(); + for (String n : noms) { + String t = tapable(n); + if (!t.isEmpty()) out.add(t); + } + return new ArrayList<>(out); + } + + /** Un seul groupe de profils (ex. les joueurs en ligne, ou les amis). */ + public static Resultat resoudreParmi(String saisie, Collection profils) { + return resoudre(saisie, profils, List.of()); + } + + public static Resultat resoudre(String saisie, Collection enLigne, Collection cache) { + if (saisie == null || saisie.isEmpty()) return INCONNU; + Resultat r = etape(saisie, dedoublonner(enLigne), false); + if (r.statut() != Statut.INCONNU) return r; + return etape(saisie, dedoublonner(cache), true); + } + + /** + * strict (cache) : un pseudo exact qui partage sa forme normalisée avec un AUTRE compte reste AMBIGU + * (profils fantômes d'anciens essais) : on ne désigne pas un compte au hasard. + */ + private static Resultat etape(String saisie, List profils, boolean strict) { + List exacts = new ArrayList<>(); + for (Profil p : profils) if (p.nom().equalsIgnoreCase(saisie)) exacts.add(p); + String norm = normaliser(saisie); + List proches = new ArrayList<>(); + if (!norm.isEmpty()) for (Profil p : profils) if (normaliser(p.nom()).equals(norm)) proches.add(p); + + if (exacts.size() == 1 && (!strict || proches.size() <= 1)) { + return new Resultat(Statut.TROUVE, exacts.get(0), List.of(exacts.get(0)), false); + } + if (!exacts.isEmpty()) { + // plusieurs exacts (casse différente) ou exact + comptes proches dans le cache : jamais au hasard + return new Resultat(Statut.AMBIGU, null, List.copyOf(strict ? proches : exacts), false); + } + if (proches.size() == 1) return new Resultat(Statut.TROUVE, proches.get(0), proches, true); + if (proches.size() > 1) return new Resultat(Statut.AMBIGU, null, List.copyOf(proches), true); + return INCONNU; + } + + private static List dedoublonner(Collection profils) { + Map m = new LinkedHashMap<>(); + for (Profil p : profils) if (p != null && p.id() != null && p.nom() != null) m.putIfAbsent(p.id(), p); + return new ArrayList<>(m.values()); + } + + /** Message clair listant les candidats (vrais pseudos). */ + public static String messageAmbigu(String saisie, List candidats) { + StringBuilder sb = new StringBuilder("Plusieurs joueurs ressemblent à « ").append(saisie).append(" » : "); + for (int i = 0; i < candidats.size(); i++) { + if (i > 0) sb.append(", "); + sb.append(candidats.get(i).nom()); + } + return sb.append(". Je ne choisis pas à ta place : fais-le te rejoindre en ligne, ou tape le pseudo exact.").toString(); + } + + private PseudoMatcher() { } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index 13743cc..b9a5bd8 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -4,7 +4,7 @@ license="MIT" [[mods]] modId="gastinelclaims" -version="1.1.0" +version="1.1.1" displayName="GastinelClaims" authors="Théo Gastinel" description='''Protection de terrains par chunk (/claim, /unclaim, /friend) et zones protégées (spawn incassable, /zoneprotegee). Mod côté serveur uniquement.''' diff --git a/src/test/java/com/gastinelclaims/core/PseudoMatcherTest.java b/src/test/java/com/gastinelclaims/core/PseudoMatcherTest.java new file mode 100644 index 0000000..774bbc3 --- /dev/null +++ b/src/test/java/com/gastinelclaims/core/PseudoMatcherTest.java @@ -0,0 +1,123 @@ +package com.gastinelclaims.core; + +import com.gastinelclaims.core.PseudoMatcher.Profil; +import com.gastinelclaims.core.PseudoMatcher.Statut; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +class PseudoMatcherTest { + + private static final UUID GABY = UUID.fromString("128c0f10-9643-37ff-941d-afa49cdb30ec"); + private static final UUID GABY_FANTOME = UUID.fromString("e65f2350-d100-3a51-ae80-50fbcce624c0"); + private static final UUID GABY_BIZARRE = UUID.fromString("607ba0dc-3032-3d7d-9330-e0345e4eec23"); + private static final UUID THEO = UUID.fromString("e1769fd1-91f1-377b-b2ac-999a4a7c9c9e"); + + private static final Profil GABY_P = new Profil(GABY, "gabybou201\""); + private static final Profil FANTOME_P = new Profil(GABY_FANTOME, "gabybou201"); + private static final Profil BIZARRE_P = new Profil(GABY_BIZARRE, "\"gabybou201\"\""); + private static final Profil THEO_P = new Profil(THEO, "totoche10"); + + @Test + void normalisation() { + assertEquals("gabybou201", PseudoMatcher.normaliser("gabybou201\"")); + assertEquals("steve_1", PseudoMatcher.normaliser("Ste.ve_1")); + assertEquals("", PseudoMatcher.normaliser("\"\"-")); + assertEquals("", PseudoMatcher.normaliser(null)); + } + + @Test + void tapable() { + assertEquals("gabybou201", PseudoMatcher.tapable("gabybou201\"")); + assertEquals("a.b-c+d_e", PseudoMatcher.tapable("a.b-c+d_e")); + } + + @Test + void sansGuillemetVisePseudoAvecGuillemetEnLigne() { + var r = PseudoMatcher.resoudre("gabybou201", List.of(THEO_P, GABY_P), List.of(FANTOME_P, GABY_P)); + assertEquals(Statut.TROUVE, r.statut()); + assertEquals(GABY, r.profil().id()); + assertEquals("gabybou201\"", r.profil().nom()); + assertTrue(r.approximatif()); + } + + @Test + void enLigneEstPrioritaireSurLeCacheMemeAvecFantome() { + var r = PseudoMatcher.resoudre("GabyBou201", List.of(GABY_P), List.of(FANTOME_P, BIZARRE_P, GABY_P)); + assertTrue(r.trouve()); + assertEquals(GABY, r.profil().id()); + } + + @Test + void exactEnLigneNeEstPasDetourne() { + var r = PseudoMatcher.resoudre("gabybou201", List.of(FANTOME_P, GABY_P), List.of()); + assertTrue(r.trouve()); + assertEquals(GABY_FANTOME, r.profil().id()); + assertFalse(r.approximatif()); + } + + @Test + void deuxEnLigneProchesSansExactEstAmbigu() { + var r = PseudoMatcher.resoudre("gabybou201", List.of(GABY_P, BIZARRE_P), List.of()); + assertEquals(Statut.AMBIGU, r.statut()); + assertEquals(2, r.candidats().size()); + String m = PseudoMatcher.messageAmbigu("gabybou201", r.candidats()); + assertTrue(m.contains("gabybou201\"") && m.contains("\"gabybou201\"\"")); + } + + @Test + void cacheHorsLigneAvecFantomeEstAmbigu() { + var r = PseudoMatcher.resoudre("gabybou201", List.of(THEO_P), List.of(FANTOME_P, GABY_P, BIZARRE_P)); + assertEquals(Statut.AMBIGU, r.statut()); + assertEquals(3, r.candidats().size()); + assertNull(r.profil()); + } + + @Test + void cacheUnSeulCandidatApproximatif() { + var r = PseudoMatcher.resoudre("gabybou201", List.of(), List.of(GABY_P, THEO_P)); + assertTrue(r.trouve()); + assertEquals(GABY, r.profil().id()); + assertTrue(r.approximatif()); + } + + @Test + void cacheExactUniqueResteExact() { + var r = PseudoMatcher.resoudre("TOTOCHE10", List.of(), List.of(GABY_P, THEO_P)); + assertTrue(r.trouve()); + assertEquals(THEO, r.profil().id()); + assertFalse(r.approximatif()); + } + + @Test + void inconnuEtVide() { + assertEquals(Statut.INCONNU, PseudoMatcher.resoudre("zorglub", List.of(GABY_P), List.of(THEO_P)).statut()); + assertEquals(Statut.INCONNU, PseudoMatcher.resoudre("", List.of(GABY_P), List.of()).statut()); + assertEquals(Statut.INCONNU, PseudoMatcher.resoudre("---", List.of(GABY_P), List.of()).statut()); + assertEquals(Statut.INCONNU, PseudoMatcher.resoudre(null, List.of(GABY_P), List.of()).statut()); + } + + @Test + void memeUuidSousDeuxNomsNEstPasAmbigu() { + var autreNom = new Profil(GABY, "GabyBou201"); + var r = PseudoMatcher.resoudre("gabybou201", List.of(), List.of(GABY_P, autreNom)); + assertTrue(r.trouve()); + assertEquals(GABY, r.profil().id()); + } + + @Test + void uuidRetenuEstCeluiDuProfil() { + var r = PseudoMatcher.resoudreParmi("gabybou201", List.of(GABY_P)); + assertEquals(GABY, r.profil().id()); + assertNotEquals(GABY_FANTOME, r.profil().id()); + } + + @Test + void suggestionsSansGuillemetNiDoublon() { + assertEquals(List.of("gabybou201", "totoche10", "gabybou201x"), + PseudoMatcher.suggestions(List.of("gabybou201\"", "totoche10", "gabybou201", "\"\"", "gabybou201x"))); + } +}