From 43f3891e9effa3e93583a722003b7e69ec7032d3 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Thu, 12 Nov 2026 08:02:57 +0000 Subject: [PATCH] fix: persist default secrets across restarts, auto-relogin on portal expiry, and remove legacy json migration --- public/js/app.js | 8 + public/js/exams.js | 27 ++- public/js/private-lessons.js | 4 + public/js/syllabus.js | 4 + src/server.ts | 333 +++++++++++++++++++++++-------- src/services/db.ts | 305 ++++++++--------------------- src/services/scraper.ts | 211 +++++++++++++++----- src/services/secrets.ts | 192 +++++++++++++----- src/services/session-store.ts | 18 +- test/run-tests.ts | 358 ++++++++++++++-------------------- 10 files changed, 835 insertions(+), 625 deletions(-) diff --git a/public/js/app.js b/public/js/app.js index 1569830..b48867e 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -338,6 +338,10 @@ document.addEventListener('DOMContentLoaded', () => { try { const res = await fetch('/api/sync', { method: 'POST' }); + if (res.status === 401) { + window.location.href = '/'; + return; + } const data = await res.json(); if (data.success) { window.location.reload(); @@ -366,6 +370,10 @@ document.addEventListener('DOMContentLoaded', () => { try { const res = await fetch('/api/sync-all', { method: 'POST' }); + if (res.status === 401) { + window.location.href = '/'; + return; + } const data = await res.json(); if (data.success) { window.location.reload(); diff --git a/public/js/exams.js b/public/js/exams.js index 106d5ba..f05265f 100644 --- a/public/js/exams.js +++ b/public/js/exams.js @@ -117,6 +117,10 @@ document.addEventListener('DOMContentLoaded', () => { method: 'POST', headers: { 'Content-Type': 'application/json' } }); + if (res.status === 401) { + window.location.href = '/'; + return; + } const data = await res.json(); if (data.success) { @@ -169,6 +173,10 @@ document.addEventListener('DOMContentLoaded', () => { try { const res = await fetch(`/api/exams/${encodeURIComponent(examId)}/weaknesses`); + if (res.status === 401) { + window.location.href = '/'; + return; + } const data = await res.json(); weaknessLoading.classList.add('hidden'); @@ -298,11 +306,20 @@ document.addEventListener('DOMContentLoaded', () => { modalLessonPills.innerHTML = ''; try { - // Fetch both Wrong (Y) and Empty (B) questions - const [wrongRes, emptyRes] = await Promise.all([ - fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=Y`).then(r => r.json()), - fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=B`).then(r => r.json()) - ]); + // Fetch Wrong (Y) and Empty (B) questions sequentially to avoid overloading school report server + const wrongResp = await fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=Y`); + if (wrongResp.status === 401) { + window.location.href = '/'; + return; + } + const wrongRes = await wrongResp.json(); + + const emptyResp = await fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=B`); + if (emptyResp.status === 401) { + window.location.href = '/'; + return; + } + const emptyRes = await emptyResp.json(); mistakeLoading.classList.add('hidden'); diff --git a/public/js/private-lessons.js b/public/js/private-lessons.js index 975c59e..ef0dc7c 100644 --- a/public/js/private-lessons.js +++ b/public/js/private-lessons.js @@ -224,6 +224,10 @@ document.addEventListener('DOMContentLoaded', () => { try { const res = await fetch('/api/private-lessons/sync', { method: 'POST' }); + if (res.status === 401) { + window.location.href = '/'; + return; + } const data = await res.json(); if (data.success) { diff --git a/public/js/syllabus.js b/public/js/syllabus.js index a0e67a6..d14a848 100644 --- a/public/js/syllabus.js +++ b/public/js/syllabus.js @@ -96,6 +96,10 @@ document.addEventListener('DOMContentLoaded', () => { try { const res = await fetch('/api/syllabus/sync', { method: 'POST' }); + if (res.status === 401) { + window.location.href = '/'; + return; + } const data = await res.json(); if (data.success) { showAlert(t('syllabus.updatedAlert'), 'info'); diff --git a/src/server.ts b/src/server.ts index b9fbc75..df92ef7 100644 --- a/src/server.ts +++ b/src/server.ts @@ -235,12 +235,97 @@ declare module 'express-session' { interface SessionData { studentId?: string; portalCookies?: string; + portalPassword?: string; studentName?: string; loginAt?: string; } } const weeklySyncInFlight = new Map>(); +const portalReloginInFlight = new Map>(); +const examQuestionsInFlight = new Map>(); + +/** + * Retrieve decryptable student credentials from SQLite or active session. + * Automatically persists session password to SQLite if missing, and deletes zombie undecryptable passwords. + */ +function getStudentCredentials( + studentId: string, + req?: Request +): { studentId: string; password: string } | null { + const currentDb = LocalDatabase.getInstance(); + const creds = currentDb.getRememberedCredentials(studentId); + if (creds && creds.password) { + if (req?.session && !req.session.portalPassword) { + req.session.portalPassword = creds.password; + } + return creds; + } + + const sessionPassword = req?.session?.portalPassword; + if (typeof sessionPassword === 'string' && sessionPassword.length > 0) { + currentDb.saveCredentials(studentId, sessionPassword); + return { studentId, password: sessionPassword }; + } + + return null; +} + +/** + * Re-authenticate with the upstream school portal using stored decryptable credentials. + * Deduplicates concurrent login attempts for the same student. + */ +async function reloginToPortal(studentId: string, req?: Request): Promise { + const existing = portalReloginInFlight.get(studentId); + if (existing) { + const cookies = await existing; + if (cookies && req?.session) { + req.session.portalCookies = cookies; + } + return cookies; + } + + const task = (async (): Promise => { + const creds = getStudentCredentials(studentId, req); + if (!creds) { + return undefined; + } + + const loginRes = await ScraperService.login(creds.studentId, creds.password); + if (loginRes.success && loginRes.cookies) { + if (req?.session) { + req.session.portalCookies = loginRes.cookies; + req.session.studentName = loginRes.studentName || req.session.studentName; + } + return loginRes.cookies; + } + + // If login failed due to invalid credentials (not a 5xx portal maintenance or connection error), + // delete the outdated password to prevent zombie passwords. + const errMsg = String(loginRes.error || '').toLowerCase(); + const isTransientError = + errMsg.includes('maintenance') || + errMsg.includes('connection') || + errMsg.includes('timeout') || + errMsg.includes('500') || + errMsg.includes('502') || + errMsg.includes('503'); + + if (!isTransientError) { + LocalDatabase.getInstance().clearCredentials(studentId); + if (req?.session) { + req.session.portalPassword = undefined; + } + } + + return undefined; + })().finally(() => { + portalReloginInFlight.delete(studentId); + }); + + portalReloginInFlight.set(studentId, task); + return task; +} /** * Determine whether a student's login or cached data predates the start of the current week's Monday (00:00 Istanbul time) @@ -261,11 +346,13 @@ export function shouldTriggerMondayWeeklySync( /** * Automatically sync recent homework, exams, and weekly syllabus when a user's login * was before the start of Monday (00:00 Europe/Istanbul). + * Automatically re-authenticates with stored credentials if the portal session has expired. */ export async function syncWeeklyStudentData( studentId: string, cookies: string, - refDate: Date = new Date() + refDate: Date = new Date(), + req?: Request ): Promise { const existingPromise = weeklySyncInFlight.get(studentId); if (existingPromise) { @@ -275,27 +362,65 @@ export async function syncWeeklyStudentData( const syncTask = (async () => { const currentDb = LocalDatabase.getInstance(); const nowIso = toIstanbulIsoString(refDate); - currentDb.updateLastLogin(studentId, nowIso); + let activeCookies = cookies; + + const runWithPortalRetry = async (fn: (c: string) => Promise): Promise => { + if (!activeCookies) { + const refreshed = await reloginToPortal(studentId, req); + if (!refreshed) { + throw new Error('Session expired. Please log in again.'); + } + activeCookies = refreshed; + } + + try { + return await fn(activeCookies); + } catch (err: any) { + if (ScraperService.isSessionExpiredError(err)) { + if (req?.session) { + req.session.portalCookies = undefined; + } + const refreshed = await reloginToPortal(studentId, req); + if (refreshed) { + activeCookies = refreshed; + return await fn(activeCookies); + } + } + throw err; + } + }; const currentWeek = SyllabusService.getWeekMetadata(refDate); - await Promise.allSettled([ + const results = await Promise.allSettled([ // 1. Sync recent homework (pages 1-2) (async () => { - const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2); + const scrapeRes = await runWithPortalRetry(c => + ScraperService.scrapeMultiplePages(c, studentId, 2) + ); currentDb.mergeAssignments(studentId, scrapeRes.assignments, nowIso); })(), // 2. Sync weekly syllabus (async () => { - const schedule = await ScraperService.scrapeSyllabus(cookies); + const schedule = await runWithPortalRetry(c => ScraperService.scrapeSyllabus(c)); currentDb.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule, nowIso); })(), // 3. Sync exam reports (async () => { - const details = await ScraperService.scrapeAllExamDetails(cookies); - currentDb.saveExamReports(studentId, details, nowIso); + const details = await runWithPortalRetry(c => ScraperService.scrapeAllExamDetails(c)); + if (details.length > 0) { + currentDb.saveExamReports(studentId, details, nowIso); + } })() ]); + + const anySucceeded = results.some(r => r.status === 'fulfilled'); + if (anySucceeded) { + currentDb.updateLastLogin(studentId, nowIso); + if (req?.session) { + req.session.loginAt = nowIso; + } + } })().finally(() => { weeklySyncInFlight.delete(studentId); }); @@ -341,12 +466,40 @@ function requireAuth(req: Request, res: Response, next: NextFunction) { if (req.session && req.session.studentId) { const activeStudentId = req.session.studentId; + const hasStoredCreds = Boolean(getStudentCredentials(activeStudentId, req)); + + // Prevent zombie sessions: if a pre-existing session has neither decryptable credentials + // nor active portal cookies, destroy the session so the user logs in cleanly. + if (!hasStoredCreds && !req.session.portalCookies) { + res.clearCookie('bekultur_student_id'); + req.session.destroy(() => { + if (isAjax) { + res.status(401).json({ success: false, error: 'Session expired. Please log in again.' }); + } else { + res.redirect('/'); + } + }); + return; + } + if (shouldTriggerMondayWeeklySync(activeStudentId, req.session.loginAt)) { getOrRefreshPortalCookies(req, activeStudentId) .then(async (cookies) => { if (cookies) { - await syncWeeklyStudentData(activeStudentId, cookies); - req.session.loginAt = toIstanbulIsoString(); + await syncWeeklyStudentData(activeStudentId, cookies, new Date(), req); + } + // If Monday sync proved portalCookies were expired and no credentials exist to refresh them, + // terminate the zombie session so the user is prompted to log in. + if (!req.session.portalCookies && !getStudentCredentials(activeStudentId, req)) { + res.clearCookie('bekultur_student_id'); + req.session.destroy(() => { + if (isAjax) { + res.status(401).json({ success: false, error: 'Session expired. Please log in again.' }); + } else { + res.redirect('/'); + } + }); + return; } next(); }) @@ -367,11 +520,12 @@ function requireAuth(req: Request, res: Response, next: NextFunction) { if (loginRes.success) { req.session.studentId = creds.studentId; req.session.portalCookies = loginRes.cookies; + req.session.portalPassword = creds.password; req.session.studentName = loginRes.studentName; const nowIso = toIstanbulIsoString(); if (shouldTriggerMondayWeeklySync(creds.studentId, prevLoginAt)) { try { - await syncWeeklyStudentData(creds.studentId, loginRes.cookies); + await syncWeeklyStudentData(creds.studentId, loginRes.cookies, new Date(), req); } catch (syncErr: any) { console.warn('Monday auto-sync warning during auto-login:', syncErr.message); } @@ -394,6 +548,9 @@ function requireAuth(req: Request, res: Response, next: NextFunction) { return res.redirect('/'); }); return; + } else { + // Clear cookie if remembered credentials were purged/absent + res.clearCookie('bekultur_student_id'); } } @@ -410,26 +567,17 @@ function requireAuth(req: Request, res: Response, next: NextFunction) { } /** - * Helper to obtain active portal cookies from session or remembered credentials + * Helper to obtain active portal cookies from session or stored decryptable credentials */ async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise { if (req.session.portalCookies) { return req.session.portalCookies; } - const creds = db.getRememberedCredentials(studentId); - if (creds) { - const loginRes = await ScraperService.login(creds.studentId, creds.password); - if (loginRes.success) { - req.session.portalCookies = loginRes.cookies; - req.session.studentName = loginRes.studentName || req.session.studentName; - return loginRes.cookies; - } - } - return undefined; + return await reloginToPortal(studentId, req); } /** - * Execute scraper action with automatic session-recovery retry + * Execute scraper action with automatic session-recovery retry using stored student credentials */ async function executeWithPortalSession( req: Request, @@ -438,30 +586,27 @@ async function executeWithPortalSession( ): Promise { let cookies = await getOrRefreshPortalCookies(req, studentId); if (!cookies) { + if (req.session) { + req.session.studentId = undefined; + req.session.portalCookies = undefined; + req.session.portalPassword = undefined; + } throw new Error('Session expired. Please log in again.'); } try { return await action(cookies); } catch (err: any) { - const isSessionErr = - err?.message?.includes('Session expired') || - err?.message?.includes('unauthorized') || - err?.message?.includes('girisForm') || - err?.response?.status === 401 || - err?.response?.status === 302; - - if (isSessionErr) { + if (ScraperService.isSessionExpiredError(err)) { req.session.portalCookies = undefined; - const creds = db.getRememberedCredentials(studentId); - if (creds) { - const loginRes = await ScraperService.login(creds.studentId, creds.password); - if (loginRes.success) { - req.session.portalCookies = loginRes.cookies; - req.session.studentName = loginRes.studentName || req.session.studentName; - return await action(loginRes.cookies); - } + const refreshedCookies = await reloginToPortal(studentId, req); + if (refreshedCookies) { + return await action(refreshedCookies); } + // Re-authentication failed or no decryptable credentials exist -> clear zombie session state + req.session.studentId = undefined; + req.session.portalPassword = undefined; + throw new Error('Session expired. Please log in again.'); } throw err; } @@ -531,12 +676,16 @@ app.post('/login', loginLimiter, async (req: Request, res: Response) => { req.session.studentId = cleanStudentId; req.session.portalCookies = loginRes.cookies; + req.session.portalPassword = cleanPassword; req.session.studentName = loginRes.studentName; req.session.loginAt = nowIso; - // Handle "Remember Me" + // Always store the password encrypted in a program-decryptable way so the scraper + // can re-authenticate with https://ogrenci.ozelbursakulturokullari.com/ whenever portalCookies expire. + db.saveCredentials(cleanStudentId, cleanPassword); + + // "Remember Me" controls whether the 30-day persistent browser cookie is set if (rememberMe) { - db.saveCredentials(cleanStudentId, cleanPassword); res.cookie('bekultur_student_id', cleanStudentId, { signed: true, maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days @@ -545,7 +694,6 @@ app.post('/login', loginLimiter, async (req: Request, res: Response) => { secure: process.env.COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'false') }); } else { - db.clearCredentials(cleanStudentId); res.clearCookie('bekultur_student_id'); } @@ -553,7 +701,7 @@ app.post('/login', loginLimiter, async (req: Request, res: Response) => { // sync recent homework, exams, and syllabus automatically. Otherwise sync recent homework. try { if (needsMondaySync) { - await syncWeeklyStudentData(cleanStudentId, loginRes.cookies); + await syncWeeklyStudentData(cleanStudentId, loginRes.cookies, new Date(), req); } else { db.updateLastLogin(cleanStudentId, nowIso); const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2); @@ -1253,54 +1401,71 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo return res.status(404).json({ success: false, error: 'Exam detail not cached' }); } + const inFlightKey = `${studentId}_${cacheKey}`; + try { - const subjectQuestionsList: Array<{ - subjectName: string; - subjectId: string; - questions: any[]; - }> = []; - const allScrapedQuestions: any[] = []; + let fetchPromise = examQuestionsInFlight.get(inFlightKey); + if (!fetchPromise) { + fetchPromise = (async () => { + const subjectQuestionsList: Array<{ + subjectName: string; + subjectId: string; + questions: any[]; + }> = []; + const allScrapedQuestions: any[] = []; - await executeWithPortalSession(req, studentId, async (cookies) => { - for (const subject of exam.subjects) { - const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true; - if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) { - const q = await ScraperService.scrapeExamQuestions( - cookies, - examId, - subject.ogrenciDonemId, - subject.subjectId, - tip - ); - if (q.length > 0) { - const proxiedList = q.map(item => { - item.subjectName = subject.subjectName; - allScrapedQuestions.push({ ...item }); - return { - ...item, - imageUrl: ScraperService.toProxiedImageUrl(item.imageUrl) || item.imageUrl - }; - }); - subjectQuestionsList.push({ - subjectName: subject.subjectName, - subjectId: subject.subjectId, - questions: proxiedList - }); + await executeWithPortalSession(req, studentId, async (cookies) => { + subjectQuestionsList.length = 0; + allScrapedQuestions.length = 0; + + for (const subject of exam.subjects) { + const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true; + if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) { + const q = await ScraperService.scrapeExamQuestions( + cookies, + examId, + subject.ogrenciDonemId, + subject.subjectId, + tip + ); + if (q.length > 0) { + const proxiedList = q.map(item => { + item.subjectName = subject.subjectName; + allScrapedQuestions.push({ ...item }); + return { + ...item, + imageUrl: ScraperService.toProxiedImageUrl(item.imageUrl) || item.imageUrl + }; + }); + subjectQuestionsList.push({ + subjectName: subject.subjectName, + subjectId: subject.subjectId, + questions: proxiedList + }); + } + } } - } - } - return null; - }); + return null; + }); - if (allScrapedQuestions.length > 0) { - db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions); + if (allScrapedQuestions.length > 0) { + db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions); + } + + return { + success: true, + totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0), + subjects: subjectQuestionsList + }; + })().finally(() => { + examQuestionsInFlight.delete(inFlightKey); + }); + + examQuestionsInFlight.set(inFlightKey, fetchPromise); } - res.json({ - success: true, - totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0), - subjects: subjectQuestionsList - }); + const payload = await fetchPromise; + res.json(payload); } catch (err: any) { console.error('Failed to fetch questions:', err.message); const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500; diff --git a/src/services/db.ts b/src/services/db.ts index 12ad964..db74ba2 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -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 diff --git a/src/services/scraper.ts b/src/services/scraper.ts index 1ef3b04..7ba8947 100644 --- a/src/services/scraper.ts +++ b/src/services/scraper.ts @@ -21,6 +21,7 @@ const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com'; const BILGI_BASE_URL = 'https://bilgi.ozelbursakulturokullari.com'; const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; const REQUEST_TIMEOUT_MS = 12000; +const EXAM_QUESTIONS_TIMEOUT_MS = 25000; export interface LoginResult { success: boolean; @@ -35,6 +36,44 @@ export interface ScrapeResult { } export class ScraperService { + /** + * Detect whether an HTTP response from the school portal indicates an expired or unauthenticated session + */ + public static isSessionExpiredResponse(res: { status?: number; data?: any; headers?: any } | null | undefined): boolean { + if (!res) return false; + if (res.status === 401 || res.status === 403) return true; + if (res.status === 302 || res.status === 301) { + const loc = String(res.headers?.location || '').toLowerCase(); + if (!loc || loc.includes('giris') || loc.includes('login')) { + return true; + } + } + if (typeof res.data === 'string') { + if ( + res.data.includes('girisForm') || + res.data.includes('action="/Giris"') || + res.data.includes("action='/Giris'") + ) { + return true; + } + } + return false; + } + + /** + * Check whether an error thrown during scraping represents an expired portal session + */ + public static isSessionExpiredError(err: any): boolean { + const msg = String(err?.message || ''); + return ( + msg.includes('Session expired') || + msg.includes('unauthorized') || + msg.includes('girisForm') || + err?.response?.status === 401 || + err?.response?.status === 302 + ); + } + /** * Normalize portal image URLs (upgrades http:// to https:// and resolves relative paths) */ @@ -246,7 +285,7 @@ export class ScraperService { validateStatus: () => true }); - if (res.status === 302 || res.status === 401 || (typeof res.data === 'string' && res.data.includes('girisForm'))) { + if (this.isSessionExpiredResponse(res)) { throw new Error('Session expired or unauthorized. Please log in again.'); } @@ -350,7 +389,9 @@ export class ScraperService { totalPages }; } catch (err: any) { - console.error(`Error scraping page ${page}:`, err.message); + if (!this.isSessionExpiredError(err)) { + console.error(`Error scraping page ${page}:`, err.message); + } throw err; } } @@ -406,9 +447,14 @@ export class ScraperService { 'Referer': `${BASE_URL}/` }, timeout: REQUEST_TIMEOUT_MS, + maxRedirects: 0, validateStatus: () => true }); + if (this.isSessionExpiredResponse(res)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + if (res.status === 200 && typeof res.data === 'string') { const $ = cheerio.load(res.data); const dayLessons: Lesson[] = []; @@ -464,6 +510,9 @@ export class ScraperService { weeklySchedule[day] = dayLessons; } } catch (err: any) { + if (this.isSessionExpiredError(err)) { + throw err; + } console.error(`Failed to scrape syllabus for day ${day}:`, err.message); } } @@ -488,6 +537,7 @@ export class ScraperService { 'Cookie': cookies }, timeout: REQUEST_TIMEOUT_MS, + maxRedirects: 0, validateStatus: () => true }); @@ -501,6 +551,9 @@ export class ScraperService { try { const res = await client.get(url); + if (this.isSessionExpiredResponse(res)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } if (res.status !== 200 || !res.data) break; const $ = cheerio.load(res.data); @@ -560,6 +613,9 @@ export class ScraperService { currentPage++; } catch (err: any) { + if (this.isSessionExpiredError(err)) { + throw err; + } console.error(`Error scraping private lessons page ${currentPage}:`, err.message); break; } @@ -762,10 +818,14 @@ export class ScraperService { 'User-Agent': USER_AGENT }, timeout: REQUEST_TIMEOUT_MS, - maxRedirects: 5, + maxRedirects: 0, validateStatus: () => true }); + if (this.isSessionExpiredResponse(res)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + if (res.status < 200 || res.status >= 400) { console.error(`GET /rapor/sinav returned status ${res.status}`); return []; @@ -786,6 +846,9 @@ export class ScraperService { return exams; } catch (err: any) { + if (this.isSessionExpiredError(err)) { + throw err; + } console.error('Failed to scrape exam list:', err.message); return []; } @@ -824,10 +887,14 @@ export class ScraperService { 'User-Agent': USER_AGENT }, timeout: REQUEST_TIMEOUT_MS, - maxRedirects: 5, + maxRedirects: 0, validateStatus: () => true }); + if (this.isSessionExpiredResponse(res)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + if (res.status < 200 || res.status >= 400) { console.error(`GET /rapor/sinavkarne/${examId} returned status ${res.status}`); return null; @@ -969,6 +1036,9 @@ export class ScraperService { answerKeyUrl }; } catch (err: any) { + if (this.isSessionExpiredError(err)) { + throw err; + } console.error(`Failed to scrape exam detail ${examId}:`, err.message); return null; } @@ -984,59 +1054,83 @@ export class ScraperService { dersId: string, tip: 'D' | 'Y' | 'B' ): Promise { - try { - const url = `${BILGI_BASE_URL}/ogrencisoruanaliz?sinavId=${encodeURIComponent(sinavId)}&ogrenciDonemId=${encodeURIComponent(ogrenciDonemId)}&dersId=${encodeURIComponent(dersId)}&tip=${encodeURIComponent(tip)}`; + const url = `${BILGI_BASE_URL}/ogrencisoruanaliz?sinavId=${encodeURIComponent(sinavId)}&ogrenciDonemId=${encodeURIComponent(ogrenciDonemId)}&dersId=${encodeURIComponent(dersId)}&tip=${encodeURIComponent(tip)}`; + const maxAttempts = 2; - const res = await axios.get(url, { - headers: { - 'Cookie': cookies, - 'User-Agent': USER_AGENT - }, - timeout: REQUEST_TIMEOUT_MS, - maxRedirects: 5, - validateStatus: () => true - }); + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const res = await axios.get(url, { + headers: { + 'Cookie': cookies, + 'User-Agent': USER_AGENT, + 'Referer': `${BASE_URL}/` + }, + timeout: EXAM_QUESTIONS_TIMEOUT_MS, + maxRedirects: 5, + validateStatus: () => true + }); - if (res.status < 200 || res.status >= 400) { - console.error(`GET ogrencisoruanaliz returned status ${res.status}`); + if (this.isSessionExpiredResponse(res)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + + if (res.status < 200 || res.status >= 400) { + console.error(`GET ogrencisoruanaliz returned status ${res.status}`); + return []; + } + + const $ = cheerio.load(res.data); + const items: ExamQuestionItem[] = []; + + $('.row > div').each((_, el) => { + const text = $(el).find('p.small').text().replace(/\s+/g, ' '); + if (!text) return; + + const noMatch = text.match(/SoruNo:\s*(\d+)/i); + const dogruMatch = text.match(/Doğru\s*Cevap:\s*([A-E\-]+)/i); + const ogrenciMatch = text.match(/Öğrenci\s*Cevap:\s*([A-E\-]+)/i); + + const imgUrl = this.normalizeImageUrl($(el).find('img').attr('src')) || ''; + + const questionNumber = noMatch ? parseInt(noMatch[1], 10) : 0; + const correctAnswer = dogruMatch ? dogruMatch[1].trim() : '-'; + const studentAnswer = ogrenciMatch ? ogrenciMatch[1].trim() : (tip === 'B' ? 'Boş' : '-'); + + const status: 'correct' | 'wrong' | 'empty' = + tip === 'Y' ? 'wrong' : tip === 'B' ? 'empty' : 'correct'; + + items.push({ + questionNumber, + correctAnswer, + studentAnswer, + imageUrl: imgUrl, + status, + subjectId: dersId + }); + }); + + return items; + } catch (err: any) { + if (this.isSessionExpiredError(err)) { + throw err; + } + const isTimeoutOrNetwork = + err?.code === 'ECONNABORTED' || + err?.code === 'ETIMEDOUT' || + err?.code === 'ECONNRESET' || + String(err?.message || '').toLowerCase().includes('timeout'); + + if (isTimeoutOrNetwork && attempt < maxAttempts) { + await new Promise(resolve => setTimeout(resolve, 600)); + continue; + } + + console.error('Failed to scrape exam questions:', err.message); return []; } - - const $ = cheerio.load(res.data); - const items: ExamQuestionItem[] = []; - - $('.row > div').each((_, el) => { - const text = $(el).find('p.small').text().replace(/\s+/g, ' '); - if (!text) return; - - const noMatch = text.match(/SoruNo:\s*(\d+)/i); - const dogruMatch = text.match(/Doğru\s*Cevap:\s*([A-E\-]+)/i); - const ogrenciMatch = text.match(/Öğrenci\s*Cevap:\s*([A-E\-]+)/i); - - const imgUrl = this.normalizeImageUrl($(el).find('img').attr('src')) || ''; - - const questionNumber = noMatch ? parseInt(noMatch[1], 10) : 0; - const correctAnswer = dogruMatch ? dogruMatch[1].trim() : '-'; - const studentAnswer = ogrenciMatch ? ogrenciMatch[1].trim() : (tip === 'B' ? 'Boş' : '-'); - - const status: 'correct' | 'wrong' | 'empty' = - tip === 'Y' ? 'wrong' : tip === 'B' ? 'empty' : 'correct'; - - items.push({ - questionNumber, - correctAnswer, - studentAnswer, - imageUrl: imgUrl, - status, - subjectId: dersId - }); - }); - - return items; - } catch (err: any) { - console.error('Failed to scrape exam questions:', err.message); - return []; } + + return []; } /** @@ -1055,10 +1149,14 @@ export class ScraperService { 'User-Agent': USER_AGENT }, timeout: REQUEST_TIMEOUT_MS, - maxRedirects: 5, + maxRedirects: 0, validateStatus: () => true }); + if (this.isSessionExpiredResponse(getRes)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + const $get = cheerio.load(getRes.data); const token = $get('input[name="__RequestVerificationToken"]').val() as string; @@ -1085,6 +1183,10 @@ export class ScraperService { validateStatus: () => true }); + if (this.isSessionExpiredResponse(postRes)) { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + if (postRes.status < 200 || postRes.status >= 400) { return []; } @@ -1127,6 +1229,9 @@ export class ScraperService { return weaknesses; } catch (err: any) { + if (this.isSessionExpiredError(err)) { + throw err; + } console.error('Failed to scrape topic weaknesses:', err.message); return []; } diff --git a/src/services/secrets.ts b/src/services/secrets.ts index de5076d..de07c33 100644 --- a/src/services/secrets.ts +++ b/src/services/secrets.ts @@ -3,20 +3,32 @@ import path from 'path'; import crypto from 'crypto'; const INSECURE_DEFAULTS = new Set([ + 'bekultur_secret_session_key_change_in_production', 'bekultur_secret_key_change_in_production', 'bekultur_default_secret_key_change_me', + 'change_me', '' ]); -interface StoredSecrets { +export interface StoredSecrets { sessionSecret: string; encryptionSecret: string; createdAt: string; } -let cachedSecrets: StoredSecrets | null = null; +export interface DecryptionResult { + plaintext: string; + usedPrimaryKey: boolean; +} -function getSecretsFilePath(): string { +let cachedSecrets: StoredSecrets | null = null; +let cachedSecretsPath: string | null = null; +const extraCandidateSecrets = new Set(); + +export function getSecretsFilePath(customDataDir?: string): string { + if (customDataDir) { + return path.join(path.resolve(customDataDir), '.secrets.json'); + } const customDbPath = process.env.DB_PATH; const dataDir = customDbPath ? path.dirname(path.resolve(customDbPath)) @@ -24,12 +36,29 @@ function getSecretsFilePath(): string { return path.join(dataDir, '.secrets.json'); } -function loadOrCreateSecrets(): StoredSecrets { - if (cachedSecrets) { +function writeSecretsFile(secretsFile: string, secrets: StoredSecrets): void { + try { + const dir = path.dirname(secretsFile); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + const tmpFile = `${secretsFile}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tmpFile, JSON.stringify(secrets, null, 2), { + encoding: 'utf-8', + mode: 0o600 + }); + fs.renameSync(tmpFile, secretsFile); + } catch (err) { + console.warn('Warning: Failed to persist .secrets.json to disk:', err); + } +} + +export function loadOrCreateSecrets(customDataDir?: string): StoredSecrets { + const secretsFile = getSecretsFilePath(customDataDir); + if (cachedSecrets && cachedSecretsPath === secretsFile) { return cachedSecrets; } - const secretsFile = getSecretsFilePath(); const dir = path.dirname(secretsFile); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); @@ -40,10 +69,13 @@ function loadOrCreateSecrets(): StoredSecrets { const raw = fs.readFileSync(secretsFile, 'utf-8'); const parsed = JSON.parse(raw) as StoredSecrets; if (parsed.sessionSecret && parsed.encryptionSecret) { + extraCandidateSecrets.add(parsed.encryptionSecret); + extraCandidateSecrets.add(parsed.sessionSecret); cachedSecrets = parsed; + cachedSecretsPath = secretsFile; return cachedSecrets; } - } catch (err) { + } catch { console.warn('Warning: Could not read .secrets.json, regenerating secrets.'); } } @@ -54,17 +86,57 @@ function loadOrCreateSecrets(): StoredSecrets { createdAt: new Date().toISOString() }; - try { - fs.writeFileSync(secretsFile, JSON.stringify(generated, null, 2), { - encoding: 'utf-8', - mode: 0o600 - }); - } catch (err) { - console.warn('Warning: Failed to persist .secrets.json to disk:', err); + writeSecretsFile(secretsFile, generated); + extraCandidateSecrets.add(generated.encryptionSecret); + extraCandidateSecrets.add(generated.sessionSecret); + cachedSecrets = generated; + cachedSecretsPath = secretsFile; + return cachedSecrets; +} + +/** + * Synchronize persistent default secrets between data/.secrets.json and SQLite meta table + * so that the generated secret is permanently preserved across all container restarts and rebuilds. + */ +export function syncSecretsWithDatabase( + getMeta: (key: string) => string | undefined, + setMeta: (key: string, value: string) => void, + customDataDir?: string +): StoredSecrets { + const secretsFile = getSecretsFilePath(customDataDir); + const fileSecrets = loadOrCreateSecrets(customDataDir); + + const dbSessionSecret = (getMeta('persistent_session_secret') || '').trim(); + const dbEncryptionSecret = (getMeta('persistent_encryption_secret') || '').trim(); + + if (dbSessionSecret && dbEncryptionSecret) { + extraCandidateSecrets.add(dbEncryptionSecret); + extraCandidateSecrets.add(dbSessionSecret); + extraCandidateSecrets.add(fileSecrets.encryptionSecret); + extraCandidateSecrets.add(fileSecrets.sessionSecret); + + if ( + fileSecrets.sessionSecret !== dbSessionSecret || + fileSecrets.encryptionSecret !== dbEncryptionSecret + ) { + const synced: StoredSecrets = { + sessionSecret: dbSessionSecret, + encryptionSecret: dbEncryptionSecret, + createdAt: getMeta('persistent_secrets_created_at') || fileSecrets.createdAt + }; + writeSecretsFile(secretsFile, synced); + cachedSecrets = synced; + cachedSecretsPath = secretsFile; + return synced; + } + return fileSecrets; } - cachedSecrets = generated; - return cachedSecrets; + // Persist current file secrets into SQLite meta table so both stores stay in lockstep + setMeta('persistent_session_secret', fileSecrets.sessionSecret); + setMeta('persistent_encryption_secret', fileSecrets.encryptionSecret); + setMeta('persistent_secrets_created_at', fileSecrets.createdAt); + return fileSecrets; } /** @@ -93,6 +165,27 @@ export function getEncryptionSecret(): string { return loadOrCreateSecrets().encryptionSecret; } +/** + * Gather all candidate secrets (primary + persistent file/DB + env + historical defaults) + */ +export function getAllCandidateSecrets(): string[] { + const stored = loadOrCreateSecrets(); + const candidates = [ + getEncryptionSecret(), + stored.encryptionSecret, + stored.sessionSecret, + ...Array.from(extraCandidateSecrets), + (process.env.ENCRYPTION_SECRET || '').trim(), + (process.env.CREDENTIAL_SECRET || '').trim(), + (process.env.SESSION_SECRET || '').trim(), + 'bekultur_secret_session_key_change_in_production', + 'bekultur_secret_key_change_in_production', + 'bekultur_default_secret_key_change_me' + ].filter(Boolean); + + return Array.from(new Set(candidates)); +} + /** * Encrypt sensitive text (student passwords, portal cookies) using AES-256-GCM with per-item random salt & IV */ @@ -115,73 +208,78 @@ export function encryptCredential(plaintext: string): string { } /** - * Decrypt stored credential, supporting both v2 (random salt) and legacy v1 (static salt + legacy fallback keys) + * Decrypt stored credential and report whether it was encrypted with the current primary key + * or a legacy/fallback key (so the caller can transparently re-encrypt onto the primary key, + * or delete undecryptable zombie passwords when null is returned). */ -export function decryptCredential(stored: string): string { - if (!stored) return ''; +export function decryptCredentialWithInfo(stored: string): DecryptionResult | null { + if (!stored) return null; if (!stored.startsWith('enc:')) { - // Legacy plaintext support - return stored; + // Legacy plaintext support -> mark usedPrimaryKey: false so it gets encrypted at rest + return { plaintext: stored, usedPrimaryKey: false }; } + const primarySecret = getEncryptionSecret(); + const allSecrets = getAllCandidateSecrets(); + // v2 format: enc:v2:::: if (stored.startsWith('enc:v2:')) { const parts = stored.split(':'); - if (parts.length !== 6) return ''; + if (parts.length !== 6) return null; const [, , saltHex, ivHex, authTagHex, ciphertextHex] = parts; - const candidateSecrets = Array.from( - new Set([ - getEncryptionSecret(), - process.env.ENCRYPTION_SECRET || '', - process.env.SESSION_SECRET || '' - ].filter(Boolean)) - ); - for (const secret of candidateSecrets) { + for (const secret of allSecrets) { try { const key = crypto.scryptSync(secret, Buffer.from(saltHex, 'hex'), 32); const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex')); decipher.setAuthTag(Buffer.from(authTagHex, 'hex')); let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8'); decrypted += decipher.final('utf8'); - return decrypted; + if (decrypted) { + return { + plaintext: decrypted, + usedPrimaryKey: secret === primarySecret + }; + } } catch { // Try next candidate key } } - return ''; + return null; } // Legacy v1 format: enc::: const parts = stored.split(':'); - if (parts.length !== 4) return ''; + if (parts.length !== 4) return null; const [, ivHex, authTagHex, ciphertextHex] = parts; - const legacyCandidateSecrets = Array.from( - new Set([ - getEncryptionSecret(), - process.env.ENCRYPTION_SECRET || '', - process.env.SESSION_SECRET || '', - 'bekultur_secret_key_change_in_production', - 'bekultur_default_secret_key_change_me' - ].filter(Boolean)) - ); - - for (const secret of legacyCandidateSecrets) { + for (const secret of allSecrets) { try { const key = crypto.scryptSync(secret, 'bekultur_credential_salt', 32); const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex')); decipher.setAuthTag(Buffer.from(authTagHex, 'hex')); let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8'); decrypted += decipher.final('utf8'); - return decrypted; + if (decrypted) { + return { + plaintext: decrypted, + usedPrimaryKey: false + }; + } } catch { // Try next candidate secret } } - console.error('Failed to decrypt legacy credential with any known key.'); - return ''; + return null; +} + +/** + * Decrypt stored credential, returning empty string if undecryptable + */ +export function decryptCredential(stored: string): string { + const res = decryptCredentialWithInfo(stored); + return res ? res.plaintext : ''; } export function isModernEncryptedFormat(stored: string): boolean { diff --git a/src/services/session-store.ts b/src/services/session-store.ts index 6729707..ede088f 100644 --- a/src/services/session-store.ts +++ b/src/services/session-store.ts @@ -59,6 +59,9 @@ export class SQLiteSessionStore extends session.Store { if (typeof clone.portalCookies === 'string' && clone.portalCookies.length > 0 && !clone.portalCookies.startsWith('enc:')) { clone.portalCookies = encryptCredential(clone.portalCookies); } + if (typeof clone.portalPassword === 'string' && clone.portalPassword.length > 0 && !clone.portalPassword.startsWith('enc:')) { + clone.portalPassword = encryptCredential(clone.portalPassword); + } return JSON.stringify(clone); } @@ -66,7 +69,20 @@ export class SQLiteSessionStore extends session.Store { try { const parsed = JSON.parse(rawJson); if (typeof parsed.portalCookies === 'string' && parsed.portalCookies.startsWith('enc:')) { - parsed.portalCookies = decryptCredential(parsed.portalCookies); + const decryptedCookies = decryptCredential(parsed.portalCookies); + if (decryptedCookies) { + parsed.portalCookies = decryptedCookies; + } else { + delete parsed.portalCookies; + } + } + if (typeof parsed.portalPassword === 'string' && parsed.portalPassword.startsWith('enc:')) { + const decryptedPass = decryptCredential(parsed.portalPassword); + if (decryptedPass) { + parsed.portalPassword = decryptedPass; + } else { + delete parsed.portalPassword; + } } return parsed as session.SessionData; } catch { diff --git a/test/run-tests.ts b/test/run-tests.ts index a4cf87c..f486836 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -24,10 +24,8 @@ import { Assignment, Lesson, ExamReportDetail } from '../src/types'; // Configure isolated temporary directory BEFORE any server/db singleton initialization const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-')); const testDbPath = path.join(tempDir, 'test-bekultur.db'); -const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json'); process.env.NODE_ENV = 'test'; process.env.DB_PATH = testDbPath; -process.env.LEGACY_JSON_PATH = testLegacyJsonPath; import { shouldTriggerMondayWeeklySync, syncWeeklyStudentData } from '../src/server'; @@ -733,219 +731,6 @@ async function runAllTests() { db.clearCredentials(testId); }); - await test('LocalDatabase: Zero-Data-Loss Migration from legacy db.json to SQLite (preserving v1 credentials & filtering synthetic test records)', () => { - const migJsonPath = path.join(tempDir, 'legacy-db.json'); - const migDbPath = path.join(tempDir, 'migrated-bekultur.db'); - - // Encrypt a password using the legacy v1 scheme (`enc:::` with default legacy key) - const legacyKey = crypto.scryptSync('bekultur_secret_key_change_in_production', 'bekultur_credential_salt', 32); - const iv = crypto.randomBytes(12); - const cipher = crypto.createCipheriv('aes-256-gcm', legacyKey, iv); - let encrypted = cipher.update('MyLegacyPortalPassword99', 'utf8', 'hex'); - encrypted += cipher.final('hex'); - const authTag = cipher.getAuthTag().toString('hex'); - const legacyCiphertext = `enc:${iv.toString('hex')}:${authTag}:${encrypted}`; - - const legacyPayload = { - students: { - '415': { - studentId: '415', - lastSynced: '2026-10-25T12:00:00.000Z', - rememberedCredentials: { - studentId: '415', - password: legacyCiphertext - }, - assignments: { - hw_completed_1: { - id: 'hw_completed_1', - subject: 'AYT Matematik', - type: 'Yayın', - unit: 'Türev', - topic: 'Limit ve Süreklilik', - startDate: '20.10.2026', - endDate: '27.10.2026', - parsedStartDate: '2026-10-20', - parsedEndDate: '2026-10-27', - description: '3D AYT Sayfa 100-120', - detectedCheckDate: '27 ekim', - status: 'completed', - completed: true, - completedAt: '2026-10-24T18:30:00.000Z', - excluded: false - }, - hw_excluded_2: { - id: 'hw_excluded_2', - subject: 'Biyoloji', - type: 'Yayın', - unit: '', - topic: '', - startDate: '20.10.2026', - endDate: '27.10.2026', - parsedStartDate: '2026-10-20', - parsedEndDate: '2026-10-27', - description: 'Diğer şube ödevi', - detectedCheckDate: null, - status: 'active', - completed: false, - completedAt: null, - excluded: true - } - }, - syllabus: { - weekId: '2026-W43', - weekRange: '19.10.2026 - 23.10.2026', - lastSynced: '2026-10-25T12:00:00.000Z', - selectedStation: 'İst-4', - advisoryTeacher: 'CAN TÜRKOĞLU', - days: { 1: [], 2: [], 3: [], 4: [], 5: [] } - }, - privateLessons: { - lastSynced: '2026-10-25T12:00:00.000Z', - detectedAdvisor: 'CAN TÜRKOĞLU', - lessons: [ - { - id: 'pl_legacy_1', - subject: 'Fizik', - teacherName: 'CAN TÜRKOĞLU', - teacherPhoto: null, - date: '26.10.2026', - parsedDate: '2026-10-26', - isUpcoming: true - } - ] - }, - exams: { - lastSynced: '2026-10-25T12:00:00.000Z', - reports: { - '3366': { - summary: { - id: '3366', - name: '12 YKS-04 MF', - examType: 'TYT', - totalQuestions: 120, - totalCorrect: 90, - totalWrong: 16, - totalEmpty: 14, - totalNet: 86.0, - totalScore: 86.0, - generalRank: 7 - }, - subjects: [], - hasAnswerKey: true - } - }, - topicWeaknesses: { - '3366': [ - { - examId: '3366', - examName: '12 YKS-04 MF', - subjectName: 'Fizik', - topicName: 'Optik', - totalCount: 3, - correctCount: 1, - wrongCount: 2, - emptyCount: 0, - successRate: 33 - } - ] - }, - questions: { - '3366_Y': [ - { - questionNumber: 5, - correctAnswer: 'D', - studentAnswer: 'B', - imageUrl: 'https://example.com/q5.png', - status: 'wrong', - subjectId: '14', - subjectName: 'Fizik' - } - ] - } - } - }, - test_student_99999: { - studentId: 'test_student_99999', - lastSynced: null, - assignments: {} - }, - audit_security_student: { - studentId: 'audit_security_student', - lastSynced: null, - assignments: {} - } - } - }; - - fs.writeFileSync(migJsonPath, JSON.stringify(legacyPayload, null, 2), 'utf-8'); - - // Instantiate LocalDatabase pointing to the legacy JSON file - const migratedDb = new LocalDatabase(migDbPath, migJsonPath); - - // 1. Verify backup file was created - assert(fs.existsSync(`${migJsonPath}.bak`), 'Non-destructive backup legacy-db.json.bak must be created'); - - // 2. Verify real student 415 data was 100% preserved - const store415 = migratedDb.getStudentStore('415'); - assert.strictEqual(store415.lastSynced, '2026-10-25T12:00:00.000Z'); - assert(store415.assignments['hw_completed_1'], 'Completed assignment must be migrated'); - assert.strictEqual(store415.assignments['hw_completed_1'].completed, true); - assert.strictEqual(store415.assignments['hw_completed_1'].completedAt, '2026-10-24T18:30:00.000Z'); - assert(store415.assignments['hw_excluded_2'], 'Excluded assignment must be migrated'); - assert.strictEqual(store415.assignments['hw_excluded_2'].excluded, true); - - // 3. Verify legacy v1 encrypted password decrypts seamlessly and was upgraded to v2 at rest - const creds415 = migratedDb.getRememberedCredentials('415'); - assert(creds415 !== null, 'Legacy credentials must be migrated and decryptable'); - assert.strictEqual(creds415.password, 'MyLegacyPortalPassword99'); - - // 4. Verify syllabus, private lessons, and exam reports migrated intact - const syl415 = migratedDb.getSyllabus('415'); - assert.strictEqual(syl415?.selectedStation, 'İst-4'); - assert.strictEqual( migratedDb.getStudentAdvisoryTeacher('415'), 'CAN TÜRKOĞLU'); - - const pl415 = migratedDb.getPrivateLessons('415'); - assert.strictEqual(pl415?.lessons.length, 1); - assert.strictEqual(pl415?.lessons[0].subject, 'Fizik'); - - const exams415 = migratedDb.getExamReports('415'); - assert(exams415?.reports['3366'], 'Exam report 3366 must be migrated'); - assert.strictEqual(exams415?.reports['3366'].summary.totalNet, 86.0); - assert.strictEqual(migratedDb.getTopicWeaknesses('415', '3366')?.[0].topicName, 'Optik'); - assert.strictEqual(migratedDb.getExamQuestions('415', '3366_Y')?.[0].questionNumber, 5); - - // 5. Verify synthetic test_student_* and audit_* records were filtered out - const rowTest = migratedDb - .getSqliteDb() - .prepare('SELECT student_id FROM students WHERE student_id IN (?, ?)') - .all('test_student_99999', 'audit_security_student'); - assert.strictEqual(rowTest.length, 0, 'Synthetic test_student_* and audit_* records must be skipped during migration'); - - // 6. Toggle hw_excluded_2 as completed in SQLite, close DB (simulating container restart), and reopen - migratedDb.toggleAssignment('415', 'hw_excluded_2', true); - migratedDb.close(); - - // Modify legacy db.json (e.g. adding a new student 416 while 415 still has hw_excluded_2 completed: false in JSON) - const updatedLegacy = JSON.parse(fs.readFileSync(migJsonPath, 'utf-8')); - updatedLegacy.students['416'] = { - studentId: '416', - lastSynced: '2026-10-26T10:00:00.000Z', - assignments: {} - }; - fs.writeFileSync(migJsonPath, JSON.stringify(updatedLegacy, null, 2), 'utf-8'); - - const reopenedDb = new LocalDatabase(migDbPath, migJsonPath); - const reopened415 = reopenedDb.getStudentStore('415'); - assert.strictEqual( - reopened415.assignments['hw_excluded_2'].completed, - true, - 'Restart/re-migration must NEVER overwrite newer completed state in SQLite!' - ); - const reopened416 = reopenedDb.getStudentStore('416'); - assert.strictEqual(reopened416.lastSynced, '2026-10-26T10:00:00.000Z', 'Additive migration must import newly added student 416'); - reopenedDb.close(); - }); - await test('SQLiteSessionStore: persists sessions, encrypts portalCookies at rest, and prunes expired sessions', async () => { const db = LocalDatabase.getInstance(); const store = new SQLiteSessionStore({ db: db.getSqliteDb(), pruneIntervalMs: 0 }); @@ -1292,6 +1077,149 @@ async function runAllTests() { } }); + // 14. Persistent Default Secret Generation, Zombie Password Cleanup, and Portal Session Auto-Relogin Tests + await test('Persistent Secrets & Zombie Password Cleanup: preserves generated secret in SQLite meta + .secrets.json across restarts and deletes undecryptable passwords', () => { + const db = LocalDatabase.getInstance(); + const sqlite = db.getSqliteDb(); + + // 1. Verify persistent secrets are stored in SQLite meta table + const sessSecretRow = sqlite + .prepare('SELECT value FROM meta WHERE key = ?') + .get('persistent_session_secret') as { value: string } | undefined; + const encSecretRow = sqlite + .prepare('SELECT value FROM meta WHERE key = ?') + .get('persistent_encryption_secret') as { value: string } | undefined; + + assert(sessSecretRow && sessSecretRow.value.length >= 64, 'Persistent session secret must be stored in SQLite meta'); + assert(encSecretRow && encSecretRow.value.length >= 64, 'Persistent encryption secret must be stored in SQLite meta'); + + // 2. Insert a zombie undecryptable password (encrypted with an unknown random key) + const zombieStudentId = 'audit_zombie_password_student'; + const randomKey = crypto.randomBytes(32); + const randomSalt = crypto.randomBytes(16); + const randomIv = crypto.randomBytes(12); + const zombieCipher = crypto.createCipheriv('aes-256-gcm', randomKey, randomIv); + let zEnc = zombieCipher.update('OldDeadPassword', 'utf8', 'hex'); + zEnc += zombieCipher.final('hex'); + const zTag = zombieCipher.getAuthTag().toString('hex'); + const undecryptablePayload = `enc:v2:${randomSalt.toString('hex')}:${randomIv.toString('hex')}:${zTag}:${zEnc}`; + + db.getStudentStore(zombieStudentId); + sqlite + .prepare('UPDATE students SET remembered_password = ? WHERE student_id = ?') + .run(undecryptablePayload, zombieStudentId); + + // Verify getRememberedCredentials returns null and deletes the zombie password from SQLite + const retrievedZombie = db.getRememberedCredentials(zombieStudentId); + assert.strictEqual(retrievedZombie, null, 'Undecryptable zombie password must return null'); + assert.strictEqual( + db.getRawEncryptedPassword(zombieStudentId), + null, + 'Undecryptable zombie password must be deleted from SQLite' + ); + + // 3. Verify legacy password encrypted with bekultur_secret_session_key_change_in_production is upgraded to primary v2 key + const envDefaultStudentId = 'audit_env_default_student'; + const envDefaultKey = crypto.scryptSync('bekultur_secret_session_key_change_in_production', 'bekultur_credential_salt', 32); + const envIv = crypto.randomBytes(12); + const envCipher = crypto.createCipheriv('aes-256-gcm', envDefaultKey, envIv); + let envEnc = envCipher.update('ValidPortalPass2026', 'utf8', 'hex'); + envEnc += envCipher.final('hex'); + const envTag = envCipher.getAuthTag().toString('hex'); + const envLegacyPayload = `enc:${envIv.toString('hex')}:${envTag}:${envEnc}`; + + db.getStudentStore(envDefaultStudentId); + sqlite + .prepare('UPDATE students SET remembered_password = ? WHERE student_id = ?') + .run(envLegacyPayload, envDefaultStudentId); + + const sanitizeRes = db.sanitizeStoredCredentials(); + assert(sanitizeRes.upgradedCount >= 1, 'sanitizeStoredCredentials must upgrade legacy-key password to primary key'); + + const upgradedRaw = db.getRawEncryptedPassword(envDefaultStudentId); + assert(upgradedRaw && upgradedRaw.startsWith('enc:v2:'), 'Upgraded password must use enc:v2: format'); + const upgradedCreds = db.getRememberedCredentials(envDefaultStudentId); + assert.strictEqual(upgradedCreds?.password, 'ValidPortalPass2026'); + }); + + await test('Portal Session Expiration Recovery: automatically decrypts stored password and re-logs into portal when cookies expire', async () => { + // Verify ScraperService.isSessionExpiredResponse accurately detects 302 login redirects, 401, and girisForm HTML + assert.strictEqual( + ScraperService.isSessionExpiredResponse({ status: 302, headers: { location: '/Giris' } }), + true + ); + assert.strictEqual( + ScraperService.isSessionExpiredResponse({ status: 401 }), + true + ); + assert.strictEqual( + ScraperService.isSessionExpiredResponse({ status: 200, data: '
' }), + true + ); + assert.strictEqual( + ScraperService.isSessionExpiredResponse({ status: 200, data: '
Valid Content
' }), + false + ); + + const db = LocalDatabase.getInstance(); + const studentId = 'relogin_recovery_student_415'; + db.saveCredentials(studentId, 'StoredDecryptablePass!'); + + const origLogin = ScraperService.login; + const origScrapeRecent = ScraperService.scrapeMultiplePages; + const origScrapeExams = ScraperService.scrapeAllExamDetails; + const origScrapeSyllabus = ScraperService.scrapeSyllabus; + + let loginAttempts = 0; + let usedFreshCookies = false; + + ScraperService.login = async (id: string, pass: string) => { + loginAttempts++; + assert.strictEqual(id, studentId); + assert.strictEqual(pass, 'StoredDecryptablePass!'); + return { + success: true, + cookies: 'fresh_portal_cookie=valid123', + studentName: 'Test Student' + }; + }; + + ScraperService.scrapeMultiplePages = async (cookies: string) => { + if (cookies === 'expired_cookie=old') { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + if (cookies === 'fresh_portal_cookie=valid123') { + usedFreshCookies = true; + } + return { totalPages: 1, assignments: [] }; + }; + + ScraperService.scrapeSyllabus = async (cookies: string) => { + if (cookies === 'expired_cookie=old') { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + return { 1: [], 2: [], 3: [], 4: [], 5: [] }; + }; + + ScraperService.scrapeAllExamDetails = async (cookies: string) => { + if (cookies === 'expired_cookie=old') { + throw new Error('Session expired or unauthorized. Please log in again.'); + } + return []; + }; + + try { + await syncWeeklyStudentData(studentId, 'expired_cookie=old', new Date('2026-10-26T09:00:00.000+03:00')); + assert.strictEqual(loginAttempts, 1, 'Concurrent expired tasks must deduplicate to a single portal login call'); + assert.strictEqual(usedFreshCookies, true, 'Scraper must retry with fresh cookies obtained from decrypted credentials'); + } finally { + ScraperService.login = origLogin; + ScraperService.scrapeMultiplePages = origScrapeRecent; + ScraperService.scrapeAllExamDetails = origScrapeExams; + ScraperService.scrapeSyllabus = origScrapeSyllabus; + } + }); + // Optional Live Portal Test (via environment variables only) const testStudentId = process.env.TEST_STUDENT_ID; const testPassword = process.env.TEST_PASSWORD;