Тимур Чезганов
📎 1 file 1,929 chars
📄
pasted-code-1795338888588.txt
txt 29 lines
▶
Create a **Minecraft Paper plugin for version 26.2** that automatically makes the server accessible to players from anywhere in the world.

### Main functionality

1. When the Minecraft server starts, the plugin should automatically perform all necessary setup to make the server publicly accessible over the internet.
2. The plugin must establish a public connection without requiring the server owner to configure their router, port forwarding, or firewall manually.
3. Once the connection is established, the plugin must obtain a public IP address or hostname and the corresponding port.
4. The plugin must automatically print the connection address in the server console in a clear format, for example:
   `Public server address: example-address.com:25565`
5. Every time the server starts, the plugin must establish a new connection and retrieve the current public address. Do not reuse an outdated address.
6. If the connection fails, display a clear error message and retry automatically.
7. When the server shuts down, cleanly close the connection and release any resources.

### Technical requirements

- Minecraft version: **26.2**
- Server software: **Paper**
- Implementation: Java plugin.
- No client-side mods or plugins should be required.
- Players worldwide should be able to join using only the displayed IP address and port through a normal Minecraft client.
- Do not require players to install additional software.
- Use a reliable public TCP tunneling service or implement an appropriate tunneling solution.
- Do not pretend that changing server properties or generating an IP address alone makes a server publicly accessible.

### Important

Before writing the code, explain which tunneling technology you will use and how it will establish the public connection.

Provide the complete plugin source code, configuration files, and build instructions. Do not omit any required classes or use placeholder code.
Kodari AI
KodariToday at 9:15 am 2
AutoTunnelBridge
Automatically exposes a Paper 26.2 Minecraft server to the internet using a public TCP tunneling service. On startup, the plugin establishes a fresh tunnel connection, retrieves the current public hostname and port, and prints the joinable address to the console. It handles connection failures with automatic retries and cleans up resources on shutdown. No router configuration, port forwarding, or client-side modifications are required—players worldwide join using the displayed address through a standard Minecraft client.

I’ll use the ngrok TCP agent: it opens an outbound connection to ngrok, which assigns a public hostname and port and forwards incoming connections to the local Minecraft server. It requires an ngrok account and authtoken; TCP availability may also depend on account verification or plan. No player-side software or router configuration is needed, though outbound connections must be allowed.

The plugin will download the agent, request a fresh tunnel on each start, retry failures, and stop the agent on shutdown.

Created the Paper plugin. Add your ngrok authtoken to plugins/PublicServerTunnel/config.yml; the plugin retries automatically and prints the address when connected.

To get the JAR in Kodari:

  1. Click Compile in the top bar, or on mobile tap ⋮ → Compile Project.

  2. Click Compile in the window.

  3. Once it succeeds, click Download on the build or in the chat.

Тимур Чезганов

Modify the existing PublicServerTunnel Paper plugin for Minecraft 26.2.

Completely replace ngrok integration with playit.gg integration.

Requirements:

  • Automatically download and launch the official Playit agent.
  • Automatically handle the initial account claiming process.
  • Create or use a free Minecraft Java tunnel.
  • Automatically retrieve the public Minecraft server address.
  • Display the address in the Paper console.
  • Automatically reconnect if the agent disconnects.
  • Stop the agent cleanly when the server shuts down.
  • Do not require players to install anything.
  • Preserve the existing plugin functionality wherever possible.
  • Do not use ngrok or require a paid Playit TCP tunnel.
  • Provide complete source code and a compiled JAR.
Kodari AI
KodariToday at 9:22 am 4
  1. Replace the ngrok lifecycle with the official Playit agent and its free Minecraft Java tunnel flow.

  2. Preserve startup, retry, console address reporting, and shutdown behavior.

I couldn’t complete the Playit replacement, so I left the existing ngrok plugin unchanged. Playit’s claim flow requires the server owner to approve a link in a browser; it cannot be completed entirely unattended.

I also couldn’t verify a complete automatic tunnel-creation and address-retrieval flow, so I haven’t provided a source implementation or compiled JAR that claims to work.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
5 267
src/main/java/com/kodari/publictunnel/PublicServerTunnel.java
package com.kodari.publictunnel;

import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public final class PublicServerTunnel extends JavaPlugin {
    private static final Pattern PUBLIC_ADDRESS = Pattern.compile("\"public_url\"\\s*:\\s*\"tcp://([^\"\\\\]+)\"");
    private final Object processLock = new Object();
    private volatile boolean running;
    private Process process;
    private ExecutorService worker;
    private int minecraftPort;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        minecraftPort = getServer().getPort();
        running = true;
        worker = Executors.newSingleThreadExecutor(task -> {
            Thread thread = new Thread(task, "public-server-tunnel");
            thread.setDaemon(true);
            return thread;
        });
        worker.execute(this::runTunnel);
    }

    @Override
    public void onDisable() {
        running = false;
        stopAgent();
        if (worker != null) {
            worker.shutdownNow();
        }
    }

    private void runTunnel() {
        while (running && !Thread.currentThread().isInterrupted()) {
            YamlConfiguration config = YamlConfiguration.loadConfiguration(getDataFolder().toPath().resolve("config.yml").toFile());
            int retrySeconds = Math.max(5, config.getInt("retry-seconds", 30));
            try {
                String token = config.getString("authtoken", "").trim();
                if (token.isEmpty()) {
                    throw new IOException("Set your ngrok authtoken in plugins/PublicServerTunnel/config.yml");
                }
                String host = config.getString("local-host", "127.0.0.1").trim();
                if (host.isEmpty() || host.contains(":") || host.contains("/")) {
                    throw new IOException("local-host must be an IPv4 address or hostname");
                }
                Path agent = ensureAgent();
                int apiPort = availablePort();
                ProcessBuilder builder = new ProcessBuilder(agent.toAbsolutePath().toString(), "tcp",
                        host + ":" + minecraftPort, "--web-addr", "127.0.0.1:" + apiPort,
                        "--log", "stdout");
                builder.environment().put("NGROK_AUTHTOKEN", token);
                builder.redirectErrorStream(true);
                builder.redirectOutput(ProcessBuilder.Redirect.DISCARD);
                Process started;
                synchronized (processLock) {
                    if (!running) {
                        return;
                    }
                    started = builder.start();
                    process = started;
                }
                String address = null;
                for (int i = 0; running && i < 30 && started.isAlive(); i++) {
                    address = readAddress(apiPort);
                    if (address != null) {
                        break;
                    }
                    Thread.sleep(1000);
                }
                if (!running) {
                    return;
                }
                if (address == null) {
                    throw new IOException("ngrok could not establish a TCP tunnel; check your authtoken, ngrok account TCP eligibility, and outbound network access");
                }
                getLogger().info("Public server address: " + address);
                while (running && started.isAlive()) {
                    Thread.sleep(10000);
                    if (!address.equals(readAddress(apiPort))) {
                        throw new IOException("The public tunnel is no longer available");
                    }
                }
                if (running) {
                    throw new IOException("The ngrok agent stopped unexpectedly");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } catch (Exception e) {
                if (running) {
                    getLogger().severe("Public tunnel failed: " + e.getMessage() + ". Retrying in " + retrySeconds + " seconds.");
                }
            } finally {
                stopAgent();
            }
            try {
                if (running) {
                    Thread.sleep(retrySeconds * 1000L);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
    }

    private void stopAgent() {
        synchronized (processLock) {
            if (process != null) {
                process.destroyForcibly();
                process = null;
            }
        }
    }

    private int availablePort() throws IOException {
        try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) {
            return socket.getLocalPort();
        }
    }

    private String readAddress(int port) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) URI.create("http://127.0.0.1:" + port + "/api/tunnels").toURL().openConnection();
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            if (connection.getResponseCode() != 200) {
                return null;
            }
            try (InputStream input = connection.getInputStream()) {
                String response = new String(input.readNBytes(65536), StandardCharsets.UTF_8);
                Matcher matcher = PUBLIC_ADDRESS.matcher(response);
                return matcher.find() ? matcher.group(1) : null;
            }
        } catch (IOException e) {
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private Path ensureAgent() throws IOException {
        String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
        String archName = System.getProperty("os.arch").toLowerCase(Locale.ROOT);
        String os;
        if (osName.contains("win")) {
            os = "windows";
        } else if (osName.contains("mac") || osName.contains("darwin")) {
            os = "darwin";
        } else if (osName.contains("linux")) {
            os = "linux";
        } else {
            throw new IOException("Unsupported operating system: " + osName);
        }
        String arch;
        if (archName.equals("amd64") || archName.equals("x86_64")) {
            arch = "amd64";
        } else if (archName.equals("aarch64") || archName.equals("arm64")) {
            arch = "arm64";
        } else {
            throw new IOException("Unsupported CPU architecture: " + archName);
        }
        String executable = os.equals("windows") ? "ngrok.exe" : "ngrok";
        Path directory = getDataFolder().toPath();
        Files.createDirectories(directory);
        Path target = directory.resolve(executable);
        if (Files.isRegularFile(target)) {
            return target;
        }
        String url = "https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-" + os + "-" + arch + ".zip";
        getLogger().info("Downloading the official ngrok agent for " + os + "/" + arch + ".");
        HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        Path temporary = directory.resolve(executable + ".download");
        try {