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
102 changes: 102 additions & 0 deletions docs/MIGRATIONS.md
Original file line number Diff line number Diff line change
@@ -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<string, string>`.
- 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
```

91 changes: 74 additions & 17 deletions src/data/courseStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }

Expand Down Expand Up @@ -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);
Expand All @@ -283,42 +289,93 @@ 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,
};
}

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 ----
Expand Down
8 changes: 8 additions & 0 deletions src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<StrictMode>
Expand Down
2 changes: 2 additions & 0 deletions src/services/storage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
50 changes: 50 additions & 0 deletions src/services/storage/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> }
* Sensitive: No
* In Backup: NO (Rolling pre-migration safety snapshot)
*/
MIGRATION_BACKUP: 'jct_migration_backup_latest',
});

/**
Expand Down Expand Up @@ -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
*/
Expand Down Expand Up @@ -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<string, string> }',
isSensitive: false,
isInBackup: false,
},
'watched': {
builder: getWatchedKey,
prefix: COURSE_KEY_PREFIXES.WATCHED,
Expand Down
29 changes: 29 additions & 0 deletions src/services/storage/keys.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
STORAGE_KEY_REGISTRY,
STORAGE_PREFIX,
TRACKING_VERSION,
isSensitiveKey,
getWatchedKey,
getTodayPlanKey,
getSettingsKey,
Expand All @@ -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', () => {
Expand Down Expand Up @@ -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);
});
});
Loading
Loading