diff --git a/public/css/style.css b/public/css/style.css index 6498e5d..070a40f 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1070,6 +1070,12 @@ code { background: #ffffff; } +.grid-lesson-item:not(:last-child) { + margin-bottom: 6px; + padding-bottom: 6px; + border-bottom: 1px dashed var(--border); +} + .grid-lesson-subject { font-weight: 600; font-size: 0.825rem; @@ -1660,6 +1666,23 @@ code { 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 { background: var(--bg-card); diff --git a/public/js/app.js b/public/js/app.js index e1dcdbf..2991f31 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -211,9 +211,17 @@ document.addEventListener('DOMContentLoaded', () => { }); } + function normalizeTurkish(str) { + if (!str) return ''; + return str + .replace(/İ/g, 'i') + .replace(/I/g, 'ı') + .toLowerCase(); + } + if (searchInput) { 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); applyFilters(); }); @@ -290,7 +298,7 @@ document.addEventListener('DOMContentLoaded', () => { let matchesSearch = true; if (currentSearch) { - matchesSearch = searchText.includes(currentSearch); + matchesSearch = normalizeTurkish(searchText).includes(currentSearch); } if (matchesTab && matchesSubject && matchesSearch) { diff --git a/public/js/exams.js b/public/js/exams.js index d412d26..54dbe01 100644 --- a/public/js/exams.js +++ b/public/js/exams.js @@ -221,11 +221,16 @@ document.addEventListener('DOMContentLoaded', () => { // ---------------------------------------------------- // Inline Mistake Review Modal // ---------------------------------------------------- - function openReviewModal(targetSubjectName = null) { + function openReviewModal(targetSubjectName = null, targetType = 'all') { if (!mistakeModal || !currentExamId) return; mistakeModal.classList.remove('hidden'); document.body.style.overflow = 'hidden'; + activeTypeFilter = targetType || 'all'; + modalTypeBtns.forEach(b => { + b.classList.toggle('active', b.getAttribute('data-type') === activeTypeFilter); + }); + if (!cachedQuestions) { loadExamQuestions(targetSubjectName); } else { @@ -244,7 +249,7 @@ document.addEventListener('DOMContentLoaded', () => { } if (btnReviewMistakes) { - btnReviewMistakes.addEventListener('click', () => openReviewModal()); + btnReviewMistakes.addEventListener('click', () => openReviewModal(null, 'all')); } if (btnMistakeModalClose) { @@ -256,7 +261,9 @@ document.addEventListener('DOMContentLoaded', () => { btn.addEventListener('click', (e) => { e.stopPropagation(); 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); }); }); diff --git a/public/js/private-lessons.js b/public/js/private-lessons.js index 361bcf9..a73cd95 100644 --- a/public/js/private-lessons.js +++ b/public/js/private-lessons.js @@ -59,8 +59,13 @@ document.addEventListener('DOMContentLoaded', () => { const data = await res.json(); if (data.success && data.units && data.units.length > 0) { - selectUnit.innerHTML = '' + - data.units.map(u => ``).join(''); + selectUnit.innerHTML = ''; + data.units.forEach(u => { + const opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.name; + selectUnit.appendChild(opt); + }); selectUnit.disabled = false; } else { selectUnit.innerHTML = ''; @@ -93,8 +98,13 @@ document.addEventListener('DOMContentLoaded', () => { const data = await res.json(); if (data.success && data.topics && data.topics.length > 0) { - selectTopic.innerHTML = '' + - data.topics.map(t => ``).join(''); + selectTopic.innerHTML = ''; + data.topics.forEach(t => { + const opt = document.createElement('option'); + opt.value = t.id; + opt.textContent = t.name; + selectTopic.appendChild(opt); + }); selectTopic.disabled = false; } else { selectTopic.innerHTML = ''; diff --git a/public/js/pwa.js b/public/js/pwa.js index 0ddc7ea..14af080 100644 --- a/public/js/pwa.js +++ b/public/js/pwa.js @@ -3,6 +3,7 @@ */ (function () { let isOffline = !navigator.onLine; + let bannerTimeout = null; // 1. Service Worker Registration if ('serviceWorker' in navigator) { @@ -41,6 +42,10 @@ } function showOfflineBanner() { + if (bannerTimeout) { + clearTimeout(bannerTimeout); + bannerTimeout = null; + } const banner = getOrCreateBanner(); banner.className = 'offline-banner active'; banner.innerHTML = ` @@ -52,6 +57,10 @@ } function showOnlineBanner() { + if (bannerTimeout) { + clearTimeout(bannerTimeout); + bannerTimeout = null; + } const banner = getOrCreateBanner(); banner.className = 'offline-banner online'; banner.innerHTML = ` @@ -60,8 +69,9 @@ Connection restored. Live features re-enabled. `; - setTimeout(() => { + bannerTimeout = setTimeout(() => { banner.className = 'offline-banner hidden'; + bannerTimeout = null; }, 2800); } @@ -104,7 +114,7 @@ // --- B. Private Lesson Request Form --- 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"]'); 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 = [ '#btnSyncRecent', '#btnSyncAll', diff --git a/public/js/syllabus.js b/public/js/syllabus.js index be318cc..7bcfa53 100644 --- a/public/js/syllabus.js +++ b/public/js/syllabus.js @@ -13,6 +13,11 @@ document.addEventListener('DOMContentLoaded', () => { const btn = e.target.closest('.station-btn'); 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; stationPills.querySelectorAll('.station-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); diff --git a/public/sw.js b/public/sw.js index a89b167..da60ad8 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,7 +1,11 @@ -const CACHE_NAME = 'bekultur-v1'; +const CACHE_NAME = 'bekultur-v2'; const STATIC_ASSETS = [ '/', + '/dashboard', + '/syllabus', + '/private-lessons', + '/exams', '/css/style.css', '/js/pwa.js', '/js/app.js', @@ -53,13 +57,19 @@ self.addEventListener('fetch', (event) => { 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 - if (url.origin !== self.location.origin) { + if (url.origin !== self.location.origin && !isQuestionImage) { return; } - // 1. Static Assets (CSS, JS, Icons, Images) -> Cache-First + // 1. Static Assets & Question Images -> Cache-First const isStatic = + isQuestionImage || url.pathname.startsWith('/css/') || url.pathname.startsWith('/js/') || url.pathname.startsWith('/icons/') || @@ -75,11 +85,14 @@ self.addEventListener('fetch', (event) => { return cachedResponse; } return fetch(req).then((networkResponse) => { - if (networkResponse && networkResponse.status === 200) { + if (networkResponse && (networkResponse.status === 200 || networkResponse.type === 'opaque')) { const clone = networkResponse.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(req, clone)); } 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 () => { // 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) { 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 (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'); if (fallbackDashboard) return fallbackDashboard; diff --git a/src/server.ts b/src/server.ts index 258d25b..5ca4525 100644 --- a/src/server.ts +++ b/src/server.ts @@ -8,7 +8,7 @@ import { LocalDatabase } from './services/db'; import { InsightService } from './services/insight'; import { SyllabusService, DAY_NAMES } from './services/syllabus'; import { ExamService } from './services/exam'; -import { Assignment } from './types'; +import { Assignment, ExamReportDetail } from './types'; dotenv.config(); @@ -26,7 +26,7 @@ app.set('views', viewsPath); // Middleware app.use(express.urlencoded({ extended: true })); app.use(express.json()); -app.use(cookieParser()); +app.use(cookieParser(SESSION_SECRET)); // Custom Service Worker route with proper scope and no-cache headers app.get('/sw.js', (req: Request, res: Response) => { @@ -49,7 +49,10 @@ app.use( resave: false, saveUninitialized: false, 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) { 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) { const creds = db.getRememberedCredentials(rememberedId); if (creds) { @@ -84,17 +90,91 @@ function requireAuth(req: Request, res: Response, next: NextFunction) { return next(); } else { res.clearCookie('bekultur_student_id'); + if (isAjax) { + return res.status(401).json({ success: false, error: 'Session expired. Please log in again.' }); + } return res.redirect('/'); } }).catch(() => { + if (isAjax) { + return res.status(401).json({ success: false, error: 'Connection error during auto-login.' }); + } return res.redirect('/'); }); 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('/'); } +/** + * Helper to obtain active portal cookies from session or remembered credentials + */ +async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise { + if (req.session.portalCookies) { + return req.session.portalCookies; + } + const creds = db.getRememberedCredentials(studentId); + if (creds) { + const loginRes = await ScraperService.login(creds.studentId, creds.password); + if (loginRes.success) { + req.session.portalCookies = loginRes.cookies; + req.session.studentName = loginRes.studentName || req.session.studentName; + return loginRes.cookies; + } + } + return undefined; +} + +/** + * Execute scraper action with automatic session-recovery retry + */ +async function executeWithPortalSession( + req: Request, + studentId: string, + action: (cookies: string) => Promise +): Promise { + 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 // ---------------------------------------------------- @@ -108,7 +188,7 @@ app.get('/', (req: Request, res: Response) => { 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; res.render('login', { @@ -152,8 +232,11 @@ app.post('/login', async (req: Request, res: Response) => { if (rememberMe) { db.saveCredentials(studentId, password); res.cookie('bekultur_student_id', studentId, { + signed: true, maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days - httpOnly: true + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production' }); } else { db.clearCredentials(studentId); @@ -183,6 +266,7 @@ app.post('/login', async (req: Request, res: Response) => { * POST /logout */ app.post('/logout', (req: Request, res: Response) => { + res.clearCookie('bekultur_student_id'); req.session.destroy(() => { res.redirect('/'); }); @@ -192,6 +276,7 @@ app.post('/logout', (req: Request, res: Response) => { * GET /logout (convenience) */ app.get('/logout', (req: Request, res: Response) => { + res.clearCookie('bekultur_student_id'); req.session.destroy(() => { 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) => { const studentId = req.session.studentId!; - let cookies = req.session.portalCookies; try { - // If session cookies missing, attempt re-login using remembered credentials - 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.' - }); - } - - const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2); + const scrapeRes = await executeWithPortalSession(req, studentId, async (cookies) => { + return await ScraperService.scrapeMultiplePages(cookies, studentId, 2); + }); db.mergeAssignments(studentId, scrapeRes.assignments); const store = db.getStudentStore(studentId); @@ -361,7 +428,8 @@ app.post('/api/sync', requireAuth, async (req: Request, res: Response) => { }); } catch (err: any) { 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, 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) => { const studentId = req.session.studentId!; - let cookies = req.session.portalCookies; 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) - 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); const store = db.getStudentStore(studentId); @@ -415,7 +466,8 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => { }); } catch (err: any) { 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, 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 (!syllabusStore || !syllabusStore.weekId || syllabusStore.weekId !== currentWeek.weekId) { - let cookies = req.session.portalCookies; - 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) { - 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); - } + try { + const schedule = await executeWithPortalSession(req, studentId, async (cookies) => { + return await ScraperService.scrapeSyllabus(cookies); + }); + db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule); + syllabusStore = db.getSyllabus(studentId); + } catch (err: any) { + console.warn('Auto-syncing weekly syllabus note (using cached if available):', 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) => { const studentId = req.session.studentId!; - let cookies = req.session.portalCookies; 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 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); const store = db.getSyllabus(studentId); @@ -594,7 +617,8 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) }); } catch (err: any) { 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, 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 (!store || !store.lessons || !store.formMeta) { - let cookies = req.session.portalCookies; - 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) { - try { - const [privateRes, formMeta] = await Promise.all([ + try { + const [privateRes, formMeta] = await executeWithPortalSession(req, studentId, async (cookies) => { + return await Promise.all([ ScraperService.scrapePrivateLessons(cookies), ScraperService.fetchPrivateLessonFormMeta(studentId) ]); - - db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); - store = db.getPrivateLessons(studentId); - } catch (err: any) { - console.error('Error auto-syncing private lessons:', err.message); - } + }); + db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); + store = db.getPrivateLessons(studentId); + } catch (err: any) { + 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) => { const studentId = req.session.studentId!; - let cookies = req.session.portalCookies; 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 private lessons.' - }); - } - - const [privateRes, formMeta] = await Promise.all([ - ScraperService.scrapePrivateLessons(cookies), - ScraperService.fetchPrivateLessonFormMeta(studentId) - ]); + const [privateRes, formMeta] = await executeWithPortalSession(req, studentId, async (cookies) => { + return await Promise.all([ + ScraperService.scrapePrivateLessons(cookies), + ScraperService.fetchPrivateLessonFormMeta(studentId) + ]); + }); db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); const store = db.getPrivateLessons(studentId); @@ -780,7 +774,8 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res }); } catch (err: any) { 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, 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 // ---------------------------------------------------- -/** - * Helper to ensure active portal cookies - */ -async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise { - if (req.session.portalCookies) { - return req.session.portalCookies; - } - const creds = db.getRememberedCredentials(studentId); - if (creds) { - const loginRes = await ScraperService.login(creds.studentId, creds.password); - if (loginRes.success) { - req.session.portalCookies = loginRes.cookies; - return loginRes.cookies; - } - } - return undefined; -} - /** * GET /rapor/sinav * 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 (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) { - const cookies = await getOrRefreshPortalCookies(req, studentId); - if (cookies) { - try { + try { + await executeWithPortalSession(req, studentId, async (cookies) => { const examList = await ScraperService.scrapeExamList(cookies); if (examList.length > 0) { - const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id)); - const details = (await Promise.all(detailPromises)).filter( - (d): d is NonNullable => d !== null - ); - db.saveExamReports(studentId, details); - examStore = db.getExamReports(studentId); + const details: ExamReportDetail[] = []; + 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); + examStore = db.getExamReports(studentId); + } } - } catch (err: any) { - console.error('Initial exam scrape error:', err.message); - } + return null; + }); + } 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]; if (!exam) { - const cookies = await getOrRefreshPortalCookies(req, studentId); - if (cookies) { - const fetched = await ScraperService.scrapeExamDetail(cookies, examId); - if (fetched) { - db.saveExamReports(studentId, [fetched]); - examStore = db.getExamReports(studentId); - } + try { + await executeWithPortalSession(req, studentId, async (cookies) => { + const fetched = await ScraperService.scrapeExamDetail(cookies, examId); + if (fetched) { + db.saveExamReports(studentId, [fetched]); + 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 tip = ((req.query.tip as string) || 'Y').toUpperCase() as 'D' | 'Y' | 'B'; - const cookies = await getOrRefreshPortalCookies(req, studentId); - if (!cookies) { - return res.status(401).json({ success: false, error: 'Session expired' }); + const cacheKey = `${examId}_${tip}`; + + // 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 - if (dersId && ogrenciDonemId) { - const questions = await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip); - return res.json({ success: true, questions }); + // Check if all questions for this exam and tip are cached in db.json + const cachedQuestions = db.getExamQuestions(studentId, cacheKey); + if (cachedQuestions && cachedQuestions.length > 0) { + const subjectsMap: Record = {}; + 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 @@ -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' }); } - const subjectQuestionsList: Array<{ - subjectName: string; - subjectId: string; - questions: any[]; - }> = []; + try { + const subjectQuestionsList: Array<{ + subjectName: string; + subjectId: string; + questions: any[]; + }> = []; + const allScrapedQuestions: any[] = []; - for (const subject of exam.subjects) { - const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true; - if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) { - const q = await ScraperService.scrapeExamQuestions( - cookies, - examId, - subject.ogrenciDonemId, - subject.subjectId, - tip - ); - if (q.length > 0) { - subjectQuestionsList.push({ - subjectName: subject.subjectName, - subjectId: subject.subjectId, - questions: q - }); + await executeWithPortalSession(req, studentId, async (cookies) => { + for (const subject of exam.subjects) { + const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true; + if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) { + const q = await ScraperService.scrapeExamQuestions( + cookies, + examId, + subject.ogrenciDonemId, + subject.subjectId, + tip + ); + if (q.length > 0) { + q.forEach(item => { + item.subjectName = subject.subjectName; + allScrapedQuestions.push(item); + }); + subjectQuestionsList.push({ + subjectName: subject.subjectName, + subjectId: subject.subjectId, + questions: q + }); + } + } } - } - } + return null; + }); - res.json({ - success: true, - totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0), - subjects: subjectQuestionsList - }); + if (allScrapedQuestions.length > 0) { + db.saveExamQuestions(studentId, cacheKey, allScrapedQuestions); + } + + 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 }); } - const cookies = await getOrRefreshPortalCookies(req, studentId); - if (!cookies) { - return res.status(401).json({ success: false, error: 'Session expired' }); + try { + const weaknesses = await executeWithPortalSession(req, studentId, async (cookies) => { + 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) => { 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 { - const examList = await ScraperService.scrapeExamList(cookies); - if (!examList || examList.length === 0) { - return res.json({ success: true, count: 0, message: 'No exams found on portal.' }); - } + await executeWithPortalSession(req, studentId, async (cookies) => { + const examList = await ScraperService.scrapeExamList(cookies); + if (!examList || examList.length === 0) { + return []; + } - const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id)); - const details = (await Promise.all(detailPromises)).filter( - (d): d is NonNullable => d !== null - ); + // Batch requests in chunks of 3 to avoid overwhelming portal + const details: ExamReportDetail[] = []; + 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 rawDetails = updatedStore?.reports ? Object.values(updatedStore.reports) : []; const processed = ExamService.computeDeltasAndRatings(rawDetails); @@ -1033,7 +1063,8 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => }); } catch (err: any) { 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, error: `Exams sync failed: ${err.message}` }); diff --git a/src/services/db.ts b/src/services/db.ts index b27eeba..96ca5c7 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -1,5 +1,6 @@ import fs from 'fs'; import path from 'path'; +import crypto from 'crypto'; import { DatabaseSchema, StudentStore, @@ -9,11 +10,54 @@ import { PrivateLessonsStore, ExamReportDetail, ExamStore, - ExamTopicWeakness + ExamTopicWeakness, + ExamQuestionItem } from '../types'; 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 { private static instance: LocalDatabase; private cache: DatabaseSchema = { students: {} }; @@ -60,7 +104,7 @@ export class LocalDatabase { private save(): void { 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.renameSync(tmpFile, DB_FILE); } catch (err) { @@ -138,7 +182,8 @@ export class LocalDatabase { public saveCredentials(studentId: string, password: string): void { const student = this.getStudentStore(studentId); - student.rememberedCredentials = { studentId, password }; + const encryptedPassword = encryptCredential(password); + student.rememberedCredentials = { studentId, password: encryptedPassword }; this.save(); } @@ -150,7 +195,11 @@ export class LocalDatabase { public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null { 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( @@ -285,4 +334,26 @@ export class LocalDatabase { const student = this.cache.students[studentId]; 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; + } } diff --git a/src/services/scraper.ts b/src/services/scraper.ts index 8a1bb2f..1697a4e 100644 --- a/src/services/scraper.ts +++ b/src/services/scraper.ts @@ -18,6 +18,7 @@ import { DAY_NAMES } from './syllabus'; const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com'; const BILGI_BASE_URL = 'https://bilgi.ozelbursakulturokullari.com'; const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; +const REQUEST_TIMEOUT_MS = 12000; export interface LoginResult { success: boolean; @@ -77,6 +78,7 @@ export class ScraperService { headers: { 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 0, validateStatus: () => true // Allow handling redirects manually }); @@ -112,6 +114,15 @@ export class ScraperService { 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) const hasAuthCookie = cookies.includes('.Ogrenci.Cookie') || cookies.includes('.AspNetCore.Cookies'); const isRedirectSuccess = postRes.status === 302 && (postRes.headers.location === '/' || postRes.headers.location === ''); @@ -176,6 +187,7 @@ export class ScraperService { 'Cookie': cookies, 'Referer': `${BASE_URL}/` }, + timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true }); @@ -338,6 +350,7 @@ export class ScraperService { 'Cookie': cookies, 'Referer': `${BASE_URL}/` }, + timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true }); @@ -419,6 +432,7 @@ export class ScraperService { 'User-Agent': USER_AGENT, 'Cookie': cookies }, + timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true }); @@ -504,6 +518,7 @@ export class ScraperService { try { const client = axios.create({ headers: { 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true }); @@ -559,7 +574,8 @@ export class ScraperService { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', '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', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': USER_AGENT - } + }, + timeout: REQUEST_TIMEOUT_MS } ); @@ -643,6 +660,7 @@ export class ScraperService { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 5, validateStatus: () => true } @@ -686,6 +704,7 @@ export class ScraperService { 'Cookie': cookies, 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 5, validateStatus: () => true }); @@ -725,6 +744,7 @@ export class ScraperService { 'Cookie': cookies, 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 5, validateStatus: () => true }); @@ -893,6 +913,7 @@ export class ScraperService { 'Cookie': cookies, 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 5, validateStatus: () => true }); @@ -959,6 +980,7 @@ export class ScraperService { 'Cookie': cookies, 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 5, validateStatus: () => true }); @@ -984,6 +1006,7 @@ export class ScraperService { 'Cookie': updatedCookies, 'User-Agent': USER_AGENT }, + timeout: REQUEST_TIMEOUT_MS, maxRedirects: 5, validateStatus: () => true }); diff --git a/src/types/index.ts b/src/types/index.ts index 2ad8a4b..6c4cd2c 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -192,6 +192,7 @@ export interface ExamStore { lastSynced: string; reports: Record; topicWeaknesses?: Record; + questions?: Record; } export interface StudentStore { diff --git a/test/run-tests.ts b/test/run-tests.ts index abc2993..fb6e1df 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -694,7 +694,70 @@ async function runAllTests() { 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 testPassword = process.env.TEST_PASSWORD; diff --git a/views/exams.ejs b/views/exams.ejs index da8c4e2..a29b58c 100644 --- a/views/exams.ejs +++ b/views/exams.ejs @@ -140,7 +140,7 @@

<%= selectedExam.summary.name %>

<% if (selectedExam.hasAnswerKey && selectedExam.answerKeyUrl) { %> - + Cevap Anahtarı <% } %> diff --git a/views/syllabus.ejs b/views/syllabus.ejs index 201a557..342fb58 100644 --- a/views/syllabus.ejs +++ b/views/syllabus.ejs @@ -174,14 +174,18 @@ <% [1, 2, 3, 4, 5].forEach(function(d) { %> - <% const lesson = (filteredSchedule[d] || []).find(l => l.periodNumber === p); %> - - <% if (lesson) { %> -
<%= lesson.subject %>
-
<%= lesson.teacher %>
- <% if (lesson.station) { %> - <%= lesson.station %> - <% } %> + <% const dayLessons = (filteredSchedule[d] || []).filter(l => l.periodNumber === p); %> + + <% if (dayLessons.length > 0) { %> + <% dayLessons.forEach(function(lesson) { %> +
+
<%= lesson.subject %>
+
<%= lesson.teacher %>
+ <% if (lesson.station) { %> + <%= lesson.station %> + <% } %> +
+ <% }); %> <% } else { %> — <% } %>