├── .github └── FUNDING.yml ├── .gitignore ├── .idea ├── .gitignore ├── aws.xml ├── compiler.xml ├── discord.xml ├── encodings.xml ├── jarRepositories.xml ├── libraries │ ├── ConsoleColors_V1.xml │ └── HeadsPluginAPI_3_2_0.xml ├── material_theme_project_new.xml ├── misc.xml ├── modules.xml ├── uiDesigner.xml └── vcs.xml ├── LICENSE ├── OPProtector.iml ├── README.md ├── icon.png ├── pom.xml ├── src └── main │ ├── java │ └── org │ │ └── kasun │ │ └── opprotector │ │ ├── AuthObjects │ │ ├── IpTable.java │ │ └── TempAuth.java │ │ ├── Commands │ │ ├── CommandsManager.java │ │ ├── OppCommand.java │ │ └── Pas.java │ │ ├── Configs │ │ ├── ConfigManager.java │ │ ├── CustomConfig.java │ │ ├── MainConfig.java │ │ ├── Operator.java │ │ └── OperatorConfig.java │ │ ├── Discord │ │ ├── DiscordWebhook.java │ │ ├── Notification.java │ │ └── NotificationType.java │ │ ├── Listners │ │ ├── ListnerManager.java │ │ ├── LuckPermUpdate.java │ │ ├── PlayerBlockBreak.java │ │ ├── PlayerBlockPlace.java │ │ ├── PlayerCommand.java │ │ ├── PlayerItemDrop.java │ │ ├── PlayerJoin.java │ │ ├── PlayerLeave.java │ │ ├── PlayerMessage.java │ │ ├── PlayerMove.java │ │ └── ServerCommand.java │ │ ├── MainManager.java │ │ ├── OPProtector.java │ │ ├── Punishments │ │ ├── Ban.java │ │ ├── Lockdown.java │ │ └── PunishmentManager.java │ │ ├── Scanner │ │ ├── LiveScanner.java │ │ ├── OfflineScanResult.java │ │ ├── OfflineScanner.java │ │ └── ScanResults.java │ │ ├── Utils │ │ ├── ColorUtils.java │ │ ├── Colors.java │ │ ├── CommandExecutor.java │ │ ├── Encryption.java │ │ ├── ErrorHandler.java │ │ ├── Log.java │ │ ├── LuckpermsCheck.java │ │ ├── Metrics.java │ │ ├── OfflineScannerResultType.java │ │ └── Prefix.java │ │ ├── VerificationProcess │ │ ├── PasswordFlash.java │ │ ├── PasswordVerification.java │ │ ├── VerificationProcessManager.java │ │ ├── VerificationStatus.java │ │ └── VerifiedAnnouncer.java │ │ └── inventories │ │ └── PasswordGui.java │ └── resources │ ├── config.yml │ ├── iplist.yml │ ├── operators.yml │ └── plugin.yml └── ver.txt /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: ka0un 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: kasun 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Project exclude paths 2 | /target/ -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/aws.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 16 | 17 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/discord.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | 29 | 30 | 34 | 35 | 39 | 40 | 44 | 45 | 49 | 50 | -------------------------------------------------------------------------------- /.idea/libraries/ConsoleColors_V1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/libraries/HeadsPluginAPI_3_2_0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/material_theme_project_new.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 14 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 kasun 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OPProtector.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | SPIGOT 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![1x-fixed](https://github.com/ka0un/OPProtector/assets/88395585/c3b39431-4b34-4155-b1e3-dc76458472cd) 2 | 3 | # OPProtector 4 | > Protect Operator Accounts And Prevent Unautharized Access 5 | 6 | ![GitHub Release](https://img.shields.io/github/v/release/ka0un/OPProtector?color=fa9d01) 7 | ![GitHub commits since latest release](https://img.shields.io/github/commits-since/ka0un/OPProtector/latest?color=fa9d01) 8 | ![bStats Servers](https://img.shields.io/bstats/servers/19908?color=fa9d01) 9 | ![bStats Players](https://img.shields.io/bstats/players/19908?color=fa9d01) 10 | ![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/ka0un/OPProtector/total?color=fa9d01) 11 | ![GitHub Repo stars](https://img.shields.io/github/stars/ka0un/OPProtector?color=fa9d01) 12 | 13 | - **Spigot** : [https://www.spigotmc.org/resources/opprotector.112840/](https://www.spigotmc.org/resources/opprotector.112840/) 14 | - **BuiltByBit** : [https://builtbybit.com/resources/opprotector.32501/](https://builtbybit.com/resources/opprotector.32501/) 15 | - **Trello** : [https://trello.com/b/3Pl7ZSJ5/opprotector](https://trello.com/b/3Pl7ZSJ5/opprotector) 16 | - **Bstats** : [https://bstats.org/plugin/bukkit/OPProtector/19908](https://bstats.org/plugin/bukkit/OPProtector/19908) 17 | 18 | ![Group (48)](https://github.com/ka0un/OPProtector/assets/88395585/097b9434-1cca-4377-8803-58ee1b815c6e) 19 | 20 | > After signing in to GitHub, locate the 'Star' button on this page. Clicking on this button will ensure that you receive notifications regarding updates and the release of opp+. As a token of appreciation, upon release, you will be provided with a 100% discount coupon for builtByBit. 21 | 22 | ![1x](https://bstats.org/signatures/bukkit/OPProtector.svg) 23 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ka0un/OPProtector/a0c0b20c791cfbb0edd51ae63f980ded81464a8e/icon.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.kasun 8 | OPProtector 9 | 1.0.5 10 | jar 11 | 12 | OPProtector 13 | 14 | 15 | 1.8 16 | UTF-8 17 | 18 | 19 | 20 | 21 | 22 | org.apache.maven.plugins 23 | maven-compiler-plugin 24 | 3.8.1 25 | 26 | 9 27 | 9 28 | 29 | 30 | 31 | org.apache.maven.plugins 32 | maven-shade-plugin 33 | 3.2.4 34 | 35 | 36 | package 37 | 38 | shade 39 | 40 | 41 | false 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | src/main/resources 50 | true 51 | 52 | 53 | 54 | 55 | 56 | 57 | spigotmc-repo 58 | https://hub.spigotmc.org/nexus/content/repositories/snapshots/ 59 | 60 | 61 | sonatype 62 | https://oss.sonatype.org/content/groups/public/ 63 | 64 | 65 | 66 | 67 | 68 | org.spigotmc 69 | spigot-api 70 | 1.13-R0.1-SNAPSHOT 71 | provided 72 | 73 | 74 | com.github.stefvanschie.inventoryframework 75 | IF 76 | 0.10.19 77 | 78 | 79 | org.yaml 80 | snakeyaml 81 | 2.2 82 | 83 | 84 | net.luckperms 85 | api 86 | 5.4 87 | provided 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/AuthObjects/IpTable.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.AuthObjects; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.kasun.opprotector.Configs.CustomConfig; 5 | import org.kasun.opprotector.OPProtector; 6 | 7 | import java.util.HashMap; 8 | 9 | public class IpTable { 10 | HashMap ipTable; 11 | CustomConfig customConfig; 12 | OPProtector plugin = OPProtector.getInstance(); 13 | public IpTable() { 14 | customConfig = new CustomConfig(); 15 | ipTable = customConfig.getIpList(); 16 | } 17 | 18 | public boolean IsContains(Player player){ 19 | String playerName = player.getName(); 20 | if (ipTable.containsKey(playerName)){ 21 | return true; 22 | } 23 | return false; 24 | } 25 | 26 | public void addIp(Player player) { 27 | String playerName = player.getName(); 28 | String playerIp = player.getAddress().getAddress().getHostAddress(); 29 | ipTable.put(playerName, playerIp); 30 | saveIp(); 31 | } 32 | 33 | public boolean isIp(Player player) { 34 | String playerName = player.getName(); 35 | String playerIp = player.getAddress().getAddress().getHostAddress(); 36 | if (ipTable.containsKey(playerName)) { 37 | if (ipTable.get(playerName).equals(playerIp)) { 38 | return true; 39 | } 40 | } 41 | return false; 42 | } 43 | 44 | public void removeIp(Player player) { 45 | String playerName = player.getName(); 46 | ipTable.remove(playerName); 47 | saveIp(); 48 | } 49 | 50 | public String getIp(Player player) { 51 | String playerName = player.getName(); 52 | return ipTable.get(playerName).toString(); 53 | 54 | } 55 | 56 | private void saveIp() { 57 | customConfig.saveIpList(); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/AuthObjects/TempAuth.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.AuthObjects; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.kasun.opprotector.OPProtector; 5 | 6 | import java.sql.Timestamp; 7 | import java.util.HashMap; 8 | 9 | public class TempAuth { 10 | HashMap authorizedPlayers; 11 | private OPProtector plugin = OPProtector.getInstance(); 12 | public TempAuth() { 13 | authorizedPlayers = new HashMap<>(); 14 | } 15 | 16 | public void addAuthorizedPlayer(Player player){ 17 | authorizedPlayers.put(player.getName(), new Timestamp(System.currentTimeMillis())); 18 | } 19 | 20 | public boolean isAuthorizedPlayer(Player player){ 21 | int time = (int) plugin.getMainManager().getConfigManager().getMainConfig().session_hours; 22 | if(authorizedPlayers.containsKey(player.getName())){ 23 | if (authorizedPlayers.get(player.getName()).getTime() + (3600000 * time) > System.currentTimeMillis()) { 24 | return true; 25 | } 26 | } 27 | return false; 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Commands/CommandsManager.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Commands; 2 | 3 | import org.kasun.opprotector.OPProtector; 4 | 5 | public class CommandsManager { 6 | public CommandsManager() { 7 | OPProtector plugin = OPProtector.getInstance(); 8 | plugin.getCommand("pas").setExecutor(new Pas()); 9 | plugin.getCommand("opp").setExecutor(new OppCommand()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Commands/OppCommand.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Commands; 2 | 3 | import org.bukkit.ChatColor; 4 | import org.bukkit.OfflinePlayer; 5 | import org.bukkit.command.*; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Scanner.OfflineScanResult; 8 | import org.kasun.opprotector.Scanner.OfflineScanner; 9 | import org.kasun.opprotector.Utils.Prefix; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class OppCommand implements TabExecutor { 15 | 16 | private final OPProtector plugin = OPProtector.getInstance(); 17 | private CommandsManager commandsManager; 18 | 19 | @Override 20 | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { 21 | if (args.length == 0) { 22 | if(!sender.hasPermission("opp-admin")) { 23 | sender.sendMessage(Prefix.ERROR + "No Permission ! [opp-admin]"); 24 | return true; 25 | } 26 | sendhelp(sender); 27 | return true; 28 | } 29 | 30 | //Scan Command 31 | if (args[0].equalsIgnoreCase("scan")) { 32 | if(!sender.hasPermission("opp-admin")) { 33 | sender.sendMessage(Prefix.ERROR + "No Permission ! [opp-admin]"); 34 | return true; 35 | } 36 | 37 | OfflineScanner offlineScanner = new OfflineScanner(sender); 38 | 39 | } 40 | 41 | //Help Command 42 | if (args[0].equalsIgnoreCase("help")) { 43 | if(!sender.hasPermission("opp-admin")) { 44 | sender.sendMessage(Prefix.ERROR + "No Permission ! [opp-admin]"); 45 | return true; 46 | } 47 | sendhelp(sender); 48 | } 49 | 50 | //Reload Command 51 | if (args[0].equalsIgnoreCase("reload")) { 52 | if(!sender.hasPermission("opp-admin")) { 53 | sender.sendMessage(Prefix.ERROR + "No Permission ! [opp-admin]"); 54 | return true; 55 | } 56 | plugin.getMainManager().reload(); 57 | sender.sendMessage(Prefix.SUCCESS + "OPProtector Reloaded"); 58 | } 59 | 60 | if (args[0].equalsIgnoreCase("banall")) { 61 | if(!sender.hasPermission("opp-admin")) { 62 | sender.sendMessage(Prefix.ERROR + "No Permission ! [opp-admin]"); 63 | return true; 64 | } 65 | List resultList = plugin.getMainManager().getOfflinePlayerScanResultList(); 66 | if (resultList.size() == 0){ 67 | sender.sendMessage(Prefix.SUCCESS + "No Players Detected"); 68 | return true; 69 | }else{ 70 | for (OfflineScanResult result : resultList) { 71 | OfflinePlayer player = result.getPlayer(); 72 | plugin.getServer().getBanList(org.bukkit.BanList.Type.NAME).addBan(player.getName(), "OPProtector Detected Unauthorized OP", null, "OPProtector"); 73 | } 74 | sender.sendMessage(Prefix.SUCCESS + "Banned " + resultList.size() + " detected players"); 75 | plugin.getMainManager().getOfflinePlayerScanResultList().clear(); 76 | } 77 | } 78 | return true; 79 | } 80 | 81 | private void sendhelp(CommandSender sender) { 82 | //Border 83 | sender.sendMessage(ChatColor.YELLOW + "============================================"); 84 | 85 | sender.sendMessage(ChatColor.YELLOW + ""); 86 | 87 | //Info 88 | sender.sendMessage(ChatColor.GOLD + "OPProtector v" + plugin.getDescription().getVersion()); 89 | sender.sendMessage(ChatColor.YELLOW + "Author: " + ChatColor.WHITE + plugin.getDescription().getAuthors()); 90 | sender.sendMessage(ChatColor.YELLOW + "Doc: " + ChatColor.WHITE + plugin.getDescription().getWebsite()); 91 | 92 | //discord 93 | sender.sendMessage(ChatColor.YELLOW + "Discord: "+ ChatColor.WHITE +" https://dsc.gg/sundevs"); 94 | 95 | sender.sendMessage(ChatColor.YELLOW + ""); 96 | 97 | //Commands 98 | sender.sendMessage(ChatColor.GOLD + "Commands:"); 99 | sender.sendMessage(ChatColor.YELLOW + "/opp help "+ ChatColor.WHITE +"- View This info"); 100 | sender.sendMessage(ChatColor.YELLOW + "/opp scan "+ ChatColor.WHITE +"- Scan all Offline players for Unauthorized OPs"); 101 | sender.sendMessage(ChatColor.YELLOW + "/opp reload "+ ChatColor.WHITE +"- Reload the plugin"); 102 | 103 | sender.sendMessage(ChatColor.YELLOW + ""); 104 | //permissions 105 | sender.sendMessage(ChatColor.GOLD + "Permissions:"); 106 | sender.sendMessage(ChatColor.YELLOW + "opp-admin "+ ChatColor.WHITE +"- Access to all commands"); 107 | 108 | sender.sendMessage(ChatColor.YELLOW + ""); 109 | 110 | //copyright text 111 | sender.sendMessage(ChatColor.YELLOW + "OPProtector is licensed under the MIT License"); 112 | sender.sendMessage(ChatColor.YELLOW + "OPProtector@Sundevs 2023"); 113 | 114 | sender.sendMessage(ChatColor.YELLOW + ""); 115 | 116 | //Border 117 | sender.sendMessage(ChatColor.YELLOW + "============================================"); 118 | } 119 | 120 | @Override 121 | public List onTabComplete(CommandSender sender, Command cmd, String label, String[] args) { 122 | if (args.length == 1) { 123 | List arguments = new ArrayList<>(); 124 | arguments.add("help"); 125 | arguments.add("scan"); 126 | arguments.add("reload"); 127 | return arguments; 128 | } 129 | return null; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Commands/Pas.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Commands; 2 | 3 | import org.bukkit.command.Command; 4 | import org.bukkit.command.CommandExecutor; 5 | import org.bukkit.command.CommandSender; 6 | import org.bukkit.entity.Player; 7 | import org.kasun.opprotector.OPProtector; 8 | import org.kasun.opprotector.Utils.Prefix; 9 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 10 | 11 | public class Pas implements CommandExecutor { 12 | OPProtector plugin = OPProtector.getInstance(); 13 | @Override 14 | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { 15 | 16 | if (sender instanceof Player){ 17 | Player player = (Player) sender; 18 | if (args.length == 1) { 19 | if (plugin.getMainManager().getConfigManager().getOperatorConfig().isContains(player.getName())) { 20 | if (plugin.getMainManager().getAuthorizedPlayers().isAuthorizedPlayer(player)) { 21 | player.sendMessage(Prefix.SUCCESS + "You are already authorized."); 22 | return true; 23 | }else { 24 | String password = args[0]; 25 | String correctPassword = plugin.getMainManager().getConfigManager().getOperatorConfig().getOperator(player.getName()).getPassword(); 26 | if (password.equals(correctPassword)) { 27 | VerificationProcessManager verificationProcessManager = plugin.getMainManager().getVerificationProcessManager(); 28 | verificationProcessManager.setVerified(player); 29 | return true; 30 | } else { 31 | player.sendMessage(Prefix.ERROR + "Incorrect password."); 32 | return true; 33 | } 34 | } 35 | }else{ 36 | player.sendMessage(Prefix.INFO + "You dont have permission to use this command."); 37 | return true; 38 | } 39 | } 40 | } 41 | return true; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Configs/ConfigManager.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Configs; 2 | 3 | public class ConfigManager { 4 | 5 | MainConfig mainConfig; 6 | CustomConfig customConfig; 7 | OperatorConfig operatorConfig; 8 | public ConfigManager() { 9 | mainConfig = new MainConfig(); 10 | customConfig = new CustomConfig(); 11 | operatorConfig = new OperatorConfig(); 12 | } 13 | 14 | public MainConfig getMainConfig() { 15 | return mainConfig; 16 | } 17 | 18 | public CustomConfig getCustomConfig() { 19 | return customConfig; 20 | } 21 | 22 | public OperatorConfig getOperatorConfig() { 23 | return operatorConfig; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Configs/CustomConfig.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Configs; 2 | import org.bukkit.configuration.file.YamlConfiguration; 3 | import org.kasun.opprotector.OPProtector; 4 | import java.io.*; 5 | import java.util.HashMap; 6 | 7 | public class CustomConfig { 8 | OPProtector plugin = OPProtector.getInstance(); 9 | //private HashMap Messages; 10 | private HashMap IpList; 11 | private File fileIp; 12 | //private File fileMsg; 13 | private YamlConfiguration yamlConfigurationIp; 14 | //private YamlConfiguration yamlConfigurationMsg; 15 | 16 | 17 | public CustomConfig() { 18 | if (plugin.isFirstTime()) { 19 | createconfigfiles(); 20 | } 21 | loadConfig(); 22 | } 23 | 24 | private void loadConfig() { 25 | //Messages = new HashMap<>(); 26 | IpList = new HashMap<>(); 27 | fileIp = new File(plugin.getDataFolder() + "/iplist.yml"); 28 | //fileMsg = new File(plugin.getDataFolder() + "/messages.yml"); 29 | yamlConfigurationIp = YamlConfiguration.loadConfiguration(fileIp); 30 | //yamlConfigurationMsg = YamlConfiguration.loadConfiguration(fileMsg); 31 | yamlConfigurationIp.getKeys(false).forEach(key -> { 32 | IpList.put(key, yamlConfigurationIp.get(key)); 33 | }); 34 | //yamlConfigurationMsg.getKeys(false).forEach(key -> { 35 | // Messages.put(key, yamlConfigurationMsg.get(key)); 36 | //}); 37 | } 38 | 39 | 40 | private void createconfigfiles() { 41 | plugin.saveResource("iplist.yml", false); 42 | //plugin.saveResource("messages.yml", false); 43 | plugin.saveResource("operators.yml", false); 44 | } 45 | 46 | public void saveIpList() { 47 | IpList.forEach((key, value) -> { 48 | yamlConfigurationIp.set(key, value); 49 | }); 50 | try { 51 | yamlConfigurationIp.save(fileIp); 52 | } catch (Exception ignored) {} 53 | } 54 | 55 | /*public void saveMessages() { 56 | Messages.forEach((key, value) -> { 57 | yamlConfigurationMsg.set(key, value); 58 | }); 59 | try { 60 | yamlConfigurationMsg.save(fileMsg); 61 | } catch (Exception ignored) {} 62 | } 63 | 64 | */ 65 | 66 | public HashMap getIpList() { 67 | return IpList; 68 | } 69 | 70 | /* 71 | public HashMap getMessages() { 72 | return Messages; 73 | } 74 | 75 | */ 76 | 77 | } -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Configs/MainConfig.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Configs; 2 | 3 | import org.bukkit.configuration.ConfigurationSection; 4 | import org.bukkit.configuration.file.FileConfiguration; 5 | import org.bukkit.configuration.file.YamlConfiguration; 6 | import org.kasun.opprotector.OPProtector; 7 | 8 | import java.io.File; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public class MainConfig { 13 | private final OPProtector plugin = OPProtector.getInstance(); 14 | private File configFile; 15 | private FileConfiguration config; 16 | 17 | public String 18 | prefix, 19 | pas_command, 20 | discord_webhook; 21 | 22 | 23 | public int 24 | session_hours, 25 | interval_secounds; 26 | 27 | public boolean 28 | use_gui, 29 | block_player_move, 30 | block_break_block, 31 | block_place_block, 32 | block_item_drop, 33 | block_item_pickup, 34 | block_damage, 35 | allow_flight, 36 | scan_on_player_op_command, 37 | scan_on_console_op_command, 38 | scan_from_live_scanner, 39 | scan_for_blacklisted_permissions, 40 | scan_for_gamemode_creative, 41 | encrypt_passwords, 42 | scan_on_join, 43 | notify_op_join, 44 | notify_op_leave, 45 | notify_auth_success, 46 | notify_auth_failed, 47 | notify_unauth_access, 48 | password_enabled; 49 | 50 | 51 | 52 | 53 | 54 | public List 55 | commands_whitelist, 56 | not_in_operators_list, 57 | have_blacklisted_perms, 58 | admin_ip_changed, 59 | failed_password_timeout, 60 | blacklisted_permissions; 61 | 62 | 63 | 64 | 65 | public MainConfig() { 66 | plugin.getConfig().options().copyDefaults(); 67 | plugin.saveDefaultConfig(); 68 | configFile = new File(plugin.getDataFolder(), "config.yml"); 69 | config = YamlConfiguration.loadConfiguration(configFile); 70 | 71 | loadPasswordSettings(); 72 | loadLockdownSettings(); 73 | loadScannerSettings(); 74 | loadCommandsSettings(); 75 | loadDiscordNotifications(); 76 | } 77 | 78 | 79 | private void loadPasswordSettings(){ 80 | ConfigurationSection password = config.getConfigurationSection("password-settings"); 81 | pas_command = password.getString("pas-command"); 82 | session_hours = password.getInt("session-hours"); 83 | interval_secounds = password.getInt("interval-secounds"); 84 | use_gui = password.getBoolean("use-gui"); 85 | encrypt_passwords = password.getBoolean("encrypt-passwords"); 86 | password_enabled = password.getBoolean("enabled"); 87 | } 88 | 89 | private void loadLockdownSettings(){ 90 | ConfigurationSection lockdown = config.getConfigurationSection("lockdown-settings"); 91 | block_player_move = lockdown.getBoolean("block-player-move"); 92 | block_break_block = lockdown.getBoolean("block-break-block"); 93 | block_place_block = lockdown.getBoolean("block-place-block"); 94 | block_item_drop = lockdown.getBoolean("block-item-drop"); 95 | block_item_pickup = lockdown.getBoolean("block-item-pickup"); 96 | block_damage = lockdown.getBoolean("block-damage"); 97 | allow_flight = lockdown.getBoolean("allow-flight"); 98 | 99 | commands_whitelist = new ArrayList<>(lockdown.getStringList("commands-whitelist")); 100 | } 101 | 102 | private void loadScannerSettings(){ 103 | ConfigurationSection scanner = config.getConfigurationSection("scanner-settings"); 104 | scan_on_player_op_command = scanner.getBoolean("scan-on-player-op-command"); 105 | scan_on_console_op_command = scanner.getBoolean("scan-on-console-op-command"); 106 | scan_from_live_scanner = scanner.getBoolean("scan-from-live-scanner"); 107 | scan_for_blacklisted_permissions = scanner.getBoolean("scan-for-blacklisted-permissions"); 108 | scan_for_gamemode_creative = scanner.getBoolean("scan-for-gamemode-creative"); 109 | scan_on_join = scanner.getBoolean("scan-on-join"); 110 | blacklisted_permissions = new ArrayList<>(scanner.getStringList("blacklisted-permissions")); 111 | } 112 | 113 | private void loadCommandsSettings(){ 114 | ConfigurationSection commands = config.getConfigurationSection("commands-settings"); 115 | not_in_operators_list = new ArrayList<>(commands.getStringList("not-in-operators-list")); 116 | have_blacklisted_perms = new ArrayList<>(commands.getStringList("have-blacklisted-perms")); 117 | admin_ip_changed = new ArrayList<>(commands.getStringList("admin-ip-changed")); 118 | failed_password_timeout = new ArrayList<>(commands.getStringList("failed-password-timeout")); 119 | 120 | } 121 | 122 | private void loadDiscordNotifications(){ 123 | ConfigurationSection discord = config.getConfigurationSection("discord-notifications"); 124 | notify_op_join = discord.getBoolean("notify-op-join"); 125 | notify_op_leave = discord.getBoolean("notify-op-leave"); 126 | notify_auth_success = discord.getBoolean("notify-auth-success"); 127 | notify_auth_failed = discord.getBoolean("notify-auth-failed"); 128 | notify_unauth_access = discord.getBoolean("notify-unauth-access"); 129 | discord_webhook = discord.getString("discord-webhook"); 130 | 131 | } 132 | 133 | 134 | 135 | 136 | 137 | } 138 | 139 | 140 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Configs/Operator.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Configs; 2 | 3 | import java.util.List; 4 | 5 | public class Operator { 6 | private String name; 7 | private String password; 8 | private List commandBlacklist; 9 | 10 | public Operator() { 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public String getPassword() { 22 | return password; 23 | } 24 | 25 | public void setPassword(String password) { 26 | this.password = password; 27 | } 28 | 29 | 30 | public List getCommandBlacklist() { 31 | return commandBlacklist; 32 | } 33 | 34 | public void setCommandBlacklist(List commandBlacklist) { 35 | this.commandBlacklist = commandBlacklist; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Configs/OperatorConfig.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Configs; 2 | 3 | 4 | import org.kasun.opprotector.OPProtector; 5 | import org.kasun.opprotector.Utils.Encryption; 6 | import org.yaml.snakeyaml.Yaml; 7 | 8 | import java.io.*; 9 | import java.util.*; 10 | 11 | public class OperatorConfig { 12 | 13 | private OPProtector plugin = OPProtector.getInstance(); 14 | 15 | private final String FILE_PATH = plugin.getDataFolder() + "/operators.yml"; 16 | 17 | private Map operatorDataMap; 18 | String EncryptedPrefix = "Encrypted_"; 19 | String key = "1234567890123456"; 20 | 21 | 22 | 23 | public OperatorConfig() { 24 | operatorDataMap = new HashMap<>(); 25 | loadOperators(); 26 | } 27 | 28 | public void loadOperators() { 29 | try (InputStream inputStream = new FileInputStream(FILE_PATH)) { 30 | Yaml yaml = new Yaml(); 31 | Map> data = yaml.load(inputStream); 32 | 33 | for (Map.Entry> entry : data.entrySet()) { 34 | String operatorName = entry.getKey(); 35 | Map operatorData = entry.getValue(); 36 | 37 | Operator operator = new Operator(); 38 | operator.setName(operatorName); 39 | if (operatorData.get("password").toString().startsWith(EncryptedPrefix)) { 40 | String encryptedPassword = operatorData.get("password").toString().substring(EncryptedPrefix.length()); 41 | try{ 42 | operator.setPassword(Encryption.decrypt(encryptedPassword, key)); 43 | }catch (Exception ignored){} 44 | } else { 45 | operator.setPassword(operatorData.get("password").toString()); 46 | 47 | } 48 | operator.setCommandBlacklist((List) operatorData.get("commandBlacklist")); 49 | 50 | operatorDataMap.put(operatorName, operator); 51 | } 52 | saveOperators(); 53 | } catch (IOException e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | 58 | 59 | public void saveOperators() { 60 | try (OutputStream outputStream = new FileOutputStream(FILE_PATH)) { 61 | Yaml yaml = new Yaml(); 62 | Map> data = new HashMap<>(); 63 | MainConfig mainConfig = new MainConfig(); 64 | 65 | for (Map.Entry entry : operatorDataMap.entrySet()) { 66 | String operatorName = entry.getKey(); 67 | Operator operator = entry.getValue(); 68 | 69 | Map operatorData = new HashMap<>(); 70 | if (mainConfig.encrypt_passwords){ 71 | try{ 72 | operatorData.put("password", EncryptedPrefix + Encryption.encrypt(operator.getPassword(), key)); 73 | }catch (Exception ignored){} 74 | }else { 75 | operatorData.put("password", operator.getPassword()); 76 | } 77 | operatorData.put("commandBlacklist", operator.getCommandBlacklist()); 78 | 79 | data.put(operatorName, operatorData); 80 | } 81 | 82 | yaml.dump(data, new OutputStreamWriter(outputStream)); 83 | } catch (IOException e) { 84 | e.printStackTrace(); 85 | } 86 | } 87 | 88 | 89 | public Operator getOperator(String operatorName) { 90 | return operatorDataMap.get(operatorName); 91 | } 92 | 93 | public Map getOperatorDataMap() { 94 | return operatorDataMap; 95 | } 96 | 97 | public boolean isContains(String operatorName) { 98 | if (operatorDataMap.containsKey(operatorName)) { 99 | return true; 100 | }else{ 101 | return false; 102 | } 103 | } 104 | 105 | 106 | } 107 | 108 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Discord/DiscordWebhook.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Discord; 2 | 3 | import javax.net.ssl.HttpsURLConnection; 4 | import java.awt.Color; 5 | import java.io.IOException; 6 | import java.io.OutputStream; 7 | import java.lang.reflect.Array; 8 | import java.net.URL; 9 | import java.util.*; 10 | 11 | /** 12 | * Class used to execute Discord Webhooks with low effort 13 | */ 14 | public class DiscordWebhook { 15 | 16 | private final String url; 17 | private String content; 18 | private String username; 19 | private String avatarUrl; 20 | private boolean tts; 21 | private UUID uuid; 22 | private final List embeds = new ArrayList<>(); 23 | 24 | /** 25 | * Constructs a new DiscordWebhook instance 26 | * 27 | * @param url The webhook URL obtained in Discord 28 | */ 29 | public DiscordWebhook(String url) { 30 | this.url = url; 31 | } 32 | 33 | public void setContent(String content) { 34 | this.content = content; 35 | } 36 | 37 | public void setUsername(String username) { 38 | this.username = username; 39 | } 40 | 41 | public void setAvatarUrl(String avatarUrl) { 42 | this.avatarUrl = avatarUrl; 43 | } 44 | 45 | public void setTts(boolean tts) { 46 | this.tts = tts; 47 | } 48 | 49 | public void addEmbed(EmbedObject embed) { 50 | this.embeds.add(embed); 51 | } 52 | 53 | public void execute() throws IOException{ 54 | if (this.content == null && this.embeds.isEmpty() ) { 55 | throw new IllegalArgumentException("Set content or add at least one EmbedObject"); 56 | } 57 | 58 | 59 | 60 | JSONObject json = new JSONObject(); 61 | 62 | json.put("content", this.content); 63 | json.put("username", this.username); 64 | json.put("avatar_url", this.avatarUrl); 65 | json.put("tts", this.tts); 66 | 67 | if (!this.embeds.isEmpty()) { 68 | List embedObjects = new ArrayList<>(); 69 | 70 | for (EmbedObject embed : this.embeds) { 71 | JSONObject jsonEmbed = new JSONObject(); 72 | 73 | jsonEmbed.put("title", embed.getTitle()); 74 | jsonEmbed.put("description", embed.getDescription()); 75 | jsonEmbed.put("url", embed.getUrl()); 76 | 77 | if (embed.getColor() != null) { 78 | Color color = embed.getColor(); 79 | int rgb = color.getRed(); 80 | rgb = (rgb << 8) + color.getGreen(); 81 | rgb = (rgb << 8) + color.getBlue(); 82 | 83 | jsonEmbed.put("color", rgb); 84 | } 85 | 86 | EmbedObject.Footer footer = embed.getFooter(); 87 | EmbedObject.Image image = embed.getImage(); 88 | EmbedObject.Thumbnail thumbnail = embed.getThumbnail(); 89 | EmbedObject.Author author = embed.getAuthor(); 90 | List fields = embed.getFields(); 91 | 92 | if (footer != null) { 93 | JSONObject jsonFooter = new JSONObject(); 94 | 95 | jsonFooter.put("text", footer.getText()); 96 | jsonEmbed.put("footer", jsonFooter); 97 | } 98 | 99 | if (image != null) { 100 | JSONObject jsonImage = new JSONObject(); 101 | 102 | jsonImage.put("url", image.getUrl()); 103 | jsonEmbed.put("image", jsonImage); 104 | } 105 | 106 | if (thumbnail != null) { 107 | JSONObject jsonThumbnail = new JSONObject(); 108 | 109 | jsonThumbnail.put("url", thumbnail.getUrl()); 110 | jsonEmbed.put("thumbnail", jsonThumbnail); 111 | } 112 | 113 | if (author != null) { 114 | JSONObject jsonAuthor = new JSONObject(); 115 | 116 | jsonAuthor.put("name", author.getName()); 117 | jsonAuthor.put("url", author.getUrl()); 118 | jsonAuthor.put("icon_url", author.getIconUrl()); 119 | jsonEmbed.put("author", jsonAuthor); 120 | } 121 | 122 | List jsonFields = new ArrayList<>(); 123 | for (EmbedObject.Field field : fields) { 124 | JSONObject jsonField = new JSONObject(); 125 | 126 | jsonField.put("name", field.getName()); 127 | jsonField.put("value", field.getValue()); 128 | jsonField.put("inline", field.isInline()); 129 | 130 | jsonFields.add(jsonField); 131 | } 132 | 133 | jsonEmbed.put("fields", jsonFields.toArray()); 134 | embedObjects.add(jsonEmbed); 135 | } 136 | 137 | json.put("embeds", embedObjects.toArray()); 138 | } 139 | 140 | URL url = new URL(this.url); 141 | HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 142 | connection.addRequestProperty("Content-Type", "application/json"); 143 | connection.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_"); 144 | connection.setDoOutput(true); 145 | connection.setRequestMethod("POST"); 146 | 147 | OutputStream stream = connection.getOutputStream(); 148 | stream.write(json.toString().getBytes()); 149 | stream.flush(); 150 | stream.close(); 151 | 152 | connection.getInputStream().close(); //I'm not sure why but it doesn't work without getting the InputStream 153 | connection.disconnect(); 154 | } 155 | 156 | public static class EmbedObject { 157 | private String title; 158 | private String description; 159 | private String url; 160 | private Color color; 161 | 162 | private Footer footer; 163 | private Thumbnail thumbnail; 164 | private Image image; 165 | private Author author; 166 | private List fields = new ArrayList<>(); 167 | 168 | public String getTitle() { 169 | return title; 170 | } 171 | 172 | public String getDescription() { 173 | return description; 174 | } 175 | 176 | public String getUrl() { 177 | return url; 178 | } 179 | 180 | public Color getColor() { 181 | return color; 182 | } 183 | 184 | public Footer getFooter() { 185 | return footer; 186 | } 187 | 188 | public Thumbnail getThumbnail() { 189 | return thumbnail; 190 | } 191 | 192 | public Image getImage() { 193 | return image; 194 | } 195 | 196 | public Author getAuthor() { 197 | return author; 198 | } 199 | 200 | public List getFields() { 201 | return fields; 202 | } 203 | 204 | public EmbedObject setTitle(String title) { 205 | this.title = title; 206 | return this; 207 | } 208 | 209 | public EmbedObject setDescription(String description) { 210 | this.description = description; 211 | return this; 212 | } 213 | 214 | public EmbedObject setUrl(String url) { 215 | this.url = url; 216 | return this; 217 | } 218 | 219 | public EmbedObject setColor(Color color) { 220 | this.color = color; 221 | return this; 222 | } 223 | 224 | public EmbedObject setFooter(String text) { 225 | this.footer = new Footer(text); 226 | return this; 227 | } 228 | 229 | public EmbedObject setThumbnail(String url) { 230 | this.thumbnail = new Thumbnail(url); 231 | return this; 232 | } 233 | 234 | public EmbedObject setImage(String url) { 235 | this.image = new Image(url); 236 | return this; 237 | } 238 | 239 | public EmbedObject setAuthor(String name, String url, String icon) { 240 | this.author = new Author(name, url, icon); 241 | return this; 242 | } 243 | 244 | public EmbedObject addField(String name, String value, boolean inline) { 245 | this.fields.add(new Field(name, value, inline)); 246 | return this; 247 | } 248 | 249 | private class Footer { 250 | private String text; 251 | 252 | private Footer(String text) { 253 | this.text = text; 254 | } 255 | 256 | private String getText() { 257 | return text; 258 | } 259 | 260 | } 261 | 262 | private class Thumbnail { 263 | private String url; 264 | 265 | private Thumbnail(String url) { 266 | this.url = url; 267 | } 268 | 269 | private String getUrl() { 270 | return url; 271 | } 272 | } 273 | 274 | private class Image { 275 | private String url; 276 | 277 | private Image(String url) { 278 | this.url = url; 279 | } 280 | 281 | private String getUrl() { 282 | return url; 283 | } 284 | } 285 | 286 | private class Author { 287 | private String name; 288 | private String url; 289 | private String iconUrl; 290 | 291 | private Author(String name, String url, String iconUrl) { 292 | this.name = name; 293 | this.url = url; 294 | this.iconUrl = iconUrl; 295 | } 296 | 297 | private String getName() { 298 | return name; 299 | } 300 | 301 | private String getUrl() { 302 | return url; 303 | } 304 | 305 | private String getIconUrl() { 306 | return iconUrl; 307 | } 308 | } 309 | 310 | private class Field { 311 | private String name; 312 | private String value; 313 | private boolean inline; 314 | 315 | private Field(String name, String value, boolean inline) { 316 | this.name = name; 317 | this.value = value; 318 | this.inline = inline; 319 | } 320 | 321 | private String getName() { 322 | return name; 323 | } 324 | 325 | private String getValue() { 326 | return value; 327 | } 328 | 329 | private boolean isInline() { 330 | return inline; 331 | } 332 | } 333 | } 334 | 335 | private class JSONObject { 336 | 337 | private final HashMap map = new HashMap<>(); 338 | 339 | void put(String key, Object value) { 340 | if (value != null) { 341 | map.put(key, value); 342 | } 343 | } 344 | 345 | @Override 346 | public String toString() { 347 | StringBuilder builder = new StringBuilder(); 348 | Set> entrySet = map.entrySet(); 349 | builder.append("{"); 350 | 351 | int i = 0; 352 | for (Map.Entry entry : entrySet) { 353 | Object val = entry.getValue(); 354 | builder.append(quote(entry.getKey())).append(":"); 355 | 356 | if (val instanceof String) { 357 | builder.append(quote(String.valueOf(val))); 358 | } else if (val instanceof Integer) { 359 | builder.append(Integer.valueOf(String.valueOf(val))); 360 | } else if (val instanceof Boolean) { 361 | builder.append(val); 362 | } else if (val instanceof JSONObject) { 363 | builder.append(val.toString()); 364 | } else if (val.getClass().isArray()) { 365 | builder.append("["); 366 | int len = Array.getLength(val); 367 | for (int j = 0; j < len; j++) { 368 | builder.append(Array.get(val, j).toString()).append(j != len - 1 ? "," : ""); 369 | } 370 | builder.append("]"); 371 | } 372 | 373 | builder.append(++i == entrySet.size() ? "}" : ","); 374 | } 375 | 376 | return builder.toString(); 377 | } 378 | 379 | private String quote(String string) { 380 | return "\"" + string + "\""; 381 | } 382 | } 383 | 384 | } 385 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Discord/Notification.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Discord; 2 | 3 | import org.kasun.opprotector.OPProtector; 4 | 5 | import java.awt.*; 6 | import java.sql.Timestamp; 7 | 8 | public class Notification { 9 | private String username; 10 | private String avatar_url; 11 | private String colour; 12 | private String title; 13 | private String description; 14 | private OPProtector plugin; 15 | 16 | public Notification(String username, NotificationType type, String description) { 17 | plugin = OPProtector.getInstance(); 18 | this.username = username; 19 | this.title = title; 20 | this.description = description; 21 | avatar_url = "https://minotar.net/avatar/" + username + "/64.png"; 22 | 23 | switch (type){ 24 | case JOIN: 25 | title = "<:PlusOne:566099198118854676> Operator Joined"; 26 | colour = "#B3C998"; 27 | this.description = "``` " + username + "```"; 28 | break; 29 | case LEAVE: 30 | title = "<:MinusOne:566099197603086348> Operator Left"; 31 | colour = "#B3C998"; 32 | this.description = "``` " + username + "```"; 33 | break; 34 | case AUTH_FAIL: 35 | title = "<:TeamYellow:827068159252103179> Operator Failed to Authenticate"; 36 | colour = "#FFFC31"; 37 | break; 38 | case AUTH_SUCCESS: 39 | title = "<:TeamGreen:827068159088787516> Operator Authenticated"; 40 | colour = "#7BB61E"; 41 | this.description = "``` " + username + "```"; 42 | break; 43 | case UNAUTH_ACCESS: 44 | title = "<:TeamRed:827068159390646292> Unauthenticated Access Attempt"; 45 | colour = "#E94F37"; 46 | break; 47 | } 48 | 49 | if(!(plugin.getMainManager().getConfigManager().getMainConfig().discord_webhook == null || plugin.getMainManager().getConfigManager().getMainConfig().discord_webhook == "" || plugin.getMainManager().getConfigManager().getMainConfig().discord_webhook == " " || plugin.getMainManager().getConfigManager().getMainConfig().discord_webhook == "-")){ 50 | send(); 51 | } 52 | 53 | } 54 | 55 | private void send(){ 56 | DiscordWebhook webhook = new DiscordWebhook(plugin.getMainManager().getConfigManager().getMainConfig().discord_webhook); 57 | webhook.setUsername("OPProtector"); 58 | webhook.setAvatarUrl("https://raw.githubusercontent.com/ka0un/OPProtector/master/icon.png"); 59 | webhook.addEmbed(new DiscordWebhook.EmbedObject() 60 | .setThumbnail(avatar_url) 61 | .setFooter(new Timestamp(System.currentTimeMillis()).toString()) 62 | .setTitle(title) 63 | .setDescription(description) 64 | .setColor(Color.decode(colour))); 65 | 66 | try{ 67 | webhook.execute(); 68 | }catch (Exception e) { 69 | plugin.getLogger().warning("Failed to send notification to discord"); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Discord/NotificationType.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Discord; 2 | 3 | public enum NotificationType { 4 | JOIN, 5 | LEAVE, 6 | AUTH_FAIL, 7 | AUTH_SUCCESS, 8 | UNAUTH_ACCESS, 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/ListnerManager.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | 4 | import org.kasun.opprotector.OPProtector; 5 | 6 | public class ListnerManager { 7 | OPProtector plugin = OPProtector.getInstance(); 8 | public ListnerManager() { 9 | plugin.getServer().getPluginManager().registerEvents(new PlayerJoin(), plugin); 10 | plugin.getServer().getPluginManager().registerEvents(new PlayerMove(), plugin); 11 | plugin.getServer().getPluginManager().registerEvents(new PlayerCommand(), plugin); 12 | plugin.getServer().getPluginManager().registerEvents(new ServerCommand(), plugin); 13 | plugin.getServer().getPluginManager().registerEvents(new PlayerBlockBreak(), plugin); 14 | plugin.getServer().getPluginManager().registerEvents(new PlayerBlockPlace(), plugin); 15 | plugin.getServer().getPluginManager().registerEvents(new PlayerItemDrop(), plugin); 16 | plugin.getServer().getPluginManager().registerEvents(new PlayerLeave(), plugin); 17 | plugin.getServer().getPluginManager().registerEvents(new PlayerMessage(), plugin); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/LuckPermUpdate.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import net.luckperms.api.LuckPerms; 4 | import net.luckperms.api.LuckPermsProvider; 5 | import net.luckperms.api.event.EventBus; 6 | import net.luckperms.api.event.node.NodeMutateEvent; 7 | import net.luckperms.api.model.user.User; 8 | import net.luckperms.api.node.Node; 9 | import org.bukkit.Bukkit; 10 | import org.bukkit.entity.Player; 11 | import org.bukkit.plugin.Plugin; 12 | import org.bukkit.scheduler.BukkitRunnable; 13 | import org.kasun.opprotector.OPProtector; 14 | import org.kasun.opprotector.Punishments.Ban; 15 | import org.kasun.opprotector.Utils.CommandExecutor; 16 | import org.kasun.opprotector.VerificationProcess.VerificationStatus; 17 | 18 | import java.util.HashSet; 19 | import java.util.List; 20 | import java.util.Set; 21 | import java.util.concurrent.ConcurrentHashMap; 22 | 23 | public class LuckPermUpdate{ 24 | 25 | OPProtector plugin = OPProtector.getInstance(); 26 | 27 | public LuckPermUpdate() { 28 | 29 | if (!isLuckPermsInstalledAndEnabled()) { 30 | return; 31 | } 32 | 33 | LuckPerms api = LuckPermsProvider.get(); 34 | EventBus eventBus = api.getEventBus(); 35 | eventBus.subscribe(NodeMutateEvent.class, this::onNodeMutateEvent); 36 | } 37 | 38 | 39 | private void onNodeMutateEvent(NodeMutateEvent event) { 40 | 41 | if (event.isUser()) { 42 | 43 | User user = (User) event.getTarget(); 44 | 45 | if (Bukkit.getPlayer(user.getUniqueId()) == null) { 46 | return; 47 | } 48 | 49 | 50 | Player player = Bukkit.getPlayer(user.getUniqueId()); 51 | 52 | ConcurrentHashMap verificationStatusMap = plugin.getMainManager().getVerificationProcessManager().getVerificationStatusMap(); 53 | 54 | VerificationStatus verificationStatus = verificationStatusMap.getOrDefault(player.getName(), VerificationStatus.NOT_VERIFIED); 55 | 56 | if (verificationStatus == VerificationStatus.VERIFIED || verificationStatus == VerificationStatus.IN_PASSWORD_VERIFICATION) { 57 | return; 58 | } 59 | 60 | List blacklistedPermissions = plugin.getMainManager().getConfigManager().getMainConfig().blacklisted_permissions; 61 | boolean allowScanBlacklistedPerms = plugin.getMainManager().getConfigManager().getMainConfig().scan_for_blacklisted_permissions; 62 | 63 | Set dataBefore = event.getDataBefore(); 64 | Set dataAfter = event.getDataAfter(); 65 | 66 | // Find added permissions 67 | Set addedPermissions = new HashSet<>(dataAfter); 68 | addedPermissions.removeAll(dataBefore); 69 | 70 | 71 | 72 | for (Node addedPermission : addedPermissions) { 73 | String permission = addedPermission.getKey(); 74 | 75 | if (blacklistedPermissions.contains(permission) && allowScanBlacklistedPerms) { 76 | new BukkitRunnable() { 77 | @Override 78 | public void run() { 79 | executeCommandsAndBanPlayer(player, "Blacklisted Permission", "Blacklisted Permission: " + permission, plugin); 80 | } 81 | }.runTask(plugin); 82 | } 83 | } 84 | 85 | } 86 | } 87 | 88 | private boolean isLuckPermsInstalledAndEnabled() { 89 | Plugin luckPermsPlugin = Bukkit.getPluginManager().getPlugin("LuckPerms"); 90 | return luckPermsPlugin != null && luckPermsPlugin.isEnabled(); 91 | } 92 | 93 | private void executeCommandsAndBanPlayer(Player player, String banReason, String logReason, OPProtector plugin) { 94 | 95 | if (player == null){ 96 | return; 97 | } 98 | 99 | List commands = plugin.getMainManager().getConfigManager().getMainConfig().not_in_operators_list; 100 | CommandExecutor commandExecutor = new CommandExecutor(player, commands); 101 | Ban ban = new Ban(player, banReason, logReason); 102 | plugin.getMainManager().getLog().banned(player, logReason); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerBlockBreak.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.EventPriority; 5 | import org.bukkit.event.Listener; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Punishments.Lockdown; 8 | 9 | public class PlayerBlockBreak implements Listener { 10 | Lockdown lockdown; 11 | OPProtector plugin = OPProtector.getInstance(); 12 | @EventHandler(priority = EventPriority.LOWEST) 13 | public void onPlayerBlockBreak(org.bukkit.event.block.BlockBreakEvent e){ 14 | lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 15 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().block_break_block; 16 | if (allow && lockdown.isPlayerLocked(e.getPlayer())) { 17 | e.setCancelled(true); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerBlockPlace.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.EventPriority; 5 | import org.bukkit.event.Listener; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Punishments.Lockdown; 8 | 9 | public class PlayerBlockPlace implements Listener { 10 | Lockdown lockdown; 11 | OPProtector plugin = OPProtector.getInstance(); 12 | @EventHandler(priority = EventPriority.LOWEST) 13 | public void onPlayerBlockPlace(org.bukkit.event.block.BlockPlaceEvent e){ 14 | lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 15 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().block_place_block; 16 | if (allow && lockdown.isPlayerLocked(e.getPlayer())) { 17 | e.setCancelled(true); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerCommand.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.event.EventHandler; 6 | import org.bukkit.event.EventPriority; 7 | import org.bukkit.event.Listener; 8 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 9 | import org.kasun.opprotector.OPProtector; 10 | import org.kasun.opprotector.Punishments.Lockdown; 11 | import org.kasun.opprotector.Utils.Prefix; 12 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 13 | 14 | import java.util.List; 15 | 16 | public class PlayerCommand implements Listener { 17 | Lockdown lockdown; 18 | OPProtector plugin = OPProtector.getInstance(); 19 | @EventHandler(priority = EventPriority.LOWEST) 20 | public void onPlayerCommandProcess(PlayerCommandPreprocessEvent e){ 21 | lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 22 | 23 | 24 | if (lockdown.isPlayerLocked(e.getPlayer())) { 25 | List commandsWhitelist = plugin.getMainManager().getConfigManager().getMainConfig().commands_whitelist; 26 | boolean startsWithCommand = false; 27 | String message = e.getMessage(); 28 | 29 | for (String command : commandsWhitelist){ 30 | if (message.startsWith(command)) { 31 | startsWithCommand = true; 32 | break; 33 | } 34 | } 35 | 36 | if (!startsWithCommand) { 37 | e.setCancelled(true); 38 | } 39 | 40 | } 41 | 42 | if (plugin.getMainManager().getAuthorizedPlayers().isAuthorizedPlayer(e.getPlayer())) { 43 | boolean blockCommand = false; 44 | List commandsBlacklist = plugin.getMainManager().getConfigManager().getOperatorConfig().getOperator(e.getPlayer().getName()).getCommandBlacklist(); 45 | for (String command : commandsBlacklist){ 46 | if (e.getMessage().startsWith("/" + command)){ 47 | blockCommand = true; 48 | break; 49 | } 50 | } 51 | if (blockCommand){ 52 | e.setCancelled(true); 53 | e.getPlayer().sendMessage(Prefix.ERROR + "You are not allowed to use this command"); 54 | } 55 | } 56 | 57 | if (e.getPlayer().isOp()){ 58 | plugin.getMainManager().getLog().command(e.getPlayer(), e.getMessage()); 59 | } 60 | 61 | if (e.getMessage().startsWith("/op")){ 62 | OPProtector plugin = OPProtector.getInstance(); 63 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().scan_on_player_op_command; 64 | 65 | if (!allow) {return;} 66 | String str = e.getMessage(); 67 | int index = str.indexOf("/op "); 68 | String result = str.substring(index + 4); 69 | Player player = Bukkit.getPlayer(result); 70 | 71 | if (player != null){ 72 | VerificationProcessManager verificationProcessManager = plugin.getMainManager().getVerificationProcessManager(); 73 | verificationProcessManager.start(player); 74 | } 75 | 76 | } 77 | 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerItemDrop.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.EventPriority; 5 | import org.bukkit.event.Listener; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Punishments.Lockdown; 8 | 9 | public class PlayerItemDrop implements Listener { 10 | Lockdown lockdown; 11 | OPProtector plugin = OPProtector.getInstance(); 12 | @EventHandler(priority = EventPriority.LOWEST) 13 | public void onPlayerItemDrop(org.bukkit.event.player.PlayerDropItemEvent e){ 14 | lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 15 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().block_item_drop; 16 | if (allow && lockdown.isPlayerLocked(e.getPlayer())) { 17 | e.setCancelled(true); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerJoin.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | import org.bukkit.entity.Player; 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.EventPriority; 5 | import org.bukkit.event.Listener; 6 | import org.bukkit.event.player.PlayerJoinEvent; 7 | import org.kasun.opprotector.OPProtector; 8 | import org.kasun.opprotector.Utils.Log; 9 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 10 | 11 | 12 | public class PlayerJoin implements Listener { 13 | @EventHandler(priority = EventPriority.LOWEST) 14 | public void onPlayerJoin(PlayerJoinEvent e){ 15 | OPProtector plugin = OPProtector.getInstance(); 16 | Log log = plugin.getMainManager().getLog(); 17 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().scan_on_join; 18 | 19 | if (!allow) {return;} 20 | Player player = e.getPlayer(); 21 | VerificationProcessManager verificationProcessManager = plugin.getMainManager().getVerificationProcessManager(); 22 | verificationProcessManager.start(player); 23 | 24 | if (player.isOp()) { 25 | log.login(player); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerLeave.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | 4 | import org.bukkit.event.EventHandler; 5 | import org.bukkit.event.EventPriority; 6 | import org.bukkit.event.Listener; 7 | import org.kasun.opprotector.OPProtector; 8 | import org.kasun.opprotector.VerificationProcess.PasswordFlash; 9 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 10 | import org.kasun.opprotector.VerificationProcess.VerificationStatus; 11 | 12 | import java.util.HashMap; 13 | import java.util.concurrent.ConcurrentHashMap; 14 | 15 | public class PlayerLeave implements Listener { 16 | @EventHandler(priority = EventPriority.LOWEST) 17 | public void onPlayerLeave(org.bukkit.event.player.PlayerQuitEvent e){ 18 | OPProtector plugin = OPProtector.getInstance(); 19 | VerificationProcessManager verificationProcessManager = plugin.getMainManager().getVerificationProcessManager(); 20 | ConcurrentHashMap verificationStatusMap = verificationProcessManager.getVerificationStatusMap(); 21 | if (plugin.getServer().getOnlinePlayers().size() == 1) { 22 | plugin.getMainManager().getLiveScanner().stop(); 23 | } 24 | boolean isinverification = verificationStatusMap.containsKey(e.getPlayer().getName()) && verificationStatusMap.get(e.getPlayer().getName()) == VerificationStatus.IN_PASSWORD_VERIFICATION; 25 | if (isinverification) { 26 | PasswordFlash passwordFlash = verificationProcessManager.getPasswordFlash(); 27 | passwordFlash.stopTasks(); 28 | verificationStatusMap.remove(e.getPlayer().getName()); 29 | } 30 | if (e.getPlayer().isOp()) { 31 | plugin.getMainManager().getLog().logout(e.getPlayer()); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerMessage.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.EventPriority; 5 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Punishments.Lockdown; 8 | 9 | import java.util.List; 10 | 11 | public class PlayerMessage implements org.bukkit.event.Listener{ 12 | OPProtector plugin = OPProtector.getInstance(); 13 | Lockdown lockdown; 14 | 15 | @EventHandler(priority = EventPriority.LOWEST) 16 | public void onPlayerCommandProcess(PlayerCommandPreprocessEvent e){ 17 | lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 18 | 19 | 20 | if (lockdown.isPlayerLocked(e.getPlayer())) { 21 | List commandsWhitelist = plugin.getMainManager().getConfigManager().getMainConfig().commands_whitelist; 22 | boolean startsWithCommand = false; 23 | String message = e.getMessage(); 24 | 25 | for (String command : commandsWhitelist){ 26 | if (message.startsWith(command)) { 27 | startsWithCommand = true; 28 | break; 29 | } 30 | } 31 | 32 | if (!startsWithCommand) { 33 | e.setCancelled(true); 34 | } 35 | 36 | } 37 | 38 | if (e.getPlayer().isOp()){ 39 | plugin.getMainManager().getLog().command(e.getPlayer(), e.getMessage()); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/PlayerMove.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.EventPriority; 5 | import org.bukkit.event.Listener; 6 | import org.bukkit.event.player.PlayerMoveEvent; 7 | import org.kasun.opprotector.OPProtector; 8 | import org.kasun.opprotector.Punishments.Lockdown; 9 | 10 | public class PlayerMove implements Listener { 11 | Lockdown lockdown; 12 | OPProtector plugin = OPProtector.getInstance(); 13 | @EventHandler(priority = EventPriority.LOWEST) 14 | public void onPlayerMove(PlayerMoveEvent e) { 15 | lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 16 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().block_player_move; 17 | 18 | if (allow && lockdown.isPlayerLocked(e.getPlayer())) { 19 | e.setCancelled(true); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Listners/ServerCommand.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Listners; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.event.EventHandler; 6 | import org.bukkit.event.EventPriority; 7 | import org.bukkit.event.Listener; 8 | import org.kasun.opprotector.OPProtector; 9 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 10 | 11 | public class ServerCommand implements Listener { 12 | 13 | @EventHandler(priority = EventPriority.LOWEST) 14 | public void onServerCommand(org.bukkit.event.server.ServerCommandEvent e){ 15 | OPProtector plugin = OPProtector.getInstance(); 16 | boolean allow = plugin.getMainManager().getConfigManager().getMainConfig().scan_on_console_op_command; 17 | if (e.getCommand().startsWith("op ")) { 18 | if (!allow) {return;} 19 | String str = e.getCommand(); 20 | int index = str.indexOf("op "); 21 | String result = str.substring(index + 3); 22 | Player player = Bukkit.getPlayer(result); 23 | if (player != null){ 24 | VerificationProcessManager verificationProcessManager = plugin.getMainManager().getVerificationProcessManager(); 25 | verificationProcessManager.start(player); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/MainManager.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector; 2 | 3 | import org.bukkit.command.ConsoleCommandSender; 4 | import org.kasun.opprotector.AuthObjects.IpTable; 5 | import org.kasun.opprotector.Listners.LuckPermUpdate; 6 | import org.kasun.opprotector.Scanner.LiveScanner; 7 | import org.kasun.opprotector.AuthObjects.TempAuth; 8 | import org.kasun.opprotector.Commands.CommandsManager; 9 | import org.kasun.opprotector.Configs.ConfigManager; 10 | import org.kasun.opprotector.Listners.ListnerManager; 11 | import org.kasun.opprotector.Punishments.PunishmentManager; 12 | import org.kasun.opprotector.Scanner.OfflineScanResult; 13 | import org.kasun.opprotector.Utils.Log; 14 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 15 | import org.bukkit.Bukkit; 16 | import org.bukkit.event.HandlerList; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | public class MainManager { 22 | private ConfigManager configManager; 23 | private ListnerManager listnerManager; 24 | private PunishmentManager punishmentManager; 25 | private TempAuth tempAuth; 26 | private CommandsManager commandsManager; 27 | private VerificationProcessManager verificationProcessManager; 28 | private LiveScanner liveScanner; 29 | private IpTable ipTable; 30 | private Log log; 31 | private List offlinePlayerScanResultList; 32 | private LuckPermUpdate luckPermUpdate; 33 | OPProtector plugin = OPProtector.getInstance(); 34 | public MainManager() { 35 | configManager = new ConfigManager(); 36 | listnerManager = new ListnerManager(); 37 | punishmentManager = new PunishmentManager(); 38 | commandsManager = new CommandsManager(); 39 | tempAuth = new TempAuth(); 40 | verificationProcessManager = new VerificationProcessManager(); 41 | liveScanner = new LiveScanner(configManager); 42 | ipTable = new IpTable(); 43 | log = new Log(); 44 | offlinePlayerScanResultList = new ArrayList<>(); 45 | luckPermUpdate = new LuckPermUpdate(); 46 | } 47 | 48 | public void reload() { 49 | HandlerList.unregisterAll(plugin); 50 | Bukkit.getScheduler().cancelTasks(plugin); 51 | setConfigManager(new ConfigManager()); 52 | setListnerManager(new ListnerManager()); 53 | setPunishmentManager(new PunishmentManager()); 54 | setCommandsManager(new CommandsManager()); 55 | setTempAuth(new TempAuth()); 56 | setVerificationProcessManager(new VerificationProcessManager()); 57 | setLiveScanner(new LiveScanner(configManager)); 58 | setIpTable(new IpTable()); 59 | setLog(new Log()); 60 | ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); 61 | offlinePlayerScanResultList = new ArrayList<>(); 62 | luckPermUpdate = new LuckPermUpdate(); 63 | } 64 | 65 | public List getOfflinePlayerScanResultList() { 66 | return offlinePlayerScanResultList; 67 | } 68 | 69 | public void setOfflinePlayerScanResultList(List offlinePlayerScanResultList) { 70 | this.offlinePlayerScanResultList = offlinePlayerScanResultList; 71 | } 72 | 73 | public ConfigManager getConfigManager() { 74 | return configManager; 75 | } 76 | 77 | public ListnerManager getListnerManager() { 78 | return listnerManager; 79 | } 80 | 81 | public PunishmentManager getPunishmentManager() { 82 | return punishmentManager; 83 | } 84 | 85 | public TempAuth getAuthorizedPlayers() { 86 | return tempAuth; 87 | } 88 | 89 | public CommandsManager getCommandsManager() { 90 | return commandsManager; 91 | } 92 | 93 | public VerificationProcessManager getVerificationProcessManager() { 94 | return verificationProcessManager; 95 | } 96 | 97 | public LiveScanner getLiveScanner() { 98 | return liveScanner; 99 | } 100 | 101 | public IpTable getIpTable() { 102 | return ipTable; 103 | } 104 | 105 | public Log getLog() { 106 | return log; 107 | } 108 | 109 | public void setConfigManager(ConfigManager configManager) { 110 | this.configManager = configManager; 111 | } 112 | 113 | public void setListnerManager(ListnerManager listnerManager) { 114 | this.listnerManager = listnerManager; 115 | } 116 | 117 | public void setPunishmentManager(PunishmentManager punishmentManager) { 118 | this.punishmentManager = punishmentManager; 119 | } 120 | 121 | public void setTempAuth(TempAuth tempAuth) { 122 | this.tempAuth = tempAuth; 123 | } 124 | 125 | public void setCommandsManager(CommandsManager commandsManager) { 126 | this.commandsManager = commandsManager; 127 | } 128 | 129 | public void setVerificationProcessManager(VerificationProcessManager verificationProcessManager) { 130 | this.verificationProcessManager = verificationProcessManager; 131 | } 132 | 133 | public void setLiveScanner(LiveScanner liveScanner) { 134 | this.liveScanner = liveScanner; 135 | } 136 | 137 | public void setIpTable(IpTable ipTable) { 138 | this.ipTable = ipTable; 139 | } 140 | 141 | public void setLog(Log log) { 142 | this.log = log; 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/OPProtector.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector; 2 | 3 | 4 | import org.bukkit.plugin.java.JavaPlugin; 5 | import org.kasun.opprotector.Utils.Metrics; 6 | 7 | public final class OPProtector extends JavaPlugin { 8 | private static OPProtector instance; 9 | private boolean isFirstTime; 10 | MainManager mainManager; 11 | 12 | 13 | @Override 14 | public void onEnable() { 15 | instance = this; 16 | fisttimecheck(); 17 | mainManager = new MainManager(); 18 | int pluginId = 19908; 19 | Metrics metrics = new Metrics(this, pluginId); 20 | } 21 | 22 | @Override 23 | public void onDisable() { 24 | // Plugin shutdown logic 25 | } 26 | 27 | public static OPProtector getInstance() { 28 | return instance; 29 | } 30 | 31 | public void fisttimecheck() { 32 | if (!getDataFolder().exists()) { 33 | getDataFolder().mkdir(); 34 | isFirstTime = true; 35 | } 36 | } 37 | 38 | public boolean isFirstTime() { 39 | return isFirstTime; 40 | } 41 | 42 | public MainManager getMainManager() { 43 | return mainManager; 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Punishments/Ban.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Punishments; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.kasun.opprotector.OPProtector; 5 | 6 | public class Ban { 7 | private OPProtector plugin = OPProtector.getInstance(); 8 | public Ban(Player player, String kickMessage, String banMessage){ 9 | player.setOp(false); 10 | plugin.getServer().getBanList(org.bukkit.BanList.Type.NAME).addBan(player.getName(), banMessage, null, null); 11 | player.kickPlayer(kickMessage); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Punishments/Lockdown.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Punishments; 2 | import org.bukkit.entity.Player; 3 | import org.kasun.opprotector.OPProtector; 4 | import java.util.ArrayList; 5 | 6 | 7 | public class Lockdown { 8 | private OPProtector plugin = OPProtector.getInstance(); 9 | private ArrayList lockedPlayers; 10 | private boolean allowflight; 11 | private boolean blockdamage; 12 | private boolean blockitempickup; 13 | public Lockdown() { 14 | lockedPlayers = new ArrayList<>(); 15 | } 16 | 17 | public void lockPlayer(Player player){ 18 | allowflight = plugin.getMainManager().getConfigManager().getMainConfig().allow_flight; 19 | blockdamage = plugin.getMainManager().getConfigManager().getMainConfig().block_damage; 20 | blockitempickup = plugin.getMainManager().getConfigManager().getMainConfig().block_item_pickup; 21 | 22 | lockedPlayers.add(player); 23 | if (allowflight){ 24 | player.setAllowFlight(true); 25 | } 26 | if (blockdamage){ 27 | player.setInvulnerable(true); 28 | } 29 | if (blockitempickup){ 30 | player.setCanPickupItems(false); 31 | } 32 | } 33 | 34 | public void unlockPlayer(Player player){ 35 | allowflight = plugin.getMainManager().getConfigManager().getMainConfig().allow_flight; 36 | blockdamage = plugin.getMainManager().getConfigManager().getMainConfig().block_damage; 37 | blockitempickup = plugin.getMainManager().getConfigManager().getMainConfig().block_item_pickup; 38 | 39 | lockedPlayers.remove(player); 40 | if (allowflight){ 41 | player.setAllowFlight(false); 42 | } 43 | if (blockdamage){ 44 | player.setInvulnerable(false); 45 | } 46 | if (blockitempickup){ 47 | player.setCanPickupItems(true); 48 | } 49 | } 50 | 51 | public boolean isPlayerLocked(Player player){ 52 | if (lockedPlayers.contains(player)){ 53 | return true; 54 | }else { 55 | return false; 56 | } 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Punishments/PunishmentManager.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Punishments; 2 | 3 | public class PunishmentManager { 4 | Lockdown lockdown; 5 | public PunishmentManager() { 6 | lockdown = new Lockdown(); 7 | } 8 | public Lockdown getLockdown() { 9 | return lockdown; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Scanner/LiveScanner.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Scanner; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.GameMode; 5 | import org.bukkit.entity.Player; 6 | import org.bukkit.scheduler.BukkitRunnable; 7 | import org.bukkit.scheduler.BukkitTask; 8 | import org.kasun.opprotector.Configs.ConfigManager; 9 | import org.kasun.opprotector.OPProtector; 10 | import org.kasun.opprotector.Punishments.Ban; 11 | import org.kasun.opprotector.Utils.CommandExecutor; 12 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 13 | import org.kasun.opprotector.VerificationProcess.VerificationStatus; 14 | 15 | import java.util.List; 16 | import java.util.concurrent.ConcurrentHashMap; 17 | 18 | public class LiveScanner { 19 | private BukkitTask liveScannerTask; 20 | 21 | public LiveScanner(ConfigManager configManager) { 22 | 23 | boolean scanFromLiveScan = configManager.getMainConfig().scan_from_live_scanner; 24 | 25 | if (scanFromLiveScan){ 26 | start(); 27 | } 28 | 29 | } 30 | 31 | public void start() { 32 | 33 | OPProtector plugin = OPProtector.getInstance(); 34 | 35 | long period = (long) (1 * 20); 36 | 37 | liveScannerTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> { 38 | ConcurrentHashMap verificationStatusMap = plugin.getMainManager().getVerificationProcessManager().getVerificationStatusMap(); 39 | 40 | if (verificationStatusMap == null) { 41 | return; 42 | } 43 | 44 | if (Bukkit.getOnlinePlayers().isEmpty()) { 45 | return; 46 | } 47 | 48 | for (Player player : Bukkit.getOnlinePlayers()) { 49 | VerificationStatus verificationStatus = verificationStatusMap.getOrDefault(player.getName(), VerificationStatus.NOT_VERIFIED); 50 | 51 | if (verificationStatus != VerificationStatus.VERIFIED && verificationStatus != VerificationStatus.IN_PASSWORD_VERIFICATION) { 52 | scanPlayer(player, verificationStatusMap, plugin); 53 | } 54 | } 55 | }, 5L, period); // Run every second (20 ticks) 56 | } 57 | 58 | private void scanPlayer(Player player, ConcurrentHashMap verificationStatusMap, OPProtector plugin) { 59 | List blacklistedPermissions = plugin.getMainManager().getConfigManager().getMainConfig().blacklisted_permissions; 60 | boolean allowScanCreative = plugin.getMainManager().getConfigManager().getMainConfig().scan_for_gamemode_creative; 61 | boolean allowScanBlacklistedPerms = plugin.getMainManager().getConfigManager().getMainConfig().scan_for_blacklisted_permissions; 62 | boolean opContainsInYml = plugin.getMainManager().getConfigManager().getOperatorConfig().isContains(player.getName()); 63 | 64 | // Check for blacklisted permissions 65 | if (allowScanBlacklistedPerms) { 66 | for (String permission : blacklistedPermissions) { 67 | 68 | if (player.hasPermission(permission) && !opContainsInYml) { 69 | executeCommandsAndBanPlayer(player, "You aren't listed in OPProtector/operators.yml", "Blacklisted Permission: " + permission, plugin); 70 | } 71 | } 72 | } 73 | 74 | // check for op 75 | if (player.isOp()){ 76 | if (!opContainsInYml){ 77 | executeCommandsAndBanPlayer(player, "You aren't listed in OPProtector/operators.yml", "OP", plugin); 78 | } 79 | } 80 | 81 | // Check for creative mode 82 | if (player.getGameMode() == GameMode.CREATIVE && allowScanCreative) { 83 | if (!opContainsInYml) { 84 | executeCommandsAndBanPlayer(player, "You aren't listed in OPProtector/operators.yml", "Creative Mode", plugin); 85 | } 86 | } 87 | 88 | verify(player, plugin); 89 | } 90 | 91 | private void executeCommandsAndBanPlayer(Player player, String banReason, String logReason, OPProtector plugin) { 92 | 93 | new BukkitRunnable() { 94 | @Override 95 | public void run() { 96 | List commands = plugin.getMainManager().getConfigManager().getMainConfig().not_in_operators_list; 97 | CommandExecutor commandExecutor = new CommandExecutor(player, commands); 98 | Ban ban = new Ban(player, banReason, logReason); 99 | plugin.getMainManager().getLog().banned(player, logReason); 100 | } 101 | }.runTask(plugin); 102 | 103 | 104 | } 105 | 106 | private void verify(Player player, OPProtector plugin) { 107 | new BukkitRunnable() { 108 | @Override 109 | public void run() { 110 | VerificationProcessManager verificationProcessManager = plugin.getMainManager().getVerificationProcessManager(); 111 | verificationProcessManager.start(player); 112 | } 113 | }.runTask(plugin); 114 | } 115 | 116 | public void stop() { 117 | if (liveScannerTask != null) { 118 | liveScannerTask.cancel(); 119 | liveScannerTask = null; 120 | } 121 | } 122 | } 123 | 124 | 125 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Scanner/OfflineScanResult.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Scanner; 2 | 3 | import org.bukkit.OfflinePlayer; 4 | import org.kasun.opprotector.Utils.OfflineScannerResultType; 5 | 6 | 7 | 8 | public class OfflineScanResult { 9 | private OfflinePlayer player; 10 | private OfflineScannerResultType resultType; 11 | private String description; 12 | 13 | public OfflineScanResult(OfflinePlayer player, OfflineScannerResultType resultType, String description) { 14 | this.player = player; 15 | this.resultType = resultType; 16 | this.description = description; 17 | } 18 | 19 | public OfflinePlayer getPlayer() { 20 | return player; 21 | } 22 | 23 | public void setPlayer(OfflinePlayer player) { 24 | this.player = player; 25 | } 26 | 27 | public OfflineScannerResultType getResultType() { 28 | return resultType; 29 | } 30 | 31 | public void setResultType(OfflineScannerResultType resultType) { 32 | this.resultType = resultType; 33 | } 34 | 35 | public String getDescription() { 36 | return description; 37 | } 38 | 39 | public void setDescription(String description) { 40 | this.description = description; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Scanner/OfflineScanner.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Scanner; 2 | 3 | 4 | import org.bukkit.OfflinePlayer; 5 | import org.bukkit.command.CommandSender; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Utils.LuckpermsCheck; 8 | import org.kasun.opprotector.Utils.OfflineScannerResultType; 9 | import org.kasun.opprotector.Utils.Prefix; 10 | 11 | import java.util.*; 12 | import java.util.concurrent.ExecutorService; 13 | import java.util.concurrent.Executors; 14 | 15 | import org.bukkit.Bukkit; 16 | import org.bukkit.plugin.Plugin; 17 | 18 | public class OfflineScanner { 19 | private CommandSender sender; 20 | private int totalOfflinePlayers; 21 | private List blacklistedPermissions; 22 | private boolean allowScanBlacklistedPerms; 23 | private List resultList; 24 | 25 | private OPProtector plugin; 26 | private ExecutorService executorService; 27 | 28 | public OfflineScanner(CommandSender sender) { 29 | resultList = new ArrayList<>(); 30 | plugin = OPProtector.getInstance(); 31 | this.sender = sender; 32 | 33 | blacklistedPermissions = plugin.getMainManager().getConfigManager().getMainConfig().blacklisted_permissions; 34 | allowScanBlacklistedPerms = plugin.getMainManager().getConfigManager().getMainConfig().scan_for_blacklisted_permissions; 35 | 36 | List offlinePlayers = Arrays.asList(plugin.getServer().getOfflinePlayers()); 37 | totalOfflinePlayers = offlinePlayers.size(); 38 | 39 | if (totalOfflinePlayers == 0) { 40 | sender.sendMessage(Prefix.ERROR + "No Joined Players Found"); 41 | return; 42 | }else{ 43 | sender.sendMessage(Prefix.SUCCESS + "Started Scanning " + offlinePlayers.size() + " Players"); 44 | if (totalOfflinePlayers > 10){ 45 | sender.sendMessage(Prefix.WARNING + "This may take a while..."); 46 | } 47 | } 48 | 49 | boolean onlyOP = !isLuckPermsInstalledAndEnabled(); 50 | 51 | if (onlyOP){ 52 | sender.sendMessage(Prefix.WARNING + "LuckPerms not found, scanning for OPs only"); 53 | } 54 | 55 | executorService = Executors.newSingleThreadExecutor(); 56 | 57 | startScanning(offlinePlayers, sender, onlyOP, totalOfflinePlayers); 58 | 59 | } 60 | 61 | private void startScanning(List offlinePlayers, CommandSender sender, boolean onlyOP, int totalOfflinePlayers) { 62 | executorService.execute(() -> { 63 | int i = 1; 64 | for (OfflinePlayer player : offlinePlayers) { 65 | scan(player, onlyOP); 66 | if (i != 0 && i % 5 == 0) { 67 | sender.sendMessage(Prefix.INFO + "Scanned " + i + " / " + totalOfflinePlayers + " Players"); 68 | } 69 | i++; 70 | } 71 | 72 | // Perform actions after scanning is finished 73 | sender.sendMessage(Prefix.SUCCESS + "Finished Scanning"); 74 | 75 | if (resultList == null || resultList.size() == 0) { 76 | sender.sendMessage(Prefix.SUCCESS + "No Unauthorized Players Detected"); 77 | } else { 78 | plugin.getMainManager().setOfflinePlayerScanResultList(resultList); 79 | new ScanResults(resultList, sender); 80 | } 81 | this.executorService.shutdown(); 82 | }); 83 | } 84 | 85 | private void scan(OfflinePlayer player, boolean onlyOP){ 86 | 87 | if (player.isBanned()){ 88 | return; 89 | } 90 | 91 | boolean opContainsInYml = plugin.getMainManager().getConfigManager().getOperatorConfig().isContains(player.getName()); 92 | 93 | 94 | if (onlyOP){ 95 | if (!opContainsInYml){ 96 | if (player.isOp()){ 97 | OfflineScanResult offlineScanResult = new OfflineScanResult(player, OfflineScannerResultType.UnlistedOP, "Not Listed in operators.yml"); 98 | resultList.add(offlineScanResult); 99 | } 100 | } 101 | }else{ 102 | 103 | for (String permission : blacklistedPermissions) { 104 | try { 105 | if (LuckpermsCheck.hasPermission(player.getUniqueId(), permission)) { 106 | if (!opContainsInYml) { 107 | if (!player.isOp()){ 108 | OfflineScanResult offlineScanResult = new OfflineScanResult(player, OfflineScannerResultType.BlackListedPerms, "Permission : " + permission); 109 | resultList.add(offlineScanResult); 110 | return; 111 | }else{ 112 | OfflineScanResult offlineScanResult = new OfflineScanResult(player, OfflineScannerResultType.UnlistedOP, "Not Listed in operators.yml"); 113 | resultList.add(offlineScanResult); 114 | return; 115 | } 116 | 117 | }else{ 118 | return; 119 | } 120 | } 121 | } catch (NullPointerException ignored) { 122 | } 123 | } 124 | 125 | // Check if player is an OP 126 | if (player.isOp()) { 127 | if (!opContainsInYml) { 128 | OfflineScanResult offlineScanResult = new OfflineScanResult(player, OfflineScannerResultType.UnlistedOP, "Not Listed in operators.yml"); 129 | resultList.add(offlineScanResult); 130 | } 131 | } 132 | } 133 | 134 | } 135 | 136 | private boolean isLuckPermsInstalledAndEnabled() { 137 | Plugin luckPermsPlugin = Bukkit.getPluginManager().getPlugin("LuckPerms"); 138 | return luckPermsPlugin != null && luckPermsPlugin.isEnabled(); 139 | } 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Scanner/ScanResults.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Scanner; 2 | 3 | import org.bukkit.ChatColor; 4 | import org.bukkit.command.CommandSender; 5 | 6 | 7 | import java.util.List; 8 | 9 | public class ScanResults { 10 | private List resultList; 11 | private CommandSender sender; 12 | 13 | public ScanResults(List resultList, CommandSender sender) { 14 | this.resultList = resultList; 15 | this.sender = sender; 16 | showResultsWithChat(); 17 | } 18 | 19 | 20 | private void showResultsWithChat(){ 21 | sender.sendMessage(ChatColor.RED + "Total Players Detected: " + resultList.size()); 22 | sender.sendMessage(" "); 23 | for (OfflineScanResult result : resultList) { 24 | sender.sendMessage( ChatColor.GOLD + result.getPlayer().getName() + " - " + ChatColor.YELLOW + result.getResultType().toString() + " - " + ChatColor.WHITE + result.getDescription()); 25 | } 26 | sender.sendMessage(" "); 27 | sender.sendMessage(ChatColor.RED + "Use /opp banall to ban all detected players"); 28 | } 29 | 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/ColorUtils.java: -------------------------------------------------------------------------------- 1 | /* */ package org.kasun.opprotector.Utils; 2 | /* */ 3 | /* */ import java.util.ArrayList; 4 | /* */ import java.util.Arrays; 5 | /* */ import java.util.List; 6 | /* */ import java.util.Random; 7 | /* */ 8 | /* */ 9 | /* */ public class ColorUtils 10 | /* */ { 11 | /* */ public static String colorGradient(String string) { 12 | /* 12 */ String message = string.replace("", " "); 13 | /* 13 */ int spaceCount = message.length() - message.replaceAll(" ", "").length(); 14 | /* */ 15 | /* 15 */ List colors = new ArrayList<>(Arrays.asList(new Integer[] { Integer.valueOf(100), Integer.valueOf(101), Integer.valueOf(102), Integer.valueOf(103), Integer.valueOf(104), Integer.valueOf(105), Integer.valueOf(141), Integer.valueOf(140), Integer.valueOf(139), Integer.valueOf(138), Integer.valueOf(137), Integer.valueOf(136), Integer.valueOf(172), Integer.valueOf(173), Integer.valueOf(174), Integer.valueOf(175), Integer.valueOf(176), Integer.valueOf(177), Integer.valueOf(213), Integer.valueOf(212), Integer.valueOf(211), Integer.valueOf(210), Integer.valueOf(209), Integer.valueOf(208) })); 16 | /* 16 */ String finalMessage = message; 17 | /* 17 */ for (int i = 0; i < spaceCount; i++) { 18 | /* 18 */ Random random = new Random(); 19 | /* 19 */ int rd = random.nextInt(24); 20 | /* 20 */ String color = "\033[38;5;" + colors.get(rd) + "m"; 21 | /* */ 22 | /* 22 */ finalMessage = finalMessage.replaceFirst("\\s+", color); 23 | /* */ } 24 | /* 24 */ return finalMessage; 25 | /* */ } 26 | /* */ } 27 | 28 | 29 | /* Location: D:\Downloads\ConsoleColors-V1 (1).jar!\net\godead\consolecolors\ColorUtils.class 30 | * Java compiler version: 8 (52.0) 31 | * JD-Core Version: 1.1.3 32 | */ -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/Colors.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | public class Colors { 4 | public static final String RESET = "\033[0m"; 5 | 6 | public static final String BLINK = "\033[5m"; 7 | 8 | public static final String FAST_BLINK = "\033[6m"; 9 | 10 | public static final String BOLD = "\033[1m"; 11 | 12 | public static final String FAINT = "\033[2m"; 13 | 14 | public static final String ITALIC = "\033[3m"; 15 | 16 | public static final String UNDERLINE = "\033[4m"; 17 | 18 | public static final String FRAMED = "\033[51m"; 19 | 20 | public static final String ENCIRCLED = "\033[52m"; 21 | 22 | public static final String OVERLINE = "\033[53m"; 23 | 24 | public static final String REVERSE_BACKGROUND = "\033[7m"; 25 | 26 | public static final String BOLD_DOUBLE_UNDERLINE = "\033[21m"; 27 | 28 | public static final String TEST = "\033[38;5;209m"; 29 | 30 | public static final String RED = "\033[31m"; 31 | 32 | public static final String GREEN = "\033[32m"; 33 | 34 | public static final String GOLD = "\033[33m"; 35 | 36 | public static final String DARK_BLUE = "\033[34m"; 37 | 38 | public static final String PURPLE = "\033[35m"; 39 | 40 | public static final String CYAN = "\033[36m"; 41 | 42 | public static final String LIGHT_GRAY = "\033[37m"; 43 | 44 | public static final String DARK_GRAY = "\033[90m"; 45 | 46 | public static final String LIGHT_RED = "\033[91m"; 47 | 48 | public static final String LIME = "\033[92m"; 49 | 50 | public static final String YELLOW = "\033[93m"; 51 | 52 | public static final String BLUE = "\033[94m"; 53 | 54 | public static final String PINK = "\033[95m"; 55 | 56 | public static final String AQUA = "\033[96m"; 57 | 58 | public static final String BLACK = "\033[97m"; 59 | 60 | public static final String BLACK_BACKGROUND = "\033[40m"; 61 | 62 | public static final String RED_BACKGROUND = "\033[41m"; 63 | 64 | public static final String GREEN_BACKGROUND = "\033[42m"; 65 | 66 | public static final String GOLD_BACKGROUND = "\033[43m"; 67 | 68 | public static final String DARK_BLUE_BACKGROUND = "\033[44m"; 69 | 70 | public static final String PURPLE_BACKGROUND = "\033[45m"; 71 | 72 | public static final String CYAN_BACKGROUND = "\033[46m"; 73 | 74 | public static final String WHITE_BACKGROUND = "\033[47m"; 75 | 76 | public static final String DARK_GRAY_BACKGROUND = "\033[100m"; 77 | 78 | public static final String LIGHT_RED_BACKGROUND = "\033[101m"; 79 | 80 | public static final String LIME_BACKGROUND = "\033[102m"; 81 | 82 | public static final String YELLOW_BACKGROUND = "\033[103m"; 83 | 84 | public static final String BLUE_BACKGROUND = "\033[104m"; 85 | 86 | public static final String PINK_BACKGROUND = "\033[105m"; 87 | 88 | public static final String AQUA_BACKGROUND = "\033[106m"; 89 | 90 | public static void main(String[] args) {} 91 | } 92 | 93 | 94 | /* Location: D:\Downloads\ConsoleColors-V1 (1).jar!\net\godead\consolecolors\Colors.class 95 | * Java compiler version: 8 (52.0) 96 | * JD-Core Version: 1.1.3 97 | */ -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/CommandExecutor.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.Player; 5 | 6 | import java.util.List; 7 | 8 | public class CommandExecutor { 9 | public CommandExecutor(Player player, List commands) { 10 | if (commands == null) { 11 | return; 12 | } 13 | for (String command : commands) { 14 | String replacedCommand = command.replace("%player%", player.getName()); 15 | Bukkit.dispatchCommand(Bukkit.getConsoleSender(), replacedCommand); 16 | } 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/Encryption.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | import javax.crypto.Cipher; 4 | import javax.crypto.spec.IvParameterSpec; 5 | import javax.crypto.spec.SecretKeySpec; 6 | import java.nio.charset.StandardCharsets; 7 | import java.util.Base64; 8 | 9 | public class Encryption { 10 | 11 | public static String encrypt(String plainText, String secretKey) throws Exception { 12 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 13 | SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES"); 14 | IvParameterSpec ivSpec = new IvParameterSpec(secretKey.getBytes(StandardCharsets.UTF_8), 0, 16); 15 | cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); 16 | byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); 17 | return Base64.getEncoder().encodeToString(encryptedBytes); 18 | } 19 | 20 | public static String decrypt(String encryptedString, String secretKey) throws Exception { 21 | byte[] encryptedBytes = Base64.getDecoder().decode(encryptedString); 22 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 23 | SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES"); 24 | IvParameterSpec ivSpec = new IvParameterSpec(secretKey.getBytes(StandardCharsets.UTF_8), 0, 16); 25 | cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); 26 | byte[] decryptedBytes = cipher.doFinal(encryptedBytes); 27 | return new String(decryptedBytes, StandardCharsets.UTF_8); 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/ErrorHandler.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | import org.kasun.opprotector.OPProtector; 4 | 5 | public class ErrorHandler{ 6 | private static OPProtector plugin; 7 | public static void handleError(String code){ 8 | plugin = OPProtector.getInstance(); 9 | plugin.getLogger().severe("========================================================="); 10 | plugin.getLogger().severe("An error occurred."); 11 | plugin.getLogger().severe("Error Code : " + code); 12 | plugin.getLogger().severe("Please check the error and report it to the developer."); 13 | plugin.getLogger().severe("Discord Server : https://dsc.gg/sundevs"); 14 | plugin.getLogger().severe("========================================================="); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/Log.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.kasun.opprotector.Discord.Notification; 5 | import org.kasun.opprotector.Discord.NotificationType; 6 | import org.kasun.opprotector.OPProtector; 7 | 8 | import java.io.File; 9 | import java.io.FileWriter; 10 | import java.io.IOException; 11 | import java.sql.Timestamp; 12 | import java.text.SimpleDateFormat; 13 | import java.util.ArrayList; 14 | import java.util.Arrays; 15 | import java.util.Date; 16 | import java.util.HashMap; 17 | 18 | public class Log { 19 | private File logFile; 20 | private HashMap cache; 21 | 22 | 23 | 24 | 25 | OPProtector plugin = OPProtector.getInstance(); 26 | public Log() { 27 | cache = new HashMap<>(); 28 | // Get the current date and time 29 | Date currentDate = new Date(); 30 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); 31 | String formattedDate = dateFormat.format(currentDate); 32 | 33 | // Create the logs folder if it doesn't exist 34 | File logsFolder = new File(plugin.getDataFolder(), "logs"); 35 | if (!logsFolder.exists()) { 36 | logsFolder.mkdirs(); 37 | } 38 | 39 | // Create the file with the current date and time as the name 40 | logFile = new File(logsFolder, formattedDate + ".txt"); 41 | 42 | try { 43 | // Create the file and write some initial content 44 | logFile.createNewFile(); 45 | FileWriter writer = new FileWriter(logFile); 46 | writer.write("This is your log file for " + formattedDate + "\n"); 47 | writer.close(); 48 | // You can continue writing to the log file as needed. 49 | } catch (IOException e) { 50 | e.printStackTrace(); 51 | } 52 | } 53 | 54 | public void log(String message, boolean timestamp, boolean border) { 55 | try { 56 | FileWriter writer = new FileWriter(logFile, true); // Open the file in append mode 57 | if (border) { 58 | writer.write("--------------------------------------------------\n"); 59 | } 60 | if (timestamp) { 61 | Date currentDate = new Date(); 62 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); 63 | String formattedDate = dateFormat.format(currentDate); 64 | writer.write("[" + formattedDate + "] " + message + "\n"); 65 | } else { 66 | writer.write(message + "\n"); 67 | } 68 | if (border) { 69 | writer.write("--------------------------------------------------\n"); 70 | } 71 | writer.close(); 72 | } catch (IOException e) { 73 | e.printStackTrace(); 74 | } 75 | } 76 | 77 | 78 | public void authorized(Player player) { 79 | log("Operator [" + player.getName() + "] [" + player.getAddress().getHostName() + "] has been authorized.", true, false); 80 | if (plugin.getMainManager().getConfigManager().getMainConfig().notify_auth_success) { 81 | Notification notification = new Notification(player.getName(), NotificationType.AUTH_SUCCESS, ""); 82 | } 83 | } 84 | 85 | public void banned(Player player, String reason) { 86 | log("[" + player.getName() + "] [" + player.getAddress().getHostName() + "] has been banned. Reason: " + reason, true, true); 87 | if(plugin.getMainManager().getConfigManager().getMainConfig().notify_unauth_access) { 88 | Notification notification = new Notification(player.getName(), NotificationType.UNAUTH_ACCESS, "```Player : " + player.getName() + "\\u000A" + "IP : " + player.getAddress().getHostName() + "\\u000A" + "Reason : " + reason + "\\u000A" + "Status : Banned ```"); 89 | } 90 | } 91 | 92 | public void failedPassword(Player player) { 93 | log("Operator [" + player.getName() + "] [" + player.getAddress().getHostName() + "] has failed to enter the password.", true, false); 94 | if(plugin.getMainManager().getConfigManager().getMainConfig().notify_auth_failed){ 95 | Notification notification = new Notification(player.getName(), NotificationType.AUTH_FAIL, "```Player : " + player.getName() + "\\u000A" + "Reason : Failed to enter the password ```"); 96 | } 97 | } 98 | 99 | public void failedFactor(Player player) { 100 | log("Operator [" + player.getName() + "] [" + player.getAddress().getHostName() + "] has failed to enter the factor.", true, false); 101 | if (plugin.getMainManager().getConfigManager().getMainConfig().notify_auth_failed) { 102 | Notification notification = new Notification(player.getName(), NotificationType.AUTH_FAIL, "```Player : " + player.getName() + "\\u000A" + "Reason : Failed to submit the factor authentication ```"); 103 | } 104 | } 105 | 106 | public void loginfromDifferntIP(Player player, String oldIP, String newIP) { 107 | log("Operator [" + player.getName() + "] [" + oldIP + "] has logged in from a different IP [" + newIP + "] and Forced to perform Factor Verification.", true, false); 108 | } 109 | 110 | public void login(Player player) { 111 | log("Operator [" + player.getName() + "] [" + player.getAddress().getHostName() + "] has logged in.", true, false); 112 | if (plugin.getMainManager().getConfigManager().getMainConfig().notify_op_join) { 113 | Notification notification = new Notification(player.getName(), NotificationType.JOIN, ""); 114 | } 115 | } 116 | 117 | public void logout(Player player) { 118 | log("Operator [" + player.getName() + "] [" + player.getAddress().getHostName() + "] has logged out.", true, false); 119 | if (plugin.getMainManager().getConfigManager().getMainConfig().notify_op_leave) { 120 | Notification notification = new Notification(player.getName(), NotificationType.LEAVE, ""); 121 | } 122 | } 123 | 124 | public void command(Player player, String command) { 125 | 126 | if (cached("[" + player.getName() + "] >> " + command)){ 127 | return; 128 | } 129 | 130 | for (String commandBlacklist : plugin.getMainManager().getConfigManager().getMainConfig().commands_whitelist){ 131 | if (command.startsWith(commandBlacklist)){ 132 | return; 133 | } 134 | } 135 | 136 | log("[" + player.getName() + "] >> " + command, true, false); 137 | } 138 | 139 | public void message(Player player, String message) { 140 | if (cached("[" + player.getName() + "] >> " + message)){ 141 | return; 142 | } 143 | log("[" + player.getName() + "] >> " + message, true, false); 144 | } 145 | 146 | private boolean cached(String message){ 147 | 148 | //if theres something older than 3 secounds in the cache remove them 149 | 150 | if (cache.keySet() != null){ 151 | 152 | ArrayList expiredtimestamps = new ArrayList<>(); 153 | 154 | for (Timestamp timestamp : cache.keySet()){ 155 | if (timestamp.getTime() < System.currentTimeMillis() - 3000){ 156 | expiredtimestamps.add(timestamp); 157 | } 158 | } 159 | 160 | for (Timestamp timestamp : expiredtimestamps){ 161 | cache.remove(timestamp); 162 | } 163 | } 164 | 165 | 166 | for (String cachedMessage : cache.values()){ 167 | if (cachedMessage.equals(message)){ 168 | return true; 169 | } 170 | } 171 | 172 | Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 173 | cache.put(timestamp, message); 174 | 175 | return false; 176 | } 177 | 178 | } 179 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/LuckpermsCheck.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | import net.luckperms.api.LuckPerms; 4 | import net.luckperms.api.LuckPermsProvider; 5 | import net.luckperms.api.model.user.User; 6 | import net.luckperms.api.node.Node; 7 | import net.luckperms.api.node.NodeType; 8 | 9 | import java.util.UUID; 10 | 11 | public class LuckpermsCheck { 12 | public static boolean hasPermission(UUID uuid, String permission) { 13 | LuckPerms luckPerms = LuckPermsProvider.get(); 14 | User user = luckPerms.getUserManager().loadUser(uuid).join(); 15 | 16 | if (user == null) { 17 | return false; 18 | } 19 | 20 | for (Node node : user.getNodes()) { 21 | if (node.getType() == NodeType.PERMISSION && node.getKey().equals(permission)) { 22 | return true; 23 | } 24 | } 25 | 26 | return false; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/Metrics.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | /* 4 | * This Metrics class was auto-generated and can be copied into your project if you are 5 | * not using a build tool like Gradle or Maven for dependency management. 6 | * 7 | * IMPORTANT: You are not allowed to modify this class, except changing the package. 8 | * 9 | * Disallowed modifications include but are not limited to: 10 | * - Remove the option for users to opt-out 11 | * - Change the frequency for data submission 12 | * - Obfuscate the code (every obfuscator should allow you to make an exception for specific files) 13 | * - Reformat the code (if you use a linter, add an exception) 14 | * 15 | * Violations will result in a ban of your plugin and account from bStats. 16 | */ 17 | 18 | 19 | import java.io.BufferedReader; 20 | import java.io.ByteArrayOutputStream; 21 | import java.io.DataOutputStream; 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.io.InputStreamReader; 25 | import java.lang.reflect.Method; 26 | import java.net.URL; 27 | import java.nio.charset.StandardCharsets; 28 | import java.util.Arrays; 29 | import java.util.Collection; 30 | import java.util.HashSet; 31 | import java.util.Map; 32 | import java.util.Objects; 33 | import java.util.Set; 34 | import java.util.UUID; 35 | import java.util.concurrent.Callable; 36 | import java.util.concurrent.ScheduledExecutorService; 37 | import java.util.concurrent.ScheduledThreadPoolExecutor; 38 | import java.util.concurrent.TimeUnit; 39 | import java.util.function.BiConsumer; 40 | import java.util.function.Consumer; 41 | import java.util.function.Supplier; 42 | import java.util.logging.Level; 43 | import java.util.stream.Collectors; 44 | import java.util.zip.GZIPOutputStream; 45 | import javax.net.ssl.HttpsURLConnection; 46 | import org.bukkit.Bukkit; 47 | import org.bukkit.configuration.file.YamlConfiguration; 48 | import org.bukkit.entity.Player; 49 | import org.bukkit.plugin.Plugin; 50 | import org.bukkit.plugin.java.JavaPlugin; 51 | 52 | public class Metrics { 53 | 54 | private final Plugin plugin; 55 | 56 | private final MetricsBase metricsBase; 57 | 58 | /** 59 | * Creates a new Metrics instance. 60 | * 61 | * @param plugin Your plugin instance. 62 | * @param serviceId The id of the service. It can be found at What is my plugin id? 64 | */ 65 | public Metrics(JavaPlugin plugin, int serviceId) { 66 | this.plugin = plugin; 67 | // Get the config file 68 | File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); 69 | File configFile = new File(bStatsFolder, "config.yml"); 70 | YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); 71 | if (!config.isSet("serverUuid")) { 72 | config.addDefault("enabled", true); 73 | config.addDefault("serverUuid", UUID.randomUUID().toString()); 74 | config.addDefault("logFailedRequests", false); 75 | config.addDefault("logSentData", false); 76 | config.addDefault("logResponseStatusText", false); 77 | // Inform the server owners about bStats 78 | config 79 | .options() 80 | .header( 81 | "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" 82 | + "many people use their plugin and their total player count. It's recommended to keep bStats\n" 83 | + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" 84 | + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" 85 | + "anonymous.") 86 | .copyDefaults(true); 87 | try { 88 | config.save(configFile); 89 | } catch (IOException ignored) { 90 | } 91 | } 92 | // Load the data 93 | boolean enabled = config.getBoolean("enabled", true); 94 | String serverUUID = config.getString("serverUuid"); 95 | boolean logErrors = config.getBoolean("logFailedRequests", false); 96 | boolean logSentData = config.getBoolean("logSentData", false); 97 | boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); 98 | metricsBase = 99 | new MetricsBase( 100 | "bukkit", 101 | serverUUID, 102 | serviceId, 103 | enabled, 104 | this::appendPlatformData, 105 | this::appendServiceData, 106 | submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), 107 | plugin::isEnabled, 108 | (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), 109 | (message) -> this.plugin.getLogger().log(Level.INFO, message), 110 | logErrors, 111 | logSentData, 112 | logResponseStatusText); 113 | } 114 | 115 | /** Shuts down the underlying scheduler service. */ 116 | public void shutdown() { 117 | metricsBase.shutdown(); 118 | } 119 | 120 | /** 121 | * Adds a custom chart. 122 | * 123 | * @param chart The chart to add. 124 | */ 125 | public void addCustomChart(CustomChart chart) { 126 | metricsBase.addCustomChart(chart); 127 | } 128 | 129 | private void appendPlatformData(JsonObjectBuilder builder) { 130 | builder.appendField("playerAmount", getPlayerAmount()); 131 | builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); 132 | builder.appendField("bukkitVersion", Bukkit.getVersion()); 133 | builder.appendField("bukkitName", Bukkit.getName()); 134 | builder.appendField("javaVersion", System.getProperty("java.version")); 135 | builder.appendField("osName", System.getProperty("os.name")); 136 | builder.appendField("osArch", System.getProperty("os.arch")); 137 | builder.appendField("osVersion", System.getProperty("os.version")); 138 | builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); 139 | } 140 | 141 | private void appendServiceData(JsonObjectBuilder builder) { 142 | builder.appendField("pluginVersion", plugin.getDescription().getVersion()); 143 | } 144 | 145 | private int getPlayerAmount() { 146 | try { 147 | // Around MC 1.8 the return type was changed from an array to a collection, 148 | // This fixes java.lang.NoSuchMethodError: 149 | // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; 150 | Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); 151 | return onlinePlayersMethod.getReturnType().equals(Collection.class) 152 | ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() 153 | : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; 154 | } catch (Exception e) { 155 | // Just use the new method if the reflection failed 156 | return Bukkit.getOnlinePlayers().size(); 157 | } 158 | } 159 | 160 | public static class MetricsBase { 161 | 162 | /** The version of the Metrics class. */ 163 | public static final String METRICS_VERSION = "3.0.2"; 164 | 165 | private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; 166 | 167 | private final ScheduledExecutorService scheduler; 168 | 169 | private final String platform; 170 | 171 | private final String serverUuid; 172 | 173 | private final int serviceId; 174 | 175 | private final Consumer appendPlatformDataConsumer; 176 | 177 | private final Consumer appendServiceDataConsumer; 178 | 179 | private final Consumer submitTaskConsumer; 180 | 181 | private final Supplier checkServiceEnabledSupplier; 182 | 183 | private final BiConsumer errorLogger; 184 | 185 | private final Consumer infoLogger; 186 | 187 | private final boolean logErrors; 188 | 189 | private final boolean logSentData; 190 | 191 | private final boolean logResponseStatusText; 192 | 193 | private final Set customCharts = new HashSet<>(); 194 | 195 | private final boolean enabled; 196 | 197 | /** 198 | * Creates a new MetricsBase class instance. 199 | * 200 | * @param platform The platform of the service. 201 | * @param serviceId The id of the service. 202 | * @param serverUuid The server uuid. 203 | * @param enabled Whether or not data sending is enabled. 204 | * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and 205 | * appends all platform-specific data. 206 | * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and 207 | * appends all service-specific data. 208 | * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be 209 | * used to delegate the data collection to a another thread to prevent errors caused by 210 | * concurrency. Can be {@code null}. 211 | * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. 212 | * @param errorLogger A consumer that accepts log message and an error. 213 | * @param infoLogger A consumer that accepts info log messages. 214 | * @param logErrors Whether or not errors should be logged. 215 | * @param logSentData Whether or not the sent data should be logged. 216 | * @param logResponseStatusText Whether or not the response status text should be logged. 217 | */ 218 | public MetricsBase( 219 | String platform, 220 | String serverUuid, 221 | int serviceId, 222 | boolean enabled, 223 | Consumer appendPlatformDataConsumer, 224 | Consumer appendServiceDataConsumer, 225 | Consumer submitTaskConsumer, 226 | Supplier checkServiceEnabledSupplier, 227 | BiConsumer errorLogger, 228 | Consumer infoLogger, 229 | boolean logErrors, 230 | boolean logSentData, 231 | boolean logResponseStatusText) { 232 | ScheduledThreadPoolExecutor scheduler = 233 | new ScheduledThreadPoolExecutor(1, task -> new Thread(task, "bStats-Metrics")); 234 | // We want delayed tasks (non-periodic) that will execute in the future to be 235 | // cancelled when the scheduler is shutdown. 236 | // Otherwise, we risk preventing the server from shutting down even when 237 | // MetricsBase#shutdown() is called 238 | scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); 239 | this.scheduler = scheduler; 240 | this.platform = platform; 241 | this.serverUuid = serverUuid; 242 | this.serviceId = serviceId; 243 | this.enabled = enabled; 244 | this.appendPlatformDataConsumer = appendPlatformDataConsumer; 245 | this.appendServiceDataConsumer = appendServiceDataConsumer; 246 | this.submitTaskConsumer = submitTaskConsumer; 247 | this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; 248 | this.errorLogger = errorLogger; 249 | this.infoLogger = infoLogger; 250 | this.logErrors = logErrors; 251 | this.logSentData = logSentData; 252 | this.logResponseStatusText = logResponseStatusText; 253 | checkRelocation(); 254 | if (enabled) { 255 | // WARNING: Removing the option to opt-out will get your plugin banned from 256 | // bStats 257 | startSubmitting(); 258 | } 259 | } 260 | 261 | public void addCustomChart(CustomChart chart) { 262 | this.customCharts.add(chart); 263 | } 264 | 265 | public void shutdown() { 266 | scheduler.shutdown(); 267 | } 268 | 269 | private void startSubmitting() { 270 | final Runnable submitTask = 271 | () -> { 272 | if (!enabled || !checkServiceEnabledSupplier.get()) { 273 | // Submitting data or service is disabled 274 | scheduler.shutdown(); 275 | return; 276 | } 277 | if (submitTaskConsumer != null) { 278 | submitTaskConsumer.accept(this::submitData); 279 | } else { 280 | this.submitData(); 281 | } 282 | }; 283 | // Many servers tend to restart at a fixed time at xx:00 which causes an uneven 284 | // distribution of requests on the 285 | // bStats backend. To circumvent this problem, we introduce some randomness into 286 | // the initial and second delay. 287 | // WARNING: You must not modify and part of this Metrics class, including the 288 | // submit delay or frequency! 289 | // WARNING: Modifying this code will get your plugin banned on bStats. Just 290 | // don't do it! 291 | long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); 292 | long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); 293 | scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); 294 | scheduler.scheduleAtFixedRate( 295 | submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); 296 | } 297 | 298 | private void submitData() { 299 | final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); 300 | appendPlatformDataConsumer.accept(baseJsonBuilder); 301 | final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); 302 | appendServiceDataConsumer.accept(serviceJsonBuilder); 303 | JsonObjectBuilder.JsonObject[] chartData = 304 | customCharts.stream() 305 | .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) 306 | .filter(Objects::nonNull) 307 | .toArray(JsonObjectBuilder.JsonObject[]::new); 308 | serviceJsonBuilder.appendField("id", serviceId); 309 | serviceJsonBuilder.appendField("customCharts", chartData); 310 | baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); 311 | baseJsonBuilder.appendField("serverUUID", serverUuid); 312 | baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); 313 | JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); 314 | scheduler.execute( 315 | () -> { 316 | try { 317 | // Send the data 318 | sendData(data); 319 | } catch (Exception e) { 320 | // Something went wrong! :( 321 | if (logErrors) { 322 | errorLogger.accept("Could not submit bStats metrics data", e); 323 | } 324 | } 325 | }); 326 | } 327 | 328 | private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { 329 | if (logSentData) { 330 | infoLogger.accept("Sent bStats metrics data: " + data.toString()); 331 | } 332 | String url = String.format(REPORT_URL, platform); 333 | HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); 334 | // Compress the data to save bandwidth 335 | byte[] compressedData = compress(data.toString()); 336 | connection.setRequestMethod("POST"); 337 | connection.addRequestProperty("Accept", "application/json"); 338 | connection.addRequestProperty("Connection", "close"); 339 | connection.addRequestProperty("Content-Encoding", "gzip"); 340 | connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); 341 | connection.setRequestProperty("Content-Type", "application/json"); 342 | connection.setRequestProperty("User-Agent", "Metrics-Service/1"); 343 | connection.setDoOutput(true); 344 | try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { 345 | outputStream.write(compressedData); 346 | } 347 | StringBuilder builder = new StringBuilder(); 348 | try (BufferedReader bufferedReader = 349 | new BufferedReader(new InputStreamReader(connection.getInputStream()))) { 350 | String line; 351 | while ((line = bufferedReader.readLine()) != null) { 352 | builder.append(line); 353 | } 354 | } 355 | if (logResponseStatusText) { 356 | infoLogger.accept("Sent data to bStats and received response: " + builder); 357 | } 358 | } 359 | 360 | /** Checks that the class was properly relocated. */ 361 | private void checkRelocation() { 362 | // You can use the property to disable the check in your test environment 363 | if (System.getProperty("bstats.relocatecheck") == null 364 | || !System.getProperty("bstats.relocatecheck").equals("false")) { 365 | // Maven's Relocate is clever and changes strings, too. So we have to use this 366 | // little "trick" ... :D 367 | final String defaultPackage = 368 | new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); 369 | final String examplePackage = 370 | new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); 371 | // We want to make sure no one just copy & pastes the example and uses the wrong 372 | // package names 373 | if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) 374 | || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { 375 | throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); 376 | } 377 | } 378 | } 379 | 380 | /** 381 | * Gzips the given string. 382 | * 383 | * @param str The string to gzip. 384 | * @return The gzipped string. 385 | */ 386 | private static byte[] compress(final String str) throws IOException { 387 | if (str == null) { 388 | return null; 389 | } 390 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 391 | try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { 392 | gzip.write(str.getBytes(StandardCharsets.UTF_8)); 393 | } 394 | return outputStream.toByteArray(); 395 | } 396 | } 397 | 398 | public static class SimplePie extends CustomChart { 399 | 400 | private final Callable callable; 401 | 402 | /** 403 | * Class constructor. 404 | * 405 | * @param chartId The id of the chart. 406 | * @param callable The callable which is used to request the chart data. 407 | */ 408 | public SimplePie(String chartId, Callable callable) { 409 | super(chartId); 410 | this.callable = callable; 411 | } 412 | 413 | @Override 414 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 415 | String value = callable.call(); 416 | if (value == null || value.isEmpty()) { 417 | // Null = skip the chart 418 | return null; 419 | } 420 | return new JsonObjectBuilder().appendField("value", value).build(); 421 | } 422 | } 423 | 424 | public static class MultiLineChart extends CustomChart { 425 | 426 | private final Callable> callable; 427 | 428 | /** 429 | * Class constructor. 430 | * 431 | * @param chartId The id of the chart. 432 | * @param callable The callable which is used to request the chart data. 433 | */ 434 | public MultiLineChart(String chartId, Callable> callable) { 435 | super(chartId); 436 | this.callable = callable; 437 | } 438 | 439 | @Override 440 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 441 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 442 | Map map = callable.call(); 443 | if (map == null || map.isEmpty()) { 444 | // Null = skip the chart 445 | return null; 446 | } 447 | boolean allSkipped = true; 448 | for (Map.Entry entry : map.entrySet()) { 449 | if (entry.getValue() == 0) { 450 | // Skip this invalid 451 | continue; 452 | } 453 | allSkipped = false; 454 | valuesBuilder.appendField(entry.getKey(), entry.getValue()); 455 | } 456 | if (allSkipped) { 457 | // Null = skip the chart 458 | return null; 459 | } 460 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 461 | } 462 | } 463 | 464 | public static class AdvancedPie extends CustomChart { 465 | 466 | private final Callable> callable; 467 | 468 | /** 469 | * Class constructor. 470 | * 471 | * @param chartId The id of the chart. 472 | * @param callable The callable which is used to request the chart data. 473 | */ 474 | public AdvancedPie(String chartId, Callable> callable) { 475 | super(chartId); 476 | this.callable = callable; 477 | } 478 | 479 | @Override 480 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 481 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 482 | Map map = callable.call(); 483 | if (map == null || map.isEmpty()) { 484 | // Null = skip the chart 485 | return null; 486 | } 487 | boolean allSkipped = true; 488 | for (Map.Entry entry : map.entrySet()) { 489 | if (entry.getValue() == 0) { 490 | // Skip this invalid 491 | continue; 492 | } 493 | allSkipped = false; 494 | valuesBuilder.appendField(entry.getKey(), entry.getValue()); 495 | } 496 | if (allSkipped) { 497 | // Null = skip the chart 498 | return null; 499 | } 500 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 501 | } 502 | } 503 | 504 | public static class SimpleBarChart extends CustomChart { 505 | 506 | private final Callable> callable; 507 | 508 | /** 509 | * Class constructor. 510 | * 511 | * @param chartId The id of the chart. 512 | * @param callable The callable which is used to request the chart data. 513 | */ 514 | public SimpleBarChart(String chartId, Callable> callable) { 515 | super(chartId); 516 | this.callable = callable; 517 | } 518 | 519 | @Override 520 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 521 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 522 | Map map = callable.call(); 523 | if (map == null || map.isEmpty()) { 524 | // Null = skip the chart 525 | return null; 526 | } 527 | for (Map.Entry entry : map.entrySet()) { 528 | valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); 529 | } 530 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 531 | } 532 | } 533 | 534 | public static class AdvancedBarChart extends CustomChart { 535 | 536 | private final Callable> callable; 537 | 538 | /** 539 | * Class constructor. 540 | * 541 | * @param chartId The id of the chart. 542 | * @param callable The callable which is used to request the chart data. 543 | */ 544 | public AdvancedBarChart(String chartId, Callable> callable) { 545 | super(chartId); 546 | this.callable = callable; 547 | } 548 | 549 | @Override 550 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 551 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 552 | Map map = callable.call(); 553 | if (map == null || map.isEmpty()) { 554 | // Null = skip the chart 555 | return null; 556 | } 557 | boolean allSkipped = true; 558 | for (Map.Entry entry : map.entrySet()) { 559 | if (entry.getValue().length == 0) { 560 | // Skip this invalid 561 | continue; 562 | } 563 | allSkipped = false; 564 | valuesBuilder.appendField(entry.getKey(), entry.getValue()); 565 | } 566 | if (allSkipped) { 567 | // Null = skip the chart 568 | return null; 569 | } 570 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 571 | } 572 | } 573 | 574 | public static class DrilldownPie extends CustomChart { 575 | 576 | private final Callable>> callable; 577 | 578 | /** 579 | * Class constructor. 580 | * 581 | * @param chartId The id of the chart. 582 | * @param callable The callable which is used to request the chart data. 583 | */ 584 | public DrilldownPie(String chartId, Callable>> callable) { 585 | super(chartId); 586 | this.callable = callable; 587 | } 588 | 589 | @Override 590 | public JsonObjectBuilder.JsonObject getChartData() throws Exception { 591 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 592 | Map> map = callable.call(); 593 | if (map == null || map.isEmpty()) { 594 | // Null = skip the chart 595 | return null; 596 | } 597 | boolean reallyAllSkipped = true; 598 | for (Map.Entry> entryValues : map.entrySet()) { 599 | JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); 600 | boolean allSkipped = true; 601 | for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { 602 | valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); 603 | allSkipped = false; 604 | } 605 | if (!allSkipped) { 606 | reallyAllSkipped = false; 607 | valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); 608 | } 609 | } 610 | if (reallyAllSkipped) { 611 | // Null = skip the chart 612 | return null; 613 | } 614 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 615 | } 616 | } 617 | 618 | public abstract static class CustomChart { 619 | 620 | private final String chartId; 621 | 622 | protected CustomChart(String chartId) { 623 | if (chartId == null) { 624 | throw new IllegalArgumentException("chartId must not be null"); 625 | } 626 | this.chartId = chartId; 627 | } 628 | 629 | public JsonObjectBuilder.JsonObject getRequestJsonObject( 630 | BiConsumer errorLogger, boolean logErrors) { 631 | JsonObjectBuilder builder = new JsonObjectBuilder(); 632 | builder.appendField("chartId", chartId); 633 | try { 634 | JsonObjectBuilder.JsonObject data = getChartData(); 635 | if (data == null) { 636 | // If the data is null we don't send the chart. 637 | return null; 638 | } 639 | builder.appendField("data", data); 640 | } catch (Throwable t) { 641 | if (logErrors) { 642 | errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); 643 | } 644 | return null; 645 | } 646 | return builder.build(); 647 | } 648 | 649 | protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; 650 | } 651 | 652 | public static class SingleLineChart extends CustomChart { 653 | 654 | private final Callable callable; 655 | 656 | /** 657 | * Class constructor. 658 | * 659 | * @param chartId The id of the chart. 660 | * @param callable The callable which is used to request the chart data. 661 | */ 662 | public SingleLineChart(String chartId, Callable callable) { 663 | super(chartId); 664 | this.callable = callable; 665 | } 666 | 667 | @Override 668 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 669 | int value = callable.call(); 670 | if (value == 0) { 671 | // Null = skip the chart 672 | return null; 673 | } 674 | return new JsonObjectBuilder().appendField("value", value).build(); 675 | } 676 | } 677 | 678 | /** 679 | * An extremely simple JSON builder. 680 | * 681 | *

While this class is neither feature-rich nor the most performant one, it's sufficient enough 682 | * for its use-case. 683 | */ 684 | public static class JsonObjectBuilder { 685 | 686 | private StringBuilder builder = new StringBuilder(); 687 | 688 | private boolean hasAtLeastOneField = false; 689 | 690 | public JsonObjectBuilder() { 691 | builder.append("{"); 692 | } 693 | 694 | /** 695 | * Appends a null field to the JSON. 696 | * 697 | * @param key The key of the field. 698 | * @return A reference to this object. 699 | */ 700 | public JsonObjectBuilder appendNull(String key) { 701 | appendFieldUnescaped(key, "null"); 702 | return this; 703 | } 704 | 705 | /** 706 | * Appends a string field to the JSON. 707 | * 708 | * @param key The key of the field. 709 | * @param value The value of the field. 710 | * @return A reference to this object. 711 | */ 712 | public JsonObjectBuilder appendField(String key, String value) { 713 | if (value == null) { 714 | throw new IllegalArgumentException("JSON value must not be null"); 715 | } 716 | appendFieldUnescaped(key, "\"" + escape(value) + "\""); 717 | return this; 718 | } 719 | 720 | /** 721 | * Appends an integer field to the JSON. 722 | * 723 | * @param key The key of the field. 724 | * @param value The value of the field. 725 | * @return A reference to this object. 726 | */ 727 | public JsonObjectBuilder appendField(String key, int value) { 728 | appendFieldUnescaped(key, String.valueOf(value)); 729 | return this; 730 | } 731 | 732 | /** 733 | * Appends an object to the JSON. 734 | * 735 | * @param key The key of the field. 736 | * @param object The object. 737 | * @return A reference to this object. 738 | */ 739 | public JsonObjectBuilder appendField(String key, JsonObject object) { 740 | if (object == null) { 741 | throw new IllegalArgumentException("JSON object must not be null"); 742 | } 743 | appendFieldUnescaped(key, object.toString()); 744 | return this; 745 | } 746 | 747 | /** 748 | * Appends a string array to the JSON. 749 | * 750 | * @param key The key of the field. 751 | * @param values The string array. 752 | * @return A reference to this object. 753 | */ 754 | public JsonObjectBuilder appendField(String key, String[] values) { 755 | if (values == null) { 756 | throw new IllegalArgumentException("JSON values must not be null"); 757 | } 758 | String escapedValues = 759 | Arrays.stream(values) 760 | .map(value -> "\"" + escape(value) + "\"") 761 | .collect(Collectors.joining(",")); 762 | appendFieldUnescaped(key, "[" + escapedValues + "]"); 763 | return this; 764 | } 765 | 766 | /** 767 | * Appends an integer array to the JSON. 768 | * 769 | * @param key The key of the field. 770 | * @param values The integer array. 771 | * @return A reference to this object. 772 | */ 773 | public JsonObjectBuilder appendField(String key, int[] values) { 774 | if (values == null) { 775 | throw new IllegalArgumentException("JSON values must not be null"); 776 | } 777 | String escapedValues = 778 | Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); 779 | appendFieldUnescaped(key, "[" + escapedValues + "]"); 780 | return this; 781 | } 782 | 783 | /** 784 | * Appends an object array to the JSON. 785 | * 786 | * @param key The key of the field. 787 | * @param values The integer array. 788 | * @return A reference to this object. 789 | */ 790 | public JsonObjectBuilder appendField(String key, JsonObject[] values) { 791 | if (values == null) { 792 | throw new IllegalArgumentException("JSON values must not be null"); 793 | } 794 | String escapedValues = 795 | Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); 796 | appendFieldUnescaped(key, "[" + escapedValues + "]"); 797 | return this; 798 | } 799 | 800 | /** 801 | * Appends a field to the object. 802 | * 803 | * @param key The key of the field. 804 | * @param escapedValue The escaped value of the field. 805 | */ 806 | private void appendFieldUnescaped(String key, String escapedValue) { 807 | if (builder == null) { 808 | throw new IllegalStateException("JSON has already been built"); 809 | } 810 | if (key == null) { 811 | throw new IllegalArgumentException("JSON key must not be null"); 812 | } 813 | if (hasAtLeastOneField) { 814 | builder.append(","); 815 | } 816 | builder.append("\"").append(escape(key)).append("\":").append(escapedValue); 817 | hasAtLeastOneField = true; 818 | } 819 | 820 | /** 821 | * Builds the JSON string and invalidates this builder. 822 | * 823 | * @return The built JSON string. 824 | */ 825 | public JsonObject build() { 826 | if (builder == null) { 827 | throw new IllegalStateException("JSON has already been built"); 828 | } 829 | JsonObject object = new JsonObject(builder.append("}").toString()); 830 | builder = null; 831 | return object; 832 | } 833 | 834 | /** 835 | * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. 836 | * 837 | *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. 838 | * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). 839 | * 840 | * @param value The value to escape. 841 | * @return The escaped value. 842 | */ 843 | private static String escape(String value) { 844 | final StringBuilder builder = new StringBuilder(); 845 | for (int i = 0; i < value.length(); i++) { 846 | char c = value.charAt(i); 847 | if (c == '"') { 848 | builder.append("\\\""); 849 | } else if (c == '\\') { 850 | builder.append("\\\\"); 851 | } else if (c <= '\u000F') { 852 | builder.append("\\u000").append(Integer.toHexString(c)); 853 | } else if (c <= '\u001F') { 854 | builder.append("\\u00").append(Integer.toHexString(c)); 855 | } else { 856 | builder.append(c); 857 | } 858 | } 859 | return builder.toString(); 860 | } 861 | 862 | /** 863 | * A super simple representation of a JSON object. 864 | * 865 | *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not 866 | * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, 867 | * JsonObject)}. 868 | */ 869 | public static class JsonObject { 870 | 871 | private final String value; 872 | 873 | private JsonObject(String value) { 874 | this.value = value; 875 | } 876 | 877 | @Override 878 | public String toString() { 879 | return value; 880 | } 881 | } 882 | } 883 | } 884 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/OfflineScannerResultType.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | public enum OfflineScannerResultType { 4 | Authorized, 5 | BlackListedPerms, 6 | UnlistedOP, 7 | } 8 | 9 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/Utils/Prefix.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.Utils; 2 | 3 | public class Prefix { 4 | //this class provide temp prefix solution until we add messages.yml 5 | 6 | public static final String INFO = "§7[§bOPProtector§7] §f"; 7 | public static final String ERROR = "§7[§bOPProtector§7] §c"; 8 | public static final String WARNING = "§7[§bOPProtector§7] §e"; 9 | public static final String SUCCESS = "§7[§bOPProtector§7] §a"; 10 | public static final String DEBUG = "§7[§bOPProtector§7] §3"; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/VerificationProcess/PasswordFlash.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.VerificationProcess; 2 | 3 | 4 | import org.bukkit.ChatColor; 5 | import org.bukkit.Sound; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.scheduler.BukkitRunnable; 8 | import org.bukkit.scheduler.BukkitTask; 9 | import org.kasun.opprotector.OPProtector; 10 | import org.kasun.opprotector.Utils.CommandExecutor; 11 | import org.kasun.opprotector.Utils.Log; 12 | import org.kasun.opprotector.Utils.Prefix; 13 | 14 | import java.util.List; 15 | 16 | public class PasswordFlash { 17 | private BukkitTask titleTask; 18 | private BukkitTask countdownTask; 19 | private boolean stopTasks = false; 20 | private int countdownSeconds = 20; 21 | private Player player; 22 | private OPProtector plugin = OPProtector.getInstance(); 23 | public PasswordFlash(Player Player) { 24 | this.player = Player; 25 | } 26 | 27 | public void start(){ 28 | titleTask = new BukkitRunnable() { 29 | boolean flash = false; 30 | 31 | @Override 32 | public void run() { 33 | 34 | String titlebefore = ChatColor.GOLD + "OP" + ChatColor.YELLOW + "P"; 35 | String title = ChatColor.BOLD + titlebefore; 36 | 37 | if (flash) { 38 | player.sendTitle(title, ChatColor.RED + "█████████", 0, 15, 0);; 39 | Sound sound = Sound.BLOCK_NOTE_BLOCK_HARP; 40 | player.playSound(player.getLocation(), sound, 1, 1); 41 | } else { 42 | player.sendTitle("", "", 0, 20, 0); 43 | } 44 | 45 | flash = !flash; 46 | } 47 | }.runTaskTimer(plugin, 0, 10); // Change the flashing interval if desired (10 ticks = 0.5 seconds) 48 | 49 | countdownTask = new BukkitRunnable() { 50 | int remainingTime = plugin.getMainManager().getConfigManager().getMainConfig().interval_secounds; 51 | @Override 52 | public void run() { 53 | if (remainingTime > 0) { 54 | player.sendMessage(Prefix.ERROR + "You have " + remainingTime + " seconds to enter the password.(/pas )"); 55 | remainingTime--; 56 | } else { 57 | List commands = plugin.getMainManager().getConfigManager().getMainConfig().failed_password_timeout; 58 | CommandExecutor commandExecutor = new CommandExecutor(player, commands); 59 | Log log = plugin.getMainManager().getLog(); 60 | log.failedPassword(player); 61 | player.setOp(false); 62 | player.kickPlayer(ChatColor.RED + "You have failed to enter the password in time."); 63 | cancel(); 64 | } 65 | } 66 | }.runTaskTimer(plugin, 0, 20); // Change the countdown interval if desired (20 ticks = 1 second) 67 | } 68 | 69 | public void stopTasks() { 70 | stopTasks = true; 71 | if (titleTask != null) { 72 | titleTask.cancel(); 73 | } 74 | if (countdownTask != null) { 75 | countdownTask.cancel(); 76 | } 77 | } 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/VerificationProcess/PasswordVerification.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.VerificationProcess; 2 | 3 | 4 | 5 | import org.bukkit.entity.Player; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.inventories.PasswordGui; 8 | 9 | 10 | 11 | 12 | public class PasswordVerification { 13 | private OPProtector plugin = OPProtector.getInstance(); 14 | private boolean isgui; 15 | public PasswordVerification(Player player) { 16 | isgui = plugin.getMainManager().getConfigManager().getMainConfig().use_gui; 17 | if (isgui) { 18 | String password = plugin.getMainManager().getConfigManager().getOperatorConfig().getOperator(player.getName()).getPassword(); 19 | PasswordGui passwordGui = new PasswordGui("Enter The Password", password, player); 20 | passwordGui.show(); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/VerificationProcess/VerificationProcessManager.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.VerificationProcess; 2 | 3 | import org.bukkit.GameMode; 4 | import org.bukkit.entity.Player; 5 | import org.kasun.opprotector.AuthObjects.IpTable; 6 | import org.kasun.opprotector.OPProtector; 7 | import org.kasun.opprotector.Punishments.Ban; 8 | import org.kasun.opprotector.Punishments.Lockdown; 9 | import org.kasun.opprotector.Utils.CommandExecutor; 10 | 11 | import java.util.List; 12 | import java.util.concurrent.ConcurrentHashMap; 13 | 14 | public class VerificationProcessManager { 15 | private static final OPProtector plugin = OPProtector.getInstance(); 16 | private List blacklistedPermissions; 17 | private PasswordFlash passwordFlash; 18 | private ConcurrentHashMap verificationStatusMap; 19 | private boolean allowScanBlackListedPerms; 20 | private boolean allowScanCreative; 21 | private IpTable ipTable; 22 | 23 | public VerificationProcessManager() { 24 | verificationStatusMap = new ConcurrentHashMap<>(); 25 | } 26 | 27 | public void start(Player player) { 28 | blacklistedPermissions = plugin.getMainManager().getConfigManager().getMainConfig().blacklisted_permissions; 29 | allowScanCreative = plugin.getMainManager().getConfigManager().getMainConfig().scan_for_gamemode_creative; 30 | allowScanBlackListedPerms = plugin.getMainManager().getConfigManager().getMainConfig().scan_for_blacklisted_permissions; 31 | boolean opContainsInYml = plugin.getMainManager().getConfigManager().getOperatorConfig().isContains(player.getName()); 32 | 33 | if (allowScanBlackListedPerms) { 34 | checkForBlacklistedPermissions(player, opContainsInYml); 35 | } 36 | 37 | if (player.isOp() || (player.getGameMode() == GameMode.CREATIVE && allowScanCreative)) { 38 | checkForOp(player, opContainsInYml); 39 | } 40 | } 41 | 42 | private void checkForBlacklistedPermissions(Player player, boolean opContainsInYml) { 43 | for (String permission : blacklistedPermissions) { 44 | if (player.hasPermission(permission) && !opContainsInYml) { 45 | executeCommandsAndBanPlayer(player, "You aren't listed in OPProtector/operators.yml", "Unauthorized Access"); 46 | } 47 | } 48 | } 49 | 50 | private void checkForOp(Player player, boolean opContainsInYml) { 51 | if (!opContainsInYml) { 52 | executeCommandsAndBanPlayer(player, "You aren't listed in OPProtector/operators.yml", "Unauthorized Access"); 53 | } else if (plugin.getMainManager().getAuthorizedPlayers().isAuthorizedPlayer(player) && isPlayerVerified(player)) { 54 | announceVerified(player); 55 | } else if (isPlayerInPasswordVerification(player)) { 56 | // Do nothing 57 | } else if (isPlayerLoggedInUsingSameIp(player)) { 58 | announceVerified(player); 59 | verificationStatusMap.put(player.getName(), VerificationStatus.VERIFIED); 60 | } else if (!plugin.getMainManager().getConfigManager().getMainConfig().password_enabled) { 61 | announceVerified(player); 62 | verificationStatusMap.put(player.getName(), VerificationStatus.VERIFIED); 63 | } else { 64 | startPasswordVerificationProcess(player); 65 | } 66 | } 67 | 68 | private void executeCommandsAndBanPlayer(Player player, String banReason, String logReason) { 69 | List commands = plugin.getMainManager().getConfigManager().getMainConfig().not_in_operators_list; 70 | CommandExecutor commandExecutor = new CommandExecutor(player, commands); 71 | Ban ban = new Ban(player, banReason, logReason); 72 | plugin.getMainManager().getLog().banned(player, logReason); 73 | } 74 | 75 | private boolean isPlayerVerified(Player player) { 76 | return verificationStatusMap.containsKey(player.getName()) && verificationStatusMap.get(player.getName()) == VerificationStatus.VERIFIED; 77 | } 78 | 79 | private void announceVerified(Player player) { 80 | VerifiedAnnouncer verifiedAnnouncer = new VerifiedAnnouncer(player); 81 | } 82 | 83 | private boolean isPlayerInPasswordVerification(Player player) { 84 | return verificationStatusMap.containsKey(player.getName()) && verificationStatusMap.get(player.getName()) == VerificationStatus.IN_PASSWORD_VERIFICATION; 85 | } 86 | 87 | private boolean isPlayerLoggedInUsingSameIp(Player player) { 88 | ipTable = plugin.getMainManager().getIpTable(); 89 | return ipTable.IsContains(player) && ipTable.isIp(player); 90 | } 91 | 92 | private void startPasswordVerificationProcess(Player player) { 93 | verificationStatusMap.put(player.getName(), VerificationStatus.IN_PASSWORD_VERIFICATION); 94 | Lockdown lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 95 | lockdown.lockPlayer(player); 96 | PasswordVerification passwordVerification = new PasswordVerification(player); 97 | passwordFlash = new PasswordFlash(player); 98 | passwordFlash.start(); 99 | } 100 | 101 | public void setVerified(Player player) { 102 | passwordFlash.stopTasks(); 103 | plugin.getMainManager().getAuthorizedPlayers().addAuthorizedPlayer(player); 104 | 105 | ipTable = plugin.getMainManager().getIpTable(); 106 | ipTable.addIp(player); 107 | 108 | Lockdown lockdown = plugin.getMainManager().getPunishmentManager().getLockdown(); 109 | lockdown.unlockPlayer(player); 110 | 111 | announceVerified(player); 112 | plugin.getMainManager().getLog().authorized(player); 113 | verificationStatusMap.put(player.getName(), VerificationStatus.VERIFIED); 114 | } 115 | 116 | public PasswordFlash getPasswordFlash() { 117 | return passwordFlash; 118 | } 119 | 120 | public ConcurrentHashMap getVerificationStatusMap() { 121 | return verificationStatusMap; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/VerificationProcess/VerificationStatus.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.VerificationProcess; 2 | 3 | public enum VerificationStatus { 4 | NOT_VERIFIED, 5 | IN_PASSWORD_VERIFICATION, 6 | VERIFIED; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/VerificationProcess/VerifiedAnnouncer.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.VerificationProcess; 2 | 3 | 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.ChatColor; 6 | 7 | import org.bukkit.OfflinePlayer; 8 | import org.bukkit.Sound; 9 | import org.bukkit.entity.Player; 10 | 11 | import org.bukkit.scheduler.BukkitRunnable; 12 | import org.kasun.opprotector.OPProtector; 13 | import org.kasun.opprotector.Utils.Prefix; 14 | 15 | 16 | import java.util.Set; 17 | 18 | public class VerifiedAnnouncer { 19 | OPProtector plugin = OPProtector.getInstance(); 20 | 21 | public VerifiedAnnouncer(Player player) { 22 | 23 | 24 | 25 | sendTitile(player); 26 | 27 | 28 | Set operatorSet = plugin.getServer().getOperators(); 29 | 30 | for (OfflinePlayer offlinePlayer : operatorSet) { 31 | if (offlinePlayer.isOnline()) { 32 | Player onlinePlayer = offlinePlayer.getPlayer(); 33 | onlinePlayer.sendMessage(Prefix.ERROR + "[" + player.getName() + "] " + ChatColor.BLUE + "[" + player.getAddress().getHostName() + "]" + ChatColor.GRAY + " is Authorized, and now have Operator Access ✔"); 34 | 35 | } 36 | } 37 | } 38 | 39 | 40 | private void sendTitile(Player player){ 41 | 42 | //send animated title 43 | BukkitRunnable titleTask = new BukkitRunnable() { 44 | int tick = 0; 45 | String titlebefore = ChatColor.GOLD + "OP" + ChatColor.YELLOW + "P"; 46 | String title = ChatColor.BOLD + titlebefore; 47 | 48 | @Override 49 | public void run() { 50 | if (tick < 1) { 51 | 52 | player.sendTitle(title, ChatColor.GREEN + "█", 1, 10, 0); 53 | sleep(200); 54 | 55 | player.sendTitle(title, ChatColor.GREEN + "██", 0, 10, 0); 56 | sleep(200); 57 | 58 | player.sendTitle(title, ChatColor.GREEN + "███", 0, 10, 0); 59 | sleep(200); 60 | 61 | player.sendTitle(title, ChatColor.GREEN + "████", 0, 10, 0); 62 | sleep(200); 63 | 64 | player.sendTitle(title, ChatColor.GREEN + "█████", 0, 10, 0); 65 | sleep(200); 66 | 67 | player.sendTitle(title, ChatColor.GREEN + "██████", 0, 10, 0); 68 | sleep(200); 69 | 70 | player.sendTitle(title, ChatColor.GREEN + "███████", 0, 10, 0); 71 | sleep(200); 72 | 73 | player.sendTitle(title, ChatColor.GREEN + "████████", 0, 10, 0); 74 | sleep(200); 75 | 76 | player.sendTitle(title, ChatColor.GREEN + "█████████", 0, 10, 0); 77 | sleep(200); 78 | 79 | Sound sound = Sound.BLOCK_NOTE_BLOCK_HARP; 80 | player.playSound(player.getLocation(), sound, 5, 1); 81 | 82 | player.sendTitle(title, ChatColor.GREEN + "Authenticated!", 0, 100, 20); 83 | tick++; 84 | } else { 85 | // Animation is done, so cancel the task 86 | this.cancel(); 87 | } 88 | } 89 | 90 | private void sleep(int ms) { 91 | try{ 92 | Thread.sleep(ms); 93 | } catch (InterruptedException e) { 94 | e.printStackTrace(); 95 | } 96 | } 97 | 98 | }; 99 | 100 | titleTask.runTaskTimerAsynchronously(plugin, 0, 20*5); // 1 tick interval 101 | 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/org/kasun/opprotector/inventories/PasswordGui.java: -------------------------------------------------------------------------------- 1 | package org.kasun.opprotector.inventories; 2 | 3 | import com.github.stefvanschie.inventoryframework.gui.GuiItem; 4 | import com.github.stefvanschie.inventoryframework.gui.type.AnvilGui; 5 | import com.github.stefvanschie.inventoryframework.pane.StaticPane; 6 | import org.bukkit.ChatColor; 7 | import org.bukkit.Material; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | import org.bukkit.inventory.meta.ItemMeta; 11 | import org.kasun.opprotector.OPProtector; 12 | import org.kasun.opprotector.Utils.Prefix; 13 | import org.kasun.opprotector.VerificationProcess.VerificationProcessManager; 14 | import org.kasun.opprotector.VerificationProcess.VerificationStatus; 15 | 16 | 17 | public class PasswordGui { 18 | private String title; 19 | private String correctPassword; 20 | private Player player; 21 | private boolean isPasswordCorrect = false; 22 | private int attempts = 0; 23 | private VerificationProcessManager verificationProcessManager; 24 | OPProtector plugin = OPProtector.getInstance(); 25 | 26 | public PasswordGui(String title, String correctPassword, Player player) { 27 | this.title = title; 28 | this.correctPassword = correctPassword; 29 | this.player = player; 30 | verificationProcessManager = OPProtector.getInstance().getMainManager().getVerificationProcessManager(); 31 | } 32 | 33 | public void show(){ 34 | 35 | 36 | AnvilGui gui = new AnvilGui(title); 37 | ItemStack itemStack1 = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE); 38 | ItemMeta itemMeta1 = itemStack1.getItemMeta(); 39 | itemMeta1.setDisplayName(" "); 40 | itemStack1.setItemMeta(itemMeta1); 41 | 42 | GuiItem item1 = new GuiItem(itemStack1, event -> event.setCancelled(true)); 43 | StaticPane pane1 = new StaticPane(0, 0, 1, 1); 44 | pane1.addItem(item1, 0, 0); 45 | gui.getFirstItemComponent().addPane(pane1); 46 | 47 | ItemStack itemStack2 = new ItemStack(Material.LIME_STAINED_GLASS_PANE); 48 | ItemMeta itemMeta2 = itemStack2.getItemMeta(); 49 | itemMeta2.setDisplayName(ChatColor.GREEN + "Enter"); 50 | itemStack2.setItemMeta(itemMeta2); 51 | 52 | GuiItem item2 = new GuiItem(itemStack2, event -> { 53 | attempts++; 54 | if (gui.getRenameText().equals(correctPassword) || gui.getRenameText().equals(" " + correctPassword)){ 55 | 56 | isPasswordCorrect = true; 57 | player.closeInventory(); 58 | verificationProcessManager.setVerified(player); 59 | 60 | }else{ 61 | isPasswordCorrect = false; 62 | player.sendMessage(Prefix.ERROR + "You have entered the wrong password."); 63 | 64 | } 65 | }); 66 | StaticPane pane2 = new StaticPane(0, 0, 1, 1); 67 | pane2.addItem(item2, 0, 0); 68 | gui.getResultComponent().addPane(pane2); 69 | 70 | gui.setOnNameInputChanged(event -> { 71 | attempts++; 72 | if (event.equals(correctPassword) || event.equals(" " + correctPassword)){ 73 | if (attempts < 20){ 74 | isPasswordCorrect = true; 75 | player.closeInventory(); 76 | verificationProcessManager.setVerified(player); 77 | } 78 | } 79 | }); 80 | gui.setOnGlobalClick(event -> event.setCancelled(true)); 81 | 82 | // inventory close event 83 | /* 84 | gui.setOnClose(event -> { 85 | OPProtector plugin = OPProtector.getInstance(); 86 | if (verificationProcessManager.getVerificationStatusMap().get(player.getName()) == VerificationStatus.IN_PASSWORD_VERIFICATION){ 87 | gui.show(player); 88 | } 89 | 90 | }); 91 | */ 92 | 93 | gui.show(player); 94 | 95 | } 96 | 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | # 2 | # ██████╗ ██████╗ ██████╗ OPProtector 2023 (Operator Security System) 3 | # ██╔═══██╗██╔══██╗██╔══██╗ Version: 1.0.2 4 | # ██║ ██║██████╔╝██████╔╝ Contributors: Kasun Hapangama(ka0un) 5 | # ██║ ██║██╔═══╝ ██╔═══╝ GitHub:https://github.com/ka0un/OPProtector 6 | # ╚██████╔╝██║ ██║ Discord:https://dsc.gg/sundevs 7 | # ╚═════╝ ╚═╝ ╚═╝ Website: https://ka0un.github.io/OPProtector/ 8 | # 9 | 10 | #=============================================================================== 11 | # Password Settings 12 | #=============================================================================== 13 | 14 | password-settings: 15 | enabled: true # you can disable the password in the lobby server (since you have login system) 16 | session-hours: 24 # how many hours the password will be valid 17 | use-gui: true # use gui to enter the password 18 | interval-secounds: 20 # within how many secounds the player should enter the password 19 | pas-command: "pas" # the command to open the password gui 20 | encrypt-passwords: true # encrypt the passwords in the config file 21 | 22 | #=============================================================================== 23 | # Lockdown Settings 24 | #=============================================================================== 25 | 26 | lockdown-settings: 27 | block-player-move: true 28 | block-break-blocks: true 29 | block-place-blocks: true 30 | block-player-commands: true 31 | block-item-drop: true 32 | block-item-pickup: true 33 | block-damage: true 34 | allow-flight: false 35 | commands-whitelist: # commands that are allowed to execute while lockdown 36 | - "/pas" 37 | - "/auth" 38 | - "/register" 39 | - "/login" 40 | - "/changepassword" 41 | - "/changepass" 42 | 43 | #=============================================================================== 44 | # Scanner Settings 45 | #=============================================================================== 46 | 47 | scanner-settings: 48 | scan-on-join: true 49 | scan-on-player-op-command: true 50 | scan-on-console-op-command: true 51 | scan-from-live-scanner: true 52 | scan-for-blacklisted-permissions: true 53 | scan-for-gamemode-creative: true 54 | blacklisted-permissions: 55 | - "essentials.*" 56 | - "*" 57 | - "bungeecord.command.*" 58 | - "minecraft.command.*" 59 | - "bungeecord.*" 60 | - "fawe.*" 61 | - "worledit.*" 62 | - "bukkit.*" 63 | - "minecraft.*" 64 | - "worldedit.*" 65 | - "worldguard.*" 66 | - "luckperms.*" 67 | - "lp.*" 68 | - "luckperms.*" 69 | - "luckperms.trusteditor" 70 | - "luckperms.editor" 71 | - "luckperms.user.permission.set" 72 | - "lands.admin.*" 73 | - "lands.bypass.*" 74 | - "excellentcrates.*" 75 | - "citizens.admin" 76 | - "minecraft.admin" 77 | - "plhide.bypass" 78 | 79 | #=============================================================================== 80 | # Commands Settings 81 | #=============================================================================== 82 | 83 | commands-settings: 84 | not-in-operators-list: 85 | - 'deop %player%' 86 | 87 | have-blacklisted-perms: 88 | - 'deop %player%' 89 | 90 | admin-ip-changed: 91 | 92 | failed-password-timeout: 93 | 94 | #=============================================================================== 95 | # Discord Notifier Settings 96 | #=============================================================================== 97 | discord-notifications: 98 | discord-webhook: "" 99 | notify-op-join: false 100 | notify-op-leave: false 101 | notify-auth-success : false 102 | notify-auth-failed: false 103 | notify-unauth-access: false 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /src/main/resources/iplist.yml: -------------------------------------------------------------------------------- 1 | test: "ii" 2 | #do not make changes here manually, unless you know what you are doing -------------------------------------------------------------------------------- /src/main/resources/operators.yml: -------------------------------------------------------------------------------- 1 | KASUNhapangama2: 2 | password: password123 3 | commandBlacklist: 4 | - blacklistedCommand1 5 | - blacklistedCommand2 6 | 7 | Yourname: 8 | password: password123 9 | commandBlacklist: 10 | - blacklistedCommand1 11 | - blacklistedCommand2 12 | 13 | #make sure to do /opp reload after changeing this file -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: OPProtector 2 | version: '${project.version}' 3 | main: org.kasun.opprotector.OPProtector 4 | api-version: 1.13 5 | description: Operator Security Plugin That Provide Multi Factor Auth for staff members 6 | author: Kasun Hapangama 7 | website: https://opp.hapangama.com 8 | softdepend: 9 | - LuckPerms 10 | commands: 11 | pas: 12 | description: Operator Password 13 | usage: / password 14 | permission: opp.admin 15 | opp: 16 | description: OPProtector Admin Command 17 | usage: / 18 | permission: opp.admin 19 | aliases: 20 | - opprotector -------------------------------------------------------------------------------- /ver.txt: -------------------------------------------------------------------------------- 1 | Version: 1.0.5 2 | --------------------------------------------------------------------------------