fix: persist default secrets across restarts, auto-relogin on portal expiry, and remove legacy json migration

This commit is contained in:
tyuXX 2026-11-12 08:02:57 +00:00
parent 5d576137ae
commit 43f3891e9e
10 changed files with 835 additions and 625 deletions

View file

@ -2,10 +2,8 @@ import '../utils/time';
import { toIstanbulIsoString } from '../utils/time';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import Database from 'better-sqlite3';
import {
DatabaseSchema,
StudentStore,
Assignment,
PrivateLesson,
@ -19,13 +17,11 @@ import {
} from '../types';
import {
encryptCredential,
decryptCredential
decryptCredentialWithInfo,
syncSecretsWithDatabase
} from './secrets';
const DEFAULT_DB_FILE = path.resolve(process.cwd(), 'data', 'bekultur.db');
const DEFAULT_LEGACY_JSON_FILE = path.resolve(process.cwd(), 'data', 'db.json');
const SYNTHETIC_TEST_ID_REGEX = /^(test_student_|audit_)/i;
interface StudentRow {
student_id: string;
@ -62,22 +58,9 @@ export class LocalDatabase {
private static instance: LocalDatabase | null = null;
private sqlite: Database.Database;
private dbPath: string;
private legacyJsonPath: string;
private skipTestFilter: boolean;
public constructor(
customDbPath?: string,
customLegacyJsonPath?: string,
options?: { skipTestFilter?: boolean }
) {
public constructor(customDbPath?: string) {
this.dbPath = customDbPath || process.env.DB_PATH || DEFAULT_DB_FILE;
const effectiveCustomDb = customDbPath || process.env.DB_PATH;
this.legacyJsonPath =
customLegacyJsonPath ||
process.env.LEGACY_JSON_DB_PATH ||
process.env.LEGACY_JSON_PATH ||
(effectiveCustomDb ? path.join(path.dirname(effectiveCustomDb), 'db.json') : DEFAULT_LEGACY_JSON_FILE);
this.skipTestFilter = options?.skipTestFilter ?? false;
const dir = path.dirname(this.dbPath);
if (!fs.existsSync(dir)) {
@ -86,7 +69,61 @@ export class LocalDatabase {
this.sqlite = new Database(this.dbPath);
this.initSchema();
this.migrateFromLegacyJson();
this.syncPersistentSecrets();
this.sanitizeStoredCredentials();
}
/**
* Synchronize persistent default secrets between SQLite meta table and .secrets.json
*/
private syncPersistentSecrets(): void {
const getMetaStmt = this.sqlite.prepare('SELECT value FROM meta WHERE key = ?');
const setMetaStmt = this.sqlite.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)');
syncSecretsWithDatabase(
(key: string) => {
const row = getMetaStmt.get(key) as { value: string } | undefined;
return row?.value;
},
(key: string, value: string) => {
setMetaStmt.run(key, value);
}
);
}
/**
* Verify all stored passwords on startup:
* - Re-encrypt any valid passwords that were encrypted with legacy/fallback keys onto the persistent primary key
* - Delete any undecryptable / zombie passwords from old unknown secrets so they never trap sessions
*/
public sanitizeStoredCredentials(): { upgradedCount: number; purgedCount: number } {
const stats = { upgradedCount: 0, purgedCount: 0 };
try {
const rows = this.sqlite
.prepare('SELECT student_id, remembered_password FROM students WHERE remembered_password IS NOT NULL')
.all() as Array<{ student_id: string; remembered_password: string }>;
const nowIso = toIstanbulIsoString();
const updateStmt = this.sqlite.prepare(
'UPDATE students SET remembered_password = ?, updated_at = ? WHERE student_id = ?'
);
for (const row of rows) {
const info = decryptCredentialWithInfo(row.remembered_password);
if (info && info.plaintext) {
if (!info.usedPrimaryKey) {
updateStmt.run(encryptCredential(info.plaintext), nowIso, row.student_id);
stats.upgradedCount++;
}
} else {
// Undecryptable zombie password -> delete it immediately
updateStmt.run(null, nowIso, row.student_id);
stats.purgedCount++;
}
}
} catch (err) {
console.error('Error sanitizing stored credentials:', err);
}
return stats;
}
public static getInstance(): LocalDatabase {
@ -175,200 +212,6 @@ export class LocalDatabase {
}
}
/**
* Automatically migrate data from legacy data/db.json into SQLite without losing any student data.
* Preserves a backup at data/db.json.bak and leaves data/db.json intact.
* Uses a SHA-256 content hash so that if db.json is ever restored or updated later,
* any missing records are additively merged without overwriting newer SQLite state.
*/
public migrateFromLegacyJson(): { migratedCount: number; skippedTestCount: number } {
const result = { migratedCount: 0, skippedTestCount: 0 };
if (!fs.existsSync(this.legacyJsonPath)) {
return result;
}
try {
const raw = fs.readFileSync(this.legacyJsonPath, 'utf-8');
const fileHash = crypto.createHash('sha256').update(raw).digest('hex');
const migratedHashRow = this.sqlite
.prepare('SELECT value FROM meta WHERE key = ?')
.get('json_migrated_sha256') as { value: string } | undefined;
if (migratedHashRow && migratedHashRow.value === fileHash) {
return result;
}
const parsed = JSON.parse(raw) as DatabaseSchema;
const studentsMap = parsed?.students || {};
// Backup original db.json before any changes
const backupPath = `${this.legacyJsonPath}.bak`;
if (!fs.existsSync(backupPath)) {
fs.copyFileSync(this.legacyJsonPath, backupPath);
}
const upsertStudentStmt = this.sqlite.prepare(`
INSERT INTO students (
student_id,
last_synced,
remembered_password,
advisory_teacher,
syllabus_json,
private_lessons_json,
exams_json,
updated_at
) VALUES (
@student_id,
@last_synced,
@remembered_password,
@advisory_teacher,
@syllabus_json,
@private_lessons_json,
@exams_json,
@updated_at
)
ON CONFLICT(student_id) DO UPDATE SET
last_synced = COALESCE(students.last_synced, excluded.last_synced),
remembered_password = COALESCE(students.remembered_password, excluded.remembered_password),
advisory_teacher = COALESCE(students.advisory_teacher, excluded.advisory_teacher),
syllabus_json = COALESCE(students.syllabus_json, excluded.syllabus_json),
private_lessons_json = COALESCE(students.private_lessons_json, excluded.private_lessons_json),
exams_json = COALESCE(students.exams_json, excluded.exams_json),
updated_at = excluded.updated_at
`);
const upsertAssignmentStmt = this.sqlite.prepare(`
INSERT INTO assignments (
student_id,
id,
subject,
type,
unit,
topic,
start_date,
end_date,
parsed_start_date,
parsed_end_date,
description,
detected_check_date,
status,
completed,
completed_at,
excluded,
page
) VALUES (
@student_id,
@id,
@subject,
@type,
@unit,
@topic,
@start_date,
@end_date,
@parsed_start_date,
@parsed_end_date,
@description,
@detected_check_date,
@status,
@completed,
@completed_at,
@excluded,
@page
)
ON CONFLICT(student_id, id) DO UPDATE SET
subject = COALESCE(NULLIF(assignments.subject, ''), excluded.subject),
type = COALESCE(NULLIF(assignments.type, ''), excluded.type),
unit = COALESCE(NULLIF(assignments.unit, ''), excluded.unit),
topic = COALESCE(NULLIF(assignments.topic, ''), excluded.topic),
start_date = COALESCE(NULLIF(assignments.start_date, ''), excluded.start_date),
end_date = COALESCE(NULLIF(assignments.end_date, ''), excluded.end_date),
parsed_start_date = COALESCE(assignments.parsed_start_date, excluded.parsed_start_date),
parsed_end_date = COALESCE(assignments.parsed_end_date, excluded.parsed_end_date),
description = COALESCE(NULLIF(assignments.description, ''), excluded.description),
detected_check_date = COALESCE(assignments.detected_check_date, excluded.detected_check_date),
status = CASE WHEN assignments.completed = 1 OR excluded.completed = 1 THEN 'completed' ELSE assignments.status END,
completed = CASE WHEN assignments.completed = 1 OR excluded.completed = 1 THEN 1 ELSE 0 END,
completed_at = COALESCE(assignments.completed_at, excluded.completed_at),
excluded = CASE WHEN assignments.excluded = 1 OR excluded.excluded = 1 THEN 1 ELSE 0 END,
page = COALESCE(assignments.page, excluded.page)
`);
const setMetaStmt = this.sqlite.prepare(`
INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)
`);
const nowIso = toIstanbulIsoString();
const runMigration = this.sqlite.transaction(() => {
for (const [studentId, store] of Object.entries(studentsMap)) {
if (!studentId || !store) continue;
if (!this.skipTestFilter && SYNTHETIC_TEST_ID_REGEX.test(studentId)) {
result.skippedTestCount++;
continue;
}
let encryptedPassword: string | null = null;
if (store.rememberedCredentials?.password) {
const plain = decryptCredential(store.rememberedCredentials.password);
if (plain) {
encryptedPassword = encryptCredential(plain);
}
}
upsertStudentStmt.run({
student_id: studentId,
last_synced: store.lastSynced || null,
remembered_password: encryptedPassword,
advisory_teacher: store.advisoryTeacher || store.privateLessons?.detectedAdvisor || null,
syllabus_json: store.syllabus ? JSON.stringify(store.syllabus) : null,
private_lessons_json: store.privateLessons ? JSON.stringify(store.privateLessons) : null,
exams_json: store.exams ? JSON.stringify(store.exams) : null,
updated_at: nowIso
});
const assignments = store.assignments ? Object.values(store.assignments) : [];
for (const a of assignments) {
if (!a || !a.id) continue;
upsertAssignmentStmt.run({
student_id: studentId,
id: a.id,
subject: a.subject || 'Genel',
type: a.type || 'Ödev',
unit: a.unit || '',
topic: a.topic || '',
start_date: a.startDate || '',
end_date: a.endDate || '',
parsed_start_date: a.parsedStartDate || null,
parsed_end_date: a.parsedEndDate || null,
description: a.description || '',
detected_check_date: a.detectedCheckDate || null,
status: a.status || 'active',
completed: a.completed ? 1 : 0,
completed_at: a.completedAt || null,
excluded: a.excluded ? 1 : 0,
page: a.page ?? null
});
}
result.migratedCount++;
}
setMetaStmt.run('json_migrated_at', nowIso);
setMetaStmt.run('json_migrated_sha256', fileHash);
setMetaStmt.run('schema_version', '2');
});
runMigration();
} catch (err) {
console.error('Error migrating legacy db.json to SQLite:', err);
}
return result;
}
private ensureStudentRow(studentId: string): StudentRow {
const existing = this.sqlite
.prepare('SELECT * FROM students WHERE student_id = ?')
@ -670,12 +513,25 @@ export class LocalDatabase {
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
.get(studentId) as { remembered_password: string | null } | undefined;
if (!row?.remembered_password) return null;
const decrypted = decryptCredential(row.remembered_password);
if (!decrypted) return null;
if (!row?.remembered_password) {
return null;
}
const info = decryptCredentialWithInfo(row.remembered_password);
if (!info || !info.plaintext) {
// Delete undecryptable / old-secret password immediately to prevent zombie passwords
this.clearCredentials(studentId);
return null;
}
if (!info.usedPrimaryKey) {
// Upgrade to canonical persistent secret
this.saveCredentials(studentId, info.plaintext);
}
return {
studentId,
password: decrypted
password: info.plaintext
};
}
@ -698,13 +554,22 @@ export class LocalDatabase {
const existingStation = existingSyllabus?.selectedStation || null;
const now = syncedAt || toIstanbulIsoString();
const hasNewLessons =
schedule &&
Object.values(schedule).some(arr => Array.isArray(arr) && arr.length > 0);
const hasExistingLessons =
existingSyllabus?.schedule &&
Object.values(existingSyllabus.schedule).some(arr => Array.isArray(arr) && arr.length > 0);
const effectiveSchedule = !hasNewLessons && hasExistingLessons ? existingSyllabus!.schedule : schedule;
const syllabus: SyllabusStore = {
weekId,
weekRange,
selectedStation: existingStation,
advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null,
lastSynced: now,
schedule
schedule: effectiveSchedule
};
this.sqlite