fixes and patches n stuff

This commit is contained in:
tyuXX 2026-10-21 21:07:54 +00:00
parent 7c7ae8e051
commit 1af973d001
14 changed files with 571 additions and 268 deletions

View file

@ -1070,6 +1070,12 @@ code {
background: #ffffff; background: #ffffff;
} }
.grid-lesson-item:not(:last-child) {
margin-bottom: 6px;
padding-bottom: 6px;
border-bottom: 1px dashed var(--border);
}
.grid-lesson-subject { .grid-lesson-subject {
font-weight: 600; font-weight: 600;
font-size: 0.825rem; font-size: 0.825rem;
@ -1660,6 +1666,23 @@ code {
margin-top: 2px; margin-top: 2px;
} }
/* Standalone Rating Badge Icons (Unicode Glyphs - Zero External Font Dependency) */
.bi {
display: inline-block;
font-style: normal;
line-height: 1;
margin-right: 3px;
}
.bi-stars::before { content: "✨"; }
.bi-award-fill::before { content: "🏅"; }
.bi-shield-check::before { content: "🛡️"; }
.bi-graph-up-arrow::before { content: "📈"; }
.bi-trophy-fill::before { content: "🏆"; }
.bi-flag-fill::before { content: "🚩"; }
.bi-exclamation-triangle-fill::before { content: "⚠️"; }
.bi-check-circle-fill::before { content: "✓"; }
/* Exam Detail Card */ /* Exam Detail Card */
.exam-detail-card { .exam-detail-card {
background: var(--bg-card); background: var(--bg-card);

View file

@ -211,9 +211,17 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
} }
function normalizeTurkish(str) {
if (!str) return '';
return str
.replace(/İ/g, 'i')
.replace(/I/g, 'ı')
.toLowerCase();
}
if (searchInput) { if (searchInput) {
searchInput.addEventListener('input', (e) => { searchInput.addEventListener('input', (e) => {
currentSearch = e.target.value.trim().toLowerCase(); currentSearch = normalizeTurkish(e.target.value.trim());
if (searchClear) searchClear.classList.toggle('hidden', currentSearch.length === 0); if (searchClear) searchClear.classList.toggle('hidden', currentSearch.length === 0);
applyFilters(); applyFilters();
}); });
@ -290,7 +298,7 @@ document.addEventListener('DOMContentLoaded', () => {
let matchesSearch = true; let matchesSearch = true;
if (currentSearch) { if (currentSearch) {
matchesSearch = searchText.includes(currentSearch); matchesSearch = normalizeTurkish(searchText).includes(currentSearch);
} }
if (matchesTab && matchesSubject && matchesSearch) { if (matchesTab && matchesSubject && matchesSearch) {

View file

@ -221,11 +221,16 @@ document.addEventListener('DOMContentLoaded', () => {
// ---------------------------------------------------- // ----------------------------------------------------
// Inline Mistake Review Modal // Inline Mistake Review Modal
// ---------------------------------------------------- // ----------------------------------------------------
function openReviewModal(targetSubjectName = null) { function openReviewModal(targetSubjectName = null, targetType = 'all') {
if (!mistakeModal || !currentExamId) return; if (!mistakeModal || !currentExamId) return;
mistakeModal.classList.remove('hidden'); mistakeModal.classList.remove('hidden');
document.body.style.overflow = 'hidden'; document.body.style.overflow = 'hidden';
activeTypeFilter = targetType || 'all';
modalTypeBtns.forEach(b => {
b.classList.toggle('active', b.getAttribute('data-type') === activeTypeFilter);
});
if (!cachedQuestions) { if (!cachedQuestions) {
loadExamQuestions(targetSubjectName); loadExamQuestions(targetSubjectName);
} else { } else {
@ -244,7 +249,7 @@ document.addEventListener('DOMContentLoaded', () => {
} }
if (btnReviewMistakes) { if (btnReviewMistakes) {
btnReviewMistakes.addEventListener('click', () => openReviewModal()); btnReviewMistakes.addEventListener('click', () => openReviewModal(null, 'all'));
} }
if (btnMistakeModalClose) { if (btnMistakeModalClose) {
@ -256,7 +261,9 @@ document.addEventListener('DOMContentLoaded', () => {
btn.addEventListener('click', (e) => { btn.addEventListener('click', (e) => {
e.stopPropagation(); e.stopPropagation();
const subjectName = btn.getAttribute('data-subject-name'); const subjectName = btn.getAttribute('data-subject-name');
openReviewModal(subjectName); const tip = btn.getAttribute('data-tip');
const targetType = tip === 'B' ? 'empty' : tip === 'Y' ? 'wrong' : 'all';
openReviewModal(subjectName, targetType);
}); });
}); });

View file

@ -59,8 +59,13 @@ document.addEventListener('DOMContentLoaded', () => {
const data = await res.json(); const data = await res.json();
if (data.success && data.units && data.units.length > 0) { if (data.success && data.units && data.units.length > 0) {
selectUnit.innerHTML = '<option value="">Seçiniz...</option>' + selectUnit.innerHTML = '<option value="">Seçiniz...</option>';
data.units.map(u => `<option value="${u.id}">${u.name}</option>`).join(''); data.units.forEach(u => {
const opt = document.createElement('option');
opt.value = u.id;
opt.textContent = u.name;
selectUnit.appendChild(opt);
});
selectUnit.disabled = false; selectUnit.disabled = false;
} else { } else {
selectUnit.innerHTML = '<option value="">Ünite bulunamadı</option>'; selectUnit.innerHTML = '<option value="">Ünite bulunamadı</option>';
@ -93,8 +98,13 @@ document.addEventListener('DOMContentLoaded', () => {
const data = await res.json(); const data = await res.json();
if (data.success && data.topics && data.topics.length > 0) { if (data.success && data.topics && data.topics.length > 0) {
selectTopic.innerHTML = '<option value="">Seçiniz...</option>' + selectTopic.innerHTML = '<option value="">Seçiniz...</option>';
data.topics.map(t => `<option value="${t.id}">${t.name}</option>`).join(''); data.topics.forEach(t => {
const opt = document.createElement('option');
opt.value = t.id;
opt.textContent = t.name;
selectTopic.appendChild(opt);
});
selectTopic.disabled = false; selectTopic.disabled = false;
} else { } else {
selectTopic.innerHTML = '<option value="">Konu bulunamadı</option>'; selectTopic.innerHTML = '<option value="">Konu bulunamadı</option>';

View file

@ -3,6 +3,7 @@
*/ */
(function () { (function () {
let isOffline = !navigator.onLine; let isOffline = !navigator.onLine;
let bannerTimeout = null;
// 1. Service Worker Registration // 1. Service Worker Registration
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
@ -41,6 +42,10 @@
} }
function showOfflineBanner() { function showOfflineBanner() {
if (bannerTimeout) {
clearTimeout(bannerTimeout);
bannerTimeout = null;
}
const banner = getOrCreateBanner(); const banner = getOrCreateBanner();
banner.className = 'offline-banner active'; banner.className = 'offline-banner active';
banner.innerHTML = ` banner.innerHTML = `
@ -52,6 +57,10 @@
} }
function showOnlineBanner() { function showOnlineBanner() {
if (bannerTimeout) {
clearTimeout(bannerTimeout);
bannerTimeout = null;
}
const banner = getOrCreateBanner(); const banner = getOrCreateBanner();
banner.className = 'offline-banner online'; banner.className = 'offline-banner online';
banner.innerHTML = ` banner.innerHTML = `
@ -60,8 +69,9 @@
<span class="offline-banner-text">Connection restored. Live features re-enabled.</span> <span class="offline-banner-text">Connection restored. Live features re-enabled.</span>
</div> </div>
`; `;
setTimeout(() => { bannerTimeout = setTimeout(() => {
banner.className = 'offline-banner hidden'; banner.className = 'offline-banner hidden';
bannerTimeout = null;
}, 2800); }, 2800);
} }
@ -104,7 +114,7 @@
// --- B. Private Lesson Request Form --- // --- B. Private Lesson Request Form ---
const lessonForm = document.getElementById('privateLessonForm'); const lessonForm = document.getElementById('privateLessonForm');
const btnSubmitLesson = document.getElementById('btnSubmitLessonRequest'); const btnSubmitLesson = document.getElementById('btnSubmitRequest');
const formSelects = document.querySelectorAll('#privateLessonForm select, #privateLessonForm button[type="submit"]'); const formSelects = document.querySelectorAll('#privateLessonForm select, #privateLessonForm button[type="submit"]');
let noticeEl = document.getElementById('privateLessonOfflineNotice'); let noticeEl = document.getElementById('privateLessonOfflineNotice');
@ -130,7 +140,19 @@
} }
} }
// --- C. Sync Buttons Across All Pages --- // --- C. Station Buttons in Syllabus ---
const stationButtons = document.querySelectorAll('.station-btn');
stationButtons.forEach((btn) => {
if (offline) {
btn.classList.add('station-btn-offline');
btn.title = 'Offline mode: Station selection requires connection.';
} else {
btn.classList.remove('station-btn-offline');
btn.title = '';
}
});
// --- D. Sync Buttons Across All Pages ---
const syncButtonSelectors = [ const syncButtonSelectors = [
'#btnSyncRecent', '#btnSyncRecent',
'#btnSyncAll', '#btnSyncAll',

View file

@ -13,6 +13,11 @@ document.addEventListener('DOMContentLoaded', () => {
const btn = e.target.closest('.station-btn'); const btn = e.target.closest('.station-btn');
if (!btn) return; if (!btn) return;
if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
showAlert('Çevrimdışı moddasınız. İstasyon seçimi için internet bağlantısı gereklidir.', 'danger');
return;
}
const station = btn.dataset.station; const station = btn.dataset.station;
stationPills.querySelectorAll('.station-btn').forEach(b => b.classList.remove('active')); stationPills.querySelectorAll('.station-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active'); btn.classList.add('active');

View file

@ -1,7 +1,11 @@
const CACHE_NAME = 'bekultur-v1'; const CACHE_NAME = 'bekultur-v2';
const STATIC_ASSETS = [ const STATIC_ASSETS = [
'/', '/',
'/dashboard',
'/syllabus',
'/private-lessons',
'/exams',
'/css/style.css', '/css/style.css',
'/js/pwa.js', '/js/pwa.js',
'/js/app.js', '/js/app.js',
@ -53,13 +57,19 @@ self.addEventListener('fetch', (event) => {
const url = new URL(req.url); const url = new URL(req.url);
// Allow caching question images from panel.ozelbursakulturokullari.com
const isQuestionImage =
url.origin.includes('ozelbursakulturokullari.com') &&
(url.pathname.endsWith('.png') || url.pathname.endsWith('.jpg') || url.pathname.endsWith('.jpeg') || url.pathname.includes('/soru/'));
// Ignore cross-origin external analytics or fonts // Ignore cross-origin external analytics or fonts
if (url.origin !== self.location.origin) { if (url.origin !== self.location.origin && !isQuestionImage) {
return; return;
} }
// 1. Static Assets (CSS, JS, Icons, Images) -> Cache-First // 1. Static Assets & Question Images -> Cache-First
const isStatic = const isStatic =
isQuestionImage ||
url.pathname.startsWith('/css/') || url.pathname.startsWith('/css/') ||
url.pathname.startsWith('/js/') || url.pathname.startsWith('/js/') ||
url.pathname.startsWith('/icons/') || url.pathname.startsWith('/icons/') ||
@ -75,11 +85,14 @@ self.addEventListener('fetch', (event) => {
return cachedResponse; return cachedResponse;
} }
return fetch(req).then((networkResponse) => { return fetch(req).then((networkResponse) => {
if (networkResponse && networkResponse.status === 200) { if (networkResponse && (networkResponse.status === 200 || networkResponse.type === 'opaque')) {
const clone = networkResponse.clone(); const clone = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(req, clone)); caches.open(CACHE_NAME).then((cache) => cache.put(req, clone));
} }
return networkResponse; return networkResponse;
}).catch(() => {
// If question image fails offline and not cached, return empty placeholder
return new Response('', { status: 404, statusText: 'Not found offline' });
}); });
}) })
); );
@ -98,13 +111,35 @@ self.addEventListener('fetch', (event) => {
}) })
.catch(async () => { .catch(async () => {
// Network failed (Offline) -> Look in CacheStorage // Network failed (Offline) -> Look in CacheStorage
const cached = await caches.match(req); // 1. Try exact match
let cached = await caches.match(req);
// 2. Try match ignoring query parameters
if (!cached) {
cached = await caches.match(req, { ignoreSearch: true });
}
// 3. Try match by pathname
if (!cached) {
cached = await caches.match(url.pathname);
}
if (cached) { if (cached) {
return cached; return cached;
} }
// If it was a navigation request, try fallback to cached dashboard or root // If it was a navigation request, try route-specific fallbacks
if (req.mode === 'navigate') { if (req.mode === 'navigate') {
if (url.pathname.startsWith('/exams')) {
const fallback = await caches.match('/exams');
if (fallback) return fallback;
}
if (url.pathname.startsWith('/syllabus')) {
const fallback = await caches.match('/syllabus');
if (fallback) return fallback;
}
if (url.pathname.startsWith('/private-lessons')) {
const fallback = await caches.match('/private-lessons');
if (fallback) return fallback;
}
const fallbackDashboard = await caches.match('/dashboard'); const fallbackDashboard = await caches.match('/dashboard');
if (fallbackDashboard) return fallbackDashboard; if (fallbackDashboard) return fallbackDashboard;

View file

@ -8,7 +8,7 @@ import { LocalDatabase } from './services/db';
import { InsightService } from './services/insight'; import { InsightService } from './services/insight';
import { SyllabusService, DAY_NAMES } from './services/syllabus'; import { SyllabusService, DAY_NAMES } from './services/syllabus';
import { ExamService } from './services/exam'; import { ExamService } from './services/exam';
import { Assignment } from './types'; import { Assignment, ExamReportDetail } from './types';
dotenv.config(); dotenv.config();
@ -26,7 +26,7 @@ app.set('views', viewsPath);
// Middleware // Middleware
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
app.use(express.json()); app.use(express.json());
app.use(cookieParser()); app.use(cookieParser(SESSION_SECRET));
// Custom Service Worker route with proper scope and no-cache headers // Custom Service Worker route with proper scope and no-cache headers
app.get('/sw.js', (req: Request, res: Response) => { app.get('/sw.js', (req: Request, res: Response) => {
@ -49,7 +49,10 @@ app.use(
resave: false, resave: false,
saveUninitialized: false, saveUninitialized: false,
cookie: { cookie: {
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days maxAge: 14 * 24 * 60 * 60 * 1000, // 14 days
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production'
} }
}) })
); );
@ -70,8 +73,11 @@ function requireAuth(req: Request, res: Response, next: NextFunction) {
if (req.session && req.session.studentId) { if (req.session && req.session.studentId) {
return next(); return next();
} }
// Check if studentId remembered in cookie
const rememberedId = req.cookies.bekultur_student_id; const isAjax = req.path.startsWith('/api/') || req.xhr || req.headers.accept?.includes('application/json');
// Check if studentId remembered in signed cookie (tamper-proof)
const rememberedId = req.signedCookies?.bekultur_student_id;
if (rememberedId) { if (rememberedId) {
const creds = db.getRememberedCredentials(rememberedId); const creds = db.getRememberedCredentials(rememberedId);
if (creds) { if (creds) {
@ -84,17 +90,91 @@ function requireAuth(req: Request, res: Response, next: NextFunction) {
return next(); return next();
} else { } else {
res.clearCookie('bekultur_student_id'); res.clearCookie('bekultur_student_id');
if (isAjax) {
return res.status(401).json({ success: false, error: 'Session expired. Please log in again.' });
}
return res.redirect('/'); return res.redirect('/');
} }
}).catch(() => { }).catch(() => {
if (isAjax) {
return res.status(401).json({ success: false, error: 'Connection error during auto-login.' });
}
return res.redirect('/'); return res.redirect('/');
}); });
return; return;
} }
} }
// Clear unsigned or untrusted cookie if present without valid signature
if (req.cookies?.bekultur_student_id && !rememberedId) {
res.clearCookie('bekultur_student_id');
}
if (isAjax) {
return res.status(401).json({ success: false, error: 'Authentication required. Please log in.' });
}
res.redirect('/'); res.redirect('/');
} }
/**
* Helper to obtain active portal cookies from session or remembered 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;
}
/**
* Execute scraper action with automatic session-recovery retry
*/
async function executeWithPortalSession<T>(
req: Request,
studentId: string,
action: (cookies: string) => Promise<T>
): Promise<T> {
let cookies = await getOrRefreshPortalCookies(req, studentId);
if (!cookies) {
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) {
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);
}
}
}
throw err;
}
}
// ---------------------------------------------------- // ----------------------------------------------------
// Routes // Routes
// ---------------------------------------------------- // ----------------------------------------------------
@ -108,7 +188,7 @@ app.get('/', (req: Request, res: Response) => {
return res.redirect('/dashboard'); return res.redirect('/dashboard');
} }
const rememberedId = req.cookies.bekultur_student_id || ''; const rememberedId = req.signedCookies?.bekultur_student_id || '';
const error = (req.query.error as string) || null; const error = (req.query.error as string) || null;
res.render('login', { res.render('login', {
@ -152,8 +232,11 @@ app.post('/login', async (req: Request, res: Response) => {
if (rememberMe) { if (rememberMe) {
db.saveCredentials(studentId, password); db.saveCredentials(studentId, password);
res.cookie('bekultur_student_id', studentId, { res.cookie('bekultur_student_id', studentId, {
signed: true,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production'
}); });
} else { } else {
db.clearCredentials(studentId); db.clearCredentials(studentId);
@ -183,6 +266,7 @@ app.post('/login', async (req: Request, res: Response) => {
* POST /logout * POST /logout
*/ */
app.post('/logout', (req: Request, res: Response) => { app.post('/logout', (req: Request, res: Response) => {
res.clearCookie('bekultur_student_id');
req.session.destroy(() => { req.session.destroy(() => {
res.redirect('/'); res.redirect('/');
}); });
@ -192,6 +276,7 @@ app.post('/logout', (req: Request, res: Response) => {
* GET /logout (convenience) * GET /logout (convenience)
*/ */
app.get('/logout', (req: Request, res: Response) => { app.get('/logout', (req: Request, res: Response) => {
res.clearCookie('bekultur_student_id');
req.session.destroy(() => { req.session.destroy(() => {
res.redirect('/'); res.redirect('/');
}); });
@ -321,29 +406,11 @@ app.post('/api/exclude', requireAuth, (req: Request, res: Response) => {
*/ */
app.post('/api/sync', requireAuth, async (req: Request, res: Response) => { app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!; const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try { try {
// If session cookies missing, attempt re-login using remembered credentials const scrapeRes = await executeWithPortalSession(req, studentId, async (cookies) => {
if (!cookies) { return await ScraperService.scrapeMultiplePages(cookies, studentId, 2);
const creds = db.getRememberedCredentials(studentId); });
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync.'
});
}
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2);
db.mergeAssignments(studentId, scrapeRes.assignments); db.mergeAssignments(studentId, scrapeRes.assignments);
const store = db.getStudentStore(studentId); const store = db.getStudentStore(studentId);
@ -361,7 +428,8 @@ app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
}); });
} catch (err: any) { } catch (err: any) {
console.error('API sync error:', err.message); console.error('API sync error:', err.message);
res.status(500).json({ const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({
success: false, success: false,
error: `Sync failed: ${err.message}` error: `Sync failed: ${err.message}`
}); });
@ -374,29 +442,12 @@ app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
*/ */
app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => { app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!; const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try { try {
if (!cookies) {
const creds = db.getRememberedCredentials(studentId);
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync full history.'
});
}
// Scrape up to 20 pages (portal currently has ~7 pages) // Scrape up to 20 pages (portal currently has ~7 pages)
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 20); const scrapeRes = await executeWithPortalSession(req, studentId, async (cookies) => {
return await ScraperService.scrapeMultiplePages(cookies, studentId, 20);
});
db.mergeAssignments(studentId, scrapeRes.assignments); db.mergeAssignments(studentId, scrapeRes.assignments);
const store = db.getStudentStore(studentId); const store = db.getStudentStore(studentId);
@ -415,7 +466,8 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
}); });
} catch (err: any) { } catch (err: any) {
console.error('API sync-all error:', err.message); console.error('API sync-all error:', err.message);
res.status(500).json({ const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({
success: false, success: false,
error: `Full history sync failed: ${err.message}` error: `Full history sync failed: ${err.message}`
}); });
@ -434,26 +486,14 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
// If syllabus missing or belongs to an older week, auto-sync from portal! // If syllabus missing or belongs to an older week, auto-sync from portal!
if (!syllabusStore || !syllabusStore.weekId || syllabusStore.weekId !== currentWeek.weekId) { if (!syllabusStore || !syllabusStore.weekId || syllabusStore.weekId !== currentWeek.weekId) {
let cookies = req.session.portalCookies; try {
if (!cookies) { const schedule = await executeWithPortalSession(req, studentId, async (cookies) => {
const creds = db.getRememberedCredentials(studentId); return await ScraperService.scrapeSyllabus(cookies);
if (creds) { });
const loginRes = await ScraperService.login(creds.studentId, creds.password); db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
if (loginRes.success) { syllabusStore = db.getSyllabus(studentId);
cookies = loginRes.cookies; } catch (err: any) {
req.session.portalCookies = cookies; console.warn('Auto-syncing weekly syllabus note (using cached if available):', err.message);
}
}
}
if (cookies) {
try {
const schedule = await ScraperService.scrapeSyllabus(cookies);
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
syllabusStore = db.getSyllabus(studentId);
} catch (err: any) {
console.error('Failed auto-syncing weekly syllabus:', err.message);
}
} }
} }
@ -550,29 +590,12 @@ app.post('/api/syllabus/advisory-teacher', requireAuth, (req: Request, res: Resp
*/ */
app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) => { app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!; const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try { try {
if (!cookies) {
const creds = db.getRememberedCredentials(studentId);
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync syllabus.'
});
}
const currentWeek = SyllabusService.getWeekMetadata(); const currentWeek = SyllabusService.getWeekMetadata();
const schedule = await ScraperService.scrapeSyllabus(cookies); const schedule = await executeWithPortalSession(req, studentId, async (cookies) => {
return await ScraperService.scrapeSyllabus(cookies);
});
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule); db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
const store = db.getSyllabus(studentId); const store = db.getSyllabus(studentId);
@ -594,7 +617,8 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
}); });
} catch (err: any) { } catch (err: any) {
console.error('API syllabus sync error:', err.message); console.error('API syllabus sync error:', err.message);
res.status(500).json({ const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({
success: false, success: false,
error: `Syllabus sync failed: ${err.message}` error: `Syllabus sync failed: ${err.message}`
}); });
@ -615,30 +639,17 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) =>
// If not yet synced or formMeta missing, try auto-syncing // If not yet synced or formMeta missing, try auto-syncing
if (!store || !store.lessons || !store.formMeta) { if (!store || !store.lessons || !store.formMeta) {
let cookies = req.session.portalCookies; try {
if (!cookies) { const [privateRes, formMeta] = await executeWithPortalSession(req, studentId, async (cookies) => {
const creds = db.getRememberedCredentials(studentId); return await Promise.all([
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (cookies) {
try {
const [privateRes, formMeta] = await Promise.all([
ScraperService.scrapePrivateLessons(cookies), ScraperService.scrapePrivateLessons(cookies),
ScraperService.fetchPrivateLessonFormMeta(studentId) ScraperService.fetchPrivateLessonFormMeta(studentId)
]); ]);
});
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
store = db.getPrivateLessons(studentId); store = db.getPrivateLessons(studentId);
} catch (err: any) { } catch (err: any) {
console.error('Error auto-syncing private lessons:', err.message); console.warn('Auto-syncing private lessons warning (using cached if available):', err.message);
}
} }
} }
@ -742,31 +753,14 @@ app.post('/api/private-lessons/request', requireAuth, async (req: Request, res:
*/ */
app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Response) => { app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!; const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try { try {
if (!cookies) { const [privateRes, formMeta] = await executeWithPortalSession(req, studentId, async (cookies) => {
const creds = db.getRememberedCredentials(studentId); return await Promise.all([
if (creds) { ScraperService.scrapePrivateLessons(cookies),
const loginRes = await ScraperService.login(creds.studentId, creds.password); ScraperService.fetchPrivateLessonFormMeta(studentId)
if (loginRes.success) { ]);
cookies = loginRes.cookies; });
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync private lessons.'
});
}
const [privateRes, formMeta] = await Promise.all([
ScraperService.scrapePrivateLessons(cookies),
ScraperService.fetchPrivateLessonFormMeta(studentId)
]);
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
const store = db.getPrivateLessons(studentId); const store = db.getPrivateLessons(studentId);
@ -780,7 +774,8 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res
}); });
} catch (err: any) { } catch (err: any) {
console.error('API private-lessons sync error:', err.message); console.error('API private-lessons sync error:', err.message);
res.status(500).json({ const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({
success: false, success: false,
error: `Private lessons sync failed: ${err.message}` error: `Private lessons sync failed: ${err.message}`
}); });
@ -791,24 +786,6 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res
// Exam Reports (Sınav Rapor) Routes // Exam Reports (Sınav Rapor) Routes
// ---------------------------------------------------- // ----------------------------------------------------
/**
* Helper to ensure active portal cookies
*/
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;
return loginRes.cookies;
}
}
return undefined;
}
/** /**
* GET /rapor/sinav * GET /rapor/sinav
* Official portal alias redirect * Official portal alias redirect
@ -827,21 +804,26 @@ app.get('/exams', requireAuth, async (req: Request, res: Response) => {
// If no cached exams or empty, sync now // If no cached exams or empty, sync now
if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) { if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) {
const cookies = await getOrRefreshPortalCookies(req, studentId); try {
if (cookies) { await executeWithPortalSession(req, studentId, async (cookies) => {
try {
const examList = await ScraperService.scrapeExamList(cookies); const examList = await ScraperService.scrapeExamList(cookies);
if (examList.length > 0) { if (examList.length > 0) {
const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id)); const details: ExamReportDetail[] = [];
const details = (await Promise.all(detailPromises)).filter( const batchSize = 3;
(d): d is NonNullable<typeof d> => d !== null for (let i = 0; i < examList.length; i += batchSize) {
); const batch = examList.slice(i, i + batchSize);
db.saveExamReports(studentId, details); const batchRes = await Promise.all(batch.map(item => ScraperService.scrapeExamDetail(cookies, item.id)));
examStore = db.getExamReports(studentId); batchRes.forEach(d => { if (d) details.push(d); });
}
if (details.length > 0) {
db.saveExamReports(studentId, details);
examStore = db.getExamReports(studentId);
}
} }
} catch (err: any) { return null;
console.error('Initial exam scrape error:', err.message); });
} } catch (err: any) {
console.warn('Initial exam scrape warning (using cached if available):', err.message);
} }
} }
@ -884,13 +866,17 @@ app.get('/api/exams/:id', requireAuth, async (req: Request, res: Response) => {
let exam = examStore?.reports?.[examId]; let exam = examStore?.reports?.[examId];
if (!exam) { if (!exam) {
const cookies = await getOrRefreshPortalCookies(req, studentId); try {
if (cookies) { await executeWithPortalSession(req, studentId, async (cookies) => {
const fetched = await ScraperService.scrapeExamDetail(cookies, examId); const fetched = await ScraperService.scrapeExamDetail(cookies, examId);
if (fetched) { if (fetched) {
db.saveExamReports(studentId, [fetched]); db.saveExamReports(studentId, [fetched]);
examStore = db.getExamReports(studentId); examStore = db.getExamReports(studentId);
} }
return fetched;
});
} catch (err: any) {
console.warn(`Could not fetch exam detail ${examId}:`, err.message);
} }
} }
@ -916,15 +902,38 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
const ogrenciDonemId = (req.query.ogrenciDonemId as string) || ''; const ogrenciDonemId = (req.query.ogrenciDonemId as string) || '';
const tip = ((req.query.tip as string) || 'Y').toUpperCase() as 'D' | 'Y' | 'B'; const tip = ((req.query.tip as string) || 'Y').toUpperCase() as 'D' | 'Y' | 'B';
const cookies = await getOrRefreshPortalCookies(req, studentId); const cacheKey = `${examId}_${tip}`;
if (!cookies) {
return res.status(401).json({ success: false, error: 'Session expired' }); // If specific subject requested, fetch directly with portal session
if (dersId && ogrenciDonemId) {
try {
const questions = await executeWithPortalSession(req, studentId, async (cookies) => {
return await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip);
});
return res.json({ success: true, questions });
} catch (err: any) {
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
return res.status(status).json({ success: false, error: err.message });
}
} }
// If specific subject requested, fetch directly // Check if all questions for this exam and tip are cached in db.json
if (dersId && ogrenciDonemId) { const cachedQuestions = db.getExamQuestions(studentId, cacheKey);
const questions = await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip); if (cachedQuestions && cachedQuestions.length > 0) {
return res.json({ success: true, questions }); const subjectsMap: Record<string, { subjectName: string; subjectId: string; questions: any[] }> = {};
cachedQuestions.forEach(q => {
const sName = q.subjectName || 'Genel';
if (!subjectsMap[sName]) {
subjectsMap[sName] = { subjectName: sName, subjectId: q.subjectId || '', questions: [] };
}
subjectsMap[sName].questions.push(q);
});
return res.json({
success: true,
totalMistakes: cachedQuestions.length,
subjects: Object.values(subjectsMap),
cached: true
});
} }
// Otherwise, inspect exam details and fetch questions for all subjects with mistakes // Otherwise, inspect exam details and fetch questions for all subjects with mistakes
@ -935,37 +944,55 @@ 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 subjectQuestionsList: Array<{ try {
subjectName: string; const subjectQuestionsList: Array<{
subjectId: string; subjectName: string;
questions: any[]; subjectId: string;
}> = []; questions: any[];
}> = [];
const allScrapedQuestions: any[] = [];
for (const subject of exam.subjects) { await executeWithPortalSession(req, studentId, async (cookies) => {
const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true; for (const subject of exam.subjects) {
if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) { const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true;
const q = await ScraperService.scrapeExamQuestions( if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) {
cookies, const q = await ScraperService.scrapeExamQuestions(
examId, cookies,
subject.ogrenciDonemId, examId,
subject.subjectId, subject.ogrenciDonemId,
tip subject.subjectId,
); tip
if (q.length > 0) { );
subjectQuestionsList.push({ if (q.length > 0) {
subjectName: subject.subjectName, q.forEach(item => {
subjectId: subject.subjectId, item.subjectName = subject.subjectName;
questions: q allScrapedQuestions.push(item);
}); });
subjectQuestionsList.push({
subjectName: subject.subjectName,
subjectId: subject.subjectId,
questions: q
});
}
}
} }
} return null;
} });
res.json({ if (allScrapedQuestions.length > 0) {
success: true, db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions);
totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0), }
subjects: subjectQuestionsList
}); res.json({
success: true,
totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0),
subjects: subjectQuestionsList
});
} catch (err: any) {
console.error('Failed to fetch questions:', err.message);
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({ success: false, error: err.message });
}
}); });
/** /**
@ -981,15 +1008,16 @@ app.get('/api/exams/:id/weaknesses', requireAuth, async (req: Request, res: Resp
return res.json({ success: true, weaknesses: cached }); return res.json({ success: true, weaknesses: cached });
} }
const cookies = await getOrRefreshPortalCookies(req, studentId); try {
if (!cookies) { const weaknesses = await executeWithPortalSession(req, studentId, async (cookies) => {
return res.status(401).json({ success: false, error: 'Session expired' }); return await ScraperService.scrapeTopicWeaknesses(cookies, examId);
});
db.saveTopicWeaknesses(studentId, examId, weaknesses);
res.json({ success: true, weaknesses });
} catch (err: any) {
const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({ success: false, error: err.message });
} }
const weaknesses = await ScraperService.scrapeTopicWeaknesses(cookies, examId);
db.saveTopicWeaknesses(studentId, examId, weaknesses);
res.json({ success: true, weaknesses });
}); });
/** /**
@ -998,27 +1026,29 @@ app.get('/api/exams/:id/weaknesses', requireAuth, async (req: Request, res: Resp
*/ */
app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => { app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!; const studentId = req.session.studentId!;
const cookies = await getOrRefreshPortalCookies(req, studentId);
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync exams.'
});
}
try { try {
const examList = await ScraperService.scrapeExamList(cookies); await executeWithPortalSession(req, studentId, async (cookies) => {
if (!examList || examList.length === 0) { const examList = await ScraperService.scrapeExamList(cookies);
return res.json({ success: true, count: 0, message: 'No exams found on portal.' }); if (!examList || examList.length === 0) {
} return [];
}
const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id)); // Batch requests in chunks of 3 to avoid overwhelming portal
const details = (await Promise.all(detailPromises)).filter( const details: ExamReportDetail[] = [];
(d): d is NonNullable<typeof d> => d !== null const batchSize = 3;
); for (let i = 0; i < examList.length; i += batchSize) {
const batch = examList.slice(i, i + batchSize);
const batchRes = await Promise.all(batch.map(item => ScraperService.scrapeExamDetail(cookies, item.id)));
batchRes.forEach(d => { if (d) details.push(d); });
}
if (details.length > 0) {
db.saveExamReports(studentId, details);
}
return details;
});
db.saveExamReports(studentId, details);
const updatedStore = db.getExamReports(studentId); const updatedStore = db.getExamReports(studentId);
const rawDetails = updatedStore?.reports ? Object.values(updatedStore.reports) : []; const rawDetails = updatedStore?.reports ? Object.values(updatedStore.reports) : [];
const processed = ExamService.computeDeltasAndRatings(rawDetails); const processed = ExamService.computeDeltasAndRatings(rawDetails);
@ -1033,7 +1063,8 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) =>
}); });
} catch (err: any) { } catch (err: any) {
console.error('API exams sync error:', err.message); console.error('API exams sync error:', err.message);
res.status(500).json({ const status = err.message?.includes('expired') || err.message?.includes('log in') ? 401 : 500;
res.status(status).json({
success: false, success: false,
error: `Exams sync failed: ${err.message}` error: `Exams sync failed: ${err.message}`
}); });

View file

@ -1,5 +1,6 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import crypto from 'crypto';
import { import {
DatabaseSchema, DatabaseSchema,
StudentStore, StudentStore,
@ -9,11 +10,54 @@ import {
PrivateLessonsStore, PrivateLessonsStore,
ExamReportDetail, ExamReportDetail,
ExamStore, ExamStore,
ExamTopicWeakness ExamTopicWeakness,
ExamQuestionItem
} from '../types'; } from '../types';
const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json'); const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json');
// Derive 32-byte AES key from environment secret
function getEncryptionKey(): Buffer {
const secret = process.env.ENCRYPTION_SECRET || process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
return crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
}
function encryptCredential(plaintext: string): string {
try {
const key = getEncryptionKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
return `enc:${iv.toString('hex')}:${authTag}:${encrypted}`;
} catch (err) {
console.error('Failed to encrypt credential:', err);
return plaintext;
}
}
function decryptCredential(stored: string): string {
if (!stored || !stored.startsWith('enc:')) {
// Legacy plaintext support
return stored;
}
try {
const parts = stored.split(':');
if (parts.length !== 4) return stored;
const [, ivHex, authTagHex, ciphertextHex] = parts;
const key = getEncryptionKey();
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;
} catch (err) {
console.error('Failed to decrypt credential:', err);
return '';
}
}
export class LocalDatabase { export class LocalDatabase {
private static instance: LocalDatabase; private static instance: LocalDatabase;
private cache: DatabaseSchema = { students: {} }; private cache: DatabaseSchema = { students: {} };
@ -60,7 +104,7 @@ export class LocalDatabase {
private save(): void { private save(): void {
try { try {
const tmpFile = `${DB_FILE}.tmp`; const tmpFile = `${DB_FILE}.${process.pid}.${Date.now()}.tmp`;
fs.writeFileSync(tmpFile, JSON.stringify(this.cache, null, 2), 'utf-8'); fs.writeFileSync(tmpFile, JSON.stringify(this.cache, null, 2), 'utf-8');
fs.renameSync(tmpFile, DB_FILE); fs.renameSync(tmpFile, DB_FILE);
} catch (err) { } catch (err) {
@ -138,7 +182,8 @@ export class LocalDatabase {
public saveCredentials(studentId: string, password: string): void { public saveCredentials(studentId: string, password: string): void {
const student = this.getStudentStore(studentId); const student = this.getStudentStore(studentId);
student.rememberedCredentials = { studentId, password }; const encryptedPassword = encryptCredential(password);
student.rememberedCredentials = { studentId, password: encryptedPassword };
this.save(); this.save();
} }
@ -150,7 +195,11 @@ export class LocalDatabase {
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null { public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
const student = this.cache.students[studentId]; const student = this.cache.students[studentId];
return student?.rememberedCredentials || null; if (!student?.rememberedCredentials) return null;
return {
studentId: student.rememberedCredentials.studentId,
password: decryptCredential(student.rememberedCredentials.password)
};
} }
public saveSyllabus( public saveSyllabus(
@ -285,4 +334,26 @@ export class LocalDatabase {
const student = this.cache.students[studentId]; const student = this.cache.students[studentId];
return student?.exams?.topicWeaknesses?.[examId] || null; return student?.exams?.topicWeaknesses?.[examId] || null;
} }
public saveExamQuestions(studentId: string, examId: string, questions: ExamQuestionItem[]): void {
const student = this.getStudentStore(studentId);
if (!student.exams) {
student.exams = {
lastSynced: new Date().toISOString(),
reports: {},
topicWeaknesses: {},
questions: {}
};
}
if (!student.exams.questions) {
student.exams.questions = {};
}
student.exams.questions[examId] = questions;
this.save();
}
public getExamQuestions(studentId: string, examId: string): ExamQuestionItem[] | null {
const student = this.cache.students[studentId];
return student?.exams?.questions?.[examId] || null;
}
} }

View file

@ -18,6 +18,7 @@ import { DAY_NAMES } from './syllabus';
const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com'; 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;
export interface LoginResult { export interface LoginResult {
success: boolean; success: boolean;
@ -77,6 +78,7 @@ export class ScraperService {
headers: { headers: {
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 0, maxRedirects: 0,
validateStatus: () => true // Allow handling redirects manually validateStatus: () => true // Allow handling redirects manually
}); });
@ -112,6 +114,15 @@ export class ScraperService {
cookies = this.mergeCookies(cookies, postRes.headers['set-cookie']); cookies = this.mergeCookies(cookies, postRes.headers['set-cookie']);
// Check if server error
if (postRes.status >= 500) {
return {
success: false,
cookies: '',
error: `School portal returned error ${postRes.status}. The portal may be under maintenance.`
};
}
// Check if successful login (302 redirect or has auth cookies) // Check if successful login (302 redirect or has auth cookies)
const hasAuthCookie = cookies.includes('.Ogrenci.Cookie') || cookies.includes('.AspNetCore.Cookies'); const hasAuthCookie = cookies.includes('.Ogrenci.Cookie') || cookies.includes('.AspNetCore.Cookies');
const isRedirectSuccess = postRes.status === 302 && (postRes.headers.location === '/' || postRes.headers.location === ''); const isRedirectSuccess = postRes.status === 302 && (postRes.headers.location === '/' || postRes.headers.location === '');
@ -176,6 +187,7 @@ export class ScraperService {
'Cookie': cookies, 'Cookie': cookies,
'Referer': `${BASE_URL}/` 'Referer': `${BASE_URL}/`
}, },
timeout: REQUEST_TIMEOUT_MS,
validateStatus: () => true validateStatus: () => true
}); });
@ -338,6 +350,7 @@ export class ScraperService {
'Cookie': cookies, 'Cookie': cookies,
'Referer': `${BASE_URL}/` 'Referer': `${BASE_URL}/`
}, },
timeout: REQUEST_TIMEOUT_MS,
validateStatus: () => true validateStatus: () => true
}); });
@ -419,6 +432,7 @@ export class ScraperService {
'User-Agent': USER_AGENT, 'User-Agent': USER_AGENT,
'Cookie': cookies 'Cookie': cookies
}, },
timeout: REQUEST_TIMEOUT_MS,
validateStatus: () => true validateStatus: () => true
}); });
@ -504,6 +518,7 @@ export class ScraperService {
try { try {
const client = axios.create({ const client = axios.create({
headers: { 'User-Agent': USER_AGENT }, headers: { 'User-Agent': USER_AGENT },
timeout: REQUEST_TIMEOUT_MS,
validateStatus: () => true validateStatus: () => true
}); });
@ -559,7 +574,8 @@ export class ScraperService {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest', 'X-Requested-With': 'XMLHttpRequest',
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
} },
timeout: REQUEST_TIMEOUT_MS
} }
); );
@ -592,7 +608,8 @@ export class ScraperService {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest', 'X-Requested-With': 'XMLHttpRequest',
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
} },
timeout: REQUEST_TIMEOUT_MS
} }
); );
@ -643,6 +660,7 @@ export class ScraperService {
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 5, maxRedirects: 5,
validateStatus: () => true validateStatus: () => true
} }
@ -686,6 +704,7 @@ export class ScraperService {
'Cookie': cookies, 'Cookie': cookies,
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 5, maxRedirects: 5,
validateStatus: () => true validateStatus: () => true
}); });
@ -725,6 +744,7 @@ export class ScraperService {
'Cookie': cookies, 'Cookie': cookies,
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 5, maxRedirects: 5,
validateStatus: () => true validateStatus: () => true
}); });
@ -893,6 +913,7 @@ export class ScraperService {
'Cookie': cookies, 'Cookie': cookies,
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 5, maxRedirects: 5,
validateStatus: () => true validateStatus: () => true
}); });
@ -959,6 +980,7 @@ export class ScraperService {
'Cookie': cookies, 'Cookie': cookies,
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 5, maxRedirects: 5,
validateStatus: () => true validateStatus: () => true
}); });
@ -984,6 +1006,7 @@ export class ScraperService {
'Cookie': updatedCookies, 'Cookie': updatedCookies,
'User-Agent': USER_AGENT 'User-Agent': USER_AGENT
}, },
timeout: REQUEST_TIMEOUT_MS,
maxRedirects: 5, maxRedirects: 5,
validateStatus: () => true validateStatus: () => true
}); });

View file

@ -192,6 +192,7 @@ export interface ExamStore {
lastSynced: string; lastSynced: string;
reports: Record<string, ExamReportDetail>; reports: Record<string, ExamReportDetail>;
topicWeaknesses?: Record<string, ExamTopicWeakness[]>; topicWeaknesses?: Record<string, ExamTopicWeakness[]>;
questions?: Record<string, ExamQuestionItem[]>;
} }
export interface StudentStore { export interface StudentStore {

View file

@ -694,7 +694,70 @@ async function runAllTests() {
assert(pwaContent.includes('btnSync'), 'pwa.js must manage sync buttons in offline mode'); assert(pwaContent.includes('btnSync'), 'pwa.js must manage sync buttons in offline mode');
}); });
// 6. Optional Live Portal Test (via environment variables only) // 6. Security & Hardening Tests
await test('LocalDatabase: saveCredentials encrypts with AES-256-GCM and getRememberedCredentials decrypts', () => {
const fs = require('fs');
const path = require('path');
const db = LocalDatabase.getInstance();
const dbFile = path.resolve(process.cwd(), 'data', 'db.json');
const testId = 'audit_security_student';
const rawPass = 'SuperSecret123!';
db.saveCredentials(testId, rawPass);
// Verify stored format on disk is encrypted
const onDiskRaw = JSON.parse(fs.readFileSync(dbFile, 'utf-8'));
const storedCred = onDiskRaw.students[testId]?.rememberedCredentials;
assert(storedCred, 'Credentials must be saved');
assert(storedCred.password.startsWith('enc:'), 'Stored password must be encrypted with enc: prefix');
assert(!storedCred.password.includes(rawPass), 'Raw password must not be present in database file');
// Verify retrieval returns decrypted password
const retrieved = db.getRememberedCredentials(testId);
assert(retrieved !== null, 'Retrieved credentials must not be null');
assert.strictEqual(retrieved.password, rawPass, 'Decrypted password must match original raw password');
// Clean up
db.clearCredentials(testId);
});
await test('LocalDatabase: saveExamQuestions and getExamQuestions persists question review cache', () => {
const db = LocalDatabase.getInstance();
const testId = 'audit_exam_student';
const examKey = '3366_Y';
const sampleQuestions = [
{
questionNumber: 1,
correctAnswer: 'A',
studentAnswer: 'C',
imageUrl: 'https://panel.example.com/soru/1.png',
status: 'wrong' as const,
subjectId: '10',
subjectName: 'Türkçe'
}
];
db.saveExamQuestions(testId, examKey, sampleQuestions);
const cached = db.getExamQuestions(testId, examKey);
assert(cached !== null, 'Cached questions should exist');
assert.strictEqual(cached.length, 1);
assert.strictEqual(cached[0].questionNumber, 1);
assert.strictEqual(cached[0].correctAnswer, 'A');
});
await test('PWA: sw.js contains route-specific offline fallbacks and ignoreSearch', () => {
const fs = require('fs');
const path = require('path');
const swPath = path.resolve(__dirname, '../public/sw.js');
const swContent = fs.readFileSync(swPath, 'utf-8');
assert(swContent.includes('ignoreSearch: true'), 'sw.js must match cache ignoring query strings');
assert(swContent.includes("url.pathname.startsWith('/exams')"), 'sw.js must have route fallback for exams');
assert(swContent.includes("url.pathname.startsWith('/syllabus')"), 'sw.js must have route fallback for syllabus');
assert(swContent.includes("url.pathname.startsWith('/private-lessons')"), 'sw.js must have route fallback for private lessons');
});
// 7. 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;

View file

@ -140,7 +140,7 @@
</span> </span>
<h2 class="exam-title-text" id="selectedExamTitle"><%= selectedExam.summary.name %></h2> <h2 class="exam-title-text" id="selectedExamTitle"><%= selectedExam.summary.name %></h2>
<% if (selectedExam.hasAnswerKey && selectedExam.answerKeyUrl) { %> <% if (selectedExam.hasAnswerKey && selectedExam.answerKeyUrl) { %>
<a href="<%= selectedExam.answerKeyUrl %>" target="_blank" class="btn btn-outline btn-xs" title="Cevap Anahtarı"> <a href="<%= selectedExam.answerKeyUrl %>" target="_blank" rel="noopener noreferrer" class="btn btn-outline btn-xs" title="Cevap Anahtarı">
Cevap Anahtarı Cevap Anahtarı
</a> </a>
<% } %> <% } %>

View file

@ -174,14 +174,18 @@
</td> </td>
<% [1, 2, 3, 4, 5].forEach(function(d) { %> <% [1, 2, 3, 4, 5].forEach(function(d) { %>
<% const lesson = (filteredSchedule[d] || []).find(l => l.periodNumber === p); %> <% const dayLessons = (filteredSchedule[d] || []).filter(l => l.periodNumber === p); %>
<td class="grid-lesson-cell <%= lesson ? 'has-lesson' : '' %>"> <td class="grid-lesson-cell <%= dayLessons.length > 0 ? 'has-lesson' : '' %>">
<% if (lesson) { %> <% if (dayLessons.length > 0) { %>
<div class="grid-lesson-subject"><%= lesson.subject %></div> <% dayLessons.forEach(function(lesson) { %>
<div class="grid-lesson-teacher"><%= lesson.teacher %></div> <div class="grid-lesson-item">
<% if (lesson.station) { %> <div class="grid-lesson-subject"><%= lesson.subject %></div>
<span class="grid-station-tag"><%= lesson.station %></span> <div class="grid-lesson-teacher"><%= lesson.teacher %></div>
<% } %> <% if (lesson.station) { %>
<span class="grid-station-tag"><%= lesson.station %></span>
<% } %>
</div>
<% }); %>
<% } else { %> <% } else { %>
<span class="grid-empty-cell">&mdash;</span> <span class="grid-empty-cell">&mdash;</span>
<% } %> <% } %>