Paper Proxy Messaging
ASecurityPaper 與 BungeeCord/Velocity 代理的 plugin messaging:BungeeCord 頻道(Connect 傳送、PlayerCount、GetServers、GetServer、Forward 跨伺服器自訂訊息)、需要線上玩家當載體、回應以 CompletableFuture 配對並逾時、Velocity bungee-plugin-message-channel、轉發資料視為不可信 / Paper plugin messaging with BungeeCord / Velocity proxies: the BungeeCord channel (Connect, PlayerCount, GetServers, GetServer, Forward for cross-server messages), a connected player as carrier, responses matched to CompletableFutures with timeouts, Velocity bungee-plugin-message-ch...
- 3 stars
- 0 votes
- 0 copies
- 0 views
- Added December 5, 2026
Works with
Security analysis
100/100Pro scans all 4 files and shows the line behind each finding
npx -y skills add MrPippi/MJP-Paper-Skills --skill paper-proxy-messaging --agent claude-codeAre you the author of Paper Proxy Messaging?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/mrpippi-paper-proxy-messaging)---
name: paper-proxy-messaging
description: "Paper 與 BungeeCord/Velocity 代理的 plugin messaging:BungeeCord 頻道(Connect 傳送、PlayerCount、GetServers、GetServer、Forward 跨伺服器自訂訊息)、需要線上玩家當載體、回應以 CompletableFuture 配對並逾時、Velocity bungee-plugin-message-channel、轉發資料視為不可信 / Paper plugin messaging with BungeeCord / Velocity proxies: the BungeeCord channel (Connect, PlayerCount, GetServers, GetServer, Forward for cross-server messages), a connected player as carrier, responses matched to CompletableFutures with timeouts, Velocity bungee-plugin-message-channel, forwarded data treated as untrusted"
---
# Paper Proxy Messaging
## Skill Name
`paper-proxy-messaging`
## Purpose
Backend servers behind BungeeCord or Velocity talk to the proxy through plugin messages on the `BungeeCord` channel: send a player to another server, ask how many players a server has, list the servers, or forward custom data to other backends. The protocol is old and has traps that make code fail silently:
| Trap | Detail |
|------|------|
| Needs a player | Plugin messages travel over a player's connection. With nobody online, nothing can be sent or received |
| Silent drop | Paper only sends on a channel the connection has registered (`CraftPlayer#sendPluginMessage` checks `channels()`); the proxy registers `bungeecord:main` for its players. Not behind a proxy, or Velocity with `bungee-plugin-message-channel = false`: every message is dropped without an error |
| No request ids | Responses carry the subchannel and the arguments only; match them yourself (e.g. `PlayerCount` by server name) and time out, because a request may never be answered |
| `ALL` excludes you | `Forward` to `ALL` reaches every other server, not the sender; a target server with no players cannot receive it |
| The `player` argument | `onPluginMessageReceived(channel, player, data)` gives the carrier connection, not the player the message is about |
Read from Paper 26.3 build 273: `StandardMessenger.validateAndCorrectChannel` maps `BungeeCord` ↔ `bungeecord:main`, so plugins keep using `BungeeCord`; incoming custom payloads are dispatched on the thread that processes packets (the main thread on Paper).
## Paper Version Requirements
- Paper 1.21.11 / 26.3: `Messenger`, `PluginMessageListener`, `PluginMessageRecipient#sendPluginMessage` have identical signatures on both; compile-verified on both
- Proxies: BungeeCord (built in), Velocity with `bungee-plugin-message-channel = true` in `velocity.toml`
- Without a proxy, `Player#transfer(host, port)` (1.20.5+) moves a player to another server directly; the target must set `accepts-transfers=true`
- **Spigot**: the same API exists; this template runs there unchanged except for the Brigadier command and the Folia-compatible scheduler calls
## Triggers
- 「BungeeCord 頻道」「BungeeCord channel」「plugin messaging」「plugin message」「跨伺服器」「cross-server」
- 「傳送到其他伺服器」「send player to server」「Connect 子頻道」「PlayerCount」「GetServers」「Forward」
- 「Velocity 訊息」「代理伺服器」「proxy」「大廳指令 /hub」「全網廣播」
## Inputs
| Parameter | Example | Description |
|------|------|------|
| `proxy` | Velocity | BungeeCord or Velocity (Velocity needs `bungee-plugin-message-channel`) |
| `servers` | `lobby`, `survival` | Server names as configured on the proxy |
| `requests` | player count of `survival` | Data the backend needs from the proxy |
| `forwarded_messages` | network-wide announcement | Custom data sent to other backends |
## Outputs
- `ProxyMessenger.java` — sends requests through any online player, matches responses to futures with a timeout, dispatches forwarded custom messages
- `NoCarrierException.java` — failure when no player is online to carry a message
- `ProxyPlugin.java` — channel registration, `/hub`, a network-wide `/announce` with `Forward`
## Build Setup
See [`references/paper-api-platform.md`](references/paper-api-platform.md). Only `paper-api` (`compileOnly`). Set `bungeecord: true` in `spigot.yml` (BungeeCord) or Velocity modern forwarding in `config/paper-global.yml`; that is login forwarding, separate from messaging.
## Code Template
### `NoCarrierException.java`
```java
package com.example.proxy;
/** Plugin messages need a player connection; thrown when nobody is online. */
public final class NoCarrierException extends IllegalStateException {
public NoCarrierException() {
super("No player online to carry the plugin message");
}
}
```
### `ProxyMessenger.java`
```java
package com.example.proxy;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.PluginMessageListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* BungeeCord-channel client for BungeeCord and Velocity. Responses have no request ids, so pending requests
* are queued per key ("PlayerCount:survival") and completed in order; each one times out.
*/
public final class ProxyMessenger implements PluginMessageListener {
public static final String CHANNEL = "BungeeCord"; // Paper maps it to bungeecord:main
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private static final int MAX_FORWARD_BYTES = Short.MAX_VALUE;
private static final List<String> RESERVED = List.of("Connect", "ConnectOther", "IP", "IPOther", "PlayerCount",
"PlayerList", "GetServers", "Message", "MessageRaw", "GetServer", "GetPlayerServer", "Forward",
"ForwardToPlayer", "UUID", "UUIDOther", "ServerIP", "KickPlayer", "KickPlayerRaw");
private final Plugin plugin;
private final Map<String, Queue<CompletableFuture<String[]>>> pending = new ConcurrentHashMap<>();
private final Map<String, Consumer<byte[]>> forwardHandlers = new ConcurrentHashMap<>();
public ProxyMessenger(Plugin plugin) {
this.plugin = plugin;
}
public void register() {
plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, CHANNEL);
plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, CHANNEL, this);
}
public void unregister() {
plugin.getServer().getMessenger().unregisterOutgoingPluginChannel(plugin, CHANNEL);
plugin.getServer().getMessenger().unregisterIncomingPluginChannel(plugin, CHANNEL, this);
pending.values().forEach(queue -> queue.forEach(f -> f.cancel(false)));
pending.clear();
}
/** Runs a stage on the main thread (Paper) / global region (Folia): use with whenCompleteAsync. */
public Executor sync() {
return task -> plugin.getServer().getGlobalRegionScheduler().execute(plugin, task);
}
/** Sends the player to another server. No response; nothing happens if the name is unknown. */
public void connect(Player player, String server) {
player.sendPluginMessage(plugin, CHANNEL, encode("Connect", server));
}
public CompletableFuture<Integer> playerCount(String server) {
return request("PlayerCount:" + server, encode("PlayerCount", server)).thenApply(r -> Integer.parseInt(r[1]));
}
public CompletableFuture<List<String>> servers() {
return request("GetServers", encode("GetServers")).thenApply(r -> r[0].isEmpty() ? List.<String>of() : List.of(r[0].split(", ")));
}
/** The name the proxy uses for this server. */
public CompletableFuture<String> serverName() {
return request("GetServer", encode("GetServer")).thenApply(r -> r[0]);
}
/**
* Sends custom data to another server ("ALL" = every other server). Only servers with a player online receive
* it. @return false when no player is online here to carry it
*/
public boolean forward(String target, String subchannel, byte[] payload) {
if (RESERVED.contains(subchannel)) {
throw new IllegalArgumentException("Subchannel " + subchannel + " collides with a BungeeCord command");
}
if (payload.length > MAX_FORWARD_BYTES) {
throw new IllegalArgumentException("Forward payload too large: " + payload.length + " bytes");
}
Optional<? extends Player> carrier = carrier();
if (carrier.isEmpty()) {
return false;
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeUTF("Forward");
out.writeUTF(target);
out.writeUTF(subchannel);
out.writeShort(payload.length);
out.write(payload);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
carrier.get().sendPluginMessage(plugin, CHANNEL, bytes.toByteArray());
return true;
}
/** Handler for data forwarded by other servers. Runs on the packet thread; treat the payload as untrusted. */
public void onForward(String subchannel, Consumer<byte[]> handler) {
forwardHandlers.put(subchannel, handler);
}
@Override
public void onPluginMessageReceived(String channel, Player carrier, byte[] message) {
if (!CHANNEL.equals(channel)) {
return;
}
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(message))) {
String subchannel = in.readUTF();
switch (subchannel) {
case "PlayerCount" -> {
String server = in.readUTF();
complete("PlayerCount:" + server, new String[] {server, Integer.toString(in.readInt())});
}
case "GetServers" -> complete("GetServers", new String[] {in.readUTF()});
case "GetServer" -> complete("GetServer", new String[] {in.readUTF()});
default -> {
Consumer<byte[]> handler = forwardHandlers.get(subchannel);
if (handler != null) {
byte[] payload = new byte[in.readUnsignedShort()];
in.readFully(payload);
handler.accept(payload);
}
}
}
} catch (IOException | RuntimeException e) {
plugin.getLogger().warning("Malformed BungeeCord message: " + e);
}
}
private CompletableFuture<String[]> request(String key, byte[] data) {
Optional<? extends Player> carrier = carrier();
if (carrier.isEmpty()) {
return CompletableFuture.failedFuture(new NoCarrierException());
}
CompletableFuture<String[]> future = new CompletableFuture<>();
Queue<CompletableFuture<String[]>> queue = pending.computeIfAbsent(key, k -> new ConcurrentLinkedQueue<>());
queue.add(future);
future.orTimeout(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS).whenComplete((r, e) -> queue.remove(future));
carrier.get().sendPluginMessage(plugin, CHANNEL, data);
return future;
}
private void complete(String key, String[] response) {
Queue<CompletableFuture<String[]>> queue = pending.get(key);
CompletableFuture<String[]> future;
while (queue != null && (future = queue.poll()) != null) {
if (future.complete(Arrays.copyOf(response, response.length))) {
return; // one response answers the oldest request still waiting
}
}
}
private Optional<? extends Player> carrier() {
Server server = plugin.getServer();
return server.getOnlinePlayers().stream().findAny();
}
private static byte[] encode(String... fields) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
for (String field : fields) {
out.writeUTF(field);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
}
```
### `ProxyPlugin.java`
```java
package com.example.proxy;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.StringArgumentType;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.nio.charset.StandardCharsets;
public final class ProxyPlugin extends JavaPlugin {
private static final String LOBBY = "lobby";
private static final String ANNOUNCE = "example:announce"; // custom subchannel, namespaced to avoid clashes
private static final int MAX_ANNOUNCE_LENGTH = 256;
private ProxyMessenger messenger;
@Override
public void onEnable() {
messenger = new ProxyMessenger(this);
messenger.register();
messenger.onForward(ANNOUNCE, payload -> {
String text = new String(payload, StandardCharsets.UTF_8);
if (text.length() <= MAX_ANNOUNCE_LENGTH) { // forwarded data is untrusted input
getServer().broadcast(Component.text("[Network] " + text, NamedTextColor.GOLD));
}
});
getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event -> {
event.registrar().register(Commands.literal("hub")
.requires(source -> source.getExecutor() instanceof Player)
.executes(context -> {
if (context.getSource().getExecutor() instanceof Player player) {
messenger.connect(player, LOBBY);
}
return Command.SINGLE_SUCCESS;
}).build(), "Go to the lobby");
event.registrar().register(Commands.literal("announce")
.requires(source -> source.getSender().hasPermission("proxy.announce"))
.then(Commands.argument("text", StringArgumentType.greedyString()).executes(context -> {
String text = StringArgumentType.getString(context, "text");
if (text.length() > MAX_ANNOUNCE_LENGTH) {
context.getSource().getSender().sendMessage(Component.text("Too long.", NamedTextColor.RED));
return 0;
}
getServer().broadcast(Component.text("[Network] " + text, NamedTextColor.GOLD)); // ALL skips this server
if (!messenger.forward("ALL", ANNOUNCE, text.getBytes(StandardCharsets.UTF_8))) {
context.getSource().getSender().sendMessage(
Component.text("Only sent here: nobody online to carry it.", NamedTextColor.YELLOW));
}
return Command.SINGLE_SUCCESS;
})).build(), "Announce on every server");
});
}
@Override
public void onDisable() {
if (messenger != null) {
messenger.unregister();
}
}
}
```
Reading a response on the main thread:
```java
messenger.playerCount("survival").whenCompleteAsync((count, error) -> {
if (error != null) {
sign.line(1, Component.text("offline")); // timeout, NoCarrierException, or the server name is unknown
} else {
sign.line(1, Component.text(count + " online"));
}
}, messenger.sync());
```
## Recommended Directory Structure
```
src/main/java/com/example/proxy/
├── NoCarrierException.java <- nobody online to carry a message
├── ProxyMessenger.java <- requests, responses, Forward
└── ProxyPlugin.java <- channels, /hub, /announce
```
## Thread Safety
- `onPluginMessageReceived` runs on the thread that processes packets (main thread on Paper, the carrier's region on Folia); forward handlers run there too
- `sendPluginMessage` only queues a packet and may be called from any thread
- Futures complete on the packet thread, or on the JDK timer thread when they time out. Continue with `whenCompleteAsync(..., messenger.sync())` before touching the world
- Pending queues and handlers are concurrent maps
- See [`references/paper-threading.md`](references/paper-threading.md)
### Key Techniques
| Topic | Approach |
|------|------|
| Message format | `DataOutputStream#writeUTF` for every field; subchannel first |
| Response matching | Queue of futures per key (`PlayerCount:<server>`, `GetServers`), oldest first, 5 s timeout |
| Carrier | Any online player; requests fail with `NoCarrierException` when the server is empty |
| Custom data | `Forward` with a namespaced subchannel (`example:announce`), `writeShort(length)` then the bytes (max 32767) |
| Receiving forwarded data | Same channel; the first UTF is your subchannel, then `readUnsignedShort` length and the bytes |
| Move a player | `Connect` from that player's connection; `ConnectOther` moves a player on another server |
| Empty-server problem | Keep state that must survive (bans, mail) in a database or Redis, not only in plugin messages |
## Fallback
| Error | Cause | Fix |
|------|------|------|
| Nothing happens, no error | Not behind a proxy, Velocity `bungee-plugin-message-channel = false`, or the player joined directly | Enable the option on Velocity; test through the proxy |
| Requests always time out on an empty server | No player to carry the message | Expected; fall back to a cached value or a database |
| `PlayerCount` answers mixed up between servers | Responses matched by arrival order only | Match by subchannel and server name (this template) |
| Forwarded message never arrives | Target server has no players, or `ALL` used and you expected the sender to receive it | Apply it locally as well; store durable data elsewhere |
| `IllegalArgumentException` / `ChannelNameTooLongException` | Custom channel name without a namespace, or longer than `Messenger.MAX_CHANNEL_SIZE` | Use `namespace:name`; for the BungeeCord channel just use `BungeeCord` |
| `Connect` does nothing | Server name differs from the proxy config (case-sensitive) | Use `servers()` to list the exact names |
| Handler acts on a forged message | A client or another plugin sent data on your subchannel | Validate every field and length; never run commands from forwarded text; sign sensitive messages with a shared secret |
| `EOFException` in the log | Writer and reader disagree on the format (e.g. `writeInt` length vs `readShort`) | Keep both sides in one shared class |
Files in this skill
- SKILL.md
- examples.md
- references/paper-api-platform.md
- references/paper-threading.md
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.