Nekoware v1 private AutoArmor module 2 files, 142 lines

Nekoware v1 private AutoArmor: Full Source Analysis

Nekoware v1 private's AutoArmor is a byte-for-byte fork of Memeware 7.3's module - same tier arrays, same self-referential protection comparison, same one-shot Timer latch - differing only…

me/nekoWare/client/module/combat/AutoArmor.java · GitHub source ↗

Published 2026-08-12 · Updated 2026-08-12

Analysis

Overview

Nekoware v1 private's AutoArmor is a byte-for-byte fork of Memeware 7.3's module - same tier arrays, same self-referential protection comparison, same one-shot Timer latch - differing only in the display name passed to the Module constructor. The handler runs on every pre-update tick after the first half-second of client uptime, cycling one armor slot at a time through the 5-8 rotation and shift-clicking the first matching piece it finds into whatever slot is empty. Because change() evaluates the armor slot's own stack instead of the candidate's, the module cannot rank armor and cannot upgrade an occupied slot; it only fills gaps. Each equip emits C0EPacketClickWindow traffic on window 0 (mode 1 SHIFT_CLICK) with no GUI open, and the fork's PlayerControllerMP.windowClick omits the held-slot sync, so the swap is pure C0E with no C09 companion - the same closed-window, same-tick click burst as its parent client. The shared lineage means both modules trip the same anticheat surfaces, and Nekoware adds nothing to hide it.

Fork lineage

The file is Memeware 7.3's AutoArmor.java with the package renamed me.nekoWare, the class renamed, and the module title changed from 'Auto Armor' to 'AutoArmor'. Every behavioral line matches: the five-element tier arrays per armor slot, the inventory scan over container slots 9-44, the canEquip slot mapping, the change() ranker that compares the armor slot's own stack against itself, the two windowClick(0, slot, 0, 1) calls, and the Timer that is constructed once and never reset. The only divergence is cosmetic, which makes the two modules a single codebase for anticheat purposes: anything that detects one detects the other, and the identical wire pattern - two C0E SHIFT_CLICK packets in one tick, per empty armor slot, with no preceding window-open - is the fingerprint.

Per-tick rotation and gap filling

The num field walks 5 (helmet) through 8 (boots), one slot per tick, wrapping back to 5. Each cycle scans inventory slots 9-44 for the first stack whose canEquip() equals the current num, and the change() guard only passes when the armor slot is empty: protVal starts at -1.0 against getProtValue(null) == 0.0, so the first candidate is pinned (item = slot, maxValue = 0.0) and every subsequent candidate in the same cycle loses the 0.0 <= 0.0 tie. The result is first-scan-order equipping - an iron chestplate in slot 9 beats a diamond one in slot 20 - and no upgrade path at all once a slot is filled. The timer.delay(500L) check is a latch, not a period, so a full four-slot equip completes in four ticks from world entry rather than the two seconds the constant implies.

Wire signature

The equip sequence is windowClick(0, num, 0, 1, player) then windowClick(0, item, 0, 1, player): a C0EPacketClickWindow with windowId 0, button 0, mode 1 for the armor slot, then a second C0E for the inventory slot. Since the ranker never replaces a worn piece, the first click only fires during the brief window when a slot is empty - the common case is a single C0E per equip. The creative-mode and windowId != 0 guards confine all clicks to window 0 with no screen open. Nekoware's PlayerControllerMP.windowClick (line 518) sends the C0E directly without the syncCurrentPlayItem call, so no C09PacketHeldItemChange is ever emitted by the module; the entire operation is C0E-only, which is the signature the countering checks below are keyed to.

source AutoArmor.java (module)

AutoArmor.java111 lines · JavaOriginal ↗
1
2
package me.nekoWare.client.module.combat;
3
4
import me.hippo.api.lwjeb.annotation.Handler;
5
import me.nekoWare.client.event.events.UpdateEvent;
6
import me.nekoWare.client.module.Module;
7
import me.nekoWare.client.util.misc.Timer;
8
import net.minecraft.enchantment.Enchantment;
9
import net.minecraft.enchantment.EnchantmentHelper;
10
import net.minecraft.item.Item;
11
import net.minecraft.item.ItemArmor;
12
import net.minecraft.item.ItemStack;
13
14
import java.util.function.Consumer;
15
16
public class AutoArmor extends Module {
17
    private static final int[] HELMET = new int[]{310, 306, 314, 302, 298};
18
    private static final int[] CHESTPLATE = new int[]{311, 307, 315, 303, 299};
19
    private static final int[] LEGGINGS = new int[]{312, 308, 316, 304, 300};
20
    private static final int[] BOOTS = new int[]{313, 309, 317, 305, 301};
21
22
    private Timer timer = new Timer();
23
    private int num = 5;
24
    private double maxValue = -1.0;
25
    private double protVal;
26
    private int item = -1;
27
28
    public AutoArmor() {
29
        super("AutoArmor", 0, Module.Category.COMBAT);
30
    }
31
32
33
    @Handler
34
    public Consumer<UpdateEvent> update = e -> {
35
        if (e.isPost())
36
            return;
37
        if (mc.thePlayer.capabilities.isCreativeMode
38
                || mc.thePlayer.openContainer != null && mc.thePlayer.openContainer.windowId != 0) {
39
            return;
40
        }
41
        if (timer.delay(500L)) {
42
            maxValue = -1.0;
43
            item = -1;
44
            for (int i = 9; i < 45; ++i) {
45
                if (mc.thePlayer.inventoryContainer.getSlot(i).getStack() == null
46
                        || canEquip(mc.thePlayer.inventoryContainer.getSlot(i).getStack()) == -1
47
                        || canEquip(mc.thePlayer.inventoryContainer.getSlot(i).getStack()) != num) {
48
                    continue;
49
                }
50
                change(num, i);
51
            }
52
            if (item != -1) {
53
                if (mc.thePlayer.inventoryContainer.getSlot(item).getStack() != null) {
54
                    mc.playerController.windowClick(0, num, 0, 1, mc.thePlayer);
55
                }
56
                mc.playerController.windowClick(0, item, 0, 1, mc.thePlayer);
57
            }
58
            num = num == 8 ? 5 : ++num;
59
        }
60
    };
61
62
    private int canEquip(ItemStack stack) {
63
        for (int id : BOOTS) {
64
            if (Item.getIdFromItem(stack.getItem()) != id) {
65
                continue;
66
            }
67
            return 8;
68
        }
69
        for (int id : LEGGINGS) {
70
            if (Item.getIdFromItem(stack.getItem()) != id) {
71
                continue;
72
            }
73
            return 7;
74
        }
75
        for (int id : CHESTPLATE) {
76
            if (Item.getIdFromItem(stack.getItem()) != id) {
77
                continue;
78
            }
79
            return 6;
80
        }
81
        for (int id : HELMET) {
82
            if (Item.getIdFromItem(stack.getItem()) != id) {
83
                continue;
84
            }
85
            return 5;
86
        }
87
        return -1;
88
    }
89
90
    private void change(int armorSlot, int slot) {
91
        ItemStack stack = mc.thePlayer.inventoryContainer.getSlot(armorSlot).getStack();
92
        protVal = maxValue == -1.0 ? stack != null
93
                ? getProtValue(stack)
94
                : maxValue : maxValue;
95
        if (protVal <= getProtValue(stack)
96
                && protVal != getProtValue(stack)) {
97
            item = slot;
98
            maxValue = getProtValue(stack);
99
        }
100
    }
101
102
    private double getProtValue(ItemStack stack) {
103
        if (stack != null) {
104
            return ((ItemArmor) stack.getItem()).damageReduceAmount
105
                    + (100 - ((ItemArmor) stack.getItem()).damageReduceAmount * 4)
106
                    * EnchantmentHelper.getEnchantmentLevel(Enchantment.field_180310_c.effectId, stack) * 4
107
                    * 0.0075;
108
        }
109
        return 0.0;
110
    }
111
}

What this file does

The module body mirrors Memeware 7.3 exactly. The UpdateEvent handler (lines 33-60) bails on post events, creative mode, and any openContainer.windowId other than 0; the timer check (line 41) is the non-resetting one-shot latch; the scan (lines 44-51) filters slots 9-44 to items whose canEquip() equals the current armor slot num; and lines 52-57 emit the one or two windowClick(0, ..., 0, 1) calls that become the C0E burst. Line 58 advances the rotation. canEquip (lines 62-88) returns the armor slot index for each of the four item families, and change() (lines 90-100) holds the ranker bug: stack is the armor slot's own stack, protVal derives from it, and the guard compares it against itself, so only the first candidate of an empty-slot cycle is selected. getProtValue (lines 102-110) is the unused rating formula.

source Timer.java (cadence gate)

Timer.java31 lines · JavaOriginal ↗
1
2
package me.nekoWare.client.util.misc;
3
4
public class Timer {
5
    private long prevMS = 0L;
6
7
    public Timer() {
8
        this.reset();
9
    }
10
11
    public boolean delay(final float milliSec) {
12
        return this.getTime() - this.prevMS >= milliSec;
13
    }
14
15
    public void reset() {
16
        this.prevMS = this.getTime();
17
    }
18
19
    public long getTime() {
20
        return System.nanoTime() / 1000000L;
21
    }
22
23
    public boolean sleep(long time) {
24
	    if (getTime() >= time) {
25
	      reset();
26
	      return true;
27
	    } 
28
	    return false;
29
	  }
30
31
}

What this file does

Nekoware ships the same Timer as its parent client: a constructor reset to the current millis and a delay(milliSec) that only compares - no reset inside. AutoArmor never calls reset(), so the gate opens 500ms after the module instance is constructed (client startup) and stays open for the rest of the session, which is what turns the intended 500ms cadence into a per-tick cadence. Modules that do call reset() - Nekoware's AutoPotion-family modules - get a genuine period from the same class. The class is the load-bearing difference between the module's intended and actual click rates.

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 FastClick (C0E click-rate ledger)

FastClick.java243 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.inventory;
16
17
import java.util.ArrayList;
18
import java.util.List;
19
20
import org.bukkit.Material;
21
import org.bukkit.entity.Player;
22
import org.bukkit.event.inventory.InventoryClickEvent;
23
import org.bukkit.event.inventory.InventoryType;
24
import org.bukkit.inventory.InventoryView;
25
import org.bukkit.inventory.ItemStack;
26
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
32
import fr.neatmonster.nocheatplus.permissions.Permissions;
33
import fr.neatmonster.nocheatplus.players.IPlayerData;
34
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
35
import fr.neatmonster.nocheatplus.utilities.StringUtil;
36
import fr.neatmonster.nocheatplus.utilities.TickTask;
37
38
39
/**
40
 * FastClick checks for players clicking in inventories too quickly (nerfs autosteal cheats and the like).
41
 */
42
public class FastClick extends Check {
43
44
45
    final List<String> tags = new ArrayList<String>();
46
47
48
    /**
49
     * Instantiates a new fast click check.
50
     */
51
    public FastClick() {
52
        super(CheckType.INVENTORY_FASTCLICK);
53
    }
54
55
56
   /**
57
    * Checks a player.
58
    * 
59
    * @param player
60
    * @param now Millisec
61
    * @param view
62
    * @param slot
63
    * @param cursor
64
    * @param clicked
65
    * @param isShiftClick
66
    * @param inventoryAction
67
    * @param data
68
    * @param cc 
69
    * @param pData
70
    * @return true, if successful
71
    */
72
    public boolean check(final Player player, final long now, 
73
                         final InventoryClickEvent event, final int slot, final ItemStack cursor, 
74
                         final ItemStack clicked, final boolean isShiftClick, 
75
                         final String inventoryAction, final InventoryData data, final InventoryConfig cc, 
76
                         final IPlayerData pData) {
77
78
        final float amount;
79
        final Material clickedMat = clicked == null ? Material.AIR : clicked.getType();
80
        final Material cursorMat;
81
        final int cursorAmount;
82
        boolean cancel = false;
83
        tags.clear();
84
85
        if (cursor != null) {
86
            cursorMat = cursor.getType();
87
            cursorAmount = Math.max(1, cursor.getAmount());
88
        }
89
        else {
90
            cursorMat = null;
91
            cursorAmount = 0;
92
        }
93
94
        if (inventoryAction != null) {
95
            amount = getAmountWithAction(event, slot, clicked, clickedMat, cursorMat, cursorAmount, isShiftClick, inventoryAction, data, cc);
96
        }
97
        else if (cursor != null) {
98
            // Detect shift-click features indirectly.
99
            amount = detectTweaks1_5(event, slot, clicked, clickedMat, cursorMat, cursorAmount, isShiftClick, data, cc);
100
        }
101
        else amount = 1f;
102
103
        if (isShiftClick && inventoryAction.equals("MOVE_TO_OTHER_INVENTORY") 
104
            && (cursorMat != null && cursorMat != Material.AIR) 
105
            && clickedMat != Material.AIR) {
106
            return false;
107
        }
108
        
109
        // Count clicks
110
        data.fastClickFreq.add(now, amount);
111
        
112
        // Shor-term VL
113
        float shortTerm = data.fastClickFreq.bucketScore(0);
114
        if (shortTerm > cc.fastClickShortTermLimit) {
115
            // Check for lag.
116
            shortTerm /= (float) TickTask.getLag(data.fastClickFreq.bucketDuration(), true);
117
        }
118
        shortTerm -= cc.fastClickShortTermLimit;
119
        
120
        // Normal VL
121
        float normal = data.fastClickFreq.score(1f);
122
        if (normal > cc.fastClickNormalLimit) {
123
            // Check for lag.
124
            normal /= (float) TickTask.getLag(data.fastClickFreq.bucketDuration() * data.fastClickFreq.numberOfBuckets(), true);
125
        }
126
        normal -= cc.fastClickNormalLimit;
127
        
128
        // Process Violations.
129
        final double violation = Math.max(shortTerm, normal);
130
        if (violation > 0.0) {
131
            tags.add("clickspeed");
132
            data.fastClickVL += violation;
133
            final ViolationData vd = new ViolationData(this, player, data.fastClickVL, violation, cc.fastClickActions);
134
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
135
            cancel = executeActions(vd).willCancel();
136
        }
137
        else data.fastClickVL *= 0.99;
138
139
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
140
            player.sendMessage("FastClick: " + data.fastClickFreq.bucketScore(0) + " | " + data.fastClickFreq.score(1f) + " | cursor=" + cursor 
141
                                + " | clicked=" + clicked + " | action=" + inventoryAction);
142
        }
143
        
144
        // Adjust data
145
        data.fastClickLastClicked = clickedMat;
146
        data.fastClickLastSlot = slot;
147
        data.fastClickLastCursor = cursorMat;
148
        data.fastClickLastCursorAmount = cursorAmount;
149
150
        // Lastly, always feed the improbable.
151
        if (cc.fastClickImprobableWeight > 0.0f) {
152
            Improbable.feed(player, cc.fastClickImprobableWeight * amount, now);
153
        }
154
        return cancel;
155
    }
156
    
157
158
   /**
159
    * Enforce sane timings for interacting with the container and clicking in it.
160
    * 
161
    * @param player
162
    * @param data
163
    * @param cc
164
    */
165
    public boolean checkContainerInteraction(final Player player, final InventoryData data, final InventoryConfig cc) {
166
        boolean cancel = false;
167
        tags.clear();
168
        if (InventoryUtil.isContainerInteractionRecent(player, cc.chestOpenLimit)) {
169
            // Interaction was too quick, violation.
170
            tags.add("interact_time");
171
            long duration = Math.max(data.lastClickTime - data.containerInteractTime, 20);
172
            double violation = (cc.chestOpenLimit / duration) * 100D; // Normalize.
173
            data.fastClickVL += violation;
174
            final ViolationData vd = new ViolationData(this, player, data.fastClickVL, violation, cc.fastClickActions);
175
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
176
            cancel = executeActions(vd).willCancel();  
177
        }
178
       return cancel;
179
    }
180
    
181
182
   /**
183
    * Detect the inventory tweaks that were introduced in MC 1.5
184
    * 
185
    * @param view
186
    * @param slot
187
    * @param clicked
188
    * @param clickedMat
189
    * @param cursorAmount
190
    * @param isShiftClick
191
    * @param data
192
    * @param cc
193
    */
194
    private float detectTweaks1_5(final InventoryClickEvent event, final int slot, final ItemStack clicked, 
195
                                  final Material clickedMat, final Material cursorMat, 
196
                                  final int cursorAmount, final boolean isShiftClick, 
197
                                  final InventoryData data, final InventoryConfig cc) {
198
199
        if (cursorMat != data.fastClickLastCursor 
200
            && (!isShiftClick || clickedMat == Material.AIR || clickedMat != data.fastClickLastClicked) 
201
            || cursorMat == Material.AIR || cursorAmount != data.fastClickLastCursorAmount) {
202
            return 1f;
203
        }
204
        else if (clickedMat == Material.AIR || clickedMat == cursorMat 
205
                || isShiftClick && clickedMat == data.fastClickLastClicked ) {
206
            return Math.min(cc.fastClickNormalLimit , cc.fastClickShortTermLimit) 
207
                    / (float) (isShiftClick && clickedMat != Material.AIR ? (1.0 + Math.max(cursorAmount, InventoryUtil.getStackCount(event, clicked))) : cursorAmount)  * 0.75f;
208
        }
209
        return 1f;
210
    }
211
212
213
    private float getAmountWithAction(final InventoryClickEvent event, final int slot, final ItemStack clicked, 
214
                                      final Material clickedMat, final Material cursorMat, 
215
                                      final int cursorAmount, final boolean isShiftClick, 
216
                                      final String inventoryAction, 
217
                                      final InventoryData data, final InventoryConfig cc) {
218
219
        // Continuous drop feature with open inventories.
220
        if (inventoryAction.equals("DROP_ONE_SLOT")
221
            && slot == data.fastClickLastSlot 
222
            && clickedMat == data.fastClickLastClicked
223
            && event.getInventory().getType() == InventoryType.CRAFTING
224
            // && InventoryUtil.couldHaveInventoryOpen(player)
225
            // TODO: Distinguish if the inventory is really open.
226
            ) {
227
            return 0.6f;
228
        }
229
230
        // Collect to cursor.
231
        if (inventoryAction.equals("COLLECT_TO_CURSOR")) {
232
            final int stackCount = InventoryUtil.getStackCount(event, clicked);
233
            return stackCount <= 0 ? 1f : Math.min(cc.fastClickNormalLimit , cc.fastClickShortTermLimit) / stackCount * 0.75f;
234
        }
235
236
        // Shift click features.
237
        if ((inventoryAction.equals("MOVE_TO_OTHER_INVENTORY")) && cursorMat != Material.AIR) {
238
            // Let the legacy method do the side condition checks and counting for now.
239
            return detectTweaks1_5(event, slot, clicked, clickedMat, cursorMat, cursorAmount, isShiftClick, data, cc);
240
        }
241
        return 1f;
242
    }
243
}

How it counteracts this module

FastClick is NCP's per-click accounting layer for window traffic. Every InventoryClickEvent is fed to FastClick.check, which adds an amount-weighted sample to data.fastClickFreq - shift-click MOVE_TO_OTHER_INVENTORY actions are discounted through detectTweaks1_5 by dividing the limit by the stack counts involved - then scores the newest bucket against fastClickShortTermLimit and the whole window against fastClickNormalLimit, decaying VL by 0.99 on clean buckets and feeding Improbable when configured. For Nekoware's module the ledger sees one or two SHIFT_CLICK C0Es per armor slot, all in the same tick because the rotation advances per tick; a full four-slot equip is a 4-8 click burst inside 200ms, which is exactly the short-term window the check samples. Sustained combat equipping - re-equipping after armor breaks, or toggling the module - repeats the burst, and each burst lands in a fresh bucket. The click-speed thresholds are tuned to tolerate rapid legitimate clicking, so the module usually survives the raw rate; what it cannot avoid is the surrounding accounting: checkContainerInteraction compares click timing against container-open timing (never satisfied here), and every click feeds Improbable, dragging the combined probability score toward flagging.

anticheat InventoryActions (clicks with inventory closed)

InventoryActions.java60 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.check.interaction.inventory;
20
21
/*
22
 * InventoryActions check originally written by Havesta; modified, split apart, and implemented into Hawk by Islandscout
23
 *
24
 * InventoryActions checks if a player is
25
 * - interacting with entities/blocks while inventory is opened
26
 */
27
28
import me.islandscout.hawk.HawkPlayer;
29
import me.islandscout.hawk.check.CustomCheck;
30
import me.islandscout.hawk.event.*;
31
32
public class InventoryActions extends CustomCheck {
33
34
    public InventoryActions() {
35
        super("inventoryactions", true, 3, 5, 0.999, 5000, "%player% failed inventory-actions, VL: %vl%", null);
36
    }
37
38
    @Override
39
    protected void check(Event e) {
40
        HawkPlayer pp = e.getHawkPlayer();
41
42
        //player tried to interact with entities/world while an inventory window is open
43
        if(pp.hasInventoryOpen() != 0 && (e instanceof InteractEntityEvent || e instanceof BlockDigEvent ||
44
                e instanceof ArmSwingEvent || e instanceof InteractWorldEvent)) {
45
            punish(pp, true, e);
46
            e.resync();
47
            //TODO After failing several times, there's a chance that they could be legit, but the inventory state is glitched. Close the player's inventory.
48
        }
49
50
        //player tried to interact with inventory while it is closed
51
        else if(pp.hasInventoryOpen() == 0 && e instanceof ClickInventoryEvent) {
52
            //TODO also check that window ID makes sense with the window type (eg. ID 0 must mean hasInventoryOpen() == 0)
53
            punish(pp, true, e);
54
            e.resync();
55
        }
56
        else {
57
            reward(pp);
58
        }
59
    }
60
}

How it counteracts this module

Hawk's InventoryActions enforces the invariant that window clicks require an open window. When HawkPlayer.hasInventoryOpen() is 0 and a ClickInventoryEvent arrives, the check punishes (VL +1) and calls e.resync() - the first branch of check() is written for exactly the cheat family this module belongs to, and the comment in the source names the residual problem: after repeated fails the server-side inventory state may disagree with the client, which is precisely the state an auto-armor module produces. Nekoware's handler clicks window 0 from a pre-update event while mc.currentScreen is null, so hasInventoryOpen() is always 0 when its C0Es arrive. The resync is the operative countermeasure: it force-syncs the inventory, reverting the just-completed armor swap, so the module's local view and the server's view diverge and its next scan clicks stale slots - every cycle repeats the punish/resync loop as long as the module is on. Because the check is cancellable and accumulates VL with no false-positive pressure from legitimate closed-window clicks (humans cannot click a closed inventory), sustained use is a guaranteed VL climb.

anticheat CheckEnums (INVENTORY_CLICKS registration)

CheckEnums.java182 lines · Java
1
package ai.idealistic.spartan.abstraction.check;
2
3
import ai.idealistic.spartan.abstraction.check.implementation.misc.ImpossibleInventory;
4
import ai.idealistic.spartan.abstraction.check.implementation.misc.InventoryClicks;
5
import ai.idealistic.spartan.abstraction.check.implementation.movement.GravitySimulation;
6
import ai.idealistic.spartan.abstraction.check.implementation.movement.SpeedSimulation;
7
import ai.idealistic.spartan.abstraction.check.implementation.movement.exploits.Exploits;
8
import ai.idealistic.spartan.utils.minecraft.inventory.MaterialUtils;
9
import lombok.Getter;
10
import org.bukkit.Material;
11
12
import java.util.Collection;
13
import java.util.Map;
14
import java.util.concurrent.ConcurrentHashMap;
15
16
public class CheckEnums {
17
18
    public enum HackType {
19
        HIT_REACH(
20
                HackCategoryType.COMBAT,
21
                ai.idealistic.spartan.abstraction.check.implementation.combat.HitReach.class,
22
                Material.ARROW
23
        ),
24
        CRITICALS(
25
                HackCategoryType.COMBAT,
26
                ai.idealistic.spartan.abstraction.check.implementation.combat.Criticals.class,
27
                Material.REDSTONE
28
        ),
29
        FAST_CLICKS(
30
                HackCategoryType.COMBAT,
31
                ai.idealistic.spartan.abstraction.check.implementation.combat.FastClicks.class,
32
                Material.LEVER
33
        ),
34
        VELOCITY(
35
                HackCategoryType.COMBAT,
36
                ai.idealistic.spartan.abstraction.check.implementation.combat.Velocity.class,
37
                Material.CHAINMAIL_BOOTS
38
        ),
39
        KILL_AURA(
40
                HackCategoryType.COMBAT,
41
                ai.idealistic.spartan.abstraction.check.implementation.combat.killaura.KillAura.class,
42
                Material.IRON_SWORD
43
        ),
44
        IRREGULAR_MOVEMENTS(
45
                HackCategoryType.MOVEMENT,
46
                ai.idealistic.spartan.abstraction.check.implementation.movement.irregularmovements.IrregularMovements.class,
47
                Material.HOPPER
48
        ),
49
        GRAVITY_SIMULATION(
50
                HackCategoryType.MOVEMENT,
51
                GravitySimulation.class,
52
                Material.LADDER
53
        ),
54
        SPEED_SIMULATION(
55
                HackCategoryType.MOVEMENT,
56
                SpeedSimulation.class,
57
                Material.FEATHER
58
        ),
59
        EXPLOITS(
60
                HackCategoryType.MOVEMENT,
61
                Exploits.class,
62
                Material.TNT
63
        ),
64
        MORE_PACKETS(
65
                HackCategoryType.MOVEMENT,
66
                ai.idealistic.spartan.abstraction.check.implementation.movement.MorePackets.class,
67
                Material.FLINT_AND_STEEL
68
        ),
69
        X_RAY(
70
                HackCategoryType.WORLD,
71
                ai.idealistic.spartan.abstraction.check.implementation.world.XRay.class,
72
                Material.GLASS
73
        ),
74
        IMPOSSIBLE_ACTIONS(
75
                HackCategoryType.WORLD,
76
                ai.idealistic.spartan.abstraction.check.implementation.world.impossibleactions.ImpossibleActions.class,
77
                Material.BEDROCK
78
        ),
79
        FAST_BREAK(
80
                HackCategoryType.WORLD,
81
                ai.idealistic.spartan.abstraction.check.implementation.world.FastBreak.class,
82
                Material.ENCHANTED_BOOK
83
        ),
84
        FAST_PLACE(
85
                HackCategoryType.WORLD,
86
                ai.idealistic.spartan.abstraction.check.implementation.world.FastPlace.class,
87
                Material.STONE
88
        ),
89
        BLOCK_REACH(
90
                HackCategoryType.WORLD,
91
                ai.idealistic.spartan.abstraction.check.implementation.world.BlockReach.class,
92
                Material.FISHING_ROD
93
        ),
94
        NO_SWING(
95
                HackCategoryType.MISCELLANEOUS,
96
                ai.idealistic.spartan.abstraction.check.implementation.misc.NoSwing.class,
97
                Material.SHEARS
98
        ),
99
        INVENTORY_CLICKS(
100
                HackCategoryType.MISCELLANEOUS,
101
                InventoryClicks.class,
102
                Material.STONE_BUTTON
103
        ),
104
        FAST_HEAL(
105
                HackCategoryType.MISCELLANEOUS,
106
                ai.idealistic.spartan.abstraction.check.implementation.misc.FastHeal.class,
107
                Material.APPLE
108
        ),
109
        IMPOSSIBLE_INVENTORY(
110
                HackCategoryType.MISCELLANEOUS,
111
                ImpossibleInventory.class,
112
                Material.MILK_BUCKET
113
        ),
114
        FAST_EAT(
115
                HackCategoryType.MISCELLANEOUS,
116
                ai.idealistic.spartan.abstraction.check.implementation.misc.FastEat.class,
117
                Material.CAKE
118
        );
119
120
        @Getter
121
        private Check check;
122
        public final HackCategoryType category;
123
        public final Class<?> executor;
124
        private final Map<String, Long> detections;
125
        public final Material material;
126
127
        HackType(HackCategoryType category, Class<?> executor, Material material) {
128
            this.category = category;
129
            this.executor = executor;
130
            this.detections = new ConcurrentHashMap<>();
131
            this.check = new Check(this);
132
            this.material = material;
133
        }
134
135
        public void resetCheck() {
136
            if (this.check != null) {
137
                this.check = new Check(this);
138
            }
139
        }
140
141
        public void addDetection(String detection, long averageTime) {
142
            this.detections.put(detection, averageTime);
143
        }
144
145
        public void removeDetection(String detection) {
146
            this.detections.remove(detection);
147
        }
148
149
        public long getDefaultAverageTime(String detection) {
150
            return this.detections.get(detection);
151
        }
152
153
        public Collection<String> getDetections() {
154
            return this.detections.keySet();
155
        }
156
157
        @Override
158
        public String toString() {
159
            return super.toString().toLowerCase().replace("_", "-");
160
        }
161
    }
162
163
    public enum HackCategoryType {
164
        COMBAT(Material.IRON_SWORD),
165
        MOVEMENT(Material.FEATHER),
166
        WORLD(Material.DIAMOND_PICKAXE),
167
        MISCELLANEOUS(MaterialUtils.get("crafting_table"));
168
169
        public final Material material;
170
171
        HackCategoryType(Material material) {
172
            this.material = material;
173
        }
174
175
        @Override
176
        public String toString() {
177
            return super.toString().toLowerCase().replace("_", "-");
178
        }
179
180
    }
181
182
}

How it counteracts this module

Spartan's detection registry maps HackType entries to executor classes; the C0E-relevant registrations are INVENTORY_CLICKS (executor InventoryClicks.class, HackCategoryType.MISCELLANEOUS) and IMPOSSIBLE_INVENTORY (executor ImpossibleInventory.class), with FAST_CLICKS covering the swing/click path. Each HackType owns a Check instance and a per-player detections map that the runner framework fills as clicks are processed. For Nekoware's module the significance is structural: the click stream from InventoryEvent.executeRunners is matched against these registered executors, and the inventory-click checks are the ones designed to distinguish a human organizing a chest from a script emitting SHIFT_CLICK pairs at 20 slots per second with no window open. The module's same-tick C0E pairs are delivered as consecutive click events, and the executor layer sees the full click metadata - slot, cursor, ClickType - so the pattern is visible even though the thresholds themselves live in the executor classes that are not included in this source snapshot.

anticheat InventoryListener (Open check and open-state ledger)

InventoryListener.java717 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.inventory;
16
17
import org.bukkit.ChatColor;
18
import org.bukkit.GameMode;
19
import org.bukkit.Location;
20
import org.bukkit.Material;
21
import org.bukkit.entity.Entity;
22
import org.bukkit.entity.HumanEntity;
23
import org.bukkit.entity.LivingEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.event.EventHandler;
26
import org.bukkit.event.EventPriority;
27
import org.bukkit.event.block.Action;
28
import org.bukkit.event.block.BlockBreakEvent;
29
import org.bukkit.event.block.BlockPlaceEvent;
30
import org.bukkit.event.entity.EntityDeathEvent;
31
import org.bukkit.event.entity.EntityPortalEnterEvent;
32
import org.bukkit.event.entity.EntityShootBowEvent;
33
import org.bukkit.event.entity.FoodLevelChangeEvent;
34
import org.bukkit.event.inventory.InventoryClickEvent;
35
import org.bukkit.event.inventory.InventoryCloseEvent;
36
import org.bukkit.event.inventory.InventoryEvent;
37
import org.bukkit.event.inventory.InventoryOpenEvent;
38
import org.bukkit.event.inventory.InventoryType;
39
import org.bukkit.event.player.PlayerBedEnterEvent;
40
import org.bukkit.event.player.PlayerBedLeaveEvent;
41
import org.bukkit.event.player.PlayerChangedWorldEvent;
42
import org.bukkit.event.player.PlayerEditBookEvent;
43
import org.bukkit.event.player.PlayerInteractEntityEvent;
44
import org.bukkit.event.player.PlayerInteractEvent;
45
import org.bukkit.event.player.PlayerItemConsumeEvent;
46
import org.bukkit.event.player.PlayerItemHeldEvent;
47
import org.bukkit.event.player.PlayerMoveEvent;
48
import org.bukkit.event.player.PlayerPortalEvent;
49
import org.bukkit.event.player.PlayerRespawnEvent;
50
import org.bukkit.event.player.PlayerTeleportEvent;
51
import org.bukkit.inventory.Inventory;
52
import org.bukkit.inventory.ItemStack;
53
import org.bukkit.inventory.meta.BookMeta;
54
55
import fr.neatmonster.nocheatplus.NCPAPIProvider;
56
import fr.neatmonster.nocheatplus.checks.CheckListener;
57
import fr.neatmonster.nocheatplus.checks.CheckType;
58
import fr.neatmonster.nocheatplus.checks.combined.Combined;
59
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
60
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
61
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeHealth;
62
import fr.neatmonster.nocheatplus.compat.registry.BukkitAPIAccessFactory;
63
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
64
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
65
import fr.neatmonster.nocheatplus.components.data.ICheckData;
66
import fr.neatmonster.nocheatplus.components.data.IData;
67
import fr.neatmonster.nocheatplus.components.entity.IEntityAccessVehicle;
68
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
69
import fr.neatmonster.nocheatplus.components.registry.factory.IFactoryOne;
70
import fr.neatmonster.nocheatplus.components.registry.feature.JoinLeaveListener;
71
import fr.neatmonster.nocheatplus.players.DataManager;
72
import fr.neatmonster.nocheatplus.players.IPlayerData;
73
import fr.neatmonster.nocheatplus.players.PlayerFactoryArgument;
74
import fr.neatmonster.nocheatplus.stats.Counters;
75
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
76
import fr.neatmonster.nocheatplus.utilities.ReflectionUtil;
77
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
78
import fr.neatmonster.nocheatplus.utilities.math.MathUtil;
79
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
80
import fr.neatmonster.nocheatplus.worlds.WorldFactoryArgument;
81
82
/**
83
 * Central location to listen to events that are relevant for the inventory checks.
84
 * 
85
 * @see InventoryEvent
86
 */
87
public class InventoryListener  extends CheckListener implements JoinLeaveListener {
88
    
89
    // Checks
90
    /** More Inventory check */
91
    private final MoreInventory moreInv = addCheck(new MoreInventory());
92
93
    /** The fast click check. */
94
    private final FastClick fastClick  = addCheck(new FastClick());
95
96
    /** The instant bow check. */
97
    private final InstantBow instantBow = addCheck(new InstantBow());
98
99
    /** The fast consume check. */
100
    private final FastConsume fastConsume = addCheck(new FastConsume());
101
    
102
    private final Gutenberg gutenberg = addCheck(new Gutenberg());
103
    
104
    /** The open check */
105
    private final Open open = addCheck(new Open());
106
    
107
    // Other/Auxiliary stuff
108
    private boolean keepCancel = false;
109
110
    private final boolean hasInventoryAction;
111
112
    /** For temporary use: LocUtil.clone before passing deeply, call setWorld(null) after use. */
113
    private final Location useLoc = new Location(null, 0, 0, 0);
114
115
    private final Counters counters = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstance(Counters.class);
116
117
    private final int idCancelDead = counters.registerKey("cancel.dead");
118
119
    private final IGenericInstanceHandle<IEntityAccessVehicle> handleVehicles = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IEntityAccessVehicle.class);
120
121
    @SuppressWarnings("unchecked")
122
    public InventoryListener() {
123
        super(CheckType.INVENTORY);
124
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
125
        api.register(api.newRegistrationContext()
126
                // InventoryConfig
127
                .registerConfigWorld(InventoryConfig.class)
128
                .factory(new IFactoryOne<WorldFactoryArgument, InventoryConfig>() {
129
                    @Override
130
                    public InventoryConfig getNewInstance(
131
                            WorldFactoryArgument arg) {
132
                        return new InventoryConfig(arg.worldData);
133
                    }
134
                })
135
                .registerConfigTypesPlayer()
136
                .context() //
137
                // InventoryData
138
                .registerDataPlayer(InventoryData.class)
139
                .factory(new IFactoryOne<PlayerFactoryArgument, InventoryData>() {
140
                    @Override
141
                    public InventoryData getNewInstance(
142
                            PlayerFactoryArgument arg) {
143
                        return new InventoryData();
144
                    }
145
                })
146
                .addToGroups(CheckType.INVENTORY, true, IData.class, ICheckData.class)
147
                .context() //
148
                );
149
        hasInventoryAction = ReflectionUtil.getClass("org.bukkit.event.inventory.InventoryAction") != null;
150
    }
151
152
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
153
    public void onEntityShootBow(final EntityShootBowEvent event) {
154
        // Only if a player shot the arrow.
155
        if (event.getEntity() instanceof Player) {
156
            final Player player = (Player) event.getEntity();
157
            final IPlayerData pData = DataManager.getPlayerData(player);
158
            if (instantBow.isEnabled(player, pData)) {
159
                final long now = System.currentTimeMillis();
160
                final Location loc = player.getLocation(useLoc);
161
                if (Combined.checkYawRate(player, loc.getYaw(), now, loc.getWorld().getName(), pData)) {
162
                    // No else if with this, could be cancelled due to other checks feeding, does not have actions.
163
                    event.setCancelled(true);
164
                }
165
166
                final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
167
                // Still check instantBow, whatever yawrate says.
168
                if (instantBow.check(player, event.getForce(), now)) {
169
                    event.setCancelled(true);
170
                }
171
                else if (cc.instantBowImprobableWeight > 0.0f) {
172
                    if (cc.instantBowImprobableFeedOnly) {
173
                        Improbable.feed(player, cc.instantBowImprobableWeight, now);
174
                    }
175
                    else if (Improbable.check(player, cc.instantBowImprobableWeight, now, "inventory.instantbow", pData)) {
176
                        // Combined fighting speed (Else if: Matter of taste, preventing extreme cascading and actions spam).
177
                        event.setCancelled(true);
178
                    }
179
                }
180
                useLoc.setWorld(null);
181
            }  
182
        }
183
    }
184
185
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
186
    public void onFoodLevelChange(final FoodLevelChangeEvent event) {
187
        // Only if a player ate food.
188
        if (event.getEntity() instanceof Player) {
189
            final Player player = (Player) event.getEntity();
190
            if (player.isDead() && BridgeHealth.getHealth(player) <= 0.0) {
191
                // Eat after death.
192
                event.setCancelled(true);
193
                counters.addPrimaryThread(idCancelDead, 1);
194
            }
195
        }
196
    }
197
198
    @EventHandler(priority = EventPriority.LOWEST)
199
    public void onInventoryClick(final InventoryClickEvent event) {
200
        if (!(event.getWhoClicked() instanceof Player)) {
201
            return;
202
        }
203
        final long now = System.currentTimeMillis();
204
        final HumanEntity entity = event.getWhoClicked();
205
        if (!(entity instanceof Player)) {
206
            return;
207
        }
208
        final Player player = (Player) entity;
209
        final IPlayerData pData = DataManager.getPlayerData(player);
210
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
211
        final int slot = event.getSlot();
212
        final String inventoryAction = hasInventoryAction ? event.getAction().name() : null;
213
        final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
214
        if (pData.isDebugActive(checkType)) {
215
            outputDebugInventoryClick(player, slot, event, inventoryAction);
216
        }
217
        // Set this one as soon as we can and regardless if the click was cancelled or not.
218
        if (data.inventoryOpenTime == 0) {
219
            data.inventoryOpenTime = now;
220
            if (pData.isDebugActive(CheckType.INVENTORY)) {
221
                debug(player, "InventoryClickEvent: inventory wasn't explicitly open previously but an inventory click was sent; register time of the 1st click (assume inventory is open from this moment on)");
222
            }
223
        }
224
        if (event.isCancelled()) {
225
            // Previously: ignoreCancelled = true
226
            // We still want to know if the player clicked in the inventory (even if cancelled) for the inventory-open estimate above.
227
            return;
228
        }
229
        if (slot == -999 || slot < 0) {
230
            // Set and return, not interested in these clicks.
231
            data.lastClickTime = now;
232
            return;
233
        }
234
235
        final ItemStack cursor = event.getCursor();
236
        final ItemStack clicked = event.getCurrentItem();
237
        boolean cancel = false;
238
        // Fast inventory manipulation check.
239
        if (fastClick.isEnabled(player, pData)) {
240
            if (!((event.getInventory().getType().equals(InventoryType.CREATIVE) || player.getGameMode() == GameMode.CREATIVE) && cc.fastClickSpareCreative)) {
241
                boolean check = true;
242
                try {
243
                    // Exempted inventories are not checked.
244
                    check = !cc.inventoryExemptions.contains(ChatColor.stripColor(BukkitAPIAccessFactory.getBukkitAccess().getInventoryTitle(event)));
245
                }
246
                catch (IllegalStateException e) {
247
                    // Uhm... Can this ISE be fixed?
248
                    check = true; 
249
                }
250
                
251
                if (check) {
252
                    // Check for too quick interactions first (we don't need to check for fast clicking if the interaction is inhumanly fast)
253
                    if (InventoryUtil.isContainerInventory(event.getInventory().getType())
254
                        && fastClick.checkContainerInteraction(player, data, cc)) {
255
                        cancel = true;
256
                        keepCancel = true;
257
                    }
258
                    // Then check for too fast inventory clicking
259
                    if (!cancel && fastClick.check(player, now, event, slot, cursor, clicked, event.isShiftClick(), inventoryAction, data, cc, pData)) {  
260
                        cancel = true;
261
                    }
262
                }
263
            }
264
        }
265
        
266
        data.lastClickTime = now;
267
        data.clickedSlotType = event.getSlotType();
268
        // Cancel the event.
269
        if (cancel || keepCancel) {
270
            event.setCancelled(true);
271
        }
272
    }
273
    
274
    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
275
    public void onEditingABook(final PlayerEditBookEvent event) {
276
        final Player player = event.getPlayer();
277
        if (!gutenberg.isEnabled(player)) {
278
            return;
279
        }
280
        final IPlayerData pData = DataManager.getPlayerData(player);
281
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
282
        final BookMeta newMeta = event.getNewBookMeta();
283
        final int pages = newMeta.getPageCount();
284
        if (gutenberg.check(player, data, pData, pages)) {
285
        	event.setCancelled(true);
286
        }
287
    }
288
289
    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
290
    public void onConsumingFoodOrPotions(final PlayerItemConsumeEvent event){
291
        final Player player = event.getPlayer();
292
        if (player.isDead() && BridgeHealth.getHealth(player) <= 0.0) {
293
            // Eat after death.
294
            event.setCancelled(true);
295
            counters.addPrimaryThread(idCancelDead, 1);
296
            return;
297
        }
298
        final IPlayerData pData = DataManager.getPlayerData(player);
299
        if (!fastConsume.isEnabled(player)) {
300
            return;
301
        }
302
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
303
        final long time = System.currentTimeMillis();
304
        if (fastConsume.check(player, event.getItem(), time, data, pData)) {
305
            event.setCancelled(true);
306
            DataManager.getPlayerData(player).requestUpdateInventory();
307
        }
308
    }
309
    
310
    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
311
    public void onClosingAnyInventory(final InventoryCloseEvent event) {
312
        // NOTE: ignoreCancelled is kept to true here. Cancelled events won't reset data.
313
        // NOTE: Priority level -> same as opening time.
314
        final HumanEntity entity = event.getPlayer();
315
        if (entity instanceof Player) {
316
            final Player player = (Player) entity;
317
            final IPlayerData pData = DataManager.getPlayerData(player);
318
            final InventoryData data = pData.getGenericInstance(InventoryData.class);
319
            data.inventoryOpenTime = 0;
320
            data.containerInteractTime = 0;
321
            if (pData.isDebugActive(CheckType.INVENTORY)) {
322
                debug(player, "InventoryCloseEvent: reset timing data.");
323
            }
324
        }
325
        keepCancel = false;
326
    }
327
328
    @EventHandler(priority = EventPriority.LOWEST)
329
    public final void onPlayerInteract(final PlayerInteractEvent event) {
330
        final Player player = event.getPlayer();
331
        final IPlayerData pData = DataManager.getPlayerData(player);
332
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
333
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
334
        // Set the container opening time.
335
        if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null
336
            // Sneaking and right clicking with a block in hand will cause the player to place the block down, not to open the container.
337
            && !(BridgeMisc.isUsingItem(player) || pData.isShiftKeyPressed() && event.isBlockInHand())) {
338
            if (BlockProperties.isContainer(event.getClickedBlock().getType())) {
339
                data.containerInteractTime = System.currentTimeMillis();
340
                if (pData.isDebugActive(CheckType.INVENTORY)) {
341
                    debug(player, "Interacted with a container: register the interaction time.");
342
                }
343
            }
344
        } 
345
        // Only interested in right-clicks while holding an item.
346
        if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
347
            return;
348
        }
349
        
350
        boolean resetAll = false;
351
        if (event.hasItem()) {
352
            final ItemStack item = event.getItem();
353
            final Material type = item.getType();
354
            // TODO: Get Magic values (800) from the config.
355
            // TODO: Cancelled / deny use item -> reset all?
356
            if (type == Material.BOW) {
357
                final long now = System.currentTimeMillis();
358
                // It was a bow, the player starts to pull the string, remember this time.
359
                data.instantBowInteract = (data.instantBowInteract > 0 && now - data.instantBowInteract < 800) ? Math.min(System.currentTimeMillis(), data.instantBowInteract) : System.currentTimeMillis();
360
            }
361
            else if (InventoryUtil.isConsumable(type)) {
362
                final long now = System.currentTimeMillis();
363
                // It was food, the player starts to eat some food, remember this time and the type of food.
364
                data.fastConsumeFood = type;
365
                data.fastConsumeInteract = (data.fastConsumeInteract > 0 && now - data.fastConsumeInteract < 800) ? Math.min(System.currentTimeMillis(), data.fastConsumeInteract) : System.currentTimeMillis();
366
                data.instantBowInteract = 0; 
367
            } 
368
            else resetAll = true;
369
        }
370
        else resetAll = true;
371
372
        if (resetAll) {
373
            // Nothing that we are interested in, reset data.
374
            data.instantBowInteract = 0;
375
            data.fastConsumeInteract = 0;
376
            data.fastConsumeFood = null;
377
        }
378
    }
379
    
380
    // TODO: Why is this handler inside the INVENTORY listener!?
381
    @EventHandler(priority = EventPriority.LOWEST)
382
    public final void onPlayerInteractEntity(final PlayerInteractEntityEvent event) {
383
        final Player player = event.getPlayer();
384
        if (player.getGameMode() == GameMode.CREATIVE || !DataManager.getPlayerData(player).isCheckActive(CheckType.INVENTORY, player)) {
385
            return;
386
        }
387
        if (player.isDead() && BridgeHealth.getHealth(player) <= 0.0) {
388
            // No zombies.
389
            event.setCancelled(true);
390
            counters.addPrimaryThread(idCancelDead, 1);
391
            return;
392
        }
393
        else if (MovingUtil.hasScheduledPlayerSetBack(player)) {
394
            event.setCancelled(true);
395
            return;
396
        }
397
    }
398
    
399
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
400
    public final void onContainerOpen(final InventoryOpenEvent event) {
401
        // Possibly already prevented by block + entity interaction.
402
        // NOTE: ignoreCancelled is kept true. Denied openings won't register timing data.
403
        final long now = System.currentTimeMillis();
404
        final HumanEntity entity = event.getPlayer();
405
        if (entity instanceof Player) {
406
            final Player player = (Player) entity;
407
            final IPlayerData pData = DataManager.getPlayerData(player);
408
            final InventoryData data = pData.getGenericInstance(InventoryData.class);
409
            if (MovingUtil.hasScheduledPlayerSetBack(player)) {
410
                // Don't allow players to open inventories on set-backs.
411
                event.setCancelled(true);
412
                data.inventoryOpenTime = 0; // Just to be sure
413
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
414
                    debug(player, "InventoryOpenEvent: attempted to open a container during set back processing; reset timing data and prevent opening.");
415
                }
416
            }
417
            else if (data.inventoryOpenTime == 0) {
418
                // Only set the inventory opening time, if a setback is not scheduled.
419
                data.inventoryOpenTime = now;
420
                 if (pData.isDebugActive(CheckType.INVENTORY)) {
421
                    debug(player, "Fired an explicit InventoryOpenEvent; inventory is now open (no assumptions): register time.");
422
                }
423
            }
424
        }
425
    }
426
427
    @EventHandler(priority = EventPriority.MONITOR)
428
    public void onItemHeldChange(final PlayerItemHeldEvent event) {
429
        final Player player = event.getPlayer();
430
        final IPlayerData pData = DataManager.getPlayerData(player);
431
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
432
        if (pData.isDebugActive(checkType) && data.fastConsumeFood != null) {
433
            debug(player, "PlayerItemHeldEvent, reset fastconsume.");
434
        }
435
        data.instantBowInteract = 0;
436
        data.fastConsumeInteract = System.currentTimeMillis();
437
        data.fastConsumeFood = null;
438
        if (event.getPreviousSlot() != event.getNewSlot()) {
439
            if (open.check(player)) {
440
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
441
                    debug(player, "Force-close inventory on changing slots.");
442
                }
443
            }
444
        }   
445
    }
446
    
447
    @EventHandler(priority = EventPriority.MONITOR)
448
    public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) {
449
        // Data is reset regardless of cancellation state (better safe than sorry)
450
        final Player player = event.getPlayer();
451
        final IPlayerData pData = DataManager.getPlayerData(player);
452
        if (open.check(event.getPlayer())) {
453
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
454
                debug(player, "Force-close inventory on changing worlds.");
455
            }
456
        }
457
    }
458
459
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
460
    public void onBreakingBlocks(final BlockBreakEvent event) {
461
        final Player player = event.getPlayer();
462
        final IPlayerData pData = DataManager.getPlayerData(player);
463
        // Can't break blocks with inventory open.
464
        if (open.check(event.getPlayer())) {
465
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
466
                debug(player, "Force-close inventory on breaking blocks (cheat prevention).");
467
            }
468
        }
469
    }
470
471
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
472
    public void onPlacingBlocks(final BlockPlaceEvent event) {
473
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
474
        // Can't place blocks with inventory open.
475
        if (open.check(event.getPlayer())) {
476
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
477
                debug(event.getPlayer(), "Force-close inventory on placing blocks (cheat prevention).");
478
            }
479
        }
480
    }
481
    
482
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
483
    public void onPlayerPortal(final PlayerPortalEvent event) {
484
        // Note: ignore cancelother setting.
485
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
486
        if (open.check(event.getPlayer())) {
487
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
488
                debug(event.getPlayer(), "Force-close inventory on using a portal.");
489
            }
490
        }
491
    }
492
    
493
    @EventHandler(priority = EventPriority.MONITOR)
494
    public void onPlayerRespawn(final PlayerRespawnEvent event) {
495
        // NOTE: Data is reset regardless of cancellation state (better safe than sorry)
496
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
497
        if (open.check(event.getPlayer())) {
498
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
499
                debug(event.getPlayer(), "Force-close inventory on respawning.");
500
            }
501
        }
502
    }
503
    
504
    @EventHandler(priority = EventPriority.MONITOR)
505
    public void onPlayerDeath(final EntityDeathEvent event) {
506
        // NOTE: Data is reset regardless of cancellation state (better safe than sorry)
507
        final LivingEntity entity = event.getEntity();
508
        if (entity instanceof Player) {
509
            final Player player = (Player) entity;
510
            final IPlayerData pData = DataManager.getPlayerData(player);
511
            if (open.check(player)) {
512
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
513
                    debug(player, "Force-close inventory on death.");
514
                }
515
            }
516
        }
517
    }
518
    
519
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
520
    public void onPlayerSleep(final PlayerBedEnterEvent event) {
521
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
522
        if (open.check(event.getPlayer())) {
523
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
524
                debug(event.getPlayer(), "Force-close inventory on sleeping.");
525
            }
526
        }
527
    }
528
529
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
530
    public void onPlayerWake(final PlayerBedLeaveEvent event) {
531
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
532
        if (open.check(event.getPlayer())) {
533
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
534
                debug(event.getPlayer(), "Force-close inventory on waking up.");
535
            }
536
        }
537
    }
538
    
539
    // Check even if cancelled
540
    // (Players swing their arm when dropping items.)
541
    // @EventHandler(priority = EventPriority.MONITOR)
542
    // public void onSwingingArm(final PlayerAnimationEvent event) {
543
    //     final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
544
    //     if (open.check(event.getPlayer())) {
545
    //         if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
546
    //             debug(event.getPlayer(), "Force-close inventory on swinging arm (cheat prevention).");
547
    //         }
548
    //     }
549
    // }
550
551
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
552
    public void onEntityPortal(final EntityPortalEnterEvent event) {
553
        // Check passengers flat for now.
554
        final Entity entity = event.getEntity();
555
        if (entity instanceof Player) {
556
            final IPlayerData pData = DataManager.getPlayerData((Player) entity);
557
            if (open.check((Player) entity)) {
558
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
559
                    debug((Player) entity, "Force-close inventory on using a portal (entity).");
560
                }
561
            }
562
        }
563
        else {
564
            for (final Entity passenger : handleVehicles.getHandle().getEntityPassengers(entity)) {
565
                if (passenger instanceof Player) {
566
                	final IPlayerData pData = DataManager.getPlayerData((Player) entity);
567
                    if (open.check((Player) passenger)) {
568
                        if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
569
                            debug((Player) passenger, "Force-close inventory of passenger on using a portal, passenger: " + passenger.toString());
570
                        }
571
                    }
572
                }
573
            }
574
        }
575
    }
576
    
577
    /** Event priority must be set to priority used for moving checks due using moving data from there */
578
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
579
    public void onPlayerMove(final PlayerMoveEvent event) {
580
        final Location from = event.getFrom();
581
        final Location to = event.getTo();
582
        final boolean PoYdiff = from.getPitch() != to.getPitch() || from.getYaw() != to.getYaw();
583
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
584
        if (MovingUtil.hasScheduledPlayerSetBack(event.getPlayer())) {
585
            // On 1.8 set back technique is different, as we do not cancel the event.
586
            return;
587
        }
588
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
589
        final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
590
        final Inventory inv = BukkitAPIAccessFactory.getBukkitAccess().getTopInventory(event.getPlayer());
591
        boolean moreInvCheck = false;
592
        if (moreInv.isEnabled(event.getPlayer(), pData) 
593
            && moreInv.check(event.getPlayer(), cData, pData, inv.getType(), inv, PoYdiff)) {
594
            for (int i = 1; i <= 4; i++) {
595
                final ItemStack item = inv.getItem(i);
596
                // Ensure air-clicking is not detected... :)
597
                if (item != null && !BlockProperties.isAir(item.getType())) {
598
                    // NOTE: dropItemsNaturally does not fire InvDrop events, so don't use it here. Simply close the inventory,
599
                    event.getPlayer().closeInventory(); // Do not call Open.checkClose() here, as it checks for if the inventory is open again, and we're not interested in that.
600
                    if (pData.isDebugActive(CheckType.INVENTORY_MOREINVENTORY)) {
601
                        debug(event.getPlayer(), "On PlayerMoveEvent: force-close inventory on MoreInv detection.");
602
                    }
603
                    moreInvCheck = true;
604
                    break;
605
                }
606
            }
607
        }
608
        if (moreInvCheck) {
609
            // Already closed inventory; no need to also check for open-on-move.
610
            return;
611
        }
612
        // Determine if the inventory should be closed.
613
        if (cc.openCancelOnMove && !pData.hasBypass(CheckType.INVENTORY_OPEN, event.getPlayer())) {
614
            if (InventoryUtil.hasInventoryOpen(event.getPlayer()) && open.checkOnMove(event.getPlayer(), pData)) {
615
                event.getPlayer().closeInventory(); // Do not call open.check() here. <- Uhm... Why did I write this note?
616
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
617
                    debug(event.getPlayer(), "Player is actively moving: force-close open inventory.");
618
                }
619
            }
620
        }
621
    }
622
    
623
    @EventHandler(priority = EventPriority.MONITOR)
624
    public void onPlayerTeleport(final PlayerTeleportEvent event) {
625
        // NOTE: Data is reset regardless of cancellation state (better safe than sorry)
626
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
627
        if (open.check(event.getPlayer())) {
628
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
629
                debug(event.getPlayer(), "Force-close inventory on teleporting.");
630
            }
631
        }
632
    }
633
634
    @Override
635
    public void playerJoins(Player player) {
636
        // Just to be sure...
637
        final IPlayerData pData = DataManager.getPlayerData(player);
638
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
639
        data.inventoryOpenTime = 0;
640
        if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
641
            debug(player, "Reset inventory timings data on join.");
642
        }
643
    }
644
645
    @Override
646
    public void playerLeaves(Player player) {
647
        final IPlayerData pData = DataManager.getPlayerData(player);
648
        if (open.check(player)) {
649
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
650
                debug(player, "Force-close inventory on leaving the server.");
651
            }
652
        }
653
    }
654
655
    /**
656
     * Debug inventory classes. Contains information about classes, to indicate
657
     * if cross-plugin compatibility issues can be dealt with easily.
658
     * 
659
     * @param player
660
     * @param slot
661
     * @param event
662
     */
663
    private void outputDebugInventoryClick(final Player player, final int slot, final InventoryClickEvent event, 
664
                                           final String action) {
665
        // TODO: Consider only logging where different from expected (CraftXY, more/other viewer than player). 
666
667
        final StringBuilder builder = new StringBuilder(512);
668
        final InventoryData data = DataManager.getPlayerData(player).getGenericInstance(InventoryData.class);
669
        builder.append("Inventory click: slot: " + slot);
670
        builder.append(" , Inventory has been opened for: " + MathUtil.toSeconds(System.currentTimeMillis() - data.inventoryOpenTime) + " secs");
671
        builder.append(" , Time between inventory click and last interaction time: " + MathUtil.toSeconds(data.lastClickTime - data.containerInteractTime) + " secs");
672
673
        // Viewers.
674
        builder.append(" , Viewers: ");
675
        for (final HumanEntity entity : event.getViewers()) {
676
            builder.append(entity.getName());
677
            builder.append("(");
678
            builder.append(entity.getClass().getName());
679
            builder.append(")");
680
        }
681
682
        // Inventory view.
683
        builder.append(" , View: ");
684
        //final InventoryView view = BridgeBukkitAPI.getInventoryView(event);
685
        //builder.append(view.getClass().getName());
686
687
        // Bottom inventory.
688
        addInventory(BukkitAPIAccessFactory.getBukkitAccess().getBottomInventory(event), BukkitAPIAccessFactory.getBukkitAccess().getInventoryTitle(event), " , Bottom: ", builder);
689
690
        // Top inventory.
691
        addInventory(BukkitAPIAccessFactory.getBukkitAccess().getTopInventory(event), BukkitAPIAccessFactory.getBukkitAccess().getInventoryTitle(event), " , Top: ", builder);
692
        
693
        if (action != null) {
694
            builder.append(" , Action: ");
695
            builder.append(action);
696
        }
697
698
        // Event class.
699
        builder.append(" , Event: ");
700
        builder.append(event.getClass().getName());
701
702
        // Log debug.
703
        debug(player, builder.toString());
704
    }
705
706
    private void addInventory(final Inventory inventory, final String name, final String prefix, final StringBuilder builder) {
707
        builder.append(prefix);
708
        if (inventory == null) {
709
            builder.append("(none)");
710
        }
711
        else {
712
            builder.append(name);
713
            builder.append("/");
714
            builder.append(inventory.getClass().getName());
715
        }
716
    }
717
}

How it counteracts this module

The listener maintains the inventory-open ledger the Open check and FastClick both rely on. The first window click with inventoryOpenTime == 0 stamps the open time and assumes the inventory is open from that moment (line 218-223), onInventoryClose resets it, and onContainerOpen only stamps real opens. The Open check then force-closes the window whenever the player breaks blocks, places blocks, uses a portal or respawns while the ledger says a window is open - actions Auto Armor's host client performs constantly in combat. Nekoware's module fabricates the open state through its window-0 clicks, so the Open check's force-close path activates on the first subsequent world interaction: the interaction is cancelled and the inventory resynced, and because the module keeps clicking every tick, the fabricated-open state is continuously renewed. The listener's MONITOR-priority onItemHeldChange is the C09 side of the ledger: it resets fastConsume bookkeeping and stamps fastConsumeInteract on every slot change, which matters for the sibling AutoPotion modules that pair C09 with C08 - AutoArmor never sends C09 in this fork, so it touches only the click side of this listener.

← Back to Analysis Hub