diff --git a/README.md b/README.md index 8febc39..f30eacd 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,23 @@ Features: * **Console delegate** - a robust way to prompt a player via console. * **Post command** - expands your command by incorporation post commands. +## Delegated (console-run) prompts + +Commands started with `/consoledelegate` or `/playerdelegate` run with console or temporarily +granted permissions, but the answers are typed by the prompted player. To keep a player from adding +arguments or entity selectors to such a command, answers in delegated sessions must be a single +argument by default: an answer that contains whitespace or starts with `@` is rejected and the +prompt is shown again. + +* Add the `-allowargs` flag to a prompt (for a JSON preset, + `"behavior": {"flags": {"allowargs": "true"}}`) only when it really needs multi-word answers, e.g. + `/cd %target_player% say `. +* Always pair console-run prompts with an input validator (`-iv:`) or the `-int` answer type + so the answer is limited to what the command expects. This is required for any prompt that uses + `-allowargs`. + +Prompts started by the player (non-delegated) are not affected. + ## Building CommandPrompter uses Gradle as a project manager. You can build CommandPrompter for yourself by following the instructions below: diff --git a/prompt-core/src/main/java/dev/cyr1en/promptcore/PromptTag.java b/prompt-core/src/main/java/dev/cyr1en/promptcore/PromptTag.java index 5133bc5..1890c78 100644 --- a/prompt-core/src/main/java/dev/cyr1en/promptcore/PromptTag.java +++ b/prompt-core/src/main/java/dev/cyr1en/promptcore/PromptTag.java @@ -75,6 +75,12 @@ public record PromptTag( Map flags, Condition breakIf) { + /** + * Flag name ({@code -allowargs}) stored in {@link #flags()} when a prompt may be answered with + * several command arguments or a leading {@code @} in a delegated (console-run) session. + */ + public static final String ALLOW_ARGS_FLAG = "allowargs"; + /** Describes an optional type constraint on the answer value. */ public enum AnswerType { /** No type constraint — accept any string. */ @@ -294,6 +300,12 @@ public boolean isPreset() { return preset; } + /** Whether this tag opts in to multi-argument answers in delegated sessions. */ + public boolean allowsArgs() { + var value = flags.get(ALLOW_ARGS_FLAG); + return value != null && "true".equalsIgnoreCase(value.trim()); + } + /** Whether this tag has an attached breakIf condition. */ public boolean hasBreakIf() { return breakIf != null; diff --git a/prompt-core/src/main/java/dev/cyr1en/promptcore/parser/CommandLineParser.java b/prompt-core/src/main/java/dev/cyr1en/promptcore/parser/CommandLineParser.java index 4400608..198a00b 100644 --- a/prompt-core/src/main/java/dev/cyr1en/promptcore/parser/CommandLineParser.java +++ b/prompt-core/src/main/java/dev/cyr1en/promptcore/parser/CommandLineParser.java @@ -51,6 +51,8 @@ public class CommandLineParser { private static final Pattern DS_FLAG = Pattern.compile("(? p var newRemainder = stripFlags(DS_FLAG, remainder, false); var sanitize = remainder.length() == newRemainder.length(); remainder = newRemainder; + var allowArgs = false; + if (isBuiltInKey(key)) { + var withoutAllowArgs = stripFlags(ALLOW_ARGS_FLAG, remainder, false); + allowArgs = remainder.length() != withoutAllowArgs.length(); + remainder = withoutAllowArgs; + } var timeout = extractTimeout(remainder); if (timeout != null) { remainder = stripFlags(TIMEOUT_FLAG, remainder, true); @@ -613,7 +621,7 @@ private void parsePromptTag(String rawContent, String fullTag, List p // Log a one-shot migration hint if using the deprecated trailing-kind form. if (filter == null) warnIfTrailingKind(rawContent); - Map flags = Map.of(); + Map flags = allowArgs ? Map.of(PromptTag.ALLOW_ARGS_FLAG, "true") : Map.of(); if (!isBuiltInKey(key)) { var flagResult = extractTrailingCustomFlags(remainder); remainder = flagResult.remainingContent(); @@ -849,6 +857,9 @@ private void parseCompoundPromptTag( var contentWithoutDs = stripFlags(DS_FLAG, contentWithoutBreakIf, false); var sanitize = contentWithoutBreakIf.length() == contentWithoutDs.length(); + var withoutAllowArgs = stripFlags(ALLOW_ARGS_FLAG, contentWithoutDs, false); + var allowArgs = contentWithoutDs.length() != withoutAllowArgs.length(); + contentWithoutDs = withoutAllowArgs; var timeout = extractTimeout(contentWithoutDs); if (timeout != null) { contentWithoutDs = stripFlags(TIMEOUT_FLAG, contentWithoutDs, true); @@ -914,7 +925,7 @@ private void parseCompoundPromptTag( false, title, timeout, - Map.of(), + allowArgs ? Map.of(PromptTag.ALLOW_ARGS_FLAG, "true") : Map.of(), breakIf)); } diff --git a/prompt-core/src/main/java/dev/cyr1en/promptcore/session/PromptSession.java b/prompt-core/src/main/java/dev/cyr1en/promptcore/session/PromptSession.java index cfb7510..b792f19 100644 --- a/prompt-core/src/main/java/dev/cyr1en/promptcore/session/PromptSession.java +++ b/prompt-core/src/main/java/dev/cyr1en/promptcore/session/PromptSession.java @@ -453,7 +453,7 @@ private static String cleanAnswer(String raw, boolean sanitize) { * @param input the raw input string * @return the sanitized string, or null/empty if input was null/empty */ - static String sanitize(String input) { + public static String sanitize(String input) { if (input == null || input.isEmpty()) return input; // Strip color codes and decorative symbols var noColor = input.replaceAll("(?i)[§&][0-9a-fklmnor]", ""); diff --git a/prompt-core/src/test/java/dev/cyr1en/promptcore/parser/CustomFlagsParserTest.java b/prompt-core/src/test/java/dev/cyr1en/promptcore/parser/CustomFlagsParserTest.java index a6e289e..1309c5a 100644 --- a/prompt-core/src/test/java/dev/cyr1en/promptcore/parser/CustomFlagsParserTest.java +++ b/prompt-core/src/test/java/dev/cyr1en/promptcore/parser/CustomFlagsParserTest.java @@ -265,4 +265,42 @@ void promptTagConstructorsCompatibility() { assertTrue(tag11.flags().isEmpty()); assertEquals(30, tag11.timeout()); } + + @Test + @DisplayName("Built-in tags accept -allowargs and keep it out of the display text") + void parsesAllowArgsOnBuiltInTag() { + var tag = parser.parse("/cmd ").promptTags().get(0); + assertEquals("Message", tag.displayText()); + assertEquals("msg", tag.validatorAlias()); + assertTrue(tag.allowsArgs()); + + var plain = parser.parse("/cmd ").promptTags().get(0); + assertFalse(plain.allowsArgs()); + assertTrue(plain.flags().isEmpty()); + } + + @Test + @DisplayName("Compound and custom tags accept -allowargs") + void parsesAllowArgsOnCompoundAndCustomTags() { + var compound = + parser.parse("/cmd ").promptTags().get(0); + assertTrue(compound.isCompound()); + assertEquals(2, compound.subTags().size()); + assertTrue(compound.allowsArgs()); + + var custom = parser.parse("/give ").promptTags().get(0); + assertEquals("Pick weapon", custom.displayText()); + assertTrue(custom.allowsArgs()); + } + + @Test + @DisplayName("-allowargs is stored as \"true\" and an explicit false does not opt in") + void allowArgsValueIsChecked() { + var builtIn = parser.parse("/cmd ").promptTags().get(0); + assertEquals("true", builtIn.flags().get(PromptTag.ALLOW_ARGS_FLAG)); + + var disabled = parser.parse("/give ").promptTags().get(0); + assertEquals("false", disabled.flags().get(PromptTag.ALLOW_ARGS_FLAG)); + assertFalse(disabled.allowsArgs()); + } } diff --git a/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/ConsoleDelegateCommand.java b/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/ConsoleDelegateCommand.java index 7437c6e..78770a5 100644 --- a/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/ConsoleDelegateCommand.java +++ b/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/ConsoleDelegateCommand.java @@ -26,6 +26,10 @@ *

Restricted to console senders with {@code promptpaper.consoledelegate}. The target is parsed * via {@link ArgumentTypes#player()} which gives us a {@link PlayerSelectorArgumentResolver} that * supports {@code @a} / {@code @p} selectors in addition to plain names. + * + *

Answers in the delegated session must be a single argument (no whitespace, no leading + * {@code @}) unless the prompt carries the {@code -allowargs} flag; prompts in delegated commands + * should always use an input validator. */ public class ConsoleDelegateCommand extends PromptCommand implements Command { diff --git a/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/PlayerDelegateCommand.java b/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/PlayerDelegateCommand.java index c2b0334..1e31024 100644 --- a/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/PlayerDelegateCommand.java +++ b/prompt-paper/src/main/java/dev/cyr1en/promptpaper/command/PlayerDelegateCommand.java @@ -28,6 +28,10 @@ * *

Restricted to console senders with {@code promptpaper.playerdelegate}. The {@code * permissionKey} argument is tab-completed from the configured permission keys. + * + *

Answers in the delegated session must be a single argument (no whitespace, no leading + * {@code @}) unless the prompt carries the {@code -allowargs} flag; prompts in delegated commands + * should always use an input validator. */ public class PlayerDelegateCommand extends PromptCommand implements Command { diff --git a/prompt-paper/src/main/java/dev/cyr1en/promptpaper/screen/ScreenManager.java b/prompt-paper/src/main/java/dev/cyr1en/promptpaper/screen/ScreenManager.java index 90f300c..7f82c69 100644 --- a/prompt-paper/src/main/java/dev/cyr1en/promptpaper/screen/ScreenManager.java +++ b/prompt-paper/src/main/java/dev/cyr1en/promptpaper/screen/ScreenManager.java @@ -4,6 +4,7 @@ import dev.cyr1en.promptcore.PromptTag; import dev.cyr1en.promptcore.i18n.Placeholder; import dev.cyr1en.promptcore.logic.condition.ConditionBindings; +import dev.cyr1en.promptcore.session.PromptSession; import dev.cyr1en.promptpaper.CommandPrompter; import dev.cyr1en.promptpaper.custom.ActiveScreenHandle; import dev.cyr1en.promptpaper.custom.CustomScreenAdapter; @@ -1372,6 +1373,13 @@ private boolean validateAnswer(Player player, String answer, PromptTag tag) { "validation.answer_too_long", player, Placeholder.of("max", String.valueOf(maxLen)))); return false; } + if (isUnsafeDelegatedAnswer(player, answer, tag)) { + plugin + .getPluginLogger() + .debug("Delegated answer rejected (whitespace or selector) for " + player.getName()); + player.sendMessage(i18n.get("validation.delegated_single_argument", player)); + return false; + } switch (tag.type()) { case INTEGER -> { try { @@ -1418,6 +1426,28 @@ private boolean validateAnswer(Player player, String answer, PromptTag tag) { return true; } + /** + * In sessions started by {@code /consoledelegate} or {@code /playerdelegate} the answer is + * dispatched with console or temporarily elevated permissions, so by default it must stay one + * literal argument: no whitespace (extra arguments) and no leading {@code @} (entity selectors). + */ + private boolean isUnsafeDelegatedAnswer(Player player, String answer, PromptTag tag) { + if (!dispatchModes.containsKey(player.getUniqueId())) return false; + if (tag.allowsArgs()) return false; + // PromptSession sanitizes the answer after validation, which can expose a selector that was + // hidden behind stripped characters (e.g. "&a@a" or "$@a" become "@a"). + return isMultiArgumentOrSelector(answer) + || isMultiArgumentOrSelector(PromptSession.sanitize(answer)); + } + + private static boolean isMultiArgumentOrSelector(String answer) { + return answer.startsWith("@") || answer.chars().anyMatch(ScreenManager::isArgumentSeparator); + } + + private static boolean isArgumentSeparator(int ch) { + return Character.isWhitespace(ch) || Character.isSpaceChar(ch); + } + public boolean hasActiveScreen(Player player) { return activeScreenHandles.containsKey(player.getUniqueId()) || activeScreens.containsKey(player.getUniqueId()); diff --git a/prompt-paper/src/main/resources/messages_en_US.properties b/prompt-paper/src/main/resources/messages_en_US.properties index 8980c85..a315431 100644 --- a/prompt-paper/src/main/resources/messages_en_US.properties +++ b/prompt-paper/src/main/resources/messages_en_US.properties @@ -11,6 +11,7 @@ prompt.error.command_failed=Command failed: %message% validation.invalid_integer=Please enter a valid integer. validation.invalid_string=Input cannot be empty. validation.answer_too_long=Input exceeds maximum length of %max% characters. +validation.delegated_single_argument=Input must be a single word and cannot start with @. player_ui.search_instruction=Type your search term in chat. dialog.no_options=No options available, enter argument manually. dialog.too_many_options=Too many options (%count%), enter argument manually. diff --git a/prompt-paper/src/main/resources/messages_es_ES.properties b/prompt-paper/src/main/resources/messages_es_ES.properties index 38086a3..bad92d4 100644 --- a/prompt-paper/src/main/resources/messages_es_ES.properties +++ b/prompt-paper/src/main/resources/messages_es_ES.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=El comando falló: %message% validation.invalid_integer=Por favor, introduce un número entero válido. validation.invalid_string=La entrada no puede estar vacía. validation.answer_too_long=La entrada excede la longitud máxima de %max% caracteres. +validation.delegated_single_argument=La entrada debe ser una sola palabra y no puede empezar por @. player_ui.search_instruction=Escribe tu término de búsqueda en el chat. dialog.no_options=No hay opciones disponibles, introduce el argumento manualmente. dialog.too_many_options=Demasiadas opciones (%count%), introduce el argumento manualmente. diff --git a/prompt-paper/src/main/resources/messages_fr_FR.properties b/prompt-paper/src/main/resources/messages_fr_FR.properties index f6d5cbd..27f01ef 100644 --- a/prompt-paper/src/main/resources/messages_fr_FR.properties +++ b/prompt-paper/src/main/resources/messages_fr_FR.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=Échec de la commande : %message% validation.invalid_integer=Veuillez entrer un entier valide. validation.invalid_string=La saisie ne peut pas être vide. validation.answer_too_long=La saisie dépasse la longueur maximale de %max% caractères. +validation.delegated_single_argument=La saisie doit être un seul mot et ne peut pas commencer par @. player_ui.search_instruction=Tapez votre terme de recherche dans le chat. dialog.no_options=Aucune option disponible, entrez l'argument manuellement. dialog.too_many_options=Trop d'options (%count%), entrez l'argument manuellement. diff --git a/prompt-paper/src/main/resources/messages_ja_JP.properties b/prompt-paper/src/main/resources/messages_ja_JP.properties index 77a9747..0a623e3 100644 --- a/prompt-paper/src/main/resources/messages_ja_JP.properties +++ b/prompt-paper/src/main/resources/messages_ja_JP.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=コマンドの実行に失敗しました:%m validation.invalid_integer=有効な整数を入力してください。 validation.invalid_string=入力内容を空にすることはできません。 validation.answer_too_long=入力が最大文��数(%max%文字)を超えています。 +validation.delegated_single_argument=入力は1語のみで、@ で始めることはできません。 player_ui.search_instruction=チャットに検索キーワードを入力してください。 dialog.no_options=利用可能な選択肢がありません。引数を手動で入力してください。 dialog.too_many_options=選択肢が多すぎます(%count%件)。引数を手動で入力してください。 diff --git a/prompt-paper/src/main/resources/messages_ko_KR.properties b/prompt-paper/src/main/resources/messages_ko_KR.properties index 4a6d616..6776ba2 100644 --- a/prompt-paper/src/main/resources/messages_ko_KR.properties +++ b/prompt-paper/src/main/resources/messages_ko_KR.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=명령 실행에 실패했습니다: %message%< validation.invalid_integer=유효한 정수를 입력해 주세요. validation.invalid_string=입력 내용은 비워 둘 수 없습니다. validation.answer_too_long=입력 내용이 최대 길이(%max%자)를 초과했습니다. +validation.delegated_single_argument=입력은 한 단어여야 하며 @로 시작할 수 없습니다. player_ui.search_instruction=채팅창에 검색어를 입력하세요. dialog.no_options=사용 가능한 옵션이 없습니다. 인수를 직접 입력해 주세요. dialog.too_many_options=옵션이 너무 많습니다 (%count%개). 인수를 직접 입력해 주세요. diff --git a/prompt-paper/src/main/resources/messages_pirate.properties b/prompt-paper/src/main/resources/messages_pirate.properties index 7a6f228..029bd79 100644 --- a/prompt-paper/src/main/resources/messages_pirate.properties +++ b/prompt-paper/src/main/resources/messages_pirate.properties @@ -11,6 +11,7 @@ prompt.error.command_failed=The command ran aground: %message% validation.invalid_integer=Enter a proper whole number, landlubber. validation.invalid_string=Ye cannot submit an empty message. validation.answer_too_long=Yer yarn be too long! Keep it under %max% letters. +validation.delegated_single_argument=Yer answer must be a single word, and it cannot start with @! player_ui.search_instruction=Speak yer search words into the chat. dialog.no_options=No choices be available. Enter the argument by hand. dialog.too_many_options=Too many choices aboard (%count%). Enter the argument by hand. diff --git a/prompt-paper/src/main/resources/messages_pl_PL.properties b/prompt-paper/src/main/resources/messages_pl_PL.properties index 8621222..5d5bbaa 100644 --- a/prompt-paper/src/main/resources/messages_pl_PL.properties +++ b/prompt-paper/src/main/resources/messages_pl_PL.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=Wykonanie polecenia nie powiodło się: %messag validation.invalid_integer=Proszę podać prawidłową liczbę całkowitą. validation.invalid_string=Pole nie może być puste. validation.answer_too_long=Wprowadzony tekst przekracza maksymalną długość %max% znaków. +validation.delegated_single_argument=Wpis musi być jednym słowem i nie może zaczynać się od @. player_ui.search_instruction=Wpisz wyszukiwaną frazę na czacie. dialog.no_options=Brak dostępnych opcji, podaj argument ręcznie. dialog.too_many_options=Zbyt wiele opcji (%count%), podaj argument ręcznie. diff --git a/prompt-paper/src/main/resources/messages_pt_BR.properties b/prompt-paper/src/main/resources/messages_pt_BR.properties index 64f0c11..e0cbbb2 100644 --- a/prompt-paper/src/main/resources/messages_pt_BR.properties +++ b/prompt-paper/src/main/resources/messages_pt_BR.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=O comando falhou: %message% validation.invalid_integer=Por favor, insira um número inteiro válido. validation.invalid_string=A entrada não pode estar vazia. validation.answer_too_long=A entrada excede o comprimento máximo de %max% caracteres. +validation.delegated_single_argument=A entrada deve ser uma única palavra e não pode começar com @. player_ui.search_instruction=Digite seu termo de busca no chat. dialog.no_options=Nenhuma opção disponível, insira o argumento manualmente. dialog.too_many_options=Opções demais (%count%), insira o argumento manualmente. diff --git a/prompt-paper/src/main/resources/messages_tl_PH.properties b/prompt-paper/src/main/resources/messages_tl_PH.properties index 1a817ba..eb3e287 100644 --- a/prompt-paper/src/main/resources/messages_tl_PH.properties +++ b/prompt-paper/src/main/resources/messages_tl_PH.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=Nabigo ang utos: %message% validation.invalid_integer=Mangyaring magpasok ng tamang integer. validation.invalid_string=Hindi maaaring walang laman ang input. validation.answer_too_long=Lumampas ang input sa pinakamataas na haba na %max% character. +validation.delegated_single_argument=Dapat isang salita lang ang input at hindi maaaring magsimula sa @. player_ui.search_instruction=I-type ang iyong hinahanap sa chat. dialog.no_options=Walang available na opsyon, ilagay ang argumento nang manu-mano. dialog.too_many_options=Masyadong maraming opsyon (%count%), ilagay ang argumento nang manu-mano. diff --git a/prompt-paper/src/main/resources/messages_zh_CN.properties b/prompt-paper/src/main/resources/messages_zh_CN.properties index a2dceaa..9889bfe 100644 --- a/prompt-paper/src/main/resources/messages_zh_CN.properties +++ b/prompt-paper/src/main/resources/messages_zh_CN.properties @@ -10,6 +10,7 @@ prompt.error.command_failed=命令执行失败:%message% validation.invalid_integer=请输入一个有效的整数。 validation.invalid_string=输入内容不能为空。 validation.answer_too_long=输入内容超过了最大长度 %max% 个字符。 +validation.delegated_single_argument=输入必须是单个词,且不能以 @ 开头。 player_ui.search_instruction=请在聊天框中输入搜索关键词。 dialog.no_options=暂无可用选项,请手动输入参数。 dialog.too_many_options=选项过多(%count%),请手动输入参数。 diff --git a/prompt-paper/src/test/java/dev/cyr1en/promptpaper/command/DelegateCommandsIntegrationTest.java b/prompt-paper/src/test/java/dev/cyr1en/promptpaper/command/DelegateCommandsIntegrationTest.java index f8fe2bf..abfdf97 100644 --- a/prompt-paper/src/test/java/dev/cyr1en/promptpaper/command/DelegateCommandsIntegrationTest.java +++ b/prompt-paper/src/test/java/dev/cyr1en/promptpaper/command/DelegateCommandsIntegrationTest.java @@ -30,6 +30,12 @@ void setUpDelegates() { engine = new PromptEngine(plugin, scheduler); factory = new PromptFactory(plugin); screenManager = new ScreenManager(plugin, engine, factory, scheduler); + lenient() + .when( + i18n.get( + org.mockito.ArgumentMatchers.eq("validation.delegated_single_argument"), + org.mockito.ArgumentMatchers.any(org.bukkit.entity.Player.class))) + .thenReturn(net.kyori.adventure.text.Component.text("single argument only")); } @Test @@ -83,4 +89,103 @@ void delegatedSessionCompletesWithChatInput() { assertFalse(screenManager.hasActiveScreen(player)); assertFalse(engine.hasActiveSession(player)); } + + private java.util.List captureDispatches(String name) { + var dispatched = new java.util.concurrent.CopyOnWriteArrayList(); + server + .getCommandMap() + .register( + name, + new org.bukkit.command.Command(name) { + @Override + public boolean execute( + org.bukkit.command.CommandSender sender, String label, String[] args) { + dispatched.add(sender.getName() + ":" + String.join(" ", args)); + return true; + } + }); + return dispatched; + } + + private void assertRejected(ScreenManager.DispatchMode mode, String key, String answer) { + if (key != null) when(config.getPermissionAttachment(key)).thenReturn(new String[] {"p.x"}); + var dispatched = captureDispatches("givegems"); + var player = createPlayer(); + screenManager.startDelegatedSession(player, "/givegems ", mode, key); + assertTrue(screenManager.hasChatScreen(player)); + + screenManager.handleChatInput(player, answer); + performTicks(5); + + org.mockito.Mockito.verify(i18n) + .get( + org.mockito.ArgumentMatchers.eq("validation.delegated_single_argument"), + org.mockito.ArgumentMatchers.same(player)); + assertTrue(screenManager.hasActiveScreen(player), "prompt must be shown again"); + assertTrue(engine.hasActiveSession(player)); + assertTrue(dispatched.isEmpty(), "rejected answer must not be dispatched: " + dispatched); + + screenManager.handleChatInput(player, "64"); + performTicks(5); + assertFalse(engine.hasActiveSession(player)); + assertEquals(1, dispatched.size()); + assertTrue(dispatched.get(0).endsWith(":64"), dispatched.toString()); + } + + @Test + void consoleDelegateRejectsSelectorAnswer() { + assertRejected(ScreenManager.DispatchMode.CONSOLE, null, "@a"); + } + + @Test + void consoleDelegateRejectsAnswerWithExtraArgument() { + assertRejected(ScreenManager.DispatchMode.CONSOLE, null, "1 extra"); + } + + @Test + void consoleDelegateRejectsNonBreakingSpaceAnswer() { + assertRejected(ScreenManager.DispatchMode.CONSOLE, null, "1\u00A0extra"); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"&a@a", "$@a", "(@a)", "{@a}", "[@a]", "<@a>", "&&a@a", "1&a &b2"}) + void consoleDelegateRejectsSelectorRevealedBySanitization(String answer) { + assertRejected(ScreenManager.DispatchMode.CONSOLE, null, answer); + } + + @Test + void playerDelegateRejectsSelectorAndExtraArgument() { + assertRejected(ScreenManager.DispatchMode.ATTACHMENT, "test-key", "1 @a"); + } + + @Test + void consoleDelegateAllowArgsFlagOptsIn() { + var dispatched = captureDispatches("givegems"); + var player = createPlayer(); + screenManager.startDelegatedSession( + player, "/givegems ", ScreenManager.DispatchMode.CONSOLE, null); + assertTrue(screenManager.hasChatScreen(player)); + + screenManager.handleChatInput(player, "1 extra"); + performTicks(5); + + assertFalse(engine.hasActiveSession(player)); + assertEquals(1, dispatched.size()); + assertTrue(dispatched.get(0).endsWith(":1 extra"), dispatched.toString()); + } + + @Test + void nonDelegatedSessionStillAcceptsSpacesAndSelectors() { + var dispatched = captureDispatches("givegems"); + var player = createPlayer(); + screenManager.startSession(player, "/givegems "); + assertTrue(screenManager.hasChatScreen(player)); + + screenManager.handleChatInput(player, "@a extra"); + performTicks(5); + + assertFalse(engine.hasActiveSession(player)); + assertEquals(java.util.List.of(player.getName() + ":@a extra"), dispatched); + } }