feat(user-secret): 密钥设置支持 LLM 渠道与代理供应商切换

- 用户密钥新增 channel 列(V180):LLM 行存渠道 longtaitou/t8star,代理行存供应商
  qingguo/jikip;存量与新建默认均回填 t8star/jikip(默认仍走贞贞与极客,手动可切)
- 外观专利/货源查询按任务归属用户的密钥渠道路由 LLM 主机(渠道经 SecretUsageContext
  下到工作线程,不逐层改签名);切到龙抬头时模型映射 gemini-3.1-flash-lite 并补
  enable_thinking + thinking_budget=medium(对齐贞贞现网口径),检测链路刻意不思考
- 代理检测按供应商解析:青果 code 为字符串、隧道端点支持 域名:端口、
  NO_AVAILABLE_CHANNEL 归为可重试;青果只验提取成功(账密只在客户端本地)
- 密钥设置页:每个模块加渠道分段选择、代理卡加供应商选择与青果 Authkey/Authpwd
  (只存本机,不上报),切换渠道未重填密钥时拦住保存;换号继承带渠道与供应商
- 后管密钥管理三列显示渠道/供应商标签
This commit is contained in:
2026-10-30 04:00:38 +08:00
parent eaab173ae9
commit 457af3607f
36 changed files with 1644 additions and 159 deletions
@@ -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<String, Object> 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();
@@ -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<Appear
properties, llmClient, taskCacheService, taskFileJobService,
rowReader()::rowKey, this::shouldInspectRow, rowReader()::readChunkRows, this::loadSubmittedChunks,
this::isResultSubmissionComplete, this::touchJavaSideTaskActivity,
llmSubmission::readAiPrompt, llmSubmission::readApiKey, this::mergeChunkPayload, this::firstNonBlank,
llmSubmission::readAiPrompt, llmSubmission::readApiKey,
task -> userApiSecretService.resolveLlmHost(task.getUserId(), UserSecretModule.APPEARANCE_PATENT),
this::mergeChunkPayload, this::firstNonBlank,
this::terminalizeTaskOnFatalLlmFailure);
}
@@ -81,6 +81,8 @@ public class AppearancePatentLlmBatchPipeline {
private final Consumer<Long> taskActivityToucher;
private final Function<FileTaskEntity, String> promptReader;
private final Function<FileTaskEntity, String> apiKeyReader;
/** 按任务归属用户密钥的渠道解析 LLM 主机(龙抬头/贞贞);为空表示走模块全局配置。 */
private final Function<FileTaskEntity, String> apiHostReader;
private final ChunkRowMerger chunkRowMerger;
private final BiFunction<String, String, String> firstNonBlankFn;
private final FatalLlmFailureHandler fatalLlmFailureHandler;
@@ -97,6 +99,7 @@ public class AppearancePatentLlmBatchPipeline {
Consumer<Long> taskActivityToucher,
Function<FileTaskEntity, String> promptReader,
Function<FileTaskEntity, String> apiKeyReader,
Function<FileTaskEntity, String> apiHostReader,
ChunkRowMerger chunkRowMerger,
BiFunction<String, String, String> 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<AppearancePatentResultRowDto> 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)) {
@@ -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<String, Object> 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();
@@ -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());
@@ -931,10 +931,12 @@ public class SimilarAsinPipelineSupport {
boolean categorySwitch = host.readCategorySwitch(task);
int batchSize = SimilarAsinLimits.resolveLlmBatchSize(properties, imgSwitch);
List<SimilarAsinResultRowDto> result = new ArrayList<>();
// 渠道主机任务级解析一次:本任务的所有批次都发往同一家中转
String apiHost = payloadSupport.resolveLlmHost(task);
for (int i = 0; i < items.size(); i += batchSize) {
List<SimilarAsinResultRowDto> 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<SimilarAsinResultRowDto> 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");
@@ -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}")
@@ -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")
@@ -9,4 +9,8 @@ public class UserApiSecretCheckRequest {
@Schema(description = "待检测的密钥明文;为空时检测服务端已保存的密钥(结果落库),非空时仅检测输入值(不落库)")
private String value;
@Schema(description = "待检测的货源(未保存的下拉选择):LLM 密钥填 longtaitou/t8star,代理填 qingguo/jikip;"
+ "为空时按服务端已存行的渠道/供应商检测")
private String channel;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
@@ -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;
@@ -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;
@@ -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);
}
/**
* 供应商拒付/鉴权失败的独立分类(两家错误码词表不同):
* <ul>
* <li>青果:code 为字符串。BALANCE_INSUFFICIENT=余额不足;INVALID_KEY/UNAVAILABLE_KEY/KEY_BLOCK/
* ACCESS_DENY/API_AUTH_DENY=密钥不可用或未授权;REQUEST_LIMIT_EXCEEDED=限流;
* INVALID_PARAMETER=参数错;其余业务失败按上游异常。</li>
* <li>极客:沿用历史口径(code=-1 或 message 含「余额不足」=余额不足)。</li>
* </ul>
* 返回 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",...}]}}。
* <b>server 才是代理地址</b>,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();
@@ -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<UserSecretModule> 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 时只检测输入值,结果暂存(不落库),保存同一个值时可沿用;
* 不传时检测已存值并直接落库。
*
* <p>货源(渠道/供应商)优先取本次请求带的选择,其次取服务端已存行;都为空时按模块默认值。
* 检测必须按同一个货源发起——渠道选错时「连通」是个假结论。</p>
*/
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)) {
@@ -0,0 +1,152 @@
package com.nanri.aiimage.modules.usersecret.support;
import java.util.Locale;
/**
* LLM 中转渠道:同一类密钥在不同中转上是**不同的 key**,所以渠道必须跟着密钥存。
*
* <p>两条渠道都走 OpenAI 兼容协议({@code POST {host}/v1/chat/completions}),
* 差别只有主机名,因此这里只登记 key / 展示名 / 主机,不另做适配层。</p>
*
* <p>默认值口径(2026-10-30 用户拍板):**新建**配置默认贞贞,龙抬头手动切换;
* 存量行同样回填为 {@link #T8STAR},两者一致。</p>
*/
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=沿用调用方配置的模型名。
*
* <p>两家中转的模型目录不同名:本系统业务配置写的是贞贞的
* {@code gemini-3.1-flash-lite-preview-thinking-medium} 等,龙抬头那边同一个模型叫
* {@code gemini-3.1-flash-lite}(2026-10-29 用户指定)。不映射直接切渠道会 model_not_found。</p>
*/
private final String defaultModel;
/**
* 该渠道是否需要**显式**传思考参数。
*
* <p>贞贞把思考写在模型名里({@code gemini-3.1-flash-lite-preview-thinking-medium}),
* 请求体不用额外字段;龙抬头的同名模型默认不思考,要复刻现网口径必须传
* {@code enable_thinking=true}(2026-10-30 实测:不传时 2.4s / 无 reasoning_content,
* 传 medium 后 13s / 返回 10k+ 字符思考链)。</p>
*/
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<String, Object> 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<String, Object> 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;
}
}
@@ -0,0 +1,94 @@
package com.nanri.aiimage.modules.usersecret.support;
import java.util.Locale;
/**
* 代理 IP 供应商:两家的提取链接与响应体结构不同,检测/解析必须按供应商分支。
*
* <ul>
* <li>{@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);</li>
* <li>{@link #JIKIP}:{@code https://api.jikip.com/ip-get?...},成功 {@code code=0},
* 失败 {@code code=-1} 且 message 常含「余额不足」。解析口径见 ProxyParser 模式 1/2。</li>
* </ul>
*
* <p>默认值口径(2026-10-30 用户拍板):**新建**配置默认极客,青果手动切换;
* 存量行同样回填为 {@link #JIKIP}。</p>
*/
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;
}
}
@@ -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 渠道主机。
*
* <p>渠道主机跟着任务上下文一起下发,而不是逐层加函数参数:行级处理跑在线程池里,
* 一条链路上有十几层方法都只透传 apiKey,多带一个 host 会把每个签名都改一遍,
* 而 {@link #wrap} 已经把整份上下文带到工作线程了,顺路带 host 成本为零。
* 显式传 host 的调用点仍然优先(见各 LLM 客户端的 resolveHost)。</p>
*/
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> T call(Long userId, String moduleKey, Supplier<T> action) {
return call(userId, moduleKey, null, action);
}
/** 在指定归属 + LLM 渠道主机下执行并返回结果。 */
public static <T> T call(Long userId, String moduleKey, String llmHost, Supplier<T> 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();
@@ -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<UserSecretModule> requiredModules() {
return Arrays.stream(values()).filter(UserSecretModule::required).toList();
@@ -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
@@ -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';