From 1a42f0f88e26c8dd0e14815b00112a210dc5bd85 Mon Sep 17 00:00:00 2001 From: Bill Date: Sat, 25 Oct 2025 23:12:40 -0400 Subject: [PATCH] feat: improve API key encryption reliability across environments - Added safe electron import with fallback for non-electron environments - Enhanced error handling when safeStorage is unavailable - Updated encryption checks to handle cases where safeStorage is null - Added warning message when API keys must be stored in plaintext - Modified isEncryptionAvailable to check for both safeStorage existence and capability --- src/utils/encryption-utils.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/utils/encryption-utils.ts b/src/utils/encryption-utils.ts index 646123c..de3adad 100644 --- a/src/utils/encryption-utils.ts +++ b/src/utils/encryption-utils.ts @@ -1,4 +1,11 @@ -import { safeStorage } from 'electron'; +// Safely import safeStorage - may not be available in all environments +let safeStorage: any = null; +try { + const electron = require('electron'); + safeStorage = electron.safeStorage; +} catch (error) { + console.warn('Electron safeStorage not available, API keys will be stored in plaintext'); +} /** * Encrypts an API key using Electron's safeStorage API @@ -11,8 +18,8 @@ export function encryptApiKey(apiKey: string): string { return ''; } - // Check if encryption is available - if (!safeStorage.isEncryptionAvailable()) { + // Check if safeStorage is available and encryption is enabled + if (!safeStorage || !safeStorage.isEncryptionAvailable()) { console.warn('Encryption not available, storing API key in plaintext'); return apiKey; } @@ -42,6 +49,12 @@ export function decryptApiKey(stored: string): string { return stored; } + // If safeStorage is not available, we can't decrypt + if (!safeStorage) { + console.error('Cannot decrypt API key: safeStorage not available'); + throw new Error('Failed to decrypt API key. You may need to regenerate it.'); + } + try { const encryptedData = stored.substring(10); // Remove "encrypted:" prefix const buffer = Buffer.from(encryptedData, 'base64'); @@ -57,5 +70,5 @@ export function decryptApiKey(stored: string): string { * @returns true if safeStorage encryption is available */ export function isEncryptionAvailable(): boolean { - return safeStorage.isEncryptionAvailable(); + return safeStorage !== null && safeStorage.isEncryptionAvailable(); }