diff --git a/admin-frontend-vue/src/api/user-secrets.ts b/admin-frontend-vue/src/api/user-secrets.ts index 29bb1737d..c67d67b88 100644 --- a/admin-frontend-vue/src/api/user-secrets.ts +++ b/admin-frontend-vue/src/api/user-secrets.ts @@ -5,6 +5,8 @@ import { unwrap } from './envelope' export interface AdminUserSecretModule { moduleKey: string moduleLabel: string + /** 货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip)。 */ + channel?: string | null masked: string /** 完整明文值:仅代理列有值(后端对密钥列不下发明文)。 */ full: string diff --git a/admin-frontend-vue/src/pages/account/UserSecretsPage.vue b/admin-frontend-vue/src/pages/account/UserSecretsPage.vue index 3078f13f3..b50e432ef 100644 --- a/admin-frontend-vue/src/pages/account/UserSecretsPage.vue +++ b/admin-frontend-vue/src/pages/account/UserSecretsPage.vue @@ -99,6 +99,22 @@ function moduleTooltip(module: AdminUserSecretModule | undefined) { return parts.join(';') || '暂无检测记录' } +/** 货源标签:LLM 密钥显示渠道(龙抬头/贞贞),代理显示供应商(青果/极客)。 */ +function sourceLabel(channel: string | null | undefined) { + switch (String(channel || '').trim().toLowerCase()) { + case 'longtaitou': + return '龙抬头' + case 't8star': + return '贞贞' + case 'qingguo': + return '青果' + case 'jikip': + return '极客' + default: + return '—' + } +} + /** 分组列文案:优先分组名;未建分组的用户回退展示所属主管,便于判断归属。 */ function groupTextOf(row: AdminUserSecretRow) { if (row.groups?.length) return row.groups.join('、') @@ -311,6 +327,9 @@ onMounted(load)
{{ row.similarAsin.masked }} 未配置 + + {{ sourceLabel(row.similarAsin.channel) }} + {{ moduleStatusMeta(row.similarAsin).label }} @@ -320,6 +339,9 @@ onMounted(load)
{{ row.appearancePatent.masked }} 未配置 + + {{ sourceLabel(row.appearancePatent.channel) }} + {{ moduleStatusMeta(row.appearancePatent).label }} @@ -330,6 +352,9 @@ onMounted(load) {{ row.proxy.full || row.proxy.masked }} 未配置 + + {{ sourceLabel(row.proxy.channel) }} + {{ moduleStatusMeta(row.proxy).label }} @@ -627,6 +652,12 @@ h3 { cursor: help; flex-shrink: 0; } +.wh-pill.is-source { + background: #eef2fb; + border-color: #ccd8f2; + color: #3d5a99; + font-weight: 600; +} .wh-pill.is-allowed { background: #e8f6ee; border-color: #b9e0c9; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/client/AppearancePatentLlmClient.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/client/AppearancePatentLlmClient.java index 853878fdc..e7b215855 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/client/AppearancePatentLlmClient.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/client/AppearancePatentLlmClient.java @@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePate import com.nanri.aiimage.modules.brand.client.BrandCheckClient; import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService; import com.nanri.aiimage.modules.usersecret.support.SecretUsageContext; +import com.nanri.aiimage.modules.usersecret.support.LlmChannel; import com.nanri.aiimage.modules.usersecret.support.UserSecretModule; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -668,7 +669,7 @@ public class AppearancePatentLlmClient { String responseFormat) throws Exception { int attempts = Math.max(1, properties.getLlmRetryTimes()); long cooldownMillis = Math.max(0, properties.getLlmUnreachableCooldownMillis()); - String host = properties.getLlmHost(); + String host = resolveHost(); if (unreachableCooldown.isCoolingDown(host, cooldownMillis)) { // 冷却期快失败不发请求、不记密钥次数(B24) log.debug("[appearance-patent] 客户端级冷却中,快速失败 model={} window={}ms", model, cooldownMillis); @@ -751,11 +752,17 @@ public class AppearancePatentLlmClient { int attempt) { recordSecretUsage(); Map body = buildChatBody(model, system, userText, images, responseFormat); - log.info("[appearance-patent] llm request attempt={} model={} url={} body={}", - attempt, model, joinUrl(properties.getLlmHost(), "/v1/chat/completions"), + String host = resolveHost(); + // 渠道模型映射:龙抬头那边的同款模型叫 gemini-3.1-flash-lite,直接发贞贞的模型名会 model_not_found + String requestModel = LlmChannel.modelForHost(host, model); + body.put("model", requestModel); + // 思考参数按渠道补:贞贞把 thinking 写在模型名里,龙抬头要显式传(复刻现网的 thinking-medium) + LlmChannel.applyThinkingForHost(host, body); + log.info("[appearance-patent] llm request attempt={} model={} channelModel={} url={} body={}", + attempt, model, requestModel, joinUrl(host, "/v1/chat/completions"), writeJson(maskChatBody(body))); RestClient.RequestBodySpec request = restClient(attempt).post() - .uri(joinUrl(properties.getLlmHost(), "/v1/chat/completions")) + .uri(joinUrl(host, "/v1/chat/completions")) .headers(headers -> { headers.setBearerAuth(stripBearer(apiKey)); headers.setContentType(APPLICATION_JSON_UTF8); @@ -1505,6 +1512,12 @@ public class AppearancePatentLlmClient { return normalized.regionMatches(true, 0, "Bearer ", 0, 7) ? normalized.substring(7).trim() : normalized; } + /** 渠道主机:优先取任务上下文里按用户密钥渠道解析出的主机(龙抬头/贞贞),否则回落模块全局配置。 */ + private String resolveHost() { + String contextual = SecretUsageContext.currentLlmHost(); + return contextual == null ? properties.getLlmHost() : contextual; + } + private String joinUrl(String baseUrl, String path) { String base = baseUrl == null ? "" : baseUrl.trim(); String suffix = path == null ? "" : path.trim(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentTaskService.java index c29e9b1a4..1337e0754 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentTaskService.java @@ -74,6 +74,7 @@ import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo; import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler; import com.nanri.aiimage.modules.task.service.pipeline.AbstractFileTaskPipeline; import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService; +import com.nanri.aiimage.modules.usersecret.support.UserSecretModule; @Service @Slf4j @@ -410,7 +411,9 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline userApiSecretService.resolveLlmHost(task.getUserId(), UserSecretModule.APPEARANCE_PATENT), + this::mergeChunkPayload, this::firstNonBlank, this::terminalizeTaskOnFatalLlmFailure); } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentLlmBatchPipeline.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentLlmBatchPipeline.java index 7b7fcc83d..31cbc7c80 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentLlmBatchPipeline.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentLlmBatchPipeline.java @@ -81,6 +81,8 @@ public class AppearancePatentLlmBatchPipeline { private final Consumer taskActivityToucher; private final Function promptReader; private final Function apiKeyReader; + /** 按任务归属用户密钥的渠道解析 LLM 主机(龙抬头/贞贞);为空表示走模块全局配置。 */ + private final Function apiHostReader; private final ChunkRowMerger chunkRowMerger; private final BiFunction firstNonBlankFn; private final FatalLlmFailureHandler fatalLlmFailureHandler; @@ -97,6 +99,7 @@ public class AppearancePatentLlmBatchPipeline { Consumer taskActivityToucher, Function promptReader, Function apiKeyReader, + Function apiHostReader, ChunkRowMerger chunkRowMerger, BiFunction firstNonBlankFn, FatalLlmFailureHandler fatalLlmFailureHandler) { @@ -112,6 +115,7 @@ public class AppearancePatentLlmBatchPipeline { this.taskActivityToucher = taskActivityToucher; this.promptReader = promptReader; this.apiKeyReader = apiKeyReader; + this.apiHostReader = apiHostReader; this.chunkRowMerger = chunkRowMerger; this.firstNonBlankFn = firstNonBlankFn; this.fatalLlmFailureHandler = fatalLlmFailureHandler; @@ -130,6 +134,8 @@ public class AppearancePatentLlmBatchPipeline { } String prompt = promptReader.apply(task); String apiKey = apiKeyReader.apply(task); + // 渠道主机在任务级解析一次:同一任务的批次都发往同一个中转(密钥属于谁就发谁那家) + String apiHost = apiHostReader == null ? null : apiHostReader.apply(task); int batchSize = Math.max(1, properties.getLlmBatchSize()); ChunkRowKeyIndex rowKeyIndex = new ChunkRowKeyIndex(); List candidates = terminalizeRoundExhaustedRows( @@ -177,7 +183,7 @@ public class AppearancePatentLlmBatchPipeline { boolean batchAnswered = true; try { llmRows = SecretUsageContext.call(task.getUserId(), UserSecretModule.APPEARANCE_PATENT.key(), - () -> llmClient.inspectRows(batchRows, prompt, apiKey)); + apiHost, () -> llmClient.inspectRows(batchRows, prompt, apiKey)); } catch (Exception ex) { String message = firstNonBlank(ex.getMessage(), "LLM 检测失败"); if (AppearancePatentResultJobSupport.isFatalLlmArrearsFailure(message)) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/client/SimilarAsinLlmClient.java b/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/client/SimilarAsinLlmClient.java index 47b0b199d..f7717af7b 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/client/SimilarAsinLlmClient.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/client/SimilarAsinLlmClient.java @@ -11,6 +11,7 @@ import com.nanri.aiimage.config.SimilarAsinProperties; import com.nanri.aiimage.metrics.ExternalCallMetricsRecorder; import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService; import com.nanri.aiimage.modules.usersecret.support.SecretUsageContext; +import com.nanri.aiimage.modules.usersecret.support.LlmChannel; import com.nanri.aiimage.modules.usersecret.support.UserSecretModule; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; @@ -93,7 +94,7 @@ public class SimilarAsinLlmClient { String resolvedKey = resolveApiKey(apiKey); int attempts = Math.max(1, properties.getLlmRetryTimes()); long cooldownMillis = Math.max(0, properties.getLlmUnreachableCooldownMillis()); - String host = properties.getLlmHost(); + String host = resolveHost(); if (unreachableCooldown.isCoolingDown(host, cooldownMillis)) { // 冷却期快失败不发请求、不记密钥次数:结论与短路版一致(调用方拿不到 LLM 结论), // 差别只是不再为"确认还是断的"各烧一轮连接探针(B24) @@ -186,11 +187,17 @@ public class SimilarAsinLlmClient { int attempt) { recordSecretUsage(); Map body = buildChatBody(model, system, userText, images, responseFormat); - log.debug("[similar-asin][llm] request attempt={} model={} url={} body={}", - attempt, model, joinUrl(properties.getLlmHost(), "/v1/chat/completions"), + String host = resolveHost(); + // 渠道模型映射:龙抬头那边的同款模型叫 gemini-3.1-flash-lite,直接发贞贞的模型名会 model_not_found + String requestModel = LlmChannel.modelForHost(host, model); + body.put("model", requestModel); + // 思考参数按渠道补:贞贞把 thinking 写在模型名里,龙抬头要显式传(复刻现网的 thinking-medium) + LlmChannel.applyThinkingForHost(host, body); + log.debug("[similar-asin][llm] request attempt={} model={} channelModel={} url={} body={}", + attempt, model, requestModel, joinUrl(host, "/v1/chat/completions"), writeJson(maskChatBody(body))); RestClient.RequestBodySpec request = restClient(attempt).post() - .uri(joinUrl(properties.getLlmHost(), "/v1/chat/completions")) + .uri(joinUrl(host, "/v1/chat/completions")) .headers(headers -> { headers.setBearerAuth(stripBearer(apiKey)); headers.setContentType(APPLICATION_JSON_UTF8); @@ -475,6 +482,15 @@ public class SimilarAsinLlmClient { return normalized.regionMatches(true, 0, "Bearer ", 0, 7) ? normalized.substring(7).trim() : normalized; } + /** + * 渠道主机:优先取任务上下文里按用户密钥渠道解析出的主机(龙抬头/贞贞), + * 没有上下文(单测、巡检等)时回落模块全局配置,保持历史行为。 + */ + private String resolveHost() { + String contextual = SecretUsageContext.currentLlmHost(); + return contextual == null ? properties.getLlmHost() : contextual; + } + private String joinUrl(String baseUrl, String path) { String base = baseUrl == null ? "" : baseUrl.trim(); String suffix = path == null ? "" : path.trim(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPayloadSupport.java b/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPayloadSupport.java index daeef5203..610536ed3 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPayloadSupport.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPayloadSupport.java @@ -233,6 +233,11 @@ public class SimilarAsinPayloadSupport { return fromUserSecret; } + /** 任务归属用户密钥所属渠道的 LLM 主机:密钥属于哪条中转(龙抬头/贞贞)就发到哪条。 */ + public String resolveLlmHost(FileTaskEntity task) { + return userApiSecretService.resolveLlmHost(task.getUserId(), UserSecretModule.SIMILAR_ASIN); + } + public boolean readImgSwitch(FileTaskEntity task) { try { return Boolean.TRUE.equals(readParsedPayload(task).getImgSwitch()); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPipelineSupport.java b/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPipelineSupport.java index 10190530f..028e47e5d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPipelineSupport.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/similarasin/service/support/SimilarAsinPipelineSupport.java @@ -931,10 +931,12 @@ public class SimilarAsinPipelineSupport { boolean categorySwitch = host.readCategorySwitch(task); int batchSize = SimilarAsinLimits.resolveLlmBatchSize(properties, imgSwitch); List result = new ArrayList<>(); + // 渠道主机任务级解析一次:本任务的所有批次都发往同一家中转 + String apiHost = payloadSupport.resolveLlmHost(task); for (int i = 0; i < items.size(); i += batchSize) { List batch = items.subList(i, Math.min(i + batchSize, items.size())); // 批次内所有 LLM 请求按任务归属用户计次(无归属时上下文自动跳过) - result.addAll(SecretUsageContext.call(task.getUserId(), UserSecretModule.SIMILAR_ASIN.key(), + result.addAll(SecretUsageContext.call(task.getUserId(), UserSecretModule.SIMILAR_ASIN.key(), apiHost, () -> similarAsinLlmService.inspectRows(batch, prompt, apiKey, imgSwitch, categorySwitch))); if (progressHook != null) { progressHook.run(); @@ -1294,6 +1296,7 @@ public class SimilarAsinPipelineSupport { List llmRows; try { llmRows = SecretUsageContext.call(task.getUserId(), UserSecretModule.SIMILAR_ASIN.key(), + payloadSupport.resolveLlmHost(task), () -> similarAsinLlmService.inspectRows(batchRows, prompt, apiKey, imgSwitch, categorySwitch)); } catch (Exception ex) { String message = firstNonBlank(ex.getMessage(), "LLM submit failed"); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java index cbf9a25dd..a4fbfa49e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java @@ -99,7 +99,7 @@ public class AdminUserApiSecretController { @Valid @RequestBody UserApiSecretSaveRequest body) { AdminUserEntity operator = adminAuthSupport.requireAdmin(request); return ApiResponse.success("已代填并锁定", - userApiSecretService.adminSaveModule(operator, userId, moduleKey, body.getValue())); + userApiSecretService.adminSaveModule(operator, userId, moduleKey, body.getValue(), body.getChannel())); } @DeleteMapping("/{userId}/modules/{moduleKey}") diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java index 3d65978e3..bfc79b830 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java @@ -62,7 +62,7 @@ public class UserApiSecretController { @Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey, @Valid @RequestBody UserApiSecretSaveRequest body) { Long userId = currentUserId(request); - return ApiResponse.success("保存成功", userApiSecretService.save(userId, moduleKey, body.getValue())); + return ApiResponse.success("保存成功", userApiSecretService.save(userId, moduleKey, body.getValue(), body.getChannel())); } @DeleteMapping("/{moduleKey}") @@ -85,7 +85,8 @@ public class UserApiSecretController { @RequestBody(required = false) UserApiSecretCheckRequest body) { Long userId = currentUserId(request); String overrideValue = body == null ? null : body.getValue(); - return ApiResponse.success("检测完成", userApiSecretService.check(userId, moduleKey, overrideValue)); + String channel = body == null ? null : body.getChannel(); + return ApiResponse.success("检测完成", userApiSecretService.check(userId, moduleKey, overrideValue, channel)); } @PostMapping("/migrate") diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretCheckRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretCheckRequest.java index 5277414bd..05a8d8d76 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretCheckRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretCheckRequest.java @@ -9,4 +9,8 @@ public class UserApiSecretCheckRequest { @Schema(description = "待检测的密钥明文;为空时检测服务端已保存的密钥(结果落库),非空时仅检测输入值(不落库)") private String value; + + @Schema(description = "待检测的货源(未保存的下拉选择):LLM 密钥填 longtaitou/t8star,代理填 qingguo/jikip;" + + "为空时按服务端已存行的渠道/供应商检测") + private String channel; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretMigrateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretMigrateRequest.java index 9cb2dc0c1..07a43e803 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretMigrateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretMigrateRequest.java @@ -24,5 +24,8 @@ public class UserApiSecretMigrateRequest { @Schema(description = "密钥明文", requiredMode = Schema.RequiredMode.REQUIRED) private String value; + + @Schema(description = "货源:LLM 密钥填 longtaitou/t8star,代理填 qingguo/jikip;为空时按模块默认值") + private String channel; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretSaveRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretSaveRequest.java index 86d753968..618c41007 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretSaveRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserApiSecretSaveRequest.java @@ -11,4 +11,7 @@ public class UserApiSecretSaveRequest { @NotBlank(message = "密钥不能为空") @Schema(description = "密钥明文(服务端加密存储)", requiredMode = Schema.RequiredMode.REQUIRED) private String value; + + @Schema(description = "货源:LLM 密钥填 longtaitou/t8star(缺省=龙抬头);代理填 qingguo/jikip(缺省=青果)") + private String channel; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserApiSecretEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserApiSecretEntity.java index 5e4b76bf2..d0ccf1311 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserApiSecretEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserApiSecretEntity.java @@ -15,6 +15,8 @@ public class UserApiSecretEntity { private Long id; private Long userId; private String moduleKey; + /** 货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip),见 V180。 */ + private String channel; private String secretValue; private String checkStatus; private String checkCode; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretModuleVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretModuleVo.java index b4cf03cba..51f1117ee 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretModuleVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretModuleVo.java @@ -15,6 +15,9 @@ public class AdminUserSecretModuleVo { @Schema(description = "密钥模块显示名") private String moduleLabel; + @Schema(description = "货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip)") + private String channel; + @Schema(description = "脱敏值") private String masked; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretItemVo.java index 87104bedd..c1863b6f6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretItemVo.java @@ -15,6 +15,9 @@ public class UserApiSecretItemVo { @Schema(description = "密钥模块显示名") private String moduleLabel; + @Schema(description = "货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip);未配置时为空") + private String channel; + @Schema(description = "脱敏值,如 sk-a****1234") private String masked; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckService.java index a51243d99..0d9e97c86 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckService.java @@ -9,6 +9,8 @@ import com.nanri.aiimage.config.SimilarAsinProperties; import com.nanri.aiimage.config.UserSecretProperties; import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient; import com.nanri.aiimage.modules.usersecret.support.UserSecretModule; +import com.nanri.aiimage.modules.usersecret.support.ProxyProvider; +import com.nanri.aiimage.modules.usersecret.support.LlmChannel; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; @@ -93,8 +95,16 @@ public class UserApiSecretCheckService { * 代理模块不重试——jikip 按提取次数计费,重试会多扣一次。 */ public CheckOutcome probe(UserSecretModule module, String plainApiKey) { + return probe(module, plainApiKey, null); + } + + /** + * 探测入口(带货源):LLM 密钥按所选渠道取主机;代理按所选供应商解析提取响应。 + * 货源为空时沿用历史口径(模块全局主机 / 极客解析)。 + */ + public CheckOutcome probe(UserSecretModule module, String plainApiKey, String channel) { if (module == UserSecretModule.PROXY) { - return probeProxy(plainApiKey); + return probeProxy(plainApiKey, channel); } String proxyUrl; try { @@ -104,14 +114,14 @@ public class UserApiSecretCheckService { return new CheckOutcome(STATUS_FAILED, CODE_INSUFFICIENT_BALANCE, INSUFFICIENT_BALANCE_MESSAGE, null, false); } if (proxyUrl != null) { - CheckOutcome viaProxy = probeOnce(module, plainApiKey, proxyUrl, true); + CheckOutcome viaProxy = probeOnce(module, plainApiKey, proxyUrl, true, channel); if (isTransportFailure(viaProxy)) { // 掩码后再打日志:proxyUrl 含用户代理账密,明文入日志等于持久化敏感凭据 log.warn("[user-secret][check] 经代理检测失败 module={} proxy={} code={},回退直连重试", module.key(), SecretMasking.maskProxy(proxyUrl), viaProxy.code()); - CheckOutcome direct = probeOnce(module, plainApiKey, null, false); + CheckOutcome direct = probeOnce(module, plainApiKey, null, false, channel); if (isTransportFailure(direct)) { - direct = retryOnce(module, plainApiKey, direct); + direct = retryOnce(module, plainApiKey, direct, channel); } return new CheckOutcome( direct.status(), @@ -122,16 +132,16 @@ public class UserApiSecretCheckService { } return viaProxy; } - CheckOutcome direct = probeOnce(module, plainApiKey, null, false); - return isTransportFailure(direct) ? retryOnce(module, plainApiKey, direct) : direct; + CheckOutcome direct = probeOnce(module, plainApiKey, null, false, channel); + return isTransportFailure(direct) ? retryOnce(module, plainApiKey, direct, channel) : direct; } /** 传输层失败重试一次(间隔 {@link #RETRY_BACKOFF_MILLIS}):抗上游偶发单请求不响应。 */ - private CheckOutcome retryOnce(UserSecretModule module, String plainApiKey, CheckOutcome failed) { + private CheckOutcome retryOnce(UserSecretModule module, String plainApiKey, CheckOutcome failed, String channel) { log.warn("[user-secret][check] 直连探测失败 module={} code={} latency={}ms,{}ms 后重试一次", module.key(), failed.code(), failed.latencyMs(), RETRY_BACKOFF_MILLIS); sleepQuietly(RETRY_BACKOFF_MILLIS); - CheckOutcome retried = probeOnce(module, plainApiKey, null, false); + CheckOutcome retried = probeOnce(module, plainApiKey, null, false, channel); if (isTransportFailure(retried)) { log.warn("[user-secret][check] 重试仍失败 module={} code={} latency={}ms", module.key(), retried.code(), retried.latencyMs()); @@ -167,6 +177,10 @@ public class UserApiSecretCheckService { * 「假通过」(3-39ms + HTTP 301),余额不足 / 链接失效都测不出来。 */ private CheckOutcome probeProxy(String proxyUrl) { + return probeProxy(proxyUrl, null); + } + + private CheckOutcome probeProxy(String proxyUrl, String channel) { String normalized = proxyUrl == null ? "" : proxyUrl.trim(); if (normalized.isEmpty()) { return new CheckOutcome(STATUS_FAILED, CODE_INVALID_KEY, "代理地址为空,请重新配置", null, true); @@ -178,31 +192,103 @@ public class UserApiSecretCheckService { return probeThroughProxy(normalized, startMillis); } - // 提取链接:先真实提取一次 - String body; + // 供应商:显式选择优先,其次按链接域名识别,最后按默认(青果) + ProxyProvider provider = ProxyProvider.parse(channel); + if (provider == null) { + ProxyProvider detected = ProxyProvider.detectFromUrl(normalized); + provider = detected == null ? ProxyProvider.DEFAULT : detected; + } + + // 提取链接:先真实提取一次。刻意读响应体而不依赖 2xx—— + // 青果的失败码(API_AUTH_DENY / BALANCE_INSUFFICIENT)走 HTTP 4xx, + // 交给 RestClient 抛异常会把「密钥没授权」误报成「接口无法访问」。 + StatusAndBody extract; try { - body = clientFor(null).get().uri(normalized).retrieve().body(String.class); + extract = clientFor(null).get().uri(normalized) + .exchange((request, response) -> new StatusAndBody( + response.getStatusCode().value(), + readResponseBodyBounded(response.getBody()))); } catch (Exception ex) { long latency = System.currentTimeMillis() - startMillis; - log.warn("[user-secret][check] 代理提取接口不可达 latency={}ms err={}", latency, ex.getMessage()); + log.warn("[user-secret][check] 代理提取接口不可达 provider={} latency={}ms err={}", + provider.key(), latency, ex.getMessage()); return new CheckOutcome(STATUS_FAILED, CODE_NETWORK_ERROR, "代理提取接口无法访问,请检查提取链接或稍后重试", (int) latency, false); } long extractLatency = System.currentTimeMillis() - startMillis; - if (isInsufficientBalance(body)) { - log.warn("[user-secret][check] 代理提取被拒:供应商余额不足 latency={}ms", extractLatency); - return new CheckOutcome(STATUS_FAILED, CODE_INSUFFICIENT_BALANCE, - INSUFFICIENT_BALANCE_MESSAGE, (int) extractLatency, false); + CheckOutcome rejection = classifyProviderRejection(provider, extract.body(), (int) extractLatency); + if (rejection != null) { + log.warn("[user-secret][check] 代理提取被供应商拒绝 provider={} httpStatus={} code={}", + provider.key(), extract.statusCode(), rejection.code()); + return rejection; } - String extractedProxyUrl = extractProxyUrlFromBody(body); + String extractedProxyUrl = extractProxyUrlFromBody(extract.body()); if (extractedProxyUrl == null) { - log.warn("[user-secret][check] 代理提取响应未解析出 IP,响应前 150 字={}", abbreviate(body, 150)); + log.warn("[user-secret][check] 代理提取响应未解析出 IP provider={} httpStatus={} 响应前 150 字={}", + provider.key(), extract.statusCode(), abbreviate(extract.body(), 150)); return new CheckOutcome(STATUS_FAILED, CODE_INVALID_KEY, "链接未返回可用 IP,请检查代理提取配置", (int) extractLatency, false); } + if (provider == ProxyProvider.QINGGUO) { + // 青果通道提取返回的是**隧道端点**(如 tunpool-xxx.qg.net:16359),连它要用 + // Authkey/Authpwd 做 Basic 认证,而这对账密只存在用户本机、不上报服务端; + // 所以这里只验"提取接口可用且拿到端点",连接态由客户端的实际任务证明。 + log.info("[user-secret][check] 青果提取成功,跳过经隧道探测(端点鉴权在客户端)endpoint={}", + SecretMasking.maskProxy(extractedProxyUrl)); + return new CheckOutcome(STATUS_PASSED, CODE_OK, + "提取成功(青果隧道端点,连接鉴权在客户端)", (int) extractLatency, false); + } return probeThroughProxy(extractedProxyUrl, startMillis); } + /** + * 供应商拒付/鉴权失败的独立分类(两家错误码词表不同): + *
    + *
  • 青果:code 为字符串。BALANCE_INSUFFICIENT=余额不足;INVALID_KEY/UNAVAILABLE_KEY/KEY_BLOCK/ + * ACCESS_DENY/API_AUTH_DENY=密钥不可用或未授权;REQUEST_LIMIT_EXCEEDED=限流; + * INVALID_PARAMETER=参数错;其余业务失败按上游异常。
  • + *
  • 极客:沿用历史口径(code=-1 或 message 含「余额不足」=余额不足)。
  • + *
+ * 返回 null 表示不是拒付/鉴权类失败,继续走 IP 解析。 + */ + CheckOutcome classifyProviderRejection(ProxyProvider provider, String body, int latencyMs) { + if (provider == ProxyProvider.QINGGUO) { + JsonNode root = parseJson(body); + if (root == null || !root.isObject()) { + return null; + } + JsonNode codeNode = root.get("code"); + String code = codeNode == null || codeNode.isNull() ? "" : codeNode.asText("").trim(); + if (code.isEmpty() || "SUCCESS".equalsIgnoreCase(code) || "0".equals(code)) { + return null; + } + String message = text(root.get("message")); + String detail = message == null || message.isBlank() ? "" : ":" + abbreviate(message, 120); + String upper = code.toUpperCase(java.util.Locale.ROOT); + return switch (upper) { + case "BALANCE_INSUFFICIENT" -> + new CheckOutcome(STATUS_FAILED, CODE_INSUFFICIENT_BALANCE, INSUFFICIENT_BALANCE_MESSAGE, latencyMs, false); + case "INVALID_KEY", "UNAVAILABLE_KEY", "KEY_BLOCK", "ACCESS_DENY", "API_AUTH_DENY" -> + new CheckOutcome(STATUS_FAILED, CODE_FORBIDDEN, + "青果密钥不可用或未授权(" + upper + ")" + detail, latencyMs, false); + case "REQUEST_LIMIT_EXCEEDED" -> + new CheckOutcome(STATUS_ERROR, CODE_RATE_LIMITED, "青果提取触发限流,本次无法判定" + detail, latencyMs, false); + case "NO_AVAILABLE_CHANNEL" -> + // 通道被占满(存活期内一个通道只给一个端点):不是密钥问题,稍后重试即可 + new CheckOutcome(STATUS_ERROR, CODE_PROVIDER_ERROR, + "青果通道已全部占用,请等当前通道释放(约 3 分钟)后重试" + detail, latencyMs, false); + case "INVALID_PARAMETER" -> + new CheckOutcome(STATUS_FAILED, CODE_BAD_REQUEST, "青果提取参数不正确" + detail, latencyMs, false); + default -> + new CheckOutcome(STATUS_FAILED, CODE_PROVIDER_ERROR, "青果提取失败(" + upper + ")" + detail, latencyMs, false); + }; + } + if (isInsufficientBalance(body)) { + return new CheckOutcome(STATUS_FAILED, CODE_INSUFFICIENT_BALANCE, INSUFFICIENT_BALANCE_MESSAGE, latencyMs, false); + } + return null; + } + /** 经指定代理请求自家域名:任意 HTTP 响应即转发可用;407 为代理自身认证失败;网络异常不可达。 */ private CheckOutcome probeThroughProxy(String proxyUrl, long startMillis) { try { @@ -245,7 +331,7 @@ public class UserApiSecretCheckService { } } - /** 提取响应解析:JSON data.list[0] 的 ip/port(账密可选)优先,正文 ip:port 正则兜底。 */ + /** 提取响应解析:青果 data[0].server 优先;极客 data.list[0] 的 ip/port(账密可选)其次;正文 ip:port 正则兜底。 */ String extractProxyUrlFromBody(String body) { String text = body == null ? "" : body.trim(); if (text.isEmpty()) { @@ -254,6 +340,10 @@ public class UserApiSecretCheckService { if (text.charAt(0) == '{' || text.charAt(0) == '[') { JsonNode root = parseJson(text); if (root != null) { + String qingguo = qingguoProxyUrl(root); + if (qingguo != null) { + return qingguo; + } JsonNode list = root.path("data").path("list"); if (list.isArray() && list.size() > 0) { JsonNode first = list.get(0); @@ -277,7 +367,37 @@ public class UserApiSecretCheckService { return null; } - /** 提取响应是否表明供应商欠费(如 jikip {"code":-1,"data":null,"message":"余额不足"})。 */ + /** + * 青果提取响应解析:{@code {"code":"SUCCESS","data":[{"proxy_ip":"1.2.3.4","server":"1.2.3.4:8080",...}]}}。 + * server 才是代理地址,proxy_ip 只是出口 IP(青果文档明确区分)——拿错字段会得到一个 + * 没端口的裸 IP,探测直接失败。缺 server 时按 ip/port 两字段兜底;都没有返回 null 交给上层报错。 + */ + private String qingguoProxyUrl(JsonNode root) { + JsonNode data = root.path("data"); + if (!data.isArray() || data.isEmpty()) { + return null; + } + JsonNode first = data.get(0); + if (first == null || !first.isObject()) { + return null; + } + String server = text(first.get("server")); + if (server != null && !server.isBlank()) { + String trimmed = server.trim(); + return trimmed.startsWith("http://") || trimmed.startsWith("https://") + ? trimmed + : "http://" + trimmed; + } + String ip = text(first.get("ip")); + String port = text(first.get("port")); + if (ip != null && !ip.isBlank() && port != null && !port.isBlank()) { + return "http://" + ip + ":" + port; + } + return null; + } + + + /** 提取响应是否表明供应商欠费(极客 {"code":-1,...,"message":"余额不足"} / 青果 code=BALANCE_INSUFFICIENT)。 */ boolean isInsufficientBalance(String body) { String text = body == null ? "" : body.trim(); if (text.isEmpty()) { @@ -290,16 +410,24 @@ public class UserApiSecretCheckService { return true; } JsonNode code = root.get("code"); - if (code != null && !code.isNull() && code.asDouble(Double.NaN) == -1D) { - return true; + if (code != null && !code.isNull()) { + if (code.isNumber() && code.asDouble(Double.NaN) == -1D) { + return true; + } + if (code.isTextual() && "BALANCE_INSUFFICIENT".equalsIgnoreCase(code.asText().trim())) { + return true; + } } } return text.contains("余额不足"); } - private CheckOutcome probeOnce(UserSecretModule module, String plainApiKey, String proxyUrl, boolean viaProxy) { - String host = module.resolveLlmHost(appearancePatentProperties, similarAsinProperties); - String model = userSecretProperties.getCheckModel(); + private CheckOutcome probeOnce(UserSecretModule module, String plainApiKey, String proxyUrl, boolean viaProxy, + String channel) { + String host = module.resolveLlmHost(appearancePatentProperties, similarAsinProperties, channel); + // 检测也要按渠道换模型名:龙抬头那边叫 gemini-3.1-flash-lite,发贞贞的名字会 404/model_not_found, + // 用户会误以为自己的密钥坏了 + String model = LlmChannel.modelForHost(host, userSecretProperties.getCheckModel()); String url = joinUrl(host, "/v1/chat/completions"); String key = stripBearer(plainApiKey); long startMillis = System.currentTimeMillis(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java index 0d64ca625..8072be5df 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java @@ -6,6 +6,8 @@ import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort; import com.nanri.aiimage.common.security.ShopCredentialCryptoService; import com.nanri.aiimage.config.UserSecretProperties; +import com.nanri.aiimage.config.AppearancePatentProperties; +import com.nanri.aiimage.config.SimilarAsinProperties; import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.DeviceSessionPolicy; import com.nanri.aiimage.common.service.ReadScope; @@ -28,6 +30,8 @@ import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo; import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo; import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretItemVo; import com.nanri.aiimage.modules.usersecret.support.UserSecretModule; +import com.nanri.aiimage.modules.usersecret.support.LlmChannel; +import com.nanri.aiimage.modules.usersecret.support.ProxyProvider; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; @@ -98,6 +102,8 @@ public class UserApiSecretService implements UserSecretCleanupPort { private final UserDataScopeSupport userDataScopeSupport; private final NotificationDispatchService notificationDispatchService; private final UserSecretProperties userSecretProperties; + private final AppearancePatentProperties appearancePatentProperties; + private final SimilarAsinProperties similarAsinProperties; private final StringRedisTemplate stringRedisTemplate; private final ObjectMapper objectMapper; @@ -117,6 +123,12 @@ public class UserApiSecretService implements UserSecretCleanupPort { return vo; } + /** 兼容旧签名:不传货源时按模块默认值保存。 */ + @Transactional + public UserApiSecretItemVo save(Long userId, String moduleKey, String value) { + return save(userId, moduleKey, value, null); + } + /** * 保存密钥:加密落库并重置检测状态为 unknown; * 若该值与用户刚检测过的输入值完全一致,则沿用那次检测结果(见 {@link #applyPendingVerification}), @@ -124,7 +136,7 @@ public class UserApiSecretService implements UserSecretCleanupPort { * 后台代填并锁定的模块(source=admin)客户端不可覆盖。 */ @Transactional - public UserApiSecretItemVo save(Long userId, String moduleKey, String value) { + public UserApiSecretItemVo save(Long userId, String moduleKey, String value, String channel) { requireUserId(userId); UserSecretModule module = requireModule(moduleKey); requireNotAdminLocked(userId, module, "修改"); @@ -135,9 +147,15 @@ public class UserApiSecretService implements UserSecretCleanupPort { if (module == UserSecretModule.PROXY) { validateProxyValue(plainValue); } - upsert(userId, module.key(), plainValue, SOURCE_CLIENT); - boolean carried = applyPendingVerification(userId, module, plainValue); - log.info("[user-secret] 密钥已保存 userId={} module={} 沿用检测结果={}", userId, module.key(), carried); + // 代理没给供应商时按链接域名识别(老客户端只上报地址):极客链接别记成青果。 + // LLM 密钥没给渠道才按产品默认(新密钥默认龙抬头)。 + String channelKey = hasText(channel) + ? module.requireChannel(channel) + : (module.isProxy() ? module.channelOrDefault(null, plainValue) : module.defaultChannel()); + upsert(userId, module.key(), plainValue, SOURCE_CLIENT, channelKey); + boolean carried = applyPendingVerification(userId, module, plainValue, channelKey); + log.info("[user-secret] 密钥已保存 userId={} module={} channel={} 沿用检测结果={}", + userId, module.key(), channelKey, carried); return toItem(module, selectOne(userId, module.key())); } @@ -153,13 +171,20 @@ public class UserApiSecretService implements UserSecretCleanupPort { log.info("[user-secret] 密钥已清空 userId={} module={}", userId, module.key()); } + /** 兼容旧签名:后台代填不传货源时按链接识别,识别不出回落模块默认值(代理=青果)。 */ + @Transactional + public AdminUserSecretModuleVo adminSaveModule(AdminUserEntity operator, Long userId, String moduleKey, String value) { + return adminSaveModule(operator, userId, moduleKey, value, null); + } + /** * 后台代填并锁定:写入后该模块 source=admin,客户端不可修改或清空。 * 目前仅开放代理设置——密钥模块要由客户端提交任务时携带本地明文,代填会让用户用不了。 * 数据权限:超管可操作全部用户,其余管理员限自己数据权限范围内的用户。 */ @Transactional - public AdminUserSecretModuleVo adminSaveModule(AdminUserEntity operator, Long userId, String moduleKey, String value) { + public AdminUserSecretModuleVo adminSaveModule(AdminUserEntity operator, Long userId, String moduleKey, + String value, String channel) { requireUserId(userId); requireVisibleUser(operator, userId); UserSecretModule module = requireModule(moduleKey); @@ -171,9 +196,13 @@ public class UserApiSecretService implements UserSecretCleanupPort { throw new BusinessException("代理地址不能为空"); } validateProxyValue(plainValue); - upsert(userId, module.key(), plainValue, SOURCE_ADMIN); - log.info("[user-secret] 后台代填并锁定配置 userId={} module={} operatorId={}", - userId, module.key(), operator == null ? null : operator.getId()); + // 后台代填没给供应商时按链接域名识别(代填的是极客链接就记 jikip),识别不出才用默认青果 + String channelKey = hasText(channel) + ? module.requireChannel(channel) + : module.channelOrDefault(null, plainValue); + upsert(userId, module.key(), plainValue, SOURCE_ADMIN, channelKey); + log.info("[user-secret] 后台代填并锁定配置 userId={} module={} channel={} operatorId={}", + userId, module.key(), channelKey, operator == null ? null : operator.getId()); return toModuleVo(module, selectOne(userId, module.key())); } @@ -234,7 +263,12 @@ public class UserApiSecretService implements UserSecretCleanupPort { if (existing != null && hasText(existing.getSecretValue())) { continue; } - upsert(userId, module.get().key(), plainValue, SOURCE_MIGRATED); + // 老客户端只上报明文、不上报货源:这类存量密钥当时跑的就是贞贞/极客, + // 不能按「新建默认」落成龙抬头/青果(会把老密钥发到它没开通过的渠道)。 + String migratedChannel = hasText(item.getChannel()) + ? module.get().requireChannel(item.getChannel()) + : legacyChannel(module.get()); + upsert(userId, module.get().key(), plainValue, SOURCE_MIGRATED, migratedChannel); migrated++; } log.info("[user-secret] 本地密钥迁移完成 userId={} 提交={} 实际写入={}", userId, items.size(), migrated); @@ -258,23 +292,68 @@ public class UserApiSecretService implements UserSecretCleanupPort { } } + /** + * 任务执行兜底读取「货源」:未配置返回空串(调用方按模块默认值处理)。 + * 代理模块额外做链接域名识别,兜住老数据(只有链接、没有供应商列)的存量行。 + */ + public String findChannel(Long userId, String moduleKey) { + if (userId == null || userId <= 0 || !hasText(moduleKey)) { + return ""; + } + Optional module = UserSecretModule.of(moduleKey); + if (module.isEmpty()) { + return ""; + } + // 刻意不在这里兜异常(与 findPlainValue 不同):读库失败时回落空串等于"按默认渠道发", + // 会把贞贞的密钥静默发到龙抬头——错渠道比一次可见的失败更难查。让它抛,任务当场失败。 + UserApiSecretEntity row = selectOne(userId, module.get().key()); + String stored = row == null ? "" : row.getChannel(); + if (module.get().isProxy()) { + String plain = row == null ? "" : normalize(decryptQuietly(row.getSecretValue())); + return module.get().channelOrDefault(stored, plain); + } + return module.get().channelOrDefault(stored, null); + } + + /** + * 按用户密钥所属渠道解析 LLM 主机:任务执行与检测共用同一口径。 + * 用户没配密钥时返回模块全局配置主机,保证后续报错来自「没有密钥」而不是「主机为空」。 + */ + public String resolveLlmHost(Long userId, UserSecretModule module) { + return module.resolveLlmHost(appearancePatentProperties, similarAsinProperties, + findChannel(userId, module.key())); + } + + /** 存量迁移/回填的货源:LLM=贞贞,代理=极客(本功能上线前系统实际在用的两家)。 */ + private String legacyChannel(UserSecretModule module) { + return module.isProxy() ? ProxyProvider.JIKIP.key() : LlmChannel.T8STAR.key(); + } + + /** 兼容旧签名:不传货源时按已存行/模块默认值检测。 */ + public UserApiSecretCheckResultVo check(Long userId, String moduleKey, String overrideValue) { + return check(userId, moduleKey, overrideValue, null); + } + /** * 检测:传 overrideValue 时只检测输入值,结果暂存(不落库),保存同一个值时可沿用; * 不传时检测已存值并直接落库。 + * + *

货源(渠道/供应商)优先取本次请求带的选择,其次取服务端已存行;都为空时按模块默认值。 + * 检测必须按同一个货源发起——渠道选错时「连通」是个假结论。

*/ - public UserApiSecretCheckResultVo check(Long userId, String moduleKey, String overrideValue) { + public UserApiSecretCheckResultVo check(Long userId, String moduleKey, String overrideValue, String channel) { requireUserId(userId); UserSecretModule module = requireModule(moduleKey); String override = normalize(overrideValue); String plainKey = override; boolean persist = false; + UserApiSecretEntity existingRow = selectOne(userId, module.key()); if (plainKey.isEmpty()) { - UserApiSecretEntity row = selectOne(userId, module.key()); - if (row == null || !hasText(row.getSecretValue())) { + if (existingRow == null || !hasText(existingRow.getSecretValue())) { throw new BusinessException(module == UserSecretModule.PROXY ? "请先保存代理地址后再检测" : "请先保存密钥后再检测"); } - plainKey = normalize(cryptoService.decrypt(row.getSecretValue())); + plainKey = normalize(cryptoService.decrypt(existingRow.getSecretValue())); if (plainKey.isEmpty()) { throw new BusinessException("配置内容为空,请重新配置"); } @@ -282,14 +361,18 @@ public class UserApiSecretService implements UserSecretCleanupPort { } else if (module == UserSecretModule.PROXY) { validateProxyValue(plainKey); } - UserApiSecretCheckService.CheckOutcome outcome = reuseFreshOutcome(module, plainKey); + String requestedChannel = hasText(channel) + ? channel + : (existingRow == null ? null : existingRow.getChannel()); + String channelKey = module.channelOrDefault(requestedChannel, plainKey); + UserApiSecretCheckService.CheckOutcome outcome = reuseFreshOutcome(module, plainKey, channelKey); if (outcome != null) { - log.info("[user-secret] 新鲜期内重复检测相同配置,复用上次结果(代理按次计费,避免连点重复提取)userId={} module={}", - userId, module.key()); + log.info("[user-secret] 新鲜期内重复检测相同配置,复用上次结果(代理按次计费,避免连点重复提取)userId={} module={} channel={}", + userId, module.key(), channelKey); } else { - outcome = checkService.probe(module, plainKey); + outcome = checkService.probe(module, plainKey, channelKey); if (UserApiSecretCheckService.STATUS_PASSED.equals(outcome.status())) { - rememberFreshOutcome(module, plainKey, outcome); + rememberFreshOutcome(module, plainKey, channelKey, outcome); } } UserApiSecretCheckResultVo vo = toCheckResult(module, outcome); @@ -297,10 +380,10 @@ public class UserApiSecretService implements UserSecretCleanupPort { applyCheckOutcome(userId, module.key(), outcome); vo.setCheckedAt(LocalDateTime.now()); } else { - rememberPendingVerification(userId, module, plainKey, outcome); + rememberPendingVerification(userId, module, plainKey, channelKey, outcome); } - log.info("[user-secret] 检测完成 userId={} module={} status={} code={} viaProxy={} latency={}ms persist={}", - userId, module.key(), outcome.status(), outcome.code(), outcome.viaProxy(), outcome.latencyMs(), persist); + log.info("[user-secret] 检测完成 userId={} module={} channel={} status={} code={} viaProxy={} latency={}ms persist={}", + userId, module.key(), channelKey, outcome.status(), outcome.code(), outcome.viaProxy(), outcome.latencyMs(), persist); return vo; } @@ -517,7 +600,8 @@ public class UserApiSecretService implements UserSecretCleanupPort { UserApiSecretCheckService.CODE_INVALID_KEY, "配置内容为空,请重新配置", null, false); } else { - outcome = checkService.probe(module, plainValue); + outcome = checkService.probe(module, plainValue, + module.channelOrDefault(row.getChannel(), plainValue)); } } catch (Exception ex) { log.warn("[user-secret] 后台检测解密失败 userId={} module={} err={}", userId, module.key(), ex.getMessage()); @@ -599,7 +683,8 @@ public class UserApiSecretService implements UserSecretCleanupPort { UserApiSecretCheckService.STATUS_FAILED, UserApiSecretCheckService.CODE_INVALID_KEY, "配置内容为空,请重新配置", null, false) - : checkService.probe(module.get(), plainKey); + : checkService.probe(module.get(), plainKey, + module.get().channelOrDefault(row.getChannel(), plainKey)); outcomeBySecret.put(groupKey, outcome); probed++; sleepQuietly(200L); @@ -642,7 +727,8 @@ public class UserApiSecretService implements UserSecretCleanupPort { /** 巡检分组键:同模块 + 同密文视为同一把密钥。密文确定性加密,无需解密即可分组。 */ private String inspectionGroupKey(UserApiSecretEntity row) { - return row.getModuleKey() + '|' + row.getSecretValue(); + // 渠道参与分组:同一串密钥在龙抬头与贞贞上是两次独立探测,合并会拿 A 的结论冒充 B + return row.getModuleKey() + '|' + (row.getChannel() == null ? "" : row.getChannel()) + '|' + row.getSecretValue(); } /** @@ -860,12 +946,13 @@ public class UserApiSecretService implements UserSecretCleanupPort { return earliest; } - private void upsert(Long userId, String moduleKey, String plainValue, String source) { + private void upsert(Long userId, String moduleKey, String plainValue, String source, String channel) { LocalDateTime now = LocalDateTime.now(); UserApiSecretEntity existing = selectOne(userId, moduleKey); UserApiSecretEntity row = existing == null ? new UserApiSecretEntity() : existing; row.setUserId(userId); row.setModuleKey(moduleKey); + row.setChannel(channel); row.setSecretValue(cryptoService.encrypt(plainValue)); row.setCheckStatus(STATUS_UNKNOWN); row.setCheckCode(""); @@ -906,20 +993,20 @@ public class UserApiSecretService implements UserSecretCleanupPort { } /** - * 检测值指纹:SHA-256(uid|module|明文)。用于判断「要保存的值」是否就是刚检测过的那个值, - * 只在 Redis 暂存里做比对,不落库、不下发。 + * 检测值指纹:SHA-256(uid|module|channel|明文)。用于判断「要保存的值」是否就是刚检测过的那个值, + * 只在 Redis 暂存里做比对,不落库、不下发。渠道参与指纹:同一串密钥在不同渠道上是两件事。 */ - private String fingerprint(Long userId, UserSecretModule module, String plainValue) { - String hash = sha256Hex(userId + "|" + module.key() + "|" + plainValue); + private String fingerprint(Long userId, UserSecretModule module, String plainValue, String channel) { + String hash = sha256Hex(userId + "|" + module.key() + "|" + channel + "|" + plainValue); if (hash.isEmpty()) { - log.warn("[user-secret] 生成检测指纹失败 userId={} module={}", userId, module.key()); + log.warn("[user-secret] 生成检测指纹失败 userId={} module={} channel={}", userId, module.key(), channel); } return hash; } - /** 新鲜期指纹:只按「模块 + 明文」,不含 uid —— 同一把密钥在任意账号上的检测结论是同一个。 */ - private String sharedFingerprint(UserSecretModule module, String plainValue) { - return sha256Hex(module.key() + "|" + plainValue); + /** 新鲜期指纹:只按「模块 + 渠道 + 明文」,不含 uid —— 同一把密钥在同一渠道上的检测结论是同一个。 */ + private String sharedFingerprint(UserSecretModule module, String plainValue, String channel) { + return sha256Hex(module.key() + "|" + channel + "|" + plainValue); } private String sha256Hex(String raw) { @@ -938,8 +1025,9 @@ public class UserApiSecretService implements UserSecretCleanupPort { /** 暂存「输入值」检测结果:TTL 内保存同一个值即沿用;暂存失败仅影响体验(用户需再检一次),不阻断检测。 */ private void rememberPendingVerification(Long userId, UserSecretModule module, String plainValue, + String channel, UserApiSecretCheckService.CheckOutcome outcome) { - String hash = fingerprint(userId, module, plainValue); + String hash = fingerprint(userId, module, plainValue, channel); if (hash.isEmpty()) { return; } @@ -965,9 +1053,10 @@ public class UserApiSecretService implements UserSecretCleanupPort { return FRESH_CHECK_KEY_PREFIX + ":" + module.key() + ":" + sharedHash; } - /** 读取新鲜期结果:同值且窗口内返回上次 outcome,否则 null(走真实探测)。 */ - private UserApiSecretCheckService.CheckOutcome reuseFreshOutcome(UserSecretModule module, String plainValue) { - String hash = sharedFingerprint(module, plainValue); + /** 读取新鲜期结果:同值同渠道且窗口内返回上次 outcome,否则 null(走真实探测)。 */ + private UserApiSecretCheckService.CheckOutcome reuseFreshOutcome(UserSecretModule module, String plainValue, + String channel) { + String hash = sharedFingerprint(module, plainValue, channel); if (hash.isEmpty()) { return null; } @@ -990,9 +1079,9 @@ public class UserApiSecretService implements UserSecretCleanupPort { } /** 暂存「通过」的检测结果供新鲜期内重复检测复用;失败不暂存(允许立即重试)。 */ - private void rememberFreshOutcome(UserSecretModule module, String plainValue, + private void rememberFreshOutcome(UserSecretModule module, String plainValue, String channel, UserApiSecretCheckService.CheckOutcome outcome) { - String hash = sharedFingerprint(module, plainValue); + String hash = sharedFingerprint(module, plainValue, channel); if (hash.isEmpty()) { return; } @@ -1011,8 +1100,8 @@ public class UserApiSecretService implements UserSecretCleanupPort { * 保存时沿用暂存结果:仅当保存值与最近一次「输入值检测」的值完全一致才落库该结果 * (passed/failed/error 一并沿用,页面据此如实展示),改过值或从未检测则维持未检测。 */ - private boolean applyPendingVerification(Long userId, UserSecretModule module, String plainValue) { - String hash = fingerprint(userId, module, plainValue); + private boolean applyPendingVerification(Long userId, UserSecretModule module, String plainValue, String channel) { + String hash = fingerprint(userId, module, plainValue, channel); if (hash.isEmpty()) { return false; } @@ -1051,6 +1140,7 @@ public class UserApiSecretService implements UserSecretCleanupPort { vo.setModuleKey(module.key()); vo.setModuleLabel(module.label()); if (row == null) { + vo.setChannel(module.defaultChannel()); vo.setMasked(""); vo.setExists(false); vo.setLocked(false); @@ -1060,6 +1150,7 @@ public class UserApiSecretService implements UserSecretCleanupPort { return vo; } String plain = decryptQuietly(row.getSecretValue()); + vo.setChannel(module.channelOrDefault(row.getChannel(), plain)); vo.setMasked(maskValue(module, plain)); // 后台代理列要求完整可见(含账号密码),密钥列不下发明文 if (module == UserSecretModule.PROXY) { @@ -1081,6 +1172,7 @@ public class UserApiSecretService implements UserSecretCleanupPort { vo.setModuleKey(module.key()); vo.setModuleLabel(module.label()); if (row == null) { + vo.setChannel(module.defaultChannel()); vo.setMasked(""); vo.setExists(false); vo.setLocked(false); @@ -1090,6 +1182,7 @@ public class UserApiSecretService implements UserSecretCleanupPort { return vo; } String plain = decryptQuietly(row.getSecretValue()); + vo.setChannel(module.channelOrDefault(row.getChannel(), plain)); vo.setMasked(maskValue(module, plain)); // 锁定代理要下发完整地址:客户端据此把本地配置对齐到后台值(其余模块不下发明文) if (module == UserSecretModule.PROXY && isAdminLocked(row)) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/LlmChannel.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/LlmChannel.java new file mode 100644 index 000000000..335243ca7 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/LlmChannel.java @@ -0,0 +1,152 @@ +package com.nanri.aiimage.modules.usersecret.support; + +import java.util.Locale; + +/** + * LLM 中转渠道:同一类密钥在不同中转上是**不同的 key**,所以渠道必须跟着密钥存。 + * + *

两条渠道都走 OpenAI 兼容协议({@code POST {host}/v1/chat/completions}), + * 差别只有主机名,因此这里只登记 key / 展示名 / 主机,不另做适配层。

+ * + *

默认值口径(2026-10-30 用户拍板):**新建**配置默认贞贞,龙抬头手动切换; + * 存量行同样回填为 {@link #T8STAR},两者一致。

+ */ +public enum LlmChannel { + + LONGTAITOU("longtaitou", "龙抬头", "https://longtaitou.token6688.com", + "gemini-3.1-flash-lite", true, "medium"), + T8STAR("t8star", "贞贞", "https://ai.t8star.org", null, false, null); + + /** 新建配置的默认渠道(2026-10-30 用户拍板:默认仍是贞贞,龙抬头手动切)。 */ + public static final LlmChannel DEFAULT = T8STAR; + + private final String key; + private final String label; + private final String host; + /** + * 该渠道上可路由的模型 id;null=沿用调用方配置的模型名。 + * + *

两家中转的模型目录不同名:本系统业务配置写的是贞贞的 + * {@code gemini-3.1-flash-lite-preview-thinking-medium} 等,龙抬头那边同一个模型叫 + * {@code gemini-3.1-flash-lite}(2026-10-29 用户指定)。不映射直接切渠道会 model_not_found。

+ */ + private final String defaultModel; + /** + * 该渠道是否需要**显式**传思考参数。 + * + *

贞贞把思考写在模型名里({@code gemini-3.1-flash-lite-preview-thinking-medium}), + * 请求体不用额外字段;龙抬头的同名模型默认不思考,要复刻现网口径必须传 + * {@code enable_thinking=true}(2026-10-30 实测:不传时 2.4s / 无 reasoning_content, + * 传 medium 后 13s / 返回 10k+ 字符思考链)。

+ */ + private final boolean thinkingParamsRequired; + /** 思考预算档位:none/minimal/low/medium/high。 */ + private final String thinkingBudget; + + LlmChannel(String key, String label, String host, String defaultModel, + boolean thinkingParamsRequired, String thinkingBudget) { + this.key = key; + this.label = label; + this.host = host; + this.defaultModel = defaultModel; + this.thinkingParamsRequired = thinkingParamsRequired; + this.thinkingBudget = thinkingBudget; + } + + public String key() { + return key; + } + + public String label() { + return label; + } + + /** 渠道 API 主机基址(不带 /v1,与 properties.llmHost 同口径)。 */ + public String host() { + return host; + } + + /** 该渠道实际请求要用的模型 id:渠道不统一改名时原样返回配置里的模型名。 */ + public String modelFor(String configuredModel) { + return defaultModel == null || defaultModel.isBlank() ? configuredModel : defaultModel; + } + + /** 按主机识别渠道;识别不出返回 null(调用方按原样使用模型名)。 */ + public static LlmChannel ofHost(String host) { + if (host == null || host.isBlank()) { + return null; + } + String normalized = host.trim().toLowerCase(Locale.ROOT); + for (LlmChannel channel : values()) { + if (normalized.contains(channel.host.replace("https://", ""))) { + return channel; + } + } + return null; + } + + /** 按请求主机把配置的模型名换成该渠道上可路由的 id(主机为空/未知时原样返回)。 */ + public static String modelForHost(String host, String configuredModel) { + LlmChannel channel = ofHost(host); + return channel == null ? configuredModel : channel.modelFor(configuredModel); + } + + /** 该渠道是否需要显式思考参数(贞贞不需要:思考写在模型名里)。 */ + public boolean thinkingParamsRequired() { + return thinkingParamsRequired; + } + + public String thinkingBudget() { + return thinkingBudget; + } + + /** 把该渠道的思考参数写进请求体;不需要显式参数的渠道原样不动。 */ + public void applyThinking(java.util.Map body) { + if (body == null || !thinkingParamsRequired) { + return; + } + body.put("enable_thinking", true); + if (thinkingBudget != null && !thinkingBudget.isBlank()) { + body.put("thinking_budget", thinkingBudget); + } + } + + /** + * 按请求主机补思考参数:业务链路用(外观专利 / 货源查询)。 + * **检测链路不要调它**——检测只验密钥与连通,不思考才快且便宜。 + */ + public static void applyThinkingForHost(String host, java.util.Map body) { + LlmChannel channel = ofHost(host); + if (channel != null) { + channel.applyThinking(body); + } + } + + /** 宽松解析:空值或未知值一律回落到 {@link #DEFAULT},绝不因脏数据抛异常中断保存/检测。 */ + public static LlmChannel of(String raw) { + if (raw == null || raw.isBlank()) { + return DEFAULT; + } + String normalized = raw.trim().toLowerCase(Locale.ROOT); + for (LlmChannel channel : values()) { + if (channel.key.equals(normalized)) { + return channel; + } + } + return DEFAULT; + } + + /** 解析为登记过的渠道 key;未知返回 null(供保存时区分「没填」与「填错」)。 */ + public static LlmChannel parse(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + String normalized = raw.trim().toLowerCase(Locale.ROOT); + for (LlmChannel channel : values()) { + if (channel.key.equals(normalized)) { + return channel; + } + } + return null; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/ProxyProvider.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/ProxyProvider.java new file mode 100644 index 000000000..a527f81a4 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/ProxyProvider.java @@ -0,0 +1,94 @@ +package com.nanri.aiimage.modules.usersecret.support; + +import java.util.Locale; + +/** + * 代理 IP 供应商:两家的提取链接与响应体结构不同,检测/解析必须按供应商分支。 + * + *
    + *
  • {@link #QINGGUO}:{@code https://overseas.proxy.qg.net/get?key=...&format=json}, + * 成功 {@code {"code":"SUCCESS","data":[{"server":"ip:port","proxy_ip":"..."}]}}, + * 失败 {@code code} 为字符串错误码(如 API_AUTH_DENY / BALANCE_INSUFFICIENT);
  • + *
  • {@link #JIKIP}:{@code https://api.jikip.com/ip-get?...},成功 {@code code=0}, + * 失败 {@code code=-1} 且 message 常含「余额不足」。解析口径见 ProxyParser 模式 1/2。
  • + *
+ * + *

默认值口径(2026-10-30 用户拍板):**新建**配置默认极客,青果手动切换; + * 存量行同样回填为 {@link #JIKIP}。

+ */ +public enum ProxyProvider { + + QINGGUO("qingguo", "青果", "overseas.proxy.qg.net"), + JIKIP("jikip", "极客", "api.jikip.com"); + + /** 新建配置的默认供应商(2026-10-30 用户拍板:默认仍是极客,青果手动切)。 */ + public static final ProxyProvider DEFAULT = JIKIP; + + private final String key; + private final String label; + private final String host; + + ProxyProvider(String key, String label, String host) { + this.key = key; + this.label = label; + this.host = host; + } + + public String key() { + return key; + } + + public String label() { + return label; + } + + /** 供应商提取域名(仅用于日志与链接自检,实际请求一律用用户填写的完整链接)。 */ + public String host() { + return host; + } + + /** 宽松解析:空值或未知值回落到 {@link #DEFAULT}。 */ + public static ProxyProvider of(String raw) { + ProxyProvider parsed = parse(raw); + return parsed == null ? DEFAULT : parsed; + } + + /** 解析为登记过的供应商 key;未知返回 null。 */ + public static ProxyProvider parse(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + String normalized = raw.trim().toLowerCase(Locale.ROOT); + for (ProxyProvider provider : values()) { + if (provider.key.equals(normalized)) { + return provider; + } + } + return null; + } + + /** + * 按提取链接域名识别供应商:老版本客户端只上报链接、不上报供应商, + * 存量的代理配置没写 provider 时靠它兜底,避免把极客链接按青果解析(反之亦然)。 + * 识别不出返回 null(调用方再回落默认值)。 + */ + public static ProxyProvider detectFromUrl(String url) { + if (url == null || url.isBlank()) { + return null; + } + String lower = url.trim().toLowerCase(Locale.ROOT); + for (ProxyProvider provider : values()) { + if (lower.contains(provider.host)) { + return provider; + } + } + // 青果的分享域名(share.proxy.qg.net)与极客的旧域名(jikip.cn)不带上表主域名时按后缀兜底 + if (lower.contains("qg.net")) { + return QINGGUO; + } + if (lower.contains("jikip.cn") || lower.contains("jikip.com")) { + return JIKIP; + } + return null; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/SecretUsageContext.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/SecretUsageContext.java index 3a288218d..db8a8b5df 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/SecretUsageContext.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/SecretUsageContext.java @@ -18,8 +18,20 @@ public final class SecretUsageContext { private SecretUsageContext() { } - /** 计次归属:用户 + 密钥模块 key(如 similar-asin / appearance-patent)。 */ - public record Context(Long userId, String moduleKey) { + /** + * 计次归属:用户 + 密钥模块 key(如 similar-asin / appearance-patent)+ LLM 渠道主机。 + * + *

渠道主机跟着任务上下文一起下发,而不是逐层加函数参数:行级处理跑在线程池里, + * 一条链路上有十几层方法都只透传 apiKey,多带一个 host 会把每个签名都改一遍, + * 而 {@link #wrap} 已经把整份上下文带到工作线程了,顺路带 host 成本为零。 + * 显式传 host 的调用点仍然优先(见各 LLM 客户端的 resolveHost)。

+ */ + public record Context(Long userId, String moduleKey, String llmHost) { + + public Context(Long userId, String moduleKey) { + this(userId, moduleKey, null); + } + public boolean usable() { return userId != null && userId > 0 && moduleKey != null && !moduleKey.isBlank(); } @@ -27,8 +39,13 @@ public final class SecretUsageContext { /** 在指定归属下执行并返回结果,结束后恢复原有上下文(支持嵌套)。 */ public static T call(Long userId, String moduleKey, Supplier action) { + return call(userId, moduleKey, null, action); + } + + /** 在指定归属 + LLM 渠道主机下执行并返回结果。 */ + public static T call(Long userId, String moduleKey, String llmHost, Supplier action) { Context previous = HOLDER.get(); - Context next = new Context(userId, moduleKey); + Context next = new Context(userId, moduleKey, llmHost); if (next.usable()) { HOLDER.set(next); } @@ -39,6 +56,16 @@ public final class SecretUsageContext { } } + /** 当前 LLM 渠道主机;无上下文或未设置时返回 null(客户端据此回落模块全局配置)。 */ + public static String currentLlmHost() { + Context context = HOLDER.get(); + if (context == null) { + return null; + } + String host = context.llmHost(); + return host == null || host.isBlank() ? null : host; + } + /** 当前归属;无上下文或归属不可用时返回 null。 */ public static Context current() { Context context = HOLDER.get(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/UserSecretModule.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/UserSecretModule.java index 4f4bd49b7..fa512ea01 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/UserSecretModule.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/support/UserSecretModule.java @@ -1,5 +1,6 @@ package com.nanri.aiimage.modules.usersecret.support; +import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.config.AppearancePatentProperties; import com.nanri.aiimage.config.SimilarAsinProperties; @@ -41,9 +42,69 @@ public enum UserSecretModule { return required; } - /** 检测目标主机:各 LLM 模块自己的 API 主机(检测模型由 aiimage.user-secret.check-model 统一指定)。 */ + /** 是否代理模块(货源词表为代理供应商,而非 LLM 渠道)。 */ + public boolean isProxy() { + return this == PROXY; + } + + /** 新建配置的默认货源:LLM 模块=龙抬头,代理=青果(2026-10-29 用户拍板)。 */ + public String defaultChannel() { + return isProxy() ? ProxyProvider.DEFAULT.key() : LlmChannel.DEFAULT.key(); + } + + /** + * 保存时的货源归一化:空值→默认值;未知值→明确报错(不接受脏值落库, + * 否则这条配置会静默走默认渠道,用户以为切过去了其实没有)。 + */ + public String requireChannel(String raw) { + if (raw == null || raw.isBlank()) { + return defaultChannel(); + } + if (isProxy()) { + ProxyProvider provider = ProxyProvider.parse(raw); + if (provider == null) { + throw new BusinessException("未知的代理供应商:" + raw.trim()); + } + return provider.key(); + } + LlmChannel channel = LlmChannel.parse(raw); + if (channel == null) { + throw new BusinessException("未知的 LLM 渠道:" + raw.trim()); + } + return channel.key(); + } + + /** + * 读取/检测时的货源归一化(宽松):空值或历史脏值回落到默认值,绝不抛异常。 + * 代理模块额外支持按提取链接域名识别——老版本客户端只上报链接、不上报供应商。 + */ + public String channelOrDefault(String raw, String proxyUrl) { + if (isProxy()) { + ProxyProvider parsed = ProxyProvider.parse(raw); + if (parsed != null) { + return parsed.key(); + } + ProxyProvider detected = ProxyProvider.detectFromUrl(proxyUrl); + return detected == null ? ProxyProvider.DEFAULT.key() : detected.key(); + } + LlmChannel parsed = LlmChannel.parse(raw); + return parsed == null ? LlmChannel.DEFAULT.key() : parsed.key(); + } + + /** + * 渠道对应的检测目标主机:各 LLM 模块按该用户密钥所属渠道取主机; + * 渠道为空(迁移前遗留行)时回落到模块全局配置,保持与历史行为一致。 + */ public String resolveLlmHost(AppearancePatentProperties appearancePatentProperties, - SimilarAsinProperties similarAsinProperties) { + SimilarAsinProperties similarAsinProperties, + String channel) { + if (isProxy()) { + throw new IllegalStateException("代理模块没有 LLM 检测目标"); + } + LlmChannel parsed = LlmChannel.parse(channel); + if (parsed != null) { + return parsed.host(); + } return switch (this) { case APPEARANCE_PATENT -> appearancePatentProperties.getLlmHost(); case SIMILAR_ASIN -> similarAsinProperties.getLlmHost(); @@ -51,6 +112,12 @@ public enum UserSecretModule { }; } + /** 检测目标主机(渠道为空时按模块全局配置,供兼容旧调用点)。 */ + public String resolveLlmHost(AppearancePatentProperties appearancePatentProperties, + SimilarAsinProperties similarAsinProperties) { + return resolveLlmHost(appearancePatentProperties, similarAsinProperties, null); + } + /** 桌面端门禁模块:密钥包下发与完整性判定的唯一来源。 */ public static List requiredModules() { return Arrays.stream(values()).filter(UserSecretModule::required).toList(); diff --git a/backend-java/src/main/resources/application-local.example.yml b/backend-java/src/main/resources/application-local.example.yml index b972f872d..e96c904b7 100644 --- a/backend-java/src/main/resources/application-local.example.yml +++ b/backend-java/src/main/resources/application-local.example.yml @@ -93,6 +93,13 @@ AIIMAGE_NOTIFICATION_JIKIP_LOW_SURPLUS_THRESHOLD=100 # 账户余额 ≤ 阈值 → 管理员通知;供应商口径,0=关闭 AIIMAGE_NOTIFICATION_JIKIP_LOW_BALANCE_THRESHOLD=0 +# 以上 LLM 主机/模型是「贞贞」渠道的默认值(历史口径)。 +# 2026-10-29 起用户密钥可按人选择渠道(龙抬头 / 贞贞,默认贞贞,可手动切龙抬头): +# - 渠道主机写死在 UserSecretModule/LlmChannel 里,不读本段; +# - 手动切到龙抬头渠道后,模型 id 统一映射为 gemini-3.1-flash-lite,并显式补 +# enable_thinking=true + thinking_budget=medium(贞贞把 thinking 写在模型名里; +# 不补这一对就等于给外观专利/货源查询降档。检测链路刻意不思考,只验连通); +# - 用户没配密钥或迁移前遗留行没有 channel 时,才会回落到本段配置。 AIIMAGE_APPEARANCE_PATENT_LLM_HOST=https://ai.t8star.org AIIMAGE_APPEARANCE_PATENT_TITLE_MODEL=gemini-3.1-flash-lite-preview-thinking-medium AIIMAGE_APPEARANCE_PATENT_APPEARANCE_MODEL=gemini-3.1-flash-lite-preview-thinking-medium diff --git a/backend-java/src/main/resources/db/V180__user_api_secret_channel.sql b/backend-java/src/main/resources/db/V180__user_api_secret_channel.sql new file mode 100644 index 000000000..7cf46927b --- /dev/null +++ b/backend-java/src/main/resources/db/V180__user_api_secret_channel.sql @@ -0,0 +1,36 @@ +-- V180: 用户密钥增加「货源」维度(LLM 渠道 / 代理供应商) +-- +-- 背景(2026-10-29 用户提出): +-- 1) LLM 密钥此前只有一把,请求地址由全局配置 aiimage.*.llm-host 定死(现网 ai.t8star.org/贞贞)。 +-- 现在多了一家中转「龙抬头」(https://longtaitou.token6688.com),两家的 sk- 密钥互不通用, +-- 所以「密钥属于哪一家」必须跟着密钥一起存,否则切换渠道就得改全局配置、影响所有人。 +-- 2) 代理此前只认极客(jikip) 的提取链接与余额接口。新增青果(overseas.proxy.qg.net), +-- 两家返回体结构不同(青果 code 是字符串 SUCCESS/...,data 是数组、地址在 server 字段), +-- 解析与检测都要按供应商分支,因此供应商也要跟着代理配置存。 +-- +-- 列语义(同一列按 module_key 取不同词表,刻意不拆两列——两者都是「这一行配置的货源」, +-- 拆开会出现「LLM 行有 provider/代理行有 channel」这种半空列): +-- module_key IN ('appearance-patent','similar-asin') → LLM 渠道:longtaitou / t8star +-- module_key = 'proxy' → 代理供应商:qingguo / jikip +-- +-- 存量回填(关键,不能省): +-- 新建默认是 t8star/jikip(2026-10-30 用户拍板:默认仍走贞贞与极客,龙抬头/青果手动切), +-- 存量行也一律回填成 t8star/jikip —— 与加列默认值一致,但仍显式写一遍: +-- 即使将来默认值再变,这条迁移落库的历史数据也永远是"当时的真实货源"。 +-- +-- 影响表与数据量:biz_user_api_secret 增加一列,行数=用户数×3,量级极小。 +-- +-- 回滚(手工): +-- ALTER TABLE `biz_user_api_secret` DROP COLUMN `channel`; + +ALTER TABLE `biz_user_api_secret` + ADD COLUMN `channel` VARCHAR(32) NOT NULL DEFAULT 't8star' + COMMENT '货源:LLM 行为渠道(longtaitou/t8star);代理行为供应商(qingguo/jikip)' AFTER `module_key`; + +UPDATE `biz_user_api_secret` + SET `channel` = 't8star' + WHERE `module_key` IN ('appearance-patent', 'similar-asin'); + +UPDATE `biz_user_api_secret` + SET `channel` = 'jikip' + WHERE `module_key` = 'proxy'; diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCandidateCollectionFaultToleranceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCandidateCollectionFaultToleranceTest.java index 461ba1634..87caf7886 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCandidateCollectionFaultToleranceTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCandidateCollectionFaultToleranceTest.java @@ -179,6 +179,7 @@ class AppearancePatentCandidateCollectionFaultToleranceTest { }, task -> "prompt", task -> "sk-test", + task -> null, (taskId, scopeHash, chunkIndex, rows) -> List.of(), (preferred, fallback) -> preferred == null || preferred.isBlank() ? fallback : preferred, // 本夹具只驱动「候选收集」,永远不会进欠费终态分支;真进来了就说明测试形状变了 diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckServiceTest.java index 6219e46e3..d92dbea0a 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckServiceTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckServiceTest.java @@ -251,4 +251,64 @@ class UserApiSecretCheckServiceTest { "{\"data\":{\"list\":[{\"ip\":\"1.2.3.4\",\"port\":8080}]},\"code\":0}")).isFalse(); assertThat(service.isInsufficientBalance("")).isFalse(); } + + // ---------- 青果(overseas.proxy.qg.net):code 是字符串、地址在 data[].server ---------- + + @Test + void extractQingguoProxyUrlUsesServerFieldNotProxyIp() { + // 青果文档明确:server 才是代理地址,proxy_ip 只是真实出口 IP(没端口,拿来连必失败) + String body = "{\"code\":\"SUCCESS\",\"data\":[{\"proxy_ip\":\"123.54.55.24\"," + + "\"server\":\"123.54.55.24:59419\",\"area\":\"河南省商丘市\",\"isp\":\"电信\"," + + "\"deadline\":\"2023-02-25 15:38:36\"}],\"request_id\":\"83158ebe\"}"; + + assertThat(service.extractProxyUrlFromBody(body)).isEqualTo("http://123.54.55.24:59419"); + } + + @Test + void extractQingguoProxyUrlNullWhenNoServerAndNoPort() { + assertThat(service.extractProxyUrlFromBody( + "{\"code\":\"SUCCESS\",\"data\":[{\"proxy_ip\":\"123.54.55.24\"}]}")).isNull(); + assertThat(service.extractProxyUrlFromBody( + "{\"code\":\"SUCCESS\",\"data\":[]}")).isNull(); + } + + @Test + void qingguoBalanceShortageIsInsufficientBalance() { + UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection( + com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO, + "{\"code\":\"BALANCE_INSUFFICIENT\",\"message\":\"余额不足\",\"request_id\":\"x\"}", 88); + + assertThat(outcome).isNotNull(); + assertThat(outcome.status()).isEqualTo(UserApiSecretCheckService.STATUS_FAILED); + assertThat(outcome.code()).isEqualTo(UserApiSecretCheckService.CODE_INSUFFICIENT_BALANCE); + } + + @Test + void qingguoAuthDenyIsForbiddenWithChineseMessage() { + UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection( + com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO, + "{\"code\":\"API_AUTH_DENY\",\"message\":\"Api授权不通过,请检查Api鉴权配置\",\"request_id\":\"x\"}", 90); + + assertThat(outcome).isNotNull(); + assertThat(outcome.status()).isEqualTo(UserApiSecretCheckService.STATUS_FAILED); + assertThat(outcome.code()).isEqualTo(UserApiSecretCheckService.CODE_FORBIDDEN); + assertThat(outcome.message()).contains("青果").contains("API_AUTH_DENY"); + } + + @Test + void qingguoSuccessIsNotRejection() { + assertThat(service.classifyProviderRejection( + com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO, + "{\"code\":\"SUCCESS\",\"data\":[]}", 60)).isNull(); + } + + @Test + void jikipBalanceShortageStillClassified() { + UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection( + com.nanri.aiimage.modules.usersecret.support.ProxyProvider.JIKIP, + "{\"code\":-1,\"data\":null,\"message\":\"余额不足\"}", 70); + + assertThat(outcome).isNotNull(); + assertThat(outcome.code()).isEqualTo(UserApiSecretCheckService.CODE_INSUFFICIENT_BALANCE); + } } diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java index 281bdb072..b689ac069 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java @@ -11,6 +11,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.ibatis.builder.MapperBuilderAssistant; import com.nanri.aiimage.common.security.ShopCredentialCryptoService; import com.nanri.aiimage.config.UserSecretProperties; +import com.nanri.aiimage.config.AppearancePatentProperties; +import com.nanri.aiimage.config.SimilarAsinProperties; import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.service.ReadScope; import com.nanri.aiimage.modules.notification.service.NotificationDispatchService; @@ -99,6 +101,7 @@ class UserApiSecretServiceTest { return new UserApiSecretService( mapper, crypto, checkService, adminUserMapper, adminAuthSupport, adminGroupMapper, userDataScopeSupport, notificationDispatchService, userSecretProperties, + mock(AppearancePatentProperties.class), mock(SimilarAsinProperties.class), stringRedisTemplate, objectMapper); } @@ -144,7 +147,7 @@ class UserApiSecretServiceTest { UserApiSecretService service = newService(); UserApiSecretEntity existing = existingRow("enc:old-key"); when(mapper.selectOne(any())).thenReturn(existing); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 1678)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "正常", 1678)); service.check(7L, "similar-asin", "sk-input"); // 输入值检测只暂存,不落库 @@ -167,7 +170,7 @@ class UserApiSecretServiceTest { UserApiSecretService service = newService(); UserApiSecretEntity existing = existingRow("enc:old-key"); when(mapper.selectOne(any())).thenReturn(existing); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 900)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "正常", 900)); service.check(7L, "similar-asin", "sk-input"); service.save(7L, "similar-asin", "sk-changed"); @@ -184,7 +187,7 @@ class UserApiSecretServiceTest { UserApiSecretService service = newService(); UserApiSecretEntity existing = existingRow("enc:old-key"); when(mapper.selectOne(any())).thenReturn(existing); - when(checkService.probe(any(), anyString())).thenReturn(outcome("failed", "invalid_key", "密钥无效", 300)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("failed", "invalid_key", "密钥无效", 300)); service.check(7L, "similar-asin", "sk-bad"); service.save(7L, "similar-asin", "sk-bad"); @@ -199,7 +202,7 @@ class UserApiSecretServiceTest { UserApiSecretService service = newService(); UserApiSecretEntity existing = existingRow("enc:old-key"); when(mapper.selectOne(any())).thenReturn(existing); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 500)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "正常", 500)); when(valueOps.get(anyString())).thenThrow(new IllegalStateException("redis down")); assertThat(service.check(7L, "similar-asin", "sk-input").getCheckStatus()).isEqualTo("passed"); @@ -214,12 +217,12 @@ class UserApiSecretServiceTest { @Test void repeatedCheckWithinFreshWindowReusesResult() { UserApiSecretService service = newService(); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "代理可用", 120)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "代理可用", 120)); var first = service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc"); var second = service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc"); - verify(checkService, times(1)).probe(any(), anyString()); + verify(checkService, times(1)).probe(any(), anyString(), any()); assertThat(second.getCheckStatus()).isEqualTo("passed"); assertThat(second.getCheckStatus()).isEqualTo(first.getCheckStatus()); } @@ -228,25 +231,25 @@ class UserApiSecretServiceTest { @Test void repeatedCheckProbesAgainWhenValueChanged() { UserApiSecretService service = newService(); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 100)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "正常", 100)); service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=aaa"); service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=bbb"); - verify(checkService, times(2)).probe(any(), anyString()); + verify(checkService, times(2)).probe(any(), anyString(), any()); } /** 失败结果不进新鲜期缓存:余额不足充值后应能立即重检。 */ @Test void failedCheckIsNotReusedWithinFreshWindow() { UserApiSecretService service = newService(); - when(checkService.probe(any(), anyString())) + when(checkService.probe(any(), anyString(), any())) .thenReturn(outcome("failed", "insufficient_balance", "代理服务商余额不足,请充值后重试", 80)); service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc"); service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc"); - verify(checkService, times(2)).probe(any(), anyString()); + verify(checkService, times(2)).probe(any(), anyString(), any()); } /** @@ -256,12 +259,12 @@ class UserApiSecretServiceTest { @Test void freshCheckIsSharedAcrossAccountsUsingTheSameSecret() { UserApiSecretService service = newService(); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "代理可用", 120)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "代理可用", 120)); var first = service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc"); var second = service.check(8L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc"); - verify(checkService, times(1)).probe(any(), anyString()); + verify(checkService, times(1)).probe(any(), anyString(), any()); assertThat(second.getCheckStatus()).isEqualTo("passed"); assertThat(second.getCheckStatus()).isEqualTo(first.getCheckStatus()); } @@ -270,24 +273,24 @@ class UserApiSecretServiceTest { @Test void freshCheckDoesNotLeakAcrossDifferentSecretValues() { UserApiSecretService service = newService(); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 100)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "正常", 100)); service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=aaa"); service.check(8L, "proxy", "https://api.jikip.com/ip-get?num=1&key=bbb"); - verify(checkService, times(2)).probe(any(), anyString()); + verify(checkService, times(2)).probe(any(), anyString(), any()); } /** 同一串值在不同模块下结论可能不同(货源/外观各自独立的检测端点),新鲜期按模块隔离。 */ @Test void freshCheckIsScopedPerModule() { UserApiSecretService service = newService(); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "连通正常", 100)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "连通正常", 100)); service.check(7L, "similar-asin", "sk-shared"); service.check(8L, "appearance-patent", "sk-shared"); - verify(checkService, times(2)).probe(any(), anyString()); + verify(checkService, times(2)).probe(any(), anyString(), any()); } private UserApiSecretEntity existingRow(String cipher) { @@ -980,7 +983,7 @@ class UserApiSecretServiceTest { 11L, storedRow(11L, "proxy", sharedCipher), 12L, storedRow(12L, "proxy", sharedCipher), 13L, storedRow(13L, "proxy", sharedCipher))); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "代理可用", 120)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "代理可用", 120)); when(mapper.selectList(any())).thenReturn(List.of( inspectionRow(1L, 11L, "proxy", sharedCipher), inspectionRow(2L, 12L, "proxy", sharedCipher), @@ -988,7 +991,7 @@ class UserApiSecretServiceTest { var summary = service.checkAllForScheduler(500, 20); - verify(checkService, times(1)).probe(any(), anyString()); + verify(checkService, times(1)).probe(any(), anyString(), any()); assertThat(summary.checked()).isEqualTo(3); assertThat(summary.probed()).isEqualTo(1); assertThat(inspectionWrites.keySet()).containsExactlyInAnyOrder(11L, 12L, 13L); @@ -1003,7 +1006,7 @@ class UserApiSecretServiceTest { stubInspectionStore(Map.of( 11L, storedRow(11L, "proxy", sharedCipher), 12L, storedRow(12L, "proxy", sharedCipher))); - when(checkService.probe(any(), anyString())).thenReturn( + when(checkService.probe(any(), anyString(), any())).thenReturn( outcome("failed", "insufficient_balance", "代理服务商余额不足,请充值后重试", 80)); when(mapper.selectList(any())).thenReturn(List.of( inspectionRow(1L, 11L, "proxy", sharedCipher), @@ -1011,7 +1014,7 @@ class UserApiSecretServiceTest { var summary = service.checkAllForScheduler(500, 20); - verify(checkService, times(1)).probe(any(), anyString()); + verify(checkService, times(1)).probe(any(), anyString(), any()); assertThat(summary.probed()).isEqualTo(1); assertThat(summary.failed()).isEqualTo(2); assertThat(inspectionWrites.values()).containsOnly("failed"); @@ -1025,14 +1028,14 @@ class UserApiSecretServiceTest { stubInspectionStore(Map.of( 11L, storedRow(11L, "similar-asin", sharedCipher), 12L, storedRow(12L, "appearance-patent", sharedCipher))); - when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "连通正常", 100)); + when(checkService.probe(any(), anyString(), any())).thenReturn(outcome("passed", "ok", "连通正常", 100)); when(mapper.selectList(any())).thenReturn(List.of( inspectionRow(1L, 11L, "similar-asin", sharedCipher), inspectionRow(2L, 12L, "appearance-patent", sharedCipher)), List.of()); var summary = service.checkAllForScheduler(500, 20); - verify(checkService, times(2)).probe(any(), anyString()); + verify(checkService, times(2)).probe(any(), anyString(), any()); assertThat(summary.checked()).isEqualTo(2); assertThat(summary.probed()).isEqualTo(2); } @@ -1049,7 +1052,7 @@ class UserApiSecretServiceTest { 11L, storedRow(11L, "proxy", sharedCipher), 12L, storedRow(12L, "proxy", sharedCipher), 13L, storedRow(13L, "proxy", sharedCipher))); - when(checkService.probe(any(), anyString())).thenReturn( + when(checkService.probe(any(), anyString(), any())).thenReturn( outcome("failed", "insufficient_balance", "代理服务商余额不足,请充值后重试", 80)); when(mapper.selectList(any())).thenReturn(List.of( inspectionRow(1L, 11L, "proxy", sharedCipher), @@ -1081,7 +1084,7 @@ class UserApiSecretServiceTest { UserApiSecretService service = newService(); String cipher = "enc:sk-solo"; stubInspectionStore(Map.of(11L, storedRow(11L, "similar-asin", cipher))); - when(checkService.probe(any(), anyString())).thenReturn( + when(checkService.probe(any(), anyString(), any())).thenReturn( outcome("failed", "invalid_key", "密钥无效或已被拒绝", 90)); when(mapper.selectList(any())).thenReturn(List.of( inspectionRow(1L, 11L, "similar-asin", cipher)), List.of()); diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/support/LlmChannelProxyProviderTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/support/LlmChannelProxyProviderTest.java new file mode 100644 index 000000000..6b0292103 --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/support/LlmChannelProxyProviderTest.java @@ -0,0 +1,129 @@ +package com.nanri.aiimage.modules.usersecret.support; + +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.config.AppearancePatentProperties; +import com.nanri.aiimage.config.SimilarAsinProperties; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * 密钥「货源」维度:LLM 渠道(龙抬头/贞贞)与代理供应商(青果/极客)的归一化、默认值、主机与模型映射。 + * + *

口径来源(2026-10-29 用户拍板):新建默认龙抬头 + 青果;存量由迁移 V180 回填贞贞/极客; + * 龙抬头的模型 id 统一用 {@code gemini-3.1-flash-lite}。

+ */ +class LlmChannelProxyProviderTest { + + @Test + void llmChannelDefaultsToT8star() { + // 2026-10-30 用户拍板:默认仍是贞贞,龙抬头只做手动切换 + assertThat(LlmChannel.of(null)).isEqualTo(LlmChannel.T8STAR); + assertThat(LlmChannel.of(" ")).isEqualTo(LlmChannel.T8STAR); + assertThat(LlmChannel.of("unknown-channel")).isEqualTo(LlmChannel.T8STAR); + assertThat(LlmChannel.of(" LONGTAITOU ")).isEqualTo(LlmChannel.LONGTAITOU); + } + + @Test + void llmChannelParseRejectsUnknownWithoutFallback() { + assertThat(LlmChannel.parse("t8star")).isEqualTo(LlmChannel.T8STAR); + assertThat(LlmChannel.parse("nope")).isNull(); + assertThat(LlmChannel.parse("")).isNull(); + } + + @Test + void longtaitouUsesItsOwnModelId() { + // 贞贞的模型名在龙抬头那边不存在,切渠道必须换 id,否则 model_not_found + assertThat(LlmChannel.LONGTAITOU.modelFor("gemini-3.1-flash-lite-preview-thinking-medium")) + .isEqualTo("gemini-3.1-flash-lite"); + // 贞贞保持配置里的模型名原样 + assertThat(LlmChannel.T8STAR.modelFor("gemini-3.1-flash-lite-preview-thinking-medium")) + .isEqualTo("gemini-3.1-flash-lite-preview-thinking-medium"); + } + + @Test + void modelMappingFollowsRequestHost() { + assertThat(LlmChannel.modelForHost("https://longtaitou.token6688.com", "any-model")) + .isEqualTo("gemini-3.1-flash-lite"); + assertThat(LlmChannel.modelForHost("https://ai.t8star.org", "any-model")).isEqualTo("any-model"); + assertThat(LlmChannel.modelForHost(null, "any-model")).isEqualTo("any-model"); + assertThat(LlmChannel.modelForHost("https://unknown.example.com", "any-model")).isEqualTo("any-model"); + } + + @Test + void proxyProviderDefaultsToQingguoAndDetectsByUrl() { + assertThat(ProxyProvider.of(null)).isEqualTo(ProxyProvider.JIKIP); + assertThat(ProxyProvider.of("jikip")).isEqualTo(ProxyProvider.JIKIP); + assertThat(ProxyProvider.detectFromUrl( + "https://overseas.proxy.qg.net/get?key=abc&num=1&format=json")).isEqualTo(ProxyProvider.QINGGUO); + assertThat(ProxyProvider.detectFromUrl("https://api.jikip.com/ip-get?num=1&minute=3&key=abc")) + .isEqualTo(ProxyProvider.JIKIP); + assertThat(ProxyProvider.detectFromUrl("https://example.com/get")).isNull(); + assertThat(ProxyProvider.detectFromUrl(null)).isNull(); + } + + @Test + void longtaitouNeedsExplicitThinkingParamsLikeT8star() { + // 贞贞把 thinking 写在模型名里(…-thinking-medium),请求体不用额外字段 + Map t8 = new LinkedHashMap<>(); + LlmChannel.applyThinkingForHost("https://ai.t8star.org", t8); + assertThat(t8).isEmpty(); + + // 龙抬头的同名模型默认不思考,业务链路要显式补上,才等于现网口径 + Map ltt = new LinkedHashMap<>(); + LlmChannel.applyThinkingForHost("https://longtaitou.token6688.com", ltt); + assertThat(ltt).containsEntry("enable_thinking", true); + assertThat(ltt).containsEntry("thinking_budget", "medium"); + + // 未知主机不动请求体(自建中转/本地假上游不要被塞参数) + Map unknown = new LinkedHashMap<>(); + LlmChannel.applyThinkingForHost("http://127.0.0.1:8080", unknown); + assertThat(unknown).isEmpty(); + } + + @Test + void moduleDefaultsAndValidation() { + assertThat(UserSecretModule.APPEARANCE_PATENT.defaultChannel()).isEqualTo("t8star"); + assertThat(UserSecretModule.SIMILAR_ASIN.defaultChannel()).isEqualTo("t8star"); + assertThat(UserSecretModule.PROXY.defaultChannel()).isEqualTo("jikip"); + + assertThat(UserSecretModule.APPEARANCE_PATENT.requireChannel(null)).isEqualTo("t8star"); + assertThat(UserSecretModule.APPEARANCE_PATENT.requireChannel("T8STAR")).isEqualTo("t8star"); + assertThat(UserSecretModule.PROXY.requireChannel("jikip")).isEqualTo("jikip"); + assertThatThrownBy(() -> UserSecretModule.APPEARANCE_PATENT.requireChannel("qingguo")) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("未知的 LLM 渠道"); + assertThatThrownBy(() -> UserSecretModule.PROXY.requireChannel("longtaitou")) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("未知的代理供应商"); + } + + @Test + void proxyChannelFallsBackToUrlDetectionForLegacyRows() { + // 老数据只有链接、没有供应商列:按域名识别,别把极客链接当青果解析 + assertThat(UserSecretModule.PROXY.channelOrDefault(null, "https://api.jikip.com/ip-get?key=x")) + .isEqualTo("jikip"); + assertThat(UserSecretModule.PROXY.channelOrDefault(null, "https://overseas.proxy.qg.net/get?key=x")) + .isEqualTo("qingguo"); + assertThat(UserSecretModule.PROXY.channelOrDefault(null, "https://example.com/get")) + .isEqualTo("jikip"); + } + + @Test + void llmHostResolvesByChannelAndFallsBackToModuleConfig() { + AppearancePatentProperties appearance = new AppearancePatentProperties(); + SimilarAsinProperties similar = new SimilarAsinProperties(); + + assertThat(UserSecretModule.APPEARANCE_PATENT.resolveLlmHost(appearance, similar, "longtaitou")) + .isEqualTo("https://longtaitou.token6688.com"); + assertThat(UserSecretModule.APPEARANCE_PATENT.resolveLlmHost(appearance, similar, "t8star")) + .isEqualTo("https://ai.t8star.org"); + // 迁移前遗留行没有 channel:沿用模块全局配置,行为不变 + assertThat(UserSecretModule.APPEARANCE_PATENT.resolveLlmHost(appearance, similar, null)) + .isEqualTo(appearance.getLlmHost()); + } +} diff --git a/frontend-vue/src/shared/api/types/modules/user-secret.ts b/frontend-vue/src/shared/api/types/modules/user-secret.ts index 3d625d7ee..1535c5925 100644 --- a/frontend-vue/src/shared/api/types/modules/user-secret.ts +++ b/frontend-vue/src/shared/api/types/modules/user-secret.ts @@ -11,6 +11,8 @@ export type ApiSecretCheckStatus = 'unknown' | 'passed' | 'failed' | 'error' export interface UserApiSecretItem { moduleKey: string moduleLabel: string + /** 货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip);未配置时服务端下发默认值。 */ + channel?: string | null masked: string /** 完整明文值:仅代理模块被后台代填并锁定时下发,供客户端写入本地配置;其余情况为空。 */ full?: string | null @@ -65,6 +67,8 @@ export interface UserProxyPlan { export interface UserApiSecretMigrateItem { moduleKey: string value: string + /** 货源(老客户端不上报,服务端按「贞贞/极客」回填存量口径)。 */ + channel?: string } export function fetchMyApiSecrets() { @@ -73,11 +77,11 @@ export function fetchMyApiSecrets() { ) } -export function putMyApiSecret(moduleKey: string, value: string) { +export function putMyApiSecret(moduleKey: string, value: string, channel?: string) { return unwrapJavaResponse( - put, { value: string }>( + put, { value: string; channel?: string }>( buildJavaUrl(API_ENDPOINTS.userSecret.save.replace('{moduleKey}', encodeURIComponent(moduleKey))), - { value }, + channel ? { value, channel } : { value }, ), ) } @@ -90,11 +94,11 @@ export function deleteMyApiSecret(moduleKey: string) { /** value 非空时检测输入值(不落库);为空时检测服务端已存密钥并把结果落库。 */ /** 检测连通性:服务端最多「首查 + 传输层失败重试一次」,最坏约 31s,故单独放宽超时。 */ -export function checkMyApiSecret(moduleKey: string, value?: string) { +export function checkMyApiSecret(moduleKey: string, value?: string, channel?: string) { return unwrapJavaResponse( - post, { value?: string }>( + post, { value?: string; channel?: string }>( buildJavaUrl(API_ENDPOINTS.userSecret.check.replace('{moduleKey}', encodeURIComponent(moduleKey))), - { value }, + channel ? { value, channel } : { value }, { timeout: 60000 }, ), ) diff --git a/frontend-vue/src/shared/bridges/pywebview.ts b/frontend-vue/src/shared/bridges/pywebview.ts index 903494ac9..29a816ac7 100644 --- a/frontend-vue/src/shared/bridges/pywebview.ts +++ b/frontend-vue/src/shared/bridges/pywebview.ts @@ -65,6 +65,12 @@ export interface VariantTaskQueryData { export interface DesktopConfig { proxy_url?: string; proxy_mode?: number | string; + /** 代理供应商:qingguo(青果,默认)/ jikip(极客);老配置没有该键时按链接域名识别。 */ + proxy_provider?: string; + /** 青果隧道端点的代理账号(Authkey);极客不需要。 */ + proxy_account?: string; + /** 青果隧道端点的代理密码(Authpwd);极客不需要。 */ + proxy_password?: string; aliprice_usename?: string; aliprice_pwd?: string; [key: string]: unknown; @@ -73,13 +79,24 @@ export interface DesktopConfig { export interface DesktopConfigUpdate { proxy_url?: string; proxy_mode?: ProxyMode; + /** 代理供应商:qingguo(青果,默认)/ jikip(极客)。 */ + proxy_provider?: string; + /** 青果隧道代理账号/密码(Authkey/Authpwd);空串表示清除。 */ + proxy_account?: string; + proxy_password?: string; current_uid?: string; /** 全局 proxy_url 的归属 uid(CR-04:只有 owner 匹配才允许回退)。 */ proxy_uid?: string; /** 显式共享白名单:整机共享或指定 uid 列表(CR-04)。 */ proxy_shared?: boolean; proxy_shared_uids?: string[]; - proxy_users?: Record; + proxy_users?: Record; /** 本机继承快照的作用域标记(CR-12:同一 app.json 才能继承)。 */ api_secret_os_scope?: string; /** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */ diff --git a/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue b/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue index 9d4e218f1..0b7045a5a 100644 --- a/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue +++ b/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue @@ -2,8 +2,14 @@
-
-
{{ module.moduleLabel }}
+
+
+ {{ module.moduleLabel }} + {{ llmChannelLabel(moduleChannels[module.moduleKey]) }} + + {{ statusPillTextOf(module.moduleKey) }} + +
{{ descriptionOf(module.moduleKey) }}
- +
+ +
+ +
+ + +
+ +
+ 已切换到「{{ llmChannelLabel(moduleChannels[module.moduleKey]) }}」,请填写该渠道的密钥后再保存(两家渠道的密钥不通用)。 +
+
+
+
+
隧道代理账号(青果 Authkey / Authpwd)
+
+ + +
+
+ 青果通道提取返回的是隧道端点(如 tunpool-xxx.qg.net:16359),连接时要用这对账密做认证;只存在本机,不上报服务端。 +
+
+
代理模式
@@ -93,7 +171,7 @@
-
+
jikip 套餐信息(用于余量查询与预警)
+
+ 青果的账户余量与通道用量请到青果后台查看;本客户端目前只做青果提取链接的连通性检测。 +