From b8b73452c9d90d487bb60edced228bf03db41611 Mon Sep 17 00:00:00 2001 From: Sagar Dhadke <70995022+sagardhadke@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:46:33 +0530 Subject: [PATCH 1/3] feat(storage): add central storage key registry and memory fallback driver --- src/services/storage/LocalStorageDriver.js | 138 ++++++++ src/services/storage/MemoryStorageDriver.js | 75 +++++ src/services/storage/StorageDriver.js | 83 +++++ src/services/storage/index.js | 4 + src/services/storage/keys.js | 342 ++++++++++++++++++++ src/services/storageService.js | 182 +++++++---- 6 files changed, 755 insertions(+), 69 deletions(-) create mode 100644 src/services/storage/LocalStorageDriver.js create mode 100644 src/services/storage/MemoryStorageDriver.js create mode 100644 src/services/storage/StorageDriver.js create mode 100644 src/services/storage/index.js create mode 100644 src/services/storage/keys.js diff --git a/src/services/storage/LocalStorageDriver.js b/src/services/storage/LocalStorageDriver.js new file mode 100644 index 0000000..a20f480 --- /dev/null +++ b/src/services/storage/LocalStorageDriver.js @@ -0,0 +1,138 @@ +import { StorageDriver } from './StorageDriver.js'; + +/** + * Browser LocalStorage Driver + * + * Implements the synchronous StorageDriver contract backed by window.localStorage. + * Includes availability probing, serialization guards, quota error detection, + * and global quota notification events. + */ +export class LocalStorageDriver extends StorageDriver { + constructor() { + super(); + this.name = 'localStorage'; + } + + /** + * Probes window.localStorage availability and writability. + * Handles Safari private browsing and disabled cookie/storage environments. + * @returns {boolean} + */ + isAvailable() { + try { + if (typeof window === 'undefined' || !window.localStorage) return false; + const testKey = '__storage_test__'; + window.localStorage.setItem(testKey, testKey); + window.localStorage.removeItem(testKey); + return true; + } catch { + return false; + } + } + + get(key, defaultValue = null) { + try { + if (typeof window === 'undefined' || !window.localStorage) return defaultValue; + const raw = window.localStorage.getItem(key); + if (raw === null || raw === undefined) return defaultValue; + return JSON.parse(raw); + } catch (err) { + console.warn(`[LocalStorageDriver] Failed to read key "${key}":`, err); + return defaultValue; + } + } + + set(key, value) { + try { + if (typeof window === 'undefined' || !window.localStorage) { + const unavailErr = new Error('localStorage is unavailable'); + unavailErr.name = 'StorageUnavailableError'; + throw unavailErr; + } + const serialized = JSON.stringify(value); + window.localStorage.setItem(key, serialized); + return true; + } catch (err) { + if (this.isQuotaExceeded(err)) { + console.error(`[LocalStorageDriver] Storage quota exceeded while writing "${key}".`, err); + this.notifyQuotaExceeded(); + } else { + console.error(`[LocalStorageDriver] Error writing "${key}":`, err); + } + throw err; + } + } + + remove(key) { + try { + if (typeof window === 'undefined' || !window.localStorage) return false; + window.localStorage.removeItem(key); + return true; + } catch (err) { + console.error(`[LocalStorageDriver] Error removing key "${key}":`, err); + return false; + } + } + + keys() { + try { + if (!this.isAvailable()) return []; + const result = []; + for (let i = 0; i < window.localStorage.length; i++) { + const k = window.localStorage.key(i); + if (k) result.push(k); + } + return result; + } catch { + return []; + } + } + + clear() { + try { + if (!this.isAvailable()) return false; + window.localStorage.clear(); + return true; + } catch (err) { + console.error('[LocalStorageDriver] Error clearing storage:', err); + return false; + } + } + + /** + * Computes approximate UTF-16 byte usage of all stored keys and values. + * @returns {number} + */ + getUsageBytes() { + try { + if (!this.isAvailable()) return 0; + let total = 0; + for (let i = 0; i < window.localStorage.length; i++) { + const k = window.localStorage.key(i); + const v = window.localStorage.getItem(k); + total += (k ? k.length : 0) + (v ? v.length : 0); + } + return total * 2; // UTF-16 characters = 2 bytes each + } catch { + return 0; + } + } + + isQuotaExceeded(err) { + return ( + err && + (err.code === 22 || + err.code === 1014 || + err.name === 'QuotaExceededError' || + err.name === 'NS_ERROR_DOM_QUOTA_REACHED') + ); + } + + notifyQuotaExceeded() { + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') { + window.dispatchEvent(new CustomEvent('jct:storage_quota_exceeded')); + } + } +} + +export default LocalStorageDriver; diff --git a/src/services/storage/MemoryStorageDriver.js b/src/services/storage/MemoryStorageDriver.js new file mode 100644 index 0000000..843ac8c --- /dev/null +++ b/src/services/storage/MemoryStorageDriver.js @@ -0,0 +1,75 @@ +import { StorageDriver } from './StorageDriver.js'; + +/** + * In-Memory Fallback Storage Driver + * + * Implements the synchronous StorageDriver interface using an in-memory Map. + * Values are stored as serialized JSON strings to ensure immutability and exact parity + * with browser localStorage semantics (preventing shared reference mutations). + * + * Used as an automatic fallback when localStorage is unavailable (e.g. private browsing, + * disabled cookies, security sandboxes, or storage quota exhaustion). + */ +export class MemoryStorageDriver extends StorageDriver { + constructor() { + super(); + this.name = 'memory'; + /** @type {Map} */ + this._store = new Map(); + this._simulateQuota = false; + } + + isAvailable() { + return true; + } + + get(key, defaultValue = null) { + if (!this._store.has(key)) return defaultValue; + try { + const raw = this._store.get(key); + if (raw === undefined || raw === null) return defaultValue; + return JSON.parse(raw); + } catch { + return defaultValue; + } + } + + set(key, value) { + if (this._simulateQuota) { + const err = new Error('Simulated QuotaExceededError in MemoryStorageDriver'); + err.name = 'QuotaExceededError'; + err.code = 22; + throw err; + } + try { + const serialized = JSON.stringify(value); + this._store.set(key, serialized); + return true; + } catch { + return false; + } + } + + remove(key) { + return this._store.delete(key); + } + + keys() { + return Array.from(this._store.keys()); + } + + clear() { + this._store.clear(); + return true; + } + + /** + * Helper for testing quota exhaustion behavior + * @param {boolean} flag + */ + simulateQuota(flag = true) { + this._simulateQuota = flag; + } +} + +export default MemoryStorageDriver; diff --git a/src/services/storage/StorageDriver.js b/src/services/storage/StorageDriver.js new file mode 100644 index 0000000..3f7bfd5 --- /dev/null +++ b/src/services/storage/StorageDriver.js @@ -0,0 +1,83 @@ +/** + * Storage Driver Interface Contract + * + * Defines the common synchronous contract implemented by all physical storage drivers + * (e.g. LocalStorageDriver, MemoryStorageDriver). + * + * --- + * Future IndexedDB / Async Storage Adaptation Note: + * + * This interface currently enforces synchronous operations (`get`, `set`, `remove`, `keys`) + * to align with React's synchronous initial render cycle (`useState(read)` in `useLocalStorage`) + * and existing sync feature models. + * + * For future asynchronous drivers (IndexedDB, OPFS, or Remote Cloud Sync): + * 1. An async-enabled facade or adapter will mirror this contract with Promise-based variants: + * `async get(key)`, `async set(key, value)`, `async remove(key)`, `async keys()`. + * 2. To avoid async waterfalls during initial React component rendering, an in-memory + * read-through cache (seeded at app boot via IndexedDB snapshot) provides instant sync reads + * while writes flush asynchronously to the underlying IndexedDB object store with transactional durability. + */ + +export class StorageDriver { + /** + * Human-readable driver name identifier + * @type {string} + */ + name = 'baseDriver'; + + /** + * Checks whether this driver is supported and operable in the current environment. + * @returns {boolean} + */ + isAvailable() { + throw new Error('StorageDriver.isAvailable must be implemented by subclass.'); + } + + /** + * Retrieves and deserializes a value by key. + * @param {string} key + * @param {*} [defaultValue=null] + * @returns {*} Deserialized value, or defaultValue if key does not exist or parsing fails. + */ + get(key, defaultValue = null) { + throw new Error('StorageDriver.get must be implemented by subclass.'); + } + + /** + * Serializes and persists a value by key. + * @param {string} key + * @param {*} value + * @returns {boolean} True if successfully stored, false on error or quota rejection. + */ + set(key, value) { + throw new Error('StorageDriver.set must be implemented by subclass.'); + } + + /** + * Removes a key and its stored value. + * @param {string} key + * @returns {boolean} True if successfully removed, false on error. + */ + remove(key) { + throw new Error('StorageDriver.remove must be implemented by subclass.'); + } + + /** + * Lists all keys managed by this driver. + * @returns {string[]} + */ + keys() { + throw new Error('StorageDriver.keys must be implemented by subclass.'); + } + + /** + * Clears all stored data from this driver. + * @returns {boolean} + */ + clear() { + throw new Error('StorageDriver.clear must be implemented by subclass.'); + } +} + +export default StorageDriver; diff --git a/src/services/storage/index.js b/src/services/storage/index.js new file mode 100644 index 0000000..a5dd4cb --- /dev/null +++ b/src/services/storage/index.js @@ -0,0 +1,4 @@ +export * from './keys.js'; +export * from './StorageDriver.js'; +export * from './LocalStorageDriver.js'; +export * from './MemoryStorageDriver.js'; diff --git a/src/services/storage/keys.js b/src/services/storage/keys.js new file mode 100644 index 0000000..7fe77cc --- /dev/null +++ b/src/services/storage/keys.js @@ -0,0 +1,342 @@ +/** + * Central Storage Key Registry + * + * Single source of truth for all storage keys, dynamic key builders, + * and key metadata across the application. + * + * Preserves 100% exact backwards compatibility with all existing keys. + */ + +export const STORAGE_PREFIX = 'jct_'; + +/** + * Static global storage keys + */ +export const STORAGE_KEYS = Object.freeze({ + /** + * Owner: course + * Shape: { courseIds: string[], activeCourseId: string, customCourses: Record } + * Sensitive: No + * In Backup: Yes + */ + REGISTRY: 'jct_course_registry_v1', + + /** + * Owner: notifications + * Shape: NotificationItem[] + * Sensitive: No + * In Backup: Yes + */ + NOTIFICATIONS: 'jct_notifications_v1', + + /** + * Owner: notifications + * Shape: { enabled: boolean, reminderTime: string, milestoneAlerts: boolean, streakAlerts: boolean } + * Sensitive: No + * In Backup: Yes + */ + NOTIFICATION_SETTINGS: 'jct_notification_settings_v1', + + /** + * Owner: motivation + * Shape: string (plaintext OpenAI secret key) + * Sensitive: YES (Critical secret) + * In Backup: NO (Strictly excluded) + */ + OPENAI_API_KEY: 'jct_openai_api_key_v1', + + /** + * Owner: ai-tutor + * Shape: ApiKeyRecord[] ([{ id, provider, key, label, createdAt }]) + * Sensitive: YES (Critical secrets) + * In Backup: NO (Strictly excluded) + */ + AI_API_KEYS: 'jct_ai_api_keys_v1', + + /** + * Owner: ai-tutor + * Shape: 'true' | 'false' (whether user dismissed floating tutor button) + * Sensitive: No + * In Backup: Yes + */ + AI_FAB_HIDDEN: 'jct_ai_fab_hidden', + + /** + * Owner: motivation + * Shape: { queue: Quote[], seenIds: string[] } + * Sensitive: No + * In Backup: Yes + */ + MOTIVATION_STORE: 'jct_motivation_store_v2', + + /** + * Owner: motivation + * Shape: { until: number } (timestamp ms) + * Sensitive: No + * In Backup: Yes + */ + PREFETCH_COOLDOWN: 'jct_prefetch_cooldown_v1', + + /** + * Owner: motivation + * Shape: { date: string } (ISO date YYYY-MM-DD) + * Sensitive: No + * In Backup: Yes + */ + MOTIVATION_SHOWN: 'jct_motivation_shown_v1', +}); + +/** + * Dynamic per-course key prefixes + */ +export const COURSE_KEY_PREFIXES = Object.freeze({ + WATCHED: 'jct_watched__', + TODAY_PLAN: 'jct_today_plan__', + SETTINGS: 'jct_settings__', + HISTORY: 'jct_history__', + START_DATE: 'jct_start_date__', + START_DATE_MANUAL: 'jct_start_date_manual__', + BADGES: 'jct_badges__', + STREAK_FREEZES: 'jct_streak_freezes__', + COMPLETION: 'jct_completion__', + TRACKING: 'jct_tracking__', +}); + +/** + * Tracking version suffix + */ +export const TRACKING_VERSION = 'v2'; + +/** + * Key builder functions for course-isolated namespaces + */ +export function getWatchedKey(courseId) { + return `${COURSE_KEY_PREFIXES.WATCHED}${courseId}`; +} + +export function getTodayPlanKey(courseId) { + return `${COURSE_KEY_PREFIXES.TODAY_PLAN}${courseId}`; +} + +export function getSettingsKey(courseId) { + return `${COURSE_KEY_PREFIXES.SETTINGS}${courseId}`; +} + +export function getHistoryKey(courseId) { + return `${COURSE_KEY_PREFIXES.HISTORY}${courseId}`; +} + +export function getStartDateKey(courseId) { + return `${COURSE_KEY_PREFIXES.START_DATE}${courseId}`; +} + +export function getStartDateManualKey(courseId) { + return `${COURSE_KEY_PREFIXES.START_DATE_MANUAL}${courseId}`; +} + +export function getBadgesKey(courseId) { + return `${COURSE_KEY_PREFIXES.BADGES}${courseId}`; +} + +export function getStreakFreezesKey(courseId) { + return `${COURSE_KEY_PREFIXES.STREAK_FREEZES}${courseId}`; +} + +export function getCompletionKey(courseId) { + return `${COURSE_KEY_PREFIXES.COMPLETION}${courseId}`; +} + +export function getTrackingKey(courseId) { + return `${COURSE_KEY_PREFIXES.TRACKING}${courseId}_${TRACKING_VERSION}`; +} + +/** + * Array of course key prefixes used for cascading deletion and purging + */ +export const COURSE_PREFIX_LIST = Object.freeze([ + COURSE_KEY_PREFIXES.WATCHED, + COURSE_KEY_PREFIXES.TODAY_PLAN, + COURSE_KEY_PREFIXES.SETTINGS, + COURSE_KEY_PREFIXES.HISTORY, + COURSE_KEY_PREFIXES.START_DATE, + COURSE_KEY_PREFIXES.START_DATE_MANUAL, + COURSE_KEY_PREFIXES.BADGES, + COURSE_KEY_PREFIXES.STREAK_FREEZES, + COURSE_KEY_PREFIXES.COMPLETION, + COURSE_KEY_PREFIXES.TRACKING, +]); + +/** + * Legacy storage keys recognized during migrations and cleanup + */ +export const LEGACY_STORAGE_KEYS = Object.freeze({ + OPENAI_API_KEY: 'jct_openai_api_key', + SETTINGS_V1: 'course_tracker_settings_v1', + WATCHED_V1: 'jct_watched_v1', + TODAY_PLAN_V1: 'jct_today_plan_v1', + SETTINGS_V1_OLD: 'jct_settings_v1', + HISTORY_V1: 'jct_history_v1', + MOTIVATION_SHOWN_V1: 'jct_motivation_shown_v1', +}); + +/** + * Sensitive storage keys that must NEVER be written to backup export payloads + */ +export const SENSITIVE_STORAGE_KEYS = Object.freeze([ + STORAGE_KEYS.OPENAI_API_KEY, + STORAGE_KEYS.AI_API_KEYS, + LEGACY_STORAGE_KEYS.OPENAI_API_KEY, + 'jct_openai_key', + 'jct_api_key', + 'jct_anthropic_api_key', + 'jct_gemini_api_key', +]); + +/** + * Structured metadata registry for all active keys and builders + */ +export const STORAGE_KEY_REGISTRY = Object.freeze({ + [STORAGE_KEYS.REGISTRY]: { + key: STORAGE_KEYS.REGISTRY, + ownerFeature: 'course', + dataShape: '{ courseIds: string[], activeCourseId: string, customCourses: Record }', + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.NOTIFICATIONS]: { + key: STORAGE_KEYS.NOTIFICATIONS, + ownerFeature: 'notifications', + dataShape: 'NotificationItem[]', + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.NOTIFICATION_SETTINGS]: { + key: STORAGE_KEYS.NOTIFICATION_SETTINGS, + ownerFeature: 'notifications', + dataShape: '{ enabled: boolean, reminderTime: string, milestoneAlerts: boolean, streakAlerts: boolean }', + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.OPENAI_API_KEY]: { + key: STORAGE_KEYS.OPENAI_API_KEY, + ownerFeature: 'motivation', + dataShape: 'string (plaintext API key)', + isSensitive: true, + isInBackup: false, + }, + [STORAGE_KEYS.AI_API_KEYS]: { + key: STORAGE_KEYS.AI_API_KEYS, + ownerFeature: 'ai-tutor', + dataShape: 'ApiKeyRecord[]', + isSensitive: true, + isInBackup: false, + }, + [STORAGE_KEYS.AI_FAB_HIDDEN]: { + key: STORAGE_KEYS.AI_FAB_HIDDEN, + ownerFeature: 'ai-tutor', + dataShape: "'true' | 'false'", + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.MOTIVATION_STORE]: { + key: STORAGE_KEYS.MOTIVATION_STORE, + ownerFeature: 'motivation', + dataShape: '{ queue: Quote[], seenIds: string[] }', + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.PREFETCH_COOLDOWN]: { + key: STORAGE_KEYS.PREFETCH_COOLDOWN, + ownerFeature: 'motivation', + dataShape: '{ until: number }', + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.MOTIVATION_SHOWN]: { + key: STORAGE_KEYS.MOTIVATION_SHOWN, + ownerFeature: 'motivation', + dataShape: '{ date: string }', + isSensitive: false, + isInBackup: true, + }, + 'watched': { + builder: getWatchedKey, + prefix: COURSE_KEY_PREFIXES.WATCHED, + ownerFeature: 'course', + dataShape: 'string[] (completed lecture IDs)', + isSensitive: false, + isInBackup: true, + }, + 'today_plan': { + builder: getTodayPlanKey, + prefix: COURSE_KEY_PREFIXES.TODAY_PLAN, + ownerFeature: 'today-plan', + dataShape: 'string[] (planned lecture IDs)', + isSensitive: false, + isInBackup: true, + }, + 'settings': { + builder: getSettingsKey, + prefix: COURSE_KEY_PREFIXES.SETTINGS, + ownerFeature: 'settings', + dataShape: '{ dailyTargetHours: number, streakMode: string, autoPlan: boolean, apiKey?: string }', + isSensitive: false, + isInBackup: true, + }, + 'history': { + builder: getHistoryKey, + prefix: COURSE_KEY_PREFIXES.HISTORY, + ownerFeature: 'streak', + dataShape: 'Record', + isSensitive: false, + isInBackup: true, + }, + 'start_date': { + builder: getStartDateKey, + prefix: COURSE_KEY_PREFIXES.START_DATE, + ownerFeature: 'streak', + dataShape: 'string (ISO date YYYY-MM-DD)', + isSensitive: false, + isInBackup: true, + }, + 'start_date_manual': { + builder: getStartDateManualKey, + prefix: COURSE_KEY_PREFIXES.START_DATE_MANUAL, + ownerFeature: 'streak', + dataShape: "'true' | 'false'", + isSensitive: false, + isInBackup: true, + }, + 'badges': { + builder: getBadgesKey, + prefix: COURSE_KEY_PREFIXES.BADGES, + ownerFeature: 'badges', + dataShape: 'Record', + isSensitive: false, + isInBackup: true, + }, + 'streak_freezes': { + builder: getStreakFreezesKey, + prefix: COURSE_KEY_PREFIXES.STREAK_FREEZES, + ownerFeature: 'streak', + dataShape: '{ availableFreezes: number, usedFreezes: number, freezeHistory: string[] }', + isSensitive: false, + isInBackup: true, + }, + 'completion': { + builder: getCompletionKey, + prefix: COURSE_KEY_PREFIXES.COMPLETION, + ownerFeature: 'course', + dataShape: '{ completedAt: string, verificationPinHash: string, salt: string, attempts: number }', + isSensitive: true, + isInBackup: true, + }, + 'tracking': { + builder: getTrackingKey, + prefix: COURSE_KEY_PREFIXES.TRACKING, + ownerFeature: 'tracking', + dataShape: '{ version: "v2", dailyLog: Record, velocityEWMA: number }', + isSensitive: false, + isInBackup: true, + }, +}); diff --git a/src/services/storageService.js b/src/services/storageService.js index bb8ceff..9a385ef 100644 --- a/src/services/storageService.js +++ b/src/services/storageService.js @@ -1,109 +1,153 @@ /** * Enterprise Storage Service & Repository Abstraction Layer * - * Implements a pluggable Repository pattern decoupling client state - * from physical storage media. Currently operates on a hardened LocalStorageAdapter + * Implements a pluggable Repository pattern decoupling client state from physical storage. + * Manages physical storage drivers (LocalStorageDriver with automatic MemoryStorageDriver fallback) * with quota monitoring, error recovery, and serialization guards. - * - * Prepared for seamless drop-in cloud backend / remote REST/GraphQL synchronization. */ -class LocalStorageAdapter { - constructor() { - this.name = 'localStorage'; +import { LocalStorageDriver } from './storage/LocalStorageDriver.js'; +import { MemoryStorageDriver } from './storage/MemoryStorageDriver.js'; + +export class StorageService { + constructor(primaryDriver = new LocalStorageDriver(), fallbackDriver = new MemoryStorageDriver()) { + this.primaryDriver = primaryDriver; + this.fallbackDriver = fallbackDriver; + this._usingFallback = false; + + // Check initial availability + if (!this.primaryDriver.isAvailable()) { + this._activateFallback('Primary storage driver unavailable at startup'); + } } - isAvailable() { + /** + * Indicates whether the storage service is currently operating in fallback mode. + * @returns {boolean} + */ + isUsingFallback() { + return this._usingFallback; + } + + /** + * Returns the currently active storage driver. + * @returns {import('./storage/StorageDriver.js').StorageDriver} + */ + getActiveDriver() { + return this._usingFallback ? this.fallbackDriver : this.primaryDriver; + } + + /** + * Transitions to the in-memory fallback driver upon storage failure or quota exhaustion. + * Copies available items from the primary driver to preserve session state. + * @param {string|Error} [reason] + * @private + */ + _activateFallback(reason) { + if (this._usingFallback) return; + this._usingFallback = true; + console.warn('[StorageService] Switching to in-memory fallback driver:', reason); + + // Attempt to seed fallback driver with any accessible keys from primary try { - if (typeof window === 'undefined' || !window.localStorage) return false; - const testKey = '__storage_test__'; - window.localStorage.setItem(testKey, testKey); - window.localStorage.removeItem(testKey); - return true; - } catch { - return false; + if (this.primaryDriver && typeof this.primaryDriver.keys === 'function') { + const existingKeys = this.primaryDriver.keys(); + for (const k of existingKeys) { + const v = this.primaryDriver.get(k); + if (v !== null && v !== undefined) { + this.fallbackDriver.set(k, v); + } + } + } + } catch (copyErr) { + console.warn('[StorageService] Could not copy existing keys to fallback driver:', copyErr); + } + + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') { + window.dispatchEvent( + new CustomEvent('jct:storage_fallback_active', { + detail: { reason: reason ? String(reason) : 'unknown' }, + }) + ); } } + isAvailable() { + return this.getActiveDriver().isAvailable(); + } + getItem(key, defaultValue = null) { + if (this._usingFallback) { + return this.fallbackDriver.get(key, defaultValue); + } try { - if (!this.isAvailable()) return defaultValue; - const raw = window.localStorage.getItem(key); - if (raw === null) return defaultValue; - return JSON.parse(raw); + return this.primaryDriver.get(key, defaultValue); } catch (err) { - console.warn(`[StorageService] Failed to read key "${key}":`, err); - return defaultValue; + console.warn(`[StorageService] Failed to read "${key}" from primary driver, switching to fallback:`, err); + this._activateFallback(err); + return this.fallbackDriver.get(key, defaultValue); } } setItem(key, value) { + if (this._usingFallback) { + return this.fallbackDriver.set(key, value); + } try { - if (!this.isAvailable()) return false; - const serialized = JSON.stringify(value); - window.localStorage.setItem(key, serialized); - return true; + return this.primaryDriver.set(key, value); } catch (err) { - if (this.isQuotaExceeded(err)) { - console.error(`[StorageService] Storage quota exceeded while writing "${key}".`, err); - this.notifyQuotaExceeded(); - } else { - console.error(`[StorageService] Error writing "${key}":`, err); - } - return false; + this._activateFallback(err); + return this.fallbackDriver.set(key, value); } } removeItem(key) { - try { - if (!this.isAvailable()) return false; - window.localStorage.removeItem(key); - return true; - } catch (err) { - console.error(`[StorageService] Error removing key "${key}":`, err); - return false; + const activeResult = this.getActiveDriver().remove(key); + // Also remove from fallback driver if it was seeded + if (!this._usingFallback) { + this.fallbackDriver.remove(key); } + return activeResult; } clear() { - try { - if (!this.isAvailable()) return false; - window.localStorage.clear(); - return true; - } catch (err) { - console.error('[StorageService] Error clearing storage:', err); - return false; - } + this.fallbackDriver.clear(); + return this.getActiveDriver().clear(); + } + + keys() { + return this.getActiveDriver().keys(); + } + + get(key, defaultValue = null) { + return this.getItem(key, defaultValue); + } + + set(key, value) { + return this.setItem(key, value); + } + + remove(key) { + return this.removeItem(key); } getUsageBytes() { - try { - if (!this.isAvailable()) return 0; - let total = 0; - for (let i = 0; i < window.localStorage.length; i++) { - const k = window.localStorage.key(i); - const v = window.localStorage.getItem(k); - total += (k ? k.length : 0) + (v ? v.length : 0); - } - return total * 2; // UTF-16 characters = 2 bytes each - } catch { - return 0; + if (!this._usingFallback && typeof this.primaryDriver.getUsageBytes === 'function') { + return this.primaryDriver.getUsageBytes(); } + return 0; } isQuotaExceeded(err) { - return ( - err && - (err.code === 22 || - err.code === 1014 || - err.name === 'QuotaExceededError' || - err.name === 'NS_ERROR_DOM_QUOTA_REACHED') - ); + if (typeof this.primaryDriver.isQuotaExceeded === 'function') { + return this.primaryDriver.isQuotaExceeded(err); + } + return false; } notifyQuotaExceeded() { - if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') { - window.dispatchEvent(new CustomEvent('jct:storage_quota_exceeded')); + if (typeof this.primaryDriver.notifyQuotaExceeded === 'function') { + this.primaryDriver.notifyQuotaExceeded(); } } } @@ -116,7 +160,7 @@ export class RemoteApiAdapter { this.name = 'remoteApi'; this.baseUrl = apiBaseUrl; this.token = authToken; - this.localFallback = new LocalStorageAdapter(); + this.localFallback = new StorageService(); } setToken(token) { @@ -162,6 +206,6 @@ export class RemoteApiAdapter { } // Active singleton instance -export const storageService = new LocalStorageAdapter(); +export const storageService = new StorageService(); export { exportAllData as exportBackup, importAllData as restoreBackup } from '../data/courseStore.js'; export default storageService; From 5a093eb1ef4db1b115b413f431c5a067ee99cf6d Mon Sep 17 00:00:00 2001 From: Sagar Dhadke <70995022+sagardhadke@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:47:21 +0530 Subject: [PATCH 2/3] refactor(storage): replace raw storage key literals with central registry imports --- src/data/courseStore.js | 56 ++++++++++--------- src/features/ai-tutor/models/apiKeyStorage.js | 6 +- .../ai-tutor/views/AiTutorFloatingButton.jsx | 3 +- .../course/models/courseCompletionModel.js | 4 +- src/features/motivation/models/apiKeyModel.js | 6 +- .../motivation/models/motivationModel.js | 5 +- .../viewmodels/useMotivationViewModel.js | 3 +- .../notifications/models/notificationModel.js | 6 +- .../streak/models/activityHistoryModel.js | 3 +- .../tracking/models/learningTrackerModel.js | 11 ++-- src/hooks/useCourseProgress.js | 28 +++++++--- 11 files changed, 77 insertions(+), 54 deletions(-) diff --git a/src/data/courseStore.js b/src/data/courseStore.js index 58f9ba4..1a85a81 100644 --- a/src/data/courseStore.js +++ b/src/data/courseStore.js @@ -1,7 +1,14 @@ import { DEFAULT_COURSES } from './defaultCourses.js'; import { parseCourseXml } from './xmlCourseParser.js'; +import { + STORAGE_KEYS, + COURSE_KEY_PREFIXES as COURSE_PREFIXES, + SENSITIVE_STORAGE_KEYS as REGISTRY_SENSITIVE_KEYS, + LEGACY_STORAGE_KEYS, + STORAGE_PREFIX, +} from '../services/storage/keys.js'; -const REGISTRY_KEY = 'jct_course_registry_v1'; // { courseIds: [...], activeCourseId, customCourses: { [id]: courseObject } } +const REGISTRY_KEY = STORAGE_KEYS.REGISTRY; // { courseIds: [...], activeCourseId, customCourses: { [id]: courseObject } } // The set of default course ids that ship with the app. These are never // stored in localStorage themselves (they come from defaultCourses.js), only @@ -64,15 +71,15 @@ function saveRegistry(registry) { // Exhaustive list of all localStorage key prefixes owned by a specific course. // Includes progress, plan, settings, history, start dates, badges, streak freezes, and completion states. export const COURSE_KEY_PREFIXES = [ - 'jct_watched__', - 'jct_today_plan__', - 'jct_settings__', - 'jct_history__', - 'jct_start_date__', - 'jct_start_date_manual__', - 'jct_badges__', - 'jct_streak_freezes__', - 'jct_completion__', + COURSE_PREFIXES.WATCHED, + COURSE_PREFIXES.TODAY_PLAN, + COURSE_PREFIXES.SETTINGS, + COURSE_PREFIXES.HISTORY, + COURSE_PREFIXES.START_DATE, + COURSE_PREFIXES.START_DATE_MANUAL, + COURSE_PREFIXES.BADGES, + COURSE_PREFIXES.STREAK_FREEZES, + COURSE_PREFIXES.COMPLETION, ]; // Returns all exact keys belonging to a specific course. @@ -207,8 +214,13 @@ export function resetEverything() { localStorage.removeItem(REGISTRY_KEY); // Also clear any legacy/global keys from earlier single-course versions of the app. - ['jct_watched_v1', 'jct_today_plan_v1', 'jct_settings_v1', 'jct_history_v1', - 'jct_motivation_shown_v1'].forEach((k) => localStorage.removeItem(k)); + [ + LEGACY_STORAGE_KEYS.WATCHED_V1, + LEGACY_STORAGE_KEYS.TODAY_PLAN_V1, + LEGACY_STORAGE_KEYS.SETTINGS_V1_OLD, + LEGACY_STORAGE_KEYS.HISTORY_V1, + LEGACY_STORAGE_KEYS.MOTIVATION_SHOWN_V1, + ].forEach((k) => localStorage.removeItem(k)); } // ---- Backup & Restore ---- @@ -217,17 +229,9 @@ export function resetEverything() { // SECURITY GUARANTEE: Sensitive credentials (OpenAI API keys) are strictly // stripped from exports to prevent credential leakage when sharing backups. -const APP_KEY_PREFIX = 'jct_'; +const APP_KEY_PREFIX = STORAGE_PREFIX; -const SENSITIVE_STORAGE_KEYS = new Set([ - 'jct_openai_api_key_v1', - 'jct_openai_key', - 'jct_api_key', - 'jct_ai_api_keys_v1', - 'jct_openai_api_key', - 'jct_anthropic_api_key', - 'jct_gemini_api_key', -]); +const SENSITIVE_STORAGE_KEYS = new Set(REGISTRY_SENSITIVE_KEYS); /** * Sanitizes stored values before inclusion in an export bundle. @@ -237,7 +241,7 @@ function sanitizeValueForExport(key, rawValue) { if (SENSITIVE_STORAGE_KEYS.has(key)) { return null; // Exclude top-level API key } - if (key && key.startsWith('jct_settings__') && typeof rawValue === 'string') { + if (key && key.startsWith(COURSE_PREFIXES.SETTINGS) && typeof rawValue === 'string') { try { const parsed = JSON.parse(rawValue); if (parsed && typeof parsed === 'object') { @@ -293,7 +297,7 @@ export function importAllData(backup, { preserveExistingApiKey = true } = {}) { // Preserve existing local API key so restoring a course backup doesn't wipe credentials let existingApiKey = null; if (preserveExistingApiKey) { - existingApiKey = localStorage.getItem('jct_openai_api_key_v1'); + existingApiKey = localStorage.getItem(STORAGE_KEYS.OPENAI_API_KEY); } // Clear all existing app keys first, so a restore fully replaces state @@ -312,8 +316,8 @@ export function importAllData(backup, { preserveExistingApiKey = true } = {}) { }); // Restore preserved local API key if the backup did not provide one - if (preserveExistingApiKey && existingApiKey && !backup.data['jct_openai_api_key_v1']) { - localStorage.setItem('jct_openai_api_key_v1', existingApiKey); + if (preserveExistingApiKey && existingApiKey && !backup.data[STORAGE_KEYS.OPENAI_API_KEY]) { + localStorage.setItem(STORAGE_KEYS.OPENAI_API_KEY, existingApiKey); } } diff --git a/src/features/ai-tutor/models/apiKeyStorage.js b/src/features/ai-tutor/models/apiKeyStorage.js index 3204627..b0af594 100644 --- a/src/features/ai-tutor/models/apiKeyStorage.js +++ b/src/features/ai-tutor/models/apiKeyStorage.js @@ -5,9 +5,11 @@ * Never transmitted to any 3rd-party backend or telemetry server. */ +import { STORAGE_KEYS, LEGACY_STORAGE_KEYS } from '../../../services/storage/keys.js'; + export const MAX_API_KEYS = 5; -export const API_KEYS_STORAGE_KEY = 'jct_ai_api_keys_v1'; -export const LEGACY_OPENAI_STORAGE_KEY = 'jct_openai_api_key'; +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 AI_PROVIDERS = { openai: { diff --git a/src/features/ai-tutor/views/AiTutorFloatingButton.jsx b/src/features/ai-tutor/views/AiTutorFloatingButton.jsx index 8b75200..0ed74ed 100644 --- a/src/features/ai-tutor/views/AiTutorFloatingButton.jsx +++ b/src/features/ai-tutor/views/AiTutorFloatingButton.jsx @@ -1,8 +1,9 @@ import { useState } from 'react'; +import { STORAGE_KEYS } from '../../../services/storage/keys.js'; import { showToast } from '../../../utils/toast.js'; import './AiTutorFloatingButton.css'; -const AI_FAB_STORAGE_KEY = 'jct_ai_fab_hidden'; +const AI_FAB_STORAGE_KEY = STORAGE_KEYS.AI_FAB_HIDDEN; /** * Floating Action Button (FAB) for AI Tutor diff --git a/src/features/course/models/courseCompletionModel.js b/src/features/course/models/courseCompletionModel.js index f530277..77a4860 100644 --- a/src/features/course/models/courseCompletionModel.js +++ b/src/features/course/models/courseCompletionModel.js @@ -11,8 +11,10 @@ * in_progress → verification_pending (PIN sent) → verification_completed → completed (100%) */ +import { COURSE_KEY_PREFIXES } from '../../../services/storage/keys.js'; + // ── localStorage keys (namespaced per course) ────────────────────────── -export const COMPLETION_KEY_PREFIX = 'jct_completion__'; +export const COMPLETION_KEY_PREFIX = COURSE_KEY_PREFIXES.COMPLETION; // ── Status enum ──────────────────────────────────────────────────────── export const COMPLETION_STATUS = { diff --git a/src/features/motivation/models/apiKeyModel.js b/src/features/motivation/models/apiKeyModel.js index 4d066c5..00b1cbb 100644 --- a/src/features/motivation/models/apiKeyModel.js +++ b/src/features/motivation/models/apiKeyModel.js @@ -1,4 +1,6 @@ -const API_KEY_STORAGE = 'jct_openai_api_key_v1'; +import { STORAGE_KEYS, COURSE_KEY_PREFIXES } from '../../../services/storage/keys.js'; + +const API_KEY_STORAGE = STORAGE_KEYS.OPENAI_API_KEY; export function getStoredApiKey() { try { @@ -6,7 +8,7 @@ export function getStoredApiKey() { if (direct.trim()) return direct.trim(); for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); - if (k && k.startsWith('jct_settings__')) { + 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(); diff --git a/src/features/motivation/models/motivationModel.js b/src/features/motivation/models/motivationModel.js index c3f4b1c..aecfae4 100644 --- a/src/features/motivation/models/motivationModel.js +++ b/src/features/motivation/models/motivationModel.js @@ -1,4 +1,5 @@ import { showToast } from '../../../utils/toast.js'; +import { STORAGE_KEYS } from '../../../services/storage/keys.js'; /** * Curated list of 15 high-impact motivational messages for the daily popup dialog. @@ -22,7 +23,7 @@ export const DEFAULT_MOTIVATION_MESSAGES = [ "The gap between who you are and who you want to become is closed by the code you write today.", ]; -export const MOTIVATION_STORE_KEY = 'jct_motivation_store_v2'; +export const MOTIVATION_STORE_KEY = STORAGE_KEYS.MOTIVATION_STORE; /** * Fisher-Yates array shuffler to ensure non-deterministic, unbiased quote distribution. @@ -276,7 +277,7 @@ export function explainPrefetchError(err, status = null) { return `AI Quote Notice: ${msg || 'Could not fetch remote quote'}. Using curated study message.`; } -const PREFETCH_COOLDOWN_KEY = 'jct_prefetch_cooldown_v1'; +const PREFETCH_COOLDOWN_KEY = STORAGE_KEYS.PREFETCH_COOLDOWN; const PREFETCH_COOLDOWN_MS = 60 * 60 * 1000; // 1 hour cooldown after API errors /** diff --git a/src/features/motivation/viewmodels/useMotivationViewModel.js b/src/features/motivation/viewmodels/useMotivationViewModel.js index 50e75f3..4dd9568 100644 --- a/src/features/motivation/viewmodels/useMotivationViewModel.js +++ b/src/features/motivation/viewmodels/useMotivationViewModel.js @@ -8,8 +8,9 @@ import { getMotivationStore, } from '../models/motivationModel.js'; import { showToast } from '../../../utils/toast.js'; +import { STORAGE_KEYS } from '../../../services/storage/keys.js'; -const SHOWN_KEY = 'jct_motivation_shown_v1'; +const SHOWN_KEY = STORAGE_KEYS.MOTIVATION_SHOWN; export function getShownDate() { try { diff --git a/src/features/notifications/models/notificationModel.js b/src/features/notifications/models/notificationModel.js index 74fe65b..7664d4f 100644 --- a/src/features/notifications/models/notificationModel.js +++ b/src/features/notifications/models/notificationModel.js @@ -3,8 +3,10 @@ * Enterprise-grade state management, Web Notification API integration, and scheduled study alerts. */ -export const NOTIFICATIONS_STORAGE_KEY = 'jct_notifications_v1'; -export const NOTIFICATION_SETTINGS_KEY = 'jct_notification_settings_v1'; +import { STORAGE_KEYS } from '../../../services/storage/keys.js'; + +export const NOTIFICATIONS_STORAGE_KEY = STORAGE_KEYS.NOTIFICATIONS; +export const NOTIFICATION_SETTINGS_KEY = STORAGE_KEYS.NOTIFICATION_SETTINGS; export const NOTIFICATION_TYPES = { ACHIEVEMENT: 'achievement', diff --git a/src/features/streak/models/activityHistoryModel.js b/src/features/streak/models/activityHistoryModel.js index 82e8076..41ec5c5 100644 --- a/src/features/streak/models/activityHistoryModel.js +++ b/src/features/streak/models/activityHistoryModel.js @@ -1,4 +1,5 @@ import { formatDuration } from '../../../utils/time.js'; +import { getHistoryKey } from '../../../services/storage/keys.js'; /** * Aggregates study activity history across all registered courses. @@ -12,7 +13,7 @@ export function getAggregatedHistory(courses = [], activeCourse = null, activeHi courseList.forEach((c) => { try { const isCurrentActive = activeCourse && c.id === activeCourse.id; - const raw = localStorage.getItem(`jct_history__${c.id}`); + const raw = localStorage.getItem(getHistoryKey(c.id)); const courseHistory = isCurrentActive && activeHistory ? activeHistory : (raw ? JSON.parse(raw) : {}); if (!courseHistory || typeof courseHistory !== 'object') return; diff --git a/src/features/tracking/models/learningTrackerModel.js b/src/features/tracking/models/learningTrackerModel.js index 77979d0..a6cde24 100644 --- a/src/features/tracking/models/learningTrackerModel.js +++ b/src/features/tracking/models/learningTrackerModel.js @@ -18,13 +18,10 @@ function toLocalDateKey(d) { * - Personalized progress reports */ -export const TRACKING_VERSION = 'v2'; -export const DAILY_LIMIT_SEC = 5 * 3600; // 5 hours in seconds +import { getTrackingKey, getHistoryKey, TRACKING_VERSION } from '../../../services/storage/keys.js'; -/** localStorage key namespaced per course */ -export function getTrackingKey(courseId) { - return `jct_tracking__${courseId}_${TRACKING_VERSION}`; -} +export { getTrackingKey, TRACKING_VERSION }; +export const DAILY_LIMIT_SEC = 5 * 3600; // 5 hours in seconds /** Default empty tracking store structure */ export function createEmptyTrackingStore() { @@ -145,7 +142,7 @@ export function getTodayLearnedSec(courseId, dateKey, inMemoryHistory) { historySec = inMemoryHistory[dateKey].watchedSec; } else if (typeof localStorage !== 'undefined') { try { - const raw = localStorage.getItem(`jct_history__${courseId}`); + const raw = localStorage.getItem(getHistoryKey(courseId)); if (raw) { const h = JSON.parse(raw); historySec = h?.[dateKey]?.watchedSec || 0; diff --git a/src/hooks/useCourseProgress.js b/src/hooks/useCourseProgress.js index 8fcbd93..59cd05a 100644 --- a/src/hooks/useCourseProgress.js +++ b/src/hooks/useCourseProgress.js @@ -1,5 +1,15 @@ import { useEffect, useMemo, useRef, useState, useCallback } from 'react'; import { useLocalStorage } from './useLocalStorage'; +import { + getWatchedKey, + getTodayPlanKey, + getSettingsKey, + getHistoryKey, + getStartDateKey, + getStartDateManualKey, + getBadgesKey, + getStreakFreezesKey, +} from '../services/storage/keys.js'; import { dateKey, formatDuration } from '../utils/time'; import { getBadgesStatus } from '../features/badges/models/badgeModel.js'; import { DEFAULT_SETTINGS } from '../features/settings/models/settingsModel.js'; @@ -48,14 +58,14 @@ export function useCourseProgress(course) { const courseId = course?.id || 'core-java-ai'; const allLectures = useMemo(() => course?.allLectures || [], [course]); - const WATCHED_KEY = `jct_watched__${courseId}`; - const PLAN_KEY = `jct_today_plan__${courseId}`; - const SETTINGS_KEY = `jct_settings__${courseId}`; - const HISTORY_KEY = `jct_history__${courseId}`; - const START_DATE_KEY = `jct_start_date__${courseId}`; - const START_DATE_MANUAL_KEY = `jct_start_date_manual__${courseId}`; - const BADGES_KEY = `jct_badges__${courseId}`; - const FREEZES_KEY = `jct_streak_freezes__${courseId}`; + const WATCHED_KEY = getWatchedKey(courseId); + const PLAN_KEY = getTodayPlanKey(courseId); + const SETTINGS_KEY = getSettingsKey(courseId); + const HISTORY_KEY = getHistoryKey(courseId); + const START_DATE_KEY = getStartDateKey(courseId); + const START_DATE_MANUAL_KEY = getStartDateManualKey(courseId); + const BADGES_KEY = getBadgesKey(courseId); + const FREEZES_KEY = getStreakFreezesKey(courseId); const [watched, setWatched] = useLocalStorage(WATCHED_KEY, {}); const [planStore, setPlanStore] = useLocalStorage(PLAN_KEY, { date: null, ids: [], auto: true }); @@ -187,7 +197,7 @@ export function useCourseProgress(course) { } const nextHistory = { ...h, [key]: nextBucket }; try { - localStorage.setItem(`jct_history__${courseId}`, JSON.stringify(nextHistory)); + localStorage.setItem(getHistoryKey(courseId), JSON.stringify(nextHistory)); } catch {} return nextHistory; }); From 8d4d78c5c2dc4a3ebb742d56f550a96070cae379 Mon Sep 17 00:00:00 2001 From: Sagar Dhadke <70995022+sagardhadke@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:48:20 +0530 Subject: [PATCH 3/3] test(storage): add unit tests for key registry, storage drivers, and key enforcement --- src/services/storage/drivers.test.js | 161 ++++++++++++++++++ src/services/storage/keys.test.js | 90 ++++++++++ .../storage/storageKeyEnforcement.test.js | 95 +++++++++++ 3 files changed, 346 insertions(+) create mode 100644 src/services/storage/drivers.test.js create mode 100644 src/services/storage/keys.test.js create mode 100644 src/services/storage/storageKeyEnforcement.test.js diff --git a/src/services/storage/drivers.test.js b/src/services/storage/drivers.test.js new file mode 100644 index 0000000..03c2006 --- /dev/null +++ b/src/services/storage/drivers.test.js @@ -0,0 +1,161 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { StorageDriver } from './StorageDriver.js'; +import { MemoryStorageDriver } from './MemoryStorageDriver.js'; +import { LocalStorageDriver } from './LocalStorageDriver.js'; +import { StorageService } from '../storageService.js'; + +describe('Storage Drivers & Fallback System', () => { + beforeEach(() => { + localStorage.clear(); + vi.restoreAllMocks(); + }); + + describe('StorageDriver Base Contract', () => { + it('throws errors for unimplemented abstract methods', () => { + const base = new StorageDriver(); + expect(() => base.isAvailable()).toThrow(); + expect(() => base.get('k')).toThrow(); + expect(() => base.set('k', 'v')).toThrow(); + expect(() => base.remove('k')).toThrow(); + expect(() => base.keys()).toThrow(); + expect(() => base.clear()).toThrow(); + }); + }); + + describe('MemoryStorageDriver', () => { + it('stores, retrieves, removes, and lists keys correctly', () => { + const driver = new MemoryStorageDriver(); + expect(driver.isAvailable()).toBe(true); + + expect(driver.get('test_key', 'fallback_val')).toBe('fallback_val'); + + driver.set('test_key', { count: 42, active: true }); + expect(driver.get('test_key')).toEqual({ count: 42, active: true }); + expect(driver.keys()).toEqual(['test_key']); + + driver.remove('test_key'); + expect(driver.get('test_key')).toBeNull(); + expect(driver.keys()).toEqual([]); + }); + + it('isolates stored data from subsequent in-memory mutations', () => { + const driver = new MemoryStorageDriver(); + const payload = { nested: { val: 10 } }; + driver.set('payload', payload); + + // Mutate local object + payload.nested.val = 999; + + // Stored value should remain untouched + expect(driver.get('payload')).toEqual({ nested: { val: 10 } }); + }); + + it('handles simulated quota errors', () => { + const driver = new MemoryStorageDriver(); + driver.simulateQuota(true); + + expect(() => driver.set('any', 'value')).toThrow(/QuotaExceededError/); + }); + }); + + describe('LocalStorageDriver', () => { + it('interacts with window.localStorage and computes approximate usage bytes', () => { + const driver = new LocalStorageDriver(); + expect(driver.isAvailable()).toBe(true); + + driver.set('driver_item', { text: 'hello' }); + expect(driver.get('driver_item')).toEqual({ text: 'hello' }); + expect(driver.keys()).toContain('driver_item'); + expect(driver.getUsageBytes()).toBeGreaterThan(0); + + driver.remove('driver_item'); + expect(driver.get('driver_item')).toBeNull(); + }); + + it('detects quota errors and dispatches jct:storage_quota_exceeded', () => { + const driver = new LocalStorageDriver(); + const quotaErr = new Error('Quota exceeded'); + quotaErr.name = 'QuotaExceededError'; + quotaErr.code = 22; + + expect(driver.isQuotaExceeded(quotaErr)).toBe(true); + + const eventSpy = vi.fn(); + window.addEventListener('jct:storage_quota_exceeded', eventSpy); + + vi.spyOn(Storage.prototype, 'setItem').mockImplementationOnce(() => { + throw quotaErr; + }); + + expect(() => driver.set('fail_key', 'value')).toThrow(/Quota exceeded/); + expect(eventSpy).toHaveBeenCalledTimes(1); + + window.removeEventListener('jct:storage_quota_exceeded', eventSpy); + }); + + it('returns default value when localStorage throws or fails to read', () => { + const driver = new LocalStorageDriver(); + vi.spyOn(Storage.prototype, 'getItem').mockImplementationOnce(() => { + throw new Error('SecurityError: Access Denied'); + }); + + const result = driver.get('denied_key', 'safe_default'); + expect(result).toBe('safe_default'); + }); + }); + + describe('StorageService Fallback & Error Recovery', () => { + it('operates normally with LocalStorageDriver when available', () => { + const service = new StorageService(); + expect(service.isUsingFallback()).toBe(false); + expect(service.getActiveDriver().name).toBe('localStorage'); + + service.setItem('svc_test', { greeting: 'world' }); + expect(service.getItem('svc_test')).toEqual({ greeting: 'world' }); + }); + + it('automatically activates fallback driver if primary driver is unavailable at boot', () => { + const mockPrimary = new LocalStorageDriver(); + vi.spyOn(mockPrimary, 'isAvailable').mockReturnValue(false); + + const service = new StorageService(mockPrimary); + expect(service.isUsingFallback()).toBe(true); + expect(service.getActiveDriver().name).toBe('memory'); + + service.setItem('offline_key', 'persisted_in_memory'); + expect(service.getItem('offline_key')).toBe('persisted_in_memory'); + }); + + it('switches to fallback and copies existing items when primary driver throws QuotaExceededError', () => { + const fallbackEventSpy = vi.fn(); + window.addEventListener('jct:storage_fallback_active', fallbackEventSpy); + + const primary = new LocalStorageDriver(); + const fallback = new MemoryStorageDriver(); + const service = new StorageService(primary, fallback); + + // Seed an existing key before quota error + service.setItem('initial_key', 'preserved_state'); + + // Simulate quota error on next write + const quotaErr = new Error('Quota exceeded'); + quotaErr.name = 'QuotaExceededError'; + quotaErr.code = 22; + vi.spyOn(primary, 'set').mockImplementationOnce(() => { + throw quotaErr; + }); + + // Write that triggers quota failure + const writeSuccess = service.setItem('overflow_key', 'recovered_in_fallback'); + expect(writeSuccess).toBe(true); + expect(service.isUsingFallback()).toBe(true); + expect(fallbackEventSpy).toHaveBeenCalledTimes(1); + + // Both the newly written key AND the previously seeded key should exist in fallback + expect(service.getItem('overflow_key')).toBe('recovered_in_fallback'); + expect(service.getItem('initial_key')).toBe('preserved_state'); + + window.removeEventListener('jct:storage_fallback_active', fallbackEventSpy); + }); + }); +}); diff --git a/src/services/storage/keys.test.js b/src/services/storage/keys.test.js new file mode 100644 index 0000000..9f041ab --- /dev/null +++ b/src/services/storage/keys.test.js @@ -0,0 +1,90 @@ +import { describe, it, expect } from 'vitest'; +import { + STORAGE_KEYS, + COURSE_KEY_PREFIXES, + COURSE_PREFIX_LIST, + LEGACY_STORAGE_KEYS, + SENSITIVE_STORAGE_KEYS, + STORAGE_KEY_REGISTRY, + STORAGE_PREFIX, + TRACKING_VERSION, + getWatchedKey, + getTodayPlanKey, + getSettingsKey, + getHistoryKey, + getStartDateKey, + getStartDateManualKey, + getBadgesKey, + getStreakFreezesKey, + getCompletionKey, + getTrackingKey, +} from './keys.js'; + +describe('Storage Key Registry & Metadata', () => { + it('defines exact static key names with 100% backwards compatibility', () => { + expect(STORAGE_PREFIX).toBe('jct_'); + expect(STORAGE_KEYS.REGISTRY).toBe('jct_course_registry_v1'); + expect(STORAGE_KEYS.NOTIFICATIONS).toBe('jct_notifications_v1'); + expect(STORAGE_KEYS.NOTIFICATION_SETTINGS).toBe('jct_notification_settings_v1'); + expect(STORAGE_KEYS.OPENAI_API_KEY).toBe('jct_openai_api_key_v1'); + expect(STORAGE_KEYS.AI_API_KEYS).toBe('jct_ai_api_keys_v1'); + expect(STORAGE_KEYS.AI_FAB_HIDDEN).toBe('jct_ai_fab_hidden'); + expect(STORAGE_KEYS.MOTIVATION_STORE).toBe('jct_motivation_store_v2'); + expect(STORAGE_KEYS.PREFETCH_COOLDOWN).toBe('jct_prefetch_cooldown_v1'); + expect(STORAGE_KEYS.MOTIVATION_SHOWN).toBe('jct_motivation_shown_v1'); + }); + + it('builds course-isolated namespaced keys matching characterization tests', () => { + const courseId = 'core-java-ai'; + + expect(getWatchedKey(courseId)).toBe('jct_watched__core-java-ai'); + expect(getTodayPlanKey(courseId)).toBe('jct_today_plan__core-java-ai'); + expect(getSettingsKey(courseId)).toBe('jct_settings__core-java-ai'); + expect(getHistoryKey(courseId)).toBe('jct_history__core-java-ai'); + expect(getStartDateKey(courseId)).toBe('jct_start_date__core-java-ai'); + expect(getStartDateManualKey(courseId)).toBe('jct_start_date_manual__core-java-ai'); + expect(getBadgesKey(courseId)).toBe('jct_badges__core-java-ai'); + expect(getStreakFreezesKey(courseId)).toBe('jct_streak_freezes__core-java-ai'); + expect(getCompletionKey(courseId)).toBe('jct_completion__core-java-ai'); + expect(getTrackingKey(courseId)).toBe(`jct_tracking__core-java-ai_${TRACKING_VERSION}`); + }); + + it('exports course prefix list and prefixes object for namespace cleanup', () => { + expect(COURSE_KEY_PREFIXES.WATCHED).toBe('jct_watched__'); + expect(COURSE_KEY_PREFIXES.TODAY_PLAN).toBe('jct_today_plan__'); + expect(COURSE_KEY_PREFIXES.SETTINGS).toBe('jct_settings__'); + expect(COURSE_KEY_PREFIXES.HISTORY).toBe('jct_history__'); + expect(COURSE_KEY_PREFIXES.START_DATE).toBe('jct_start_date__'); + expect(COURSE_KEY_PREFIXES.START_DATE_MANUAL).toBe('jct_start_date_manual__'); + expect(COURSE_KEY_PREFIXES.BADGES).toBe('jct_badges__'); + expect(COURSE_KEY_PREFIXES.STREAK_FREEZES).toBe('jct_streak_freezes__'); + expect(COURSE_KEY_PREFIXES.COMPLETION).toBe('jct_completion__'); + expect(COURSE_KEY_PREFIXES.TRACKING).toBe('jct_tracking__'); + + expect(COURSE_PREFIX_LIST).toContain('jct_watched__'); + expect(COURSE_PREFIX_LIST).toContain('jct_today_plan__'); + expect(COURSE_PREFIX_LIST).toContain('jct_completion__'); + }); + + it('identifies sensitive keys strictly excluded from backup bundles', () => { + 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'); + }); + + it('includes complete schema metadata for all registered keys', () => { + Object.entries(STORAGE_KEY_REGISTRY).forEach(([name, meta]) => { + expect(meta.ownerFeature, `ownerFeature missing for ${name}`).toBeDefined(); + expect(meta.dataShape, `dataShape missing for ${name}`).toBeDefined(); + expect(typeof meta.isSensitive, `isSensitive boolean missing for ${name}`).toBe('boolean'); + expect(typeof meta.isInBackup, `isInBackup boolean missing for ${name}`).toBe('boolean'); + }); + + // Verify critical sensitive keys are flagged as sensitive + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.OPENAI_API_KEY].isSensitive).toBe(true); + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.OPENAI_API_KEY].isInBackup).toBe(false); + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.AI_API_KEYS].isSensitive).toBe(true); + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.AI_API_KEYS].isInBackup).toBe(false); + expect(STORAGE_KEY_REGISTRY['completion'].isSensitive).toBe(true); + }); +}); diff --git a/src/services/storage/storageKeyEnforcement.test.js b/src/services/storage/storageKeyEnforcement.test.js new file mode 100644 index 0000000..a7ff8d3 --- /dev/null +++ b/src/services/storage/storageKeyEnforcement.test.js @@ -0,0 +1,95 @@ +import { describe, it, expect } from 'vitest'; +import fs from 'fs'; +import path from 'path'; +import { + STORAGE_KEYS, + COURSE_KEY_PREFIXES, + LEGACY_STORAGE_KEYS, + SENSITIVE_STORAGE_KEYS, +} from './keys.js'; + +describe('Storage Key Enforcement (Anti-Rot / Anti-Drift Architecture Gate)', () => { + const srcDir = path.resolve(__dirname, '../../'); + + // Collect all known, sanctioned keys and prefixes + const knownKeysAndPrefixes = new Set([ + ...Object.values(STORAGE_KEYS), + ...Object.values(COURSE_KEY_PREFIXES), + ...Object.values(LEGACY_STORAGE_KEYS), + ...SENSITIVE_STORAGE_KEYS, + ]); + + function getSourceFiles(dir) { + const results = []; + const list = fs.readdirSync(dir, { withFileTypes: true }); + + for (const entry of list) { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + // Skip services/storage (where keys are defined) and test directories + if ( + fullPath.includes(path.join('services', 'storage')) || + fullPath.includes(path.join('src', 'tests')) || + entry.name === 'node_modules' || + entry.name === 'dist' + ) { + continue; + } + results.push(...getSourceFiles(fullPath)); + } else if ( + (entry.name.endsWith('.js') || entry.name.endsWith('.jsx')) && + !entry.name.includes('.test.') + ) { + results.push(fullPath); + } + } + return results; + } + + it('prohibits unregistered raw "jct_" storage key literals across all production source files', () => { + const files = getSourceFiles(srcDir); + const violations = []; + + // Regex to match string literals starting with jct_ in code: 'jct_...', "jct_...", `jct_...` + const literalRegex = /['"`](jct_[a-zA-Z0-9_]+)['"`]/g; + + for (const file of files) { + const relativePath = path.relative(srcDir, file).replace(/\\/g, '/'); + const content = fs.readFileSync(file, 'utf-8'); + + // Strip comments (simple heuristic to avoid false positives in JSDoc comments) + const codeWithoutComments = content.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, ''); + + let match; + while ((match = literalRegex.exec(codeWithoutComments)) !== null) { + const foundLiteral = match[1]; + + // Check if the found literal is recognized in the central registry + const isRecognized = + knownKeysAndPrefixes.has(foundLiteral) || + Array.from(knownKeysAndPrefixes).some((k) => foundLiteral.startsWith(k)); + + if (!isRecognized) { + violations.push({ + file: relativePath, + literal: foundLiteral, + }); + } + } + } + + expect( + violations, + `Found unregistered raw storage key literals in production source files. All keys must be registered in src/services/storage/keys.js:\n${JSON.stringify( + violations, + null, + 2 + )}` + ).toEqual([]); + }); + + it('guarantees that all recognized static keys exist in the central registry export', () => { + expect(Object.keys(STORAGE_KEYS).length).toBeGreaterThanOrEqual(9); + expect(Object.keys(COURSE_KEY_PREFIXES).length).toBeGreaterThanOrEqual(10); + }); +});