fix: persist default secrets across restarts, auto-relogin on portal expiry, and remove legacy json migration
This commit is contained in:
parent
5d576137ae
commit
43f3891e9e
10 changed files with 835 additions and 625 deletions
|
|
@ -338,6 +338,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/sync', { method: 'POST' });
|
const res = await fetch('/api/sync', { method: 'POST' });
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
|
|
@ -366,6 +370,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/sync-all', { method: 'POST' });
|
const res = await fetch('/api/sync-all', { method: 'POST' });
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
|
|
|
||||||
|
|
@ -117,6 +117,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' }
|
headers: { 'Content-Type': 'application/json' }
|
||||||
});
|
});
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
|
|
@ -169,6 +173,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/exams/${encodeURIComponent(examId)}/weaknesses`);
|
const res = await fetch(`/api/exams/${encodeURIComponent(examId)}/weaknesses`);
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
weaknessLoading.classList.add('hidden');
|
weaknessLoading.classList.add('hidden');
|
||||||
|
|
||||||
|
|
@ -298,11 +306,20 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
modalLessonPills.innerHTML = '';
|
modalLessonPills.innerHTML = '';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Fetch both Wrong (Y) and Empty (B) questions
|
// Fetch Wrong (Y) and Empty (B) questions sequentially to avoid overloading school report server
|
||||||
const [wrongRes, emptyRes] = await Promise.all([
|
const wrongResp = await fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=Y`);
|
||||||
fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=Y`).then(r => r.json()),
|
if (wrongResp.status === 401) {
|
||||||
fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=B`).then(r => r.json())
|
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');
|
mistakeLoading.classList.add('hidden');
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -224,6 +224,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/private-lessons/sync', { method: 'POST' });
|
const res = await fetch('/api/private-lessons/sync', { method: 'POST' });
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
|
|
|
||||||
|
|
@ -96,6 +96,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/syllabus/sync', { method: 'POST' });
|
const res = await fetch('/api/syllabus/sync', { method: 'POST' });
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
showAlert(t('syllabus.updatedAlert'), 'info');
|
showAlert(t('syllabus.updatedAlert'), 'info');
|
||||||
|
|
|
||||||
249
src/server.ts
249
src/server.ts
|
|
@ -235,12 +235,97 @@ declare module 'express-session' {
|
||||||
interface SessionData {
|
interface SessionData {
|
||||||
studentId?: string;
|
studentId?: string;
|
||||||
portalCookies?: string;
|
portalCookies?: string;
|
||||||
|
portalPassword?: string;
|
||||||
studentName?: string;
|
studentName?: string;
|
||||||
loginAt?: string;
|
loginAt?: string;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const weeklySyncInFlight = new Map<string, Promise<void>>();
|
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)
|
* 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
|
* Automatically sync recent homework, exams, and weekly syllabus when a user's login
|
||||||
* was before the start of Monday (00:00 Europe/Istanbul).
|
* 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(
|
export async function syncWeeklyStudentData(
|
||||||
studentId: string,
|
studentId: string,
|
||||||
cookies: string,
|
cookies: string,
|
||||||
refDate: Date = new Date()
|
refDate: Date = new Date(),
|
||||||
|
req?: Request
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const existingPromise = weeklySyncInFlight.get(studentId);
|
const existingPromise = weeklySyncInFlight.get(studentId);
|
||||||
if (existingPromise) {
|
if (existingPromise) {
|
||||||
|
|
@ -275,27 +362,65 @@ export async function syncWeeklyStudentData(
|
||||||
const syncTask = (async () => {
|
const syncTask = (async () => {
|
||||||
const currentDb = LocalDatabase.getInstance();
|
const currentDb = LocalDatabase.getInstance();
|
||||||
const nowIso = toIstanbulIsoString(refDate);
|
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);
|
const currentWeek = SyllabusService.getWeekMetadata(refDate);
|
||||||
|
|
||||||
await Promise.allSettled([
|
const results = await Promise.allSettled([
|
||||||
// 1. Sync recent homework (pages 1-2)
|
// 1. Sync recent homework (pages 1-2)
|
||||||
(async () => {
|
(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);
|
currentDb.mergeAssignments(studentId, scrapeRes.assignments, nowIso);
|
||||||
})(),
|
})(),
|
||||||
// 2. Sync weekly syllabus
|
// 2. Sync weekly syllabus
|
||||||
(async () => {
|
(async () => {
|
||||||
const schedule = await ScraperService.scrapeSyllabus(cookies);
|
const schedule = await runWithPortalRetry(c => ScraperService.scrapeSyllabus(c));
|
||||||
currentDb.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule, nowIso);
|
currentDb.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule, nowIso);
|
||||||
})(),
|
})(),
|
||||||
// 3. Sync exam reports
|
// 3. Sync exam reports
|
||||||
(async () => {
|
(async () => {
|
||||||
const details = await ScraperService.scrapeAllExamDetails(cookies);
|
const details = await runWithPortalRetry(c => ScraperService.scrapeAllExamDetails(c));
|
||||||
|
if (details.length > 0) {
|
||||||
currentDb.saveExamReports(studentId, details, nowIso);
|
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(() => {
|
})().finally(() => {
|
||||||
weeklySyncInFlight.delete(studentId);
|
weeklySyncInFlight.delete(studentId);
|
||||||
});
|
});
|
||||||
|
|
@ -341,12 +466,40 @@ function requireAuth(req: Request, res: Response, next: NextFunction) {
|
||||||
|
|
||||||
if (req.session && req.session.studentId) {
|
if (req.session && req.session.studentId) {
|
||||||
const activeStudentId = 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)) {
|
if (shouldTriggerMondayWeeklySync(activeStudentId, req.session.loginAt)) {
|
||||||
getOrRefreshPortalCookies(req, activeStudentId)
|
getOrRefreshPortalCookies(req, activeStudentId)
|
||||||
.then(async (cookies) => {
|
.then(async (cookies) => {
|
||||||
if (cookies) {
|
if (cookies) {
|
||||||
await syncWeeklyStudentData(activeStudentId, cookies);
|
await syncWeeklyStudentData(activeStudentId, cookies, new Date(), req);
|
||||||
req.session.loginAt = toIstanbulIsoString();
|
}
|
||||||
|
// 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();
|
next();
|
||||||
})
|
})
|
||||||
|
|
@ -367,11 +520,12 @@ function requireAuth(req: Request, res: Response, next: NextFunction) {
|
||||||
if (loginRes.success) {
|
if (loginRes.success) {
|
||||||
req.session.studentId = creds.studentId;
|
req.session.studentId = creds.studentId;
|
||||||
req.session.portalCookies = loginRes.cookies;
|
req.session.portalCookies = loginRes.cookies;
|
||||||
|
req.session.portalPassword = creds.password;
|
||||||
req.session.studentName = loginRes.studentName;
|
req.session.studentName = loginRes.studentName;
|
||||||
const nowIso = toIstanbulIsoString();
|
const nowIso = toIstanbulIsoString();
|
||||||
if (shouldTriggerMondayWeeklySync(creds.studentId, prevLoginAt)) {
|
if (shouldTriggerMondayWeeklySync(creds.studentId, prevLoginAt)) {
|
||||||
try {
|
try {
|
||||||
await syncWeeklyStudentData(creds.studentId, loginRes.cookies);
|
await syncWeeklyStudentData(creds.studentId, loginRes.cookies, new Date(), req);
|
||||||
} catch (syncErr: any) {
|
} catch (syncErr: any) {
|
||||||
console.warn('Monday auto-sync warning during auto-login:', syncErr.message);
|
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 res.redirect('/');
|
||||||
});
|
});
|
||||||
return;
|
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> {
|
async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise<string | undefined> {
|
||||||
if (req.session.portalCookies) {
|
if (req.session.portalCookies) {
|
||||||
return req.session.portalCookies;
|
return req.session.portalCookies;
|
||||||
}
|
}
|
||||||
const creds = db.getRememberedCredentials(studentId);
|
return await reloginToPortal(studentId, req);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute scraper action with automatic session-recovery retry
|
* Execute scraper action with automatic session-recovery retry using stored student credentials
|
||||||
*/
|
*/
|
||||||
async function executeWithPortalSession<T>(
|
async function executeWithPortalSession<T>(
|
||||||
req: Request,
|
req: Request,
|
||||||
|
|
@ -438,30 +586,27 @@ async function executeWithPortalSession<T>(
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
let cookies = await getOrRefreshPortalCookies(req, studentId);
|
let cookies = await getOrRefreshPortalCookies(req, studentId);
|
||||||
if (!cookies) {
|
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.');
|
throw new Error('Session expired. Please log in again.');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await action(cookies);
|
return await action(cookies);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
const isSessionErr =
|
if (ScraperService.isSessionExpiredError(err)) {
|
||||||
err?.message?.includes('Session expired') ||
|
|
||||||
err?.message?.includes('unauthorized') ||
|
|
||||||
err?.message?.includes('girisForm') ||
|
|
||||||
err?.response?.status === 401 ||
|
|
||||||
err?.response?.status === 302;
|
|
||||||
|
|
||||||
if (isSessionErr) {
|
|
||||||
req.session.portalCookies = undefined;
|
req.session.portalCookies = undefined;
|
||||||
const creds = db.getRememberedCredentials(studentId);
|
const refreshedCookies = await reloginToPortal(studentId, req);
|
||||||
if (creds) {
|
if (refreshedCookies) {
|
||||||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
return await action(refreshedCookies);
|
||||||
if (loginRes.success) {
|
|
||||||
req.session.portalCookies = loginRes.cookies;
|
|
||||||
req.session.studentName = loginRes.studentName || req.session.studentName;
|
|
||||||
return await action(loginRes.cookies);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// 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;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
@ -531,12 +676,16 @@ app.post('/login', loginLimiter, async (req: Request, res: Response) => {
|
||||||
|
|
||||||
req.session.studentId = cleanStudentId;
|
req.session.studentId = cleanStudentId;
|
||||||
req.session.portalCookies = loginRes.cookies;
|
req.session.portalCookies = loginRes.cookies;
|
||||||
|
req.session.portalPassword = cleanPassword;
|
||||||
req.session.studentName = loginRes.studentName;
|
req.session.studentName = loginRes.studentName;
|
||||||
req.session.loginAt = nowIso;
|
req.session.loginAt = nowIso;
|
||||||
|
|
||||||
// Handle "Remember Me"
|
// Always store the password encrypted in a program-decryptable way so the scraper
|
||||||
if (rememberMe) {
|
// can re-authenticate with https://ogrenci.ozelbursakulturokullari.com/ whenever portalCookies expire.
|
||||||
db.saveCredentials(cleanStudentId, cleanPassword);
|
db.saveCredentials(cleanStudentId, cleanPassword);
|
||||||
|
|
||||||
|
// "Remember Me" controls whether the 30-day persistent browser cookie is set
|
||||||
|
if (rememberMe) {
|
||||||
res.cookie('bekultur_student_id', cleanStudentId, {
|
res.cookie('bekultur_student_id', cleanStudentId, {
|
||||||
signed: true,
|
signed: true,
|
||||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
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')
|
secure: process.env.COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'false')
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
db.clearCredentials(cleanStudentId);
|
|
||||||
res.clearCookie('bekultur_student_id');
|
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.
|
// sync recent homework, exams, and syllabus automatically. Otherwise sync recent homework.
|
||||||
try {
|
try {
|
||||||
if (needsMondaySync) {
|
if (needsMondaySync) {
|
||||||
await syncWeeklyStudentData(cleanStudentId, loginRes.cookies);
|
await syncWeeklyStudentData(cleanStudentId, loginRes.cookies, new Date(), req);
|
||||||
} else {
|
} else {
|
||||||
db.updateLastLogin(cleanStudentId, nowIso);
|
db.updateLastLogin(cleanStudentId, nowIso);
|
||||||
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2);
|
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2);
|
||||||
|
|
@ -1253,7 +1401,12 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
|
||||||
return res.status(404).json({ success: false, error: 'Exam detail not cached' });
|
return res.status(404).json({ success: false, error: 'Exam detail not cached' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const inFlightKey = `${studentId}_${cacheKey}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
let fetchPromise = examQuestionsInFlight.get(inFlightKey);
|
||||||
|
if (!fetchPromise) {
|
||||||
|
fetchPromise = (async () => {
|
||||||
const subjectQuestionsList: Array<{
|
const subjectQuestionsList: Array<{
|
||||||
subjectName: string;
|
subjectName: string;
|
||||||
subjectId: string;
|
subjectId: string;
|
||||||
|
|
@ -1262,6 +1415,9 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
|
||||||
const allScrapedQuestions: any[] = [];
|
const allScrapedQuestions: any[] = [];
|
||||||
|
|
||||||
await executeWithPortalSession(req, studentId, async (cookies) => {
|
await executeWithPortalSession(req, studentId, async (cookies) => {
|
||||||
|
subjectQuestionsList.length = 0;
|
||||||
|
allScrapedQuestions.length = 0;
|
||||||
|
|
||||||
for (const subject of exam.subjects) {
|
for (const subject of exam.subjects) {
|
||||||
const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true;
|
const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true;
|
||||||
if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) {
|
if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) {
|
||||||
|
|
@ -1296,11 +1452,20 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
|
||||||
db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions);
|
db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0),
|
totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0),
|
||||||
subjects: subjectQuestionsList
|
subjects: subjectQuestionsList
|
||||||
|
};
|
||||||
|
})().finally(() => {
|
||||||
|
examQuestionsInFlight.delete(inFlightKey);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
examQuestionsInFlight.set(inFlightKey, fetchPromise);
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await fetchPromise;
|
||||||
|
res.json(payload);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error('Failed to fetch questions:', err.message);
|
console.error('Failed to fetch questions:', err.message);
|
||||||
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,8 @@ import '../utils/time';
|
||||||
import { toIstanbulIsoString } from '../utils/time';
|
import { toIstanbulIsoString } from '../utils/time';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import crypto from 'crypto';
|
|
||||||
import Database from 'better-sqlite3';
|
import Database from 'better-sqlite3';
|
||||||
import {
|
import {
|
||||||
DatabaseSchema,
|
|
||||||
StudentStore,
|
StudentStore,
|
||||||
Assignment,
|
Assignment,
|
||||||
PrivateLesson,
|
PrivateLesson,
|
||||||
|
|
@ -19,13 +17,11 @@ import {
|
||||||
} from '../types';
|
} from '../types';
|
||||||
import {
|
import {
|
||||||
encryptCredential,
|
encryptCredential,
|
||||||
decryptCredential
|
decryptCredentialWithInfo,
|
||||||
|
syncSecretsWithDatabase
|
||||||
} from './secrets';
|
} from './secrets';
|
||||||
|
|
||||||
const DEFAULT_DB_FILE = path.resolve(process.cwd(), 'data', 'bekultur.db');
|
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 {
|
interface StudentRow {
|
||||||
student_id: string;
|
student_id: string;
|
||||||
|
|
@ -62,22 +58,9 @@ export class LocalDatabase {
|
||||||
private static instance: LocalDatabase | null = null;
|
private static instance: LocalDatabase | null = null;
|
||||||
private sqlite: Database.Database;
|
private sqlite: Database.Database;
|
||||||
private dbPath: string;
|
private dbPath: string;
|
||||||
private legacyJsonPath: string;
|
|
||||||
private skipTestFilter: boolean;
|
|
||||||
|
|
||||||
public constructor(
|
public constructor(customDbPath?: string) {
|
||||||
customDbPath?: string,
|
|
||||||
customLegacyJsonPath?: string,
|
|
||||||
options?: { skipTestFilter?: boolean }
|
|
||||||
) {
|
|
||||||
this.dbPath = customDbPath || process.env.DB_PATH || DEFAULT_DB_FILE;
|
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);
|
const dir = path.dirname(this.dbPath);
|
||||||
if (!fs.existsSync(dir)) {
|
if (!fs.existsSync(dir)) {
|
||||||
|
|
@ -86,7 +69,61 @@ export class LocalDatabase {
|
||||||
|
|
||||||
this.sqlite = new Database(this.dbPath);
|
this.sqlite = new Database(this.dbPath);
|
||||||
this.initSchema();
|
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 {
|
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 {
|
private ensureStudentRow(studentId: string): StudentRow {
|
||||||
const existing = this.sqlite
|
const existing = this.sqlite
|
||||||
.prepare('SELECT * FROM students WHERE student_id = ?')
|
.prepare('SELECT * FROM students WHERE student_id = ?')
|
||||||
|
|
@ -670,12 +513,25 @@ export class LocalDatabase {
|
||||||
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
|
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
|
||||||
.get(studentId) as { remembered_password: string | null } | undefined;
|
.get(studentId) as { remembered_password: string | null } | undefined;
|
||||||
|
|
||||||
if (!row?.remembered_password) return null;
|
if (!row?.remembered_password) {
|
||||||
const decrypted = decryptCredential(row.remembered_password);
|
return null;
|
||||||
if (!decrypted) 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 {
|
return {
|
||||||
studentId,
|
studentId,
|
||||||
password: decrypted
|
password: info.plaintext
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -698,13 +554,22 @@ export class LocalDatabase {
|
||||||
const existingStation = existingSyllabus?.selectedStation || null;
|
const existingStation = existingSyllabus?.selectedStation || null;
|
||||||
const now = syncedAt || toIstanbulIsoString();
|
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 = {
|
const syllabus: SyllabusStore = {
|
||||||
weekId,
|
weekId,
|
||||||
weekRange,
|
weekRange,
|
||||||
selectedStation: existingStation,
|
selectedStation: existingStation,
|
||||||
advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null,
|
advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null,
|
||||||
lastSynced: now,
|
lastSynced: now,
|
||||||
schedule
|
schedule: effectiveSchedule
|
||||||
};
|
};
|
||||||
|
|
||||||
this.sqlite
|
this.sqlite
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com';
|
||||||
const BILGI_BASE_URL = 'https://bilgi.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 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 REQUEST_TIMEOUT_MS = 12000;
|
||||||
|
const EXAM_QUESTIONS_TIMEOUT_MS = 25000;
|
||||||
|
|
||||||
export interface LoginResult {
|
export interface LoginResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -35,6 +36,44 @@ export interface ScrapeResult {
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ScraperService {
|
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)
|
* Normalize portal image URLs (upgrades http:// to https:// and resolves relative paths)
|
||||||
*/
|
*/
|
||||||
|
|
@ -246,7 +285,7 @@ export class ScraperService {
|
||||||
validateStatus: () => true
|
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.');
|
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -350,7 +389,9 @@ export class ScraperService {
|
||||||
totalPages
|
totalPages
|
||||||
};
|
};
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
if (!this.isSessionExpiredError(err)) {
|
||||||
console.error(`Error scraping page ${page}:`, err.message);
|
console.error(`Error scraping page ${page}:`, err.message);
|
||||||
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -406,9 +447,14 @@ export class ScraperService {
|
||||||
'Referer': `${BASE_URL}/`
|
'Referer': `${BASE_URL}/`
|
||||||
},
|
},
|
||||||
timeout: REQUEST_TIMEOUT_MS,
|
timeout: REQUEST_TIMEOUT_MS,
|
||||||
|
maxRedirects: 0,
|
||||||
validateStatus: () => true
|
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') {
|
if (res.status === 200 && typeof res.data === 'string') {
|
||||||
const $ = cheerio.load(res.data);
|
const $ = cheerio.load(res.data);
|
||||||
const dayLessons: Lesson[] = [];
|
const dayLessons: Lesson[] = [];
|
||||||
|
|
@ -464,6 +510,9 @@ export class ScraperService {
|
||||||
weeklySchedule[day] = dayLessons;
|
weeklySchedule[day] = dayLessons;
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
if (this.isSessionExpiredError(err)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
console.error(`Failed to scrape syllabus for day ${day}:`, err.message);
|
console.error(`Failed to scrape syllabus for day ${day}:`, err.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -488,6 +537,7 @@ export class ScraperService {
|
||||||
'Cookie': cookies
|
'Cookie': cookies
|
||||||
},
|
},
|
||||||
timeout: REQUEST_TIMEOUT_MS,
|
timeout: REQUEST_TIMEOUT_MS,
|
||||||
|
maxRedirects: 0,
|
||||||
validateStatus: () => true
|
validateStatus: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -501,6 +551,9 @@ export class ScraperService {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await client.get(url);
|
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;
|
if (res.status !== 200 || !res.data) break;
|
||||||
|
|
||||||
const $ = cheerio.load(res.data);
|
const $ = cheerio.load(res.data);
|
||||||
|
|
@ -560,6 +613,9 @@ export class ScraperService {
|
||||||
|
|
||||||
currentPage++;
|
currentPage++;
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
if (this.isSessionExpiredError(err)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
console.error(`Error scraping private lessons page ${currentPage}:`, err.message);
|
console.error(`Error scraping private lessons page ${currentPage}:`, err.message);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -762,10 +818,14 @@ export class ScraperService {
|
||||||
'User-Agent': USER_AGENT
|
'User-Agent': USER_AGENT
|
||||||
},
|
},
|
||||||
timeout: REQUEST_TIMEOUT_MS,
|
timeout: REQUEST_TIMEOUT_MS,
|
||||||
maxRedirects: 5,
|
maxRedirects: 0,
|
||||||
validateStatus: () => true
|
validateStatus: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.isSessionExpiredResponse(res)) {
|
||||||
|
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||||
|
}
|
||||||
|
|
||||||
if (res.status < 200 || res.status >= 400) {
|
if (res.status < 200 || res.status >= 400) {
|
||||||
console.error(`GET /rapor/sinav returned status ${res.status}`);
|
console.error(`GET /rapor/sinav returned status ${res.status}`);
|
||||||
return [];
|
return [];
|
||||||
|
|
@ -786,6 +846,9 @@ export class ScraperService {
|
||||||
|
|
||||||
return exams;
|
return exams;
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
if (this.isSessionExpiredError(err)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
console.error('Failed to scrape exam list:', err.message);
|
console.error('Failed to scrape exam list:', err.message);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
@ -824,10 +887,14 @@ export class ScraperService {
|
||||||
'User-Agent': USER_AGENT
|
'User-Agent': USER_AGENT
|
||||||
},
|
},
|
||||||
timeout: REQUEST_TIMEOUT_MS,
|
timeout: REQUEST_TIMEOUT_MS,
|
||||||
maxRedirects: 5,
|
maxRedirects: 0,
|
||||||
validateStatus: () => true
|
validateStatus: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.isSessionExpiredResponse(res)) {
|
||||||
|
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||||
|
}
|
||||||
|
|
||||||
if (res.status < 200 || res.status >= 400) {
|
if (res.status < 200 || res.status >= 400) {
|
||||||
console.error(`GET /rapor/sinavkarne/${examId} returned status ${res.status}`);
|
console.error(`GET /rapor/sinavkarne/${examId} returned status ${res.status}`);
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -969,6 +1036,9 @@ export class ScraperService {
|
||||||
answerKeyUrl
|
answerKeyUrl
|
||||||
};
|
};
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
if (this.isSessionExpiredError(err)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
console.error(`Failed to scrape exam detail ${examId}:`, err.message);
|
console.error(`Failed to scrape exam detail ${examId}:`, err.message);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
@ -984,19 +1054,26 @@ export class ScraperService {
|
||||||
dersId: string,
|
dersId: string,
|
||||||
tip: 'D' | 'Y' | 'B'
|
tip: 'D' | 'Y' | 'B'
|
||||||
): Promise<ExamQuestionItem[]> {
|
): 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;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||||
|
try {
|
||||||
const res = await axios.get(url, {
|
const res = await axios.get(url, {
|
||||||
headers: {
|
headers: {
|
||||||
'Cookie': cookies,
|
'Cookie': cookies,
|
||||||
'User-Agent': USER_AGENT
|
'User-Agent': USER_AGENT,
|
||||||
|
'Referer': `${BASE_URL}/`
|
||||||
},
|
},
|
||||||
timeout: REQUEST_TIMEOUT_MS,
|
timeout: EXAM_QUESTIONS_TIMEOUT_MS,
|
||||||
maxRedirects: 5,
|
maxRedirects: 5,
|
||||||
validateStatus: () => true
|
validateStatus: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.isSessionExpiredResponse(res)) {
|
||||||
|
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||||
|
}
|
||||||
|
|
||||||
if (res.status < 200 || res.status >= 400) {
|
if (res.status < 200 || res.status >= 400) {
|
||||||
console.error(`GET ogrencisoruanaliz returned status ${res.status}`);
|
console.error(`GET ogrencisoruanaliz returned status ${res.status}`);
|
||||||
return [];
|
return [];
|
||||||
|
|
@ -1034,11 +1111,28 @@ export class ScraperService {
|
||||||
|
|
||||||
return items;
|
return items;
|
||||||
} catch (err: any) {
|
} 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);
|
console.error('Failed to scrape exam questions:', err.message);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Scrape topic weakness breakdown from /rapor/yanliskonu
|
* Scrape topic weakness breakdown from /rapor/yanliskonu
|
||||||
*/
|
*/
|
||||||
|
|
@ -1055,10 +1149,14 @@ export class ScraperService {
|
||||||
'User-Agent': USER_AGENT
|
'User-Agent': USER_AGENT
|
||||||
},
|
},
|
||||||
timeout: REQUEST_TIMEOUT_MS,
|
timeout: REQUEST_TIMEOUT_MS,
|
||||||
maxRedirects: 5,
|
maxRedirects: 0,
|
||||||
validateStatus: () => true
|
validateStatus: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.isSessionExpiredResponse(getRes)) {
|
||||||
|
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||||
|
}
|
||||||
|
|
||||||
const $get = cheerio.load(getRes.data);
|
const $get = cheerio.load(getRes.data);
|
||||||
const token = $get('input[name="__RequestVerificationToken"]').val() as string;
|
const token = $get('input[name="__RequestVerificationToken"]').val() as string;
|
||||||
|
|
||||||
|
|
@ -1085,6 +1183,10 @@ export class ScraperService {
|
||||||
validateStatus: () => true
|
validateStatus: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.isSessionExpiredResponse(postRes)) {
|
||||||
|
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||||
|
}
|
||||||
|
|
||||||
if (postRes.status < 200 || postRes.status >= 400) {
|
if (postRes.status < 200 || postRes.status >= 400) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
@ -1127,6 +1229,9 @@ export class ScraperService {
|
||||||
|
|
||||||
return weaknesses;
|
return weaknesses;
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
if (this.isSessionExpiredError(err)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
console.error('Failed to scrape topic weaknesses:', err.message);
|
console.error('Failed to scrape topic weaknesses:', err.message);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,20 +3,32 @@ import path from 'path';
|
||||||
import crypto from 'crypto';
|
import crypto from 'crypto';
|
||||||
|
|
||||||
const INSECURE_DEFAULTS = new Set([
|
const INSECURE_DEFAULTS = new Set([
|
||||||
|
'bekultur_secret_session_key_change_in_production',
|
||||||
'bekultur_secret_key_change_in_production',
|
'bekultur_secret_key_change_in_production',
|
||||||
'bekultur_default_secret_key_change_me',
|
'bekultur_default_secret_key_change_me',
|
||||||
|
'change_me',
|
||||||
''
|
''
|
||||||
]);
|
]);
|
||||||
|
|
||||||
interface StoredSecrets {
|
export interface StoredSecrets {
|
||||||
sessionSecret: string;
|
sessionSecret: string;
|
||||||
encryptionSecret: string;
|
encryptionSecret: string;
|
||||||
createdAt: 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 customDbPath = process.env.DB_PATH;
|
||||||
const dataDir = customDbPath
|
const dataDir = customDbPath
|
||||||
? path.dirname(path.resolve(customDbPath))
|
? path.dirname(path.resolve(customDbPath))
|
||||||
|
|
@ -24,12 +36,29 @@ function getSecretsFilePath(): string {
|
||||||
return path.join(dataDir, '.secrets.json');
|
return path.join(dataDir, '.secrets.json');
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadOrCreateSecrets(): StoredSecrets {
|
function writeSecretsFile(secretsFile: string, secrets: StoredSecrets): void {
|
||||||
if (cachedSecrets) {
|
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;
|
return cachedSecrets;
|
||||||
}
|
}
|
||||||
|
|
||||||
const secretsFile = getSecretsFilePath();
|
|
||||||
const dir = path.dirname(secretsFile);
|
const dir = path.dirname(secretsFile);
|
||||||
if (!fs.existsSync(dir)) {
|
if (!fs.existsSync(dir)) {
|
||||||
fs.mkdirSync(dir, { recursive: true });
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
|
@ -40,10 +69,13 @@ function loadOrCreateSecrets(): StoredSecrets {
|
||||||
const raw = fs.readFileSync(secretsFile, 'utf-8');
|
const raw = fs.readFileSync(secretsFile, 'utf-8');
|
||||||
const parsed = JSON.parse(raw) as StoredSecrets;
|
const parsed = JSON.parse(raw) as StoredSecrets;
|
||||||
if (parsed.sessionSecret && parsed.encryptionSecret) {
|
if (parsed.sessionSecret && parsed.encryptionSecret) {
|
||||||
|
extraCandidateSecrets.add(parsed.encryptionSecret);
|
||||||
|
extraCandidateSecrets.add(parsed.sessionSecret);
|
||||||
cachedSecrets = parsed;
|
cachedSecrets = parsed;
|
||||||
|
cachedSecretsPath = secretsFile;
|
||||||
return cachedSecrets;
|
return cachedSecrets;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch {
|
||||||
console.warn('Warning: Could not read .secrets.json, regenerating secrets.');
|
console.warn('Warning: Could not read .secrets.json, regenerating secrets.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -54,17 +86,57 @@ function loadOrCreateSecrets(): StoredSecrets {
|
||||||
createdAt: new Date().toISOString()
|
createdAt: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
writeSecretsFile(secretsFile, generated);
|
||||||
fs.writeFileSync(secretsFile, JSON.stringify(generated, null, 2), {
|
extraCandidateSecrets.add(generated.encryptionSecret);
|
||||||
encoding: 'utf-8',
|
extraCandidateSecrets.add(generated.sessionSecret);
|
||||||
mode: 0o600
|
cachedSecrets = generated;
|
||||||
});
|
cachedSecretsPath = secretsFile;
|
||||||
} catch (err) {
|
return cachedSecrets;
|
||||||
console.warn('Warning: Failed to persist .secrets.json to disk:', err);
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
// Persist current file secrets into SQLite meta table so both stores stay in lockstep
|
||||||
return cachedSecrets;
|
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;
|
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
|
* 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 {
|
export function decryptCredentialWithInfo(stored: string): DecryptionResult | null {
|
||||||
if (!stored) return '';
|
if (!stored) return null;
|
||||||
if (!stored.startsWith('enc:')) {
|
if (!stored.startsWith('enc:')) {
|
||||||
// Legacy plaintext support
|
// Legacy plaintext support -> mark usedPrimaryKey: false so it gets encrypted at rest
|
||||||
return stored;
|
return { plaintext: stored, usedPrimaryKey: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const primarySecret = getEncryptionSecret();
|
||||||
|
const allSecrets = getAllCandidateSecrets();
|
||||||
|
|
||||||
// v2 format: enc:v2:<saltHex>:<ivHex>:<authTagHex>:<ciphertextHex>
|
// v2 format: enc:v2:<saltHex>:<ivHex>:<authTagHex>:<ciphertextHex>
|
||||||
if (stored.startsWith('enc:v2:')) {
|
if (stored.startsWith('enc:v2:')) {
|
||||||
const parts = stored.split(':');
|
const parts = stored.split(':');
|
||||||
if (parts.length !== 6) return '';
|
if (parts.length !== 6) return null;
|
||||||
const [, , saltHex, ivHex, authTagHex, ciphertextHex] = parts;
|
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 {
|
try {
|
||||||
const key = crypto.scryptSync(secret, Buffer.from(saltHex, 'hex'), 32);
|
const key = crypto.scryptSync(secret, Buffer.from(saltHex, 'hex'), 32);
|
||||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
|
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
|
||||||
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
||||||
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
||||||
decrypted += decipher.final('utf8');
|
decrypted += decipher.final('utf8');
|
||||||
return decrypted;
|
if (decrypted) {
|
||||||
|
return {
|
||||||
|
plaintext: decrypted,
|
||||||
|
usedPrimaryKey: secret === primarySecret
|
||||||
|
};
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Try next candidate key
|
// Try next candidate key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return '';
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Legacy v1 format: enc:<ivHex>:<authTagHex>:<ciphertextHex>
|
// Legacy v1 format: enc:<ivHex>:<authTagHex>:<ciphertextHex>
|
||||||
const parts = stored.split(':');
|
const parts = stored.split(':');
|
||||||
if (parts.length !== 4) return '';
|
if (parts.length !== 4) return null;
|
||||||
const [, ivHex, authTagHex, ciphertextHex] = parts;
|
const [, ivHex, authTagHex, ciphertextHex] = parts;
|
||||||
|
|
||||||
const legacyCandidateSecrets = Array.from(
|
for (const secret of allSecrets) {
|
||||||
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) {
|
|
||||||
try {
|
try {
|
||||||
const key = crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
|
const key = crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
|
||||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
|
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
|
||||||
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
||||||
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
||||||
decrypted += decipher.final('utf8');
|
decrypted += decipher.final('utf8');
|
||||||
return decrypted;
|
if (decrypted) {
|
||||||
|
return {
|
||||||
|
plaintext: decrypted,
|
||||||
|
usedPrimaryKey: false
|
||||||
|
};
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Try next candidate secret
|
// Try next candidate secret
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error('Failed to decrypt legacy credential with any known key.');
|
return null;
|
||||||
return '';
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
export function isModernEncryptedFormat(stored: string): boolean {
|
||||||
|
|
|
||||||
|
|
@ -59,6 +59,9 @@ export class SQLiteSessionStore extends session.Store {
|
||||||
if (typeof clone.portalCookies === 'string' && clone.portalCookies.length > 0 && !clone.portalCookies.startsWith('enc:')) {
|
if (typeof clone.portalCookies === 'string' && clone.portalCookies.length > 0 && !clone.portalCookies.startsWith('enc:')) {
|
||||||
clone.portalCookies = encryptCredential(clone.portalCookies);
|
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);
|
return JSON.stringify(clone);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -66,7 +69,20 @@ export class SQLiteSessionStore extends session.Store {
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(rawJson);
|
const parsed = JSON.parse(rawJson);
|
||||||
if (typeof parsed.portalCookies === 'string' && parsed.portalCookies.startsWith('enc:')) {
|
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;
|
return parsed as session.SessionData;
|
||||||
} catch {
|
} catch {
|
||||||
|
|
|
||||||
|
|
@ -24,10 +24,8 @@ import { Assignment, Lesson, ExamReportDetail } from '../src/types';
|
||||||
// Configure isolated temporary directory BEFORE any server/db singleton initialization
|
// Configure isolated temporary directory BEFORE any server/db singleton initialization
|
||||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-'));
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-'));
|
||||||
const testDbPath = path.join(tempDir, 'test-bekultur.db');
|
const testDbPath = path.join(tempDir, 'test-bekultur.db');
|
||||||
const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json');
|
|
||||||
process.env.NODE_ENV = 'test';
|
process.env.NODE_ENV = 'test';
|
||||||
process.env.DB_PATH = testDbPath;
|
process.env.DB_PATH = testDbPath;
|
||||||
process.env.LEGACY_JSON_PATH = testLegacyJsonPath;
|
|
||||||
|
|
||||||
import { shouldTriggerMondayWeeklySync, syncWeeklyStudentData } from '../src/server';
|
import { shouldTriggerMondayWeeklySync, syncWeeklyStudentData } from '../src/server';
|
||||||
|
|
||||||
|
|
@ -733,219 +731,6 @@ async function runAllTests() {
|
||||||
db.clearCredentials(testId);
|
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:<iv>:<tag>:<cipher>` 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 () => {
|
await test('SQLiteSessionStore: persists sessions, encrypts portalCookies at rest, and prunes expired sessions', async () => {
|
||||||
const db = LocalDatabase.getInstance();
|
const db = LocalDatabase.getInstance();
|
||||||
const store = new SQLiteSessionStore({ db: db.getSqliteDb(), pruneIntervalMs: 0 });
|
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: '<form id="girisForm" action="/Giris"></form>' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
assert.strictEqual(
|
||||||
|
ScraperService.isSessionExpiredResponse({ status: 200, data: '<div class="kltr-card">Valid Content</div>' }),
|
||||||
|
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)
|
// Optional Live Portal Test (via environment variables only)
|
||||||
const testStudentId = process.env.TEST_STUDENT_ID;
|
const testStudentId = process.env.TEST_STUDENT_ID;
|
||||||
const testPassword = process.env.TEST_PASSWORD;
|
const testPassword = process.env.TEST_PASSWORD;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue