From 53aa612c2d4223ea3c393a211e490207cd8ed254 Mon Sep 17 00:00:00 2001 From: Sagar Dhadke <70995022+sagardhadke@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:18:46 +0530 Subject: [PATCH 1/2] feat(storage): add schema versioning, migration engine, and rollback safety --- docs/MIGRATIONS.md | 102 +++++ src/main.jsx | 8 + src/services/storage/index.js | 2 + src/services/storage/keys.js | 50 +++ src/services/storage/keys.test.js | 29 ++ .../storage/migrations/migrationRegistry.js | 77 ++++ .../storage/migrations/migrationRunner.js | 384 ++++++++++++++++++ .../migrations/migrationRunner.test.js | 278 +++++++++++++ 8 files changed, 930 insertions(+) create mode 100644 docs/MIGRATIONS.md create mode 100644 src/services/storage/migrations/migrationRegistry.js create mode 100644 src/services/storage/migrations/migrationRunner.js create mode 100644 src/services/storage/migrations/migrationRunner.test.js diff --git a/docs/MIGRATIONS.md b/docs/MIGRATIONS.md new file mode 100644 index 0000000..80fa8e6 --- /dev/null +++ b/docs/MIGRATIONS.md @@ -0,0 +1,102 @@ +# Storage Schema Migrations Guide + +This document describes the schema versioning system, migration engine, and guidelines for adding future storage migrations in Java Course Tracker. + +--- + +## 1. Architecture Overview + +Java Course Tracker uses a lightweight, client-side migration engine to evolve data models safely without data loss or downtime. + +- **Current Schema Version**: Defined in `src/services/storage/migrations/migrationRegistry.js` as `CURRENT_SCHEMA_VERSION`. +- **Global Version Key**: Stored under `jct_schema_version` (registered in `src/services/storage/keys.js`). Unversioned legacy installs are treated as version `0`. +- **Execution Hook**: `runPendingMigrations()` executes synchronously at application startup in `src/main.jsx` before any React components or hooks mount. +- **Backup Parity**: The pure migration pipeline (`migrateDataPayload`) is also run automatically during backup restores (`importAllData`) so that backups from older versions are upgraded cleanly before being restored. + +--- + +## 2. Core Principles & Safety Gates + +### Pure Function Contract +Every migration step implements a pure `up(dataMap)` function: +- Receives a shallow clone of the working key-value map: `dataMap: Record`. +- Returns a new or modified key-value map. +- Operates purely on data; never accesses `window`, `localStorage`, or external side effects directly. + +### Strict Sensitive Key Isolation +Migrations and safety snapshots **MUST NEVER** access, modify, or output sensitive keys: +- Sensitive keys include all API provider keys (`jct_openai_api_key_v1`, `jct_ai_api_keys_v1`, etc.) and cryptographic PIN completion hashes (`jct_completion__*`). +- If a migration returns or modifies any sensitive key identified by `isSensitiveKey(key)`, the validation gate throws an error, aborts execution, and triggers an immediate rollback. + +### Pre-Migration Safety Snapshot +Before running pending migrations: +1. All non-sensitive `jct_` keys are snapshotted into `jct_migration_backup_latest`. +2. If the snapshot write fails (due to storage quota exhaustion or private browsing restrictions), migration execution is skipped, keeping the application safely on its current version. +3. Migrations will **never** run without a verified snapshot. + +### Transactional Rollback +If any migration step throws an unhandled error or outputs invalid data: +1. The pre-migration snapshot is immediately restored to storage. +2. The schema version remains unchanged at the initial version. +3. A non-blocking `jct:migration_error` event is dispatched to surface an error notification without crashing the application. +4. Data is never left in a half-migrated state. + +--- + +## 3. Step-by-Step: Adding a New Migration + +Follow these steps whenever a schema or storage key format changes: + +### Step 1: Increment Schema Version +In `src/services/storage/migrations/migrationRegistry.js`, increment `CURRENT_SCHEMA_VERSION`: +```javascript +export const CURRENT_SCHEMA_VERSION = 2; // e.g. from 1 to 2 +``` + +### Step 2: Register New Storage Keys (if applicable) +If the migration introduces new static keys or prefixes, register them in `src/services/storage/keys.js`: +- Add key to `STORAGE_KEYS` +- Add entry to `STORAGE_KEY_REGISTRY` with `ownerFeature`, `dataShape`, `isSensitive`, and `isInBackup`. + +### Step 3: Append Migration Definition +Append the new migration to `MIGRATIONS` in `src/services/storage/migrations/migrationRegistry.js`: +```javascript +export const MIGRATIONS = Object.freeze([ + { + fromVersion: 0, + toVersion: 1, + description: 'Baseline schema version stamp (v0 to v1)', + up: (dataMap) => ({ ...dataMap }), + }, + { + fromVersion: 1, + toVersion: 2, + description: 'Describe what this migration transforms', + up: (dataMap) => { + const next = { ...dataMap }; + // Example: transform a stored key format + if (next['jct_example_old_key']) { + next['jct_example_new_key'] = next['jct_example_old_key']; + delete next['jct_example_old_key']; + } + return next; + }, + }, +]); +``` + +### Step 4: Add Unit & Integration Tests +In `src/services/storage/migrations/migrationRunner.test.js`: +- Test that `fromVersion -> toVersion` transforms data as expected. +- Test that missing or malformed inputs are handled gracefully. +- Verify that older backup payloads restore correctly through `importAllData()`. + +### Step 5: Verification +Run the complete quality gate before submitting: +```bash +npm test +npm run build +npm audit --audit-level=high +node .github/scripts/forbidden-files-check.js --ci +``` + diff --git a/src/main.jsx b/src/main.jsx index b61bc3f..eb6457f 100644 --- a/src/main.jsx +++ b/src/main.jsx @@ -3,6 +3,14 @@ import { createRoot } from 'react-dom/client'; import './styles/tokens.css'; import App from './App.jsx'; import ErrorBoundary from './components/ErrorBoundary.jsx'; +import { runPendingMigrations } from './services/storage/migrations/migrationRunner.js'; + +// Execute pending storage schema migrations before components mount +try { + runPendingMigrations(); +} catch (err) { + console.error('[App] Storage migration failed at startup:', err); +} createRoot(document.getElementById('root')).render( diff --git a/src/services/storage/index.js b/src/services/storage/index.js index a5dd4cb..e21bfd0 100644 --- a/src/services/storage/index.js +++ b/src/services/storage/index.js @@ -2,3 +2,5 @@ export * from './keys.js'; export * from './StorageDriver.js'; export * from './LocalStorageDriver.js'; export * from './MemoryStorageDriver.js'; +export * from './migrations/migrationRegistry.js'; +export * from './migrations/migrationRunner.js'; diff --git a/src/services/storage/keys.js b/src/services/storage/keys.js index 7fe77cc..6316f50 100644 --- a/src/services/storage/keys.js +++ b/src/services/storage/keys.js @@ -84,6 +84,22 @@ export const STORAGE_KEYS = Object.freeze({ * In Backup: Yes */ MOTIVATION_SHOWN: 'jct_motivation_shown_v1', + + /** + * Owner: storage + * Shape: number (schema version integer, e.g. 1) + * Sensitive: No + * In Backup: Yes + */ + SCHEMA_VERSION: 'jct_schema_version', + + /** + * Owner: storage + * Shape: { timestamp: string, fromVersion: number, data: Record } + * Sensitive: No + * In Backup: NO (Rolling pre-migration safety snapshot) + */ + MIGRATION_BACKUP: 'jct_migration_backup_latest', }); /** @@ -192,6 +208,26 @@ export const SENSITIVE_STORAGE_KEYS = Object.freeze([ 'jct_gemini_api_key', ]); +/** + * Checks whether a storage key is sensitive (contains API credentials, + * secrets, or cryptographic PIN verification hashes). + * + * Sensitive keys: + * - Top-level API keys (OpenAI, Gemini, Anthropic, AI Tutor multi-provider keys) + * - Completion verification state keys (contain PIN hashes and cryptographic salt) + * - Keys matching API key naming conventions + * + * @param {string} key + * @returns {boolean} + */ +export function isSensitiveKey(key) { + if (!key || typeof key !== 'string') return false; + if (SENSITIVE_STORAGE_KEYS.includes(key)) return true; + if (key.startsWith(COURSE_KEY_PREFIXES.COMPLETION)) return true; + if (/^jct_.*(?:api_key|secret|token)/i.test(key)) return true; + return false; +} + /** * Structured metadata registry for all active keys and builders */ @@ -259,6 +295,20 @@ export const STORAGE_KEY_REGISTRY = Object.freeze({ isSensitive: false, isInBackup: true, }, + [STORAGE_KEYS.SCHEMA_VERSION]: { + key: STORAGE_KEYS.SCHEMA_VERSION, + ownerFeature: 'storage', + dataShape: 'number (schema version integer, e.g. 1)', + isSensitive: false, + isInBackup: true, + }, + [STORAGE_KEYS.MIGRATION_BACKUP]: { + key: STORAGE_KEYS.MIGRATION_BACKUP, + ownerFeature: 'storage', + dataShape: '{ timestamp: string, fromVersion: number, data: Record }', + isSensitive: false, + isInBackup: false, + }, 'watched': { builder: getWatchedKey, prefix: COURSE_KEY_PREFIXES.WATCHED, diff --git a/src/services/storage/keys.test.js b/src/services/storage/keys.test.js index 9f041ab..284854c 100644 --- a/src/services/storage/keys.test.js +++ b/src/services/storage/keys.test.js @@ -8,6 +8,7 @@ import { STORAGE_KEY_REGISTRY, STORAGE_PREFIX, TRACKING_VERSION, + isSensitiveKey, getWatchedKey, getTodayPlanKey, getSettingsKey, @@ -32,6 +33,8 @@ describe('Storage Key Registry & Metadata', () => { 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'); + expect(STORAGE_KEYS.SCHEMA_VERSION).toBe('jct_schema_version'); + expect(STORAGE_KEYS.MIGRATION_BACKUP).toBe('jct_migration_backup_latest'); }); it('builds course-isolated namespaced keys matching characterization tests', () => { @@ -86,5 +89,31 @@ describe('Storage Key Registry & Metadata', () => { 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); + + // Verify schema versioning keys metadata + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.SCHEMA_VERSION].isSensitive).toBe(false); + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.SCHEMA_VERSION].isInBackup).toBe(true); + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.MIGRATION_BACKUP].isSensitive).toBe(false); + expect(STORAGE_KEY_REGISTRY[STORAGE_KEYS.MIGRATION_BACKUP].isInBackup).toBe(false); + }); + + it('correctly classifies sensitive vs non-sensitive storage keys with isSensitiveKey', () => { + // Sensitive keys + expect(isSensitiveKey(STORAGE_KEYS.OPENAI_API_KEY)).toBe(true); + expect(isSensitiveKey(STORAGE_KEYS.AI_API_KEYS)).toBe(true); + expect(isSensitiveKey(LEGACY_STORAGE_KEYS.OPENAI_API_KEY)).toBe(true); + expect(isSensitiveKey('jct_completion__course-1')).toBe(true); + expect(isSensitiveKey('jct_anthropic_api_key')).toBe(true); + expect(isSensitiveKey('jct_gemini_api_key')).toBe(true); + + // Non-sensitive keys + expect(isSensitiveKey(STORAGE_KEYS.REGISTRY)).toBe(false); + expect(isSensitiveKey(STORAGE_KEYS.NOTIFICATIONS)).toBe(false); + expect(isSensitiveKey(STORAGE_KEYS.SCHEMA_VERSION)).toBe(false); + expect(isSensitiveKey(STORAGE_KEYS.MIGRATION_BACKUP)).toBe(false); + expect(isSensitiveKey('jct_watched__course-1')).toBe(false); + expect(isSensitiveKey('jct_today_plan__course-1')).toBe(false); + expect(isSensitiveKey('jct_settings__course-1')).toBe(false); + expect(isSensitiveKey('jct_history__course-1')).toBe(false); }); }); diff --git a/src/services/storage/migrations/migrationRegistry.js b/src/services/storage/migrations/migrationRegistry.js new file mode 100644 index 0000000..dbf16c5 --- /dev/null +++ b/src/services/storage/migrations/migrationRegistry.js @@ -0,0 +1,77 @@ +/** + * Migration Registry & Schema Version Configuration + * + * Single source of truth for the active schema version and the ordered + * list of storage migrations. + */ + +/** + * Current application storage schema version. + * Incremented whenever a schema migration is introduced. + */ +export const CURRENT_SCHEMA_VERSION = 1; + +/** + * Validates the contiguous ordering and structure of a migrations list. + * + * Enforces: + * 1. Monotonically increasing version steps (v0 -> v1, v1 -> v2, etc.) + * 2. No version gaps or out-of-order definitions + * 3. Existence of a pure up() function and description + * + * @param {Array<{ fromVersion: number, toVersion: number, description: string, up: Function }>} migrations + * @returns {boolean} + */ +export function validateMigrationList(migrations) { + if (!Array.isArray(migrations)) { + throw new Error('Migrations must be an array'); + } + + for (let i = 0; i < migrations.length; i++) { + const m = migrations[i]; + if (typeof m.fromVersion !== 'number' || typeof m.toVersion !== 'number') { + throw new Error(`Migration at index ${i} has invalid version numbers`); + } + if (m.toVersion !== m.fromVersion + 1) { + throw new Error(`Migration ${m.fromVersion}->${m.toVersion} must advance exactly 1 version`); + } + if (typeof m.up !== 'function') { + throw new Error(`Migration ${m.fromVersion}->${m.toVersion} is missing a pure up() function`); + } + if (typeof m.description !== 'string' || !m.description.trim()) { + throw new Error(`Migration ${m.fromVersion}->${m.toVersion} is missing a description`); + } + if (i > 0 && m.fromVersion !== migrations[i - 1].toVersion) { + throw new Error( + `Migration version gap detected between ${migrations[i - 1].toVersion} and ${m.fromVersion}` + ); + } + } + + return true; +} + +/** + * Ordered list of storage schema migrations. + * + * Pure function contract: + * Each `up(dataMap)` receives a shallow clone of the key-value data map (all non-sensitive `jct_` keys) + * and must return a new or modified key-value data map. + * Migrations MUST NEVER modify or return sensitive keys (e.g. API keys, completion PIN hashes). + */ +export const MIGRATIONS = Object.freeze([ + { + fromVersion: 0, + toVersion: 1, + description: 'Baseline schema version stamp (v0 to v1)', + up: (dataMap) => { + // v0 is legacy unversioned state. + // v1 introduces the schema version key without altering any user data shapes or keys. + return { ...dataMap }; + }, + }, +]); + +// Validate registry configuration +validateMigrationList(MIGRATIONS); + diff --git a/src/services/storage/migrations/migrationRunner.js b/src/services/storage/migrations/migrationRunner.js new file mode 100644 index 0000000..c8a19f6 --- /dev/null +++ b/src/services/storage/migrations/migrationRunner.js @@ -0,0 +1,384 @@ +/** + * Storage Schema Migration Runner & Rollback Engine + * + * Coordinates execution of ordered schema migrations at application startup, + * pre-migration safety snapshots, transactional rollbacks upon failure, + * and pure in-memory migrations for backup payloads. + */ + +import { + STORAGE_KEYS, + STORAGE_PREFIX, + isSensitiveKey, +} from '../keys.js'; +import { + CURRENT_SCHEMA_VERSION, + MIGRATIONS, +} from './migrationRegistry.js'; + +/** + * Normalizes different storage targets (window.localStorage, StorageDriver, or custom test mocks) + * into a uniform synchronous interface. + * + * @param {object} [storage] + * @returns {{ getItem: Function, setItem: Function, removeItem: Function, keys: Function, raw: object }} + */ +export function createStorageAdapter(storage) { + const target = storage || (typeof window !== 'undefined' ? window.localStorage : globalThis.localStorage); + if (!target) { + throw new Error('No storage target available for migration execution.'); + } + + return { + getItem(key) { + if (typeof target.getItem === 'function') return target.getItem(key); + if (typeof target.get === 'function') { + const val = target.get(key); + return typeof val === 'string' ? val : JSON.stringify(val); + } + return null; + }, + setItem(key, value) { + const stringValue = typeof value === 'string' ? value : JSON.stringify(value); + if (typeof target.setItem === 'function') { + return target.setItem(key, stringValue); + } + if (typeof target.set === 'function') { + return target.set(key, stringValue); + } + throw new Error('Storage target does not support setItem or set.'); + }, + removeItem(key) { + if (typeof target.removeItem === 'function') return target.removeItem(key); + if (typeof target.remove === 'function') return target.remove(key); + return false; + }, + keys() { + if (typeof target.keys === 'function') { + const result = target.keys(); + return Array.isArray(result) ? result : Array.from(result); + } + if (typeof target.length === 'number') { + const result = []; + for (let i = 0; i < target.length; i++) { + const k = target.key(i); + if (k) result.push(k); + } + return result; + } + return []; + }, + raw: target, + }; +} + +/** + * Reads the current schema version from storage. + * Unversioned legacy storage defaults to version 0. + * + * @param {object} adapter + * @returns {number} + */ +export function getStoredSchemaVersion(adapter) { + try { + const raw = adapter.getItem(STORAGE_KEYS.SCHEMA_VERSION); + if (raw === null || raw === undefined) return 0; + const parsed = Number(raw); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0; + } catch { + return 0; + } +} + +/** + * Persists the updated schema version into storage. + * + * @param {object} adapter + * @param {number} version + */ +export function setStoredSchemaVersion(adapter, version) { + adapter.setItem(STORAGE_KEYS.SCHEMA_VERSION, String(version)); +} + +/** + * Creates a pre-migration safety snapshot of all non-sensitive app storage keys. + * Rolling: only the latest snapshot is stored under STORAGE_KEYS.MIGRATION_BACKUP. + * + * Security Guarantee: + * Sensitive keys (API keys, cryptographic hashes) are strictly excluded. + * + * @param {object} adapter + * @param {number} fromVersion + * @returns {{ ok: boolean, snapshot?: object, error?: Error }} + */ +export function createMigrationSnapshot(adapter, fromVersion) { + try { + const data = {}; + const allKeys = adapter.keys(); + + for (const key of allKeys) { + if ( + key && + key.startsWith(STORAGE_PREFIX) && + key !== STORAGE_KEYS.MIGRATION_BACKUP && + !isSensitiveKey(key) + ) { + const raw = adapter.getItem(key); + if (raw !== null && raw !== undefined) { + data[key] = raw; + } + } + } + + const snapshot = { + timestamp: new Date().toISOString(), + fromVersion, + data, + }; + + adapter.setItem(STORAGE_KEYS.MIGRATION_BACKUP, JSON.stringify(snapshot)); + return { ok: true, snapshot }; + } catch (err) { + console.warn( + '[MigrationRunner] Failed to persist pre-migration snapshot (quota or storage unavailable):', + err + ); + return { ok: false, error: err }; + } +} + +/** + * Restores a pre-migration safety snapshot upon migration or validation failure. + * Leaves the schema version at fromVersion and dispatches a non-blocking notification. + * + * @param {object} adapter + * @param {object} snapshot + * @param {Error} error + */ +export function restoreMigrationSnapshot(adapter, snapshot, error) { + console.warn( + `[MigrationRunner] Rolling back storage changes to version ${snapshot.fromVersion}:`, + error + ); + + try { + // 1. Remove all non-sensitive keys currently in storage that weren't in snapshot + const allKeys = adapter.keys(); + for (const key of allKeys) { + if ( + key && + key.startsWith(STORAGE_PREFIX) && + key !== STORAGE_KEYS.MIGRATION_BACKUP && + !isSensitiveKey(key) && + !(key in snapshot.data) + ) { + adapter.removeItem(key); + } + } + + // 2. Restore all snapshotted keys + for (const [key, value] of Object.entries(snapshot.data)) { + adapter.setItem(key, value); + } + + // 3. Restore schema version to snapshot.fromVersion + if (snapshot.fromVersion === 0) { + adapter.removeItem(STORAGE_KEYS.SCHEMA_VERSION); + } else { + setStoredSchemaVersion(adapter, snapshot.fromVersion); + } + } catch (restoreErr) { + console.error('[MigrationRunner] Critical error during rollback restore:', restoreErr); + } + + // 4. Dispatch non-blocking error notice to the UI + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') { + try { + window.dispatchEvent( + new CustomEvent('jct:migration_error', { + detail: { + fromVersion: snapshot.fromVersion, + error: error?.message || String(error), + }, + }) + ); + } catch { + // Ignore event dispatch failure in non-DOM environments + } + } +} + +/** + * Validates the output of a migration function. + * + * @param {*} output + * @param {number} fromVersion + * @param {number} toVersion + */ +export function validateMigrationOutput(output, fromVersion, toVersion) { + if (!output || typeof output !== 'object' || Array.isArray(output)) { + throw new Error( + `Migration ${fromVersion}->${toVersion} must return a key-value data map object, got ${typeof output}.` + ); + } + + for (const [key, value] of Object.entries(output)) { + if (isSensitiveKey(key)) { + throw new Error( + `Security Violation: Migration ${fromVersion}->${toVersion} attempted to modify or create sensitive key "${key}". Migrations are strictly forbidden from touching sensitive keys.` + ); + } + if (!key.startsWith(STORAGE_PREFIX)) { + throw new Error( + `Invalid key "${key}" in migration ${fromVersion}->${toVersion}: all keys must begin with "${STORAGE_PREFIX}".` + ); + } + if (typeof value !== 'string') { + throw new Error( + `Invalid value for key "${key}" in migration ${fromVersion}->${toVersion}: value must be a serialized string, got ${typeof value}.` + ); + } + } +} + +/** + * Runs all pending migrations in order at application startup. + * + * Execution flow: + * 1. Checks current stored schema version. + * 2. If up-to-date, completes immediately. + * 3. Snapshots all non-sensitive keys into STORAGE_KEYS.MIGRATION_BACKUP. + * 4. If snapshot write fails, skips migrations and stays on current version. + * 5. Runs migrations sequentially. If any throws or fails validation, rolls back cleanly. + * + * @param {object} [storage] Storage driver or window.localStorage + * @returns {{ applied: number, currentVersion: number, skipped?: boolean, rolledBack?: boolean, error?: Error }} + */ +export function runPendingMigrations(storage) { + const adapter = createStorageAdapter(storage); + const currentVersion = getStoredSchemaVersion(adapter); + + if (currentVersion >= CURRENT_SCHEMA_VERSION) { + return { applied: 0, currentVersion, skipped: false }; + } + + const pending = MIGRATIONS.filter( + (m) => m.fromVersion >= currentVersion && m.toVersion <= CURRENT_SCHEMA_VERSION + ).sort((a, b) => a.fromVersion - b.fromVersion); + + if (pending.length === 0) { + // If no explicit migrations exist up to current, stamp to current version + setStoredSchemaVersion(adapter, CURRENT_SCHEMA_VERSION); + return { applied: 0, currentVersion: CURRENT_SCHEMA_VERSION, skipped: false }; + } + + // Safety snapshot before running the first pending migration + const snapshotResult = createMigrationSnapshot(adapter, currentVersion); + if (!snapshotResult.ok) { + console.warn( + '[MigrationRunner] Skipping storage migrations: pre-migration snapshot could not be saved. App remains on version ' + + currentVersion + + '.' + ); + return { + applied: 0, + currentVersion, + skipped: true, + reason: 'snapshot_failed', + error: snapshotResult.error, + }; + } + + // Load non-sensitive working dataset + let workingDataMap = {}; + for (const [key, value] of Object.entries(snapshotResult.snapshot.data)) { + workingDataMap[key] = value; + } + + let appliedCount = 0; + + for (const migration of pending) { + try { + // Pure up() execution on a clone of the working dataset + const nextDataMap = migration.up({ ...workingDataMap }); + validateMigrationOutput(nextDataMap, migration.fromVersion, migration.toVersion); + + // Apply mutations: remove deleted keys + for (const k of Object.keys(workingDataMap)) { + if (!(k in nextDataMap)) { + adapter.removeItem(k); + } + } + + // Apply mutations: set updated/new keys + for (const [k, v] of Object.entries(nextDataMap)) { + adapter.setItem(k, v); + } + + // Update schema version stamp + setStoredSchemaVersion(adapter, migration.toVersion); + workingDataMap = nextDataMap; + appliedCount++; + } catch (err) { + console.error( + `[MigrationRunner] Migration ${migration.fromVersion}->${migration.toVersion} failed:`, + err + ); + restoreMigrationSnapshot(adapter, snapshotResult.snapshot, err); + return { + applied: appliedCount, + currentVersion, + rolledBack: true, + error: err, + }; + } + } + + return { + applied: appliedCount, + currentVersion: CURRENT_SCHEMA_VERSION, + success: true, + }; +} + +/** + * Pure in-memory migration runner for backup payloads. + * Runs pending migrations on a backup payload's data map without touching physical storage. + * + * @param {Record} dataPayload + * @param {number} fromVersion + * @param {number} [targetVersion=CURRENT_SCHEMA_VERSION] + * @returns {Record} + */ +export function migrateDataPayload(dataPayload, fromVersion, targetVersion = CURRENT_SCHEMA_VERSION) { + if (!dataPayload || typeof dataPayload !== 'object') { + throw new Error('Data payload must be an object.'); + } + + if (fromVersion >= targetVersion) { + return { ...dataPayload }; + } + + const pending = MIGRATIONS.filter( + (m) => m.fromVersion >= fromVersion && m.toVersion <= targetVersion + ).sort((a, b) => a.fromVersion - b.fromVersion); + + let currentMap = { ...dataPayload }; + + for (const migration of pending) { + // Strip sensitive keys from input if any accidentally leaked into the map + const sanitizedInput = {}; + for (const [k, v] of Object.entries(currentMap)) { + if (!isSensitiveKey(k)) { + sanitizedInput[k] = v; + } + } + + const nextMap = migration.up(sanitizedInput); + validateMigrationOutput(nextMap, migration.fromVersion, migration.toVersion); + currentMap = nextMap; + } + + return currentMap; +} + diff --git a/src/services/storage/migrations/migrationRunner.test.js b/src/services/storage/migrations/migrationRunner.test.js new file mode 100644 index 0000000..b15e033 --- /dev/null +++ b/src/services/storage/migrations/migrationRunner.test.js @@ -0,0 +1,278 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + STORAGE_KEYS, + COURSE_KEY_PREFIXES, + isSensitiveKey, +} from '../keys.js'; +import { + CURRENT_SCHEMA_VERSION, + MIGRATIONS, + validateMigrationList, +} from './migrationRegistry.js'; +import { + createStorageAdapter, + getStoredSchemaVersion, + setStoredSchemaVersion, + createMigrationSnapshot, + restoreMigrationSnapshot, + validateMigrationOutput, + runPendingMigrations, + migrateDataPayload, +} from './migrationRunner.js'; + +describe('Storage Migration Engine & Runner', () => { + beforeEach(() => { + localStorage.clear(); + vi.restoreAllMocks(); + }); + + describe('Migration Registry & Ordering Validation', () => { + it('validates contiguous ordering and structure of migration definitions', () => { + expect(validateMigrationList(MIGRATIONS)).toBe(true); + expect(CURRENT_SCHEMA_VERSION).toBe(1); + expect(MIGRATIONS[0].fromVersion).toBe(0); + expect(MIGRATIONS[0].toVersion).toBe(1); + }); + + it('rejects non-contiguous version sequences or gaps', () => { + const gapped = [ + { fromVersion: 0, toVersion: 1, description: 'v0->v1', up: (d) => d }, + { fromVersion: 2, toVersion: 3, description: 'v2->v3', up: (d) => d }, + ]; + expect(() => validateMigrationList(gapped)).toThrow(/gap detected/i); + }); + + it('rejects migrations with multi-step or descending jumps', () => { + const jumping = [ + { fromVersion: 0, toVersion: 2, description: 'v0->v2', up: (d) => d }, + ]; + expect(() => validateMigrationList(jumping)).toThrow(/advance exactly 1 version/i); + }); + + it('rejects migrations without a pure up function or description', () => { + const missingUp = [{ fromVersion: 0, toVersion: 1, description: 'missing up' }]; + expect(() => validateMigrationList(missingUp)).toThrow(/missing a pure up/i); + + const missingDesc = [{ fromVersion: 0, toVersion: 1, up: (d) => d }]; + expect(() => validateMigrationList(missingDesc)).toThrow(/missing a description/i); + }); + }); + + describe('Pre-Migration Snapshot Creation', () => { + it('creates rolling pre-migration snapshot containing all non-sensitive app keys', () => { + localStorage.setItem('jct_course_registry_v1', JSON.stringify(['course-1'])); + localStorage.setItem('jct_watched__course-1', JSON.stringify(['l1', 'l2'])); + localStorage.setItem('unrelated_key', 'should_not_be_snapshotted'); + + const adapter = createStorageAdapter(localStorage); + const result = createMigrationSnapshot(adapter, 0); + + expect(result.ok).toBe(true); + expect(result.snapshot).toBeDefined(); + expect(result.snapshot.fromVersion).toBe(0); + expect(result.snapshot.data['jct_course_registry_v1']).toBe(JSON.stringify(['course-1'])); + expect(result.snapshot.data['jct_watched__course-1']).toBe(JSON.stringify(['l1', 'l2'])); + expect(result.snapshot.data['unrelated_key']).toBeUndefined(); + + // Check persisted snapshot + const rawStored = localStorage.getItem(STORAGE_KEYS.MIGRATION_BACKUP); + expect(rawStored).toBeTruthy(); + const stored = JSON.parse(rawStored); + expect(stored.fromVersion).toBe(0); + expect(stored.data['jct_course_registry_v1']).toBeTruthy(); + }); + + it('strictly excludes sensitive keys from safety snapshots', () => { + const mockOpenAiKey = ['sk', '-proj-snapshot-test-1234'].join(''); + const mockTutorKey = ['sk', '-proj-tutor-test-5678'].join(''); + localStorage.setItem('jct_course_registry_v1', JSON.stringify(['c1'])); + localStorage.setItem('jct_openai_api_key_v1', mockOpenAiKey); + localStorage.setItem('jct_ai_api_keys_v1', JSON.stringify([{ key: mockTutorKey }])); + localStorage.setItem('jct_completion__c1', JSON.stringify({ pinHash: 'hash123', salt: 'salt456' })); + + const adapter = createStorageAdapter(localStorage); + const result = createMigrationSnapshot(adapter, 0); + + expect(result.ok).toBe(true); + expect(result.snapshot.data['jct_course_registry_v1']).toBeDefined(); + expect(result.snapshot.data['jct_openai_api_key_v1']).toBeUndefined(); + expect(result.snapshot.data['jct_ai_api_keys_v1']).toBeUndefined(); + expect(result.snapshot.data['jct_completion__c1']).toBeUndefined(); + }); + }); + + describe('Skip Migration when Snapshot Fails', () => { + it('skips migrations, logs warning, and leaves data and version unchanged when snapshot cannot be saved', () => { + localStorage.setItem('jct_course_registry_v1', JSON.stringify(['course-1'])); + localStorage.setItem('jct_watched__course-1', JSON.stringify(['l1'])); + + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + // Simulate quota error specifically on MIGRATION_BACKUP key + const originalSetItem = Storage.prototype.setItem; + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (k, v) { + if (k === STORAGE_KEYS.MIGRATION_BACKUP) { + const quotaErr = new Error('QuotaExceededError: Storage quota reached'); + quotaErr.name = 'QuotaExceededError'; + throw quotaErr; + } + return originalSetItem.call(this, k, v); + }); + + const res = runPendingMigrations(localStorage); + + expect(res.skipped).toBe(true); + expect(res.reason).toBe('snapshot_failed'); + expect(res.applied).toBe(0); + expect(getStoredSchemaVersion(createStorageAdapter(localStorage))).toBe(0); + expect(localStorage.getItem('jct_course_registry_v1')).toBe(JSON.stringify(['course-1'])); + expect(localStorage.getItem('jct_watched__course-1')).toBe(JSON.stringify(['l1'])); + expect(warnSpy).toHaveBeenCalled(); + }); + }); + + describe('Rollback Engine', () => { + it('rolls back all storage mutations, preserves fromVersion, and dispatches notice when a migration throws', () => { + localStorage.setItem('jct_course_registry_v1', JSON.stringify(['course-alpha'])); + localStorage.setItem('jct_watched__course-alpha', JSON.stringify(['l1'])); + + // Custom test mock storage adapter with a failing migration + const errorEventSpy = vi.fn(); + window.addEventListener('jct:migration_error', errorEventSpy); + + const faultyMigration = { + fromVersion: 0, + toVersion: 1, + description: 'Faulty migration', + up: () => { + throw new Error('Simulated database corruption during migration'); + }, + }; + + const adapter = createStorageAdapter(localStorage); + const snapshotResult = createMigrationSnapshot(adapter, 0); + + try { + faultyMigration.up(); + } catch (err) { + restoreMigrationSnapshot(adapter, snapshotResult.snapshot, err); + } + + // Assert rollback + expect(getStoredSchemaVersion(adapter)).toBe(0); + expect(localStorage.getItem('jct_course_registry_v1')).toBe(JSON.stringify(['course-alpha'])); + expect(localStorage.getItem('jct_watched__course-alpha')).toBe(JSON.stringify(['l1'])); + expect(errorEventSpy).toHaveBeenCalledTimes(1); + expect(errorEventSpy.mock.calls[0][0].detail.error).toContain('Simulated database corruption'); + + window.removeEventListener('jct:migration_error', errorEventSpy); + }); + + it('rolls back when a migration returns invalid output (non-object or non-string values)', () => { + expect(() => validateMigrationOutput(null, 0, 1)).toThrow(/must return a key-value/); + expect(() => validateMigrationOutput(['array_not_allowed'], 0, 1)).toThrow(/must return a key-value/); + expect(() => validateMigrationOutput({ 'jct_foo': 12345 }, 0, 1)).toThrow(/must be a serialized string/); + expect(() => validateMigrationOutput({ 'non_jct_key': 'valid_str' }, 0, 1)).toThrow(/must begin with/); + }); + }); + + describe('Sensitive Key Protection Gate', () => { + it('strictly prohibits any migration from creating or modifying sensitive keys', () => { + const mockKey = ['sk', '-proj-illegal-key'].join(''); + const illegalOutput = { + 'jct_course_registry_v1': JSON.stringify(['course-1']), + 'jct_openai_api_key_v1': mockKey, + }; + + expect(() => validateMigrationOutput(illegalOutput, 0, 1)).toThrow( + /Security Violation: Migration 0->1 attempted to modify or create sensitive key "jct_openai_api_key_v1"/ + ); + }); + + it('prohibits migrations from touching completion PIN hash keys', () => { + const illegalOutput = { + 'jct_completion__course-1': JSON.stringify({ pinHash: 'bad_hash' }), + }; + + expect(() => validateMigrationOutput(illegalOutput, 0, 1)).toThrow( + /Security Violation: Migration 0->1 attempted to modify or create sensitive key "jct_completion__course-1"/ + ); + }); + }); + + describe('Pure In-Memory Payload Migration (migrateDataPayload)', () => { + it('passes payload through migrations in memory without touching physical storage', () => { + const v0Backup = { + 'jct_course_registry_v1': JSON.stringify(['course-x']), + 'jct_watched__course-x': JSON.stringify(['l1']), + }; + + const migrated = migrateDataPayload(v0Backup, 0, 1); + expect(migrated).toEqual(v0Backup); + // localStorage remains untouched + expect(localStorage.length).toBe(0); + }); + + it('returns a clone when fromVersion >= targetVersion', () => { + const data = { 'jct_foo': 'bar' }; + const res = migrateDataPayload(data, 1, 1); + expect(res).toEqual(data); + expect(res).not.toBe(data); + }); + }); + + describe('Baseline v0 to v1 Migration & Real Data Shapes Fixture', () => { + it('stamps schema version 1 on unversioned storage with zero change to existing data shapes', () => { + // Setup comprehensive fixture of all data shapes present in production + const fixtureData = { + 'jct_course_registry_v1': JSON.stringify({ + courseIds: ['core-java', 'custom-1'], + activeCourseId: 'core-java', + customCourses: { 'custom-1': { id: 'custom-1', title: 'Custom 1', sections: [] } }, + }), + 'jct_watched__core-java': JSON.stringify(['l1', 'l2', 'l3']), + 'jct_today_plan__core-java': JSON.stringify(['l4', 'l5']), + 'jct_settings__core-java': JSON.stringify({ dailyTargetHours: 2, streakMode: 'regular', autoPlan: true }), + 'jct_history__core-java': JSON.stringify({ '2026-11-07': { watchedCount: 2, watchedSec: 3600, isPractice: false } }), + 'jct_start_date__core-java': '2026-11-01', + 'jct_start_date_manual__core-java': 'false', + 'jct_badges__core-java': JSON.stringify({ 'first-step': { unlockedAt: '2026-11-01T10:00:00.000Z' } }), + 'jct_streak_freezes__core-java': JSON.stringify({ availableFreezes: 2, usedFreezes: [], freezeHistory: [] }), + 'jct_tracking__core-java_v2': JSON.stringify({ version: 'v2', dailyLog: {}, velocityEWMA: 1.25 }), + 'jct_notifications_v1': JSON.stringify([{ id: 'n1', title: 'Test Alert', type: 'reminder' }]), + 'jct_notification_settings_v1': JSON.stringify({ enabled: true, reminderTime: '19:00' }), + 'jct_ai_fab_hidden': 'false', + }; + + // Populate storage + Object.entries(fixtureData).forEach(([k, v]) => { + localStorage.setItem(k, v); + }); + + // Verify unversioned state before migration + const adapter = createStorageAdapter(localStorage); + expect(getStoredSchemaVersion(adapter)).toBe(0); + + // Run pending migrations + const result = runPendingMigrations(localStorage); + expect(result.success).toBe(true); + expect(result.applied).toBe(1); + expect(result.currentVersion).toBe(1); + + // Verify schema version is now stamped + expect(getStoredSchemaVersion(adapter)).toBe(1); + expect(localStorage.getItem(STORAGE_KEYS.SCHEMA_VERSION)).toBe('1'); + + // Assert that EVERY single key and value in the fixture is 100% untouched + Object.entries(fixtureData).forEach(([k, v]) => { + expect(localStorage.getItem(k), `Data shape mutated for key: ${k}`).toBe(v); + }); + + // Running a second time is a no-op + const reRun = runPendingMigrations(localStorage); + expect(reRun.applied).toBe(0); + expect(reRun.currentVersion).toBe(1); + }); + }); +}); + From 51633bb83ba8f008a31fa4f839d04daa4dc79530 Mon Sep 17 00:00:00 2001 From: Sagar Dhadke <70995022+sagardhadke@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:19:31 +0530 Subject: [PATCH 2/2] feat(backup): add backup import validation, rollback guard, and credential preservation --- src/data/courseStore.js | 91 ++++++++++++++---- .../importAllDataCharacterization.test.js | 95 ++++++++++++++++++- 2 files changed, 165 insertions(+), 21 deletions(-) diff --git a/src/data/courseStore.js b/src/data/courseStore.js index 1a85a81..d4423f8 100644 --- a/src/data/courseStore.js +++ b/src/data/courseStore.js @@ -6,7 +6,10 @@ import { SENSITIVE_STORAGE_KEYS as REGISTRY_SENSITIVE_KEYS, LEGACY_STORAGE_KEYS, STORAGE_PREFIX, + isSensitiveKey, } from '../services/storage/keys.js'; +import { CURRENT_SCHEMA_VERSION } from '../services/storage/migrations/migrationRegistry.js'; +import { migrateDataPayload } from '../services/storage/migrations/migrationRunner.js'; const REGISTRY_KEY = STORAGE_KEYS.REGISTRY; // { courseIds: [...], activeCourseId, customCourses: { [id]: courseObject } } @@ -270,8 +273,11 @@ export function exportAllData({ includeApiKeys = false } = {}) { for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key && key.startsWith(APP_KEY_PREFIX)) { - if (!includeApiKeys && SENSITIVE_STORAGE_KEYS.has(key)) { - continue; // Do not include API key in export + if (key === STORAGE_KEYS.MIGRATION_BACKUP) { + continue; // Strictly exclude rolling pre-migration snapshot from backups + } + if (!includeApiKeys && (SENSITIVE_STORAGE_KEYS.has(key) || isSensitiveKey(key))) { + continue; // Strictly exclude sensitive credentials and hashes from backup } const rawValue = localStorage.getItem(key); const sanitized = includeApiKeys ? rawValue : sanitizeValueForExport(key, rawValue); @@ -283,6 +289,7 @@ export function exportAllData({ includeApiKeys = false } = {}) { return { appName: 'Core Java + AI Lecture Tracker', backupVersion: 1, + schemaVersion: CURRENT_SCHEMA_VERSION, exportedAt: new Date().toISOString(), sanitized: !includeApiKeys, data, @@ -290,35 +297,85 @@ export function exportAllData({ includeApiKeys = false } = {}) { } export function importAllData(backup, { preserveExistingApiKey = true } = {}) { - if (!backup || typeof backup !== 'object' || !backup.data || backup.backupVersion !== 1) { - throw new Error('This file doesn\'t look like a valid backup for this app.'); + // 1. Structural validation of root object + if (!backup || typeof backup !== 'object' || Array.isArray(backup)) { + throw new Error('This file doesn\'t look like a valid backup for this app: backup root must be an object.'); + } + + // 2. Data payload structure validation + if (!backup.data || typeof backup.data !== 'object' || Array.isArray(backup.data)) { + throw new Error('This file doesn\'t look like a valid backup for this app: missing or malformed data payload.'); + } + + // 3. Backup version format check + if (backup.backupVersion !== 1 && typeof backup.schemaVersion !== 'number') { + throw new Error('This file doesn\'t look like a valid backup for this app: unrecognized backup format.'); } - // Preserve existing local API key so restoring a course backup doesn't wipe credentials - let existingApiKey = null; + // 4. Schema version guard: reject newer versions without modifying storage + const backupSchemaVersion = typeof backup.schemaVersion === 'number' ? backup.schemaVersion : 0; + if (backupSchemaVersion > CURRENT_SCHEMA_VERSION) { + throw new Error( + `Backup is from a newer schema version (${backupSchemaVersion}) than supported by this app version (${CURRENT_SCHEMA_VERSION}). Please update the app to restore this backup.` + ); + } + + // 5. Value type and key format validation before touching any existing storage + for (const [key, value] of Object.entries(backup.data)) { + if (typeof key !== 'string' || !key.startsWith(APP_KEY_PREFIX)) { + throw new Error(`Malformed backup data: key "${key}" is invalid. All keys must begin with "${APP_KEY_PREFIX}".`); + } + if (typeof value !== 'string') { + throw new Error(`Malformed backup data: value for key "${key}" must be a string, got ${typeof value}.`); + } + } + + // 6. Run pending migrations on older backups before applying + let dataToRestore = backup.data; + if (backupSchemaVersion < CURRENT_SCHEMA_VERSION) { + dataToRestore = migrateDataPayload(backup.data, backupSchemaVersion, CURRENT_SCHEMA_VERSION); + } + + // 7. Preserve all device sensitive keys (API keys, multi-provider credentials, completion PIN hashes) + const preservedSensitiveEntries = []; if (preserveExistingApiKey) { - existingApiKey = localStorage.getItem(STORAGE_KEYS.OPENAI_API_KEY); + for (let i = 0; i < localStorage.length; i++) { + const k = localStorage.key(i); + if (k && isSensitiveKey(k)) { + const val = localStorage.getItem(k); + if (val !== null && val !== undefined) { + preservedSensitiveEntries.push([k, val]); + } + } + } } - // Clear all existing app keys first, so a restore fully replaces state - // rather than merging with whatever was already there. - const existingKeys = []; + // 8. Clear non-sensitive app keys so restore cleanly replaces application state + const existingAppKeys = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); - if (key && key.startsWith(APP_KEY_PREFIX)) existingKeys.push(key); + if (key && key.startsWith(APP_KEY_PREFIX) && !isSensitiveKey(key)) { + existingAppKeys.push(key); + } } - existingKeys.forEach((k) => localStorage.removeItem(k)); + existingAppKeys.forEach((k) => localStorage.removeItem(k)); - Object.entries(backup.data).forEach(([key, value]) => { - if (key.startsWith(APP_KEY_PREFIX)) { + // 9. Write migrated backup data (strictly disallowing sensitive keys or rolling snapshot) + Object.entries(dataToRestore).forEach(([key, value]) => { + if (key.startsWith(APP_KEY_PREFIX) && !isSensitiveKey(key) && key !== STORAGE_KEYS.MIGRATION_BACKUP) { localStorage.setItem(key, value); } }); - // Restore preserved local API key if the backup did not provide one - if (preserveExistingApiKey && existingApiKey && !backup.data[STORAGE_KEYS.OPENAI_API_KEY]) { - localStorage.setItem(STORAGE_KEYS.OPENAI_API_KEY, existingApiKey); + // 10. Re-assert preserved device sensitive keys + if (preserveExistingApiKey) { + preservedSensitiveEntries.forEach(([k, v]) => { + localStorage.setItem(k, v); + }); } + + // 11. Stamp current schema version into storage + localStorage.setItem(STORAGE_KEYS.SCHEMA_VERSION, String(CURRENT_SCHEMA_VERSION)); } // ---- Memory / storage usage ---- diff --git a/src/tests/importAllDataCharacterization.test.js b/src/tests/importAllDataCharacterization.test.js index 3635b44..c32e6f7 100644 --- a/src/tests/importAllDataCharacterization.test.js +++ b/src/tests/importAllDataCharacterization.test.js @@ -1,5 +1,7 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { exportAllData, importAllData } from '../data/courseStore.js'; +import { STORAGE_KEYS } from '../services/storage/keys.js'; +import { CURRENT_SCHEMA_VERSION } from '../services/storage/migrations/migrationRegistry.js'; describe('importAllData Characterization Tests', () => { beforeEach(() => { @@ -11,17 +13,21 @@ describe('importAllData Characterization Tests', () => { localStorage.setItem('jct_watched__course-1', JSON.stringify(['l1', 'l2'])); localStorage.setItem('jct_openai_api_key_v1', ['sk', '-secret-key-12345'].join('')); localStorage.setItem('jct_ai_api_keys_v1', JSON.stringify({ version: 'v1', keys: {} })); + localStorage.setItem('jct_migration_backup_latest', JSON.stringify({ timestamp: 'now', data: {} })); const backup = exportAllData(); expect(backup).toMatchObject({ appName: 'Core Java + AI Lecture Tracker', backupVersion: 1, + schemaVersion: CURRENT_SCHEMA_VERSION, sanitized: true, }); + expect(backup.exportedAt).toBeDefined(); expect(backup.data['jct_course_registry_v1']).toBeTruthy(); expect(backup.data['jct_watched__course-1']).toBeTruthy(); expect(backup.data['jct_openai_api_key_v1']).toBeUndefined(); expect(backup.data['jct_ai_api_keys_v1']).toBeUndefined(); + expect(backup.data['jct_migration_backup_latest']).toBeUndefined(); }); it('importAllData throws descriptive error on invalid backup payloads', () => { @@ -38,6 +44,7 @@ describe('importAllData Characterization Tests', () => { const backup = { appName: 'Core Java + AI Lecture Tracker', backupVersion: 1, + schemaVersion: 1, data: { 'jct_course_registry_v1': JSON.stringify(['new-course']), 'jct_watched__new-course': JSON.stringify(['new-l1']), @@ -53,15 +60,21 @@ describe('importAllData Characterization Tests', () => { // New backup data written expect(localStorage.getItem('jct_course_registry_v1')).toBe(JSON.stringify(['new-course'])); expect(localStorage.getItem('jct_watched__new-course')).toBe(JSON.stringify(['new-l1'])); + // Schema version stamped + expect(localStorage.getItem(STORAGE_KEYS.SCHEMA_VERSION)).toBe('1'); }); - it('importAllData preserves existing openai API key if backup does not provide one', () => { - const mockPreservedKey = ['sk', '-local-preserved-key-mock'].join(''); - localStorage.setItem('jct_openai_api_key_v1', mockPreservedKey); + it('importAllData preserves all device credentials on restore', () => { + const mockOpenAiKey = ['sk', '-local-preserved-key-mock'].join(''); + const mockTutorKey = ['sk', '-local-tutor-key-mock'].join(''); + localStorage.setItem('jct_openai_api_key_v1', mockOpenAiKey); + localStorage.setItem('jct_ai_api_keys_v1', JSON.stringify([{ id: 'k1', key: mockTutorKey }])); + localStorage.setItem('jct_completion__course-xyz', JSON.stringify({ pinHash: 'hash-abc', salt: 'salt-def' })); const backup = { appName: 'Core Java + AI Lecture Tracker', backupVersion: 1, + schemaVersion: 1, data: { 'jct_course_registry_v1': JSON.stringify(['course-xyz']), }, @@ -69,6 +82,80 @@ describe('importAllData Characterization Tests', () => { importAllData(backup, { preserveExistingApiKey: true }); - expect(localStorage.getItem('jct_openai_api_key_v1')).toBe(mockPreservedKey); + // Assert that OpenAI key, AI Tutor multi-provider keys, and completion verification hashes are ALL preserved + expect(localStorage.getItem('jct_openai_api_key_v1')).toBe(mockOpenAiKey); + expect(localStorage.getItem('jct_ai_api_keys_v1')).toBe(JSON.stringify([{ id: 'k1', key: mockTutorKey }])); + expect(localStorage.getItem('jct_completion__course-xyz')).toBe( + JSON.stringify({ pinHash: 'hash-abc', salt: 'salt-def' }) + ); + }); + + it('importAllData rejects backups from a newer schema version without modifying storage', () => { + localStorage.setItem('jct_watched__safe_course', JSON.stringify(['safe_lecture'])); + + const newerBackup = { + appName: 'Core Java + AI Lecture Tracker', + backupVersion: 1, + schemaVersion: 999, + data: { + 'jct_course_registry_v1': JSON.stringify(['future-course']), + }, + }; + + expect(() => importAllData(newerBackup)).toThrow( + /Backup is from a newer schema version \(999\) than supported by this app version \(1\)/ + ); + + // Existing storage must not be wiped or mutated + expect(localStorage.getItem('jct_watched__safe_course')).toBe(JSON.stringify(['safe_lecture'])); + expect(localStorage.getItem('jct_course_registry_v1')).toBeNull(); + }); + + it('importAllData rejects malformed or tampered backup payloads without wiping existing storage', () => { + localStorage.setItem('jct_watched__existing', JSON.stringify(['keep_this'])); + + // Malformed non-string value in data map + const invalidValueBackup = { + appName: 'Core Java + AI Lecture Tracker', + backupVersion: 1, + schemaVersion: 1, + data: { + 'jct_course_registry_v1': 12345, // Number instead of string + }, + }; + + expect(() => importAllData(invalidValueBackup)).toThrow(/must be a string/); + expect(localStorage.getItem('jct_watched__existing')).toBe(JSON.stringify(['keep_this'])); + + // Malformed key in data map + const invalidKeyBackup = { + appName: 'Core Java + AI Lecture Tracker', + backupVersion: 1, + schemaVersion: 1, + data: { + 'non_jct_key': 'some_value', + }, + }; + + expect(() => importAllData(invalidKeyBackup)).toThrow(/All keys must begin with "jct_"/); + expect(localStorage.getItem('jct_watched__existing')).toBe(JSON.stringify(['keep_this'])); + }); + + it('importAllData migrates older backups (v0 without schemaVersion) before applying them', () => { + const v0LegacyBackup = { + appName: 'Core Java + AI Lecture Tracker', + backupVersion: 1, + // No schemaVersion field (legacy v0) + data: { + 'jct_course_registry_v1': JSON.stringify(['legacy-course']), + 'jct_watched__legacy-course': JSON.stringify(['l1', 'l2']), + }, + }; + + importAllData(v0LegacyBackup); + + expect(localStorage.getItem('jct_course_registry_v1')).toBe(JSON.stringify(['legacy-course'])); + expect(localStorage.getItem('jct_watched__legacy-course')).toBe(JSON.stringify(['l1', 'l2'])); + expect(localStorage.getItem(STORAGE_KEYS.SCHEMA_VERSION)).toBe('1'); }); });