diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue index 1e45b39753..2e4bbceb2d 100644 --- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue +++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue @@ -2378,7 +2378,7 @@ function currentAiEditConfig() { const reasoningLevel = aiIsClaudeCodeCli.value ? normalizeClaudeCodeReasoningLevel(aiEditReasoningLevel.value, aiSelectedModelInfo.value) : aiEditReasoningLevel.value; return { provider: aiEditProvider.value, - apiKey: aiEditApiKey.value, + apiKey: aiEditApiKey.value.trim(), authMethod: aiEditAuthMethod.value, endpoint: aiEditEndpoint.value, model: aiEditModel.value, @@ -2503,7 +2503,7 @@ async function aiFetchModelList() { try { const models = await aiListModels({ provider: aiEditProvider.value, - apiKey: aiEditApiKey.value, + apiKey: aiEditApiKey.value.trim(), endpoint: aiEditEndpoint.value, model: aiEditModel.value, authMethod: aiEditAuthMethod.value, diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts index 98570c8b50..9c5da7afdc 100644 --- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts +++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { enforceRightSidebarPanelExclusivity, EXECUTE_MODE_CURRENT_DEFAULT_VERSION, normalizeDesktopSettings, normalizeEditorSettings, normalizeMcpGlobalPolicy, transitionRightSidebarPanels, type RightSidebarPanelState } from "@/stores/settingsStore"; +import { enforceRightSidebarPanelExclusivity, EXECUTE_MODE_CURRENT_DEFAULT_VERSION, normalizeAiConfig, normalizeDesktopSettings, normalizeEditorSettings, normalizeMcpGlobalPolicy, transitionRightSidebarPanels, type RightSidebarPanelState } from "@/stores/settingsStore"; import { createPinia, setActivePinia } from "pinia"; import { isProxy } from "vue"; import type { AiConfigItem } from "@/types/ai"; @@ -318,6 +318,31 @@ function makeTestConfig(overrides: Partial & { id: string }): AiCo } as AiConfigItem; } +describe("settingsStore AI API key normalization", () => { + beforeEach(() => { + vi.resetModules(); + setActivePinia(createPinia()); + }); + + it("trims API keys before persisting new configurations", async () => { + const saveAiConfigItem = vi.fn().mockResolvedValue(undefined); + vi.doMock("@/lib/backend/api", () => ({ saveAiConfigItem })); + + const { useSettingsStore } = await import("@/stores/settingsStore"); + const store = useSettingsStore(); + const config = makeTestConfig({ id: "trimmed-key", apiKey: " \tsecret\r\n" }); + + await store.createAiConfig(config); + + expect(saveAiConfigItem).toHaveBeenCalledWith(expect.objectContaining({ apiKey: "secret" })); + expect(store.aiConfigs[0].apiKey).toBe("secret"); + }); + + it("trims API keys when normalizing loaded configurations", () => { + expect(normalizeAiConfig({ provider: "openai", apiKey: " secret " }).apiKey).toBe("secret"); + }); +}); + describe("settingsStore MCP policy persistence", () => { beforeEach(() => { vi.resetModules(); diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts index 3e279ae5af..4339587172 100644 --- a/apps/desktop/src/stores/settingsStore.ts +++ b/apps/desktop/src/stores/settingsStore.ts @@ -250,9 +250,9 @@ export function normalizeAiConfig(config: Partial | null | undefined): const provider = config?.provider && config.provider in AI_PROVIDER_PRESETS ? config.provider : inferAiProviderFromConfig(config); return { ...defaultConfigs[provider], - apiKey: config?.apiKey ?? "", ...config, provider, + apiKey: (config?.apiKey ?? "").trim(), apiStyle: config?.apiStyle ?? defaultConfigs[provider].apiStyle, authMethod: config?.authMethod ?? defaultConfigs[provider].authMethod, proxyEnabled: !!config?.proxyEnabled, @@ -267,6 +267,10 @@ export function normalizeAiConfig(config: Partial | null | undefined): }; } +function normalizeAiConfigItem(config: AiConfigItem): AiConfigItem { + return { ...config, ...normalizeAiConfig(config) }; +} + function inferAiProviderFromConfig(config: Partial | null | undefined): AiProvider { const endpoint = config?.endpoint?.toLowerCase() ?? ""; const model = config?.model?.toLowerCase() ?? ""; @@ -1087,7 +1091,7 @@ export const useSettingsStore = defineStore("settings", () => { const newConfigs = await api.loadAiConfigs(); if (newConfigs.length > 0) { - aiConfigs.value = newConfigs; + aiConfigs.value = newConfigs.map(normalizeAiConfigItem); } else { // 迁移旧格式 await migrateToMultiConfig(); @@ -1146,17 +1150,18 @@ export const useSettingsStore = defineStore("settings", () => { } async function createAiConfig(config: AiConfigItem): Promise { - await api.saveAiConfigItem(config); - aiConfigs.value.push(config); + const normalized = normalizeAiConfigItem(config); + await api.saveAiConfigItem(normalized); + aiConfigs.value.push(normalized); if (aiConfigs.value.length === 1) { - activeModel.value = { configId: config.id, modelId: config.model }; + activeModel.value = { configId: normalized.id, modelId: normalized.model }; } } async function updateAiConfigItem(id: string, config: Partial): Promise { const index = aiConfigs.value.findIndex((c) => c.id === id); if (index !== -1) { - const updated = { ...aiConfigs.value[index], ...config }; + const updated = normalizeAiConfigItem({ ...aiConfigs.value[index], ...config }); await api.saveAiConfigItem(updated); aiConfigs.value[index] = updated; } diff --git a/crates/dbx-core/src/ai.rs b/crates/dbx-core/src/ai.rs index fc99046472..6977322b18 100644 --- a/crates/dbx-core/src/ai.rs +++ b/crates/dbx-core/src/ai.rs @@ -814,6 +814,10 @@ fn provider_requires_api_key(provider: &AiProvider) -> bool { ) } +fn normalized_api_key(config: &AiConfig) -> &str { + config.api_key.trim() +} + fn validate_config(config: &AiConfig) -> Result<(), String> { if matches!(config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) { return Ok(()); @@ -843,11 +847,9 @@ fn validate_model_list_config(config: &AiConfig) -> Result<(), String> { pub fn maybe_bearer_headers(config: &AiConfig) -> Result { let mut headers = HeaderMap::new(); headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); - if !config.api_key.trim().is_empty() { - headers.insert( - AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {}", config.api_key)).map_err(|e| e.to_string())?, - ); + let api_key = normalized_api_key(config); + if !api_key.is_empty() { + headers.insert(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|e| e.to_string())?); } Ok(headers) } @@ -855,16 +857,17 @@ pub fn maybe_bearer_headers(config: &AiConfig) -> Result { pub fn claude_headers(config: &AiConfig) -> Result { let mut headers = HeaderMap::new(); headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); - if !config.api_key.trim().is_empty() { + let api_key = normalized_api_key(config); + if !api_key.is_empty() { match config.auth_method { AiAuthMethod::Bearer => { headers.insert( AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {}", config.api_key)).map_err(|e| e.to_string())?, + HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|e| e.to_string())?, ); } AiAuthMethod::ApiKey => { - headers.insert("x-api-key", HeaderValue::from_str(&config.api_key).map_err(|e| e.to_string())?); + headers.insert("x-api-key", HeaderValue::from_str(api_key).map_err(|e| e.to_string())?); } } } @@ -1120,7 +1123,7 @@ pub async fn call_gemini(client: &reqwest::Client, request: AiCompletionRequest) let res = client .post(resolve_endpoint(&request.config)) - .query(&[("key", request.config.api_key.as_str())]) + .query(&[("key", normalized_api_key(&request.config))]) .header(CONTENT_TYPE, "application/json") .json(&body) .send() @@ -1374,7 +1377,8 @@ async fn categorized_http_error(response: reqwest::Response, provider: &str, api body.trim().to_string() } }); - let detail = if api_key.trim().is_empty() { detail } else { detail.replace(api_key, "***") }; + let api_key = api_key.trim(); + let detail = if api_key.is_empty() { detail } else { detail.replace(api_key, "***") }; let detail = truncate_diagnostic(&detail, 500); let diagnostic = format!("HTTP {}: {detail}", status.as_u16()); format!("[{}] {provider} API error ({diagnostic})", classify_error(&diagnostic)) @@ -1488,7 +1492,7 @@ pub async fn test_connection_core(config: &AiConfig) -> Result