diff --git a/src/main/java/Sdf1_login/ChatFilterManager.java b/src/main/java/Sdf1_login/ChatFilterManager.java index 59cb5de..f36a7e3 100644 --- a/src/main/java/Sdf1_login/ChatFilterManager.java +++ b/src/main/java/Sdf1_login/ChatFilterManager.java @@ -34,10 +34,218 @@ public class ChatFilterManager { new ConcurrentHashMap<>(); private final Map messages = new LinkedHashMap<>(); + // ★ 广告机检测:记录每个玩家发送链接的频率 + private final Map> linkSendHistory = + new ConcurrentHashMap<>(); + // ★ 挂机检测 + private final Map playerLastActiveTime = + new ConcurrentHashMap<>(); + // ★ 管理员邮件地址 + private String adminEmail = "admin@example.com"; private boolean notifyAdmin = true; private boolean notifyAll = false; private int muteDuration = 300; private boolean enabled = true; + + // ★ 验证码数据存储 + private final Map verificationData = new ConcurrentHashMap<>(); + + // ============================================================ + // ★ 新玩家验证码系统 + // ============================================================ + + static class VerificationData { + long createTime; + int a, b, op; // 0=加法, 1=减法, 2=乘法 + boolean completed; + + VerificationData(int a, int b, int op) { + this.createTime = System.currentTimeMillis(); + this.a = a; this.b = b; this.op = op; + } + + boolean isExpired() { + return System.currentTimeMillis() - createTime > 30000; + } + } + + /** 验证码结果:通过/失败 */ + public enum VerificationResult { + NEED_VERIFICATION, // 需要验证码 + PENDING, // 验证码进行中 + VERIFIED, // 已验证 + FAILED // 验证失败(消息吞噬) + } + + /** 验证码答案缓存,供外部判断是否为答案 */ + public boolean isPendingVerificationAnswer(String playerName, String msg) { + VerificationData vd = verificationData.get(playerName); + if (vd == null || vd.completed) return false; + // 尝试作为答案检查 + VerificationResult result = checkMathAnswer(playerName, msg); + return result != VerificationResult.FAILED; // 通过或进行中都是有效的答案输入 + } + + /** + * 检查玩家是否需要验证码 + */ + public VerificationResult checkNewPlayerVerification(Player p) { + String name = p.getName(); + + // 已验证过的玩家不需要 + if (verificationData.containsKey(name)) { + VerificationData vd = verificationData.get(name); + if (vd.completed) { + return VerificationResult.VERIFIED; + } + // 正在进行验证(等待答案) + if (vd.isExpired()) { + verificationData.remove(name); + return VerificationResult.NEED_VERIFICATION; + } + return VerificationResult.PENDING; + } + + // 检查玩家加入时间是否≤1小时 + if (!isNewPlayerUnder1Hour(p)) { + // 老玩家:快速验证并标记为已完成 + generateMathVerification(name); + verificationData.get(name).completed = true; + verificationData.remove(name); + return VerificationResult.VERIFIED; + } + + // 新玩家 → 需要验证 + return VerificationResult.NEED_VERIFICATION; + } + + /** + * 生成数学题验证码 + */ + public void generateMathVerification(String playerName) { + Random rand = new Random(); + int op = rand.nextInt(3); // 0=加, 1=减, 2=乘 + int a, b, answer; + + switch (op) { + case 0: // 加法 + a = rand.nextInt(10) + 1; + b = rand.nextInt(10) + 1; + answer = a + b; + break; + case 1: // 减法 + a = rand.nextInt(10) + 2; + b = rand.nextInt(a) + 1; + answer = a - b; + break; + default: // 乘法 + a = rand.nextInt(10) + 1; + b = rand.nextInt(10) + 1; + answer = a * b; + break; + } + + String opSymbol = switch (op) { + case 0 -> "+"; + case 1 -> "-"; + default -> "×"; + }; + + verificationData.put(playerName, new VerificationData(a, b, op)); + + org.bukkit.Bukkit.getScheduler().runTask(plugin, () -> { + Player p = org.bukkit.Bukkit.getPlayer(playerName); + if (p != null && p.isOnline()) { + p.sendMessage("§e§l[验证码] §f请回答: §e" + a + " " + opSymbol + " " + b + " = ?"); + p.sendMessage("§7(30秒内输入答案)"); + } + }); + } + + /** + * 检查玩家回答是否正确 + * @return VERIFIED=正确放行, FAILED=错误吞噬 + */ + public VerificationResult checkMathAnswer(String playerName, String answerStr) { + VerificationData vd = verificationData.get(playerName); + if (vd == null) return VerificationResult.VERIFIED; // 无验证码 → 放行 + + if (vd.isExpired()) { + verificationData.remove(playerName); + return VerificationResult.FAILED; // 过期 → 吞 + } + + try { + int ans = Integer.parseInt(answerStr.trim()); + int expected; + switch (vd.op) { + case 0 -> expected = vd.a + vd.b; + case 1 -> expected = vd.a - vd.b; + default -> expected = vd.a * vd.b; + } + + if (ans == expected) { + vd.completed = true; + verificationData.remove(playerName); + return VerificationResult.VERIFIED; + } else { + verificationData.remove(playerName); + return VerificationResult.FAILED; + } + } catch (NumberFormatException e) { + return VerificationResult.FAILED; // 非数字 → 吞 + } + } + + // ★ 临时缓存玩家未验证的消息,等验证通过后由插件代为广播 + public final Map pendingMessages = new ConcurrentHashMap<>(); + + /** 缓存玩家消息,等验证通过时代为广播 */ + public void cachePendingMessage(String playerName, String message) { + pendingMessages.put(playerName, message); + } + + /** 广播缓存的消息给全服 */ + public void broadcastCachedMessage(String playerName, String message) { + pendingMessages.remove(playerName); // 广播后清除缓存 + Bukkit.broadcastMessage(message); // 普通广播,无前缀 + } + + /** + * 清理过期的验证码 + */ + public void cleanupExpiredVerifications() { + long now = System.currentTimeMillis(); + verificationData.entrySet().removeIf(e -> { + if (e.getValue().isExpired() && !e.getValue().completed) { + return true; + } + return false; + }); + } + + /** + * 检查玩家是否为新玩家(加入≤1小时) + */ + public boolean isNewPlayerUnder1Hour(Player p) { + if (p == null || !p.isOnline()) return false; + try { + Main mainPlugin = (Main) plugin; + DatabaseManager db = mainPlugin.getDb(); + if (db == null) return true; // 默认放行 + Object regTimeObj = db.getField(p.getName(), "register_time"); + if (regTimeObj == null || ((Number) regTimeObj).longValue() == 0) { + return true; // 没有注册时间 → 新玩家 + } + long regTime = ((Number) regTimeObj).longValue() * 1000; + return (System.currentTimeMillis() - regTime) < 3600000; + } catch (Exception e) { + return true; // 出错时默认放行 + } + } + + + // ==================== 广告机检测 ==================== public boolean isEnabled() { return enabled; @@ -609,4 +817,106 @@ public class ChatFilterManager { || s.contains("启用") || s.contains("是"); } + + // ==================== 广告机检测 ==================== + + /** + * 检查消息是否包含第三方推广内容(邮件、游戏内推广等) + */ + public boolean isAdvertisingContent(String msg) { + String lower = msg.toLowerCase(); + // 检测关键词 + String[] keywords = {"群", "群号", "QQ", "qq群", "加群", "交流群", "服务器", "开服", "联机", "白嫖", "免费送", "折扣", "打折", "代充", "充值优惠", "外挂", "脚本", "辅助", "破解"}; + for (String kw : keywords) { + if (lower.contains(kw)) return true; + } + return false; + } + + /** + * 记录玩家发送链接的行为,检测广告机 + * @return 如果检测到广告机返回true + */ + public boolean checkAdBotBehavior(String playerName, String msg) { + long now = System.currentTimeMillis(); + + // 提取URL + List urls = extractUrls(msg); + if (urls.isEmpty()) return false; + + // 检查是否全部非白名单 + boolean hasNonWhitelisted = false; + for (String url : urls) { + if (!isWhitelisted(url)) { + hasNonWhitelisted = true; + break; + } + } + if (!hasNonWhitelisted) return false; + + // 检查是否包含推广关键词 + if (!isAdvertisingContent(msg)) return false; + + // 记录链接发送时间 + linkSendHistory.computeIfAbsent(playerName, k -> new ArrayList<>()).add(now); + + // 清理超过10分钟前的记录 + List history = linkSendHistory.get(playerName); + history.removeIf(t -> (now - t) > 600000); + + // 10分钟内发送超过3次非白名单链接 → 广告机 + if (history.size() >= 3) { + linkSendHistory.remove(playerName); + return true; // 检测到广告机 + } + + return false; + } + + /** + * 标记玩家活跃(用于挂机检测) + */ + public void markPlayerActive(String playerName) { + playerLastActiveTime.put(playerName, System.currentTimeMillis()); + } + + /** + * 检查玩家是否长时间挂机(超过5分钟) + */ + public boolean isPlayerIdle(String playerName, long idleThresholdMs) { + Long lastActive = playerLastActiveTime.get(playerName); + if (lastActive == null) return true; + return (System.currentTimeMillis() - lastActive) > idleThresholdMs; + } + + /** + * 发送管理员通知邮件 + */ + public void sendAdminNotification(String subject, String body) { + // 异步发送,不阻塞主线程 + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + try { + EmailManager emailMgr = ((Main) plugin).getEmail(); + if (emailMgr != null) { + emailMgr.sendBody(adminEmail, subject, body); + plugin.getLogger().info("[广告机检测] 已发送管理员通知: " + subject); + } + } catch (Exception e) { + plugin.getLogger().warning("[广告机检测] 发送管理员通知失败: " + e.getMessage()); + } + }); + } + + /** + * 定时检查空闲玩家 + */ + public void checkIdlePlayers() { + long idleThreshold = 5 * 60 * 1000L; // 5分钟 + org.bukkit.Bukkit.getOnlinePlayers().forEach(p -> { + if (isPlayerIdle(p.getName(), idleThreshold)) { + p.sendMessage("§c[系统] 您已连续空闲超过5分钟,即将被踢出"); + playerLastActiveTime.put(p.getName(), System.currentTimeMillis()); // 刷新计时 + } + }); + } } diff --git a/src/main/java/Sdf1_login/Main.java b/src/main/java/Sdf1_login/Main.java index f2611e5..3fe587b 100644 --- a/src/main/java/Sdf1_login/Main.java +++ b/src/main/java/Sdf1_login/Main.java @@ -394,6 +394,19 @@ public class Main extends JavaPlugin // 所有经济相关功能使用 BondManager(债券系统)替代 // ===== 9. 注册命令 ===== + + // 启动广告机/挂机检测定时器 + 验证码过期清理 + if (chatFilter != null) { + // 每60秒检查一次广告机和挂机 + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> { + chatFilter.checkIdlePlayers(); + }, 6000L, 6000L); + // 每5秒清理一次过期的验证码 + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> { + chatFilter.cleanupExpiredVerifications(); + }, 5000L, 5000L); + } + if (getCommand("sdf1_login") != null) { getCommand("sdf1_login") .setExecutor(this); @@ -2338,28 +2351,63 @@ public class Main extends JavaPlugin e.getPlayer().getName()); } - + // ===== 告示牌/编辑书/私信链接过滤 ===== + // 告示牌通过 onSignChange 拦截,编辑书通过 onPlayerEditBook 拦截 + // 私信通过 PlayerCommandPreprocessEvent 拦截(/tell, /msg, /w, /r) + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPrivateMessage(org.bukkit.event.player.PlayerCommandPreprocessEvent e) { + Player p = e.getPlayer(); + String cmd = e.getMessage().toLowerCase(); + boolean isTellCmd = cmd.startsWith("/tell ") || cmd.startsWith("/msg ") || cmd.startsWith("/w ") || cmd.startsWith("/r "); + if (!isTellCmd) return; + if (isFrozen(p)) return; + if (chatFilter == null || !chatFilter.isEnabled()) return; + if (chatFilter.isPlayerWhitelisted(p.getName())) return; + if (filterLinkInContent(p, e.getMessage())) e.setCancelled(true); + } + + @EventHandler + public void onSignChange(org.bukkit.event.block.SignChangeEvent e) { + Player p = e.getPlayer(); + if (isFrozen(p)) return; + if (chatFilter == null || !chatFilter.isEnabled()) return; + if (chatFilter.isPlayerWhitelisted(p.getName())) return; + String content = e.getLine(0) + e.getLine(1) + e.getLine(2) + e.getLine(3); + if (filterLinkInContent(p, content)) e.setCancelled(true); + } + + @EventHandler + public void onPlayerEditBook(org.bukkit.event.player.PlayerEditBookEvent e) { + Player p = e.getPlayer(); + if (isFrozen(p)) return; + if (chatFilter == null || !chatFilter.isEnabled()) return; + if (chatFilter.isPlayerWhitelisted(p.getName())) return; + StringBuilder content = new StringBuilder(); + // Paper 1.21.4: PlayerEditBookEvent 用 getNewBook() 取 ItemStack + // 通过反射调用 getNewBook() 因为 Paper API 未公开此方法 + try { + java.lang.reflect.Method m = e.getClass().getMethod("getNewBook"); + org.bukkit.inventory.ItemStack newBook = (org.bukkit.inventory.ItemStack) m.invoke(e); + if (newBook != null && newBook.hasItemMeta() && newBook.getItemMeta() instanceof org.bukkit.inventory.meta.BookMeta) { + for (String page : ((org.bukkit.inventory.meta.BookMeta)newBook.getItemMeta()).getPages()) { + content.append(page).append("\n"); + } + } + } catch (Exception ex) { + // 反射失败,不做拦截 + } + if (content.length() > 0 && filterLinkInContent(p, content.toString())) e.setCancelled(true); + } + @EventHandler public void onBlockPlace(BlockPlaceEvent e) { - if (isFrozen(e.getPlayer())) - e.setCancelled(true); - } - - @EventHandler - public void onDrop(PlayerDropItemEvent e) { if (isFrozen(e.getPlayer())) { e.setCancelled(true); return; } - ItemStack drop = - e.getItemDrop().getItemStack(); - if (isMenuSnowball(drop)) { - e.setCancelled(true); - } - // ★ Sdf1_game宝箱物品不干预,由Sdf1_game自行处理 } - // ★ 防止雪球菜单被投掷出去(弱网兜底 + 防止快乐恶魂投喂) @EventHandler(priority = EventPriority.HIGHEST) public void onProjectileLaunch( org.bukkit.event.entity.ProjectileLaunchEvent e) { @@ -2539,6 +2587,63 @@ public class Main extends JavaPlugin public void onChat(AsyncPlayerChatEvent e) { Player p = e.getPlayer(); String msg = e.getMessage(); + + // ★ 标记玩家活跃(用于挂机检测) + if (chatFilter != null) { + chatFilter.markPlayerActive(p.getName()); + } + + // ===== 新玩家验证码检查 ===== + if (chatFilter != null && chatFilter.isEnabled()) { + ChatFilterManager.VerificationResult vr = chatFilter.checkNewPlayerVerification(p); + + if (vr == ChatFilterManager.VerificationResult.NEED_VERIFICATION) { + // 第一次发送消息 → 触发验证码 + // 缓存玩家原始消息,等验证通过后由插件代为广播 + chatFilter.cachePendingMessage(p.getName(), msg); + chatFilter.generateMathVerification(p.getName()); + e.setCancelled(true); + return; // 消息拦截,验证码通过后再广播 + } + + if (vr == ChatFilterManager.VerificationResult.PENDING) { + // 验证码进行中,判断输入是否为答案 + ChatFilterManager.VerificationResult checkResult = chatFilter.checkMathAnswer(p.getName(), msg); + if (checkResult == ChatFilterManager.VerificationResult.VERIFIED) { + // 验证通过 → 广播缓存的消息 + // 消息格式:去掉插件前缀,像普通聊天消息一样 + String cachedMsg = chatFilter.pendingMessages.get(p.getName()); + if (cachedMsg != null) { + Bukkit.broadcastMessage(p.getDisplayName() + ": " + cachedMsg); + chatFilter.pendingMessages.remove(p.getName()); + } + e.setCancelled(true); // 阻止原事件重复广播 + return; + } else { + // 验证失败 → 吞噬缓存的消息 + chatFilter.pendingMessages.remove(p.getName()); + e.setCancelled(true); + return; + } + } + } + + // ===== 以下是正常放行后的逻辑(老玩家/已验证玩家) ===== + + // ★ 广告机检测(独立于URL过滤,覆盖私信/全场景) + if (chatFilter != null && chatFilter.checkAdBotBehavior(p.getName(), msg)) { + e.setCancelled(true); + p.kickPlayer("§c§l[反广告] 检测到广告机行为,已被踢出服务器"); + chatFilter.sendAdminNotification( + "[安全告警] 检测到广告机", + "玩家: " + p.getName() + "\n" + + "行为: 短时间内多次发送非白名单链接且包含推广内容\n" + + "IP: " + (p.getAddress() != null ? p.getAddress().getAddress().getHostAddress() : "未知") + + "\n时间: " + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()) + ); + return; + } + // ★ CDK/经济/债券输入拦截 — 必须在所有聊天处理之前 if (this.getCDK() != null && this.getCDK().isListening(p.getName())) { e.setCancelled(true); @@ -2639,6 +2744,21 @@ public class Main extends JavaPlugin return; } + // ===== 广告机检测 ===== + if (chatFilter.checkAdBotBehavior(p.getName(), msg)) { + e.setCancelled(true); + p.kickPlayer("§c§l[反广告] 检测到广告机行为,已被踢出服务器"); + // 发送管理员通知邮件 + chatFilter.sendAdminNotification( + "[安全告警] 检测到广告机", + "玩家: " + p.getName() + "\n" + + "行为: 短时间内多次发送非白名单链接且包含推广内容\n" + + "IP: " + (p.getAddress() != null ? p.getAddress().getAddress().getHostAddress() : "未知") + + "\n时间: " + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()) + ); + return; + } + // ===== URL检测 ===== List urls = chatFilter.extractUrls(msg); @@ -2698,6 +2818,21 @@ public class Main extends JavaPlugin // 处罚 chatFilter.applyPunishment(p, count); + + // ===== 广告机检测(独立于URL过滤) ===== + if (chatFilter.checkAdBotBehavior(p.getName(), msg)) { + e.setCancelled(true); + p.kickPlayer("§c§l[反广告] 检测到广告机行为,已被踢出服务器"); + chatFilter.sendAdminNotification( + "[安全告警] 检测到广告机", + "玩家: " + p.getName() + "\n" + + "行为: 短时间内多次发送非白名单链接且包含推广内容\n" + + "IP: " + (p.getAddress() != null ? p.getAddress().getAddress().getHostAddress() : "未知") + + "\n时间: " + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()) + ); + return; + } + // ===== 补签确认 ===== if (pendingBackCheck.containsKey( p.getName())) { @@ -2739,6 +2874,36 @@ public class Main extends JavaPlugin } +// ==================== 聊天过滤辅助方法 ==================== + + /** + * 过滤内容中的链接(用于告示牌、编辑书等非聊天场景) + * @return 是否有违规链接 + */ + private boolean filterLinkInContent(Player p, String content) { + if (content == null || content.isEmpty()) return false; + if (chatFilter == null || !chatFilter.isEnabled()) return false; + if (chatFilter.isPlayerWhitelisted(p.getName())) return false; + + List urls = chatFilter.extractUrls(content); + if (urls.isEmpty()) return false; + + List blocked = new ArrayList<>(); + for (String url : urls) { + if (!chatFilter.isWhitelisted(url)) { + blocked.add(url); + } + } + if (blocked.isEmpty()) return false; + + p.sendMessage(chatFilter.msg("chat_url_blocked", "url", blocked.get(0))); + chatFilter.incrementViolation(p.getName()); + int count = chatFilter.getViolationCount(p.getName()); + p.sendMessage(chatFilter.msg("chat_url_violation", "count", String.valueOf(count))); + chatFilter.applyPunishment(p, count); + return true; + } + // 在 getter 区域添加 public MenuManager getMenu() { return menu; diff --git a/src/main/java/Sdf1_login/TeleportManager.java b/src/main/java/Sdf1_login/TeleportManager.java index 1bb67db..abc78e4 100644 --- a/src/main/java/Sdf1_login/TeleportManager.java +++ b/src/main/java/Sdf1_login/TeleportManager.java @@ -232,7 +232,8 @@ public class TeleportManager implements Listener { if (senders == null || !senders.contains(sender)) { return false; } - String key = receiver + ":" + sender; + // ★ 修复:teleportRequestTimes 存的是 sender:receiver(发送者在前),不是 receiver:sender + String key = sender + ":" + receiver; return !isTeleportRequestExpired(key); }