No chat to show

This project's files are all here to explore.

Files
src
build.gradle
README.md
settings.gradle
Code
6 396
src/main/java/bd/borno/migrator/MigrateCommand.java
package bd.borno.migrator;

import com.velocitypowered.api.command.SimpleCommand;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;

import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.UUID;

/**
 * /migratecreeper <path-to-limboauth-h2-file-without-extension>
 *
 * Reads plugins/CreeperMigrator/database.db (CreeperAuth SQLite export)
 * and inserts every account into LimboAuth's H2 "AUTH" table, hashing
 * the plaintext password with BCrypt first. Existing LimboAuth accounts
 * (same lowercase nickname) are skipped, never overwritten.
 */
public class MigrateCommand implements SimpleCommand {

  private final Logger logger;
  private final Path dataDirectory;
  private volatile boolean running = false;

  public MigrateCommand(Logger logger, Path dataDirectory) {
    this.logger = logger;
    this.dataDirectory = dataDirectory;
  }

  @Override
  public void execute(Invocation invocation) {
    var source = invocation.source();
    String[] args = invocation.arguments();

    if (running) {
      source.sendMessage(net.kyori.adventure.text.Component.text("Migration already running, check console."));
      return;
    }

    if (args.length != 1) {
      source.sendMessage(net.kyori.adventure.text.Component.text(
          "Usage: migratecreeper <path-to-limboauth-h2-file-without-.mv.db-extension>"));
      source.sendMessage(net.kyori.adventure.text.Component.text(
          "Example: migratecreeper /home/container/limboauth-v2"));
      return;
    }

    String h2Path = args[0];
    Path sqliteFile = dataDirectory.resolve("database.db");

    running = true;
    // Run off the main thread isn't strictly necessary here (Velocity proxy
    // init thread is fine for a one-shot admin command), but we keep it
    // synchronous and simple since this is a one-time tool, not a live feature.
    try {
      runMigration(sqliteFile.toString(), h2Path);
    } catch (Exception e) {
      logger.error("Migration failed with an exception", e);
      source.sendMessage(net.kyori.adventure.text.Component.text("Migration failed, check console for the error."));
    } finally {
      running = false;
    }
  }

  private void runMigration(String sqlitePath, String h2Path) throws Exception {
    logger.info("=======================================================");
    logger.info(" Starting CreeperAuth -> LimboAuth migration");
    logger.info(" Source (SQLite): " + sqlitePath);
    logger.info(" Target (H2):     " + h2Path + ".mv.db");
    logger.info("=======================================================");

    int migrated = 0;
    int skippedExisting = 0;
    int skippedInvalid = 0;
    int failed = 0;

    Class.forName("org.sqlite.JDBC");
    Class.forName("org.h2.Driver");

    String sqliteUrl = "jdbc:sqlite:" + sqlitePath;
    // AUTO_SERVER=TRUE lets us connect to the H2 file even though LimboAuth
    // itself is not running at the moment (which is required anyway since
    // H2 file databases only allow one exclusive writer at a time).
    String h2Url = "jdbc:h2:" + h2Path + ";AUTO_SERVER=FALSE";

    try (Connection sqliteConn = DriverManager.getConnection(sqliteUrl);
         Connection h2Conn = DriverManager.getConnection(h2Url, "sa", "")) {

      h2Conn.setAutoCommit(false);

      String selectSql = "SELECT username, password, ip_address, real_uuid, last_login FROM players WHERE username IS NOT NULL";
      String checkExistsSql = "SELECT NICKNAME FROM AUTH WHERE LOWERCASENICKNAME = ?";
      String insertSql = "INSERT INTO AUTH "
          + "(NICKNAME, LOWERCASENICKNAME, HASH, IP, TOTPTOKEN, REGDATE, LOGINIP, LOGINDATE, UUID, PREMIUMUUID, TOKENISSUEDAT) "
          + "VALUES (?, ?, ?, ?, '', ?, '', ?, ?, NULL, 0)";

      try (Statement selectStmt = sqliteConn.createStatement();
           ResultSet rs = selectStmt.executeQuery(selectSql);
           PreparedStatement checkStmt = h2Conn.prepareStatement(checkExistsSql);
           PreparedStatement insertStmt = h2Conn.prepareStatement(insertSql)) {

        while (rs.next()) {
          String username = rs.getString("username");
          String plainPassword = rs.getString("password");
          String ip = rs.getString("ip_address");
          String realUuid = rs.getString("real_uuid");
          long lastLogin = rs.getLong("last_login");

          if (username == null || username.isBlank() || plainPassword == null || plainPassword.isBlank()) {
            skippedInvalid++;
            continue;
          }

          String lowercase = username.toLowerCase(java.util.Locale.ROOT);

          try {
            checkStmt.setString(1, lowercase);
            try (ResultSet existing = checkStmt.executeQuery()) {
              if (existing.next()) {
                logger.info(" Skipping '" + username + "' - already exists in LimboAuth.");
                skippedExisting++;
                continue;
              }
            }

            String bcryptHash = BCrypt.hashpw(plainPassword, BCrypt.gensalt(10));

            String uuidToStore;
            if (realUuid != null && !realUuid.isBlank()) {
              uuidToStore = realUuid;
            } else {
              // LimboAuth generates an offline-mode UUID from the username
              // if this is left blank; we mirror that same algorithm here
              // so it is consistent from the very first insert.
              uuidToStore = UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes("UTF-8")).toString();
            }

            insertStmt.setString(1, username);
            insertStmt.setString(2, lowercase);
            insertStmt.setString(3, bcryptHash);
            insertStmt.setString(4, ip == null ? "" : ip);
            insertStmt.setLong(5, lastLogin > 0 ? lastLogin : System.currentTimeMillis());
            insertStmt.setLong(6, lastLogin > 0 ? lastLogin : System.currentTimeMillis());
            insertStmt.setString(7, uuidToStore);
            insertStmt.executeUpdate();

            migrated++;
            if (migrated % 50 == 0) {
              logger.info(" ... " + migrated + " accounts migrated so far");
            }
          } catch (Exception rowError) {
            logger.error(" Failed to migrate user '" + username + "': " + rowError.getMessage());
            failed++;
          }
        }
      }

      h2Conn.commit();
    }

    logger.info("=======================================================");
    logger.info(" Migration finished.");
    logger.info("   Migrated:          " + migrated);
    logger.info("   Skipped (existed): " + skippedExisting);
    logger.info("   Skipped (invalid): " + skippedInvalid);
    logger.info("   Failed:            " + failed);
    logger.info("=======================================================");
    logger.info(" IMPORTANT: delete this plugin and the copied database.db now.");
    logger.info("=======================================================");
  }

  @Override
  public boolean hasPermission(Invocation invocation) {
    // Console-only tool; only allow the console (no in-game player) to run it.
    return !(invocation.source() instanceof com.velocitypowered.api.proxy.Player);
  }
}