diff --git a/src/features/ai-tutor/index.js b/src/features/ai-tutor/index.js index 47696d0..3348f42 100644 --- a/src/features/ai-tutor/index.js +++ b/src/features/ai-tutor/index.js @@ -17,6 +17,10 @@ export { downloadCourseXml, downloadCourseContextFile, } from './models/courseXmlSerializer.js'; +export { + credentialsRepository, + CredentialsRepository, +} from './models/credentialsRepository.js'; export { MAX_API_KEYS, AI_PROVIDERS, diff --git a/src/features/ai-tutor/models/apiKeyStorage.js b/src/features/ai-tutor/models/apiKeyStorage.js index b0af594..68dc4dd 100644 --- a/src/features/ai-tutor/models/apiKeyStorage.js +++ b/src/features/ai-tutor/models/apiKeyStorage.js @@ -1,283 +1,79 @@ /** - * API Key Storage & Multi-Provider Manager - * Supports up to 5 API keys for OpenAI (ChatGPT), Anthropic (Claude), and Google Gemini. - * Keys are stored 100% locally in browser localStorage (jct_ai_api_keys_v1). - * Never transmitted to any 3rd-party backend or telemetry server. + * API Key Storage & Multi-Provider Adapter Layer + * + * Provides backwards-compatible adapter interface routing all reads, writes, + * and live verifications through the unified `credentialsRepository`. + * + * Supports OpenAI, Anthropic, Google Gemini, and Groq. */ -import { STORAGE_KEYS, LEGACY_STORAGE_KEYS } from '../../../services/storage/keys.js'; +import { + credentialsRepository, + AI_PROVIDERS, + MAX_CREDENTIAL_KEYS, + CREDENTIALS_STORAGE_KEY, + LEGACY_OPENAI_KEY, + getTodayDateKey, + maskApiKey, + sanitizeErrorMessage, +} from './credentialsRepository.js'; -export const MAX_API_KEYS = 5; -export const API_KEYS_STORAGE_KEY = STORAGE_KEYS.AI_API_KEYS; -export const LEGACY_OPENAI_STORAGE_KEY = LEGACY_STORAGE_KEYS.OPENAI_API_KEY; +export const MAX_API_KEYS = MAX_CREDENTIAL_KEYS; +export const API_KEYS_STORAGE_KEY = CREDENTIALS_STORAGE_KEY; +export const LEGACY_OPENAI_STORAGE_KEY = LEGACY_OPENAI_KEY; -export const AI_PROVIDERS = { - openai: { - id: 'openai', - name: 'OpenAI (ChatGPT)', - shortName: 'OpenAI', - badgeClass: 'ai-prov-badge--openai', - websiteUrl: 'https://platform.openai.com/api-keys', - keyPlaceholder: 'sk-proj-... or sk-...', - keyPrefixPattern: /^sk-[A-Za-z0-9_-]{20,}$/, - description: 'Powers GPT-4o, GPT-4o-mini, and ChatGPT reasoning models.', - helpSteps: [ - 'Sign in or sign up at https://platform.openai.com/', - 'Go to the "API Keys" section in the left sidebar navigation.', - 'Click "+ Create new secret key", name it (e.g., "Course Tracker"), and copy it.', - 'Paste your secret key into the input field above.', - ], - }, - anthropic: { - id: 'anthropic', - name: 'Anthropic (Claude)', - shortName: 'Claude', - badgeClass: 'ai-prov-badge--anthropic', - websiteUrl: 'https://console.anthropic.com/settings/keys', - keyPlaceholder: 'sk-ant-api03-...', - keyPrefixPattern: /^sk-ant-[A-Za-z0-9_-]{20,}$/, - description: 'Powers Claude 3.5 Sonnet, Claude 3 Opus, and Claude 3.5 Haiku.', - helpSteps: [ - 'Sign in to your Anthropic Console at https://console.anthropic.com/', - 'Navigate to "Settings" -> "API Keys".', - 'Click "Create Key", label it (e.g., "Java Course Tutor"), and copy the key string.', - 'Paste the key (starts with "sk-ant-...") into the field above.', - ], - }, - gemini: { - id: 'gemini', - name: 'Google Gemini', - shortName: 'Gemini', - badgeClass: 'ai-prov-badge--gemini', - websiteUrl: 'https://aistudio.google.com/app/apikey', - keyPlaceholder: 'AIzaSy...', - keyPrefixPattern: /^AIzaSy[A-Za-z0-9_-]{30,}$/, - description: 'Powers Gemini 1.5 Pro and Gemini 1.5 Flash with large context windows.', - helpSteps: [ - 'Visit Google AI Studio at https://aistudio.google.com/app/apikey', - 'Sign in with your Google Account and click "Create API key".', - 'Select a Google Cloud project or create a default one (free tier available).', - 'Copy the generated key (starts with "AIzaSy...") and paste it above.', - ], - }, -}; +export { AI_PROVIDERS, getTodayDateKey, maskApiKey, sanitizeErrorMessage }; /** - * Returns today's date formatted as YYYY-MM-DD - */ -export function getTodayDateKey() { - const d = new Date(); - const y = d.getFullYear(); - const m = String(d.getMonth() + 1).padStart(2, '0'); - const day = String(d.getDate()).padStart(2, '0'); - return `${y}-${m}-${day}`; -} - -/** - * Mask an API key for safe display (e.g. sk-proj-••••••••abcd) - */ -export function maskApiKey(key = '') { - const str = String(key || '').trim(); - if (str.length <= 8) return '••••••••'; - const prefix = str.slice(0, 6); - const suffix = str.slice(-4); - return `${prefix}••••••••${suffix}`; -} - -/** - * Reads stored API keys from localStorage, migrating legacy keys if necessary. - * @returns {Array} List of key records (max 5) + * Reads stored API keys from the unified credentials repository. + * @returns {Array} List of key records (max 5) */ export function getStoredApiKeys() { - try { - const raw = localStorage.getItem(API_KEYS_STORAGE_KEY); - let keys = []; - if (raw) { - keys = JSON.parse(raw); - if (!Array.isArray(keys)) keys = []; - } - - // Check for legacy single OpenAI key migration - const legacyKey = localStorage.getItem(LEGACY_OPENAI_STORAGE_KEY); - if (legacyKey && legacyKey.trim()) { - const trimmed = legacyKey.trim(); - const alreadyExists = keys.some((k) => k.key === trimmed); - if (!alreadyExists && keys.length < MAX_API_KEYS) { - keys.push({ - id: 'key_legacy_openai', - provider: 'openai', - label: 'OpenAI (Imported)', - key: trimmed, - addedAt: new Date().toISOString(), - lastValidatedAt: getTodayDateKey(), - status: 'valid', - }); - localStorage.setItem(API_KEYS_STORAGE_KEY, JSON.stringify(keys)); - } - } - - return keys.slice(0, MAX_API_KEYS); - } catch (err) { - console.warn('[apiKeyStorage] Failed to read stored API keys:', err); - return []; - } -} - -/** - * Persists keys array to localStorage - */ -function persistApiKeys(keys) { - try { - localStorage.setItem(API_KEYS_STORAGE_KEY, JSON.stringify(keys.slice(0, MAX_API_KEYS))); - // Sync legacy key if an OpenAI key exists - const openaiKey = keys.find((k) => k.provider === 'openai'); - if (openaiKey) { - localStorage.setItem(LEGACY_OPENAI_STORAGE_KEY, openaiKey.key); - } else { - localStorage.removeItem(LEGACY_OPENAI_STORAGE_KEY); - } - return true; - } catch (err) { - console.error('[apiKeyStorage] Failed to persist API keys:', err); - return false; - } + return credentialsRepository.getAllKeys(); } /** - * Validates key format against provider pattern + * Validates key format against provider's pattern + * @param {string} providerId + * @param {string} key + * @returns {{ valid: boolean, error: string|null }} */ export function validateKeyFormat(providerId, key) { - const provider = AI_PROVIDERS[providerId]; - if (!provider) return { valid: false, error: 'Unknown provider' }; - const str = String(key || '').trim(); - if (!str) return { valid: false, error: 'API key cannot be empty' }; - - if (provider.keyPrefixPattern && !provider.keyPrefixPattern.test(str)) { - return { - valid: false, - error: `Invalid key format for ${provider.name}. Must start with ${provider.keyPlaceholder.split('...')[0]}`, - }; - } - - return { valid: true, error: null }; + return credentialsRepository.validateKeyFormat(providerId, key); } /** - * Add a new API key record + * Adds a new API key record to the unified store + * @param {{ provider: string, key: string, label?: string }} options + * @returns {{ success: boolean, error?: string, record?: object, keys?: Array }} */ export function addApiKey({ provider, key, label }) { - const keys = getStoredApiKeys(); - if (keys.length >= MAX_API_KEYS) { - return { success: false, error: `Maximum of ${MAX_API_KEYS} API keys reached. Delete an existing key first.` }; - } - - const trimmedKey = String(key || '').trim(); - const formatCheck = validateKeyFormat(provider, trimmedKey); - if (!formatCheck.valid) { - return { success: false, error: formatCheck.error }; - } - - // Check duplicate - if (keys.some((k) => k.key === trimmedKey)) { - return { success: false, error: 'This API key has already been added.' }; - } - - const newRecord = { - id: `key_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`, - provider, - label: (label || '').trim() || `${AI_PROVIDERS[provider]?.shortName || provider} Key`, - key: trimmedKey, - addedAt: new Date().toISOString(), - lastValidatedAt: getTodayDateKey(), - status: 'valid', - }; - - keys.push(newRecord); - persistApiKeys(keys); - return { success: true, record: newRecord, keys }; + return credentialsRepository.addKey({ provider, key, label }); } /** - * Delete an API key record by ID + * Deletes an API key record by ID + * @param {string} id + * @returns {Array} */ export function deleteApiKey(id) { - const keys = getStoredApiKeys(); - const filtered = keys.filter((k) => k.id !== id); - persistApiKeys(filtered); - return filtered; + return credentialsRepository.deleteKey(id); } /** - * Validate connection of a specific key + * Validates connection of a specific key via unified verification logic + * @param {string} providerId + * @param {string} key + * @returns {Promise<{ ok: boolean, message?: string, error?: string }>} */ export async function testApiKeyConnection(providerId, key) { - const format = validateKeyFormat(providerId, key); - if (!format.valid) { - return { ok: false, error: format.error }; - } - - try { - if (providerId === 'openai') { - const resp = await fetch('https://api.openai.com/v1/models', { - headers: { Authorization: `Bearer ${key}` }, - signal: AbortSignal.timeout(6000), - }); - if (resp.status === 200) { - return { ok: true, message: 'Connected to OpenAI API successfully' }; - } - if (resp.status === 401) { - return { ok: false, error: 'Invalid OpenAI API key (Authentication 401)' }; - } - return { ok: false, error: `OpenAI returned status ${resp.status}` }; - } - - if (providerId === 'gemini') { - const resp = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${key}`, { - signal: AbortSignal.timeout(6000), - }); - if (resp.status === 200) { - return { ok: true, message: 'Connected to Google Gemini API successfully' }; - } - if (resp.status === 400 || resp.status === 403) { - return { ok: false, error: 'Invalid Google Gemini API key' }; - } - return { ok: false, error: `Google API returned status ${resp.status}` }; - } - - if (providerId === 'anthropic') { - // Anthropic does not allow cross-origin requests directly from browser web clients - // without CORS proxy or backend; format validation is used client-side - return { ok: true, message: 'Anthropic key format is valid (ready for Claude)' }; - } - - return { ok: true, message: 'Key validated' }; - } catch (err) { - // If network error/offline, keep valid format - return { ok: true, message: `Key format valid (${err.name === 'TimeoutError' ? 'timed out' : 'offline/cors checked'})` }; - } + return credentialsRepository.verifyProviderKey(providerId, key); } /** - * Validates all stored keys if not validated today. - * Runs on app start or settings mount. + * Validates all stored keys once per calendar day + * @returns {Promise>} */ export async function validateStoredKeysDaily() { - const todayKey = getTodayDateKey(); - const keys = getStoredApiKeys(); - let updated = false; - - for (const k of keys) { - if (k.lastValidatedAt !== todayKey) { - const res = await testApiKeyConnection(k.provider, k.key); - k.status = res.ok ? 'valid' : 'invalid'; - k.lastValidatedAt = todayKey; - updated = true; - } - } - - if (updated) { - persistApiKeys(keys); - } - return keys; + return credentialsRepository.validateDaily(); } - diff --git a/src/features/ai-tutor/models/credentialsRepository.js b/src/features/ai-tutor/models/credentialsRepository.js new file mode 100644 index 0000000..2bf4589 --- /dev/null +++ b/src/features/ai-tutor/models/credentialsRepository.js @@ -0,0 +1,691 @@ +/** + * Central Credentials Repository + * + * Single source of truth for all AI provider API keys (OpenAI, Anthropic, Gemini, Groq). + * Persists credentials strictly client-side under STORAGE_KEYS.AI_API_KEYS ('jct_ai_api_keys_v1'). + * + * Security & Privacy Guarantees: + * 1. Credentials are never sent to application servers, telemetry, or third parties. + * 2. Raw keys are NEVER printed, logged, or included in error messages. + * 3. Backups NEVER include credential keys. + * 4. Dedicated credentials migration preserves legacy keys (jct_openai_api_key_v1) without deleting them. + */ + +import { + STORAGE_KEYS, + LEGACY_STORAGE_KEYS, + COURSE_KEY_PREFIXES, +} from '../../../services/storage/keys.js'; + +export const MAX_CREDENTIAL_KEYS = 5; +export const CREDENTIALS_STORAGE_KEY = STORAGE_KEYS.AI_API_KEYS; +export const LEGACY_OPENAI_KEY = STORAGE_KEYS.OPENAI_API_KEY; +export const OLD_LEGACY_OPENAI_KEY = LEGACY_STORAGE_KEYS.OPENAI_API_KEY; + +/** + * Supported AI Providers Configuration + */ +export const AI_PROVIDERS = Object.freeze({ + openai: { + id: 'openai', + name: 'OpenAI (ChatGPT)', + shortName: 'OpenAI', + badgeClass: 'ai-prov-badge--openai', + websiteUrl: 'https://platform.openai.com/api-keys', + keyPlaceholder: 'sk-proj-... or sk-...', + keyPrefixPattern: /^sk-[A-Za-z0-9_-]{20,}$/, + description: 'Powers GPT-4o, GPT-4o-mini, and ChatGPT reasoning models.', + helpSteps: [ + 'Sign in or sign up at https://platform.openai.com/', + 'Go to the "API Keys" section in the left sidebar navigation.', + 'Click "+ Create new secret key", name it (e.g., "Course Tracker"), and copy it.', + 'Paste your secret key into the input field above.', + ], + }, + anthropic: { + id: 'anthropic', + name: 'Anthropic (Claude)', + shortName: 'Claude', + badgeClass: 'ai-prov-badge--anthropic', + websiteUrl: 'https://console.anthropic.com/settings/keys', + keyPlaceholder: 'sk-ant-api03-...', + keyPrefixPattern: /^sk-ant-[A-Za-z0-9_-]{20,}$/, + description: 'Powers Claude 3.5 Sonnet, Claude 3 Opus, and Claude 3.5 Haiku.', + helpSteps: [ + 'Sign in to your Anthropic Console at https://console.anthropic.com/', + 'Navigate to "Settings" -> "API Keys".', + 'Click "Create Key", label it (e.g., "Java Course Tutor"), and copy the key string.', + 'Paste the key (starts with "sk-ant-...") into the field above.', + ], + }, + gemini: { + id: 'gemini', + name: 'Google Gemini', + shortName: 'Gemini', + badgeClass: 'ai-prov-badge--gemini', + websiteUrl: 'https://aistudio.google.com/app/apikey', + keyPlaceholder: 'AIzaSy...', + keyPrefixPattern: /^AIzaSy[A-Za-z0-9_-]{30,}$/, + description: 'Powers Gemini 1.5 Pro and Gemini 1.5 Flash with large context windows.', + helpSteps: [ + 'Visit Google AI Studio at https://aistudio.google.com/app/apikey', + 'Sign in with your Google Account and click "Create API key".', + 'Select a Google Cloud project or create a default one (free tier available).', + 'Copy the generated key (starts with "AIzaSy...") and paste it above.', + ], + }, + groq: { + id: 'groq', + name: 'Groq', + shortName: 'Groq', + badgeClass: 'ai-prov-badge--groq', + websiteUrl: 'https://console.groq.com/keys', + keyPlaceholder: 'gsk_...', + keyPrefixPattern: /^gsk_[A-Za-z0-9_-]{20,}$/, + description: 'Powers ultra-fast inference with Llama 3, Mixtral, and open LLM architectures.', + helpSteps: [ + 'Sign in or register at https://console.groq.com/', + 'Go to "API Keys" in the left sidebar console.', + 'Click "Create API Key", provide a name, and copy the secret key.', + 'Paste your key (starts with "gsk_...") into the field above.', + ], + }, +}); + +/** + * Returns today's date formatted as YYYY-MM-DD + * @returns {string} + */ +export function getTodayDateKey() { + const d = new Date(); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +/** + * Masks an API key for safe presentation (e.g. sk-proj••••••••abcd) + * @param {string} key + * @returns {string} + */ +export function maskApiKey(key = '') { + const str = String(key || '').trim(); + if (str.length <= 8) return '••••••••'; + const prefix = str.slice(0, 6); + const suffix = str.slice(-4); + return `${prefix}••••••••${suffix}`; +} + +/** + * Redacts any secret keys from an error message to prevent accidental credential leakage in logs or UI. + * @param {string|Error} error + * @param {string} [rawKey] + * @returns {string} + */ +export function sanitizeErrorMessage(error, rawKey = '') { + let message = typeof error === 'string' ? error : error?.message || 'An unknown error occurred.'; + + // Strip exact raw key if provided + if (rawKey && typeof rawKey === 'string' && rawKey.trim()) { + message = message.split(rawKey.trim()).join('[REDACTED_API_KEY]'); + } + + // Strip common API key patterns from error message text (check more specific sk-ant- before sk-) + message = message + .replace(/sk-ant-[A-Za-z0-9_-]{20,}/g, '[REDACTED_ANTHROPIC_KEY]') + .replace(/sk-[A-Za-z0-9_-]{20,}/g, '[REDACTED_OPENAI_KEY]') + .replace(/AIzaSy[A-Za-z0-9_-]{30,}/g, '[REDACTED_GEMINI_KEY]') + .replace(/gsk_[A-Za-z0-9_-]{20,}/g, '[REDACTED_GROQ_KEY]'); + + return message; +} + +export class CredentialsRepository { + /** + * Internal storage access helper + * @private + */ + _getStorage() { + return typeof window !== 'undefined' ? window.localStorage : globalThis.localStorage; + } + + /** + * Reads raw list from localStorage + * @private + */ + _readRawKeys() { + try { + const storage = this._getStorage(); + if (!storage) return []; + const raw = storage.getItem(CREDENTIALS_STORAGE_KEY); + if (!raw) return []; + const parsed = JSON.parse(raw); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } + } + + /** + * Writes raw list to localStorage + * @private + */ + _writeRawKeys(keys) { + try { + const storage = this._getStorage(); + if (!storage) return false; + storage.setItem(CREDENTIALS_STORAGE_KEY, JSON.stringify(keys.slice(0, MAX_CREDENTIAL_KEYS))); + return true; + } catch (err) { + console.warn('[CredentialsRepository] Failed to persist credentials:', sanitizeErrorMessage(err)); + return false; + } + } + + /** + * Dedicated credential migration from legacy storage keys: + * 1. Copies legacy OpenAI key (jct_openai_api_key_v1) into unified store ONLY IF the unified store has no key for that provider. + * 2. NEVER deletes the legacy entry (jct_openai_api_key_v1) to guarantee backwards compatibility. + * 3. Also checks older legacy keys (jct_openai_api_key, jct_gemini_api_key, jct_anthropic_api_key, jct_groq_api_key) and per-course settings. + */ + migrateLegacyCredentials() { + const storage = this._getStorage(); + if (!storage) return; + + try { + let keys = this._readRawKeys(); + let updated = false; + + // 1. Migrate legacy OpenAI key (STORAGE_KEYS.OPENAI_API_KEY) + const hasOpenAi = keys.some((k) => k.provider === 'openai'); + if (!hasOpenAi && keys.length < MAX_CREDENTIAL_KEYS) { + let legacyKey = (storage.getItem(LEGACY_OPENAI_KEY) || '').trim(); + + // Fallback to older legacy key + if (!legacyKey) { + legacyKey = (storage.getItem(OLD_LEGACY_OPENAI_KEY) || '').trim(); + } + + // Fallback to embedded per-course settings keys + if (!legacyKey) { + for (let i = 0; i < storage.length; i++) { + const k = storage.key(i); + if (k && k.startsWith(COURSE_KEY_PREFIXES.SETTINGS)) { + try { + const s = JSON.parse(storage.getItem(k)); + if (s?.apiKey && typeof s.apiKey === 'string' && s.apiKey.trim()) { + legacyKey = s.apiKey.trim(); + break; + } + if (s?.openaiApiKey && typeof s.openaiApiKey === 'string' && s.openaiApiKey.trim()) { + legacyKey = s.openaiApiKey.trim(); + break; + } + } catch { + // ignore invalid json + } + } + } + } + + if (legacyKey && legacyKey.startsWith('sk-')) { + keys.push({ + id: 'key_migrated_openai', + provider: 'openai', + label: 'OpenAI (Primary)', + key: legacyKey, + addedAt: new Date().toISOString(), + lastValidatedAt: getTodayDateKey(), + status: 'valid', + }); + updated = true; + // CRITICAL: NEVER delete LEGACY_OPENAI_KEY in this PR! + } + } + + // 2. Migrate legacy individual provider keys if present and unified store lacks them + const individualKeys = [ + { provider: 'anthropic', storageKey: 'jct_anthropic_api_key', label: 'Anthropic (Claude)' }, + { provider: 'gemini', storageKey: 'jct_gemini_api_key', label: 'Google Gemini' }, + { provider: 'groq', storageKey: 'jct_groq_api_key', label: 'Groq' }, + ]; + + for (const item of individualKeys) { + const hasProvider = keys.some((k) => k.provider === item.provider); + if (!hasProvider && keys.length < MAX_CREDENTIAL_KEYS) { + const rawVal = (storage.getItem(item.storageKey) || '').trim(); + if (rawVal) { + keys.push({ + id: `key_migrated_${item.provider}`, + provider: item.provider, + label: item.label, + key: rawVal, + addedAt: new Date().toISOString(), + lastValidatedAt: getTodayDateKey(), + status: 'valid', + }); + updated = true; + } + } + } + + if (updated) { + this._writeRawKeys(keys); + } + } catch (err) { + console.warn('[CredentialsRepository] Credential migration error:', sanitizeErrorMessage(err)); + } + } + + /** + * Retrieves all stored credential records. Automatically checks migration on access. + * @returns {Array} + */ + getAllKeys() { + this.migrateLegacyCredentials(); + return this._readRawKeys(); + } + + /** + * Alias for getAllKeys + * @returns {Array} + */ + getStoredKeys() { + return this.getAllKeys(); + } + + /** + * Retrieves the active key string for a given provider. + * @param {string} providerId + * @returns {string} Plaintext API key, or empty string if not configured + */ + getKey(providerId) { + const keys = this.getAllKeys(); + const match = keys.find((k) => k.provider === providerId); + if (match?.key) return match.key; + + // Fallback for OpenAI from legacy key if not yet in store + if (providerId === 'openai') { + const storage = this._getStorage(); + if (storage) { + const legacy = (storage.getItem(LEGACY_OPENAI_KEY) || '').trim(); + if (legacy) return legacy; + } + } + + return ''; + } + + /** + * Alias for getKey + * @param {string} providerId + * @returns {string} + */ + getApiKey(providerId) { + return this.getKey(providerId); + } + + /** + * Legacy compatibility helper: returns OpenAI API key. + * @returns {string} + */ + getOpenAiApiKey() { + return this.getKey('openai'); + } + + /** + * Sets or replaces the active key for a provider. + * @param {string} providerId + * @param {string} key + * @param {string} [label] + * @returns {{ success: boolean, error?: string, record?: object }} + */ + setKey(providerId, key, label) { + const trimmed = String(key || '').trim(); + if (!trimmed) { + this.removeKeyByProvider(providerId); + return { success: true }; + } + + let keys = this.getAllKeys(); + const existingIndex = keys.findIndex((k) => k.provider === providerId); + + const record = { + id: existingIndex >= 0 ? keys[existingIndex].id : `key_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`, + provider: providerId, + label: (label || '').trim() || `${AI_PROVIDERS[providerId]?.shortName || providerId} Key`, + key: trimmed, + addedAt: existingIndex >= 0 ? keys[existingIndex].addedAt : new Date().toISOString(), + lastValidatedAt: getTodayDateKey(), + status: 'valid', + }; + + if (existingIndex >= 0) { + keys[existingIndex] = record; + } else { + if (keys.length >= MAX_CREDENTIAL_KEYS) { + return { success: false, error: `Maximum of ${MAX_CREDENTIAL_KEYS} API keys reached. Delete an existing key first.` }; + } + keys.push(record); + } + + this._writeRawKeys(keys); + + // Keep legacy OpenAI key in sync for backwards compatibility + if (providerId === 'openai') { + const storage = this._getStorage(); + if (storage) { + try { + storage.setItem(LEGACY_OPENAI_KEY, trimmed); + } catch { + // ignore + } + } + } + + return { success: true, record }; + } + + /** + * Legacy compatibility helper: sets OpenAI API key. + * Synchronizes both the unified store and LEGACY_OPENAI_KEY. + * @param {string} key + */ + setOpenAiApiKey(key) { + return this.setKey('openai', key); + } + + /** + * Adds a new API key record to the store with full UI format validation. + * @param {{ provider: string, key: string, label?: string }} options + * @returns {{ success: boolean, error?: string, record?: object, keys?: Array }} + */ + addKey({ provider, key, label }) { + const keys = this.getAllKeys(); + if (keys.length >= MAX_CREDENTIAL_KEYS) { + return { success: false, error: `Maximum of ${MAX_CREDENTIAL_KEYS} API keys reached. Delete an existing key first.` }; + } + + const trimmed = String(key || '').trim(); + const formatCheck = this.validateKeyFormat(provider, trimmed); + if (!formatCheck.valid) { + return { success: false, error: formatCheck.error }; + } + + // Check duplicate + if (keys.some((k) => k.key === trimmed)) { + return { success: false, error: 'This API key has already been added.' }; + } + + const newRecord = { + id: `key_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`, + provider, + label: (label || '').trim() || `${AI_PROVIDERS[provider]?.shortName || provider} Key`, + key: trimmed, + addedAt: new Date().toISOString(), + lastValidatedAt: getTodayDateKey(), + status: 'valid', + }; + + keys.push(newRecord); + this._writeRawKeys(keys); + + // Sync legacy key if OpenAI + if (provider === 'openai') { + const storage = this._getStorage(); + if (storage) { + try { + storage.setItem(LEGACY_OPENAI_KEY, trimmed); + } catch { + // ignore + } + } + } + + return { success: true, record: newRecord, keys: this.getAllKeys() }; + } + + /** + * Deletes an API key record by ID. + * @param {string} id + * @returns {Array} Updated keys list + */ + deleteKey(id) { + const keys = this.getAllKeys(); + const filtered = keys.filter((k) => k.id !== id); + this._writeRawKeys(filtered); + + // If removed key was OpenAI, sync legacy key + const remainingOpenAi = filtered.find((k) => k.provider === 'openai'); + const storage = this._getStorage(); + if (storage) { + try { + if (remainingOpenAi) { + storage.setItem(LEGACY_OPENAI_KEY, remainingOpenAi.key); + } else { + storage.removeItem(LEGACY_OPENAI_KEY); + } + } catch { + // ignore + } + } + + return filtered; + } + + /** + * Removes any key configured for a specific provider. + * @param {string} providerId + * @returns {Array} + */ + removeKeyByProvider(providerId) { + const keys = this.getAllKeys(); + const filtered = keys.filter((k) => k.provider !== providerId); + this._writeRawKeys(filtered); + + if (providerId === 'openai') { + const storage = this._getStorage(); + if (storage) { + try { + storage.removeItem(LEGACY_OPENAI_KEY); + } catch { + // ignore + } + } + } + + return filtered; + } + + /** + * Validates key format against provider's defined pattern. + * @param {string} providerId + * @param {string} key + * @returns {{ valid: boolean, error: string|null }} + */ + validateKeyFormat(providerId, key) { + const provider = AI_PROVIDERS[providerId]; + if (!provider) return { valid: false, error: 'Unknown provider' }; + const str = String(key || '').trim(); + if (!str) { + return { + valid: false, + error: `Please enter an ${provider.shortName} API key to test.`, + }; + } + + if (providerId === 'openai') { + if (!str.startsWith('sk-')) { + return { + valid: false, + error: 'Invalid key format for OpenAI. OpenAI API keys start with "sk-". Please check the key.', + }; + } + return { valid: true, error: null }; + } + + if (provider.keyPrefixPattern && !provider.keyPrefixPattern.test(str)) { + return { + valid: false, + error: `Invalid key format for ${provider.name}. Must start with ${provider.keyPlaceholder.split('...')[0]}`, + }; + } + + return { valid: true, error: null }; + } + + /** + * Single unified implementation for testing and verifying provider API keys against live endpoints. + * Replaces duplicated fetch implementations across the application. + * + * SECURITY GUARANTEE: Never prints, logs, or returns raw API keys in error strings. + * + * @param {string} providerId + * @param {string} key + * @returns {Promise<{ ok: boolean, status?: number, message?: string, error?: string }>} + */ + async verifyProviderKey(providerId, key) { + const cleanKey = String(key || '').trim(); + const formatCheck = this.validateKeyFormat(providerId, cleanKey); + if (!formatCheck.valid) { + return { ok: false, error: formatCheck.error }; + } + + try { + if (providerId === 'openai') { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 9000); + + const res = await fetch('https://api.openai.com/v1/models', { + method: 'GET', + headers: { + Authorization: `Bearer ${cleanKey}`, + }, + signal: controller.signal, + }); + + clearTimeout(timeoutId); + + if (res.status === 200) { + const data = await res.json().catch(() => null); + const count = Array.isArray(data?.data) ? data.data.length : 0; + return { + ok: true, + status: 200, + message: `API key is verified and working! Connected to OpenAI successfully (${count} models active).`, + }; + } + + if (res.status === 401) { + return { + ok: false, + status: 401, + error: 'Authentication failed (401). The API key is invalid, expired, or was revoked.', + }; + } + + if (res.status === 429) { + return { + ok: false, + status: 429, + error: 'Quota exceeded (429). Check your OpenAI account billing balance and usage limits.', + }; + } + + if (res.status === 403) { + return { + ok: false, + status: 403, + error: 'Forbidden (403). This API key does not have permission to access OpenAI services.', + }; + } + + const errData = await res.json().catch(() => null); + const detail = sanitizeErrorMessage(errData?.error?.message || `HTTP ${res.status}`, cleanKey); + return { + ok: false, + status: res.status, + error: `OpenAI returned error: ${detail}`, + }; + } + + if (providerId === 'gemini') { + const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${cleanKey}`, { + signal: AbortSignal.timeout(6000), + }); + if (res.status === 200) { + return { ok: true, status: 200, message: 'Connected to Google Gemini API successfully' }; + } + if (res.status === 400 || res.status === 403) { + return { ok: false, status: res.status, error: 'Invalid Google Gemini API key' }; + } + return { ok: false, status: res.status, error: `Google API returned status ${res.status}` }; + } + + if (providerId === 'groq') { + const res = await fetch('https://api.groq.com/openai/v1/models', { + headers: { Authorization: `Bearer ${cleanKey}` }, + signal: AbortSignal.timeout(6000), + }); + if (res.status === 200) { + return { ok: true, status: 200, message: 'Connected to Groq API successfully' }; + } + if (res.status === 401) { + return { ok: false, status: 401, error: 'Authentication failed (401). Invalid Groq API key.' }; + } + return { ok: false, status: res.status, error: `Groq returned status ${res.status}` }; + } + + if (providerId === 'anthropic') { + // Anthropic does not support CORS requests directly from browser web clients + return { ok: true, message: 'Anthropic key format is valid (ready for Claude)' }; + } + + return { ok: true, message: 'Key validated' }; + } catch (err) { + if (err.name === 'AbortError' || err.name === 'TimeoutError') { + return { + ok: false, + error: 'Request timed out. Please check your internet connection.', + }; + } + const rawMsg = err?.message || ''; + const safeMsg = sanitizeErrorMessage(rawMsg, cleanKey); + return { + ok: false, + error: safeMsg.includes('Failed to fetch') + ? 'Network request failed. Check your internet connection or browser ad/tracker blockers.' + : `Connection failed: ${safeMsg || 'Unable to reach provider servers'}`, + }; + } + } + + /** + * Validates all stored keys once per calendar day. + * @returns {Promise>} + */ + async validateDaily() { + const todayKey = getTodayDateKey(); + const keys = this.getAllKeys(); + let updated = false; + + for (const k of keys) { + if (k.lastValidatedAt !== todayKey) { + const res = await this.verifyProviderKey(k.provider, k.key); + k.status = res.ok ? 'valid' : 'invalid'; + k.lastValidatedAt = todayKey; + updated = true; + } + } + + if (updated) { + this._writeRawKeys(keys); + } + return keys; + } +} + +// Active singleton instance +export const credentialsRepository = new CredentialsRepository(); +export default credentialsRepository; diff --git a/src/features/ai-tutor/models/credentialsRepository.test.js b/src/features/ai-tutor/models/credentialsRepository.test.js new file mode 100644 index 0000000..b78fcc5 --- /dev/null +++ b/src/features/ai-tutor/models/credentialsRepository.test.js @@ -0,0 +1,252 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + credentialsRepository, + CredentialsRepository, + AI_PROVIDERS, + MAX_CREDENTIAL_KEYS, + CREDENTIALS_STORAGE_KEY, + LEGACY_OPENAI_KEY, + sanitizeErrorMessage, + maskApiKey, +} from './credentialsRepository.js'; +import { getStoredApiKey, setStoredApiKey, verifyOpenAiApiKey } from '../../motivation/models/apiKeyModel.js'; +import { getStoredApiKeys, addApiKey, deleteApiKey } from './apiKeyStorage.js'; + +describe('Credentials Repository & Unified Security Layer', () => { + beforeEach(() => { + localStorage.clear(); + vi.restoreAllMocks(); + }); + + describe('Legacy OpenAI Key Migration (jct_openai_api_key_v1)', () => { + it('migrates legacy OpenAI key into unified store and NEVER deletes the legacy entry', () => { + const mockKey = ['sk', '-proj-legacy-key-migration-12345'].join(''); + localStorage.setItem(LEGACY_OPENAI_KEY, mockKey); + + // Create a fresh instance to test initial access migration + const repo = new CredentialsRepository(); + const keys = repo.getAllKeys(); + + // Verified copied into unified store + expect(keys).toHaveLength(1); + expect(keys[0].provider).toBe('openai'); + expect(keys[0].key).toBe(mockKey); + expect(keys[0].label).toContain('OpenAI'); + + // CRITICAL INVARIANT: The legacy entry MUST remain in localStorage + expect(localStorage.getItem(LEGACY_OPENAI_KEY)).toBe(mockKey); + }); + + it('does NOT overwrite existing OpenAI key in unified store if one is already present', () => { + const existingKey = ['sk', '-proj-primary-key-existing-00000'].join(''); + const legacyKey = ['sk', '-proj-old-legacy-key-ignored-99999'].join(''); + + // Pre-populate unified store with an OpenAI key + localStorage.setItem( + CREDENTIALS_STORAGE_KEY, + JSON.stringify([ + { + id: 'key_1', + provider: 'openai', + label: 'OpenAI Existing', + key: existingKey, + addedAt: '2026-11-01T00:00:00.000Z', + }, + ]) + ); + localStorage.setItem(LEGACY_OPENAI_KEY, legacyKey); + + const repo = new CredentialsRepository(); + const keys = repo.getAllKeys(); + + expect(keys).toHaveLength(1); + expect(keys[0].key).toBe(existingKey); + // Legacy key still remains intact + expect(localStorage.getItem(LEGACY_OPENAI_KEY)).toBe(legacyKey); + }); + }); + + describe('Multi-Provider Key Management (OpenAI, Anthropic, Gemini, Groq)', () => { + it('supports adding and querying keys for all 4 supported providers', () => { + const repo = new CredentialsRepository(); + const mockOpenAi = ['sk', '-proj-openai-key-abcde12345'].join(''); + const mockAnthropic = ['sk', '-ant-api03-anthropic-key-1234567890'].join(''); + const mockGemini = ['AIza', 'SyGeminiApiKeyTest123456789012345'].join(''); + const mockGroq = ['gsk', '_groqApiKeyTest123456789012345678'].join(''); + + const res1 = repo.addKey({ provider: 'openai', key: mockOpenAi }); + const res2 = repo.addKey({ provider: 'anthropic', key: mockAnthropic }); + const res3 = repo.addKey({ provider: 'gemini', key: mockGemini }); + const res4 = repo.addKey({ provider: 'groq', key: mockGroq }); + + expect(res1.success).toBe(true); + expect(res2.success).toBe(true); + expect(res3.success).toBe(true); + expect(res4.success).toBe(true); + + expect(repo.getKey('openai')).toBe(mockOpenAi); + expect(repo.getKey('anthropic')).toBe(mockAnthropic); + expect(repo.getKey('gemini')).toBe(mockGemini); + expect(repo.getKey('groq')).toBe(mockGroq); + }); + + it('rejects duplicate keys and enforces maximum key limit of 5', () => { + const repo = new CredentialsRepository(); + const mockKey1 = ['sk', '-proj-dup-check-key-111111111'].join(''); + const mockKey2 = ['sk', '-proj-dup-check-key-222222222'].join(''); + const mockKey3 = ['sk', '-proj-dup-check-key-333333333'].join(''); + const mockKey4 = ['sk', '-proj-dup-check-key-444444444'].join(''); + const mockKey5 = ['sk', '-proj-dup-check-key-555555555'].join(''); + const mockKey6 = ['sk', '-proj-dup-check-key-666666666'].join(''); + + repo.addKey({ provider: 'openai', key: mockKey1 }); + const dupRes = repo.addKey({ provider: 'openai', key: mockKey1 }); + expect(dupRes.success).toBe(false); + expect(dupRes.error).toContain('already been added'); + + repo.addKey({ provider: 'openai', key: mockKey2 }); + repo.addKey({ provider: 'openai', key: mockKey3 }); + repo.addKey({ provider: 'openai', key: mockKey4 }); + repo.addKey({ provider: 'openai', key: mockKey5 }); + + expect(repo.getAllKeys()).toHaveLength(MAX_CREDENTIAL_KEYS); + + const overflowRes = repo.addKey({ provider: 'openai', key: mockKey6 }); + expect(overflowRes.success).toBe(false); + expect(overflowRes.error).toContain('Maximum of 5 API keys reached'); + }); + + it('validates key prefix format against provider specifications', () => { + const repo = new CredentialsRepository(); + expect(repo.validateKeyFormat('openai', 'invalid-openai-key').valid).toBe(false); + expect(repo.validateKeyFormat('anthropic', 'bad-prefix-12345').valid).toBe(false); + expect(repo.validateKeyFormat('gemini', 'sk-not-gemini-12345').valid).toBe(false); + expect(repo.validateKeyFormat('groq', 'bad-groq-prefix-12345').valid).toBe(false); + expect(repo.validateKeyFormat('unknown', 'sk-proj-something').valid).toBe(false); + }); + }); + + describe('Routing of Legacy apiKeyModel & apiKeyStorage', () => { + it('routes apiKeyModel reads and writes through credentialsRepository while keeping legacy key in sync', () => { + const testKey = ['sk', '-proj-routed-through-model-12345'].join(''); + + // Write through legacy model + setStoredApiKey(testKey); + + // Verify read through repository and legacy getter + expect(getStoredApiKey()).toBe(testKey); + expect(credentialsRepository.getKey('openai')).toBe(testKey); + expect(localStorage.getItem(LEGACY_OPENAI_KEY)).toBe(testKey); + + // Remove through legacy model + setStoredApiKey(''); + expect(getStoredApiKey()).toBe(''); + expect(credentialsRepository.getKey('openai')).toBe(''); + expect(localStorage.getItem(LEGACY_OPENAI_KEY)).toBeNull(); + }); + + it('routes apiKeyStorage operations through credentialsRepository seamlessly', () => { + const mockKey = ['sk', '-proj-routed-through-storage-12345'].join(''); + + const addRes = addApiKey({ provider: 'openai', key: mockKey, label: 'Test Route' }); + expect(addRes.success).toBe(true); + + const keys = getStoredApiKeys(); + expect(keys).toHaveLength(1); + expect(keys[0].key).toBe(mockKey); + + deleteApiKey(keys[0].id); + expect(getStoredApiKeys()).toHaveLength(0); + }); + }); + + describe('Security & Privacy: Zero Key Leakage in Logs or Error Messages', () => { + it('sanitizes and redacts raw secret keys from all error messages', () => { + const rawSecret = ['sk', '-proj-sensitive-secret-token-to-redact'].join(''); + const rawError = `Failed to connect to OpenAI endpoint with key ${rawSecret}: 401 Unauthorized`; + + const sanitized = sanitizeErrorMessage(rawError, rawSecret); + + expect(sanitized).not.toContain(rawSecret); + expect(sanitized).toContain('[REDACTED_API_KEY]'); + }); + + it('redacts generic API key regex patterns even if raw key parameter is omitted', () => { + const leakedKey = ['sk', '-ant-secretAnthropicKey1234567890'].join(''); + const leakedMsg = `Error in fetch: ${leakedKey} connection dropped`; + const sanitized = sanitizeErrorMessage(leakedMsg); + + expect(sanitized).not.toContain('secretAnthropicKey1234567890'); + expect(sanitized).toContain('[REDACTED_ANTHROPIC_KEY]'); + }); + + it('verifyProviderKey never reveals secret keys in returned error objects', async () => { + const secretToProtect = ['sk', '-proj-never-reveal-in-error-12345'].join(''); + + // Mock fetch rejection with secret in error message + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue( + new Error(`Network timeout connecting with ${secretToProtect}`) + ); + + const result = await credentialsRepository.verifyProviderKey('openai', secretToProtect); + + expect(result.ok).toBe(false); + expect(result.error).toBeDefined(); + expect(result.error).not.toContain(secretToProtect); + + fetchSpy.mockRestore(); + }); + + it('masks keys properly for safe UI presentation', () => { + const openAiKey = ['sk', '-proj-1234567890abcdef'].join(''); + const masked = maskApiKey(openAiKey); + expect(masked.startsWith('sk-pro')).toBe(true); + expect(masked.endsWith('cdef')).toBe(true); + expect(masked).toContain('••••••••'); + expect(masked).not.toContain('1234567890'); + + expect(maskApiKey('short')).toBe('••••••••'); + }); + }); + + describe('Unified Verification Logic', () => { + it('handles live OpenAI API verification responses correctly', async () => { + const mockKey = ['sk', '-proj-mock-verification-test'].join(''); + + // Test 200 OK + const fetchSuccess = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ + status: 200, + json: async () => ({ data: [{ id: 'gpt-4o' }] }), + }); + + const okRes = await verifyOpenAiApiKey(mockKey); + expect(okRes.ok).toBe(true); + expect(okRes.status).toBe(200); + + // Test 401 Unauthorized + fetchSuccess.mockResolvedValue({ + status: 401, + json: async () => ({ error: { message: 'Invalid API key' } }), + }); + + const unauthRes = await verifyOpenAiApiKey(mockKey); + expect(unauthRes.ok).toBe(false); + expect(unauthRes.status).toBe(401); + expect(unauthRes.error).toContain('Authentication failed (401)'); + + // Test 429 Quota Exceeded + fetchSuccess.mockResolvedValue({ + status: 429, + json: async () => ({ error: { message: 'Rate limit' } }), + }); + + const quotaRes = await verifyOpenAiApiKey(mockKey); + expect(quotaRes.ok).toBe(false); + expect(quotaRes.status).toBe(429); + expect(quotaRes.error).toContain('Quota exceeded (429)'); + + fetchSuccess.mockRestore(); + }); + }); +}); + diff --git a/src/features/motivation/models/apiKeyModel.js b/src/features/motivation/models/apiKeyModel.js index 00b1cbb..f13a244 100644 --- a/src/features/motivation/models/apiKeyModel.js +++ b/src/features/motivation/models/apiKeyModel.js @@ -1,132 +1,37 @@ -import { STORAGE_KEYS, COURSE_KEY_PREFIXES } from '../../../services/storage/keys.js'; +/** + * Motivation Feature API Key Model (Legacy Compatibility Adapter) + * + * @deprecated Use `credentialsRepository` from `../../ai-tutor/models/credentialsRepository.js` instead. + * All reads, writes, and verification logic are now routed through the unified `credentialsRepository`. + * Kept for backwards compatibility across existing motivation and settings components. + */ -const API_KEY_STORAGE = STORAGE_KEYS.OPENAI_API_KEY; +import { credentialsRepository } from '../../ai-tutor/models/credentialsRepository.js'; +/** + * Retrieves the stored OpenAI API key from the central credentials repository. + * @returns {string} Plaintext OpenAI API key, or empty string if not configured. + */ export function getStoredApiKey() { - try { - const direct = localStorage.getItem(API_KEY_STORAGE) || ''; - if (direct.trim()) return direct.trim(); - for (let i = 0; i < localStorage.length; i++) { - const k = localStorage.key(i); - if (k && k.startsWith(COURSE_KEY_PREFIXES.SETTINGS)) { - try { - const s = JSON.parse(localStorage.getItem(k)); - if (s?.apiKey && typeof s.apiKey === 'string' && s.apiKey.trim()) return s.apiKey.trim(); - if (s?.openaiApiKey && typeof s.openaiApiKey === 'string' && s.openaiApiKey.trim()) return s.openaiApiKey.trim(); - } catch { - // ignore - } - } - } - return ''; - } catch { - return ''; - } + return credentialsRepository.getOpenAiApiKey(); } +/** + * Persists the OpenAI API key to the central credentials repository + * and keeps the legacy storage key in sync. + * @param {string} key + */ export function setStoredApiKey(key) { - try { - const trimmed = typeof key === 'string' ? key.trim() : ''; - if (trimmed) localStorage.setItem(API_KEY_STORAGE, trimmed); - else localStorage.removeItem(API_KEY_STORAGE); - } catch { - // ignore storage errors — the key just won't persist across reloads - } + return credentialsRepository.setOpenAiApiKey(key); } /** * Validates an OpenAI API key against OpenAI's live REST API. - * Uses GET /v1/models to verify authentication without consuming token quota. + * Delegates to the single unified verification implementation in credentialsRepository. * * @param {string} key * @returns {Promise<{ ok: boolean, status?: number, message?: string, error?: string }>} */ export async function verifyOpenAiApiKey(key) { - if (!key || typeof key !== 'string' || !key.trim()) { - return { - ok: false, - error: 'Please enter an OpenAI API key to test.', - }; - } - - const cleanKey = key.trim(); - - // Basic sanity check on key prefix - if (!cleanKey.startsWith('sk-')) { - return { - ok: false, - error: 'Invalid format. OpenAI API keys start with "sk-". Please check the key.', - }; - } - - try { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), 9000); - - const res = await fetch('https://api.openai.com/v1/models', { - method: 'GET', - headers: { - Authorization: `Bearer ${cleanKey}`, - }, - signal: controller.signal, - }); - - clearTimeout(timeoutId); - - if (res.status === 200) { - const data = await res.json().catch(() => null); - const count = Array.isArray(data?.data) ? data.data.length : 0; - return { - ok: true, - status: 200, - message: `API key is verified and working! Connected to OpenAI successfully (${count} models active).`, - }; - } - - if (res.status === 401) { - return { - ok: false, - status: 401, - error: 'Authentication failed (401). The API key is invalid, expired, or was revoked.', - }; - } - - if (res.status === 429) { - return { - ok: false, - status: 429, - error: 'Quota exceeded (429). Check your OpenAI account billing balance and usage limits.', - }; - } - - if (res.status === 403) { - return { - ok: false, - status: 403, - error: 'Forbidden (403). This API key does not have permission to access OpenAI services.', - }; - } - - const errData = await res.json().catch(() => null); - const detail = errData?.error?.message || `HTTP ${res.status}`; - return { - ok: false, - status: res.status, - error: `OpenAI returned error: ${detail}`, - }; - } catch (err) { - if (err.name === 'AbortError') { - return { - ok: false, - error: 'Request timed out after 9 seconds. Please check your internet connection.', - }; - } - const msg = err?.message || ''; - return { - ok: false, - error: msg.includes('Failed to fetch') - ? 'Network request failed. Check your internet connection or browser ad/tracker blockers.' - : `Connection failed: ${msg || 'Unable to reach OpenAI servers'}`, - }; - } + return credentialsRepository.verifyProviderKey('openai', key); } diff --git a/src/services/storage/keys.js b/src/services/storage/keys.js index 6316f50..75630fd 100644 --- a/src/services/storage/keys.js +++ b/src/services/storage/keys.js @@ -206,6 +206,7 @@ export const SENSITIVE_STORAGE_KEYS = Object.freeze([ 'jct_api_key', 'jct_anthropic_api_key', 'jct_gemini_api_key', + 'jct_groq_api_key', ]); /** diff --git a/src/services/storage/keys.test.js b/src/services/storage/keys.test.js index 284854c..770ba32 100644 --- a/src/services/storage/keys.test.js +++ b/src/services/storage/keys.test.js @@ -73,6 +73,7 @@ describe('Storage Key Registry & Metadata', () => { expect(SENSITIVE_STORAGE_KEYS).toContain('jct_openai_api_key_v1'); expect(SENSITIVE_STORAGE_KEYS).toContain('jct_ai_api_keys_v1'); expect(SENSITIVE_STORAGE_KEYS).toContain('jct_openai_api_key'); + expect(SENSITIVE_STORAGE_KEYS).toContain('jct_groq_api_key'); }); it('includes complete schema metadata for all registered keys', () => { @@ -105,6 +106,7 @@ describe('Storage Key Registry & Metadata', () => { expect(isSensitiveKey('jct_completion__course-1')).toBe(true); expect(isSensitiveKey('jct_anthropic_api_key')).toBe(true); expect(isSensitiveKey('jct_gemini_api_key')).toBe(true); + expect(isSensitiveKey('jct_groq_api_key')).toBe(true); // Non-sensitive keys expect(isSensitiveKey(STORAGE_KEYS.REGISTRY)).toBe(false); diff --git a/src/tests/credentialsRestoreBug.test.js b/src/tests/credentialsRestoreBug.test.js new file mode 100644 index 0000000..28883a9 --- /dev/null +++ b/src/tests/credentialsRestoreBug.test.js @@ -0,0 +1,68 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { importAllData } from '../data/courseStore.js'; +import { STORAGE_KEYS } from '../services/storage/keys.js'; + +describe('BUG REPRODUCTION: Backup Restore Wipes Provider Credentials', () => { + beforeEach(() => { + localStorage.clear(); + }); + + it('preserves all provider keys (OpenAI, Gemini, Anthropic, Groq) when restoring a backup', () => { + const mockOpenAi = ['sk', '-proj-openai-credential-test-12345'].join(''); + const mockAnthropic = ['sk', '-ant-credential-test-1234567890'].join(''); + const mockGemini = ['AIza', 'Sy-test-key-credential-1234567890'].join(''); + const mockGroq = ['gsk', '_credentialTestKey1234567890123456'].join(''); + + // User configures all 4 provider keys on their device in multi-provider store + localStorage.setItem( + STORAGE_KEYS.AI_API_KEYS, + JSON.stringify([ + { id: 'k1', provider: 'openai', key: mockOpenAi }, + { id: 'k2', provider: 'anthropic', key: mockAnthropic }, + { id: 'k3', provider: 'gemini', key: mockGemini }, + { id: 'k4', provider: 'groq', key: mockGroq }, + ]) + ); + + // Also store individual/legacy keys as previous versions of the app stored them + localStorage.setItem(STORAGE_KEYS.OPENAI_API_KEY, mockOpenAi); + localStorage.setItem('jct_groq_api_key', mockGroq); + localStorage.setItem('jct_anthropic_api_key', mockAnthropic); + localStorage.setItem('jct_gemini_api_key', mockGemini); + + // Verify all keys are present before restore + expect(localStorage.getItem(STORAGE_KEYS.OPENAI_API_KEY)).toBe(mockOpenAi); + expect(localStorage.getItem('jct_groq_api_key')).toBe(mockGroq); + expect(localStorage.getItem('jct_anthropic_api_key')).toBe(mockAnthropic); + expect(localStorage.getItem('jct_gemini_api_key')).toBe(mockGemini); + + // Incoming course backup bundle from another device/course export (contains NO keys) + const backup = { + appName: 'Core Java + AI Lecture Tracker', + backupVersion: 1, + schemaVersion: 1, + exportedAt: new Date().toISOString(), + sanitized: true, + data: { + 'jct_course_registry_v1': JSON.stringify(['course-restored']), + 'jct_watched__course-restored': JSON.stringify(['l1', 'l2']), + }, + }; + + // Restore course backup + importAllData(backup); + + // BUG REPRODUCTION CHECK: + // Restoring a course backup must NEVER wipe user provider credentials on the device! + const restoredKeys = JSON.parse(localStorage.getItem(STORAGE_KEYS.AI_API_KEYS) || '[]'); + expect(restoredKeys.find((k) => k.provider === 'openai')?.key).toBe(mockOpenAi); + expect(restoredKeys.find((k) => k.provider === 'anthropic')?.key).toBe(mockAnthropic); + expect(restoredKeys.find((k) => k.provider === 'gemini')?.key).toBe(mockGemini); + expect(restoredKeys.find((k) => k.provider === 'groq')?.key).toBe(mockGroq); + + expect(localStorage.getItem(STORAGE_KEYS.OPENAI_API_KEY)).toBe(mockOpenAi); + expect(localStorage.getItem('jct_groq_api_key')).toBe(mockGroq); + expect(localStorage.getItem('jct_anthropic_api_key')).toBe(mockAnthropic); + expect(localStorage.getItem('jct_gemini_api_key')).toBe(mockGemini); + }); +});