Rise 5.99 StaffAlert module 2 files, 260 lines

Rise 5.99 StaffAlert: Full Source Analysis

StaffAlert polls the Hypixel public punishment-stats API and notifies the user how many players were staff-banned since the previous poll.

dev/rise/module/impl/other/StaffAlert.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-08-13

Packets This Module Uses

Analysis

Overview

StaffAlert polls the Hypixel public punishment-stats API and notifies the user how many players were staff-banned since the previous poll. It needs an API key, which it bootstraps over the game connection: onPacketReceive watches S02 chat for the exact prefix "Your new API key is ", and while apikey is still null the update handler re-issues C01 /api new on every tenth tick (a 2 per second command stream gated on Hypixel, 40 ticks after join, client tick counter modulo 10). Once a key is captured the poll runs on a worker thread: an HttpURLConnection GET to the punishmentstats endpoint, a line-by-line parse gated on the substring "true", a staff_total diff against the previous sample, and a warning notification when the diff is positive. The module hides itself off Hypixel and auto-toggles with a notification when it finds itself off the server. The S02 observation and the HTTP request are both invisible to the game server; the only wire presence is the C01 command stream.

API key bootstrap

The key-grab loop is the module's only serverbound traffic. Every tenth client tick, with ticksExisted at least 40, on a Hypixel server, while apikey is null, the handler resets the timer and sends C01PacketChatMessage("/api new"). The key is then captured from the first S02 whose unformatted text starts with the exact prefix "Your new API key is ", with the remainder stored into the static apikey field and a client-side confirmation message printed. The capture depends on the server replying with that exact prefix; if the reply differs (localization, a chat prefix) the loop keeps running at 2 per second indefinitely.

Polling and diff logic

The poll fires when the TimeUtil gate hasReached(delay seconds) or on the first update (lastTimeAmountOfBans is -1), and runs on a fresh thread so the game tick never blocks. The request sets a Firefox user agent, reads the response line by line, and only parses lines containing the substring "true" (a sloppy gate that survives because the JSON payload is usually a single line), pulling staff_total from the parsed object. The diff against the previous sample drives the notification, which pluralizes player vs players and formats the window as seconds. A failed request prints a stack trace and, when a key exists, a failure notification. onEnable resets the sample and the timer so a re-enable always polls immediately.

Wire footprint

Everything except the key bootstrap happens off the game connection: the S02 watch consumes an existing chat packet, and the API poll is a plain HTTPS request from the client's JVM. The server therefore only ever sees the /api new command stream, which stops the moment the key lands, plus the module's own chat output if the user has the notifications mirrored. The practical exposure is the command rate during the bootstrap window and the fact that the module announces its presence to anyone reading chat logs when the key is fetched.

source StaffAlert.java

StaffAlert.java110 lines · JavaOriginal ↗
1
package dev.rise.module.impl.other;
2
3
import com.google.gson.JsonParser;
4
import dev.rise.Rise;
5
import dev.rise.event.impl.other.UpdateEvent;
6
import dev.rise.event.impl.packet.PacketReceiveEvent;
7
import dev.rise.module.Module;
8
import dev.rise.module.api.ModuleInfo;
9
import dev.rise.module.enums.Category;
10
import dev.rise.notifications.NotificationType;
11
import dev.rise.setting.impl.NumberSetting;
12
import dev.rise.util.math.MathUtil;
13
import dev.rise.util.math.TimeUtil;
14
import dev.rise.util.player.PacketUtil;
15
import dev.rise.util.player.PlayerUtil;
16
import net.minecraft.network.Packet;
17
import net.minecraft.network.handshake.client.C00Handshake;
18
import net.minecraft.network.login.server.S02PacketLoginSuccess;
19
import net.minecraft.network.play.client.C01PacketChatMessage;
20
import net.minecraft.network.play.server.S02PacketChat;
21
import net.minecraft.network.play.server.S40PacketDisconnect;
22
import net.minecraft.network.status.server.S01PacketPong;
23
24
import java.io.BufferedReader;
25
import java.io.InputStreamReader;
26
import java.net.HttpURLConnection;
27
import java.net.URL;
28
29
@ModuleInfo(name = "StaffAlert", description = "Alerts you when staff ban someone else on Hypixel", category = Category.OTHER)
30
public class StaffAlert extends Module {
31
32
    private final NumberSetting delay = new NumberSetting("Delay (Seconds)", this, 60, 1, 120, 1);
33
34
    private final TimeUtil timer = new TimeUtil();
35
    private int lastTimeAmountOfBans = -1;
36
    public static String apikey;
37
    private boolean hasKey;
38
39
40
    @Override
41
    public void onUpdateAlwaysInGui() {
42
        this.hidden = !(PlayerUtil.isOnServer("Hypixel") || mc.isSingleplayer());
43
    }
44
45
    @Override
46
    public void onPacketReceive(final PacketReceiveEvent event) {
47
        if (event.getPacket() instanceof S02PacketChat) {
48
            final S02PacketChat p = (S02PacketChat) event.getPacket();
49
            final String message = p.getChatComponent().getUnformattedText();
50
            if (message.startsWith("Your new API key is ")) {
51
                apikey = message.replace("Your new API key is ", "");
52
                Rise.addChatMessage("API Key Set!");
53
            }
54
        }
55
    }
56
    @Override
57
    public void onUpdate(final UpdateEvent event) {
58
        if(apikey == null && PlayerUtil.isOnServer("Hypixel") && mc.thePlayer.ticksExisted >= 40 && !mc.isSingleplayer() && mc.thePlayer.ticksExisted % 10 == 0){
59
            timer.reset();
60
            PacketUtil.sendPacket(new C01PacketChatMessage("/api new"));
61
        }
62
        if (!PlayerUtil.isOnServer("Hypixel") || mc.isSingleplayer()) {
63
            this.registerNotification(this.getModuleInfo().name() + " only works on Hypixel.");
64
            this.toggleModule();
65
            return;
66
        }
67
68
        if (mc.isSingleplayer()) {
69
            lastTimeAmountOfBans = -1;
70
            timer.reset();
71
            return;
72
        }
73
74
        if (timer.hasReached((long) delay.getValue() * 1000) || lastTimeAmountOfBans == -1) {
75
            new Thread(() -> {
76
                try {
77
                    final HttpURLConnection connection = (HttpURLConnection) new URL("https://api.hypixel.net/punishmentstats?key=" + apikey).openConnection();
78
                    connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
79
                    connection.setRequestMethod("GET");
80
                    connection.setDoInput(true);
81
                    connection.setDoOutput(true);
82
                    connection.connect();
83
                    final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
84
                    for (String read; (read = reader.readLine()) != null; ) {
85
                        if (read.contains("true")) { //alan loves this code
86
                            final int staffBans = JsonParser.parseString(read).getAsJsonObject().get("staff_total").getAsInt();
87
                            final int diff = staffBans - lastTimeAmountOfBans;
88
                            final int delay = (int) Math.round(this.delay.getValue());
89
                            if (lastTimeAmountOfBans != -1 && diff > 0)
90
                                Rise.INSTANCE.getNotificationManager().registerNotification(diff + (diff == 1 ? " player has" : " players have") + " been staff banned in the past " + (delay == 1 ? "second" : delay + "s") + ".", NotificationType.WARNING);
91
                            lastTimeAmountOfBans = staffBans;
92
                        }
93
                    }
94
                } catch (final Exception e) {
95
                    if(apikey != null) {
96
                        Rise.INSTANCE.getNotificationManager().registerNotification(this.getModuleInfo().name() + " failed to get staff ban information.", NotificationType.WARNING);
97
                    }
98
                    e.printStackTrace();
99
                }
100
            }).start();
101
            timer.reset();
102
        }
103
    }
104
105
    @Override
106
    protected void onEnable() {
107
        lastTimeAmountOfBans = -1;
108
        timer.reset();
109
    }
110
}

What this file does

The module is one file and the analysis surface is complete in it. onPacketReceive captures the API key from S02 chat; onUpdate runs the key-bootstrap loop, the Hypixel gating with auto-toggle, and the timer-gated poll that spawns the HTTP thread; the thread performs the GET, the "true" substring gate, the staff_total diff and the notification. The JSON parsing is inline (JsonParser over the response line), the delay setting is a NumberSetting in seconds (1 to 120, default 60), and the hidden flag is maintained per-GUI-update so the module only shows on Hypixel. The class is a self-contained poller with one packet-emitting branch, the C01 command loop.

source TimeUtil.java (poll gate)

TimeUtil.java150 lines · JavaOriginal ↗
1
package dev.rise.util.math;
2
3
4
import store.intent.hwid.HWID;
5
6
import javax.net.ssl.HttpsURLConnection;
7
import java.io.BufferedReader;
8
import java.io.InputStreamReader;
9
import java.net.URL;
10
import java.util.ArrayList;
11
12
/**
13
 * TimeHelper, used to time stuff using real life time, like killaura cps
14
 *
15
 * @author Alan
16
 * @since 13/02/2021
17
 */
18
19
public final class TimeUtil {
20
21
    public long lastMS = 0L;
22
23
    /**
24
     * Devides 1000 / d
25
     */
26
    public int convertToMS(final int d) {
27
        return 1000 / d;
28
    }
29
30
    /***
31
     * Gets current system time
32
     */
33
    public long getCurrentMS() {
34
        return System.nanoTime() / 1000000L;
35
    }
36
37
    public long getElapsedTime() {
38
        return System.currentTimeMillis() - this.lastMS;
39
    }
40
41
    /***
42
     * Checks if a timer has reached an amount of time
43
     */
44
    public boolean hasReached(final long milliseconds) {
45
        return getCurrentMS() - lastMS >= milliseconds;
46
    }
47
48
    /***
49
     * Gets the current amount of time that has passed since last reset
50
     */
51
    public long getDelay() {
52
        return System.currentTimeMillis() - lastMS;
53
    }
54
55
    /***
56
     * Resets timer
57
     */
58
    public void reset() {
59
        lastMS = getCurrentMS();
60
    }
61
62
    /***
63
     * Tbh I skidded this from intent and don't remember what this does
64
     */
65
    public void setLastMS() {
66
        lastMS = System.currentTimeMillis();
67
    }
68
69
    /***
70
     * Tbh I skidded this from intent and don't remember what this does
71
     */
72
    public void setLastMS(final long lastMS) {
73
        this.lastMS = lastMS;
74
    }
75
76
    public static String lmfao() {
77
        try {
78
            final String xd = new String(new char[]{'h', 't', 't', 'p', 's', ':', '/', '/', 'i', 'n', 't', 'e', 'n', 't', '.', 's', 't', 'o', 'r', 'e', '/', 'p', 'r', 'o', 'd', 'u', 'c', 't', '/', '2', '5', '/', 'w', 'h', 'i', 't', 'e', 'l', 'i', 's', 't', '?', 'h', 'w', 'i', 'd', '='});
79
            final String xd2 = new String(new char[]{'U', 's', 'e', 'r', '-', 'A', 'g', 'e', 'n', 't'});
80
            final String xd3 = new String(new char[]{'M', 'o', 'z', 'i', 'l', 'l', 'a', '/', '5', '.', '0', ' ', '(', 'W', 'i', 'n', 'd', 'o', 'w', 's', ' ', 'N', 'T', ' ', '6', '.', '1', ';', ' ', 'W', 'O', 'W', '6', '4', ';', ' ', 'r', 'v', ':', '2', '5', '.', '0', ')', ' ', 'G', 'e', 'c', 'k', 'o', '/', '2', '0', '1', '0', '0', '1', '0', '1', ' ', 'F', 'i', 'r', 'e', 'f', 'o', 'x', '/', '2', '5', '.', '0'});
81
            final String xd4 = new String(new char[]{'琀', '爀', '甀', '攀'});
82
            final String xd5 = new String(new char[]{'昀', '愀', '氀', '猀', '攀'});
83
84
            try {
85
                final HttpsURLConnection connection =
86
                        (HttpsURLConnection) new URL(xd + HWID.getHardwareID())
87
                                .openConnection();
88
89
                connection.addRequestProperty(xd2, xd3);
90
91
92
                final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
93
94
                String currentln;
95
                final ArrayList<String> response = new ArrayList<>();
96
97
                while ((currentln = in.readLine()) != null) {
98
                    response.add(currentln);
99
                }
100
101
                final StringBuilder fax = new StringBuilder();
102
103
                for (int i = 0; i < xd4.length(); i++) {
104
                    fax.append(Character.reverseBytes(xd4.charAt(i)));
105
                }
106
107
                final StringBuilder notFax = new StringBuilder();
108
109
                for (int i = 0; i < xd5.length(); i++) {
110
                    notFax.append(Character.reverseBytes(xd5.charAt(i)));
111
                }
112
113
                if (!response.contains(fax.toString()) || response.contains(notFax.toString())) {
114
                    for (int i = 0; i < 0; i = 2) {
115
                        if (!response.contains(fax.toString()) || response.contains(notFax.toString())) {
116
                            for (int g = 0; g < 0; g = 2) {
117
118
                            }
119
                            return null;
120
                        }
121
                    }
122
                    return null;
123
                }
124
                if (!response.contains(fax.toString()) || response.contains(notFax.toString())) {
125
                    for (int i = 0; i < 0; i = 2) {
126
127
                    }
128
                    return null;
129
                }
130
                if (!response.contains(fax.toString()) || response.contains(notFax.toString())) {
131
                    for (int i = 0; i < 0; i = 2) {
132
133
                    }
134
                    return null;
135
                }
136
            } catch (final Exception e) {
137
                for (; ; ) {
138
139
                }
140
            }
141
        } catch (final Exception e) {
142
            for (int i = 0; i < 0; i = 2) {
143
144
            }
145
            return null;
146
        }
147
148
        return "Yes";
149
    }
150
}

What this file does

The wall-clock helper that gates the polling cadence: timer.hasReached(delay * 1000) turns the module's Delay seconds setting into the interval between API polls, and timer.reset() in onEnable, in the key-bootstrap branch and after each poll keeps the gate aligned. The class is the standard Rise time helper with lastMS state, convertToMS, getCurrentMS and hasReached style methods, and notably carries HWID and HTTP imports, a leftover of the client's licensing path, unrelated to the poll logic. It matters here because the module's two clocks are different animals: the poll uses this real-time gate, while the key-bootstrap loop counts client ticks with ticksExisted modulo 10, which is why the bootstrap can fire at 2 per second while the poll respects the seconds setting.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat Commands (command rate check)

Commands.java117 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.chat;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.players.IPlayerData;
22
import fr.neatmonster.nocheatplus.utilities.ColorUtil;
23
import fr.neatmonster.nocheatplus.utilities.TickTask;
24
25
/**
26
 * Check only for commands
27
 * @author asofold
28
 *
29
 */
30
public class Commands extends Check {
31
32
    public Commands() {
33
        super(CheckType.CHAT_COMMANDS);
34
    }
35
    
36
    /**
37
     * Checks a player for command spam
38
     * 
39
     * @param player
40
     * @param message
41
     * @param cc
42
     * @param pData
43
     * @param captcha
44
     * @return true if successful.
45
     */
46
    public boolean check(final Player player, final String message, 
47
                         final ChatConfig cc, final IPlayerData pData, 
48
                         final ICaptcha captcha) {
49
50
        final long now = System.currentTimeMillis();
51
        final int tick = TickTask.getTick();
52
        final ChatData data = pData.getGenericInstance(ChatData.class);
53
        final boolean captchaEnabled = !cc.captchaSkipCommands && pData.isCheckActive(CheckType.CHAT_CAPTCHA, player); 
54
        if (captchaEnabled){
55
            synchronized (data) {
56
                if (captcha.shouldCheckCaptcha(player, cc, data, pData)){
57
                    captcha.checkCaptcha(player, message, cc, data, true);
58
                    return true;
59
                }
60
            }
61
        }
62
63
        // Rest of the check is done without sync, because the data is only used by this check.
64
        // Weight might later be read from some prefix tree (also known / unknown).
65
        final float weight = 1f;
66
        data.commandsWeights.add(now, weight);
67
        if (tick < data.commandsShortTermTick) {
68
            // TickTask got reset.
69
            data.commandsShortTermTick = tick;
70
            data.commandsShortTermWeight = 1.0;
71
        }
72
        else if (tick - data.commandsShortTermTick < cc.commandsShortTermTicks) {
73
            if (!pData.getCurrentWorldData().shouldAdjustToLag(type) 
74
                || TickTask.getLag(50L * (tick - data.commandsShortTermTick), true) < 1.3f) {
75
                // Add up.
76
                data.commandsShortTermWeight += weight;
77
            }
78
            else {
79
                // Reset, too much lag.
80
                data.commandsShortTermTick = tick;
81
                data.commandsShortTermWeight = 1.0;
82
            }
83
        }
84
        else{
85
            // Reset.
86
            data.commandsShortTermTick = tick;
87
            data.commandsShortTermWeight = 1.0;
88
        }
89
90
        final float nw = data.commandsWeights.score(1f);
91
        final double violation = Math.max(nw - cc.commandsLevel, data.commandsShortTermWeight - cc.commandsShortTermLevel);
92
93
        if (violation > 0.0) {
94
            data.commandsVL += violation;
95
            // TODO: Evaluate if sync(data) is necessary or better for executeActions.
96
            if (captchaEnabled) {
97
                synchronized (data) {
98
                    captcha.sendNewCaptcha(player, cc, data);
99
                }
100
                return true;
101
            }
102
            else if (executeActions(player, data.commandsVL, violation, cc.commandsActions).willCancel()) {
103
                return true;
104
            }
105
        }
106
        else if (cc.chatWarningCheck && now - data.chatWarningTime > cc.chatWarningTimeout && (100f * nw / cc.commandsLevel > cc.chatWarningLevel || 100f * data.commandsShortTermWeight / cc.commandsShortTermLevel > cc.chatWarningLevel)){
107
            player.sendMessage(ColorUtil.replaceColors(cc.chatWarningMessage));
108
            data.chatWarningTime = now;
109
        }
110
        else {
111
            // TODO: This might need invalidation with time.
112
            data.commandsVL *= 0.99;
113
        }
114
        return false;
115
    }
116
117
}

How it counteracts this module

NoCheatPlus scores '/'-prefixed chat on PlayerCommandPreprocessEvent: each command adds weight 1.0 to a 5-bucket ActionFrequency(5, 1000) window and to a short-term weight inside a tick window, and the violation is the larger of (window score minus commandsLevel, short-term weight minus commandsShortTermLevel) with stock levels 10 and 3 over 18 ticks. The module's bootstrap loop emits exactly one command per 10 client ticks, which is 2 per second, so the 5-second window scores exactly 10 and the short-term weight stays at 2: the loop runs precisely at the stock boundary and passes by default. It becomes a real counter the moment the cadence tips over, which happens when the key never lands and any additional command traffic (or an admin-lowered level) pushes the window score past 10, or when server lag resets the short-term window mid-burst and re-accumulation crosses 3.

anticheat Captcha (chat gate, auto-armed)

Captcha.java115 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.chat;
16
17
import java.util.concurrent.ThreadLocalRandom;
18
19
import org.bukkit.entity.Player;
20
21
import fr.neatmonster.nocheatplus.checks.Check;
22
import fr.neatmonster.nocheatplus.checks.CheckType;
23
import fr.neatmonster.nocheatplus.players.DataManager;
24
import fr.neatmonster.nocheatplus.players.IPlayerData;
25
import fr.neatmonster.nocheatplus.utilities.ColorUtil;
26
27
/**
28
 * NOTE: EARLY REFACTORING STATE, MOST METHODS NEED SYNC OVER DATA !
29
 * @author mc_dev
30
 *
31
 */
32
public class Captcha extends Check implements ICaptcha{
33
34
    public Captcha() {
35
        super(CheckType.CHAT_CAPTCHA);
36
    }
37
38
    @Override
39
    public void checkCaptcha(Player player, String message, ChatConfig cc, ChatData data, boolean isMainThread) {
40
        // Correct answer to the captcha?
41
        if (message.equals(data.captchaGenerated)) {
42
            // Yes, clear their data and do not worry anymore about them.
43
            data.reset();
44
            data.captchaStarted = false;
45
            player.sendMessage(ColorUtil.replaceColors(cc.captchaSuccess));
46
        } 
47
        else {
48
            // Increment their tries number counter.
49
            data.captchTries++;
50
            data.captchaVL ++;
51
            // Have they failed too man times?
52
            if (data.captchTries > cc.captchaTries) {
53
                // Find out if we need to kick the player or not.
54
                executeActions(player, data.captchaVL, 1, cc.captchaActions);
55
                // (Resetting captcha tries is done on quit/kick).
56
            }
57
            // Display the question again (if not kicked).
58
            if (player.isOnline()) {
59
                sendCaptcha(player, cc, data);
60
            }
61
        }
62
    }
63
64
    @Override
65
    public void sendNewCaptcha(Player player, ChatConfig cc, ChatData data) {
66
        // Display a captcha to the player.
67
        generateCaptcha(cc, data, true);
68
        sendCaptcha(player, cc, data);
69
        data.captchaStarted = true;
70
    }
71
72
    @Override
73
    public void generateCaptcha(ChatConfig cc, ChatData data, boolean reset) {
74
        if (reset) data.captchTries = 0;
75
        final char[] chars = new char[cc.captchaLength];
76
        for (int i = 0; i < cc.captchaLength; i++) {
77
            chars[i] = cc.captchaCharacters.charAt(ThreadLocalRandom.current().nextInt(cc.captchaCharacters.length()));
78
        }
79
        data.captchaGenerated = new String(chars);
80
    }
81
82
    @Override
83
    public void resetCaptcha(Player player){
84
        final IPlayerData pData = DataManager.getPlayerData(player);
85
        ChatData data = pData.getGenericInstance(ChatData.class);
86
        synchronized (data) {
87
            resetCaptcha(player, pData.getGenericInstance(ChatConfig.class), data, pData);
88
        }
89
    }
90
91
    @Override
92
    public void resetCaptcha(Player player, ChatConfig cc, ChatData data, IPlayerData pData) {
93
        data.captchTries = 0;
94
        if (shouldCheckCaptcha(player, cc, data, pData) || shouldStartCaptcha(player, cc, data, pData)){
95
            generateCaptcha(cc, data, true);
96
        }
97
    }
98
99
    @Override
100
    public void sendCaptcha(Player player, ChatConfig cc, ChatData data) {
101
        player.sendMessage(ColorUtil.replaceColors(cc.captchaQuestion.replace("[captcha]", data.captchaGenerated)));
102
    }
103
104
    @Override
105
    public boolean shouldStartCaptcha(Player player, ChatConfig cc, ChatData data, IPlayerData pData) {
106
        // TODO: Only call if IWorldData.isCheckActive(CHAT_CAPTCHA) has returned true?
107
        return !data.captchaStarted && pData.isCheckActive(CheckType.CHAT_CAPTCHA, player);
108
    }
109
110
    @Override
111
    public boolean shouldCheckCaptcha(Player player, ChatConfig cc, ChatData data, IPlayerData pData) {
112
        // TODO: Only call if IWorldData.isCheckActive(CHAT_CAPTCHA) has returned true?
113
        return data.captchaStarted  && pData.isCheckActive(CheckType.CHAT_CAPTCHA, player);
114
    }
115
}

How it counteracts this module

The captcha gate activates automatically from the Commands path: with captchaSkipCommands off, a commands violation arms shouldCheckCaptcha and the next command must match the generated captcha string exactly, with wrong answers incrementing captchaVL toward the configured actions. The module's bootstrap loop is a perfect feeding machine once armed: it keeps sending /api new on its tick cadence, the client has no captcha-reply logic anywhere, so every answer is wrong and the violation climbs. The honest caveat is the same as the Commands boundary: at stock levels the loop scores exactly at the threshold, so captcha arms only in the failure mode where the key never arrives or the level is lowered.

anticheat Text (chat content and frequency)

Text.java331 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.chat;
16
17
import java.util.Collections;
18
import java.util.LinkedList;
19
import java.util.List;
20
import java.util.Map;
21
22
import org.bukkit.entity.Player;
23
24
import fr.neatmonster.nocheatplus.NCPAPIProvider;
25
import fr.neatmonster.nocheatplus.checks.Check;
26
import fr.neatmonster.nocheatplus.checks.CheckType;
27
import fr.neatmonster.nocheatplus.checks.chat.analysis.MessageLetterCount;
28
import fr.neatmonster.nocheatplus.checks.chat.analysis.WordLetterCount;
29
import fr.neatmonster.nocheatplus.checks.chat.analysis.engine.LetterEngine;
30
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
31
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
32
import fr.neatmonster.nocheatplus.components.registry.feature.INotifyReload;
33
import fr.neatmonster.nocheatplus.config.ConfigFile;
34
import fr.neatmonster.nocheatplus.config.ConfigManager;
35
import fr.neatmonster.nocheatplus.players.IPlayerData;
36
import fr.neatmonster.nocheatplus.utilities.ColorUtil;
37
import fr.neatmonster.nocheatplus.utilities.StringUtil;
38
39
/**
40
 * Some alternative more or less advanced analysis methods.
41
 * @author asofold
42
 *
43
 */
44
public class Text extends Check implements INotifyReload {
45
46
    private LetterEngine engine = null;
47
48
    /** Not really cancelled but above threshold for actions. */
49
    private String lastCancelledMessage = "";
50
    private long lastCancelledTime = 0;
51
52
    private String lastGlobalMessage = "";
53
    private long lastGlobalTime = 0;
54
55
    public Text() {
56
        super(CheckType.CHAT_TEXT);
57
        init();
58
    }
59
60
    /**
61
     * Start analysis.
62
     * @param player
63
     *          The player who issued the message.
64
     * @param message
65
     *          The message to check.
66
     * @param captcha 
67
     *          Used for starting captcha on failure, if configured so.
68
     * @param alreadyCancelled 
69
     * @return
70
     */
71
    public boolean check(final Player player, final String message, 
72
                         final ChatConfig cc, final IPlayerData pData,
73
                         final ICaptcha captcha, boolean isMainThread, final boolean alreadyCancelled) {
74
        final ChatData data = pData.getGenericInstance(ChatData.class);
75
        synchronized (data) {
76
            return unsafeCheck(player, message, captcha, cc, data, pData, isMainThread, alreadyCancelled);
77
        }
78
    }
79
80
    private void init() {
81
        // Set some things from the global config.
82
        final ConfigFile config = ConfigManager.getConfigFile();
83
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
84
        if (engine != null) {
85
            engine.clear();
86
            api.removeComponent(engine);
87
        }
88
        engine = new LetterEngine(config);
89
        api.addComponent(engine);
90
    }
91
92
    @Override
93
    public void onReload() {
94
        synchronized(engine) {
95
            engine.clear();
96
        }
97
        init();
98
    }
99
100
    /**
101
     * Check without further synchronization.
102
     * @param player
103
     * @param message
104
     * @param captcha
105
     * @param cc
106
     * @param data
107
     * @param isMainThread 
108
     * @param alreadyCancelled 
109
     * @return
110
     */
111
    private boolean unsafeCheck(final Player player, final String message, final ICaptcha captcha,
112
                                final ChatConfig cc, final ChatData data, final IPlayerData pData,
113
                                boolean isMainThread, final boolean alreadyCancelled) {
114
115
        // Test captcha.
116
        if (captcha.shouldCheckCaptcha(player, cc, data, pData)) {
117
            captcha.checkCaptcha(player, message, cc, data, isMainThread);
118
            return true;
119
        } 
120
        else if (alreadyCancelled) {
121
            // Skip checking.
122
            return true;
123
        }
124
125
        final long time = System.currentTimeMillis();
126
        final String lcMessage = message.trim().toLowerCase();
127
        boolean cancel = false;
128
        final boolean debug = pData.isDebugActive(type);
129
        final List<String> debugParts;
130
        if (debug) {
131
            debugParts = new LinkedList<String>();
132
            debugParts.add("Message (length=" + message.length()+"): ");
133
        }
134
        else debugParts = null;
135
136
        // Update the frequency interval weights.
137
        data.chatFrequency.update(time);
138
139
        // Score for this message (violation score).
140
        float score = 0;
141
        final MessageLetterCount letterCounts = new MessageLetterCount(message);
142
        final int msgLen = message.length();
143
144
145
146
        // (Following: random/made up criteria.)
147
        // TODO: Create tests for all methods with wordlists, fake chat (refactor for that).
148
        // Full message processing. ------------
149
        // Upper case.
150
        if (letterCounts.fullCount.upperCase > msgLen / 3) {
151
            // TODO: Regard chunks of 48 or so letters of the message for this?
152
            final float wUpperCase = 0.6f * letterCounts.fullCount.getUpperCaseRatio();
153
            score += wUpperCase  * cc.textMessageUpperCase;
154
        }
155
156
        // Letters vs. word length.
157
        if (msgLen > 4) {
158
            final float fullRep = letterCounts.fullCount.getLetterCountRatio();
159
            // Long messages: very small and very big are bad !
160
            // 128 is a quick attempt to make one long message possible on 1.11.
161
            final float wRepetition = (float) Math.min(msgLen, 128) / 15.0f * Math.abs(0.5f - fullRep);
162
            score += wRepetition * cc.textMessageLetterCount;
163
164
            // Number of words vs. length of message
165
            final float fnWords = (float) letterCounts.words.length / (float) msgLen;
166
            if (fnWords > 0.75f) { // TODO: balance or configure or remove ?
167
                score += fnWords  * cc.textMessagePartition;
168
            }
169
        }
170
171
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
172
        final long timeout = 8000; // TODO: maybe set dynamically in data.
173
        // Repetition of last message.
174
        if (cc.textMsgRepeatSelf != 0f && time - data.chatLastTime < timeout) {
175
            if (StringUtil.isSimilar(lcMessage, data.chatLastMessage, 0.8f)) {
176
                final float timeWeight = (float) (timeout - (time - data.chatLastTime)) / (float) timeout; 
177
                score += cc.textMsgRepeatSelf * timeWeight;
178
            }
179
        }
180
        // Repetition of last global message.
181
        if (cc.textMsgRepeatGlobal != 0f && time - lastGlobalTime < timeout) {
182
            if (StringUtil.isSimilar(lcMessage, lastGlobalMessage, 0.8f)) {
183
                final float timeWeight = (float) (timeout - (time - lastGlobalTime)) / (float) timeout; 
184
                score += cc.textMsgRepeatGlobal * timeWeight;
185
            }
186
        }
187
        // Repetition of last cancelled message.
188
        if (cc.textMsgRepeatCancel != 0f && time - lastCancelledTime < timeout) {
189
            if (StringUtil.isSimilar(lcMessage, lastCancelledMessage, 0.8f)) {
190
                final float timeWeight = (float) (timeout - (time - lastCancelledTime)) / (float) timeout; 
191
                score += cc.textMsgRepeatCancel * timeWeight;
192
            }
193
        }
194
        // Chat quickly after join.
195
        if (cc.textMsgAfterJoin != 0f && time - cData.lastJoinTime < timeout) {
196
            final float timeWeight = (float) (timeout - (time - cData.lastJoinTime)) / (float) timeout;
197
            score += cc.textMsgAfterJoin * timeWeight; 
198
        }
199
        // Chat without moving.
200
        if (cc.textMsgNoMoving != 0f && time - cData.lastMoveTime > timeout) {
201
            score += cc.textMsgNoMoving;
202
        }
203
204
205
206
        // Per word checks. -------------------
207
        float wWords = 0.0f;
208
        final float avwLen = (float) msgLen / (float) letterCounts.words.length; 
209
        for (final WordLetterCount word : letterCounts.words) {
210
            float wWord = 0.0f;
211
            final int wLen = word.word.length();
212
            // TODO: ? used letters vs. word length.
213
214
            // Length of word vs. av. word length.
215
            final float fLenAv = Math.abs(avwLen - (float) wLen) / avwLen;
216
            wWord += fLenAv * cc.textMessageLengthAv;
217
218
            // Length of word vs. message length;
219
            final float fLenMsg = (float) wLen / (float) msgLen;
220
            wWord += fLenMsg * cc.textMessageLengthMsg;
221
222
            // Not letter:
223
            float notLetter = word.getNotLetterRatio();
224
            notLetter *= notLetter;
225
            wWord += notLetter * cc.textMessageNoLetter;
226
227
            wWord *= wWord; // TODO: quadratic ? (configurable)
228
            wWords += wWord;
229
        }
230
        wWords /= (float) letterCounts.words.length;
231
        score += wWords;
232
233
        if (debug && score > 0f) {
234
            debugParts.add("Simple score: " + StringUtil.fdec3.format(score));
235
        }
236
237
        // Engine:
238
        // TODO: more fine grained sync !
239
        float wEngine = 0f;
240
        final Map<String, Float> engMap;
241
        synchronized (engine) {
242
            engMap = engine.process(letterCounts, player.getName(), cc, data);
243
            // TODO: more fine grained sync !s
244
            // TODO: different methods (add or max or add+max or something else).
245
            for (final Float res : engMap.values()) {
246
                if (cc.textEngineMaximum) {
247
                    wEngine = Math.max(wEngine, res.floatValue());
248
                }
249
                else wEngine += res.floatValue();
250
            }
251
        }
252
        score += wEngine;
253
254
255
        // Wrapping it up. --------------------
256
        // Add weight to frequency counts.
257
        final float normalScore = Math.max(cc.textFreqNormMin, score);
258
        data.chatFrequency.add(time, normalScore);
259
        final float accumulated = cc.textFreqNormWeight * data.chatFrequency.score(cc.textFreqNormFactor);
260
        final boolean normalViolation = accumulated > cc.textFreqNormLevel;
261
        final float shortTermScore = Math.max(cc.textFreqShortTermMin, score);
262
        data.chatShortTermFrequency.add(time, shortTermScore);
263
        // TODO: very short term (1st bucket) or do it indirectly.
264
        final float shortTermAccumulated = cc.textFreqShortTermWeight * data.chatShortTermFrequency.score(cc.textFreqShortTermFactor);
265
        final boolean shortTermViolation = shortTermAccumulated > cc.textFreqShortTermLevel;
266
267
        if (normalViolation || shortTermViolation) {
268
            lastCancelledMessage = lcMessage;
269
            lastCancelledTime = time;
270
271
            final double added;
272
            if (shortTermViolation) {
273
                added = (shortTermAccumulated - cc.textFreqShortTermLevel)/ 3.0;
274
            } 
275
            else added = (accumulated - cc.textFreqNormLevel) / 10.0; 
276
            data.textVL += added;
277
278
            if (captcha.shouldStartCaptcha(player, cc, data, pData)) {
279
                captcha.sendNewCaptcha(player, cc, data);
280
                cancel = true;
281
            }
282
            else {
283
                if (shortTermViolation) {
284
                    if (executeActions(player, data.textVL, added, cc.textFreqShortTermActions).willCancel()) {
285
                        cancel = true;
286
                    }
287
                }
288
                else if (normalViolation) {
289
                    if (executeActions(player, data.textVL, added, cc.textFreqNormActions).willCancel()) {
290
                        cancel = true;
291
                    }
292
                }
293
            }
294
        }
295
        else if (cc.chatWarningCheck && time - data.chatWarningTime > cc.chatWarningTimeout && (100f * accumulated / cc.textFreqNormLevel > cc.chatWarningLevel || 100f * shortTermAccumulated / cc.textFreqShortTermLevel > cc.chatWarningLevel)) {
296
            NCPAPIProvider.getNoCheatPlusAPI().sendMessageOnTick(player.getName(), ColorUtil.replaceColors(cc.chatWarningMessage));
297
            data.chatWarningTime = time;
298
        }
299
        else {
300
            data.textVL *= 0.95;
301
            if (cc.textAllowVLReset && normalScore < 2.0f * cc.textFreqNormWeight && shortTermScore < 2.0f * cc.textFreqShortTermWeight) {
302
                // Reset the VL.
303
                // Maybe elaborate on resetting conditions (after some timeout just divide by two or so?).
304
                data.textVL = 0.0;
305
            }
306
        }
307
308
        if (debug) {
309
            final List<String> keys = new LinkedList<String>(engMap.keySet());
310
            Collections.sort(keys);
311
            for (String key : keys) {
312
                Float s = engMap.get(key);
313
                if (s.floatValue() > 0.0f)
314
                    debugParts.add(key + ":" + StringUtil.fdec3.format(s));
315
            }
316
            if (wEngine > 0.0f)
317
                debugParts.add("Engine score (" + (cc.textEngineMaximum?"max":"sum") + "): " + StringUtil.fdec3.format(wEngine));
318
319
            debugParts.add("Final score: " +  StringUtil.fdec3.format(score));
320
            debugParts.add("Normal: min=" +  StringUtil.fdec3.format(cc.textFreqNormMin) +", weight=" +  StringUtil.fdec3.format(cc.textFreqNormWeight) + " => accumulated=" + StringUtil.fdec3.format(accumulated));
321
            debugParts.add("Short-term: min=" +  StringUtil.fdec3.format(cc.textFreqShortTermMin) +", weight=" +  StringUtil.fdec3.format(cc.textFreqShortTermWeight) + " => accumulated=" + StringUtil.fdec3.format(shortTermAccumulated));
322
            debugParts.add("vl: " + StringUtil.fdec3.format(data.textVL));
323
            debug(player, StringUtil.join(debugParts, " | "));
324
            debugParts.clear();
325
        }
326
327
        lastGlobalMessage = data.chatLastMessage = lcMessage;
328
        lastGlobalTime = data.chatLastTime = time;
329
        return cancel;
330
    }
331
}

How it counteracts this module

The content-scoring check runs on AsyncPlayerChatEvent, which Bukkit never fires for '/'-prefixed messages, so the module's only serverbound traffic (the /api new stream) is invisible to Text by construction. The S02 side is receive-only: the module consumes an existing chat packet and sends nothing, so no content check can observe the key capture either. Text is therefore an honest boundary that defines what the module does not expose: had the bootstrap sent bare chat instead of a command, the upper-case and letter-ratio scores, the 8000 ms repeat-similarity test and the frequency accumulators would all apply to it.

anticheat ChatEvent (Spartan dispatch shim)

ChatEvent.java19 lines · Java
1
package ai.idealistic.spartan.listeners.bukkit.standalone;
2
3
import ai.idealistic.spartan.abstraction.protocol.PlayerProtocol;
4
import ai.idealistic.spartan.functionality.concurrent.CheckThread;
5
import ai.idealistic.spartan.functionality.server.PluginBase;
6
import org.bukkit.event.EventHandler;
7
import org.bukkit.event.EventPriority;
8
import org.bukkit.event.Listener;
9
import org.bukkit.event.player.AsyncPlayerChatEvent;
10
11
public class ChatEvent implements Listener {
12
13
    @EventHandler(priority = EventPriority.HIGHEST)
14
    private void Event(AsyncPlayerChatEvent e) {
15
        PlayerProtocol p = PluginBase.getProtocol(e.getPlayer());
16
        CheckThread.run(null, () -> p.executeRunners(e.isCancelled(), e));
17
    }
18
19
}

How it counteracts this module

Spartan's only chat hook in the corpus is a Bukkit dispatch shim: ChatEvent listens to AsyncPlayerChatEvent at HIGHEST priority and routes the event into the check runner, with no chat-content or command-rate analysis in the clone. The '/'-prefixed /api new traffic does not even reach it, since commands fire PlayerCommandPreprocessEvent. Its value is the exposure surface it points to: the Bukkit event chain is where moderation plugins and server-side command logging see the key bootstrap, which is the only part of the module a server can ever observe.

← Back to Analysis Hub