Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 30 additions & 26 deletions src/data/courseStore.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 ----
Expand All @@ -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.
Expand All @@ -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') {
Expand Down Expand Up @@ -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
Expand All @@ -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);
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/features/ai-tutor/models/apiKeyStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
3 changes: 2 additions & 1 deletion src/features/ai-tutor/views/AiTutorFloatingButton.jsx
Original file line number Diff line number Diff line change
@@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/features/course/models/courseCompletionModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -214,7 +216,7 @@
if (!courseId || typeof localStorage === 'undefined') return;
try {
// Strip plaintext PIN before persisting
const { pin, ...secureState } = state || {};

Check warning on line 219 in src/features/course/models/courseCompletionModel.js

View workflow job for this annotation

GitHub Actions / Lint, Test & Production Build

eslint(no-unused-vars)

src/features/course/models/courseCompletionModel.js:219:13: Variable 'pin' is declared but never used. Unused variables should start with a '_'.
localStorage.setItem(COMPLETION_KEY_PREFIX + courseId, JSON.stringify(secureState));
} catch {
// ignore quota errors
Expand Down
6 changes: 4 additions & 2 deletions src/features/motivation/models/apiKeyModel.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
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 {
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('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();
Expand Down
5 changes: 3 additions & 2 deletions src/features/motivation/models/motivationModel.js
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 4 additions & 2 deletions src/features/notifications/models/notificationModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
3 changes: 2 additions & 1 deletion src/features/streak/models/activityHistoryModel.js
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;

Expand Down
11 changes: 4 additions & 7 deletions src/features/tracking/models/learningTrackerModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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;
Expand Down
28 changes: 19 additions & 9 deletions src/hooks/useCourseProgress.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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;
});
Expand Down
Loading
Loading