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:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
<div class="module-cell">
|
||||
<span v-if="row.similarAsin?.exists" class="mono-mask" :title="moduleTooltip(row.similarAsin)">{{ row.similarAsin.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span v-if="row.similarAsin?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
|
||||
{{ sourceLabel(row.similarAsin.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusMeta(row.similarAsin).tone" :title="moduleTooltip(row.similarAsin)">
|
||||
{{ moduleStatusMeta(row.similarAsin).label }}
|
||||
</span>
|
||||
@@ -320,6 +339,9 @@ onMounted(load)
|
||||
<div class="module-cell">
|
||||
<span v-if="row.appearancePatent?.exists" class="mono-mask" :title="moduleTooltip(row.appearancePatent)">{{ row.appearancePatent.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span v-if="row.appearancePatent?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
|
||||
{{ sourceLabel(row.appearancePatent.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusMeta(row.appearancePatent).tone" :title="moduleTooltip(row.appearancePatent)">
|
||||
{{ moduleStatusMeta(row.appearancePatent).label }}
|
||||
</span>
|
||||
@@ -330,6 +352,9 @@ onMounted(load)
|
||||
<span v-if="row.proxy?.exists" class="mono-mask mono-full" :title="moduleTooltip(row.proxy)">{{ row.proxy.full || row.proxy.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span class="module-cell-pills">
|
||||
<span v-if="row.proxy?.exists" class="wh-pill is-source" title="该用户代理所属供应商">
|
||||
{{ sourceLabel(row.proxy.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusMeta(row.proxy).tone" :title="moduleTooltip(row.proxy)">
|
||||
{{ moduleStatusMeta(row.proxy).label }}
|
||||
</span>
|
||||
@@ -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;
|
||||
|
||||
+17
-4
@@ -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();
|
||||
|
||||
+4
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -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)) {
|
||||
|
||||
+20
-4
@@ -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();
|
||||
|
||||
+5
@@ -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());
|
||||
|
||||
+4
-1
@@ -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");
|
||||
|
||||
+1
-1
@@ -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}")
|
||||
|
||||
+3
-2
@@ -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")
|
||||
|
||||
+4
@@ -9,4 +9,8 @@ public class UserApiSecretCheckRequest {
|
||||
|
||||
@Schema(description = "待检测的密钥明文;为空时检测服务端已保存的密钥(结果落库),非空时仅检测输入值(不落库)")
|
||||
private String value;
|
||||
|
||||
@Schema(description = "待检测的货源(未保存的下拉选择):LLM 密钥填 longtaitou/t8star,代理填 qingguo/jikip;"
|
||||
+ "为空时按服务端已存行的渠道/供应商检测")
|
||||
private String channel;
|
||||
}
|
||||
|
||||
+3
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -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;
|
||||
}
|
||||
|
||||
+2
@@ -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;
|
||||
|
||||
+3
@@ -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;
|
||||
|
||||
|
||||
+3
@@ -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;
|
||||
|
||||
|
||||
+153
-25
@@ -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();
|
||||
|
||||
+134
-41
@@ -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)) {
|
||||
|
||||
+152
@@ -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;
|
||||
}
|
||||
}
|
||||
+94
@@ -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;
|
||||
}
|
||||
}
|
||||
+30
-3
@@ -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();
|
||||
|
||||
+69
-2
@@ -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';
|
||||
+1
@@ -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,
|
||||
// 本夹具只驱动「候选收集」,永远不会进欠费终态分支;真进来了就说明测试形状变了
|
||||
|
||||
+60
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+27
-24
@@ -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());
|
||||
|
||||
+129
@@ -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 渠道(龙抬头/贞贞)与代理供应商(青果/极客)的归一化、默认值、主机与模型映射。
|
||||
*
|
||||
* <p>口径来源(2026-10-29 用户拍板):新建默认龙抬头 + 青果;存量由迁移 V180 回填贞贞/极客;
|
||||
* 龙抬头的模型 id 统一用 {@code gemini-3.1-flash-lite}。</p>
|
||||
*/
|
||||
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<String, Object> t8 = new LinkedHashMap<>();
|
||||
LlmChannel.applyThinkingForHost("https://ai.t8star.org", t8);
|
||||
assertThat(t8).isEmpty();
|
||||
|
||||
// 龙抬头的同名模型默认不思考,业务链路要显式补上,才等于现网口径
|
||||
Map<String, Object> ltt = new LinkedHashMap<>();
|
||||
LlmChannel.applyThinkingForHost("https://longtaitou.token6688.com", ltt);
|
||||
assertThat(ltt).containsEntry("enable_thinking", true);
|
||||
assertThat(ltt).containsEntry("thinking_budget", "medium");
|
||||
|
||||
// 未知主机不动请求体(自建中转/本地假上游不要被塞参数)
|
||||
Map<String, Object> 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());
|
||||
}
|
||||
}
|
||||
@@ -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<JavaApiResponse<UserApiSecretItem>, { value: string }>(
|
||||
put<JavaApiResponse<UserApiSecretItem>, { 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<JavaApiResponse<UserApiSecretCheckResult>, { value?: string }>(
|
||||
post<JavaApiResponse<UserApiSecretCheckResult>, { value?: string; channel?: string }>(
|
||||
buildJavaUrl(API_ENDPOINTS.userSecret.check.replace('{moduleKey}', encodeURIComponent(moduleKey))),
|
||||
{ value },
|
||||
channel ? { value, channel } : { value },
|
||||
{ timeout: 60000 },
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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<string, { proxy_url?: string; proxy_mode?: number }>;
|
||||
proxy_users?: Record<string, {
|
||||
proxy_url?: string;
|
||||
proxy_mode?: number;
|
||||
proxy_provider?: string;
|
||||
proxy_account?: string;
|
||||
proxy_password?: string;
|
||||
}>;
|
||||
/** 本机继承快照的作用域标记(CR-12:同一 app.json 才能继承)。 */
|
||||
api_secret_os_scope?: string;
|
||||
/** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */
|
||||
|
||||
@@ -2,8 +2,14 @@
|
||||
<div class="secret-settings-body">
|
||||
<section v-for="module in modules" :key="module.moduleKey" class="secret-card">
|
||||
<div class="secret-card-head">
|
||||
<div>
|
||||
<div class="secret-card-title">{{ module.moduleLabel }}</div>
|
||||
<div class="secret-card-heading">
|
||||
<div class="secret-card-title">
|
||||
{{ module.moduleLabel }}
|
||||
<span class="source-tag">{{ llmChannelLabel(moduleChannels[module.moduleKey]) }}</span>
|
||||
<span class="status-pill" :class="statusPillClassOf(module.moduleKey)">
|
||||
{{ statusPillTextOf(module.moduleKey) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="secret-card-desc">{{ descriptionOf(module.moduleKey) }}</div>
|
||||
</div>
|
||||
<button
|
||||
@@ -17,15 +23,40 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<input
|
||||
v-model="moduleStates[module.moduleKey].input"
|
||||
class="secret-input"
|
||||
type="password"
|
||||
:placeholder="placeholderOf(module.moduleKey)"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy"
|
||||
/>
|
||||
<div class="source-picker" role="radiogroup" :aria-label="`${module.moduleLabel}渠道`">
|
||||
<button
|
||||
v-for="option in LLM_CHANNEL_OPTIONS"
|
||||
:key="option.key"
|
||||
type="button"
|
||||
role="radio"
|
||||
:aria-checked="moduleChannels[module.moduleKey] === option.key"
|
||||
class="source-option"
|
||||
:class="{ 'source-option--active': moduleChannels[module.moduleKey] === option.key }"
|
||||
:disabled="busy"
|
||||
@click="selectChannel(module.moduleKey, option.key)"
|
||||
>
|
||||
<span class="source-option-label">{{ option.label }}</span>
|
||||
<span class="source-option-hint">{{ option.hint }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="secret-field">
|
||||
<label class="field-label" :for="`secret-input-${module.moduleKey}`">接口密钥</label>
|
||||
<input
|
||||
:id="`secret-input-${module.moduleKey}`"
|
||||
v-model="moduleStates[module.moduleKey].input"
|
||||
class="secret-input"
|
||||
type="password"
|
||||
:placeholder="placeholderOf(module.moduleKey)"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="channelSwitchNeedsValue(module.moduleKey)" class="inline-warn">
|
||||
已切换到「{{ llmChannelLabel(moduleChannels[module.moduleKey]) }}」,请填写该渠道的密钥后再保存(两家渠道的密钥不通用)。
|
||||
</div>
|
||||
|
||||
<div class="secret-actions">
|
||||
<button
|
||||
@@ -44,9 +75,10 @@
|
||||
|
||||
<section v-if="showProxy" class="secret-card">
|
||||
<div class="secret-card-head">
|
||||
<div>
|
||||
<div class="secret-card-heading">
|
||||
<div class="secret-card-title">
|
||||
代理设置
|
||||
<span class="source-tag">{{ proxyProviderLabel(proxyProvider) }}</span>
|
||||
<span v-if="proxyLocked" class="lock-tag">后台锁定</span>
|
||||
</div>
|
||||
<div class="secret-card-desc">
|
||||
@@ -57,6 +89,23 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="source-picker" role="radiogroup" aria-label="代理供应商">
|
||||
<button
|
||||
v-for="option in PROXY_PROVIDER_OPTIONS"
|
||||
:key="option.key"
|
||||
type="button"
|
||||
role="radio"
|
||||
:aria-checked="proxyProvider === option.key"
|
||||
class="source-option"
|
||||
:class="{ 'source-option--active': proxyProvider === option.key }"
|
||||
:disabled="!proxyReady || busy || proxyLocked"
|
||||
@click="selectProxyProvider(option.key)"
|
||||
>
|
||||
<span class="source-option-label">{{ option.label }}</span>
|
||||
<span class="source-option-hint">{{ option.hint }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="proxy-field">
|
||||
<label class="field-label" for="proxy-url">代理地址</label>
|
||||
<input
|
||||
@@ -64,7 +113,7 @@
|
||||
v-model="proxyUrl"
|
||||
class="secret-input"
|
||||
type="text"
|
||||
placeholder="如 http://user:pass@host:port 或代理提取链接"
|
||||
:placeholder="proxyPlaceholder"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="!proxyReady || busy || proxyLocked"
|
||||
@@ -72,6 +121,35 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="proxyReady && proxyProvider === 'qingguo'" class="retention-block">
|
||||
<div class="field-label">隧道代理账号(青果 Authkey / Authpwd)</div>
|
||||
<div class="proxy-plan-row">
|
||||
<input
|
||||
v-model="proxyAccount"
|
||||
class="secret-input"
|
||||
type="text"
|
||||
placeholder="Authkey,如 40F79A90"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy || proxyLocked"
|
||||
@input="proxyDirty = true"
|
||||
/>
|
||||
<input
|
||||
v-model="proxyPassword"
|
||||
class="secret-input"
|
||||
type="password"
|
||||
placeholder="Authpwd"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy || proxyLocked"
|
||||
@input="proxyDirty = true"
|
||||
/>
|
||||
</div>
|
||||
<div class="proxy-plan-hint">
|
||||
青果通道提取返回的是隧道端点(如 tunpool-xxx.qg.net:16359),连接时要用这对账密做认证;只存在本机,不上报服务端。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="retention-block">
|
||||
<div class="field-label">代理模式</div>
|
||||
<div class="retention-options">
|
||||
@@ -93,7 +171,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="proxySupported" class="retention-block">
|
||||
<div v-if="proxySupported && proxyProvider === 'jikip'" class="retention-block">
|
||||
<div class="field-label">jikip 套餐信息(用于余量查询与预警)</div>
|
||||
<div class="proxy-plan-row">
|
||||
<input
|
||||
@@ -138,6 +216,9 @@
|
||||
填写后,下方余量按你自己的 jikip 套餐查询;留空则显示平台默认套餐。套餐 ID / 用户 ID 在 jikip 后台「我的套餐」和「账户信息」查看。
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="proxySupported && proxyProvider === 'qingguo'" class="proxy-plan-hint">
|
||||
青果的账户余量与通道用量请到青果后台查看;本客户端目前只做青果提取链接的连通性检测。
|
||||
</div>
|
||||
|
||||
<div class="secret-actions">
|
||||
<button
|
||||
@@ -157,6 +238,7 @@
|
||||
<span v-if="proxyLoading">正在读取代理配置...</span>
|
||||
<span v-else-if="proxyLoadFailed">代理配置读取失败,请关闭弹窗后重试</span>
|
||||
<span v-else-if="!proxySupported">代理设置仅在桌面客户端中可用</span>
|
||||
<span v-else-if="proxyProvider === 'qingguo'">供应商:青果 · 提取链接示例 https://overseas.proxy.qg.net/get?key=...&format=json</span>
|
||||
<span v-else-if="balanceLoading">正在查询代理余量...</span>
|
||||
<span v-else-if="balance">{{ balanceText }}</span>
|
||||
<span v-else>余额查询暂不可用</span>
|
||||
@@ -184,6 +266,19 @@ import {
|
||||
type ServerProxySnapshot,
|
||||
type UserApiSecretCheckResult,
|
||||
} from '@/shared/utils/api-secret-store'
|
||||
import {
|
||||
DEFAULT_LLM_CHANNEL,
|
||||
DEFAULT_PROXY_PROVIDER,
|
||||
LLM_CHANNEL_OPTIONS,
|
||||
PROXY_PROVIDER_OPTIONS,
|
||||
detectProxyProviderFromUrl,
|
||||
llmChannelLabel,
|
||||
normalizeLlmChannel,
|
||||
normalizeProxyProvider,
|
||||
proxyProviderLabel,
|
||||
type LlmChannelKey,
|
||||
type ProxyProviderKey,
|
||||
} from '@/shared/utils/api-secret-channel'
|
||||
import { getPywebviewApi, type ProxyMode, type DesktopConfigUpdate } from '@/shared/bridges/pywebview'
|
||||
import { deleteMyApiSecret, putMyApiSecret, fetchProxyPlan, saveProxyPlan, clearProxyPlan } from '@/shared/api/types/modules/user-secret'
|
||||
import { PROXY_PLAN_CHANGED_EVENT } from '@/shared/utils/proxy-balance-alert'
|
||||
@@ -209,9 +304,15 @@ type ModuleState = {
|
||||
|
||||
const modules = ref(listApiSecretModules())
|
||||
const moduleStates = reactive<Record<string, ModuleState>>({})
|
||||
/** 每个模块当前选择的渠道:默认龙抬头,加载后以服务端已存值为准。 */
|
||||
const moduleChannels = reactive<Record<string, LlmChannelKey>>({})
|
||||
/** 用户手动切过渠道、但还没为这个渠道填写密钥:保存前必须拦住(两家密钥不通用)。 */
|
||||
const channelDirty = reactive<Record<string, boolean>>({})
|
||||
// 首次渲染即需可读:按模块清单预初始化状态(后续 refreshSnapshots 兜底补齐)
|
||||
for (const module of modules.value) {
|
||||
moduleStates[module.moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' }
|
||||
moduleChannels[module.moduleKey] = DEFAULT_LLM_CHANNEL
|
||||
channelDirty[module.moduleKey] = false
|
||||
}
|
||||
const snapshots = ref<Record<string, ApiSecretSnapshot>>({})
|
||||
const busy = ref(false)
|
||||
@@ -222,6 +323,10 @@ const proxyLocked = computed(() => Boolean(serverProxy.value?.locked && serverPr
|
||||
|
||||
const proxyUrl = ref('')
|
||||
const proxyMode = ref<ProxyMode>(1)
|
||||
const proxyProvider = ref<ProxyProviderKey>(DEFAULT_PROXY_PROVIDER)
|
||||
/** 青果隧道端点的代理账密(Authkey/Authpwd):只存本机 app.json,不上报服务端。 */
|
||||
const proxyAccount = ref('')
|
||||
const proxyPassword = ref('')
|
||||
const proxyLoading = ref(false)
|
||||
const proxyLoadFailed = ref(false)
|
||||
const proxyReady = ref(false)
|
||||
@@ -238,6 +343,12 @@ const proxyPlanConfigured = ref(false)
|
||||
const proxyPlanLoading = ref(false)
|
||||
const proxyPlanSaving = ref(false)
|
||||
|
||||
const proxyPlaceholder = computed(() =>
|
||||
proxyProvider.value === 'qingguo'
|
||||
? 'https://overseas.proxy.qg.net/get?key=...&num=1&format=json'
|
||||
: 'https://api.jikip.com/ip-get?num=1&minute=3&key=... 或 http://user:pass@host:port',
|
||||
)
|
||||
|
||||
const proxyStatusText = computed(() => {
|
||||
if (proxyChecking.value) return '正在检测...'
|
||||
if (proxyCheckResult.value) {
|
||||
@@ -258,6 +369,15 @@ const proxyResultClass = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
/** 切换代理供应商:只改本地选择,保存时与地址一起写入(检测也会按新供应商解析响应)。 */
|
||||
function selectProxyProvider(provider: ProxyProviderKey) {
|
||||
if (proxyProvider.value === provider) return
|
||||
proxyProvider.value = provider
|
||||
proxyDirty.value = true
|
||||
proxyCheckResult.value = null
|
||||
proxyCheckError.value = ''
|
||||
}
|
||||
|
||||
/** 检测代理连通性:地址有改动时检测输入值(不落库),否则检测/落库已存值并刷新状态展示。 */
|
||||
async function runProxyCheck() {
|
||||
if (proxyChecking.value) return
|
||||
@@ -267,7 +387,8 @@ async function runProxyCheck() {
|
||||
proxyCheckError.value = ''
|
||||
proxyCheckResult.value = null
|
||||
try {
|
||||
proxyCheckResult.value = await checkApiSecret('proxy', dirty ? inputValue : undefined)
|
||||
// 供应商一起提交:检测要按对应供应商解析提取响应(青果/极客返回体不同)
|
||||
proxyCheckResult.value = await checkApiSecret('proxy', dirty ? inputValue : undefined, proxyProvider.value)
|
||||
const result = proxyCheckResult.value
|
||||
if (result.checkStatus === 'failed') {
|
||||
ElMessage.warning(
|
||||
@@ -310,15 +431,34 @@ function ensureModuleState(moduleKey: string) {
|
||||
if (!moduleStates[moduleKey]) {
|
||||
moduleStates[moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' }
|
||||
}
|
||||
if (!moduleChannels[moduleKey]) {
|
||||
moduleChannels[moduleKey] = DEFAULT_LLM_CHANNEL
|
||||
}
|
||||
return moduleStates[moduleKey]
|
||||
}
|
||||
|
||||
/** 用户切换渠道:只改选择,保存时随密钥一起提交;已有密钥但没重新填写时给出提示。 */
|
||||
function selectChannel(moduleKey: string, channel: LlmChannelKey) {
|
||||
if (moduleChannels[moduleKey] === channel) return
|
||||
moduleChannels[moduleKey] = channel
|
||||
channelDirty[moduleKey] = true
|
||||
}
|
||||
|
||||
/** 切到新渠道但没填新密钥(且已有旧渠道密钥):保存前必须拦住。 */
|
||||
function channelSwitchNeedsValue(moduleKey: string) {
|
||||
return Boolean(channelDirty[moduleKey]) && !ensureModuleState(moduleKey).input.trim() && snapshotOf(moduleKey).exists
|
||||
}
|
||||
|
||||
function refreshSnapshots() {
|
||||
modules.value = listApiSecretModules()
|
||||
const next: Record<string, ApiSecretSnapshot> = {}
|
||||
for (const module of modules.value) {
|
||||
next[module.moduleKey] = getStoredApiSecretSnapshot(module.moduleKey as ApiSecretModuleKey)
|
||||
ensureModuleState(module.moduleKey)
|
||||
// 只在用户没主动切换过时跟服务端对齐,避免把手动选择回退掉
|
||||
if (!channelDirty[module.moduleKey]) {
|
||||
moduleChannels[module.moduleKey] = normalizeLlmChannel(next[module.moduleKey].channel)
|
||||
}
|
||||
}
|
||||
snapshots.value = next
|
||||
serverProxy.value = getServerProxySnapshot()
|
||||
@@ -337,7 +477,9 @@ function placeholderOf(moduleKey: string) {
|
||||
if (snapshot.exists) {
|
||||
return `已保存(${snapshot.masked || '****'}),输入新值可覆盖`
|
||||
}
|
||||
return '请输入 LLM 接口密钥'
|
||||
return moduleChannels[moduleKey] === 'longtaitou'
|
||||
? '请输入龙抬头接口密钥(sk-...)'
|
||||
: '请输入贞贞接口密钥(sk-...)'
|
||||
}
|
||||
|
||||
const CHECK_STATUS_TEXT: Record<ApiSecretCheckStatus, string> = {
|
||||
@@ -347,6 +489,26 @@ const CHECK_STATUS_TEXT: Record<ApiSecretCheckStatus, string> = {
|
||||
unknown: '已保存,未检测',
|
||||
}
|
||||
|
||||
function statusPillTextOf(moduleKey: string) {
|
||||
const state = ensureModuleState(moduleKey)
|
||||
if (state.checking) return '检测中'
|
||||
const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus
|
||||
if (status === 'passed') return '可用'
|
||||
if (status === 'failed') return '不可用'
|
||||
if (status === 'error') return '待确认'
|
||||
return snapshotOf(moduleKey).exists ? '未检测' : '未配置'
|
||||
}
|
||||
|
||||
function statusPillClassOf(moduleKey: string) {
|
||||
const state = ensureModuleState(moduleKey)
|
||||
const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus
|
||||
return {
|
||||
'status-pill--ok': status === 'passed',
|
||||
'status-pill--fail': status === 'failed',
|
||||
'status-pill--warn': status === 'error',
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(millis: number | null) {
|
||||
if (!millis) return ''
|
||||
const date = new Date(millis)
|
||||
@@ -400,7 +562,8 @@ async function runCheck(moduleKey: ApiSecretModuleKey) {
|
||||
state.lastCheckSource = inputValue ? 'input' : 'saved'
|
||||
try {
|
||||
// 不传 override 时服务端检测的是当前登录用户在密钥配置里保存的密钥(按 uid 绑定)
|
||||
const result = await checkApiSecret(moduleKey, inputValue || undefined)
|
||||
// 渠道一起提交:检测必须走所选渠道,否则「连通」是别的渠道的结论
|
||||
const result = await checkApiSecret(moduleKey, inputValue || undefined, moduleChannels[moduleKey])
|
||||
state.result = result
|
||||
if (result.checkStatus === 'failed') {
|
||||
ElMessage.warning(result.checkMessage || '密钥无效')
|
||||
@@ -427,6 +590,7 @@ async function clearModule(moduleKey: ApiSecretModuleKey) {
|
||||
state.input = ''
|
||||
state.result = null
|
||||
state.error = ''
|
||||
channelDirty[moduleKey] = false
|
||||
refreshSnapshots()
|
||||
ElMessage.success('已清空密钥')
|
||||
} catch (error) {
|
||||
@@ -451,22 +615,42 @@ function readUserProxy(config: Record<string, unknown> | null | undefined) {
|
||||
const own = (users[uid] ?? {}) as Record<string, unknown>
|
||||
const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
|
||||
if (ownUrl) {
|
||||
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
|
||||
return {
|
||||
url: ownUrl,
|
||||
mode: Number(own.proxy_mode) === 2 ? 2 : 1,
|
||||
provider: normalizeProxyProvider(own.proxy_provider ?? detectProxyProviderFromUrl(ownUrl)),
|
||||
account: typeof own.proxy_account === 'string' ? own.proxy_account : '',
|
||||
password: typeof own.proxy_password === 'string' ? own.proxy_password : '',
|
||||
}
|
||||
}
|
||||
}
|
||||
const url = typeof config?.proxy_url === 'string' ? config.proxy_url : ''
|
||||
return {
|
||||
url: typeof config?.proxy_url === 'string' ? config.proxy_url : '',
|
||||
url,
|
||||
mode: Number(config?.proxy_mode) === 2 ? 2 : 1,
|
||||
provider: normalizeProxyProvider(config?.proxy_provider ?? detectProxyProviderFromUrl(url)),
|
||||
account: typeof config?.proxy_account === 'string' ? config.proxy_account : '',
|
||||
password: typeof config?.proxy_password === 'string' ? config.proxy_password : '',
|
||||
}
|
||||
}
|
||||
|
||||
function userProxyPatch(nextProxyUrl: string, nextProxyMode: ProxyMode) {
|
||||
function userProxyPatch(
|
||||
nextProxyUrl: string,
|
||||
nextProxyMode: ProxyMode,
|
||||
provider: ProxyProviderKey,
|
||||
account: string,
|
||||
password: string,
|
||||
) {
|
||||
// 极客不需要这对账密:切过去时一并清空,避免残留串到别的供应商
|
||||
const credentials = provider === 'qingguo'
|
||||
? { proxy_account: account.trim(), proxy_password: password }
|
||||
: { proxy_account: '', proxy_password: '' }
|
||||
const uid = proxyUserId()
|
||||
if (uid === '0') {
|
||||
return { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode }
|
||||
return { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode, proxy_provider: provider, ...credentials }
|
||||
}
|
||||
const users: Record<string, unknown> = {}
|
||||
users[uid] = { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode }
|
||||
users[uid] = { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode, proxy_provider: provider, ...credentials }
|
||||
return { proxy_users: users }
|
||||
}
|
||||
|
||||
@@ -477,7 +661,7 @@ async function loadProxyConfig() {
|
||||
proxyDirty.value = false
|
||||
|
||||
const api = getPywebviewApi()
|
||||
proxySupported.value = Boolean(api?.read_config && api.save_config)
|
||||
proxySupported.value = Boolean(api?.read_config && api?.save_config)
|
||||
if (!api?.read_config || !api.save_config) {
|
||||
proxyUrl.value = ''
|
||||
proxyMode.value = 1
|
||||
@@ -490,6 +674,12 @@ async function loadProxyConfig() {
|
||||
const own = readUserProxy(config as Record<string, unknown>)
|
||||
proxyUrl.value = own.url
|
||||
proxyMode.value = (own.mode === 2 ? 2 : 1) as ProxyMode
|
||||
proxyAccount.value = own.account
|
||||
proxyPassword.value = own.password
|
||||
// 本地配置是权威(客户端任务链读的就是它);本地没写过时才用服务端里记的供应商
|
||||
proxyProvider.value = own.url
|
||||
? own.provider
|
||||
: normalizeProxyProvider(serverProxy.value?.channel ?? own.provider)
|
||||
proxyReady.value = true
|
||||
} catch (error) {
|
||||
proxyLoadFailed.value = true
|
||||
@@ -504,7 +694,8 @@ async function syncProxyToServer(url: string) {
|
||||
if (proxyUserId() === '0') return
|
||||
try {
|
||||
if (url) {
|
||||
await putMyApiSecret('proxy', url)
|
||||
// 供应商随地址一起上报:服务端检测要按供应商解析提取响应
|
||||
await putMyApiSecret('proxy', url, proxyProvider.value)
|
||||
} else {
|
||||
await deleteMyApiSecret('proxy')
|
||||
}
|
||||
@@ -515,6 +706,10 @@ async function syncProxyToServer(url: string) {
|
||||
}
|
||||
|
||||
async function loadProxyPlan() {
|
||||
if (proxyProvider.value !== 'jikip') {
|
||||
proxyPlanConfigured.value = false
|
||||
return
|
||||
}
|
||||
proxyPlanLoading.value = true
|
||||
try {
|
||||
const result = await fetchProxyPlan().catch((error) => {
|
||||
@@ -574,6 +769,11 @@ async function clearProxyPlanInfo() {
|
||||
}
|
||||
|
||||
async function loadBalance() {
|
||||
// 余量接口目前只有极客口径(jikip find-balance);青果不在客户端查询
|
||||
if (proxyProvider.value !== 'jikip') {
|
||||
balance.value = null
|
||||
return
|
||||
}
|
||||
balanceLoading.value = true
|
||||
try {
|
||||
const result = await fetchProxyBalanceSafely()
|
||||
@@ -597,6 +797,14 @@ async function loadBalance() {
|
||||
*/
|
||||
async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean> {
|
||||
if (busy.value || proxyLoading.value) return false
|
||||
// 切了渠道却只留着旧渠道的密钥:两家密钥不通用,必须让用户补填,否则保存后必然不可用
|
||||
const needRefill = modules.value.filter((module) => channelSwitchNeedsValue(module.moduleKey))
|
||||
if (needRefill.length) {
|
||||
ElMessage.warning(
|
||||
`已切换渠道,请填写该渠道的密钥:${needRefill.map((module) => module.moduleLabel).join('、')}`,
|
||||
)
|
||||
return false
|
||||
}
|
||||
const pendingModules = modules.value.filter((module) => ensureModuleState(module.moduleKey).input.trim())
|
||||
if (options.requireAll) {
|
||||
const missing = modules.value.filter(
|
||||
@@ -614,13 +822,14 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
|
||||
for (const module of pendingModules) {
|
||||
const moduleKey = module.moduleKey as ApiSecretModuleKey
|
||||
const state = ensureModuleState(module.moduleKey)
|
||||
await saveApiSecret(moduleKey, state.input.trim())
|
||||
await saveApiSecret(moduleKey, state.input.trim(), moduleChannels[module.moduleKey])
|
||||
state.input = ''
|
||||
// 输入值已保存:本地那次「检测输入值」的结果不再代表当前配置,清掉后展示统一走服务端快照
|
||||
// (保存前检测过的同一个值,服务端会沿用那次结果,快照里直接是「检测通过」)
|
||||
state.result = null
|
||||
state.lastCheckSource = ''
|
||||
state.error = ''
|
||||
channelDirty[module.moduleKey] = false
|
||||
}
|
||||
secretsSaved = true
|
||||
refreshSnapshots()
|
||||
@@ -629,13 +838,17 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.save_config) throw new Error('当前客户端未提供代理配置保存能力')
|
||||
const nextProxyUrl = proxyUrl.value.trim()
|
||||
await api.save_config(userProxyPatch(nextProxyUrl, proxyMode.value) as DesktopConfigUpdate)
|
||||
await api.save_config(
|
||||
userProxyPatch(nextProxyUrl, proxyMode.value, proxyProvider.value, proxyAccount.value, proxyPassword.value) as DesktopConfigUpdate,
|
||||
)
|
||||
proxyUrl.value = nextProxyUrl
|
||||
proxyDirty.value = false
|
||||
// 同上:地址已保存,本地「未保存」的检测文案不再适用
|
||||
proxyCheckResult.value = null
|
||||
proxyCheckError.value = ''
|
||||
await syncProxyToServer(nextProxyUrl)
|
||||
void loadProxyPlan()
|
||||
void loadBalance()
|
||||
}
|
||||
|
||||
// 保存后不再自动检测:检测一律由用户手动点击「检测」触发
|
||||
|
||||
@@ -22,6 +22,123 @@
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.secret-card-heading {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* 货源分段选择:两个选项并排,选中项描边高亮;不用原生 radio 是为了让「默认项」一眼可见 */
|
||||
.source-picker {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: 8px;
|
||||
margin: 10px 0 14px;
|
||||
}
|
||||
|
||||
.source-option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid #3b4652;
|
||||
border-radius: 10px;
|
||||
background: #1b2026;
|
||||
color: #c8d3de;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: border-color .15s ease, background .15s ease;
|
||||
}
|
||||
|
||||
.source-option:hover:not(:disabled) {
|
||||
border-color: #4c647d;
|
||||
}
|
||||
|
||||
.source-option--active {
|
||||
border-color: #5b96d6;
|
||||
background: #1f2a36;
|
||||
color: #eaf2fb;
|
||||
}
|
||||
|
||||
.source-option:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: .6;
|
||||
}
|
||||
|
||||
.source-option-label {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.source-option-hint {
|
||||
color: #7f8a96;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.source-option--active .source-option-hint {
|
||||
color: #93a5b8;
|
||||
}
|
||||
|
||||
.secret-field .field-label {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.inline-warn {
|
||||
margin-top: 8px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #6b5a2e;
|
||||
border-radius: 8px;
|
||||
background: #2e2a1c;
|
||||
color: #e6c76a;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.status-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 6px;
|
||||
padding: 1px 8px;
|
||||
border: 1px solid #3b4652;
|
||||
border-radius: 999px;
|
||||
background: #1b2026;
|
||||
color: #909ba8;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.status-pill--ok {
|
||||
border-color: #2f5c44;
|
||||
background: #1b2a22;
|
||||
color: #7fd6a4;
|
||||
}
|
||||
|
||||
.status-pill--fail {
|
||||
border-color: #6b2f2f;
|
||||
background: #2a1c1c;
|
||||
color: #ff9b9b;
|
||||
}
|
||||
|
||||
.status-pill--warn {
|
||||
border-color: #6b5a2e;
|
||||
background: #2e2a1c;
|
||||
color: #e6c76a;
|
||||
}
|
||||
|
||||
.source-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 6px;
|
||||
padding: 1px 8px;
|
||||
border: 1px solid #3b4652;
|
||||
border-radius: 999px;
|
||||
background: #1b2026;
|
||||
color: #9fb3c8;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.secret-card-title {
|
||||
color: #eef4fb;
|
||||
font-size: 15px;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* 密钥「货源」选项:LLM 渠道(龙抬头/贞贞)与代理供应商(青果/极客)。
|
||||
*
|
||||
* 与后端 `LlmChannel` / `ProxyProvider` 枚举一一对应;用户密钥行上统一叫 `channel`:
|
||||
* LLM 模块存渠道 key,代理模块存供应商 key。
|
||||
*
|
||||
* 默认值口径(2026-10-30 用户拍板):新建默认贞贞 / 极客,龙抬头与青果手动切换;
|
||||
* 存量由服务端迁移回填为贞贞 / 极客,前端只按服务端下发的值回显,不自行改写。
|
||||
*/
|
||||
export type LlmChannelKey = 'longtaitou' | 't8star'
|
||||
export type ProxyProviderKey = 'qingguo' | 'jikip'
|
||||
|
||||
export interface SourceOption<T extends string> {
|
||||
key: T
|
||||
label: string
|
||||
hint: string
|
||||
}
|
||||
|
||||
export const LLM_CHANNEL_OPTIONS: Array<SourceOption<LlmChannelKey>> = [
|
||||
{ key: 'longtaitou', label: '龙抬头', hint: 'longtaitou.token6688.com' },
|
||||
{ key: 't8star', label: '贞贞', hint: 'ai.t8star.org(默认)' },
|
||||
]
|
||||
|
||||
export const PROXY_PROVIDER_OPTIONS: Array<SourceOption<ProxyProviderKey>> = [
|
||||
{ key: 'qingguo', label: '青果', hint: 'overseas.proxy.qg.net' },
|
||||
{ key: 'jikip', label: '极客', hint: 'api.jikip.com(默认)' },
|
||||
]
|
||||
|
||||
export const DEFAULT_LLM_CHANNEL: LlmChannelKey = 't8star'
|
||||
export const DEFAULT_PROXY_PROVIDER: ProxyProviderKey = 'jikip'
|
||||
|
||||
export function isLlmChannelKey(value: unknown): value is LlmChannelKey {
|
||||
return value === 'longtaitou' || value === 't8star'
|
||||
}
|
||||
|
||||
export function isProxyProviderKey(value: unknown): value is ProxyProviderKey {
|
||||
return value === 'qingguo' || value === 'jikip'
|
||||
}
|
||||
|
||||
/** 回显用:服务端值 → 选项;未知/为空按模块默认值。 */
|
||||
export function normalizeLlmChannel(value: unknown): LlmChannelKey {
|
||||
return isLlmChannelKey(value) ? value : DEFAULT_LLM_CHANNEL
|
||||
}
|
||||
|
||||
/** 按提取链接域名识别供应商:老配置只存了链接、没存供应商时兜底(识别不出返回 null)。 */
|
||||
export function detectProxyProviderFromUrl(url: unknown): ProxyProviderKey | null {
|
||||
const text = typeof url === 'string' ? url.trim().toLowerCase() : ''
|
||||
if (!text) return null
|
||||
if (text.includes('jikip.cn') || text.includes('jikip.com')) return 'jikip'
|
||||
if (text.includes('qg.net')) return 'qingguo'
|
||||
return null
|
||||
}
|
||||
|
||||
export function normalizeProxyProvider(value: unknown): ProxyProviderKey {
|
||||
return isProxyProviderKey(value) ? value : DEFAULT_PROXY_PROVIDER
|
||||
}
|
||||
|
||||
export function llmChannelLabel(value: unknown): string {
|
||||
const key = normalizeLlmChannel(value)
|
||||
return LLM_CHANNEL_OPTIONS.find((option) => option.key === key)?.label || key
|
||||
}
|
||||
|
||||
export function proxyProviderLabel(value: unknown): string {
|
||||
const key = normalizeProxyProvider(value)
|
||||
return PROXY_PROVIDER_OPTIONS.find((option) => option.key === key)?.label || key
|
||||
}
|
||||
@@ -44,12 +44,14 @@ export interface ApiSecretInheritanceHost {
|
||||
moduleKeys(): Set<string>
|
||||
readSecret(moduleKey: string): string
|
||||
writeSecret(moduleKey: string, value: string): void
|
||||
/** 该模块密钥所属货源(longtaitou/t8star);旧实现可不提供,缺省按「存量=贞贞」处理。 */
|
||||
readSecretChannel?(moduleKey: string): string
|
||||
readConfig(): Promise<Record<string, unknown> | null>
|
||||
saveConfig(patch: Record<string, unknown>): Promise<unknown>
|
||||
readLocalProxy(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
uid: string,
|
||||
): { url: string; mode: SecretProxyMode }
|
||||
): { url: string; mode: SecretProxyMode; provider?: string }
|
||||
}
|
||||
|
||||
export interface InheritanceOutcome {
|
||||
@@ -66,8 +68,15 @@ export type InheritedSecretStash = {
|
||||
savedAt: number
|
||||
osUserScope: string
|
||||
secrets: Record<string, string>
|
||||
/**
|
||||
* 每个模块密钥的货源(longtaitou/t8star)。旧快照没有这个字段:那时的密钥都是贞贞发出来的,
|
||||
* 缺省交给服务端按「存量=贞贞」回填,不能按新建默认(龙抬头)落库。
|
||||
*/
|
||||
secretChannels: Record<string, string>
|
||||
proxyUrl: string
|
||||
proxyMode: SecretProxyMode
|
||||
/** 代理供应商(qingguo/jikip);旧快照缺省 → 服务端按链接域名识别。 */
|
||||
proxyProvider: string
|
||||
}
|
||||
|
||||
export type InheritanceStashRead =
|
||||
@@ -145,6 +154,16 @@ export function readInheritedSecretStash(
|
||||
}
|
||||
const proxyUrl = text(proxyRaw)
|
||||
if (!Object.keys(secrets).length && !proxyUrl) return { state: 'invalid' }
|
||||
// 货源字段是可选的(旧快照没有):结构不符只丢掉该字段,不整份判 invalid
|
||||
const channelRecord = asRecord(record.secretChannels)
|
||||
const secretChannels: Record<string, string> = {}
|
||||
if (channelRecord) {
|
||||
for (const [moduleKey, channel] of Object.entries(channelRecord)) {
|
||||
if (allowed.has(moduleKey) && typeof channel === 'string' && channel.trim()) {
|
||||
secretChannels[moduleKey] = channel.trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
state: 'valid',
|
||||
stash: {
|
||||
@@ -154,8 +173,10 @@ export function readInheritedSecretStash(
|
||||
savedAt,
|
||||
osUserScope,
|
||||
secrets,
|
||||
secretChannels,
|
||||
proxyUrl,
|
||||
proxyMode: Number(record.proxyMode) === 2 ? 2 : 1,
|
||||
proxyProvider: text(record.proxyProvider),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -181,9 +202,14 @@ export async function captureSecretsForInheritance(host: ApiSecretInheritanceHos
|
||||
if (uid === '0') return
|
||||
const epoch = host.currentEpoch()
|
||||
const secrets: Record<string, string> = {}
|
||||
const secretChannels: Record<string, string> = {}
|
||||
for (const moduleKey of host.moduleKeys()) {
|
||||
const value = host.readSecret(moduleKey).trim()
|
||||
if (value) secrets[moduleKey] = value
|
||||
if (value) {
|
||||
secrets[moduleKey] = value
|
||||
const channel = host.readSecretChannel?.(moduleKey) || ''
|
||||
if (channel) secretChannels[moduleKey] = channel
|
||||
}
|
||||
}
|
||||
const config = await withTimeout(host.readConfig(), BRIDGE_TIMEOUT_MS).catch((error) => {
|
||||
console.warn('[api-secret] 登出时读取本机配置失败,继承快照将不含代理:', error)
|
||||
@@ -201,8 +227,10 @@ export async function captureSecretsForInheritance(host: ApiSecretInheritanceHos
|
||||
savedAt: Date.now(),
|
||||
osUserScope,
|
||||
secrets,
|
||||
secretChannels,
|
||||
proxyUrl: proxy.url,
|
||||
proxyMode: proxy.mode,
|
||||
proxyProvider: proxy.provider || '',
|
||||
}
|
||||
: null
|
||||
await withTimeout(host.saveConfig({ [OS_SCOPE_KEY]: osUserScope, [INHERIT_STASH_KEY]: stash }), BRIDGE_TIMEOUT_MS)
|
||||
@@ -241,9 +269,12 @@ export async function applyInheritedSecrets(
|
||||
if (uid === '0') return { count: 0, notice: null, cleared: false }
|
||||
const epoch = host.currentEpoch()
|
||||
const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey))
|
||||
const pending: Array<{ moduleKey: string; value: string }> = []
|
||||
const pending: Array<{ moduleKey: string; value: string; channel?: string }> = []
|
||||
for (const [moduleKey, value] of Object.entries(stash.secrets)) {
|
||||
if (!serverHas.has(moduleKey)) pending.push({ moduleKey, value })
|
||||
if (serverHas.has(moduleKey)) continue
|
||||
// 渠道随密钥一起继承:快照没有渠道(旧版本)时留空,由服务端按「存量=贞贞」回填
|
||||
const channel = stash.secretChannels?.[moduleKey]
|
||||
pending.push(channel ? { moduleKey, value, channel } : { moduleKey, value })
|
||||
}
|
||||
// 本机已有代理时以本机为准:它会被代理补报逻辑上报给当前账号,
|
||||
// 这里再塞上一个账号的代理会让「服务端查商标」和「客户端跑任务」走两条不同的出口。
|
||||
@@ -254,7 +285,11 @@ export async function applyInheritedSecrets(
|
||||
&& !serverProxyItem?.exists
|
||||
&& !serverProxyItem?.locked
|
||||
&& !ownProxy
|
||||
if (inheritProxy) pending.push({ moduleKey: 'proxy', value: stash.proxyUrl })
|
||||
if (inheritProxy) {
|
||||
pending.push(stash.proxyProvider
|
||||
? { moduleKey: 'proxy', value: stash.proxyUrl, channel: stash.proxyProvider }
|
||||
: { moduleKey: 'proxy', value: stash.proxyUrl })
|
||||
}
|
||||
if (!pending.length) {
|
||||
await clearInheritedSecrets(host)
|
||||
return { count: 0, notice: null, cleared: true }
|
||||
@@ -272,7 +307,13 @@ export async function applyInheritedSecrets(
|
||||
}
|
||||
const patch: Record<string, unknown> = { [INHERIT_STASH_KEY]: null }
|
||||
if (inheritProxy) {
|
||||
patch.proxy_users = { [uid]: { proxy_url: stash.proxyUrl, proxy_mode: stash.proxyMode } }
|
||||
patch.proxy_users = {
|
||||
[uid]: {
|
||||
proxy_url: stash.proxyUrl,
|
||||
proxy_mode: stash.proxyMode,
|
||||
...(stash.proxyProvider ? { proxy_provider: stash.proxyProvider } : {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
await host.saveConfig(patch).catch((error) => {
|
||||
console.warn('[api-secret] 继承配置已写入服务端,但写回本机配置失败:', error)
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
type PendingApiSecretInheritance,
|
||||
} from './api-secret-inheritance.ts'
|
||||
import { withTimeout } from './promise-timeout.ts'
|
||||
import { detectProxyProviderFromUrl } from './api-secret-channel.ts'
|
||||
import type { DesktopConfigUpdate } from '../bridges/pywebview.ts'
|
||||
|
||||
export type { ApiSecretModuleKey, ApiSecretCheckStatus }
|
||||
@@ -55,6 +56,8 @@ export interface ApiSecretSnapshot {
|
||||
value: string
|
||||
/** 服务端脱敏值(权威展示,如 sk-a****1234)。 */
|
||||
masked: string
|
||||
/** 货源:LLM 行为渠道(longtaitou/t8star),代理为供应商(qingguo/jikip);空串=服务端未标注。 */
|
||||
channel: string
|
||||
exists: boolean
|
||||
/** 是否由后台代填并锁定:锁定时客户端不可修改或清空(当前仅代理模块)。 */
|
||||
locked: boolean
|
||||
@@ -174,6 +177,7 @@ function emptyEntry(): ApiSecretCacheEntry {
|
||||
schema: 2,
|
||||
value: '',
|
||||
masked: '',
|
||||
channel: '',
|
||||
exists: false,
|
||||
locked: false,
|
||||
checkStatus: 'unknown',
|
||||
@@ -208,6 +212,7 @@ function readMirror(moduleKey: string): ApiSecretCacheEntry | null {
|
||||
schema: 2,
|
||||
value: typeof parsed.value === 'string' ? parsed.value : '',
|
||||
masked: typeof parsed.masked === 'string' ? parsed.masked : '',
|
||||
channel: typeof parsed.channel === 'string' ? parsed.channel : '',
|
||||
exists: Boolean(parsed.exists),
|
||||
locked: Boolean(parsed.locked),
|
||||
checkStatus: normalizeCheckStatus(parsed.checkStatus),
|
||||
@@ -331,6 +336,8 @@ function applyServerItem(moduleKey: string, item: UserApiSecretItem) {
|
||||
// 明文仅来自本地输入/迁移,服务端不下发
|
||||
value: current.value,
|
||||
masked: item.masked || '',
|
||||
// 货源以服务端为准;服务端未下发(老版本后端)时保留本地值
|
||||
channel: item.channel || current.channel,
|
||||
exists: Boolean(item.exists),
|
||||
locked: Boolean(item.locked),
|
||||
checkStatus: normalizeCheckStatus(item.checkStatus),
|
||||
@@ -691,30 +698,39 @@ function isSharedProxy(config: Record<string, unknown> | null | undefined, uid:
|
||||
function readLocalProxyEntry(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
uid = currentUid(),
|
||||
): { url: string; mode: 1 | 2 } {
|
||||
if (!config) return { url: '', mode: 1 }
|
||||
): { url: string; mode: 1 | 2; provider: string } {
|
||||
if (!config) return { url: '', mode: 1, provider: '' }
|
||||
const globalUrl = typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
|
||||
const globalMode: 1 | 2 = Number(config.proxy_mode) === 2 ? 2 : 1
|
||||
// 供应商:显式配置优先,其次按域名识别;都没有返回空串(下游按链接再识别,别硬塞默认值)
|
||||
const providerOf = (raw: unknown, url: string) => {
|
||||
const explicit = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
||||
return explicit || detectProxyProviderFromUrl(url) || ''
|
||||
}
|
||||
if (uid !== '0') {
|
||||
const users = (config.proxy_users ?? {}) as Record<string, unknown>
|
||||
const own = (users[uid] ?? {}) as Record<string, unknown>
|
||||
const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
|
||||
if (ownUrl) {
|
||||
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
|
||||
return {
|
||||
url: ownUrl,
|
||||
mode: Number(own.proxy_mode) === 2 ? 2 : 1,
|
||||
provider: providerOf(own.proxy_provider, ownUrl),
|
||||
}
|
||||
}
|
||||
}
|
||||
const owner = typeof config.proxy_uid === 'string' ? config.proxy_uid.trim() : ''
|
||||
const shared = isSharedProxy(config, uid)
|
||||
if (!globalUrl) return { url: '', mode: 1 }
|
||||
if (!globalUrl) return { url: '', mode: 1, provider: '' }
|
||||
if (uid === '0') {
|
||||
// 未登录没有"账号归属"可言:只认匿名全局(无归属/归属 0)或显式共享
|
||||
return !owner || owner === '0' || shared
|
||||
? { url: globalUrl, mode: globalMode }
|
||||
: { url: '', mode: 1 }
|
||||
? { url: globalUrl, mode: globalMode, provider: providerOf(config.proxy_provider, globalUrl) }
|
||||
: { url: '', mode: 1, provider: '' }
|
||||
}
|
||||
return owner === uid || shared
|
||||
? { url: globalUrl, mode: globalMode }
|
||||
: { url: '', mode: 1 }
|
||||
? { url: globalUrl, mode: globalMode, provider: providerOf(config.proxy_provider, globalUrl) }
|
||||
: { url: '', mode: 1, provider: '' }
|
||||
}
|
||||
|
||||
function readLocalProxyUrl(
|
||||
@@ -729,6 +745,7 @@ function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxy
|
||||
return {
|
||||
value: '',
|
||||
masked: proxy.masked || '',
|
||||
channel: proxy.channel || '',
|
||||
exists: Boolean(proxy.exists),
|
||||
locked: Boolean(proxy.locked),
|
||||
full: typeof proxy.full === 'string' ? proxy.full.trim() : '',
|
||||
@@ -782,6 +799,8 @@ const inheritanceHost: ApiSecretInheritanceHost = {
|
||||
isDesktopStorage: isNativeDesktopStorage,
|
||||
moduleKeys: () => new Set<string>([...DEFAULT_REQUIRED_MODULES, ...requiredModules]),
|
||||
readSecret: (moduleKey) => readEntry(moduleKey).value,
|
||||
// 渠道随密钥一起继承:否则下一个账号会把龙抬头的密钥按「存量=贞贞」落库
|
||||
readSecretChannel: (moduleKey) => readEntry(moduleKey).channel,
|
||||
// 只有 applyInheritedSecrets 在 migrate 的 await 之后重新比过 uid/epoch 才会调到这里
|
||||
writeSecret: (moduleKey, value) => {
|
||||
const entry = readEntry(moduleKey)
|
||||
@@ -912,12 +931,16 @@ export function takeApiSecretInheritanceNotice(): ApiSecretInheritanceNotice | n
|
||||
}
|
||||
|
||||
/** 保存密钥到服务端;成功后刷新本地缓存(失败不写本地,避免本地有值服务端没有的假象)。 */
|
||||
export async function saveApiSecret(moduleKey: ApiSecretModuleKey, value: string): Promise<ApiSecretSnapshot> {
|
||||
export async function saveApiSecret(
|
||||
moduleKey: ApiSecretModuleKey,
|
||||
value: string,
|
||||
channel?: string,
|
||||
): Promise<ApiSecretSnapshot> {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) {
|
||||
throw new Error('密钥不能为空')
|
||||
}
|
||||
const item = await putMyApiSecret(moduleKey, trimmed)
|
||||
const item = await putMyApiSecret(moduleKey, trimmed, channel)
|
||||
applyServerItem(moduleKey, item)
|
||||
updateEntry(moduleKey, { value: trimmed, exists: true })
|
||||
bundleLoaded = true
|
||||
@@ -935,9 +958,10 @@ export async function clearApiSecret(moduleKey: ApiSecretModuleKey): Promise<voi
|
||||
export async function checkApiSecret(
|
||||
moduleKey: ApiSecretModuleKey,
|
||||
value?: string,
|
||||
channel?: string,
|
||||
): Promise<UserApiSecretCheckResult> {
|
||||
const override = value?.trim()
|
||||
const result = await checkMyApiSecret(moduleKey, override || undefined)
|
||||
const result = await checkMyApiSecret(moduleKey, override || undefined, channel)
|
||||
if (!override) {
|
||||
updateEntry(moduleKey, {
|
||||
checkStatus: normalizeCheckStatus(result.checkStatus),
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict'
|
||||
import { http } from '../src/shared/api/http.ts'
|
||||
import {
|
||||
captureApiSecretsForInheritance,
|
||||
checkApiSecret,
|
||||
clearApiSecretCache,
|
||||
confirmApiSecretInheritance,
|
||||
declineApiSecretInheritance,
|
||||
@@ -307,11 +308,13 @@ function seedDesktopMirror(
|
||||
uid: string,
|
||||
moduleKey: string,
|
||||
value: string,
|
||||
channel = '',
|
||||
) {
|
||||
localStorage.setItem(`brand:api-secret-cache:${uid}:${moduleKey}`, JSON.stringify({
|
||||
schema: 2,
|
||||
value,
|
||||
masked: '',
|
||||
channel,
|
||||
exists: true,
|
||||
locked: false,
|
||||
checkStatus: 'passed',
|
||||
@@ -812,3 +815,108 @@ test('test_secret_store_locked_proxy_not_in_module_cards', async (t) => {
|
||||
clearApiSecretCache()
|
||||
assert.equal(getServerProxySnapshot(), null, '登出清理应重置服务端代理状态')
|
||||
})
|
||||
|
||||
test('test_secret_store_save_sends_channel_and_keeps_it', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
let body: Record<string, unknown> | null = null
|
||||
mockRequest(t, (config) => {
|
||||
body = (config.data || {}) as Record<string, unknown>
|
||||
return okResponse(serverItem('appearance-patent', { masked: 'sk-a****1234', exists: true, channel: 'longtaitou' }))
|
||||
})
|
||||
|
||||
await saveApiSecret('appearance-patent', 'sk-abc123456', 'longtaitou')
|
||||
|
||||
assert.equal(body?.channel, 'longtaitou', '保存必须把渠道一起提交,否则服务端按默认渠道落库')
|
||||
assert.equal(getStoredApiSecretSnapshot('appearance-patent').channel, 'longtaitou')
|
||||
})
|
||||
|
||||
test('test_secret_store_check_passes_channel', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
let body: Record<string, unknown> | null = null
|
||||
mockRequest(t, (config) => {
|
||||
body = (config.data || {}) as Record<string, unknown>
|
||||
return okResponse({
|
||||
moduleKey: 'similar-asin',
|
||||
checkStatus: 'passed',
|
||||
checkCode: 'ok',
|
||||
checkMessage: '连通正常',
|
||||
checkLatencyMs: 120,
|
||||
checkedAt: null,
|
||||
viaProxy: false,
|
||||
})
|
||||
})
|
||||
|
||||
const result = await checkApiSecret('similar-asin', 'sk-abc123456', 't8star')
|
||||
|
||||
assert.equal(body?.channel, 't8star', '检测要按所选渠道发起,别拿默认渠道的结论冒充')
|
||||
assert.equal(body?.value, 'sk-abc123456')
|
||||
assert.equal(result.checkStatus, 'passed')
|
||||
})
|
||||
|
||||
test('test_secret_store_snapshot_without_channel_stays_empty', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
mockRequest(t, () => bundleResponse([
|
||||
serverItem('appearance-patent', { exists: true, masked: 'sk-a****1234' }),
|
||||
serverItem('similar-asin'),
|
||||
]))
|
||||
|
||||
await loadApiSecrets({ force: true })
|
||||
|
||||
assert.equal(
|
||||
getStoredApiSecretSnapshot('appearance-patent').channel,
|
||||
'',
|
||||
'老版本后端不下发渠道时保留空串,由界面按默认值展示',
|
||||
)
|
||||
})
|
||||
|
||||
test('test_secret_store_inheritance_keeps_channel_and_proxy_provider', async (t) => {
|
||||
const { localStorage } = setupWindow()
|
||||
clearApiSecretCache()
|
||||
const aliceProxy = 'https://overseas.proxy.qg.net/get?key=alice&format=json'
|
||||
let config: Record<string, unknown> = {
|
||||
current_uid: '42',
|
||||
proxy_users: { '42': { proxy_url: aliceProxy, proxy_mode: 1, proxy_provider: 'qingguo' } },
|
||||
}
|
||||
attachDesktopBridge(
|
||||
() => config,
|
||||
(patch) => {
|
||||
config = mergeDesktopConfig(config, patch)
|
||||
return config
|
||||
},
|
||||
)
|
||||
localStorage.setItem('username', 'alice')
|
||||
// 龙抬头的密钥:换号继承时必须把渠道一起带走,否则下一个账号会把它按「存量=贞贞」落库
|
||||
seedDesktopMirror(localStorage, '42', 'appearance-patent', 'sk-alice-longtaitou', 'longtaitou')
|
||||
|
||||
await captureApiSecretsForInheritance()
|
||||
clearApiSecretCache()
|
||||
localStorage.removeItem('uid')
|
||||
localStorage.setItem('uid', '43')
|
||||
localStorage.setItem('username', 'bob')
|
||||
|
||||
let migratePayload: Record<string, unknown> | null = null
|
||||
mockRequest(t, (req) => {
|
||||
if ((req.url || '').includes('/migrate')) {
|
||||
migratePayload = req.data as Record<string, unknown>
|
||||
return okResponse({ migrated: 1 })
|
||||
}
|
||||
return bundleResponse([
|
||||
serverItem('appearance-patent'),
|
||||
serverItem('similar-asin', { exists: true, masked: 'sk-c****9999' }),
|
||||
])
|
||||
})
|
||||
|
||||
await loadApiSecrets({ force: true })
|
||||
await confirmApiSecretInheritance()
|
||||
|
||||
const items = ((migratePayload?.items || []) as Array<Record<string, unknown>>)
|
||||
const appearance = items.find((item) => item.moduleKey === 'appearance-patent')
|
||||
assert.equal(appearance?.channel, 'longtaitou', '继承要带上渠道,不能按新建默认落库')
|
||||
const proxy = items.find((item) => item.moduleKey === 'proxy')
|
||||
assert.equal(proxy?.channel, 'qingguo', '代理继承要带上供应商')
|
||||
const users = (config.proxy_users || {}) as Record<string, Record<string, unknown>>
|
||||
assert.equal(users['43']?.proxy_provider, 'qingguo', '写回本机配置时供应商不能丢')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user