diff --git a/docs/telegram-webhook-deployment.md b/docs/telegram-webhook-deployment.md new file mode 100644 index 0000000..5c62e03 --- /dev/null +++ b/docs/telegram-webhook-deployment.md @@ -0,0 +1,28 @@ +# Telegram Webhook 部署 + +## 环境变量 + +```bash +export TELEGRAM_ENABLED=true +export TELEGRAM_BOT_TOKEN='BotFather签发的Token' +export TELEGRAM_AUDIT_CHAT_ID='审核群Chat ID' +export TELEGRAM_WEBHOOK_URL='https://pay.example.com/api/telegram/webhook' +export TELEGRAM_WEBHOOK_SECRET='使用字母数字下划线连字符组成的随机值' +export TELEGRAM_ALLOWED_USER_IDS='123456789,987654321' +``` + +`TELEGRAM_WEBHOOK_URL` 必须是公网可访问的 HTTPS 地址,并由反向代理转发到后端 +`POST /api/telegram/webhook`。不要把 Bot Token 或 Webhook Secret 写入仓库、日志或前端配置。 + +## 注册与检查 + +1. 使用管理员账号进入“Telegram 审核记录”页面。 +2. 点击“Webhook 设置”,页面会先查询 Telegram 当前状态。 +3. 点击“按配置重新注册”后,后端使用环境变量调用 Telegram `setWebhook`。 +4. 确认页面显示“已注册”,且“当前地址”和“配置地址”一致。 + +注册操作仅订阅 `callback_query`,并同时设置 `secret_token`。Telegram 回调时,系统会校验 +`X-Telegram-Bot-Api-Secret-Token` 请求头。所有 Telegram HTTP 调用的连接和读取超时均为 60 秒。 + +部署后应创建一条测试归集审核,确认消息可以发送、授权用户可以审核、未授权用户被拒绝,且 +`pending_update_count` 不持续增长。 diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index dc83248..2281b5d 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -217,3 +217,13 @@ google: client-secret: ${GOOGLE_OAUTH_CLIENT_SECRET:} redirect-uri: ${GOOGLE_OAUTH_REDIRECT_URI:} frontend-result-url: ${GOOGLE_OAUTH_FRONTEND_RESULT_URL:} + +# Telegram归集审核。Token、Webhook Secret等敏感值只允许通过环境变量或外部配置提供。 +telegram: + enabled: ${TELEGRAM_ENABLED:false} + bot-token: ${TELEGRAM_BOT_TOKEN:} + audit-chat-id: ${TELEGRAM_AUDIT_CHAT_ID:} + webhook-url: ${TELEGRAM_WEBHOOK_URL:} + webhook-secret: ${TELEGRAM_WEBHOOK_SECRET:} + allowed-user-ids: ${TELEGRAM_ALLOWED_USER_IDS:} + push-scan-interval-ms: ${TELEGRAM_PUSH_SCAN_INTERVAL_MS:10000} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/TelegramWebhookController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/TelegramWebhookController.java new file mode 100644 index 0000000..a4615a2 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/TelegramWebhookController.java @@ -0,0 +1,37 @@ +package com.ruoyi.system.controller; + +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.system.service.TelegramAuditService; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** Telegram Webhook管理员运维接口。 */ +@RestController +@RequestMapping("/system/telegram/webhook") +public class TelegramWebhookController { + private final TelegramAuditService telegramAuditService; + + public TelegramWebhookController(TelegramAuditService telegramAuditService) { + this.telegramAuditService = telegramAuditService; + } + + /** 查询Telegram侧当前Webhook状态,不返回Bot Token或Secret。 */ + @PreAuthorize("@ss.hasRole('admin')") + @GetMapping + public AjaxResult getInfo() { + return AjaxResult.success(telegramAuditService.getWebhookInfo()); + } + + /** 按服务端环境变量重新注册Webhook。 */ + @PreAuthorize("@ss.hasRole('admin')") + @Log(title = "Telegram Webhook设置", businessType = BusinessType.UPDATE) + @PostMapping("/set") + public AjaxResult setWebhook() { + return AjaxResult.success("Telegram Webhook设置成功", telegramAuditService.setWebhook()); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/TelegramAuditService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/TelegramAuditService.java index c3bfa0b..4a48a84 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/TelegramAuditService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/TelegramAuditService.java @@ -18,8 +18,13 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -39,13 +44,14 @@ public class TelegramAuditService { private final TelegramAuditMapper mapper; private final UsdtAggregationWorkflowService workflow; - private final RestTemplate restTemplate = new RestTemplate(); + private final RestTemplate restTemplate; private final TransactionTemplate transactionTemplate; @Value("${telegram.enabled:false}") private boolean enabled; @Value("${telegram.bot-token:}") private String botToken; @Value("${telegram.audit-chat-id:}") private String auditChatId; @Value("${telegram.webhook-secret:}") private String webhookSecret; + @Value("${telegram.webhook-url:}") private String webhookUrl; @Value("${telegram.allowed-user-ids:}") private String allowedUserIds; public TelegramAuditService(TelegramAuditMapper mapper, UsdtAggregationWorkflowService workflow, @@ -53,6 +59,106 @@ public class TelegramAuditService { this.mapper = mapper; this.workflow = workflow; this.transactionTemplate = new TransactionTemplate(transactionManager); + SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); + requestFactory.setConnectTimeout(60000); + requestFactory.setReadTimeout(60000); + this.restTemplate = new RestTemplate(requestFactory); + } + + /** + * 使用服务端配置向Telegram注册Webhook。Bot Token和Secret不会由前端传入或返回。 + * 仅订阅callback_query,减少与归集审核无关的Update进入系统。 + */ + public Map setWebhook() { + validateWebhookConfiguration(); + Map request = new HashMap<>(); + request.put("url", webhookUrl.trim()); + request.put("secret_token", webhookSecret.trim()); + request.put("allowed_updates", Collections.singletonList("callback_query")); + JSONObject response = invokeTelegramApi("setWebhook", request); + if (!response.getBooleanValue("ok")) { + throw new CustomException(telegramError(response, "Telegram Webhook注册失败")); + } + return getWebhookInfo(); + } + + /** 查询Telegram当前Webhook状态,仅返回运维所需的非敏感字段。 */ + public Map getWebhookInfo() { + validateBotConfiguration(); + JSONObject response = invokeTelegramApi("getWebhookInfo", Collections.emptyMap()); + if (!response.getBooleanValue("ok")) { + throw new CustomException(telegramError(response, "Telegram Webhook状态查询失败")); + } + JSONObject result = response.getJSONObject("result"); + Map status = new HashMap<>(); + status.put("configuredUrl", StringUtils.isBlank(webhookUrl) ? "" : webhookUrl.trim()); + status.put("url", result == null ? "" : result.getString("url")); + status.put("pendingUpdateCount", result == null ? 0 : result.getIntValue("pending_update_count")); + status.put("lastErrorDate", result == null ? null : result.getLong("last_error_date")); + status.put("lastErrorMessage", result == null ? null : result.getString("last_error_message")); + status.put("maxConnections", result == null ? null : result.getInteger("max_connections")); + status.put("allowedUpdates", result == null ? Collections.emptyList() : result.getJSONArray("allowed_updates")); + status.put("registered", result != null && StringUtils.isNotBlank(result.getString("url"))); + status.put("matchesConfiguredUrl", result != null && StringUtils.isNotBlank(webhookUrl) + && webhookUrl.trim().equals(result.getString("url"))); + return status; + } + + private JSONObject invokeTelegramApi(String method, Object request) { + try { + JSONObject response = restTemplate.postForObject(botApi(method), request, JSONObject.class); + if (response == null) { + throw new CustomException("Telegram接口未返回数据"); + } + return response; + } catch (RestClientResponseException exception) { + try { + JSONObject error = JSONObject.parseObject(exception.getResponseBodyAsString()); + throw new CustomException(telegramError(error, "Telegram接口调用失败")); + } catch (CustomException customException) { + throw customException; + } catch (Exception ignored) { + throw new CustomException("Telegram接口调用失败,HTTP状态码:" + exception.getRawStatusCode()); + } + } catch (RestClientException exception) { + // RestTemplate原始异常可能包含带Bot Token的完整URL,禁止向日志、数据库或响应透传。 + throw new CustomException("Telegram接口连接失败或超时"); + } + } + + private String telegramError(JSONObject response, String fallback) { + String description = response == null ? null : response.getString("description"); + return StringUtils.isBlank(description) ? fallback : fallback + ":" + description; + } + + private void validateBotConfiguration() { + if (!enabled) { + throw new CustomException("Telegram审核功能未启用"); + } + if (StringUtils.isBlank(botToken)) { + throw new CustomException("未配置Telegram Bot Token"); + } + } + + private void validateWebhookConfiguration() { + validateBotConfiguration(); + if (StringUtils.isBlank(webhookUrl)) { + throw new CustomException("未配置Telegram Webhook URL"); + } + if (StringUtils.isBlank(webhookSecret)) { + throw new CustomException("未配置Telegram Webhook Secret"); + } + if (!webhookSecret.matches("[A-Za-z0-9_-]{1,256}")) { + throw new CustomException("Telegram Webhook Secret只能包含字母、数字、下划线和连字符,长度1-256位"); + } + try { + URI uri = new URI(webhookUrl.trim()); + if (!"https".equalsIgnoreCase(uri.getScheme()) || StringUtils.isBlank(uri.getHost())) { + throw new CustomException("Telegram Webhook URL必须是公网HTTPS地址"); + } + } catch (URISyntaxException exception) { + throw new CustomException("Telegram Webhook URL格式不正确"); + } } /** 创建归集审核记录及持久化推送任务。业务唯一键防止重复建单。 */ @@ -238,7 +344,7 @@ public class TelegramAuditService { button("审核通过", "ta:" + record.getAuditNo() + ":A"), button("审核拒绝", "ta:" + record.getAuditNo() + ":R")))); body.put("reply_markup", keyboard); - JSONObject response = restTemplate.postForObject(botApi("sendMessage"), body, JSONObject.class); + JSONObject response = invokeTelegramApi("sendMessage", body); if (response == null || !response.getBooleanValue("ok")) { throw new CustomException("Telegram sendMessage返回失败"); } @@ -261,7 +367,7 @@ public class TelegramAuditService { body.put("text", "归集审核 - " + result + "\n审核单:" + record.getAuditNo() + "\n任务:" + payload.getString("taskName") + "\n目标:" + payload.getString("destination") + "\n审核人:" + reviewer); - restTemplate.postForObject(botApi("editMessageText"), body, JSONObject.class); + invokeTelegramApi("editMessageText", body); } catch (Exception exception) { LOGGER.warn("Telegram审核结果消息更新失败,auditNo={}", record.getAuditNo()); } @@ -275,7 +381,7 @@ public class TelegramAuditService { Map body = new HashMap<>(); body.put("callback_query_id", callbackId); body.put("text", text); - restTemplate.postForObject(botApi("answerCallbackQuery"), body, Object.class); + invokeTelegramApi("answerCallbackQuery", body); } catch (Exception exception) { LOGGER.warn("Telegram callback应答失败"); }