Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Message -allowargs -iv:msg>`.
* Always pair console-run prompts with an input validator (`-iv:<alias>`) 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:
Expand Down
12 changes: 12 additions & 0 deletions prompt-core/src/main/java/dev/cyr1en/promptcore/PromptTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ public record PromptTag(
Map<String, String> 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. */
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ public class CommandLineParser {
private static final Pattern DS_FLAG = Pattern.compile("(?<!\\S)-ds(?!\\S)");
private static final Pattern INT_FLAG = Pattern.compile("(?<!\\S)-int(?!\\S)");
private static final Pattern STR_FLAG = Pattern.compile("(?<!\\S)-str(?!\\S)");
private static final Pattern ALLOW_ARGS_FLAG =
Pattern.compile("(?<!\\S)-" + PromptTag.ALLOW_ARGS_FLAG + "(?!\\S)");
private static final Pattern TITLE_FLAG =
Pattern.compile("(?<!\\S)-t(?:\\b|(?=:))(?::(?:[^\"\\s]+|\"[^\"]*\")*)?");
private static final Pattern TIMEOUT_FLAG = Pattern.compile("(?<!\\S)-timeout(?:\\S*)");
Expand Down Expand Up @@ -598,6 +600,12 @@ private void parsePromptTag(String rawContent, String fullTag, List<PromptTag> 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);
Expand All @@ -613,7 +621,7 @@ private void parsePromptTag(String rawContent, String fullTag, List<PromptTag> p
// Log a one-shot migration hint if using the deprecated trailing-kind form.
if (filter == null) warnIfTrailingKind(rawContent);

Map<String, String> flags = Map.of();
Map<String, String> flags = allowArgs ? Map.of(PromptTag.ALLOW_ARGS_FLAG, "true") : Map.of();
if (!isBuiltInKey(key)) {
var flagResult = extractTrailingCustomFlags(remainder);
remainder = flagResult.remainingContent();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -914,7 +925,7 @@ private void parseCompoundPromptTag(
false,
title,
timeout,
Map.of(),
allowArgs ? Map.of(PromptTag.ALLOW_ARGS_FLAG, "true") : Map.of(),
breakIf));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]", "");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Message -allowargs -iv:msg>").promptTags().get(0);
assertEquals("Message", tag.displayText());
assertEquals("msg", tag.validatorAlias());
assertTrue(tag.allowsArgs());

var plain = parser.parse("/cmd <Message>").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 <d:text:First && d:text:Second -allowargs>").promptTags().get(0);
assertTrue(compound.isCompound());
assertEquals(2, compound.subTags().size());
assertTrue(compound.allowsArgs());

var custom = parser.parse("/give <ecoitem:Pick weapon -allowargs>").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 <Message -allowargs>").promptTags().get(0);
assertEquals("true", builtIn.flags().get(PromptTag.ALLOW_ARGS_FLAG));

var disabled = parser.parse("/give <ecoitem:Pick weapon -allowargs:false>").promptTags().get(0);
assertEquals("false", disabled.flags().get(PromptTag.ALLOW_ARGS_FLAG));
assertFalse(disabled.allowsArgs());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
* <p>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.
*
* <p>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<CommandSourceStack> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@
*
* <p>Restricted to console senders with {@code promptpaper.playerdelegate}. The {@code
* permissionKey} argument is tab-completed from the configured permission keys.
*
* <p>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<CommandSourceStack> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Comment thread
CyR1en marked this conversation as resolved.
Resolved
}

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());
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_en_US.properties
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ prompt.error.command_failed=<red>Command failed: %message%</red>
validation.invalid_integer=<red>Please enter a valid integer.</red>
validation.invalid_string=<red>Input cannot be empty.</red>
validation.answer_too_long=<red>Input exceeds maximum length of %max% characters.</red>
validation.delegated_single_argument=<red>Input must be a single word and cannot start with @.</red>
player_ui.search_instruction=<gold>Type your search term in chat.</gold>
dialog.no_options=<yellow>No options available, enter argument manually.</yellow>
dialog.too_many_options=<yellow>Too many options (%count%), enter argument manually.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_es_ES.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>El comando falló: %message%</red>
validation.invalid_integer=<red>Por favor, introduce un número entero válido.</red>
validation.invalid_string=<red>La entrada no puede estar vacía.</red>
validation.answer_too_long=<red>La entrada excede la longitud máxima de %max% caracteres.</red>
validation.delegated_single_argument=<red>La entrada debe ser una sola palabra y no puede empezar por @.</red>
player_ui.search_instruction=<gold>Escribe tu término de búsqueda en el chat.</gold>
dialog.no_options=<yellow>No hay opciones disponibles, introduce el argumento manualmente.</yellow>
dialog.too_many_options=<yellow>Demasiadas opciones (%count%), introduce el argumento manualmente.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_fr_FR.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>Échec de la commande : %message%</red>
validation.invalid_integer=<red>Veuillez entrer un entier valide.</red>
validation.invalid_string=<red>La saisie ne peut pas être vide.</red>
validation.answer_too_long=<red>La saisie dépasse la longueur maximale de %max% caractères.</red>
validation.delegated_single_argument=<red>La saisie doit être un seul mot et ne peut pas commencer par @.</red>
player_ui.search_instruction=<gold>Tapez votre terme de recherche dans le chat.</gold>
dialog.no_options=<yellow>Aucune option disponible, entrez l'argument manuellement.</yellow>
dialog.too_many_options=<yellow>Trop d'options (%count%), entrez l'argument manuellement.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_ja_JP.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>コマンドの実行に失敗しました:%m
validation.invalid_integer=<red>有効な整数を入力してください。</red>
validation.invalid_string=<red>入力内容を空にすることはできません。</red>
validation.answer_too_long=<red>入力が最大文��数(%max%文字)を超えています。</red>
validation.delegated_single_argument=<red>入力は1語のみで、@ で始めることはできません。</red>
player_ui.search_instruction=<gold>チャットに検索キーワードを入力してください。</gold>
dialog.no_options=<yellow>利用可能な選択肢がありません。引数を手動で入力してください。</yellow>
dialog.too_many_options=<yellow>選択肢が多すぎます(%count%件)。引数を手動で入力してください。</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_ko_KR.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>명령 실행에 실패했습니다: %message%<
validation.invalid_integer=<red>유효한 정수를 입력해 주세요.</red>
validation.invalid_string=<red>입력 내용은 비워 둘 수 없습니다.</red>
validation.answer_too_long=<red>입력 내용이 최대 길이(%max%자)를 초과했습니다.</red>
validation.delegated_single_argument=<red>입력은 한 단어여야 하며 @로 시작할 수 없습니다.</red>
player_ui.search_instruction=<gold>채팅창에 검색어를 입력하세요.</gold>
dialog.no_options=<yellow>사용 가능한 옵션이 없습니다. 인수를 직접 입력해 주세요.</yellow>
dialog.too_many_options=<yellow>옵션이 너무 많습니다 (%count%개). 인수를 직접 입력해 주세요.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_pirate.properties
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ prompt.error.command_failed=<red>The command ran aground: %message%</red>
validation.invalid_integer=<red>Enter a proper whole number, landlubber.</red>
validation.invalid_string=<red>Ye cannot submit an empty message.</red>
validation.answer_too_long=<red>Yer yarn be too long! Keep it under %max% letters.</red>
validation.delegated_single_argument=<red>Yer answer must be a single word, and it cannot start with @!</red>
player_ui.search_instruction=<gold>Speak yer search words into the chat.</gold>
dialog.no_options=<yellow>No choices be available. Enter the argument by hand.</yellow>
dialog.too_many_options=<yellow>Too many choices aboard (%count%). Enter the argument by hand.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_pl_PL.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>Wykonanie polecenia nie powiodło się: %messag
validation.invalid_integer=<red>Proszę podać prawidłową liczbę całkowitą.</red>
validation.invalid_string=<red>Pole nie może być puste.</red>
validation.answer_too_long=<red>Wprowadzony tekst przekracza maksymalną długość %max% znaków.</red>
validation.delegated_single_argument=<red>Wpis musi być jednym słowem i nie może zaczynać się od @.</red>
player_ui.search_instruction=<gold>Wpisz wyszukiwaną frazę na czacie.</gold>
dialog.no_options=<yellow>Brak dostępnych opcji, podaj argument ręcznie.</yellow>
dialog.too_many_options=<yellow>Zbyt wiele opcji (%count%), podaj argument ręcznie.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_pt_BR.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>O comando falhou: %message%</red>
validation.invalid_integer=<red>Por favor, insira um número inteiro válido.</red>
validation.invalid_string=<red>A entrada não pode estar vazia.</red>
validation.answer_too_long=<red>A entrada excede o comprimento máximo de %max% caracteres.</red>
validation.delegated_single_argument=<red>A entrada deve ser uma única palavra e não pode começar com @.</red>
player_ui.search_instruction=<gold>Digite seu termo de busca no chat.</gold>
dialog.no_options=<yellow>Nenhuma opção disponível, insira o argumento manualmente.</yellow>
dialog.too_many_options=<yellow>Opções demais (%count%), insira o argumento manualmente.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_tl_PH.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>Nabigo ang utos: %message%</red>
validation.invalid_integer=<red>Mangyaring magpasok ng tamang integer.</red>
validation.invalid_string=<red>Hindi maaaring walang laman ang input.</red>
validation.answer_too_long=<red>Lumampas ang input sa pinakamataas na haba na %max% character.</red>
validation.delegated_single_argument=<red>Dapat isang salita lang ang input at hindi maaaring magsimula sa @.</red>
player_ui.search_instruction=<gold>I-type ang iyong hinahanap sa chat.</gold>
dialog.no_options=<yellow>Walang available na opsyon, ilagay ang argumento nang manu-mano.</yellow>
dialog.too_many_options=<yellow>Masyadong maraming opsyon (%count%), ilagay ang argumento nang manu-mano.</yellow>
Expand Down
1 change: 1 addition & 0 deletions prompt-paper/src/main/resources/messages_zh_CN.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ prompt.error.command_failed=<red>命令执行失败:%message%</red>
validation.invalid_integer=<red>请输入一个有效的整数。</red>
validation.invalid_string=<red>输入内容不能为空。</red>
validation.answer_too_long=<red>输入内容超过了最大长度 %max% 个字符。</red>
validation.delegated_single_argument=<red>输入必须是单个词,且不能以 @ 开头。</red>
player_ui.search_instruction=<gold>请在聊天框中输入搜索关键词。</gold>
dialog.no_options=<yellow>暂无可用选项,请手动输入参数。</yellow>
dialog.too_many_options=<yellow>选项过多(%count%),请手动输入参数。</yellow>
Expand Down
Loading
Loading