Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat(security): encrypt API keys at rest via safeStorage (#629)

Gabriel Stein321224a455cd
diff --git a/main.js b/main.js
index 7bf728749..8b3d620ae 100644
--- a/main.js
+++ b/main.js
@@ -629,6 +629,7 @@ async function startApp() {
// Phase 1: Core managers + IPC handlers before windows
initializeCoreManagers();
+ await environmentManager.init();
registerSidecars();
startAuthBridgeServer();
diff --git a/preload.js b/preload.js
index eac91159c..22c14a4a2 100644
--- a/preload.js
+++ b/preload.js
@@ -184,7 +184,6 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Environment variables
getOpenAIKey: () => ipcRenderer.invoke("get-openai-key"),
saveOpenAIKey: (key) => ipcRenderer.invoke("save-openai-key", key),
- createProductionEnvFile: (key) => ipcRenderer.invoke("create-production-env-file", key),
// Clipboard functions
checkAccessibilityPermission: (silent) =>
@@ -361,8 +360,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Custom endpoint API keys
getCustomTranscriptionKey: () => ipcRenderer.invoke("get-custom-transcription-key"),
saveCustomTranscriptionKey: (key) => ipcRenderer.invoke("save-custom-transcription-key", key),
- getCustomReasoningKey: () => ipcRenderer.invoke("get-custom-reasoning-key"),
- saveCustomReasoningKey: (key) => ipcRenderer.invoke("save-custom-reasoning-key", key),
+ getCleanupCustomKey: () => ipcRenderer.invoke("get-cleanup-custom-key"),
+ saveCleanupCustomKey: (key) => ipcRenderer.invoke("save-cleanup-custom-key", key),
// Enterprise provider key management
getBedrockRegion: () => ipcRenderer.invoke("get-bedrock-region"),
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index b68ad866a..bc1a4dd58 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -851,7 +851,6 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
provider,
hasKey: !!apiKey,
keyLength: apiKey?.length || 0,
- keyPreview: apiKey ? `${apiKey.substring(0, 8)}...` : "(none)",
},
"transcription"
);
@@ -1533,7 +1532,6 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
provider,
isCustomEndpoint,
hasApiKey: !!apiKey,
- apiKeyPreview: apiKey ? `${apiKey.substring(0, 8)}...` : "(none)",
},
"transcription"
);
diff --git a/src/helpers/environment.js b/src/helpers/environment.js
index 72bb1abc5..dc49c009e 100644
--- a/src/helpers/environment.js
+++ b/src/helpers/environment.js
@@ -1,10 +1,11 @@
const path = require("path");
const fs = require("fs");
const fsPromises = require("fs/promises");
-const { app } = require("electron");
+const { app, safeStorage } = require("electron");
+const debugLogger = require("./debugLogger");
const { normalizeUiLanguage } = require("./i18nMain");
-const PERSISTED_KEYS = [
+const SECRET_KEYS = [
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"GEMINI_API_KEY",
@@ -14,6 +15,17 @@ const PERSISTED_KEYS = [
"DEEPGRAM_API_KEY",
"CUSTOM_TRANSCRIPTION_API_KEY",
"CUSTOM_CLEANUP_API_KEY",
+ "BEDROCK_ACCESS_KEY_ID",
+ "BEDROCK_SECRET_ACCESS_KEY",
+ "BEDROCK_SESSION_TOKEN",
+ "AZURE_OPENAI_API_KEY",
+ "VERTEX_API_KEY",
+];
+
+const SECRET_KEY_SET = new Set(SECRET_KEYS);
+
+const PERSISTED_KEYS = [
+ ...SECRET_KEYS,
"LOCAL_TRANSCRIPTION_PROVIDER",
"PARAKEET_MODEL",
"LOCAL_WHISPER_MODEL",
@@ -36,16 +48,11 @@ const PERSISTED_KEYS = [
"INTELLIGENCE_GPU_INDEX",
"BEDROCK_REGION",
"BEDROCK_PROFILE",
- "BEDROCK_ACCESS_KEY_ID",
- "BEDROCK_SECRET_ACCESS_KEY",
- "BEDROCK_SESSION_TOKEN",
"AZURE_OPENAI_ENDPOINT",
- "AZURE_OPENAI_API_KEY",
"AZURE_OPENAI_DEPLOYMENT",
"AZURE_OPENAI_API_VERSION",
"VERTEX_PROJECT",
"VERTEX_LOCATION",
- "VERTEX_API_KEY",
];
class EnvironmentManager {
@@ -79,12 +86,174 @@ class EnvironmentManager {
}
}
+ // safeStorage requires app.whenReady(), so init runs after construction.
+ async init() {
+ if (!this._encryptionAvailable()) {
+ debugLogger.warn(
+ "safeStorage unavailable — secrets remain in plaintext .env",
+ { platform: process.platform },
+ "environment"
+ );
+ return;
+ }
+
+ if (!fs.existsSync(this._getMigrationSentinelPath())) {
+ await this._migrateToSecureStorage();
+ }
+ await this._loadAllSecrets();
+ }
+
+ _getMigrationSentinelPath() {
+ return path.join(this._getSecureKeysDir(), ".migrated");
+ }
+
+ _encryptionAvailable() {
+ try {
+ return safeStorage.isEncryptionAvailable();
+ } catch {
+ return false;
+ }
+ }
+
+ _getSecureKeysDir() {
+ return path.join(app.getPath("userData"), "secure-keys");
+ }
+
+ _getSecretFilePath(envVarName) {
+ return path.join(this._getSecureKeysDir(), `${envVarName}.enc`);
+ }
+
+ async _loadAllSecrets() {
+ await Promise.all(SECRET_KEYS.map((name) => this._loadSecretKey(name)));
+ }
+
+ async _loadSecretKey(envVarName) {
+ const filePath = this._getSecretFilePath(envVarName);
+ try {
+ const buffer = await fsPromises.readFile(filePath);
+ process.env[envVarName] = safeStorage.decryptString(buffer);
+ } catch (error) {
+ if (error.code === "ENOENT") return;
+ debugLogger.error(
+ "Failed to decrypt secret — user must re-enter",
+ { key: envVarName, error: error.message },
+ "environment"
+ );
+ }
+ }
+
+ async _saveSecretKey(envVarName, value) {
+ if (!value) {
+ await this._deleteSecretKey(envVarName);
+ return;
+ }
+
+ process.env[envVarName] = value;
+
+ const dir = this._getSecureKeysDir();
+ await fsPromises.mkdir(dir, { recursive: true });
+
+ const filePath = this._getSecretFilePath(envVarName);
+ const tmpPath = `${filePath}.tmp`;
+ const encrypted = safeStorage.encryptString(value);
+
+ await fsPromises.writeFile(tmpPath, encrypted);
+ await fsPromises.rename(tmpPath, filePath);
+ }
+
+ async _deleteSecretKey(envVarName) {
+ delete process.env[envVarName];
+ try {
+ await fsPromises.unlink(this._getSecretFilePath(envVarName));
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ }
+
+ async _migrateToSecureStorage() {
+ const dir = this._getSecureKeysDir();
+ await fsPromises.mkdir(dir, { recursive: true });
+
+ // Adopt renamed key so the value survives migration. Old releases stored
+ // it under CUSTOM_REASONING_API_KEY; new code only encrypts CUSTOM_CLEANUP_API_KEY.
+ if (process.env.CUSTOM_REASONING_API_KEY && !process.env.CUSTOM_CLEANUP_API_KEY) {
+ process.env.CUSTOM_CLEANUP_API_KEY = process.env.CUSTOM_REASONING_API_KEY;
+ }
+ delete process.env.CUSTOM_REASONING_API_KEY;
+
+ const migrated = [];
+ try {
+ for (const name of SECRET_KEYS) {
+ const value = process.env[name];
+ if (!value) continue;
+ await this._saveSecretKey(name, value);
+ // Round-trip verify before stripping plaintext .env.
+ const buffer = await fsPromises.readFile(this._getSecretFilePath(name));
+ if (safeStorage.decryptString(buffer) !== value) {
+ throw new Error(`round-trip verification failed for ${name}`);
+ }
+ migrated.push(name);
+ }
+ } catch (error) {
+ debugLogger.error(
+ "Secret migration aborted — plaintext .env preserved",
+ { error: error.message, migrated },
+ "environment"
+ );
+ return;
+ }
+
+ // Sentinel before .env rewrite: if the rewrite fails, next launch loads
+ // stale plaintext but encrypted values overwrite it on _loadAllSecrets,
+ // and the next saveAllKeysToEnvFile cleans the .env. Reverse order risks
+ // stripping plaintext for secrets that haven't been encrypted yet.
+ await fsPromises.writeFile(this._getMigrationSentinelPath(), "");
+ const envPath = path.join(app.getPath("userData"), ".env");
+ if (fs.existsSync(envPath)) await this._writeEnvFileAtomic(envPath);
+ debugLogger.info(
+ "Migrated secrets to encrypted storage",
+ { count: migrated.length },
+ "environment"
+ );
+ }
+
+ async _writeEnvFileAtomic(envPath) {
+ // Only strip plaintext secrets once migration has fully completed —
+ // otherwise a partial-migration recovery can lose unencrypted secrets.
+ const stripSecrets =
+ this._encryptionAvailable() && fs.existsSync(this._getMigrationSentinelPath());
+ let envContent = "# OpenWhispr Environment Variables\n";
+ for (const key of PERSISTED_KEYS) {
+ if (stripSecrets && SECRET_KEY_SET.has(key)) continue;
+ if (process.env[key]) {
+ envContent += `${key}=${process.env[key]}\n`;
+ }
+ }
+ const tmpPath = `${envPath}.tmp`;
+ await fsPromises.writeFile(tmpPath, envContent, "utf8");
+ await fsPromises.rename(tmpPath, envPath);
+ }
+
_getKey(envVarName) {
return process.env[envVarName] || "";
}
_saveKey(envVarName, key) {
- process.env[envVarName] = key;
+ if (SECRET_KEY_SET.has(envVarName) && this._encryptionAvailable()) {
+ // _saveSecretKey updates process.env before its first await, so
+ // in-process reads see the new value while the encrypted write lands.
+ this._saveSecretKey(envVarName, key).catch((error) => {
+ debugLogger.error(
+ "Failed to persist encrypted secret",
+ { key: envVarName, error: error.message },
+ "environment"
+ );
+ });
+ } else if (key) {
+ process.env[envVarName] = key;
+ } else {
+ delete process.env[envVarName];
+ }
return { success: true };
}
@@ -152,12 +321,12 @@ class EnvironmentManager {
return this._saveKey("CUSTOM_TRANSCRIPTION_API_KEY", key);
}
- getCustomReasoningKey() {
+ getCleanupCustomKey() {
// TODO: drop CUSTOM_REASONING_API_KEY fallback after 2 releases.
return this._getKey("CUSTOM_CLEANUP_API_KEY") || this._getKey("CUSTOM_REASONING_API_KEY");
}
- saveCustomReasoningKey(key) {
+ saveCleanupCustomKey(key) {
delete process.env.CUSTOM_REASONING_API_KEY;
return this._saveKey("CUSTOM_CLEANUP_API_KEY", key);
}
@@ -327,34 +496,10 @@ class EnvironmentManager {
return { ...result, language: normalized };
}
- async createProductionEnvFile(apiKey) {
- const envPath = path.join(app.getPath("userData"), ".env");
-
- const envContent = `# OpenWhispr Environment Variables
-# This file was created automatically for production use
-OPENAI_API_KEY=${apiKey}
-`;
-
- await fsPromises.writeFile(envPath, envContent, "utf8");
- require("dotenv").config({ path: envPath });
-
- return { success: true, path: envPath };
- }
-
async saveAllKeysToEnvFile() {
const envPath = path.join(app.getPath("userData"), ".env");
-
- let envContent = "# OpenWhispr Environment Variables\n";
-
- for (const key of PERSISTED_KEYS) {
- if (process.env[key]) {
- envContent += `${key}=${process.env[key]}\n`;
- }
- }
-
- await fsPromises.writeFile(envPath, envContent, "utf8");
+ await this._writeEnvFileAtomic(envPath);
require("dotenv").config({ path: envPath });
-
return { success: true, path: envPath };
}
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 0168eb2fc..33aee5ffb 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -708,10 +708,6 @@ class IPCHandlers {
return this.environmentManager.saveOpenAIKey(key);
});
- ipcMain.handle("create-production-env-file", async (event, apiKey) => {
- return this.environmentManager.createProductionEnvFile(apiKey);
- });
-
ipcMain.handle("db-save-transcription", async (event, text, rawText, options) => {
const result = this.databaseManager.saveTranscription(text, rawText, options);
if (result?.success && result?.transcription) {
@@ -2474,12 +2470,12 @@ class IPCHandlers {
return this.environmentManager.saveCustomTranscriptionKey(key);
});
- ipcMain.handle("get-custom-reasoning-key", async () => {
- return this.environmentManager.getCustomReasoningKey();
+ ipcMain.handle("get-cleanup-custom-key", async () => {
+ return this.environmentManager.getCleanupCustomKey();
});
- ipcMain.handle("save-custom-reasoning-key", async (event, key) => {
- return this.environmentManager.saveCustomReasoningKey(key);
+ ipcMain.handle("save-cleanup-custom-key", async (event, key) => {
+ return this.environmentManager.saveCleanupCustomKey(key);
});
// Enterprise provider key handlers
diff --git a/src/helpers/mediaPlayer.js b/src/helpers/mediaPlayer.js
index 7f720e1f1..1743b57e7 100644
--- a/src/helpers/mediaPlayer.js
+++ b/src/helpers/mediaPlayer.js
@@ -511,11 +511,15 @@ try {
}
const stderr = (result.stderr?.toString() || "").trim();
- debugLogger.debug("GSMTC PowerShell failed, falling back to media key", {
- status: result.status,
- signal: result.signal,
- stderr: stderr ? stderr.slice(0, 200) : undefined,
- }, "media");
+ debugLogger.debug(
+ "GSMTC PowerShell failed, falling back to media key",
+ {
+ status: result.status,
+ signal: result.signal,
+ stderr: stderr ? stderr.slice(0, 200) : undefined,
+ },
+ "media"
+ );
return this._pauseWindowsFallback();
}
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 8312e8589..698d65566 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -66,7 +66,7 @@ class ReasoningService extends BaseReasoningService {
if (provider === "custom") {
let customKey = "";
try {
- customKey = (await window.electronAPI?.getCustomReasoningKey?.()) || "";
+ customKey = (await window.electronAPI?.getCleanupCustomKey?.()) || "";
} catch (err) {
logger.logReasoning("CUSTOM_KEY_IPC_FALLBACK", { error: (err as Error)?.message });
}
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 072bc7a1e..06f1cc0d7 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -533,6 +533,53 @@ function debouncedPersistToEnv() {
}, 1000);
}
+const SECRET_IPC_SAVERS = {
+ openai: "saveOpenAIKey",
+ anthropic: "saveAnthropicKey",
+ gemini: "saveGeminiKey",
+ groq: "saveGroqKey",
+ mistral: "saveMistralKey",
+ customTranscription: "saveCustomTranscriptionKey",
+ cleanupCustom: "saveCleanupCustomKey",
+ bedrockAccessKeyId: "saveBedrockAccessKeyId",
+ bedrockSecretAccessKey: "saveBedrockSecretAccessKey",
+ bedrockSessionToken: "saveBedrockSessionToken",
+ azureApiKey: "saveAzureApiKey",
+ vertexApiKey: "saveVertexApiKey",
+} as const;
+
+type SecretProvider = keyof typeof SECRET_IPC_SAVERS;
+
+const secretSaveTimers: Partial<Record<SecretProvider, ReturnType<typeof setTimeout>>> = {};
+function debouncedSaveSecret(provider: SecretProvider, key: string) {
+ if (!isBrowser) return;
+ const timer = secretSaveTimers[provider];
+ if (timer) clearTimeout(timer);
+ secretSaveTimers[provider] = setTimeout(() => {
+ const api = window.electronAPI;
+ const save = api?.[SECRET_IPC_SAVERS[provider]] as
+ | ((k: string) => Promise<unknown>)
+ | undefined;
+ void save?.(key);
+ }, 250);
+}
+
+const STALE_SECRET_LOCALSTORAGE_KEYS = [
+ "openaiApiKey",
+ "anthropicApiKey",
+ "geminiApiKey",
+ "groqApiKey",
+ "mistralApiKey",
+ "customTranscriptionApiKey",
+ "customReasoningApiKey",
+ "cleanupCustomApiKey",
+ "bedrockAccessKeyId",
+ "bedrockSecretAccessKey",
+ "bedrockSessionToken",
+ "azureApiKey",
+ "vertexApiKey",
+] as const;
+
function invalidateApiKeyCaches(
provider?: "openai" | "anthropic" | "gemini" | "groq" | "mistral" | "custom"
) {
@@ -570,10 +617,9 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
"cloudTranscriptionBaseUrl",
API_ENDPOINTS.TRANSCRIPTION_BASE
),
- cloudTranscriptionMode: readString(
- "cloudTranscriptionMode",
- hasStoredByokKey() ? "byok" : "openwhispr"
- ),
+ // Secrets aren't hydrated yet at construction; the BYOK default is set
+ // post-hydration in initializeSettings.
+ cloudTranscriptionMode: readString("cloudTranscriptionMode", "openwhispr"),
cleanupCloudMode: readString("cleanupCloudMode", "openwhispr"),
cleanupCloudBaseUrl: readString("cleanupCloudBaseUrl", API_ENDPOINTS.OPENAI_BASE),
customDictionary: readStringArray("customDictionary", []),
@@ -584,29 +630,30 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
cleanupModel: readString("cleanupModel", ""),
cleanupProvider: readString("cleanupProvider", "openai"),
- openaiApiKey: readString("openaiApiKey", ""),
- anthropicApiKey: readString("anthropicApiKey", ""),
- geminiApiKey: readString("geminiApiKey", ""),
- groqApiKey: readString("groqApiKey", ""),
- mistralApiKey: readString("mistralApiKey", ""),
- customTranscriptionApiKey: readString("customTranscriptionApiKey", ""),
- cleanupCustomApiKey: readString("cleanupCustomApiKey", ""),
+ // Secrets hydrate from main process in initializeSettings, never from localStorage.
+ openaiApiKey: "",
+ anthropicApiKey: "",
+ geminiApiKey: "",
+ groqApiKey: "",
+ mistralApiKey: "",
+ customTranscriptionApiKey: "",
+ cleanupCustomApiKey: "",
// Enterprise providers
bedrockAuthMode: readString("bedrockAuthMode", "sso"),
bedrockRegion: readString("bedrockRegion", "us-east-1"),
bedrockProfile: readString("bedrockProfile", ""),
- bedrockAccessKeyId: readString("bedrockAccessKeyId", ""),
- bedrockSecretAccessKey: readString("bedrockSecretAccessKey", ""),
- bedrockSessionToken: readString("bedrockSessionToken", ""),
+ bedrockAccessKeyId: "",
+ bedrockSecretAccessKey: "",
+ bedrockSessionToken: "",
azureEndpoint: readString("azureEndpoint", ""),
- azureApiKey: readString("azureApiKey", ""),
+ azureApiKey: "",
azureDeploymentName: readString("azureDeploymentName", ""),
azureApiVersion: readString("azureApiVersion", "2024-10-21"),
vertexAuthMode: readString("vertexAuthMode", "adc"),
vertexProject: readString("vertexProject", ""),
vertexLocation: readString("vertexLocation", "us-central1"),
- vertexApiKey: readString("vertexApiKey", ""),
+ vertexApiKey: "",
dictationKey: readString("dictationKey", ""),
meetingKey: readString("meetingKey", ""),
@@ -875,45 +922,38 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
},
setOpenaiApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("openaiApiKey", key);
set({ openaiApiKey: key });
- window.electronAPI?.saveOpenAIKey?.(key);
+ debouncedSaveSecret("openai", key);
invalidateApiKeyCaches("openai");
},
setAnthropicApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("anthropicApiKey", key);
set({ anthropicApiKey: key });
- window.electronAPI?.saveAnthropicKey?.(key);
+ debouncedSaveSecret("anthropic", key);
invalidateApiKeyCaches("anthropic");
},
setGeminiApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("geminiApiKey", key);
set({ geminiApiKey: key });
- window.electronAPI?.saveGeminiKey?.(key);
+ debouncedSaveSecret("gemini", key);
invalidateApiKeyCaches("gemini");
},
setGroqApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("groqApiKey", key);
set({ groqApiKey: key });
- window.electronAPI?.saveGroqKey?.(key);
+ debouncedSaveSecret("groq", key);
invalidateApiKeyCaches("groq");
},
setMistralApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("mistralApiKey", key);
set({ mistralApiKey: key });
- window.electronAPI?.saveMistralKey?.(key);
+ debouncedSaveSecret("mistral", key);
invalidateApiKeyCaches("mistral");
},
setCustomTranscriptionApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("customTranscriptionApiKey", key);
set({ customTranscriptionApiKey: key });
- window.electronAPI?.saveCustomTranscriptionKey?.(key);
+ debouncedSaveSecret("customTranscription", key);
invalidateApiKeyCaches("custom");
},
setCleanupCustomApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("cleanupCustomApiKey", key);
set({ cleanupCustomApiKey: key });
- window.electronAPI?.saveCustomReasoningKey?.(key);
+ debouncedSaveSecret("cleanupCustom", key);
invalidateApiKeyCaches("custom");
},
@@ -935,21 +975,18 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
debouncedPersistToEnv();
},
setBedrockAccessKeyId: (key: string) => {
- if (isBrowser) localStorage.setItem("bedrockAccessKeyId", key);
set({ bedrockAccessKeyId: key });
- window.electronAPI?.saveBedrockAccessKeyId?.(key);
+ debouncedSaveSecret("bedrockAccessKeyId", key);
debouncedPersistToEnv();
},
setBedrockSecretAccessKey: (key: string) => {
- if (isBrowser) localStorage.setItem("bedrockSecretAccessKey", key);
set({ bedrockSecretAccessKey: key });
- window.electronAPI?.saveBedrockSecretAccessKey?.(key);
+ debouncedSaveSecret("bedrockSecretAccessKey", key);
debouncedPersistToEnv();
},
setBedrockSessionToken: (key: string) => {
- if (isBrowser) localStorage.setItem("bedrockSessionToken", key);
set({ bedrockSessionToken: key });
- window.electronAPI?.saveBedrockSessionToken?.(key);
+ debouncedSaveSecret("bedrockSessionToken", key);
debouncedPersistToEnv();
},
setAzureEndpoint: (value: string) => {
@@ -959,9 +996,8 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
debouncedPersistToEnv();
},
setAzureApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("azureApiKey", key);
set({ azureApiKey: key });
- window.electronAPI?.saveAzureApiKey?.(key);
+ debouncedSaveSecret("azureApiKey", key);
debouncedPersistToEnv();
},
setAzureDeploymentName: (value: string) => {
@@ -993,9 +1029,8 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
debouncedPersistToEnv();
},
setVertexApiKey: (key: string) => {
- if (isBrowser) localStorage.setItem("vertexApiKey", key);
set({ vertexApiKey: key });
- window.electronAPI?.saveVertexApiKey?.(key);
+ debouncedSaveSecret("vertexApiKey", key);
debouncedPersistToEnv();
},
@@ -1377,40 +1412,62 @@ export async function initializeSettings(): Promise<void> {
const state = useSettingsStore.getState();
- // Sync API keys from main process (if localStorage is empty, read from .env via IPC)
if (window.electronAPI) {
try {
- if (!state.openaiApiKey) {
- const envKey = await window.electronAPI.getOpenAIKey?.();
- if (envKey) createStringSetter("openaiApiKey")(envKey);
- }
- if (!state.anthropicApiKey) {
- const envKey = await window.electronAPI.getAnthropicKey?.();
- if (envKey) createStringSetter("anthropicApiKey")(envKey);
- }
- if (!state.geminiApiKey) {
- const envKey = await window.electronAPI.getGeminiKey?.();
- if (envKey) createStringSetter("geminiApiKey")(envKey);
- }
- if (!state.groqApiKey) {
- const envKey = await window.electronAPI.getGroqKey?.();
- if (envKey) createStringSetter("groqApiKey")(envKey);
- }
- if (!state.mistralApiKey) {
- const envKey = await window.electronAPI.getMistralKey?.();
- if (envKey) createStringSetter("mistralApiKey")(envKey);
- }
- if (!state.customTranscriptionApiKey) {
- const envKey = await window.electronAPI.getCustomTranscriptionKey?.();
- if (envKey) createStringSetter("customTranscriptionApiKey")(envKey);
+ const [
+ openai,
+ anthropic,
+ gemini,
+ groq,
+ mistral,
+ customTx,
+ customRx,
+ bedrockAccessKeyId,
+ bedrockSecretAccessKey,
+ bedrockSessionToken,
+ azureApiKey,
+ vertexApiKey,
+ ] = await Promise.all([
+ window.electronAPI.getOpenAIKey?.(),
+ window.electronAPI.getAnthropicKey?.(),
+ window.electronAPI.getGeminiKey?.(),
+ window.electronAPI.getGroqKey?.(),
+ window.electronAPI.getMistralKey?.(),
+ window.electronAPI.getCustomTranscriptionKey?.(),
+ window.electronAPI.getCleanupCustomKey?.(),
+ window.electronAPI.getBedrockAccessKeyId?.(),
+ window.electronAPI.getBedrockSecretAccessKey?.(),
+ window.electronAPI.getBedrockSessionToken?.(),
+ window.electronAPI.getAzureApiKey?.(),
+ window.electronAPI.getVertexApiKey?.(),
+ ]);
+
+ useSettingsStore.setState({
+ openaiApiKey: openai || "",
+ anthropicApiKey: anthropic || "",
+ geminiApiKey: gemini || "",
+ groqApiKey: groq || "",
+ mistralApiKey: mistral || "",
+ customTranscriptionApiKey: customTx || "",
+ cleanupCustomApiKey: customRx || "",
+ bedrockAccessKeyId: bedrockAccessKeyId || "",
+ bedrockSecretAccessKey: bedrockSecretAccessKey || "",
+ bedrockSessionToken: bedrockSessionToken || "",
+ azureApiKey: azureApiKey || "",
+ vertexApiKey: vertexApiKey || "",
+ });
+
+ // hasStoredByokKey reads from Zustand, so this default must run after hydration.
+ if (!localStorage.getItem("cloudTranscriptionMode") && hasStoredByokKey()) {
+ useSettingsStore.setState({ cloudTranscriptionMode: "byok" });
}
- if (!state.cleanupCustomApiKey) {
- const envKey = await window.electronAPI.getCustomReasoningKey?.();
- if (envKey) createStringSetter("cleanupCustomApiKey")(envKey);
+
+ for (const key of STALE_SECRET_LOCALSTORAGE_KEYS) {
+ localStorage.removeItem(key);
}
} catch (err) {
logger.warn(
- "Failed to sync API keys on startup",
+ "Failed to hydrate secrets from main process",
{ error: (err as Error).message },
"settings"
);
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 66540b2c5..8ab1a836d 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -567,7 +567,6 @@ declare global {
// API key management
getOpenAIKey: () => Promise<string>;
saveOpenAIKey: (key: string) => Promise<{ success: boolean }>;
- createProductionEnvFile: (key: string) => Promise<void>;
getAnthropicKey: () => Promise<string | null>;
saveAnthropicKey: (key: string) => Promise<void>;
getUiLanguage: () => Promise<string>;
@@ -858,8 +857,8 @@ declare global {
// Custom endpoint API keys
getCustomTranscriptionKey?: () => Promise<string | null>;
saveCustomTranscriptionKey?: (key: string) => Promise<void>;
- getCustomReasoningKey?: () => Promise<string | null>;
- saveCustomReasoningKey?: (key: string) => Promise<void>;
+ getCleanupCustomKey?: () => Promise<string | null>;
+ saveCleanupCustomKey?: (key: string) => Promise<void>;
// Enterprise provider key persistence
getBedrockRegion?: () => Promise<string | null>;
diff --git a/src/utils/byokDetection.ts b/src/utils/byokDetection.ts
index a7b989d51..27d73f8ba 100644
--- a/src/utils/byokDetection.ts
+++ b/src/utils/byokDetection.ts
@@ -1,7 +1,6 @@
-export const hasStoredByokKey = () =>
- !!(
- localStorage.getItem("openaiApiKey") ||
- localStorage.getItem("groqApiKey") ||
- localStorage.getItem("mistralApiKey") ||
- localStorage.getItem("customTranscriptionApiKey")
- );
+import { useSettingsStore } from "../stores/settingsStore";
+
+export const hasStoredByokKey = () => {
+ const s = useSettingsStore.getState();
+ return !!(s.openaiApiKey || s.groqApiKey || s.mistralApiKey || s.customTranscriptionApiKey);
+};