diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 80bebc5..c42953d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,6 +11,10 @@ on: - 'deps/qqpd-bot-java/**' - 'server/**' - 'build.gradle.kts' + - 'gradle.properties' + - 'gradle/**' + - 'README.md' + - 'CHANGELOG.md' tags: - 'v*' # 匹配 v 开头的标签 pull_request: @@ -22,6 +26,10 @@ on: - 'deps/qqpd-bot-java/**' - 'server/**' - 'build.gradle.kts' + - 'gradle.properties' + - 'gradle/**' + - 'README.md' + - 'CHANGELOG.md' env: GRADLE_VERSION: 8.14.5 @@ -32,7 +40,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@v4 with: fetch-depth: 0 # 获取完整提交历史 submodules: recursive # 拉取 qqpd-bot-java 及其嵌套子模块 @@ -66,16 +74,34 @@ jobs: - name: Grant execute permission run: chmod +x gradlew - - name: Build with Gradle + - name: Build and test with Gradle env: WS_SERVER_URL: ${{ secrets.WS_SERVER_URL }} + run: ./gradlew build -Dorg.gradle.daemon=false + + - name: Verify release version and changelog + if: startsWith(github.ref, 'refs/tags/') + env: + TAG_NAME: ${{ github.ref_name }} run: | - ./gradlew build \ - -x test \ - -Dorg.gradle.daemon=false + set -euo pipefail + VERSION="${TAG_NAME#v}" + PROJECT_VERSION=$(./gradlew -q properties -Dorg.gradle.daemon=false | sed -n 's/^version: //p') + test "$VERSION" = "$PROJECT_VERSION" || { + echo "Tag $TAG_NAME does not match Gradle version $PROJECT_VERSION" >&2 + exit 1 + } + test "$VERSION" = "$(sed -n 's/^version=//p' gradle.properties)" || { + echo "Tag $TAG_NAME does not match gradle.properties" >&2 + exit 1 + } + grep -Fxq "## HuHoBot Penguin $TAG_NAME" CHANGELOG.md || { + echo "CHANGELOG.md has no heading for $TAG_NAME" >&2 + exit 1 + } - name: Upload Artifact - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: release-artifacts path: | @@ -101,30 +127,27 @@ jobs: - name: Extract release info id: changelog + env: + TAG_NAME: ${{ github.ref_name }} run: | - TAG_NAME=${GITHUB_REF#refs/tags/} - - # 修复:使用正确的标签格式匹配 - VERSION=${TAG_NAME#v} # 去除v前缀(如果CHANGELOG使用纯版本号) - - CHANGELOG_CONTENT=$(awk -v version="[v$VERSION]" ' - BEGIN {RS="## "; FS="\n"} - $1 ~ version { - sub(/\[.*\] - .*\n/, "") - gsub(/`/, "\\`") - gsub(/"/, "\\\"") - print - exit - } + set -euo pipefail + # Match literal headings, not regexes: release versions contain dots. + CHANGELOG_CONTENT=$(awk -v heading="## HuHoBot Penguin $TAG_NAME" ' + $0 == heading { found = 1; next } + found && /^## / { exit } + found { print } ' CHANGELOG.md) - - EOF_MARKER=$(openssl rand -base64 12) - echo "body<<$EOF_MARKER" >> $GITHUB_OUTPUT - echo "$CHANGELOG_CONTENT" >> $GITHUB_OUTPUT - echo "$EOF_MARKER" >> $GITHUB_OUTPUT - - # 添加标签名输出 - echo "tag_name=$TAG_NAME" >> $GITHUB_OUTPUT + test -n "$CHANGELOG_CONTENT" || { + echo "No release notes for $TAG_NAME" >&2 + exit 1 + } + EOF_MARKER=$(openssl rand -hex 16) + { + echo "body<<$EOF_MARKER" + printf '%s\n' "$CHANGELOG_CONTENT" + echo "$EOF_MARKER" + echo "tag_name=$TAG_NAME" + } >> "$GITHUB_OUTPUT" - name: Download Artifacts uses: actions/download-artifact@v4 @@ -133,9 +156,12 @@ jobs: path: artifacts - name: Setup workspace + env: + TAG_NAME: ${{ github.ref_name }} run: | - VERSION=${GITHUB_REF_NAME#v} # 去掉v前缀 - echo '{"latest":"$VERSION"}' > artifacts/latest.json + set -euo pipefail + VERSION="${TAG_NAME#v}" + printf '{"latest":"%s"}\n' "$VERSION" > artifacts/latest.json #- name: Upload to R2 # uses: ryand56/r2-upload-action@latest @@ -164,3 +190,5 @@ jobs: - 提交哈希: [${{ github.sha }}](${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }}) files: | artifacts/HuHoBot-*.jar + artifacts/latest.json + fail_on_unmatched_files: true diff --git a/CHANGELOG.md b/CHANGELOG.md index f398f38..04c0863 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,11 @@ -# HuHoBot Penguin v1.5.0 +## HuHoBot Penguin v1.5.1 + +- fix(security): 严格在触发平台事件及处理命令前校验群权限,移除“查信息”消息绕过;QQ 客户端关闭后不继续调用 SDK。 +- fix(audit): 敏感词二审只发送本地遮蔽后的文本,AI 输出再次本地过滤,并使用 JSON 序列化避免特殊字符破坏请求。 +- fix(platform): Spigot 网页保存配置后刷新运行态;Nukkit、Allay、BungeeCord、Velocity 不转发已取消的聊天事件。 +- fix(proxy): Redis 回调订阅断开后指数退避重连;规范发布元数据并在 CI 构建中执行单测。 + +## HuHoBot Penguin v1.5.0 - feat(group): 接入 QQ 群管理接口:群基本信息、机器人群内状态、入群申请列表与审批、群禁言查询/设置、群成员列表与详情、批量移除成员、群黑名单、入群自动审批策略列表 - feat(group): 新增群成员加入/退出与入群申请平台事件(`OnBotGroupMemberAdd` / `OnBotGroupMemberRemove` / `OnBotJoinRequest`),入群申请事件支持直接 `approve()` / `decline()` diff --git a/README.md b/README.md index 15c6ca7..fd72fb0 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ - **附属插件查询**:群内发送 `/附属插件` 可查看已安装的附属插件列表 - 群内 `/帮助` 以 Markdown 列出内置、扩展和自定义命令;管理员可见管理员命令分栏。 - `command-blacklist` 可阻止 QQ 普通执行、自定义命令展开结果或 WebUI 控制台经统一命令入口提交的黑名单命令;不会拦截其他插件、脚本或服务端控制台直接执行。 +- 安全提示:QQ 管理员拥有高权限服务器命令执行能力;请限制 `bot.groups`、审查管理员与自定义命令,**不要将默认空黑名单当成沙箱**。若只允许事先指定的群,设置 `bot.auto-add-groups: false`。群消息在转发到平台事件和处理命令之前先检查群许可。 ## 快速开始 @@ -55,18 +56,18 @@ cd PenguinClient 首次启动后会在插件数据目录生成 `config.yml`。关键配置项: -- **bot**:`app-id` / `secret` 为 QQ 机器人凭据;`groups` 为允许使用的群 OpenId 列表。默认收到未配置群消息时自动收录;网页配置页可选择群,单独覆盖命令启用、面板展示及优先级,留空覆盖会继承全局配置。 +- **bot**:`app-id` / `secret` 为 QQ 机器人凭据;`groups` 为允许使用的群 OpenId 列表。`auto-add-groups` 默认开启,收到新群消息会自动加入允许列表;只允许手动指定的群时务必关闭。网页配置页可选择群,单独覆盖命令启用、面板展示及优先级,留空覆盖会继承全局配置。 - **command-panel / commands**:设置管理员命令是否展示,以及每条命令的 `enable`、`pushMenu`、`priority`。优先级范围 `0`–`999`,数值越小越靠前;QQ 面板最多显示 20 条。隐藏管理员命令不改变实际执行权限。 - **command-blacklist**:服务器原生命令拒绝列表,支持斜杠、Minecraft 命名空间和已解析的命令别名;会检查自定义模板展开结果与 `execute ... run` 内层命令。默认空列表,不是服务端全局防火墙。 - **chat-format**:双向转发格式模板;`post-chat` 总开关;`start-with` 指定只有以该前缀开头的游戏消息才会转发(转发时移除前缀,留空表示全部转发)。 - **player-events**:配置进退服通知;`always-forward` 为 `true` 时忽略平台的隐藏、取消或登录状态判断,始终转发进退服事件。 - **whitelist**:白名单原生命令模板,代理平台需改为可路由到子服的命令。 - **admin**:管理员判定方式 `qq`(群主/群管理员)、`config`(手动名单)、`both`(任一满足),及手动名单 `openids`。 -- **audit**:OpenAI 兼容审核接口(`base-url` / `api-key` / `model`)。 +- **audit**:OpenAI 兼容审核接口(`base-url` / `api-key` / `model`);仅本地敏感词命中时触发 AI 二审,发送给第三方的是本地遮蔽后的文本,失败时回退本地遮蔽。外部网络调用可能使消息处理等待,生产环境请评估隐私和延迟。 - **custom-commands**:自定义指令列表,`permission: 0` 供所有成员执行,更高等级需要管理员;模板变量包括 `{params}`、`{group}`、`{user}`、`{name}`、`{nickname}`、`{0}`… 和 `&1`…;当前无 MC 角色绑定,`{name}` 暂以 QQ 昵称缓存回退。 - **features**:`enable-auth` 控制 QQ 头像认证;`full-amount` 控制是否默认全量转发;`group-member-events` 控制是否订阅群成员进退群与入群申请事件(默认关闭,修改后需重启服务器)。 -Spigot 版另有 `command-sender: Hybrid`,用于同时收集命令发送者输出与服务端日志。 +Spigot 版另有 `command-sender: Hybrid`,用于同时收集命令发送者输出与服务端日志;该模式通过全局日志采集,可能夹杂其他插件或并发命令输出,严格保密时请改用非 `Hybrid` 模式。Proxy 可选的 Redis 命令广播协议没有消息级鉴权/签名,必须使用隔离的私网 Redis 与 ACL/密码,并部署兼容的子服订阅端;发布成功不代表子服执行成功。 ### 扫码绑定 diff --git a/build.gradle.kts b/build.gradle.kts index bc3e42b..262c738 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,7 +5,8 @@ plugins { allprojects { group = "cn.huohuas001" - version = "1.5.1" + // Keep the existing fork release version in one place for every module. + version = providers.gradleProperty("version").get() repositories { // Resolve canonical artifacts from Maven Central first. Module-specific diff --git a/common/Bot/src/main/kotlin/cn/huohuas001/bot/QClient.kt b/common/Bot/src/main/kotlin/cn/huohuas001/bot/QClient.kt index 29d49fe..552998b 100644 --- a/common/Bot/src/main/kotlin/cn/huohuas001/bot/QClient.kt +++ b/common/Bot/src/main/kotlin/cn/huohuas001/bot/QClient.kt @@ -66,8 +66,8 @@ object QClient { syncGroupPanels() } - /** 是否已经启动过 QQ 客户端(不代表当前连接仍然可用)。 */ - fun isInitialized(): Boolean = ::starter.isInitialized + /** QQ 客户端运行态;shutdown 后保留的 SDK 实例不能继续发送请求。 */ + fun isInitialized(): Boolean = clientRunning && ::starter.isInitialized /** WebSocket transport state; an initialized SDK alone is not a healthy connection. */ fun connectionState(): String { @@ -143,7 +143,7 @@ object QClient { /** 将游戏聊天按配置格式发送到 bot.groups 中的 QQ 群。 */ fun broadcastGameMessage(playerName: String, message: String) { - if (!::starter.isInitialized) return + if (!isInitialized()) return val plugin = BotShared.getPlugin() val format = plugin.getChatFormat() if (!format.postChat) return @@ -164,7 +164,7 @@ object QClient { /** 按配置向所有 QQ 群发送玩家进服通知。 */ fun broadcastPlayerJoin(playerName: String) { - if (!::starter.isInitialized) return + if (!isInitialized()) return val plugin = BotShared.getPlugin() if (!plugin.getPlayerEventFormat().joinEnabled) return sendTextToGroups(plugin.formatPlayerJoinMessage(playerName), "发送玩家进服通知") @@ -172,7 +172,7 @@ object QClient { /** 按配置向所有 QQ 群发送玩家退服通知。 */ fun broadcastPlayerQuit(playerName: String) { - if (!::starter.isInitialized) return + if (!isInitialized()) return val plugin = BotShared.getPlugin() if (!plugin.getPlayerEventFormat().quitEnabled) return sendTextToGroups(plugin.formatPlayerQuitMessage(playerName), "发送玩家退服通知") @@ -193,7 +193,7 @@ object QClient { /** 向 bot.groups 中配置的所有 QQ 群发送普通文本。 */ fun sendText(text: String) { - if (!::starter.isInitialized) { + if (!isInitialized()) { BotShared.getPlugin().log_warning("QQ 机器人未启动,无法发送文本") return } @@ -203,7 +203,7 @@ object QClient { /** 主动向指定 QQ 群发送普通文本。 */ fun sendText(groupOpenId: String, text: String): Boolean { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法发送文本") return false } @@ -226,7 +226,7 @@ object QClient { /** 向 bot.groups 中配置的所有 QQ 群发送自定义 Markdown。 */ fun sendMarkdown(markdownContent: String, keyboard: Keyboard? = null) { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法发送 Markdown") return } @@ -258,7 +258,7 @@ object QClient { keyboard: Keyboard? = null ): Boolean { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法发送 Markdown") return false } @@ -313,7 +313,7 @@ object QClient { keyboard: Keyboard? = null ): String? { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法回复 Markdown") return null } @@ -363,7 +363,7 @@ object QClient { text: String ): String? { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法回复文本") return null } @@ -401,7 +401,7 @@ object QClient { /** 回复指定群消息,同时发送文本和网络图片。 */ fun replyWithImg(event: GroupMessageEvent, text: String, imgUrl: String): Boolean { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法回复图片消息") return false } @@ -435,7 +435,7 @@ object QClient { */ fun respondInteraction(interactionId: String, code: Int): Boolean { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法响应互动事件") return false } @@ -455,7 +455,7 @@ object QClient { */ fun recallMessage(groupOpenId: String, messageId: String): Boolean { val plugin = BotShared.getPlugin() - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法撤回消息") return false } @@ -669,7 +669,7 @@ object QClient { private fun groupApi(action: String, groupOpenId: String?, block: (GroupBaseV2) -> T?): T? { val plugin = BotShared.getPlugin() if (groupOpenId != null && groupOpenId.isBlank()) return null - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法$action") return null } @@ -685,7 +685,7 @@ object QClient { private fun groupAction(action: String, groupOpenId: String, block: (GroupBaseV2) -> Unit): Boolean { val plugin = BotShared.getPlugin() if (groupOpenId.isBlank()) return false - if (!::starter.isInitialized) { + if (!isInitialized()) { plugin.log_warning("QQ 机器人未启动,无法$action") return false } diff --git a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupEventHandler.kt b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupEventHandler.kt index 4c906a2..990497f 100644 --- a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupEventHandler.kt +++ b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupEventHandler.kt @@ -24,21 +24,29 @@ class GroupEventHandler( /** QQ 群成员加入时触发。 */ @EventReceiver fun onGroupMemberAdd(event: GroupMemberAddEvent) { + if (!isAllowedGroup(event.groupOpenId ?: event.groupId)) return dispatch("群成员加入") { plugin.onBotGroupMemberAdd(event) } } /** QQ 群成员退出或被移出时触发。 */ @EventReceiver fun onGroupMemberRemove(event: GroupMemberRemoveEvent) { + if (!isAllowedGroup(event.groupOpenId ?: event.groupId)) return dispatch("群成员退出") { plugin.onBotGroupMemberRemove(event) } } /** QQ 用户申请加群时触发。 */ @EventReceiver fun onGroupJoinRequest(event: GroupJoinRequestEvent) { + if (!isAllowedGroup(event.groupOpenId ?: event.groupId)) return dispatch("入群申请") { plugin.onBotGroupJoinRequest(event) } } + private fun isAllowedGroup(groupId: String?): Boolean { + val allowed = plugin.getGroupOpenIdList() + return !groupId.isNullOrBlank() && (allowed.isEmpty() || groupId in allowed) + } + private inline fun dispatch(name: String, action: () -> Boolean) { try { action() diff --git a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupMessageHandler.kt b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupMessageHandler.kt index ebc5e40..20d3c7f 100644 --- a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupMessageHandler.kt +++ b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/GroupMessageHandler.kt @@ -49,19 +49,20 @@ class GroupMessageHandler( @EventReceiver fun onGroupMessage(event: GroupMessageEvent) { val groupId = event.groupOpenId ?: event.groupId - if (plugin.isAutoAddGroupsEnabled() || isAllowedGroup(groupId)) plugin.observeGroup(groupId, null) + if (groupId.isBlank()) return + // 群权限检查必须先于任何平台事件、命令或全量转发;不能以消息内容为由绕过。 + // 保留显式开启的自动加群行为,但关闭时不得观察或分发未授权群消息。 + if (!isAllowedGroup(groupId) && !plugin.isAutoAddGroupsEnabled()) return + plugin.observeGroup(groupId, null) + if (!isAllowedGroup(groupId)) return val content = event.rawMessage.content ?: return val sender = event.sender val senderName = sender?.username.orEmpty() val senderOpenId = sender?.openid ?: sender?.id if (senderOpenId != null && senderName.isNotBlank()) NicknameManager.put(senderOpenId, senderName) val messageSequence = event.msgSeq - // 在群限制和内置指令处理之前通知平台适配器,保证“收到消息”事件不会漏掉命令消息。 + // 对已授权群的所有消息(包括命令)通知平台适配器。 val receivedMessageCancelled = plugin.onBotReceivedGroupMessage(event, messageSequence) - - if (!content.contains("查信息")) { - if (!isAllowedGroup(groupId)) return - } when (dispatchCommand(event)) { BaseCommand.DispatchResult.CUSTOM_COMMAND -> { val customCommandCancelled = plugin.onBotCommand(event, messageSequence) diff --git a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/InteractionHandler.kt b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/InteractionHandler.kt index 67c773e..c5a8c47 100644 --- a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/InteractionHandler.kt +++ b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/InteractionHandler.kt @@ -18,6 +18,13 @@ class InteractionHandler( @EventReceiver fun onInteractionCreate(event: InterActionEvent) { try { + val interaction = event.interAction + val isGroup = interaction?.scene == "group" || interaction?.chatType == 1 + if (isGroup) { + val groupId = interaction?.groupOpenid + val allowed = plugin.getGroupOpenIdList() + if (groupId.isNullOrBlank() || allowed.isNotEmpty() && groupId !in allowed) return + } plugin.onBotInteractionCreate(event) } catch (error: Exception) { plugin.log_error("互动事件处理异常: ${error.message}") diff --git a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/commands/SensitiveFilter.kt b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/commands/SensitiveFilter.kt index 6e4f2be..68c5e3a 100644 --- a/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/commands/SensitiveFilter.kt +++ b/common/Bot/src/main/kotlin/cn/huohuas001/bot/events/commands/SensitiveFilter.kt @@ -8,24 +8,40 @@ import java.net.URL object SensitiveFilter { private val defaults = listOf("傻逼", "操你", "色情", "反动", "赌博") + private fun redact(value: String, words: List): String = + (defaults + words).filter(String::isNotEmpty).distinct().fold(value) { text, word -> + text.replace(word, "*".repeat(word.length), ignoreCase = true) + } + fun filter(value: String, baseUrl: String? = null, apiKey: String? = null, model: String? = null, words: List = emptyList()): String { - var local = value - (defaults + words).distinct().forEach { word -> local = local.replace(word, "*".repeat(word.length), ignoreCase = true) } + val local = redact(value, words) if (local == value || baseUrl.isNullOrBlank() || apiKey.isNullOrBlank()) return local + // 仅向已显式配置的审核接口发送本地替换后的文本,不泄露已命中的原始敏感词。 + val connection = try { + URL(baseUrl.trimEnd('/') + "/chat/completions").openConnection() as HttpURLConnection + } catch (_: Exception) { return local } return try { - val connection = URL(baseUrl.trimEnd('/') + "/chat/completions").openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.doOutput = true connection.connectTimeout = 5000 connection.readTimeout = 10000 connection.setRequestProperty("Content-Type", "application/json") connection.setRequestProperty("Authorization", "Bearer $apiKey") - val body = "{\"model\":\"${escape(model ?: "gpt-4o-mini")}\",\"messages\":[{\"role\":\"system\",\"content\":\"你是敏感词二审工具,只输出替换敏感内容后的完整原文。\"},{\"role\":\"user\",\"content\":\"${escape(value)}\"}],\"temperature\":0.1}" + val body = JSON.toJSONString(mapOf( + "model" to (model ?: "gpt-4o-mini"), + "messages" to listOf( + mapOf("role" to "system", "content" to "你是敏感词二审工具,只输出替换敏感内容后的完整原文。"), + mapOf("role" to "user", "content" to local) + ), + "temperature" to 0.1 + )) connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) } val response = connection.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() } - JSON.parseObject(response).getJSONArray("choices")?.getJSONObject(0)?.getJSONObject("message")?.getString("content")?.trim() ?: local + val reviewed = JSON.parseObject(response).getJSONArray("choices") + ?.getJSONObject(0)?.getJSONObject("message")?.getString("content")?.trim() + // AI 不能恢复本地已遮蔽的敏感词;不可信的生成结果继续经过本地词库。 + reviewed?.takeIf(String::isNotEmpty)?.let { redact(it, words) } ?: local } catch (_: Exception) { local } + finally { connection.disconnect() } } - - private fun escape(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") } diff --git a/common/Bot/src/test/kotlin/cn/huohuas001/bot/SensitiveFilterTest.kt b/common/Bot/src/test/kotlin/cn/huohuas001/bot/SensitiveFilterTest.kt new file mode 100644 index 0000000..e2f7063 --- /dev/null +++ b/common/Bot/src/test/kotlin/cn/huohuas001/bot/SensitiveFilterTest.kt @@ -0,0 +1,22 @@ +package cn.huohuas001.bot + +import cn.huohuas001.bot.events.commands.SensitiveFilter +import kotlin.test.Test +import kotlin.test.assertEquals + +class SensitiveFilterTest { + @Test + fun `local words are always redacted without an audit endpoint`() { + assertEquals("**测试", SensitiveFilter.filter("坏词测试", words = listOf("坏词"))) + } + + @Test + fun `empty custom words do not change input`() { + assertEquals("hello", SensitiveFilter.filter("hello", words = listOf(""))) + } + + @Test + fun `invalid endpoint fails closed to local redaction`() { + assertEquals("**测试", SensitiveFilter.filter("坏词测试", baseUrl = "not a URL", apiKey = "secret", words = listOf("坏词"))) + } +} diff --git a/gradle.properties b/gradle.properties index b9a3437..b35ab48 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ group=cn.huohuas001 -version=1.3.0 +version=1.5.1 org.gradle.configuration-cache=true org.gradle.parallel=true org.gradle.caching=true diff --git a/server/Allay/src/main/kotlin/cn/huohuas001/huhobotPenguin/allay/HuHoBotAllay.kt b/server/Allay/src/main/kotlin/cn/huohuas001/huhobotPenguin/allay/HuHoBotAllay.kt index 7be1e25..deab0cc 100644 --- a/server/Allay/src/main/kotlin/cn/huohuas001/huhobotPenguin/allay/HuHoBotAllay.kt +++ b/server/Allay/src/main/kotlin/cn/huohuas001/huhobotPenguin/allay/HuHoBotAllay.kt @@ -39,6 +39,8 @@ import java.util.concurrent.CompletableFuture class HuHoBotAllay : Plugin(), HuHoBot { private lateinit var config: YamlConfig private val configFile = File("plugins/HuHoBot/config.yml") + // 标记插件自身的调度回调,避免回调内再次提交任务并阻塞等待自身。 + private val eventDispatchThread = ThreadLocal.withInitial { false } override fun onLoad() { config = YamlConfig(configFile, 19132, ::log_warning) @@ -58,6 +60,7 @@ class HuHoBotAllay : Plugin(), HuHoBot { @EventHandler private fun onPlayerChat(event: PlayerChatEvent) { + if (event.isCancelled) return QClient.broadcastGameMessage(event.player.displayName, event.message) } @@ -173,16 +176,21 @@ class HuHoBotAllay : Plugin(), HuHoBot { private fun callSyncEvent(event: T): T { return try { - val future = CompletableFuture() - submit { - try { - Server.getInstance().eventBus.callEvent(event) - future.complete(event) - } catch (error: Throwable) { - future.completeExceptionally(error) + if (eventDispatchThread.get()) { + Server.getInstance().eventBus.callEvent(event) + } else { + val future = CompletableFuture() + submit { + try { + Server.getInstance().eventBus.callEvent(event) + future.complete(Unit) + } catch (error: Throwable) { + future.completeExceptionally(error) + } } + future.get() } - future.get() + event } catch (error: Exception) { log_error("同步触发 Allay 事件失败: ${error.message}") event @@ -247,18 +255,28 @@ class HuHoBotAllay : Plugin(), HuHoBot { Server.getInstance().messageChannel.broadcastMessage(msg) } + private fun onScheduler(task: Runnable) = HuHoBotTask(Runnable { + val wasDispatching = eventDispatchThread.get() + eventDispatchThread.set(true) + try { + task.run() + } finally { + eventDispatchThread.set(wasDispatching) + } + }) + override fun submit(task: Runnable): Cancelable { - Server.getInstance().scheduler.scheduleDelayed(this, HuHoBotTask(task), 0) + Server.getInstance().scheduler.scheduleDelayed(this, onScheduler(task), 0) return NoopCancelable() } override fun submitLater(delay: Long, task: Runnable): Cancelable { - Server.getInstance().scheduler.scheduleDelayed(this, HuHoBotTask(task), delay.toInt()) + Server.getInstance().scheduler.scheduleDelayed(this, onScheduler(task), delay.toInt()) return NoopCancelable() } override fun submitTimer(delay: Long, period: Long, task: Runnable): Cancelable { - Server.getInstance().scheduler.scheduleRepeating(this, HuHoBotTask(task), period.toInt()) + Server.getInstance().scheduler.scheduleRepeating(this, onScheduler(task), period.toInt()) return NoopCancelable() } diff --git a/server/Nukkit/src/main/kotlin/cn/huohuas001/huhobotPenguin/nukkit/events/PlayerEvents.kt b/server/Nukkit/src/main/kotlin/cn/huohuas001/huhobotPenguin/nukkit/events/PlayerEvents.kt index c1a6127..70083f7 100644 --- a/server/Nukkit/src/main/kotlin/cn/huohuas001/huhobotPenguin/nukkit/events/PlayerEvents.kt +++ b/server/Nukkit/src/main/kotlin/cn/huohuas001/huhobotPenguin/nukkit/events/PlayerEvents.kt @@ -3,13 +3,14 @@ package cn.huohuas001.huhobotPenguin.nukkit.events import cn.huohuas001.bot.QClient import cn.huohuas001.huhobotPenguin.nukkit.HuHoBotNukkit import cn.nukkit.event.EventHandler +import cn.nukkit.event.EventPriority import cn.nukkit.event.Listener import cn.nukkit.event.player.PlayerChatEvent import cn.nukkit.event.player.PlayerJoinEvent import cn.nukkit.event.player.PlayerQuitEvent class PlayerEvents(private val plugin: HuHoBotNukkit) : Listener { - @EventHandler + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onChat(event: PlayerChatEvent) { QClient.broadcastGameMessage(event.player.name, event.message) } diff --git a/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/bungee/events/GameChat.kt b/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/bungee/events/GameChat.kt index 894b0be..e5ce399 100644 --- a/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/bungee/events/GameChat.kt +++ b/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/bungee/events/GameChat.kt @@ -9,9 +9,9 @@ import net.md_5.bungee.api.plugin.Listener import net.md_5.bungee.event.EventHandler class GameChat : Listener { - @EventHandler + @EventHandler(priority = 64) fun onPlayerChat(event: ChatEvent) { - if (event.isCommand || event.isProxyCommand) return + if (event.isCancelled || event.isCommand || event.isProxyCommand) return val sender = event.sender if (sender is ProxiedPlayer) QClient.broadcastGameMessage(sender.name, event.message) } diff --git a/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/proxy/redis/RedisManager.kt b/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/proxy/redis/RedisManager.kt index 74583f7..3b6907a 100644 --- a/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/proxy/redis/RedisManager.kt +++ b/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/proxy/redis/RedisManager.kt @@ -7,7 +7,10 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.runInterruptible import redis.clients.jedis.Jedis import redis.clients.jedis.JedisPool import redis.clients.jedis.JedisPoolConfig @@ -27,14 +30,19 @@ class RedisManager(private val plugin: HuHoBotProxy) { private val subscriberScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private var subscriberJob: Job? = null + @Volatile + private var stopped = false @Volatile private var pubSub: JedisPubSub? = null + @Volatile + private var subscriberConnection: Jedis? = null var commandCallback: CommandCallback? = null private set fun connect(host: String, port: Int, password: String?) { + if (stopped) return try { val poolConfig = JedisPoolConfig().apply { maxTotal = 10 @@ -66,31 +74,61 @@ class RedisManager(private val plugin: HuHoBotProxy) { private fun startCallbackListener(host: String, port: Int, password: String?) { subscriberJob = subscriberScope.launch { - try { - Jedis(host, port).use { jedis -> - if (!password.isNullOrEmpty()) jedis.auth(password) - pubSub = object : JedisPubSub() { - override fun onMessage(channel: String, message: String) { - commandCallback?.handleCallback(message) + var retryDelay = 1_000L + while (isActive && !stopped) { + try { + // subscribe 是阻塞调用;协程取消时中断并关闭当前 Jedis 连接。 + runInterruptible { + Jedis(host, port).use { jedis -> + subscriberConnection = jedis + try { + if (!password.isNullOrEmpty()) jedis.auth(password) + val subscription = object : JedisPubSub() { + override fun onMessage(channel: String, message: String) { + commandCallback?.handleCallback(message) + } + } + pubSub = subscription + try { + jedis.subscribe(subscription, callbackChannel) + } finally { + if (pubSub === subscription) pubSub = null + } + } finally { + if (subscriberConnection === jedis) subscriberConnection = null + } } } - jedis.subscribe(pubSub, callbackChannel) + // Redis 主动关闭订阅时也重建连接。 + } catch (_: CancellationException) { + break + } catch (error: Exception) { + if (!isActive || stopped) break + plugin.log_warning("Redis 回调监听器断开,${retryDelay}ms 后重试: ${error.message}") } - } catch (_: CancellationException) { - // 插件关闭或重连时的正常取消。 - } catch (error: Exception) { - plugin.log_error("Redis 回调监听器异常: ${error.message}") + if (!isActive || stopped) break + delay(retryDelay) + retryDelay = (retryDelay * 2).coerceAtMost(30_000L) } + pubSub = null + subscriberConnection = null } } fun disconnect() { + stopped = true try { pubSub?.unsubscribe() } catch (_: Exception) { // 连接已经关闭时无需再次处理。 } pubSub = null + try { + subscriberConnection?.close() + } catch (_: Exception) { + // 取消正在阻塞的订阅连接。 + } + subscriberConnection = null subscriberJob?.cancel() subscriberJob = null subscriberScope.cancel() diff --git a/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/velocity/events/GameChat.kt b/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/velocity/events/GameChat.kt index bb3bb75..cc5def6 100644 --- a/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/velocity/events/GameChat.kt +++ b/server/Proxy/src/main/kotlin/cn/huohuas001/huhobotPenguin/velocity/events/GameChat.kt @@ -2,14 +2,16 @@ package cn.huohuas001.huhobotPenguin.velocity.events import cn.huohuas001.bot.QClient import cn.huohuas001.huhobotPenguin.velocity.HuHoBotVelocity +import com.velocitypowered.api.event.PostOrder import com.velocitypowered.api.event.Subscribe import com.velocitypowered.api.event.connection.DisconnectEvent import com.velocitypowered.api.event.connection.PostLoginEvent import com.velocitypowered.api.event.player.PlayerChatEvent class GameChat(private val plugin: HuHoBotVelocity) { - @Subscribe + @Subscribe(order = PostOrder.LAST) fun onPlayerChat(event: PlayerChatEvent) { + if (!event.result.isAllowed) return QClient.broadcastGameMessage(event.player.username, event.message) } diff --git a/server/Spigot/src/main/kotlin/cn/huohuas001/huhobotPenguin/spigot/manager/ConfigManager.kt b/server/Spigot/src/main/kotlin/cn/huohuas001/huhobotPenguin/spigot/manager/ConfigManager.kt index 529a955..adc783f 100644 --- a/server/Spigot/src/main/kotlin/cn/huohuas001/huhobotPenguin/spigot/manager/ConfigManager.kt +++ b/server/Spigot/src/main/kotlin/cn/huohuas001/huhobotPenguin/spigot/manager/ConfigManager.kt @@ -28,7 +28,9 @@ class ConfigManager( fun saveValues(changes: Map): Boolean { val persisted = YamlConfig(configFile, plugin.server.port, plugin.logger::warning) persisted.reload() - return persisted.saveValues(ManagementConfig.merge(snapshot(), changes)) + val saved = persisted.saveValues(ManagementConfig.merge(snapshot(), changes)) + if (saved) reload() + return saved } private fun sectionValues(section: ConfigurationSection): Map =