From d4fc48bc2aefca52cb043412b36d31602b36553e Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 12:39:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=B3=BB=E7=BB=9F=E6=8E=A5?= =?UTF-8?q?=E5=85=A5=E8=AF=8A=E6=96=AD=E4=B8=8E=E5=AE=A1=E6=A0=B8=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../WechatContentModerationProvider.java | 11 +- ...dminSecureIntegrationConfigController.java | 12 +- .../impl/IntegrationProbeServiceImpl.java | 204 +++++++++++++++--- .../system/vo/SecureIntegrationConfigVO.java | 3 + ...ntentModerationCallbackControllerTest.java | 5 +- .../impl/IntegrationProbeServiceImplTest.java | 139 ++++++++++++ .../src/utils/moderation-status.test.ts | 35 +++ .../src/utils/moderation-status.ts | 64 ++++++ .../src/views/admin/PrivacyComplianceView.vue | 51 ++++- .../src/views/admin/SystemSettingsView.vue | 133 ++++++++---- .../Salon系统接入诊断与测试说明_20261104.md | 33 +++ docs/scripts/运行与发布配置总说明.md | 1 + 12 files changed, 607 insertions(+), 84 deletions(-) create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java create mode 100644 JC-Salon-Frontend/src/utils/moderation-status.test.ts create mode 100644 JC-Salon-Frontend/src/utils/moderation-status.ts create mode 100644 docs/scripts/Salon系统接入诊断与测试说明_20261104.md diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java index 28509fb4..18cb4466 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -65,9 +65,9 @@ public class WechatContentModerationProvider implements ContentModerationProvide return submitImageWithExtra(contentType, imageUrl, openId, encodeSourceEnvVersion(sourceEnvVersion)); } - public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId) { + public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) { Map extra = new LinkedHashMap<>(); - extra.put("envVersion", "trial"); + extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion)); extra.put("probeId", probeId); try { return submitImageWithExtra("INTEGRATION_PROBE", imageUrl, openId, objectMapper.writeValueAsString(extra)); @@ -76,6 +76,13 @@ public class WechatContentModerationProvider implements ContentModerationProvide } } + private String normalizeEnvVersion(String value) { + if ("developer".equalsIgnoreCase(value) || "develop".equalsIgnoreCase(value)) return "develop"; + if ("trial".equalsIgnoreCase(value)) return "trial"; + if ("formal".equalsIgnoreCase(value) || "release".equalsIgnoreCase(value)) return "release"; + return "UNKNOWN"; + } + private ModerationOutcome submitImageWithExtra(String contentType, String imageUrl, String openId, String extra) { if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java index f02f5fd9..f40efc2f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java @@ -38,7 +38,9 @@ public class AdminSecureIntegrationConfigController { @RequirePermission("messagehub:config:manage") public Result getConfig(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + config.setProbeResults(integrationProbeService.listLatest(currentUser)); + return Result.success(config); } @GetMapping("/map-runtime") @@ -95,8 +97,12 @@ public class AdminSecureIntegrationConfigController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); try { IntegrationProbeResultVO result = integrationProbeService.probe(currentUser, dto); - securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, - "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus()); + String auditDetail = "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus(); + if ("FAIL".equals(result.getStatus())) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail); + } else { + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail); + } return Result.success(result); } catch (RuntimeException exception) { securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java index f1cb0d62..b689e09a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java @@ -23,13 +23,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeCheck import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.core.env.Environment; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -43,7 +44,6 @@ import java.util.UUID; @Slf4j @Service -@RequiredArgsConstructor public class IntegrationProbeServiceImpl implements IntegrationProbeService { private static final String[] SERVICES = {"CONTENT_MODERATION", "MAP", "OBJECT_STORAGE", "SMS", "SUBSCRIBE_MESSAGE"}; private static final String TEXT = "CONTENT_MODERATION"; @@ -63,6 +63,33 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private final MessageHubPushConfigService messageHubPushConfigService; private final MessageHubClientService messageHubClientService; private final RestTemplate restTemplate; + private final Environment environment; + + public IntegrationProbeServiceImpl(IntegrationProbeResultMapper resultMapper, + ObjectMapper objectMapper, + SecureIntegrationConfigService secureIntegrationConfigService, + WechatMiniProperties wechatMiniProperties, + WechatMiniClientService wechatMiniClientService, + WechatMiniBindingMapper bindingMapper, + WechatContentModerationProvider wechatContentModerationProvider, + List storageProviders, + MessageHubPushConfigService messageHubPushConfigService, + MessageHubClientService messageHubClientService, + @Qualifier("restTemplate") RestTemplate restTemplate, + Environment environment) { + this.resultMapper = resultMapper; + this.objectMapper = objectMapper; + this.secureIntegrationConfigService = secureIntegrationConfigService; + this.wechatMiniProperties = wechatMiniProperties; + this.wechatMiniClientService = wechatMiniClientService; + this.bindingMapper = bindingMapper; + this.wechatContentModerationProvider = wechatContentModerationProvider; + this.storageProviders = storageProviders; + this.messageHubPushConfigService = messageHubPushConfigService; + this.messageHubClientService = messageHubClientService; + this.restTemplate = restTemplate; + this.environment = environment; + } @Override public IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request) { @@ -115,8 +142,21 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { .eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1")); } if (row == null) return false; - row.setStatus("pass".equalsIgnoreCase(suggest) ? "PASS" : "review".equalsIgnoreCase(suggest) ? "WARN" : "FAIL"); - row.setSummary("微信图片审核回调:" + (StringUtils.hasText(suggest) ? suggest : "review")); + if (!TEXT.equals(row.getServiceCode()) || !"IMAGE_CALLBACK".equals(row.getOperationCode())) return false; + if (!"PENDING".equals(row.getStatus())) return true; + if (row.getExpiresAt() != null && row.getExpiresAt().isBefore(LocalDateTime.now())) { + row.setStatus("FAIL"); + row.setSummary("图片审核回调已超过等待期限"); + row.setErrorCode("CALLBACK_TIMEOUT"); + row.setCheckedAt(LocalDateTime.now()); + deleteTemporaryObject(row); + resultMapper.updateById(row); + return true; + } + String candidateSuggest = StringUtils.hasText(suggest) ? suggest.trim().toLowerCase(Locale.ROOT) : "review"; + String normalizedSuggest = List.of("pass", "review", "risky").contains(candidateSuggest) ? candidateSuggest : "unknown"; + row.setStatus("pass".equals(normalizedSuggest) ? "PASS" : "review".equals(normalizedSuggest) ? "WARN" : "FAIL"); + row.setSummary("微信图片审核回调:" + normalizedSuggest); row.setCheckedAt(LocalDateTime.now()); try { row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片审核回调", row.getStatus(), row.getSummary())))); } catch (Exception ignored) { } @@ -140,23 +180,50 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { deleteTemporaryObject(row); resultMapper.updateById(row); } + List cleanup = resultMapper.selectList(new LambdaQueryWrapper() + .isNotNull(IntegrationProbeResultDO::getTemporaryObjectName) + .lt(IntegrationProbeResultDO::getExpiresAt, LocalDateTime.now())); + for (IntegrationProbeResultDO row : cleanup) { + deleteTemporaryObject(row); + resultMapper.updateById(row); + } } private IntegrationProbeResultVO probeModeration(UserDO currentUser, String operation, String mode) { SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); List checks = new ArrayList<>(); - checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取")); - checks.add(check("审核 Provider", "WECHAT".equals(config.getModerationProvider()) || "MOCK".equals(config.getModerationProvider()), config.getModerationProvider(), "未启用")); - checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置")); - if ("WECHAT".equals(config.getModerationProvider())) { - checks.add(check("回调配置", Boolean.TRUE.equals(config.getModerationCallbackReady()), "公网 HTTPS 回调资料完整", "回调 URL、Token、AESKey 或加密主密钥不完整")); + String provider = config.getModerationProvider(); + if ("WECHAT".equals(provider)) { + checks.add(check("审核 Provider", true, "微信内容安全审核", "未启用")); + checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取")); + checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置")); + String callbackUrl = config.getModerationCallbackUrl(); + boolean callbackUrlValid = false; + try { + java.net.URI callback = java.net.URI.create(callbackUrl == null ? "" : callbackUrl); + callbackUrlValid = "https".equalsIgnoreCase(callback.getScheme()) + && StringUtils.hasText(callback.getHost()) + && (callback.getPort() == -1 || callback.getPort() == 443) + && callback.getUserInfo() == null && callback.getQuery() == null && callback.getFragment() == null + && "/api/integration/wechat/content-moderation/callback".equals(callback.getPath()); + } catch (IllegalArgumentException ignored) { } + checks.add(check("回调 HTTPS 地址", callbackUrlValid, "公网 HTTPS 回调地址有效", "回调地址缺失或格式不正确")); + checks.add(check("回调 Token", Boolean.TRUE.equals(config.getModerationCallbackTokenConfigured()), "已配置", "未配置")); + checks.add(check("EncodingAESKey", Boolean.TRUE.equals(config.getModerationEncodingAesKeyConfigured()), "已配置", "未配置")); + checks.add(check("回调配置汇总", Boolean.TRUE.equals(config.getModerationCallbackReady()), "回调资料完整", "回调 URL、Token、AESKey、加密主密钥或 App 凭据不完整")); + } else if ("MOCK".equals(provider)) { + boolean mockAllowed = Boolean.TRUE.equals(config.getMockProviderAllowed()); + checks.add(new IntegrationProbeCheckVO("审核 Provider", mockAllowed ? "PASS" : "FAIL", mockAllowed ? "本地模拟审核已启用" : "当前环境不允许模拟审核")); + checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "模拟渠道不会调用微信接口")); + } else { + checks.add(new IntegrationProbeCheckVO("审核 Provider", "WARN", "内容审核未启用,内容保持隔离")); } - if (!"WECHAT".equals(config.getModerationProvider())) checks.add(new IntegrationProbeCheckVO("加密主密钥", "WARN", "当前 Provider 不是真实微信审核,无需校验加密回调密钥")); if ("CONFIG".equals(operation)) return result(TEXT, operation, mode, config.getModerationProvider(), statusForChecks(checks), "内容审核配置诊断完成", null, checks); - if ("MOCK".equals(config.getModerationProvider())) { + if ("MOCK".equals(config.getModerationProvider()) && Boolean.TRUE.equals(config.getMockProviderAllowed())) { checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "当前使用本地模拟审核,不会调用微信接口")); return result(TEXT, operation, mode, "MOCK", "WARN", "当前为本地模拟流程", null, checks); } + if ("MOCK".equals(config.getModerationProvider())) return result(TEXT, operation, mode, "MOCK", "FAIL", "当前环境不允许使用模拟审核", "MOCK_NOT_ALLOWED", checks); if (!"WECHAT".equals(config.getModerationProvider())) return result(TEXT, operation, mode, config.getModerationProvider(), "FAIL", "微信内容审核未启用", "PROVIDER_DISABLED", checks); if (!Boolean.TRUE.equals(config.getModerationReady())) return result(TEXT, operation, mode, "WECHAT", "FAIL", "微信审核配置未就绪,未发起接口请求", "MODERATION_NOT_READY", checks); String openId = findProbeOpenId(); @@ -172,24 +239,43 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { } private IntegrationProbeResultVO probeImageCallback(String mode, String openId, List checks) { + IntegrationProbeResultDO current = findResult(TEXT, "IMAGE_CALLBACK"); + if (current != null && "PENDING".equals(current.getStatus()) && current.getExpiresAt() != null && current.getExpiresAt().isAfter(LocalDateTime.now())) { + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "PENDING", "已有图片测试正在等待微信回调", null, + List.of(new IntegrationProbeCheckVO("微信图片异步接口", "PENDING", "等待上一条测试的微信回调或超时清理"))); + } + if (current != null && StringUtils.hasText(current.getTemporaryObjectName())) { + deleteTemporaryObject(current); + resultMapper.updateById(current); + if (StringUtils.hasText(current.getTemporaryObjectName())) { + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "上一张临时测试图片仍未清理,请稍后重试", "TEMP_CLEANUP_FAILED", + List.of(new IntegrationProbeCheckVO("临时图片清理", "FAIL", "无法确认旧测试文件已删除"))); + } + } String objectName = "integration-probe/" + UUID.randomUUID() + ".png"; String probeId = UUID.randomUUID().toString(); ObjectStorageProvider uploaded = null; boolean awaitingCallback = false; + boolean pendingSaved = false; try { byte[] image = createProbePng(); for (ObjectStorageProvider provider : storageProviders) { if (provider.isEnabled()) { - provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName); uploaded = provider; + provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName); break; } } if (uploaded == null) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "没有可用对象存储,无法生成图片审核地址", "STORAGE_UNAVAILABLE", checks); String url = uploaded.getPresignedUrl(objectName, 5); - if (!StringUtils.hasText(url) || !url.startsWith("https://")) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks); + if (!StringUtils.hasText(url) || !url.startsWith("https://")) { + checks.add(new IntegrationProbeCheckVO("临时图片地址", "FAIL", "对象存储未提供公网 HTTPS 签名地址")); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks); + } savePendingImageProbe(mode, probeId, uploaded.providerCode(), objectName); - ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId); + pendingSaved = true; + ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId, + wechatMiniProperties.getSubscribeMessageMiniprogramState()); String status = outcome.status() == ModerationOutcome.Status.PENDING ? "PENDING" : outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : "FAIL"; checks.add(new IntegrationProbeCheckVO("微信图片异步接口", status, outcome.reason())); awaitingCallback = "PENDING".equals(status); @@ -199,7 +285,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { checks.add(new IntegrationProbeCheckVO("微信图片异步接口", "FAIL", "临时图片上传或审核请求失败")); return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "微信图片审核探测失败", "IMAGE_PROBE_FAILED", checks); } finally { - if (uploaded != null && !awaitingCallback) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); } + if (uploaded != null && !awaitingCallback && !pendingSaved) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); } } } @@ -238,20 +324,30 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private void deleteTemporaryObject(IntegrationProbeResultDO row) { if (!StringUtils.hasText(row.getTemporaryObjectProvider()) || !StringUtils.hasText(row.getTemporaryObjectName())) return; - storageProviders.stream().filter(provider -> provider.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().ifPresent(provider -> { - try { provider.deleteFile(row.getTemporaryObjectName()); } - catch (Exception ignored) { log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); } - }); - row.setTemporaryObjectProvider(null); - row.setTemporaryObjectName(null); + ObjectStorageProvider provider = storageProviders.stream() + .filter(item -> item.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().orElse(null); + if (provider == null) return; + try { + provider.deleteFile(row.getTemporaryObjectName()); + row.setTemporaryObjectProvider(null); + row.setTemporaryObjectName(null); + } catch (Exception ignored) { + log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); + } } private IntegrationProbeResultVO probeMap(UserDO currentUser, String operation) { SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); List checks = new ArrayList<>(); - boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? Boolean.TRUE.equals(config.getAmapWebKeyConfigured()) : Boolean.TRUE.equals(config.getTencentWebKeyConfigured()); - checks.add(check("当前 Web Key", selectedKey, "已配置", "未配置")); - checks.add(new IntegrationProbeCheckVO("高德小程序 Key", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "PASS" : "WARN", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "已配置" : "未配置,仅影响小程序选点")); + boolean amapKey = Boolean.TRUE.equals(config.getAmapWebKeyConfigured()); + boolean tencentKey = Boolean.TRUE.equals(config.getTencentWebKeyConfigured()); + boolean miniKey = Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()); + boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? amapKey : tencentKey; + checks.add(check("当前渠道 Web Key", selectedKey, "已配置", "未配置")); + checks.add(new IntegrationProbeCheckVO("高德 Web Key", amapKey ? "PASS" : "WARN", amapKey ? "已配置" : "未配置")); + checks.add(new IntegrationProbeCheckVO("腾讯 Web Key", tencentKey ? "PASS" : "WARN", tencentKey ? "已配置" : "未配置")); + checks.add(new IntegrationProbeCheckVO("高德小程序 Key", miniKey ? "PASS" : "WARN", miniKey ? "已配置" : "未配置,仅影响小程序选点")); + if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), statusForChecks(checks), "地图接入配置诊断完成", null, checks); if (!selectedKey) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "当前地图渠道缺少 Web Key", "MAP_KEY_MISSING", checks); if (!Boolean.TRUE.equals(config.getMapEnabled())) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "WARN", "地图服务当前已停用,保存并启用后才能测试真实请求", "MAP_DISABLED", checks); if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "PASS", "地图 Key 配置诊断完成", null, checks); @@ -277,7 +373,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { for (ObjectStorageProvider provider : storageProviders) { checks.add(new IntegrationProbeCheckVO(provider.providerCode(), provider.isEnabled() ? "PASS" : "WARN", provider.isEnabled() ? "已启用并具备基本配置" : "未启用或配置不完整")); } - String status = checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; + String status = checks.isEmpty() ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储配置完整" : "存在未启用的对象存储渠道", null, checks); } byte[] bytes = "salon-integration-probe".getBytes(StandardCharsets.UTF_8); @@ -290,6 +386,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { continue; } enabled++; + boolean cleanupFailed = false; try { provider.uploadStream(new java.io.ByteArrayInputStream(bytes), bytes.length, "text/plain", objectName); try (InputStream input = provider.downloadFile(objectName)) { @@ -302,8 +399,10 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { } catch (Exception exception) { checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "FAIL", "上传或读取失败")); } finally { - try { provider.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); } + try { provider.deleteFile(objectName); } + catch (Exception ignored) { cleanupFailed = true; log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); } } + if (cleanupFailed) checks.add(new IntegrationProbeCheckVO(provider.providerCode() + " 清理", "FAIL", "临时测试对象未能删除,请检查存储状态")); } String status = enabled == 0 ? "FAIL" : checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储三副本往返测试成功" : "对象存储存在未就绪渠道", null, checks); @@ -316,9 +415,27 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { List checks = new ArrayList<>(); List configs = messageHubPushConfigService.listConfigs(currentUser); List expectedScenes = List.of("USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE", "USER_RESET_PASSWORD_SMS_CODE", "USER_BIND_PHONE_SMS_CODE", "USER_CHANGE_PHONE_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE"); - long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) && Integer.valueOf(1).equals(item.getEnabled()))).count(); - checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景已启用")); - boolean complete = enabled == expectedScenes.size(); + long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) + && "SMS".equalsIgnoreCase(item.getPlatform()) && Integer.valueOf(1).equals(item.getEnabled()) + && StringUtils.hasText(item.getSendMethod()) && StringUtils.hasText(item.getQueueName()) + && StringUtils.hasText(item.getTemplateCode()))).count(); + checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景配置完整并启用")); + String baseUrl = environment.getProperty("messagehub.client.base-url", "http://192.168.10.107:8080"); + String accessToken = environment.getProperty("messagehub.client.access-token"); + String exchange = environment.getProperty("messagehub.client.ingress-exchange", "messagehub.ingress.exchange"); + String routingKey = environment.getProperty("messagehub.client.ingress-routing-key", "message.send"); + String smsQueue = environment.getProperty("messagehub.client.sms-queue", "smsQueue"); + String sourceSystem = environment.getProperty("messagehub.client.source-system", "jayucloud-salon"); + String templateCode = environment.getProperty("messagehub.client.verify-template-code", "SPUG_SMS_VERIFY_1"); + String sendMethod = environment.getProperty("messagehub.client.send-method", "SPUG"); + boolean endpointConfigured = safeHttpUrl(baseUrl); + checks.add(check("MessageHub 地址", endpointConfigured, "已配置 HTTP(S) 地址", "地址未配置或格式无效")); + checks.add(check("MessageHub 访问凭据", StringUtils.hasText(accessToken), "已配置", "未配置")); + boolean deliveryConfigured = StringUtils.hasText(exchange) && StringUtils.hasText(routingKey) + && StringUtils.hasText(smsQueue) && StringUtils.hasText(sourceSystem) + && StringUtils.hasText(templateCode) && StringUtils.hasText(sendMethod); + checks.add(check("短信投递参数", deliveryConfigured, "交换机、路由、队列、来源和模板已配置", "部分投递参数缺失")); + boolean complete = enabled == expectedScenes.size() && endpointConfigured && StringUtils.hasText(accessToken) && deliveryConfigured; if ("CONFIG".equals(operation) || !"REAL".equals(mode)) return result(SMS, operation, mode, "MESSAGEHUB", complete ? "PASS" : "FAIL", complete ? "短信场景配置完整;未发送真实短信" : "部分短信场景未启用", null, checks); if (!complete) return result(SMS, operation, mode, "MESSAGEHUB", "FAIL", "短信场景配置不完整,未发送测试短信", "SMS_CONFIG_INCOMPLETE", checks); if (!StringUtils.hasText(phone) || !phone.matches("^1[3-9]\\d{9}$")) throw new IllegalArgumentException("真实短信测试需要填写有效手机号"); @@ -332,11 +449,21 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { List checks = new ArrayList<>(); String provider = StringUtils.hasText(wechatMiniProperties.getSubscribeMessageProvider()) ? wechatMiniProperties.getSubscribeMessageProvider().trim().toLowerCase(Locale.ROOT) : "mock"; boolean enabled = Boolean.TRUE.equals(wechatMiniProperties.getSubscribeMessageEnabled()); - checks.add(new IntegrationProbeCheckVO("发送渠道", "wechat".equals(provider) && enabled ? "PASS" : "WARN", "wechat".equals(provider) && enabled ? "微信真实发送已启用" : "当前为 Mock 或已停用")); + boolean liveProvider = "wechat".equals(provider) && enabled; + checks.add(new IntegrationProbeCheckVO("发送渠道", liveProvider ? "PASS" : "WARN", liveProvider ? "微信真实发送已启用" : "当前为 Mock 或已停用")); + if (!liveProvider) { + checks.add(new IntegrationProbeCheckVO("小程序凭据", "WARN", "当前未调用微信接口,因此不校验真实凭据")); + checks.add(new IntegrationProbeCheckVO("固定模板", "PASS", "3 个固定模板 ID 已加载")); + return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", + "当前为 Mock 或已停用,未调用微信接口", null, checks); + } boolean credentials = StringUtils.hasText(wechatMiniProperties.getAppId()) && StringUtils.hasText(wechatMiniProperties.getAppSecret()); checks.add(check("小程序凭据", credentials, "已配置", "AppID 或 AppSecret 未配置")); if (!credentials) return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息凭据不完整", "WECHAT_CREDENTIALS_MISSING", checks); - if (!"wechat".equals(provider) || !enabled) return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", "当前订阅消息未启用微信真实发送", "PROVIDER_NOT_LIVE", checks); + checks.add(check("固定模板", WechatSubscribeMessageService.TEMPLATE_APPOINTMENT.length() > 10 + && WechatSubscribeMessageService.TEMPLATE_CANCELLED.length() > 10 + && WechatSubscribeMessageService.TEMPLATE_SERVICE_START.length() > 10, + "3 个固定模板 ID 已加载", "固定模板 ID 不完整")); try { wechatMiniClientService.getAccessTokenForContentModeration(); checks.add(new IntegrationProbeCheckVO("access_token", "PASS", "获取成功")); @@ -360,7 +487,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private IntegrationProbeResultVO checkSubscribeTemplates(String operation, String mode, List checks) throws Exception { String accessToken = wechatMiniClientService.getAccessTokenForContentModeration(); - String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8); + String url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8); JsonNode response = objectMapper.readTree(restTemplate.getForObject(url, String.class)); int errorCode = response.path("errcode").asInt(0); if (errorCode != 0) { @@ -390,9 +517,9 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private void validateOperation(String service, String operation, String mode) { boolean valid = switch (service) { - case TEXT -> List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation); - case MAP -> List.of("CONFIG", "REQUEST").contains(operation); - case STORAGE -> List.of("CONFIG", "ROUND_TRIP").contains(operation); + case TEXT -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation); + case MAP -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "REQUEST").contains(operation); + case STORAGE -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "ROUND_TRIP").contains(operation); case SMS -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); case SUBSCRIBE -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); default -> false; @@ -434,6 +561,13 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { } private String normalize(String value) { return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; } + private boolean safeHttpUrl(String value) { + if (!StringUtils.hasText(value)) return false; + try { + java.net.URI uri = java.net.URI.create(value.trim()); + return ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())) && StringUtils.hasText(uri.getHost()); + } catch (IllegalArgumentException ignored) { return false; } + } private String safeMessage(RuntimeException exception) { return "探测请求未完成,请查看脱敏检查项"; } private String subscribeSendError(int code) { if (code == 43101) return "当前绑定账号尚未授权此订阅模板"; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java index 4c3be1a1..d8c3d72d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.vo; import lombok.Data; import java.time.LocalDateTime; +import java.util.List; @Data public class SecureIntegrationConfigVO { @@ -25,4 +26,6 @@ public class SecureIntegrationConfigVO { private Boolean encryptionKeyConfigured; private LocalDateTime updatedAt; + /** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */ + private List probeResults; } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java index f7b50956..6b91d189 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java @@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerati import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -37,6 +38,7 @@ class WechatContentModerationCallbackControllerTest { wechatProperties, crypto, mock(ContentModerationService.class), + mock(IntegrationProbeService.class), new ObjectMapper()); String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo"); @@ -58,6 +60,7 @@ class WechatContentModerationCallbackControllerTest { new WechatMiniProperties(), crypto, mock(ContentModerationService.class), + mock(IntegrationProbeService.class), new ObjectMapper()); assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo")); @@ -132,6 +135,6 @@ class WechatContentModerationCallbackControllerTest { WechatMiniProperties wechatProperties = new WechatMiniProperties(); wechatProperties.setAppId("mini-app-id"); return new WechatContentModerationCallbackController( - secureConfig, wechatProperties, crypto, moderationService, new ObjectMapper()); + secureConfig, wechatProperties, crypto, moderationService, mock(IntegrationProbeService.class), new ObjectMapper()); } } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java new file mode 100644 index 00000000..ea8eefd0 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java @@ -0,0 +1,139 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.WechatContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.IntegrationProbeResultMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.Environment; +import org.springframework.web.client.RestTemplate; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class IntegrationProbeServiceImplTest { + private final IntegrationProbeResultMapper results = mock(IntegrationProbeResultMapper.class); + private final SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); + private final WechatMiniProperties wechatProperties = new WechatMiniProperties(); + private final WechatMiniClientService wechatClient = mock(WechatMiniClientService.class); + private final WechatMiniBindingMapper bindings = mock(WechatMiniBindingMapper.class); + private final WechatContentModerationProvider moderationProvider = mock(WechatContentModerationProvider.class); + private final ObjectStorageProvider storageProvider = mock(ObjectStorageProvider.class); + private final MessageHubPushConfigService smsConfigs = mock(MessageHubPushConfigService.class); + private final MessageHubClientService smsClient = mock(MessageHubClientService.class); + private final RestTemplate restTemplate = mock(RestTemplate.class); + private final Environment environment = mock(Environment.class); + private final IntegrationProbeServiceImpl service = new IntegrationProbeServiceImpl( + results, new ObjectMapper(), secureConfig, wechatProperties, wechatClient, bindings, + moderationProvider, List.of(storageProvider), smsConfigs, smsClient, restTemplate, environment); + + @Test + void rejectsNonAdminBeforeAnyProbeSideEffect() { + UserDO manager = new UserDO(); + manager.setType(2); + + assertThrows(RuntimeException.class, () -> service.probe(manager, request("SMS", "CONFIG", "DIAGNOSTIC", false))); + verify(smsConfigs, never()).listConfigs(any()); + } + + @Test + void realSmsCannotBeSentWithoutExplicitConfirmation() { + assertThrows(IllegalArgumentException.class, + () -> service.probe(admin(), request("SMS", "SEND", "REAL", false))); + verify(smsClient, never()).sendSmsVerificationCode(any(), any(), any()); + } + + @Test + void devMockIsNotReportedAsAnAllowedMockWhenEnvironmentDisallowsIt() { + SecureIntegrationConfigVO config = new SecureIntegrationConfigVO(); + config.setModerationProvider("MOCK"); + config.setMockProviderAllowed(false); + when(secureConfig.getAdminConfig(any())).thenReturn(config); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("CONTENT_MODERATION", "CONFIG", "DIAGNOSTIC", false)); + + assertEquals("FAIL", result.getStatus()); + verify(moderationProvider, never()).reviewText(any(), any(), any()); + } + + @Test + void subscribeDiagnosticInMockModeDoesNotFetchTokenOrSendAnything() { + wechatProperties.setAppId("test-app"); + wechatProperties.setAppSecret("test-secret"); + wechatProperties.setSubscribeMessageEnabled(true); + wechatProperties.setSubscribeMessageProvider("mock"); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("SUBSCRIBE_MESSAGE", "CONFIG", "DIAGNOSTIC", false)); + + assertEquals("WARN", result.getStatus()); + verify(wechatClient, never()).getAccessTokenForContentModeration(); + verify(wechatClient, never()).sendSubscribeMessage(any(), any(), any(), any(), any()); + } + + @Test + void anOutstandingImageProbePreventsAnotherTemporaryUpload() throws Exception { + wechatProperties.setAppId("test-app"); + SecureIntegrationConfigVO config = new SecureIntegrationConfigVO(); + config.setModerationProvider("WECHAT"); + config.setModerationReady(true); + config.setModerationCallbackReady(true); + config.setEncryptionKeyConfigured(true); + config.setWechatMiniAppConfigured(true); + when(secureConfig.getAdminConfig(any())).thenReturn(config); + WechatMiniBindingDO binding = new WechatMiniBindingDO(); + binding.setOpenId("private-open-id"); + when(bindings.selectOne(any())).thenReturn(binding); + IntegrationProbeResultDO pending = new IntegrationProbeResultDO(); + pending.setId(10L); + pending.setServiceCode("CONTENT_MODERATION"); + pending.setOperationCode("IMAGE_CALLBACK"); + pending.setStatus("PENDING"); + pending.setExpiresAt(LocalDateTime.now().plusMinutes(2)); + when(results.selectOne(any())).thenReturn(pending); + + var result = service.probe(admin(), request("CONTENT_MODERATION", "IMAGE_CALLBACK", "DIAGNOSTIC", false)); + + assertEquals("PENDING", result.getStatus()); + verify(storageProvider, never()).uploadStream(any(), anyLong(), any(), any()); + verify(moderationProvider, never()).submitTestImage(any(), any(), any(), any()); + } + + private UserDO admin() { + UserDO user = new UserDO(); + user.setId(1L); + user.setType(4); + return user; + } + + private IntegrationProbeRequestDTO request(String service, String operation, String mode, boolean confirmed) { + IntegrationProbeRequestDTO request = new IntegrationProbeRequestDTO(); + request.setService(service); + request.setOperation(operation); + request.setMode(mode); + request.setConfirmed(confirmed); + request.setTargetPhone("13800138000"); + return request; + } +} diff --git a/JC-Salon-Frontend/src/utils/moderation-status.test.ts b/JC-Salon-Frontend/src/utils/moderation-status.test.ts new file mode 100644 index 00000000..899da260 --- /dev/null +++ b/JC-Salon-Frontend/src/utils/moderation-status.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import type { SecureIntegrationConfigVO } from '@/api/admin' +import { buildModerationNotice } from './moderation-status' + +function config(overrides: Partial = {}): SecureIntegrationConfigVO { + return { + mapProvider: 'TENCENT', mapEnabled: true, tencentWebKeyConfigured: false, amapWebKeyConfigured: false, + amapMiniKeyConfigured: false, mapLegacyMigrationPending: false, moderationProvider: 'DISABLED', + moderationCallbackUrl: '', moderationCallbackTokenConfigured: false, moderationEncodingAesKeyConfigured: false, + moderationCallbackReady: false, moderationReady: false, wechatMiniAppConfigured: false, + wechatMiniAppId: '', mockProviderAllowed: false, encryptionKeyConfigured: false, ...overrides + } +} + +describe('buildModerationNotice', () => { + it('only describes mock behavior when current environment permits it', () => { + expect(buildModerationNotice(config({ moderationProvider: 'MOCK', mockProviderAllowed: true })).title) + .toBe('当前使用本地模拟审核') + expect(buildModerationNotice(config({ moderationProvider: 'MOCK', mockProviderAllowed: false })).title) + .toBe('当前环境不允许模拟审核') + }) + + it('distinguishes disabled, incomplete and ready WeChat providers', () => { + expect(buildModerationNotice(config()).title).toBe('内容审核未启用') + expect(buildModerationNotice(config({ moderationProvider: 'WECHAT' })).title).toBe('微信内容审核尚未就绪') + expect(buildModerationNotice(config({ + moderationProvider: 'WECHAT', moderationReady: true, moderationCallbackReady: true, + wechatMiniAppConfigured: true, encryptionKeyConfigured: true + })).title).toBe('当前使用微信内容安全审核') + }) + + it('does not claim a provider when configuration cannot be read', () => { + expect(buildModerationNotice(null, true).title).toBe('无法读取内容审核状态') + }) +}) diff --git a/JC-Salon-Frontend/src/utils/moderation-status.ts b/JC-Salon-Frontend/src/utils/moderation-status.ts new file mode 100644 index 00000000..9055115e --- /dev/null +++ b/JC-Salon-Frontend/src/utils/moderation-status.ts @@ -0,0 +1,64 @@ +import type { SecureIntegrationConfigVO } from '@/api/admin' + +export type ModerationNotice = { + type: 'info' | 'warning' | 'error' | 'success' + title: string + description: string +} + +export function buildModerationNotice(config: SecureIntegrationConfigVO | null, statusUnavailable = false): ModerationNotice { + if (statusUnavailable) return { + type: 'error', + title: '无法读取内容审核状态', + description: '状态未知时请勿假设微信审核已生效;可重试加载或前往系统设置检查接入配置。' + } + if (!config) return { + type: 'info', + title: '正在读取内容审核状态', + description: '正在读取当前环境的真实审核渠道和最近探测结果。' + } + const latest = (config.probeResults || []) + .filter(item => item.service === 'CONTENT_MODERATION') + .sort((a, b) => String(b.checkedAt || '').localeCompare(String(a.checkedAt || '')))[0] + if (config.moderationProvider === 'MOCK' && config.mockProviderAllowed) return { + type: 'warning', + title: '当前使用本地模拟审核', + description: '不会调用微信内容安全接口,仅适用于当前允许模拟的开发环境。正式环境请切换为微信内容安全审核。' + } + if (config.moderationProvider === 'MOCK') return { + type: 'error', + title: '当前环境不允许模拟审核', + description: '已保存的模拟渠道不能在当前环境生效,内容仍保持隔离。请切换到微信审核或停用后人工处理。' + } + if (config.moderationProvider === 'DISABLED') return { + type: 'error', + title: '内容审核未启用', + description: '内容会保持隔离,不会自动放行。请在系统设置的服务接入中完成配置。' + } + if (!config.moderationReady) { + const missing = [ + !config.encryptionKeyConfigured && '服务端加密主密钥', + !config.wechatMiniAppConfigured && '小程序 AppID/AppSecret', + !config.moderationCallbackTokenConfigured && '回调 Token', + !config.moderationEncodingAesKeyConfigured && 'EncodingAESKey', + !config.moderationCallbackReady && '公网 HTTPS 回调' + ].filter(Boolean).join('、') + return { + type: 'warning', + title: '微信内容审核尚未就绪', + description: `当前已选择微信审核,但${missing || '配置校验未通过'}。请先完成配置并运行接入测试。` + } + } + const latestText = latest + ? `最近探测:${probeLabel(latest.status)} · ${latest.summary}(${latest.checkedAt ? new Date(latest.checkedAt).toLocaleString('zh-CN', { hour12: false }) : '暂无时间'})` + : '尚未运行接入探测。' + return { + type: 'success', + title: '当前使用微信内容安全审核', + description: `内容须通过微信审核后才会公开展示。${latestText}` + } +} + +function probeLabel(status?: string) { + return ({ PASS: '通过', WARN: '需关注', FAIL: '失败', PENDING: '等待回调' } as Record)[status || ''] || '未知' +} diff --git a/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue b/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue index b9b78461..0aa9ba22 100644 --- a/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue +++ b/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue @@ -9,11 +9,19 @@ + > + + @@ -74,7 +82,7 @@ - + @@ -325,6 +361,7 @@ onActivated(() => { .payload-preview { max-width: 420px; max-height: 180px; margin: 0; overflow: auto; white-space: pre-wrap; word-break: break-word; font-size: 12px; } .moderation-content { display: grid; gap: 6px; } .moderation-author { color: var(--ant-color-text-secondary); font-size: 12px; } +.moderation-provider-context { color: var(--ant-color-text-secondary); font-size: 12px; line-height: 1.55; } .image-pending { color: var(--ant-color-text-secondary); font-size: 12px; } .backfill-panel { width: 100%; padding: 8px 0; } .closure-shops { display: grid; gap: 12px; margin-bottom: 16px; } diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index 3658c4df..d0661038 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -36,27 +36,6 @@ -
-
接入诊断TEST
-
-
-
- {{ card.label }} - {{ card.description }} - 最近:{{ probeFor(card.service)?.summary }} · {{ formatProbeTime(probeFor(card.service)?.checkedAt) }} -
-
- {{ card.action }} - 图片回调 - 真实发送 -
- {{ probeStatusLabel(probeFor(card.service)?.status) }} - 未测试 -
-
-

配置保存后再测试。短信和订阅消息默认只诊断,真实发送会产生外部副作用并要求二次确认;对象存储测试文件会自动清理。

-
-
账号默认值USER保存密码设置
@@ -128,6 +107,34 @@
+
+
接入诊断TEST刷新最近结果
+
+
+
+ {{ card.label }} + {{ card.description }} +
+
+
+ {{ operation.label }} + {{ probeStatusLabel(probeFor(card.service, operation.code)?.status) }} + 未测试 + {{ probeFor(card.service, operation.code)?.summary }} · {{ formatProbeTime(probeFor(card.service, operation.code)?.checkedAt) }} + + +
+ {{ check.name }}{{ probeStatusLabel(check.status) }}{{ check.detail }} +
+
+
+
+
+
+
+

配置保存后再测试。短信和订阅消息默认只诊断,真实发送会产生外部副作用并要求二次确认;对象存储测试文件会自动清理。微信图片测试提交后显示等待回调,不会把异步结果误报为失败。

+
+
地图服务安全接入保存地图设置
@@ -279,10 +286,11 @@
- +