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
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,19 @@ public InputScreen create(Player player, PromptDefinition def, DialogCompletionC
return createExpanded(player, presentationExpander.expand(player, def), context);
}

/**
* Builds the screen for a definition mapped from an inline tag. Inline text is player-authored,
* so it goes through {@link PromptPresentationExpander#expandInline} instead of the preset path.
*/
private InputScreen createInline(
Player player, PromptDefinition def, DialogCompletionContext context, boolean trustedOrigin) {
plugin
.getPluginLogger()
.debug("PromptFactory.createInline: player=" + player.getName() + " type=" + def.type());
return createExpanded(
player, presentationExpander.expandInline(player, def, trustedOrigin), context);
}

/**
* Builds the screen from an already-expanded definition. Never expands again — the public {@link
* #create(Player, PromptDefinition, DialogCompletionContext)} is the only entry point allowed to
Expand Down Expand Up @@ -238,14 +251,30 @@ public InputScreen createFromTag(Player player, PromptTag tag) {
* <li><b>Presets</b> look up the registry with the <b>raw</b> {@code displayText} (the id is a
* semantic key, never expanded) and delegate to {@link #create}, which expands the resolved
* definition once.
* <li><b>Inline dialogs / compound tags</b> expand a presentation-only copy of the tag via
* <li><b>Inline dialogs / compound tags</b> materialize a presentation-only copy of the tag via
* {@link PromptPresentationExpander#expandInlineDialog} and build the dialog screen
* directly from that copy.
* <li><b>Other inline tags</b> map the raw tag and delegate to {@link #create}, which expands
* once.
* <li><b>Other inline tags</b> map the raw tag and materialize it once via {@link
* PromptPresentationExpander#expandInline}.
* </ul>
*
* <p>Inline text is typed by the player, so placeholders in it are only resolved for players
* holding {@code promptpaper.inline.placeholders} or for a trusted origin (see the four-argument
* overload); preset text is always resolved.
*/
public InputScreen createFromTag(Player player, PromptTag tag, DialogCompletionContext context) {
return createFromTag(player, tag, context, false);
}

/**
* As {@link #createFromTag(Player, PromptTag, DialogCompletionContext)}.
*
* @param trustedOrigin {@code true} when the command line holding the tag was written by the
* console ({@code /consoledelegate}, {@code /playerdelegate}) rather than typed by a player;
* placeholders in its inline text are then resolved.
*/
public InputScreen createFromTag(
Player player, PromptTag tag, DialogCompletionContext context, boolean trustedOrigin) {
if (tag == null) throw new IllegalArgumentException("PromptTag must not be null");
if (tag.isPreset()) {
// Lookup uses the raw displayText — a PAPI-looking preset id must never be expanded.
Expand Down Expand Up @@ -278,12 +307,12 @@ public InputScreen createFromTag(Player player, PromptTag tag, DialogCompletionC
if (isDialog) {
// Expand the presentation-only copy of the tag, then build the dialog screen directly so
// the expanded fields are materialized exactly once.
var expandedTag = presentationExpander.expandInlineDialog(player, tag);
var expandedTag = presentationExpander.expandInlineDialog(player, tag, trustedOrigin);
var dialogScreen = new DialogPromptScreen(plugin, player, expandedTag, promptConfig, context);
return wrapWithTagTitle(player, expandedTag, dialogScreen);
}
var def = InlineTagMapper.toPromptDefinition(tag, mappings);
return create(player, def, context);
return createInline(player, def, context, trustedOrigin);
}

private ChatPromptScreen createChat(Player player, ChatPrompt chat) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@
* {@code title.main} / {@code title.sub}.
* </ul>
*
* <h2>Origin</h2>
*
* <p>Only preset-sourced definitions ({@link #expand}) are sent to the expansion delegate. Inline
* tags are written on the command line by the player, so {@link #expandInline} and {@link
* #expandInlineDialog} leave their text unexpanded (length-bounded only) unless the player holds
* {@value #INLINE_PLACEHOLDER_PERMISSION} or the caller marks the tag as written by the console
* ({@code /consoledelegate}, {@code /playerdelegate}).
*
* <h2>Never expanded</h2>
*
* <p>Preset ids, tag keys, {@code rawTag}, filters, validator aliases, answer types, {@code
Expand All @@ -65,13 +73,19 @@ final class PromptPresentationExpander {

static final int MAX_DISPLAY_LENGTH = 1024;

/** Opt-in permission that lets a player's own inline prompt text reach the expansion delegate. */
static final String INLINE_PLACEHOLDER_PERMISSION = "promptpaper.inline.placeholders";

@FunctionalInterface
interface TruncationListener {
void onTruncate(Player player, int originalLength, int maxLength);
}

private final BiFunction<Player, String, String> expander;
private final TruncationListener truncationListener;
// Same length bounding, but text never reaches the expansion delegate. Null on the literal
// instance itself.
private final PromptPresentationExpander literal;

/**
* @param expander the per-field expansion function (e.g. a PAPI hook). Injected so tests can use
Expand All @@ -88,8 +102,19 @@ interface TruncationListener {
*/
PromptPresentationExpander(
BiFunction<Player, String, String> expander, TruncationListener truncationListener) {
this(expander, truncationListener, true);
}

private PromptPresentationExpander(
BiFunction<Player, String, String> expander,
TruncationListener truncationListener,
boolean withLiteral) {
this.expander = Objects.requireNonNull(expander, "expander");
this.truncationListener = Objects.requireNonNull(truncationListener, "truncationListener");
this.literal =
withLiteral
? new PromptPresentationExpander((player, text) -> text, truncationListener, false)
: null;
}

/**
Expand Down Expand Up @@ -121,7 +146,11 @@ static PromptPresentationExpander forPlugin(CommandPrompter plugin) {
});
}

/** Expands every player-visible presentation field of the definition; semantic fields are raw. */
/**
* Expands every player-visible presentation field of a <b>preset-sourced</b> definition; semantic
* fields are raw. Never pass a definition mapped from an inline tag here — use {@link
* #expandInline}.
*/
PromptDefinition expand(Player player, PromptDefinition raw) {
Objects.requireNonNull(raw, "raw");
return switch (raw) {
Expand Down Expand Up @@ -169,15 +198,48 @@ private dev.cyr1en.promptpaper.preset.ConfirmationPrompt expandConfirmation(
confirmation.behavior());
}

/**
* Materializes a definition mapped from an inline tag. Its text is player-authored, so it is
* passed through unexpanded unless the player holds {@value #INLINE_PLACEHOLDER_PERMISSION}.
*/
PromptDefinition expandInline(Player player, PromptDefinition raw) {
return expandInline(player, raw, false);
}

/**
* @param trustedOrigin {@code true} when the inline tag was written by the console ({@code
* /consoledelegate}, {@code /playerdelegate}), not typed by a player; such text is expanded.
*/
PromptDefinition expandInline(Player player, PromptDefinition raw, boolean trustedOrigin) {
return forInline(player, trustedOrigin).expand(player, raw);
}

private PromptPresentationExpander forInline(Player player, boolean trustedOrigin) {
if (literal == null || trustedOrigin) return this;
return player != null && player.hasPermission(INLINE_PLACEHOLDER_PERMISSION) ? this : literal;
}

/**
* Expands the presentation-only copy of an inline (compound) dialog tag: every sub-tag's {@code
* displayText} (recursively) plus the {@code -t} title config. All parser/semantic components
* ({@code rawTag}, {@code key}, {@code filter}, {@code validatorAlias}, {@code type}, {@code
* sanitize}, {@code preset}) are copied through unchanged.
*
* <p>The text is player-authored: it only reaches the expansion delegate when the player holds
* {@value #INLINE_PLACEHOLDER_PERMISSION}.
*/
PromptTag expandInlineDialog(Player player, PromptTag raw) {
return expandInlineDialog(player, raw, false);
}

/** As {@link #expandInlineDialog(Player, PromptTag)}; see {@link #expandInline} for the flag. */
PromptTag expandInlineDialog(Player player, PromptTag raw, boolean trustedOrigin) {
Objects.requireNonNull(raw, "raw");
var subTags = raw.subTags().stream().map(sub -> expandInlineDialog(player, sub)).toList();
return forInline(player, trustedOrigin).expandTag(player, raw);
}

private PromptTag expandTag(Player player, PromptTag raw) {
var subTags = raw.subTags().stream().map(sub -> expandTag(player, sub)).toList();
return new PromptTag(
raw.rawTag(),
raw.key(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,30 @@ public class ScreenManager {
@FunctionalInterface
public interface ScreenCreator {
InputScreen create(Player player, PromptTag tag, DialogCompletionContext context);

/**
* @param trustedOrigin whether the command line was written by the console ({@code
* /consoledelegate}, {@code /playerdelegate}) instead of typed by a player
*/
default InputScreen create(
Player player, PromptTag tag, DialogCompletionContext context, boolean trustedOrigin) {
return create(player, tag, context);
}
}

private static ScreenCreator factoryCreator(PromptFactory factory) {
return new ScreenCreator() {
@Override
public InputScreen create(Player player, PromptTag tag, DialogCompletionContext context) {
return factory.createFromTag(player, tag, context);
}

@Override
public InputScreen create(
Player player, PromptTag tag, DialogCompletionContext context, boolean trustedOrigin) {
return factory.createFromTag(player, tag, context, trustedOrigin);
}
};
}

public enum DispatchMode {
Expand Down Expand Up @@ -84,7 +108,8 @@ public enum DispatchMode {

public ScreenManager(
CommandPrompter plugin, PromptEngine engine, PromptFactory factory, Scheduler scheduler) {
this(plugin, engine, factory, scheduler, factory != null ? factory::createFromTag : null, null);
this(
plugin, engine, factory, scheduler, factory != null ? factoryCreator(factory) : null, null);
}

public ScreenManager(
Expand Down Expand Up @@ -139,7 +164,7 @@ public ScreenManager(
this.factory = factory;
this.scheduler = scheduler;
this.screenCreator =
screenCreator != null ? screenCreator : (factory != null ? factory::createFromTag : null);
screenCreator != null ? screenCreator : (factory != null ? factoryCreator(factory) : null);
this.playerExecutorFactory =
playerExecutorFactory != null
? playerExecutorFactory
Expand Down Expand Up @@ -525,10 +550,13 @@ private void showPrompt(Player player, PromptTag tag) {
}
} else {
var context = buildCompletionContext(player, tag);
// Both delegate commands are console-only, so the console wrote this command line.
var mode = dispatchModes.get(uuid);
var trustedOrigin = mode == DispatchMode.CONSOLE || mode == DispatchMode.ATTACHMENT;
screen =
screenCreator != null
? screenCreator.create(player, tag, context)
: factory.createFromTag(player, tag, context);
? screenCreator.create(player, tag, context, trustedOrigin)
: factory.createFromTag(player, tag, context, trustedOrigin);
}

if (screen == null) {
Expand Down
3 changes: 3 additions & 0 deletions prompt-paper/src/main/resources/paper-plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ permissions:
description: Allows using /commandprompter version
promptpaper.use:
description: Allows using prompt features
promptpaper.inline.placeholders:
description: Resolves PlaceholderAPI placeholders in inline prompt text typed by the player
default: false
promptpaper.consoledelegate:
description: Allows using /consoledelegate
promptpaper.playerdelegate:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,40 @@ void startDelegatedSessionWithPromptsCreatesScreen() {
assertTrue(screenManager.hasActiveScreen(player));
}

@Test
void onlyDelegatedInlineTagsAreCreatedWithTrustedOrigin() {
var origins = new java.util.ArrayList<Boolean>();
var recording =
new ScreenManager.ScreenCreator() {
@Override
public dev.cyr1en.promptui.InputScreen create(
Player p,
dev.cyr1en.promptcore.PromptTag tag,
dev.cyr1en.promptpaper.screen.dialog.DialogCompletionContext context) {
return factory.createFromTag(p, tag, context);
}

@Override
public dev.cyr1en.promptui.InputScreen create(
Player p,
dev.cyr1en.promptcore.PromptTag tag,
dev.cyr1en.promptpaper.screen.dialog.DialogCompletionContext context,
boolean trustedOrigin) {
origins.add(trustedOrigin);
return factory.createFromTag(p, tag, context, trustedOrigin);
}
};
var manager = new ScreenManager(plugin, engine, factory, scheduler, recording, null);

manager.startDelegatedSession(
createPlayer(), "/cmd <test>", ScreenManager.DispatchMode.CONSOLE, null);
manager.startSession(createPlayer(), "/cmd <test>");
manager.startDelegatedSession(
createPlayer(), "/cmd <test>", ScreenManager.DispatchMode.ATTACHMENT, "some.key");

assertEquals(java.util.List.of(true, false, true), origins);
}

@Test
void handleChatInputProcessesAnswer() {
var player = createPlayer();
Expand Down Expand Up @@ -489,7 +523,7 @@ void presetDialogWithTabCompletionBuildsCompletionContext() {
java.util.Map.of()));

var dummyScreen = org.mockito.Mockito.mock(dev.cyr1en.promptui.InputScreen.class);
when(mockFactory.createFromTag(any(Player.class), any(PromptTag.class), any()))
when(mockFactory.createFromTag(any(Player.class), any(PromptTag.class), any(), eq(false)))
.thenReturn(dummyScreen);

var player = createPlayer();
Expand All @@ -498,7 +532,8 @@ void presetDialogWithTabCompletionBuildsCompletionContext() {
var captor =
org.mockito.ArgumentCaptor.forClass(
dev.cyr1en.promptpaper.screen.dialog.DialogCompletionContext.class);
verify(mockFactory).createFromTag(eq(player), any(PromptTag.class), captor.capture());
verify(mockFactory)
.createFromTag(eq(player), any(PromptTag.class), captor.capture(), eq(false));

assertNotNull(captor.getValue());
assertEquals("/cmd ", captor.getValue().partialCommand());
Expand Down Expand Up @@ -529,7 +564,7 @@ void presetDialogWithoutTabCompletionPassesNullContext() {
when(registry.getPrompt("my_conf_preset")).thenReturn(java.util.Optional.of(dialog));

var dummyScreen = org.mockito.Mockito.mock(dev.cyr1en.promptui.InputScreen.class);
when(mockFactory.createFromTag(any(Player.class), any(PromptTag.class), any()))
when(mockFactory.createFromTag(any(Player.class), any(PromptTag.class), any(), eq(false)))
.thenReturn(dummyScreen);

var player = createPlayer();
Expand All @@ -538,7 +573,8 @@ void presetDialogWithoutTabCompletionPassesNullContext() {
var captor =
org.mockito.ArgumentCaptor.forClass(
dev.cyr1en.promptpaper.screen.dialog.DialogCompletionContext.class);
verify(mockFactory).createFromTag(eq(player), any(PromptTag.class), captor.capture());
verify(mockFactory)
.createFromTag(eq(player), any(PromptTag.class), captor.capture(), eq(false));

assertNull(captor.getValue());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -814,18 +814,44 @@ void emptyTitleMainIsPreservedAndFallbackUsesExpandedPromptTextOnce() {
}

/**
* A non-dialog inline tag flows through {@link InlineTagMapper} on the raw tag and then {@link
* PromptFactory#create}, so the display text is expanded exactly once (never twice by the mapper
* and the factory).
* Inline tag text is typed by the player, so neither the mapped (non-dialog) path nor the inline
* dialog path may send it to the expansion delegate.
*/
@Test
void inlineTagDisplayTextIsExpandedExactlyOnce() {
void inlineTagDisplayTextNeverReachesExpander() {
List<String> expanded = new ArrayList<>();
var testFactory = factoryWithExpander(expanded);

var anvil = new PromptTag("<a:Enter %player_name%>", "a", null, "Enter %player_name%");
assertInstanceOf(AnvilPromptScreen.class, testFactory.createFromTag(createPlayer(), anvil));

var dialog = new PromptTag("<d:text:Enter %player_name%>", "d", "text", "Enter %player_name%");
try {
testFactory.createFromTag(createPlayer("Other"), dialog);
} catch (NoClassDefFoundError ignored) {
// Paper's dialog API is absent from the test classpath; the tag is materialized before the
// dialog screen is constructed, so the assertion below still covers the dialog path.
}

assertTrue(expanded.isEmpty(), "inline text reached the expander: " + expanded);
}

/**
* With the opt-in permission, a non-dialog inline tag flows through {@link InlineTagMapper} on
* the raw tag and is expanded exactly once (never twice by the mapper and the factory).
*/
@Test
void inlineTagDisplayTextIsExpandedExactlyOnceWithOptInPermission() {
var tag = new PromptTag("<a:Enter %player_name%>", "a", null, "Enter %player_name%");

List<String> expanded = new ArrayList<>();
var testFactory = factoryWithExpander(expanded);
var player = createPlayer();
player
.addAttachment(plugin)
.setPermission(PromptPresentationExpander.INLINE_PLACEHOLDER_PERMISSION, true);

var screen = testFactory.createFromTag(createPlayer(), tag);
var screen = testFactory.createFromTag(player, tag);

assertInstanceOf(AnvilPromptScreen.class, screen);
assertEquals(1, Collections.frequency(expanded, "Enter %player_name%"));
Expand Down
Loading
Loading