Skip to content
Back to skills

Paper Resource Pack

ASecurity

Paper 伺服器資源包:在設定階段(AsyncPlayerConnectionConfigureEvent)送出並等待載入完成才進服、多個資源包、固定 UUID 與 SHA-1、ResourcePackCallback 追蹤狀態、拒絕或下載失敗時中斷連線、遊戲中重新載入與依小遊戲加掛/移除 / Paper server resource packs: send during configuration (AsyncPlayerConnectionConfigureEvent) and wait until loaded before join, multiple packs, stable UUIDs and SHA-1, ResourcePackCallback status, disconnect on decline or failure, in-game reload and per-minigame packs

  • 3 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 5, 2026
ai-agentsgojavaapibackendsecurity

Works with

  • terminal
  • cli
  • api

Security analysis

A100/100

Pro scans all 4 files and shows the line behind each finding

Scanned December 5, 2026

npx -y skills add MrPippi/MJP-Paper-Skills --skill paper-resource-pack --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Paper Resource Pack?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Paper Resource Pack
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/mrpippi-paper-resource-pack/badge)](https://www.skillsdirectory.com/skills/mrpippi-paper-resource-pack)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: paper-resource-pack
description: "Paper 伺服器資源包:在設定階段(AsyncPlayerConnectionConfigureEvent)送出並等待載入完成才進服、多個資源包、固定 UUID 與 SHA-1、ResourcePackCallback 追蹤狀態、拒絕或下載失敗時中斷連線、遊戲中重新載入與依小遊戲加掛/移除 / Paper server resource packs: send during configuration (AsyncPlayerConnectionConfigureEvent) and wait until loaded before join, multiple packs, stable UUIDs and SHA-1, ResourcePackCallback status, disconnect on decline or failure, in-game reload and per-minigame packs"
---

# Paper Resource Pack

## Skill Name

`paper-resource-pack`

## Purpose

Since 1.20.3 a server can push several resource packs, each with its own UUID, also while the client is still in the **configuration phase**, before the player exists in the world. Paper exposes that phase to plugins with `AsyncPlayerConnectionConfigureEvent` (present in 1.21.11 and 26.3). Sending the pack there means the player sees the loading screen once, then joins with the pack applied: no in-game reload, no textures popping in, no window where custom items look wrong.

What the server does (read from Paper 26.3 build 273: `PaperConfigurationTask`, `ServerCommonPacketListenerImpl`, `ServerGamePacketListenerImpl`):

| Behavior | Detail |
|------|------|
| `AsyncPlayerConnectionConfigureEvent` | Fired on a virtual "Configuration Thread" for each connection entering configuration. The configuration step does not finish until every handler returns, so **blocking in the handler keeps the client on the loading screen** |
| Pack responses in configuration | Only the Adventure `ResourcePackCallback` of the request is called; `PlayerResourcePackStatusEvent` is **not** fired (there is no `Player` yet) |
| Pack responses in game | The callback is called first, then `PlayerResourcePackStatusEvent` |
| Callback thread | The server thread that processes packets (the main thread on Paper) |
| Terminal statuses | Everything except `ACCEPTED` and `DOWNLOADED` (`ResourcePackStatus#intermediate()`); the callback is removed after a terminal status |
| `required(true)` | Changes the client prompt. The server itself only disconnects on decline for the `server.properties` pack (`require-resource-pack`); for plugin packs, enforce it yourself |
| Hash | At most 40 characters (SHA-1 hex); a longer string throws `IllegalArgumentException` |

## Paper Version Requirements

- Paper 1.21.11 / 26.3: `AsyncPlayerConnectionConfigureEvent`, `PlayerConfigurationConnection`, Adventure `ResourcePackInfo` / `ResourcePackRequest` / `ResourcePackCallback` / `ResourcePackStatus` have identical signatures on both (compared with `javap`); compile-verified on both
- The template uses no scheduler in the configuration path and the entity scheduler in game, so it also runs on Folia
- **Spigot**: no configuration-phase event and no Adventure; use `Player#addResourcePack(UUID, String, byte[], String, boolean)` after join and `PlayerResourcePackStatusEvent`

## Triggers

- 「資源包」「resource pack」「材質包」「texture pack」「伺服器資源包」「強制資源包」「required resource pack」
- 「ResourcePackRequest」「ResourcePackInfo」「sendResourcePacks」「PlayerResourcePackStatusEvent」「AsyncPlayerConnectionConfigureEvent」
- 「進服前下載資源包」「多個資源包」「資源包 SHA-1」「重新載入資源包」

## Inputs

| Parameter | Example | Description |
|------|------|------|
| `packs` | `main` at `https://cdn.example.com/pack.zip` | Name, URL and SHA-1 of each pack |
| `required` | `true` | Disconnect players who decline or fail to load it |
| `prompt` | "Custom items need this pack" | Text on the client's download prompt |
| `hosting` | CDN / self-hosted | Where the zip is served from |

## Outputs

- `PackSpec.java` — immutable pack definition with a stable UUID per name and a validated SHA-1
- `PackHasher.java` — SHA-1 of a local zip
- `PackDelivery.java` — configuration-phase delivery that waits for the result, in-game resend, status per player
- `PackPlugin.java` — reads the config, computes a missing hash, `/packreload`

## Build Setup

See [`references/paper-api-platform.md`](references/paper-api-platform.md). Only `paper-api` (`compileOnly`).

## Code Template

### `PackSpec.java`

```java
package com.example.resourcepack;

import net.kyori.adventure.resource.ResourcePackInfo;
import net.kyori.adventure.text.Component;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * One resource pack. The id is derived from the name, so sending the pack again (after an update, with a new
 * hash) replaces it on the client instead of stacking a second copy.
 */
public record PackSpec(UUID id, URI uri, String sha1, boolean required, Component prompt) {

    private static final Pattern SHA1 = Pattern.compile("[0-9a-f]{40}");

    public PackSpec {
        Objects.requireNonNull(id, "id");
        Objects.requireNonNull(uri, "uri");
        Objects.requireNonNull(prompt, "prompt");
        String scheme = uri.getScheme();
        if (!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) {
            throw new IllegalArgumentException("Resource pack URL must be http(s): " + uri);
        }
        sha1 = Objects.requireNonNull(sha1, "sha1").toLowerCase(Locale.ROOT);
        if (!SHA1.matcher(sha1).matches()) {
            throw new IllegalArgumentException("sha1 must be 40 hex characters, got '" + sha1 + "'");
        }
    }

    public static PackSpec named(String name, URI uri, String sha1, boolean required, Component prompt) {
        return new PackSpec(idFor(name), uri, sha1, required, prompt);
    }

    /** The same name always gives the same id. */
    public static UUID idFor(String name) {
        return UUID.nameUUIDFromBytes(("resource-pack:" + name).getBytes(StandardCharsets.UTF_8));
    }

    public ResourcePackInfo info() {
        return ResourcePackInfo.resourcePackInfo(id, uri, sha1);
    }
}
```

### `PackHasher.java`

```java
package com.example.resourcepack;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

/** SHA-1 of a resource pack zip, the hash the client checks. Blocking file I/O: never on a tick thread. */
public final class PackHasher {

    private PackHasher() {
    }

    public static String sha1(Path zip) throws IOException {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Every JVM provides SHA-1", e);
        }
        try (InputStream in = Files.newInputStream(zip)) {
            byte[] buffer = new byte[64 * 1024];
            int read;
            while ((read = in.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
        }
        return HexFormat.of().formatHex(digest.digest());
    }
}
```

### `PackDelivery.java`

```java
package com.example.resourcepack;

import io.papermc.paper.connection.PlayerConfigurationConnection;
import io.papermc.paper.event.connection.configuration.AsyncPlayerConnectionConfigureEvent;
import net.kyori.adventure.resource.ResourcePackCallback;
import net.kyori.adventure.resource.ResourcePackRequest;
import net.kyori.adventure.resource.ResourcePackStatus;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Sends the packs while the client is still configuring and waits for the result, so players join with the
 * packs applied. Players who decline or fail a required pack are disconnected before they join.
 */
public final class PackDelivery implements Listener {

    /** Upper bound for a slow download; the client stays on the loading screen meanwhile. */
    private static final Duration WAIT = Duration.ofMinutes(2);

    private final Plugin plugin;
    private volatile List<PackSpec> packs = List.of();
    /** Last terminal status per player and pack (absent: never answered). */
    private final Map<UUID, Map<UUID, ResourcePackStatus>> statuses = new ConcurrentHashMap<>();

    public PackDelivery(Plugin plugin) {
        this.plugin = plugin;
    }

    /** Takes effect for the next joins; call resend for players already online. */
    public void setPacks(List<PackSpec> newPacks) {
        packs = List.copyOf(newPacks);
    }

    public boolean hasLoaded(Player player, PackSpec pack) {
        return statuses.getOrDefault(player.getUniqueId(), Map.of()).get(pack.id()) == ResourcePackStatus.SUCCESSFULLY_LOADED;
    }

    /** Virtual configuration thread. Blocking here is intended: it holds the client on the loading screen. */
    @EventHandler
    public void onConfigure(AsyncPlayerConnectionConfigureEvent event) {
        List<PackSpec> current = packs;
        if (current.isEmpty()) {
            return;
        }
        PlayerConfigurationConnection connection = event.getConnection();
        UUID playerId = connection.getProfile().getId();
        Map<UUID, CompletableFuture<ResourcePackStatus>> results = new HashMap<>();
        current.forEach(pack -> results.put(pack.id(), new CompletableFuture<>()));

        connection.getAudience().sendResourcePacks(request(current, (packId, status, audience) -> {
            if (!status.intermediate()) {
                record(playerId, packId, status);
                CompletableFuture<ResourcePackStatus> result = results.get(packId);
                if (result != null) {
                    result.complete(status);
                }
            }
        }));

        awaitAll(results);
        for (PackSpec pack : current) {
            ResourcePackStatus status = results.get(pack.id()).getNow(null);
            if (pack.required() && status != ResourcePackStatus.SUCCESSFULLY_LOADED) {
                connection.disconnect(refusal(status));
                return;
            }
        }
    }

    /** In game (after /packreload): same packs, results handled in the callback. */
    public void resend(Player player) {
        List<PackSpec> current = packs;
        if (current.isEmpty()) {
            player.clearResourcePacks();
            return;
        }
        UUID playerId = player.getUniqueId();
        player.sendResourcePacks(request(current, (packId, status, audience) -> {
            if (status.intermediate()) {
                return;
            }
            record(playerId, packId, status);
            boolean required = current.stream().anyMatch(p -> p.id().equals(packId) && p.required());
            if (required && status != ResourcePackStatus.SUCCESSFULLY_LOADED) {
                player.getScheduler().run(plugin, task -> player.kick(refusal(status)), null);
            }
        }));
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        statuses.remove(event.getPlayer().getUniqueId());
    }

    private static ResourcePackRequest request(List<PackSpec> packs, ResourcePackCallback callback) {
        return ResourcePackRequest.resourcePackRequest()
                .packs(packs.stream().map(PackSpec::info).toList())
                .required(packs.stream().anyMatch(PackSpec::required))
                .prompt(packs.getFirst().prompt())
                .replace(true) // drop packs this server sent earlier that are no longer in the list
                .callback(callback)
                .build();
    }

    private void record(UUID playerId, UUID packId, ResourcePackStatus status) {
        statuses.computeIfAbsent(playerId, k -> new ConcurrentHashMap<>()).put(packId, status);
    }

    private static void awaitAll(Map<UUID, CompletableFuture<ResourcePackStatus>> results) {
        try {
            CompletableFuture.allOf(results.values().toArray(CompletableFuture[]::new))
                    .get(WAIT.toMillis(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException | ExecutionException e) {
            // unanswered packs stay incomplete and count as not loaded
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private static Component refusal(ResourcePackStatus status) {
        String reason = Optional.ofNullable(status).map(s -> switch (s) {
            case DECLINED -> "you declined it";
            case FAILED_DOWNLOAD, INVALID_URL -> "the download failed";
            case FAILED_RELOAD -> "it could not be applied";
            case DISCARDED -> "it was discarded";
            default -> s.name().toLowerCase();
        }).orElse("it did not load in time");
        return Component.text("This server requires its resource pack, but " + reason + ".", NamedTextColor.RED);
    }
}
```

### `PackPlugin.java`

```java
package com.example.resourcepack;

import com.mojang.brigadier.Command;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import net.kyori.adventure.resource.ResourcePackInfo;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.net.URI;
import java.util.List;

/**
 * config.yml:
 *   pack:
 *     name: main
 *     url: "https://cdn.example.com/pack.zip"
 *     sha1: ""                # empty: downloaded once at startup to compute it
 *     required: true
 *     prompt: "<gold>Custom items need this pack."
 */
public final class PackPlugin extends JavaPlugin {

    private PackDelivery delivery;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        delivery = new PackDelivery(this);
        getServer().getPluginManager().registerEvents(delivery, this);
        loadPacks();
        getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event ->
                event.registrar().register(Commands.literal("packreload")
                        .requires(source -> source.getSender().hasPermission("resourcepack.reload"))
                        .executes(context -> {
                            reloadConfig();
                            loadPacks();
                            context.getSource().getSender().sendMessage(Component.text("Reloading resource pack..."));
                            return Command.SINGLE_SUCCESS;
                        }).build(), "Reload the resource pack and send it to everyone online"));
    }

    private void loadPacks() {
        FileConfiguration config = getConfig();
        String name = config.getString("pack.name", "main");
        URI uri;
        try {
            uri = URI.create(config.getString("pack.url", ""));
        } catch (IllegalArgumentException e) {
            getLogger().severe("pack.url is not a valid URL: " + e.getMessage());
            delivery.setPacks(List.of());
            return;
        }
        boolean required = config.getBoolean("pack.required", false);
        Component prompt = MiniMessage.miniMessage().deserialize(config.getString("pack.prompt", ""));
        String sha1 = config.getString("pack.sha1", "");
        if (!sha1.isBlank()) {
            apply(PackSpec.named(name, uri, sha1, required, prompt));
            return;
        }
        // No hash configured: download once off the main thread. Joins before it finishes get no pack.
        getLogger().info("pack.sha1 is empty, downloading " + uri + " to compute it");
        ResourcePackInfo.resourcePackInfo().id(PackSpec.idFor(name)).uri(uri).computeHashAndBuild().whenComplete((info, error) -> {
            if (error != null) {
                getLogger().severe("Could not download the resource pack to hash it: " + error);
                return;
            }
            getLogger().info("Resource pack sha1: " + info.hash() + " (put it in pack.sha1 to skip this download)");
            getServer().getGlobalRegionScheduler().execute(this,
                    () -> apply(PackSpec.named(name, uri, info.hash(), required, prompt)));
        });
    }

    private void apply(PackSpec pack) {
        delivery.setPacks(List.of(pack));
        for (Player player : getServer().getOnlinePlayers()) {
            player.getScheduler().run(this, task -> delivery.resend(player), null);
        }
    }
}
```

## Recommended Directory Structure

```
src/main/java/com/example/resourcepack/
├── PackSpec.java      <- id, URL, SHA-1, required, prompt (immutable)
├── PackHasher.java    <- SHA-1 of a local zip
├── PackDelivery.java  <- configuration-phase delivery, in-game resend, statuses
└── PackPlugin.java    <- config, hash computation, /packreload
```

## Thread Safety

- `AsyncPlayerConnectionConfigureEvent` runs on a virtual thread per connection. There is no `Player` and no world for it: use `getConnection()` (`getProfile()`, `getAudience()`, `disconnect`). Blocking is fine and intended; keep a timeout so a client that never answers is not held forever
- Pack callbacks run on the thread that processes packets (main thread on Paper). Keep them short; kick through the player's entity scheduler so the template also works on Folia
- Hashing a zip or downloading it (`computeHashAndBuild`) is blocking I/O: never on a tick thread
- `statuses` is written from callbacks and read from game code, so it is concurrent
- See [`references/paper-threading.md`](references/paper-threading.md)

### Key Techniques

| Topic | Approach |
|------|------|
| Pack before join | Send in `AsyncPlayerConnectionConfigureEvent` and wait for terminal statuses |
| Stable identity | `UUID.nameUUIDFromBytes("resource-pack:" + name)`: the same name always replaces the same pack on the client |
| Update | Keep the name, change the file and its SHA-1; `replace(true)` also removes packs dropped from the list |
| Several packs | One `ResourcePackRequest` with several `ResourcePackInfo`; the client stacks them, later packs on top |
| Temporary pack (minigame) | `player.sendResourcePacks(ResourcePackRequest.addingRequest(info))` on join, `player.removeResourcePacks(id)` on leave (examples.md, Example 2) |
| Enforce required | Disconnect yourself on a terminal status other than `SUCCESSFULLY_LOADED`; `required(true)` alone only changes the prompt |
| Status in game | The request callback (always) or `PlayerResourcePackStatusEvent` (game phase only) |
| Hash | SHA-1 of the exact bytes served; `PackHasher.sha1(path)` or `ResourcePackInfo.resourcePackInfo().id(id).uri(uri).computeHashAndBuild()` |

## Fallback

| Error | Cause | Fix |
|------|------|------|
| Players join first, then the pack reloads in game | Pack sent in `PlayerJoinEvent` | Send it in `AsyncPlayerConnectionConfigureEvent` (this template) |
| `PlayerResourcePackStatusEvent` never fires for the join pack | Responses during configuration only reach the request callback | Use the callback (this template) |
| Declining a "required" pack still lets the player in | Only the `server.properties` pack is enforced by the server | Disconnect on decline / failure yourself |
| `FAILED_DOWNLOAD` for everyone | URL not a direct download (Dropbox / Google Drive page, HTML instead of zip), or the SHA-1 does not match the served file | Use a direct link; recompute the hash from the exact file served |
| Old pack still shown after an update | Same URL and same hash given, or the CDN serves a cached file | Change the hash with the content; add a version to the URL (`pack.zip?v=12`) |
| Two copies of the pack after `/packreload` | A random UUID per send | Derive the UUID from the pack name |
| `IllegalArgumentException: Hash is too long` | SHA-256 or another hash given | Use the 40-character SHA-1 |
| Players wait two minutes then join without the pack | Client never answered (very large pack, slow host) | Host it on a CDN, keep the zip small, or raise `WAIT` |
| Behind Velocity: pack applied twice or removed on server switch | The proxy or another backend also manages packs | Send packs from one place only (proxy or backend) and keep the same UUIDs on every backend |

Files in this skill

  • SKILL.md20.4 KB
  • examples.md4.7 KB
  • references/paper-api-platform.md8.7 KB
  • references/paper-threading.md6.9 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.