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

@ -235,12 +235,97 @@ declare module 'express-session' {
interface SessionData {
studentId?: string;
portalCookies?: string;
portalPassword?: string;
studentName?: string;
loginAt?: string;
}
}
const weeklySyncInFlight = new Map<string, Promise<void>>();
const portalReloginInFlight = new Map<string, Promise<string | undefined>>();
const examQuestionsInFlight = new Map<string, Promise<any>>();
/**
* 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<string | undefined> {
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<string | undefined> => {
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<void> {
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 <T>(fn: (c: string) => Promise<T>): Promise<T> => {
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<string | undefined> {
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<T>(
req: Request,
@ -438,30 +586,27 @@ async function executeWithPortalSession<T>(
): Promise<T> {
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;

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

View file

@ -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<ExamQuestionItem[]> {
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 [];
}

View file

@ -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<string>();
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:<saltHex>:<ivHex>:<authTagHex>:<ciphertextHex>
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:<ivHex>:<authTagHex>:<ciphertextHex>
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 {

View file

@ -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 {