feat: upgrade to SQLite session & data store with zero-data-loss migration, dark theme, and Turkish i18n

This commit is contained in:
tyuXX 2026-11-09 20:54:26 +00:00
parent 1af973d001
commit 56274f479b
27 changed files with 4222 additions and 1360 deletions

View file

@ -1,6 +1,8 @@
import express, { Request, Response, NextFunction } from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import path from 'path';
import dotenv from 'dotenv';
import { ScraperService } from './services/scraper';
@ -8,13 +10,25 @@ import { LocalDatabase } from './services/db';
import { InsightService } from './services/insight';
import { SyllabusService, DAY_NAMES } from './services/syllabus';
import { ExamService } from './services/exam';
import { getSessionSecret } from './services/secrets';
import { SQLiteSessionStore } from './services/session-store';
import {
SupportedLocale,
DEFAULT_LOCALE,
normalizeLocale,
createTranslator,
getClientDictionary
} from './services/i18n';
import { Assignment, ExamReportDetail } from './types';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const SESSION_SECRET = process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
const SESSION_SECRET = getSessionSecret();
// Trust first proxy (Cloudflare Tunnel / reverse proxy) so secure cookies work over proxied HTTPS
app.set('trust proxy', 1);
// View engine setup
app.set('view engine', 'ejs');
@ -23,11 +37,61 @@ const viewsPath = path.resolve(__dirname, '../views');
const publicPath = path.resolve(__dirname, '../public');
app.set('views', viewsPath);
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Security Headers (Helmet with CSP tailored for BeKultur & school portal question images)
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
scriptSrcAttr: ["'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: [
"'self'",
'data:',
'https://*.ozelbursakulturokullari.com',
'http://*.ozelbursakulturokullari.com'
],
connectSrc: ["'self'"],
fontSrc: ["'self'", 'data:'],
objectSrc: ["'none'"],
frameAncestors: ["'none'"],
upgradeInsecureRequests: null
}
},
crossOriginEmbedderPolicy: false,
crossOriginResourcePolicy: { policy: 'cross-origin' }
})
);
// Body & Cookie Parsers
app.use(express.urlencoded({ extended: true, limit: '256kb' }));
app.use(express.json({ limit: '256kb' }));
app.use(cookieParser(SESSION_SECRET));
// Localization Middleware (Default: Turkish 'tr', switchable to 'en')
app.use((req: Request, res: Response, next: NextFunction) => {
let lang: SupportedLocale = DEFAULT_LOCALE;
if (typeof req.query.lang === 'string' && (req.query.lang === 'tr' || req.query.lang === 'en')) {
lang = normalizeLocale(req.query.lang);
res.cookie('bekultur_lang', lang, {
maxAge: 365 * 24 * 60 * 60 * 1000,
httpOnly: false,
sameSite: 'lax'
});
} else if (req.cookies?.bekultur_lang) {
lang = normalizeLocale(req.cookies.bekultur_lang);
}
const t = createTranslator(lang);
res.locals.lang = lang;
res.locals.t = t;
res.locals.i18nJson = JSON.stringify(getClientDictionary(lang));
res.locals.activePage = '';
next();
});
// Custom Service Worker route with proper scope and no-cache headers
app.get('/sw.js', (req: Request, res: Response) => {
res.setHeader('Service-Worker-Allowed', '/');
@ -43,8 +107,17 @@ app.get('/api/health', (req: Request, res: Response) => {
app.use(express.static(publicPath));
// Initialize SQLite Database & Persistent SQLite Session Store
const db = LocalDatabase.getInstance();
const sessionStore = new SQLiteSessionStore({
db: db.getSqliteDb(),
ttlMs: 14 * 24 * 60 * 60 * 1000
});
app.use(
session({
store: sessionStore,
name: 'bekultur.sid',
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
@ -52,11 +125,32 @@ app.use(
maxAge: 14 * 24 * 60 * 60 * 1000, // 14 days
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production'
secure: process.env.COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'false')
}
})
);
// Rate Limiters for Production Hardening
const isTestEnv = process.env.NODE_ENV === 'test';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: isTestEnv ? 1000 : 20,
standardHeaders: true,
legacyHeaders: false,
message: 'Çok fazla giriş denemesi yapıldı. Lütfen 15 dakika sonra tekrar deneyiniz.'
});
const apiLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: isTestEnv ? 5000 : 120,
standardHeaders: true,
legacyHeaders: false,
message: { success: false, error: 'Çok fazla istek gönderildi. Lütfen biraz bekleyiniz.' }
});
app.use('/api/', apiLimiter);
// Augment express-session
declare module 'express-session' {
interface SessionData {
@ -66,7 +160,36 @@ declare module 'express-session' {
}
}
const db = LocalDatabase.getInstance();
// Language Switcher Endpoints
app.get('/lang/:locale', (req: Request, res: Response) => {
const locale = normalizeLocale(req.params.locale);
res.cookie('bekultur_lang', locale, {
maxAge: 365 * 24 * 60 * 60 * 1000,
httpOnly: false,
sameSite: 'lax'
});
const referer = req.get('Referer') || '/';
// Avoid open redirect: only allow relative paths or same host
if (referer.startsWith('/')) {
return res.redirect(referer);
}
try {
const refUrl = new URL(referer);
return res.redirect(refUrl.pathname + refUrl.search);
} catch {
return res.redirect('/');
}
});
app.post('/api/preferences/lang', (req: Request, res: Response) => {
const locale = normalizeLocale(req.body?.lang);
res.cookie('bekultur_lang', locale, {
maxAge: 365 * 24 * 60 * 60 * 1000,
httpOnly: false,
sameSite: 'lax'
});
res.json({ success: true, lang: locale });
});
// Auth guard helper
function requireAuth(req: Request, res: Response, next: NextFunction) {
@ -176,9 +299,16 @@ async function executeWithPortalSession<T>(
}
// ----------------------------------------------------
// Routes
// Routes & Official E-Kültür Aliases
// ----------------------------------------------------
app.get('/login', (req: Request, res: Response) => res.redirect('/'));
app.get('/Kullanici/Giris', (req: Request, res: Response) => res.redirect('/'));
app.get('/giris', (req: Request, res: Response) => res.redirect('/'));
app.get('/Odev', (req: Request, res: Response) => res.redirect('/dashboard'));
app.get('/odev', (req: Request, res: Response) => res.redirect('/dashboard'));
app.get('/dersprogrami', (req: Request, res: Response) => res.redirect('/syllabus'));
/**
* GET /
* Login Page
@ -190,11 +320,13 @@ app.get('/', (req: Request, res: Response) => {
const rememberedId = req.signedCookies?.bekultur_student_id || '';
const error = (req.query.error as string) || null;
const t = res.locals.t;
res.render('login', {
error,
rememberedId,
title: 'Login - BeKultur (Better E-Kultur)'
activePage: 'login',
title: t('login.pageTitle')
});
});
@ -202,51 +334,56 @@ app.get('/', (req: Request, res: Response) => {
* POST /login
* Authenticate against portal and scrape recent assignments
*/
app.post('/login', async (req: Request, res: Response) => {
app.post('/login', loginLimiter, async (req: Request, res: Response) => {
const { studentId, password, rememberMe } = req.body;
const t = res.locals.t;
const cleanStudentId = typeof studentId === 'string' ? studentId.trim() : '';
const cleanPassword = typeof password === 'string' ? password : '';
if (!studentId || !password) {
if (!cleanStudentId || !cleanPassword) {
return res.render('login', {
error: 'Please enter both Student ID and Password.',
rememberedId: studentId || '',
title: 'Login - BeKultur'
error: t('login.errorMissing'),
rememberedId: cleanStudentId,
activePage: 'login',
title: t('login.pageTitle')
});
}
try {
const loginRes = await ScraperService.login(studentId, password);
const loginRes = await ScraperService.login(cleanStudentId, cleanPassword);
if (!loginRes.success) {
return res.render('login', {
error: loginRes.error || 'Authentication failed. Please check your credentials.',
rememberedId: studentId,
title: 'Login - BeKultur'
error: loginRes.error || t('login.errorInvalid'),
rememberedId: cleanStudentId,
activePage: 'login',
title: t('login.pageTitle')
});
}
req.session.studentId = studentId;
req.session.studentId = cleanStudentId;
req.session.portalCookies = loginRes.cookies;
req.session.studentName = loginRes.studentName;
// Handle "Remember Me"
if (rememberMe) {
db.saveCredentials(studentId, password);
res.cookie('bekultur_student_id', studentId, {
db.saveCredentials(cleanStudentId, cleanPassword);
res.cookie('bekultur_student_id', cleanStudentId, {
signed: true,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production'
secure: process.env.COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'false')
});
} else {
db.clearCredentials(studentId);
db.clearCredentials(cleanStudentId);
res.clearCookie('bekultur_student_id');
}
// Scrape recent pages (1-2)
try {
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, studentId, 2);
db.mergeAssignments(studentId, scrapeRes.assignments);
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2);
db.mergeAssignments(cleanStudentId, scrapeRes.assignments);
} catch (scrapeErr: any) {
console.warn('Initial scrape warning (cached data will be used if available):', scrapeErr.message);
}
@ -255,9 +392,10 @@ app.post('/login', async (req: Request, res: Response) => {
} catch (err: any) {
console.error('Login route error:', err);
res.render('login', {
error: 'An unexpected server error occurred during login.',
rememberedId: studentId,
title: 'Login - BeKultur'
error: t('login.errorServer'),
rememberedId: cleanStudentId,
activePage: 'login',
title: t('login.pageTitle')
});
}
});
@ -284,11 +422,12 @@ app.get('/logout', (req: Request, res: Response) => {
/**
* GET /dashboard
* English dashboard with stats and checkable assignments
* Homework (Ödevler) dashboard with stats and checkable assignments
*/
app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const studentStore = db.getStudentStore(studentId);
const t = res.locals.t;
// Recalculate status for each assignment relative to current date
const rawList = Object.values(studentStore.assignments);
@ -327,9 +466,10 @@ app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
});
res.render('dashboard', {
title: 'Dashboard - BeKultur',
title: t('dashboard.pageTitle'),
activePage: 'dashboard',
studentId,
studentName: req.session.studentName || `Student ${studentId}`,
studentName: req.session.studentName || `${t('dashboard.studentLabel')} ${studentId}`,
lastSynced: studentStore.lastSynced,
stats,
assignments: updatedAssignments,
@ -345,7 +485,7 @@ app.post('/api/toggle', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { assignmentId, completed } = req.body;
if (!assignmentId) {
if (!assignmentId || typeof assignmentId !== 'string') {
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
}
@ -377,7 +517,7 @@ app.post('/api/exclude', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { assignmentId, excluded } = req.body;
if (!assignmentId) {
if (!assignmentId || typeof assignmentId !== 'string') {
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
}
@ -481,6 +621,8 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const currentWeek = SyllabusService.getWeekMetadata();
const t = res.locals.t;
const lang = res.locals.lang as SupportedLocale;
let syllabusStore = db.getSyllabus(studentId);
@ -504,7 +646,8 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
// Active day: 1 = Mon .. 5 = Fri (if weekend, default to Mon)
const todayDay = new Date().getDay();
const defaultDay = todayDay >= 1 && todayDay <= 5 ? todayDay : 1;
const activeDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay;
const parsedQueryDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay;
const activeDay = parsedQueryDay >= 1 && parsedQueryDay <= 5 ? parsedQueryDay : defaultDay;
// Compute filtered schedule for selected station & advisory teacher
const rawSchedule = syllabusStore?.schedule || {};
@ -515,11 +658,14 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
const currentStatus = SyllabusService.getCurrentLessonStatus(
filteredSchedule[activeDay] || [],
activeDay
activeDay,
new Date(),
lang
);
res.render('syllabus', {
title: 'Syllabus - BeKultur',
title: t('syllabus.pageTitle'),
activePage: 'syllabus',
studentId,
weekId: currentWeek.weekId,
weekRange: currentWeek.weekRange,
@ -636,6 +782,7 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
app.get('/private-lessons', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let store = db.getPrivateLessons(studentId);
const t = res.locals.t;
// If not yet synced or formMeta missing, try auto-syncing
if (!store || !store.lessons || !store.formMeta) {
@ -661,9 +808,10 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) =>
const subjects = Array.from(new Set(allLessons.map(l => l.subject))).sort();
res.render('private-lessons', {
title: 'Private Lessons - BeKultur',
title: t('privateLessons.pageTitle'),
activePage: 'private-lessons',
studentId,
studentName: req.session.studentName || store?.formMeta?.studentName || `Student ${studentId}`,
studentName: req.session.studentName || store?.formMeta?.studentName || `${t('dashboard.studentLabel')} ${studentId}`,
formMeta: store?.formMeta || null,
detectedAdvisor: store?.detectedAdvisor || db.getStudentAdvisoryTeacher(studentId) || null,
lastSynced: store?.lastSynced || null,
@ -678,6 +826,7 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) =>
* Redirect shortcuts
*/
app.get('/ozelders', (req: Request, res: Response) => res.redirect('/private-lessons'));
app.get('/OzelDers', (req: Request, res: Response) => res.redirect('/private-lessons'));
app.get('/ozeldersistek', (req: Request, res: Response) => res.redirect('/private-lessons'));
/**
@ -801,6 +950,7 @@ app.get('/rapor/sinav', (req: Request, res: Response) => {
app.get('/exams', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let examStore = db.getExamReports(studentId);
const t = res.locals.t;
// If no cached exams or empty, sync now
if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) {
@ -842,7 +992,8 @@ app.get('/exams', requireAuth, async (req: Request, res: Response) => {
const kpis = ExamService.calculateKPIs(processedExams);
res.render('exams', {
title: 'Sınav Raporları - BeKultur',
title: t('exams.pageTitle'),
activePage: 'exams',
studentId,
studentName: req.session.studentName || '',
allExams: processedExams,
@ -863,7 +1014,7 @@ app.get('/api/exams/:id', requireAuth, async (req: Request, res: Response) => {
const examId = req.params.id;
let examStore = db.getExamReports(studentId);
let exam = examStore?.reports?.[examId];
const exam = examStore?.reports?.[examId];
if (!exam) {
try {
@ -917,7 +1068,7 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
}
}
// Check if all questions for this exam and tip are cached in db.json
// Check if all questions for this exam and tip are cached in SQLite
const cachedQuestions = db.getExamQuestions(studentId, cacheKey);
if (cachedQuestions && cachedQuestions.length > 0) {
const subjectsMap: Record<string, { subjectName: string; subjectId: string; questions: any[] }> = {};
@ -1071,14 +1222,30 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) =>
}
});
// Start Server
// Start Server & Graceful Shutdown
if (process.env.NODE_ENV !== 'test') {
app.listen(PORT, () => {
const server = app.listen(PORT, () => {
console.log(`=========================================`);
console.log(` BeKultur (Better E-Kultur) Server`);
console.log(` Running at: http://localhost:${PORT}`);
console.log(`=========================================`);
});
const shutdown = (signal: string) => {
console.log(`\n[${signal}] Shutting down BeKultur server gracefully...`);
sessionStore.stopPruning();
server.close(() => {
db.close();
process.exit(0);
});
setTimeout(() => {
db.close();
process.exit(0);
}, 5000).unref();
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
}
export default app;

File diff suppressed because it is too large Load diff

519
src/services/i18n.ts Normal file
View file

@ -0,0 +1,519 @@
export type SupportedLocale = 'tr' | 'en';
export const DEFAULT_LOCALE: SupportedLocale = 'tr';
export const DAY_NAMES_BY_LOCALE: Record<SupportedLocale, Record<number, string>> = {
tr: {
1: 'Pazartesi',
2: 'Salı',
3: 'Çarşamba',
4: 'Perşembe',
5: 'Cuma'
},
en: {
1: 'Pazartesi',
2: 'Salı',
3: 'Çarşamba',
4: 'Perşembe',
5: 'Cuma'
}
};
const translations: Record<SupportedLocale, Record<string, string>> = {
tr: {
// Brand & Common
'app.title': 'BeKultur (E-Kültür)',
'nav.homework': 'Ödevler',
'nav.syllabus': 'Ders Programı',
'nav.privateLessons': 'Özel Ders',
'nav.exams': 'Sınav Raporları',
'header.student': 'Öğrenci',
'header.logout': 'Çıkış Yap',
'header.themeToggle': 'Tema Değiştir',
'header.themeLight': 'Açık Tema',
'header.themeDark': 'Koyu Tema',
'header.langToggleTitle': 'Dili Değiştir / Switch Language',
// Login (/Kullanici/Giris parity)
'login.pageTitle': 'Giriş Yap - BeKultur (E-Kültür)',
'login.subtitle': 'E-Kültür öğrenci portalı bilgilerinizle giriş yapınız.',
'login.studentIdLabel': 'Öğrenci ID',
'login.studentIdPlaceholder': 'Öğrenci ID',
'login.passwordLabel': 'Parola',
'login.passwordPlaceholder': 'Parola',
'login.rememberMe': 'Beni hatırla',
'login.submit': 'Giriş Yap',
'login.submitting': 'Giriş yapılıyor...',
'login.errorMissing': 'Lütfen Öğrenci ID ve Parola alanlarını doldurunuz.',
'login.errorInvalid': 'Öğrenci ID veya Parola hatalı.',
'login.errorServer': 'Giriş sırasında beklenmeyen bir sunucu hatası oluştu.',
// Homework / Dashboard (/Odev parity)
'dashboard.pageTitle': 'Ödevler - BeKultur',
'dashboard.title': 'Ödevler',
'dashboard.studentLabel': 'Öğrenci',
'dashboard.lastSynced': 'Son güncelleme:',
'dashboard.notSynced': 'Henüz güncellenmedi',
'dashboard.syncRecent': 'Güncel Ödevleri Çek',
'dashboard.syncAll': 'Tüm Geçmişi Çek',
'dashboard.syncing': 'Güncelleniyor...',
'dashboard.syncingAll': 'Tüm geçmiş çekiliyor...',
'dashboard.fetchingRecent': 'Güncel ödevler E-Kültür portalından çekiliyor...',
'dashboard.fetchingAll': 'Tüm ödev geçmişi E-Kültür portalından çekiliyor...',
'dashboard.syncFailed': 'Senkronizasyon başarısız:',
'dashboard.networkError': 'Senkronizasyon sırasında ağ hatası oluştu.',
'dashboard.statCompletion': 'Tamamlanma',
'dashboard.statDoneUnit': 'tamamlandı',
'dashboard.statActive': 'Aktif',
'dashboard.statActiveSub': 'Devam eden ödevler',
'dashboard.statNextWeek': 'Gelecek Hafta Kontrol',
'dashboard.statNextWeekSub': 'Haftaya teslim / kontrol',
'dashboard.statDueSoon': 'Yaklaşan',
'dashboard.statDueSoonSub': '3 gün içinde biten',
'dashboard.statOverdue': 'Süresi Geçen',
'dashboard.statOverdueSub': 'Bitiş tarihi geçmiş',
'dashboard.statTotal': 'Toplam',
'dashboard.statTotalSub': 'Tüm ödevler',
'dashboard.subjectsTitle': 'Dersler',
'dashboard.tabAll': 'Tümü',
'dashboard.tabNextWeek': 'Gelecek Hafta Kontrol',
'dashboard.tabActive': 'Aktif',
'dashboard.tabDueSoon': 'Yaklaşan',
'dashboard.tabCompleted': 'Tamamlanan',
'dashboard.tabOverdue': 'Süresi Geçen',
'dashboard.tabExcluded': 'Hariç Tutulan',
'dashboard.searchPlaceholder': 'Ders, yayın, ünite, konu veya açıklamaya göre ara...',
'dashboard.allSubjectsOption': 'Tüm Dersler',
'dashboard.showingCount': '{count} ödev gösteriliyor',
'dashboard.noResults': 'Filtrelere uygun ödev bulunamadı.',
'dashboard.resetFilters': 'Filtreleri Sıfırla',
'dashboard.checkDateBadge': 'Kontrol:',
'dashboard.badgeExcluded': 'Hariç Tutuldu',
'dashboard.badgeCompleted': 'Tamamlandı',
'dashboard.badgeNextWeek': 'Gelecek Hafta',
'dashboard.badgeDueSoon': 'Yaklaşan',
'dashboard.badgeOverdue': 'Süresi Geçti',
'dashboard.badgeActive': 'Aktif',
'dashboard.btnExclude': 'Hariç Tut',
'dashboard.btnRestore': 'Geri Al',
'dashboard.btnExcludeTitle': 'Bu ödevi listenden hariç tut (örn. başka sınıfa ait ödev)',
'dashboard.btnRestoreTitle': 'Bu ödevi aktif listene geri ekle',
'dashboard.unitLabel': 'Ünite:',
'dashboard.topicLabel': 'Konu:',
'dashboard.dateRangeLabel': 'Başlangıç - Bitiş Tarihi:',
'dashboard.descriptionLabel': 'Açıklama:',
'dashboard.completedOn': 'Tamamlandı:',
'dashboard.offlineToggleAlert': 'Çevrimdışı moddasınız. Ödev durumu internet bağlantısı olmadan değiştirilemez.',
'dashboard.offlineExcludeAlert': 'Çevrimdışı moddasınız. Ödev hariç tutma/geri alma işlemi için internet bağlantısı gereklidir.',
'dashboard.offlineSyncAlert': 'Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.',
// Syllabus (/dersprogrami parity)
'syllabus.pageTitle': 'Ders Programı - BeKultur',
'syllabus.title': 'Ders Programı',
'syllabus.weekLabel': 'Hafta:',
'syllabus.syncedLabel': 'Son güncelleme:',
'syllabus.notSynced': 'Henüz güncellenmedi',
'syllabus.syncBtn': 'Ders Programını Güncelle',
'syllabus.syncing': 'Güncelleniyor...',
'syllabus.fetchingAlert': '5 günlük ders programı E-Kültür portalından çekiliyor...',
'syllabus.updatedAlert': 'Ders programı başarıyla güncellendi!',
'syllabus.stationLabel': 'İstasyon:',
'syllabus.allStations': 'Tüm İstasyonlar',
'syllabus.advisorLabel': 'Danışman:',
'syllabus.advisoryTag': 'Danışmanlık',
'syllabus.viewLabel': 'Görünüm:',
'syllabus.dayView': 'Günlük Görünüm',
'syllabus.weekView': 'Haftalık Tablo',
'syllabus.todayBadge': 'Bugün',
'syllabus.noLessonsDay': '{day} günü için ders kaydı bulunamadı. Portaldan çekmek için "Ders Programını Güncelle" butonuna tıklayınız.',
'syllabus.classBadge': 'Sınıf',
'syllabus.periodHeader': 'Ders Saati',
'syllabus.periodNumberLabel': '{period}. Ders',
'syllabus.nowInSession': 'Şu anki ders: {period} — {subject} ({time})',
'syllabus.nextUp': 'Sıradaki ders: {period} — {subject} ({time})',
'syllabus.offlineStationAlert': 'Çevrimdışı moddasınız. İstasyon seçimi için internet bağlantısı gereklidir.',
// Private Lessons (/ozelders & /ozeldersistek parity)
'privateLessons.pageTitle': 'Özel Ders - BeKultur',
'privateLessons.title': 'Özel Ders',
'privateLessons.subtitle': 'Özel Ders & Başvuru',
'privateLessons.syncedLabel': 'Son güncelleme:',
'privateLessons.syncBtn': 'Dersleri Güncelle',
'privateLessons.syncing': 'Güncelleniyor...',
'privateLessons.syncSuccess': '{count} özel ders kaydı başarıyla güncellendi.',
'privateLessons.advisorLabel': 'Danışman:',
'privateLessons.policyNote': 'Başkası adına özel ders almayınız, seçtiğiniz öğretmen onayladığı takdirde özel derse alınacaksınız.',
'privateLessons.requestTitle': 'Özel Ders İstek',
'privateLessons.onlineBadge': 'Online Başvuru',
'privateLessons.courseLabel': 'Ders',
'privateLessons.unitLabel': 'Ünite',
'privateLessons.topicLabel': 'Konu',
'privateLessons.loading': 'Yükleniyor...',
'privateLessons.selectPrompt': 'Seçiniz...',
'privateLessons.selectCourseFirst': 'Önce ders seçiniz...',
'privateLessons.selectUnitFirst': 'Önce ünite seçiniz...',
'privateLessons.noUnitFound': 'Ünite bulunamadı',
'privateLessons.noTopicFound': 'Konu bulunamadı',
'privateLessons.errorOccurred': 'Hata oluştu',
'privateLessons.submitBtn': 'Gönder',
'privateLessons.submittingBtn': 'Gönderiliyor...',
'privateLessons.myLessonsTitle': 'Özel Derslerim',
'privateLessons.filterAll': 'Tümü',
'privateLessons.upcomingGroupTitle': 'Yaklaşan / Onaylanan Özel Dersler',
'privateLessons.upcomingBadge': 'Yaklaşan',
'privateLessons.activeCountBadge': '{count} Aktif',
'privateLessons.pastGroupTitle': 'Özel Ders Geçmişi',
'privateLessons.pastCountBadge': '{count} Geçmiş',
'privateLessons.completedBadge': 'Tamamlandı',
'privateLessons.emptyState': 'Henüz kayıtlı özel dersiniz bulunmuyor. Yukarıdaki formdan başvuru yapabilir veya portaldan çekmek için "Dersleri Güncelle" butonuna tıklayabilirsiniz.',
// Exam Reports (/rapor/sinav, /rapor/sinavkarne, /rapor/yanliskonu, /ogrencisoruanaliz parity)
'exams.pageTitle': 'Sınav Raporları - BeKultur',
'exams.title': 'Sınav Raporları',
'exams.subtitle': 'Sınav Karne, Gelişim Analizi & Öğrenci Soru Analiz',
'exams.syncedLabel': 'Son güncelleme:',
'exams.syncBtn': 'Sınavları Güncelle',
'exams.syncing': 'Güncelleniyor...',
'exams.kpiLatestNet': 'Son Sınav Neti',
'exams.kpiVsPrior': 'net (önceki sınava göre)',
'exams.kpiBaseline': 'İlk sınav (Referans)',
'exams.kpiBestNet': 'En Yüksek Net',
'exams.kpiAcrossExams': 'Toplam {count} sınav içinde',
'exams.kpiAvgNet': 'Ortalama Net',
'exams.kpiAvgSub': 'Genel net ortalaması',
'exams.kpiCurrentRank': 'Genel Sıra',
'exams.kpiBestRank': 'En iyi derece: #{rank}',
'exams.kpiGeneralStanding': 'Genel sıralama',
'exams.filterAll': 'Tüm Sınavlar',
'exams.answerKey': 'Cevap Anahtarı',
'exams.generalRankLabel': 'Genel Sıra :',
'exams.schoolRankLabel': 'Okul Sıra :',
'exams.rankDeltaUnit': 'sıra',
'exams.reviewMistakesBtn': '{count} Yanlış / Boş Soruyu İncele',
'exams.subtabBreakdown': 'Sınav Karne (Ders Dağılımı)',
'exams.subtabWeakness': 'Yanlış Konular (Zayıf Konu Analizi)',
'exams.colSubject': 'Ders',
'exams.colQuestions': 'Soru',
'exams.colCorrect': 'Doğru',
'exams.colWrong': 'Yanlış',
'exams.colEmpty': 'Boş',
'exams.colNet': 'Net',
'exams.colDeltaNet': 'Net Değişim (Δ)',
'exams.colSuccessRate': 'Başarı Oranı',
'exams.rowTotal': 'TOPLAM',
'exams.viewWrongQuestionsTitle': '{count} yanlış soruyu görüntülemek için tıklayınız',
'exams.viewEmptyQuestionsTitle': '{count} boş soruyu görüntülemek için tıklayınız',
'exams.weaknessLoading': 'Yanlış konu analizi yükleniyor...',
'exams.weaknessEmpty': 'Bu sınav için henüz yanlış konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.',
'exams.weaknessError': 'Yanlış konu raporu yüklenirken bir hata oluştu.',
'exams.weaknessTotal': 'Toplam:',
'exams.weaknessCorrect': 'Doğru:',
'exams.weaknessWrong': 'Yanlış:',
'exams.weaknessEmptyCount': 'Boş:',
'exams.modalTitle': 'Öğrenci Soru Analiz',
'exams.modalSubtitle': 'Yanlış ve Boş Bırakılan Sorular',
'exams.modalTypeAll': 'Tümü',
'exams.modalTypeWrong': 'Yanlış',
'exams.modalTypeEmpty': 'Boş',
'exams.modalAllMistakes': 'Tüm Sorular',
'exams.modalLoading': 'Sorular getiriliyor...',
'exams.modalNoMatch': 'Seçili filtrelere uygun soru bulunamadı.',
'exams.modalError': 'Sorular yüklenirken bir hata oluştu.',
'exams.questionNo': 'SoruNo: {num}',
'exams.correctAnswer': 'Doğru Cevap:',
'exams.studentAnswer': 'Öğrenci Cevap:',
'exams.emptyAnswerText': 'Boş',
'exams.zoomHint': 'Büyütmek için tıklayınız',
'exams.noImage': 'Soru görseli bulunamadı.',
'exams.emptyTitle': 'Henüz Sınav Raporu Bulunmuyor',
'exams.emptyDesc': 'Öğrenci portalındaki sınav karnelerinizi içe aktarmak için "Sınavları Güncelle" butonuna tıklayınız.',
// Exam Ratings
'rating.Breakthrough': 'Sıçrama',
'rating.Outperformed Curve': 'Zor Sınavda Başarı',
'rating.Net Growth': 'Net Artışı',
'rating.Rank Climb': 'Sıralama Yükselişi',
'rating.Top 10 Consistency': 'İlk 10 İstikrarı',
'rating.Needs Review': 'Tekrar Gerekli',
'rating.Stable Performance': 'Dengeli Performans',
'rating.Top 10 Baseline': 'İlk 10 Başlangıç',
'rating.Baseline Exam': 'İlk Sınav',
// PWA & Offline
'pwa.offlineBadge': '⚡ Çevrimdışı',
'pwa.offlineText': 'Önbellekteki veriler gösteriliyor. Bağlantı gerektiren işlemler duraklatıldı.',
'pwa.onlineBadge': '✓ Çevrimiçi',
'pwa.onlineText': 'Bağlantı yeniden sağlandı. Canlı özellikler aktif.',
'pwa.offlineSuffix': '(Çevrimdışı)',
'pwa.offlineCheckboxTitle': 'Çevrimdışı mod: Ödev durumu bağlantı olmadan değiştirilemez.',
'pwa.offlineExcludeTitle': 'Çevrimdışı mod: Ödev bağlantı olmadan hariç tutulamaz.',
'pwa.offlineStationTitle': 'Çevrimdışı mod: İstasyon seçimi bağlantı gerektirir.',
'pwa.offlineSyncTitle': 'Çevrimdışı mod: Senkronizasyon internet bağlantısı gerektirir.',
'pwa.offlinePrivateNotice': '⚡ <strong>Çevrimdışı mod:</strong> Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.'
},
en: {
// Brand & Common
'app.title': 'BeKultur (Better E-Kultur)',
'nav.homework': 'Homework',
'nav.syllabus': 'Syllabus',
'nav.privateLessons': 'Private Lessons',
'nav.exams': 'Exams',
'header.student': 'Student',
'header.logout': 'Log out',
'header.themeToggle': 'Toggle Theme',
'header.themeLight': 'Light Theme',
'header.themeDark': 'Dark Theme',
'header.langToggleTitle': 'Switch Language / Dili Değiştir',
// Login
'login.pageTitle': 'Login - BeKultur (Better E-Kultur)',
'login.subtitle': 'Log in with your school portal credentials.',
'login.studentIdLabel': 'Student ID',
'login.studentIdPlaceholder': 'Student ID',
'login.passwordLabel': 'Password',
'login.passwordPlaceholder': 'Password',
'login.rememberMe': 'Remember credentials',
'login.submit': 'Log In',
'login.submitting': 'Logging in...',
'login.errorMissing': 'Please enter both Student ID and Password.',
'login.errorInvalid': 'Authentication failed. Please check your credentials.',
'login.errorServer': 'An unexpected server error occurred during login.',
// Homework / Dashboard
'dashboard.pageTitle': 'Dashboard - BeKultur',
'dashboard.title': 'Homework',
'dashboard.studentLabel': 'Student',
'dashboard.lastSynced': 'Last synced:',
'dashboard.notSynced': 'Not synced',
'dashboard.syncRecent': 'Sync Recent',
'dashboard.syncAll': 'Sync Full History',
'dashboard.syncing': 'Syncing...',
'dashboard.syncingAll': 'Syncing all...',
'dashboard.fetchingRecent': 'Fetching recent assignments...',
'dashboard.fetchingAll': 'Syncing full history from portal...',
'dashboard.syncFailed': 'Sync failed:',
'dashboard.networkError': 'Network error while syncing.',
'dashboard.statCompletion': 'Completion',
'dashboard.statDoneUnit': 'done',
'dashboard.statActive': 'Active',
'dashboard.statActiveSub': 'In progress',
'dashboard.statNextWeek': 'Checked Next Week',
'dashboard.statNextWeekSub': 'Due or checked next week',
'dashboard.statDueSoon': 'Due Soon',
'dashboard.statDueSoonSub': 'Within 3 days',
'dashboard.statOverdue': 'Overdue',
'dashboard.statOverdueSub': 'Past deadline',
'dashboard.statTotal': 'Total',
'dashboard.statTotalSub': 'All assignments',
'dashboard.subjectsTitle': 'Subjects',
'dashboard.tabAll': 'All',
'dashboard.tabNextWeek': 'Checked Next Week',
'dashboard.tabActive': 'Active',
'dashboard.tabDueSoon': 'Due Soon',
'dashboard.tabCompleted': 'Completed',
'dashboard.tabOverdue': 'Overdue',
'dashboard.tabExcluded': 'Excluded',
'dashboard.searchPlaceholder': 'Filter by subject, book, or description...',
'dashboard.allSubjectsOption': 'All Subjects',
'dashboard.showingCount': 'Showing {count} assignments',
'dashboard.noResults': 'No matching assignments found.',
'dashboard.resetFilters': 'Reset filters',
'dashboard.checkDateBadge': 'Kontrol:',
'dashboard.badgeExcluded': 'Excluded',
'dashboard.badgeCompleted': 'Done',
'dashboard.badgeNextWeek': 'Next Week',
'dashboard.badgeDueSoon': 'Due Soon',
'dashboard.badgeOverdue': 'Overdue',
'dashboard.badgeActive': 'Active',
'dashboard.btnExclude': 'Exclude',
'dashboard.btnRestore': 'Restore',
'dashboard.btnExcludeTitle': 'Exclude this homework (e.g. from another class)',
'dashboard.btnRestoreTitle': 'Restore this homework to your active list',
'dashboard.unitLabel': 'Ünite:',
'dashboard.topicLabel': 'Konu:',
'dashboard.dateRangeLabel': 'Start - End Date:',
'dashboard.descriptionLabel': 'Description:',
'dashboard.completedOn': 'Done:',
'dashboard.offlineToggleAlert': 'You are offline. Homework status cannot be changed without an internet connection.',
'dashboard.offlineExcludeAlert': 'You are offline. Excluding/restoring homework requires an internet connection.',
'dashboard.offlineSyncAlert': 'You are offline. Syncing requires an internet connection.',
// Syllabus
'syllabus.pageTitle': 'Syllabus - BeKultur',
'syllabus.title': 'Syllabus',
'syllabus.weekLabel': 'Week:',
'syllabus.syncedLabel': 'Synced:',
'syllabus.notSynced': 'Not synced',
'syllabus.syncBtn': 'Sync Syllabus',
'syllabus.syncing': 'Syncing...',
'syllabus.fetchingAlert': 'Fetching weekly timetable across all 5 days...',
'syllabus.updatedAlert': 'Syllabus updated successfully!',
'syllabus.stationLabel': 'Station:',
'syllabus.allStations': 'All Stations',
'syllabus.advisorLabel': 'Advisor:',
'syllabus.advisoryTag': 'Danışmanlık',
'syllabus.viewLabel': 'View:',
'syllabus.dayView': 'Day View',
'syllabus.weekView': 'Full Week Grid',
'syllabus.todayBadge': 'Today',
'syllabus.noLessonsDay': 'No lessons found for {day}. Click "Sync Syllabus" to fetch from portal.',
'syllabus.classBadge': 'Class',
'syllabus.periodHeader': 'Period',
'syllabus.periodNumberLabel': '{period}. Ders',
'syllabus.nowInSession': 'Now in session: {period} — {subject} ({time})',
'syllabus.nextUp': 'Next up: {period} — {subject} at {time}',
'syllabus.offlineStationAlert': 'You are offline. Station selection requires an internet connection.',
// Private Lessons
'privateLessons.pageTitle': 'Private Lessons - BeKultur',
'privateLessons.title': 'Private Lessons',
'privateLessons.subtitle': 'Özel Ders & Başvuru',
'privateLessons.syncedLabel': 'Synced:',
'privateLessons.syncBtn': 'Sync Lessons',
'privateLessons.syncing': 'Syncing...',
'privateLessons.syncSuccess': 'Successfully refreshed {count} private lesson records.',
'privateLessons.advisorLabel': 'Advisor:',
'privateLessons.policyNote': 'Başkası adına özel ders almayınız, seçtiğiniz öğretmen onayladığı takdirde özel derse alınacaksınız.',
'privateLessons.requestTitle': 'New Lesson Request (Özel Ders İstek)',
'privateLessons.onlineBadge': 'Online Başvuru',
'privateLessons.courseLabel': 'Ders (Course)',
'privateLessons.unitLabel': 'Ünite (Unit)',
'privateLessons.topicLabel': 'Konu (Topic)',
'privateLessons.loading': 'Loading...',
'privateLessons.selectPrompt': 'Seçiniz...',
'privateLessons.selectCourseFirst': 'Önce ders seçiniz...',
'privateLessons.selectUnitFirst': 'Önce ünite seçiniz...',
'privateLessons.noUnitFound': 'Ünite bulunamadı',
'privateLessons.noTopicFound': 'Konu bulunamadı',
'privateLessons.errorOccurred': 'Hata oluştu',
'privateLessons.submitBtn': 'Submit Request (Gönder)',
'privateLessons.submittingBtn': 'Gönderiliyor...',
'privateLessons.myLessonsTitle': 'My Lessons (Özel Derslerim)',
'privateLessons.filterAll': 'All',
'privateLessons.upcomingGroupTitle': 'Upcoming / Approved Lessons',
'privateLessons.upcomingBadge': 'Upcoming',
'privateLessons.activeCountBadge': '{count} Active',
'privateLessons.pastGroupTitle': 'Lesson History',
'privateLessons.pastCountBadge': '{count} Past',
'privateLessons.completedBadge': 'Completed',
'privateLessons.emptyState': 'No private lessons recorded yet. Submit a request above or click Sync Lessons to fetch from the portal.',
// Exam Reports
'exams.pageTitle': 'Exam Reports - BeKultur',
'exams.title': 'Exam Reports',
'exams.subtitle': 'Sınav Raporları, Gelişim Analizi & Soru İnceleme',
'exams.syncedLabel': 'Synced:',
'exams.syncBtn': 'Sync Exams',
'exams.syncing': 'Syncing...',
'exams.kpiLatestNet': 'Latest Net',
'exams.kpiVsPrior': 'net vs prior',
'exams.kpiBaseline': 'Baseline exam',
'exams.kpiBestNet': 'Personal Best Net',
'exams.kpiAcrossExams': 'Across all {count} exams',
'exams.kpiAvgNet': 'Average Net',
'exams.kpiAvgSub': 'Overall student mean',
'exams.kpiCurrentRank': 'Current Rank',
'exams.kpiBestRank': 'Best standing: #{rank}',
'exams.kpiGeneralStanding': 'General standing',
'exams.filterAll': 'All Exams',
'exams.answerKey': 'Cevap Anahtarı',
'exams.generalRankLabel': 'Genel Sıra :',
'exams.schoolRankLabel': 'Okul Sıra :',
'exams.rankDeltaUnit': 'sıra',
'exams.reviewMistakesBtn': 'Review {count} Mistakes',
'exams.subtabBreakdown': 'Subject Breakdown (Ders Dağılımı)',
'exams.subtabWeakness': 'Topic Weaknesses (Zayıf Konular)',
'exams.colSubject': 'Ders',
'exams.colQuestions': 'Soru',
'exams.colCorrect': 'Doğru',
'exams.colWrong': 'Yanlış',
'exams.colEmpty': 'Boş',
'exams.colNet': 'Net',
'exams.colDeltaNet': 'Net Değişim (Δ)',
'exams.colSuccessRate': 'Başarı Oranı',
'exams.rowTotal': 'TOPLAM',
'exams.viewWrongQuestionsTitle': 'Click to view {count} wrong questions',
'exams.viewEmptyQuestionsTitle': 'Click to view {count} blank questions',
'exams.weaknessLoading': 'Zayıf konu analizi yükleniyor...',
'exams.weaknessEmpty': 'Bu sınav için henüz zayıf konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.',
'exams.weaknessError': 'Zayıf konu raporu yüklenirken bir hata oluştu.',
'exams.weaknessTotal': 'Toplam:',
'exams.weaknessCorrect': 'Doğru:',
'exams.weaknessWrong': 'Yanlış:',
'exams.weaknessEmptyCount': 'Boş:',
'exams.modalTitle': 'Review Mistakes',
'exams.modalSubtitle': 'Wrong & Blank Questions',
'exams.modalTypeAll': 'All',
'exams.modalTypeWrong': 'Wrong (Yanlış)',
'exams.modalTypeEmpty': 'Blank (Boş)',
'exams.modalAllMistakes': 'Tüm Yanlışlar',
'exams.modalLoading': 'Sorular getiriliyor...',
'exams.modalNoMatch': 'Seçili filtrelere uygun soru bulunamadı.',
'exams.modalError': 'Sorular yüklenirken bir hata oluştu.',
'exams.questionNo': 'Soru #{num}',
'exams.correctAnswer': 'Doğru:',
'exams.studentAnswer': 'Öğrenci:',
'exams.emptyAnswerText': 'Boş',
'exams.zoomHint': 'Büyütmek için tıklayınız',
'exams.noImage': 'Soru görseli bulunamadı.',
'exams.emptyTitle': 'Henüz Sınav Raporu Bulunmuyor',
'exams.emptyDesc': 'Öğrenci portalındaki sınav verilerini içe aktarmak için "Sync Exams" butonuna tıklayınız.',
// Exam Ratings
'rating.Breakthrough': 'Breakthrough',
'rating.Outperformed Curve': 'Outperformed Curve',
'rating.Net Growth': 'Net Growth',
'rating.Rank Climb': 'Rank Climb',
'rating.Top 10 Consistency': 'Top 10 Consistency',
'rating.Needs Review': 'Needs Review',
'rating.Stable Performance': 'Stable Performance',
'rating.Top 10 Baseline': 'Top 10 Baseline',
'rating.Baseline Exam': 'Baseline Exam',
// PWA & Offline
'pwa.offlineBadge': '⚡ Offline',
'pwa.offlineText': 'Showing locally cached data. Actions requiring connection are paused.',
'pwa.onlineBadge': '✓ Online',
'pwa.onlineText': 'Connection restored. Live features re-enabled.',
'pwa.offlineSuffix': '(Offline)',
'pwa.offlineCheckboxTitle': 'Offline mode: Homework status cannot be changed without connection.',
'pwa.offlineExcludeTitle': 'Offline mode: Homework cannot be excluded without connection.',
'pwa.offlineStationTitle': 'Offline mode: Station selection requires connection.',
'pwa.offlineSyncTitle': 'Offline mode: Sync requires internet connection.',
'pwa.offlinePrivateNotice': '⚡ <strong>Çevrimdışı mod:</strong> Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.'
}
};
export function normalizeLocale(input?: string | null): SupportedLocale {
if (!input) return DEFAULT_LOCALE;
const cleaned = input.trim().toLowerCase();
if (cleaned === 'en' || cleaned.startsWith('en-')) return 'en';
if (cleaned === 'tr' || cleaned.startsWith('tr-')) return 'tr';
return DEFAULT_LOCALE;
}
export function translate(
locale: SupportedLocale,
key: string,
params?: Record<string, string | number>
): string {
const dict = translations[locale] || translations[DEFAULT_LOCALE];
let template = dict[key] ?? translations[DEFAULT_LOCALE][key] ?? key;
if (params) {
for (const [k, v] of Object.entries(params)) {
template = template.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v));
}
}
return template;
}
export function createTranslator(locale: SupportedLocale) {
return (key: string, params?: Record<string, string | number>): string => {
return translate(locale, key, params);
};
}
export function getClientDictionary(locale: SupportedLocale): Record<string, string> {
return translations[locale] || translations[DEFAULT_LOCALE];
}

189
src/services/secrets.ts Normal file
View file

@ -0,0 +1,189 @@
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
const INSECURE_DEFAULTS = new Set([
'bekultur_secret_key_change_in_production',
'bekultur_default_secret_key_change_me',
''
]);
interface StoredSecrets {
sessionSecret: string;
encryptionSecret: string;
createdAt: string;
}
let cachedSecrets: StoredSecrets | null = null;
function getSecretsFilePath(): string {
const customDbPath = process.env.DB_PATH;
const dataDir = customDbPath
? path.dirname(path.resolve(customDbPath))
: path.resolve(process.cwd(), 'data');
return path.join(dataDir, '.secrets.json');
}
function loadOrCreateSecrets(): StoredSecrets {
if (cachedSecrets) {
return cachedSecrets;
}
const secretsFile = getSecretsFilePath();
const dir = path.dirname(secretsFile);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
if (fs.existsSync(secretsFile)) {
try {
const raw = fs.readFileSync(secretsFile, 'utf-8');
const parsed = JSON.parse(raw) as StoredSecrets;
if (parsed.sessionSecret && parsed.encryptionSecret) {
cachedSecrets = parsed;
return cachedSecrets;
}
} catch (err) {
console.warn('Warning: Could not read .secrets.json, regenerating secrets.');
}
}
const generated: StoredSecrets = {
sessionSecret: crypto.randomBytes(64).toString('hex'),
encryptionSecret: crypto.randomBytes(64).toString('hex'),
createdAt: new Date().toISOString()
};
try {
fs.writeFileSync(secretsFile, JSON.stringify(generated, null, 2), {
encoding: 'utf-8',
mode: 0o600
});
} catch (err) {
console.warn('Warning: Failed to persist .secrets.json to disk:', err);
}
cachedSecrets = generated;
return cachedSecrets;
}
/**
* Retrieve active session secret (prefers non-default env var, otherwise persistent generated secret)
*/
export function getSessionSecret(): string {
const envSecret = (process.env.SESSION_SECRET || '').trim();
if (envSecret && !INSECURE_DEFAULTS.has(envSecret)) {
return envSecret;
}
return loadOrCreateSecrets().sessionSecret;
}
/**
* Retrieve active encryption secret (prefers non-default env var, otherwise persistent generated secret)
*/
export function getEncryptionSecret(): string {
const envEnc = (process.env.ENCRYPTION_SECRET || process.env.CREDENTIAL_SECRET || '').trim();
if (envEnc && !INSECURE_DEFAULTS.has(envEnc)) {
return envEnc;
}
const envSess = (process.env.SESSION_SECRET || '').trim();
if (envSess && !INSECURE_DEFAULTS.has(envSess)) {
return envSess;
}
return loadOrCreateSecrets().encryptionSecret;
}
/**
* Encrypt sensitive text (student passwords, portal cookies) using AES-256-GCM with per-item random salt & IV
*/
export function encryptCredential(plaintext: string): string {
if (!plaintext) return '';
try {
const secret = getEncryptionSecret();
const salt = crypto.randomBytes(16);
const iv = crypto.randomBytes(12);
const key = crypto.scryptSync(secret, salt, 32);
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:v2:${salt.toString('hex')}:${iv.toString('hex')}:${authTag}:${encrypted}`;
} catch (err) {
console.error('Failed to encrypt credential:', err);
throw new Error('Encryption failure');
}
}
/**
* Decrypt stored credential, supporting both v2 (random salt) and legacy v1 (static salt + legacy fallback keys)
*/
export function decryptCredential(stored: string): string {
if (!stored) return '';
if (!stored.startsWith('enc:')) {
// Legacy plaintext support
return stored;
}
// v2 format: enc:v2:<saltHex>:<ivHex>:<authTagHex>:<ciphertextHex>
if (stored.startsWith('enc:v2:')) {
const parts = stored.split(':');
if (parts.length !== 6) return '';
const [, , saltHex, ivHex, authTagHex, ciphertextHex] = parts;
const candidateSecrets = Array.from(
new Set([
getEncryptionSecret(),
process.env.ENCRYPTION_SECRET || '',
process.env.SESSION_SECRET || ''
].filter(Boolean))
);
for (const secret of candidateSecrets) {
try {
const key = crypto.scryptSync(secret, Buffer.from(saltHex, 'hex'), 32);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch {
// Try next candidate key
}
}
return '';
}
// Legacy v1 format: enc:<ivHex>:<authTagHex>:<ciphertextHex>
const parts = stored.split(':');
if (parts.length !== 4) return '';
const [, ivHex, authTagHex, ciphertextHex] = parts;
const legacyCandidateSecrets = Array.from(
new Set([
getEncryptionSecret(),
process.env.ENCRYPTION_SECRET || '',
process.env.SESSION_SECRET || '',
'bekultur_secret_key_change_in_production',
'bekultur_default_secret_key_change_me'
].filter(Boolean))
);
for (const secret of legacyCandidateSecrets) {
try {
const key = crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch {
// Try next candidate secret
}
}
console.error('Failed to decrypt legacy credential with any known key.');
return '';
}
export function isModernEncryptedFormat(stored: string): boolean {
return Boolean(stored && stored.startsWith('enc:v2:'));
}

View file

@ -0,0 +1,212 @@
import session from 'express-session';
import Database from 'better-sqlite3';
import { encryptCredential, decryptCredential } from './secrets';
const DEFAULT_TTL_MS = 14 * 24 * 60 * 60 * 1000; // 14 days
const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
export interface SQLiteSessionStoreOptions {
db: Database.Database;
ttlMs?: number;
pruneIntervalMs?: number;
}
export class SQLiteSessionStore extends session.Store {
private db: Database.Database;
private ttlMs: number;
private pruneTimer: NodeJS.Timeout | null = null;
constructor(options: SQLiteSessionStoreOptions) {
super();
this.db = options.db;
this.ttlMs = options.ttlMs || DEFAULT_TTL_MS;
this.db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
sid TEXT PRIMARY KEY,
sess TEXT NOT NULL,
expire INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire);
`);
this.pruneExpired();
const pruneInterval = options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS;
if (pruneInterval > 0) {
this.pruneTimer = setInterval(() => {
this.pruneExpired();
}, pruneInterval);
if (this.pruneTimer.unref) {
this.pruneTimer.unref();
}
}
}
private computeExpireTimestamp(sess: session.SessionData): number {
if (sess?.cookie?.expires) {
const exp = new Date(sess.cookie.expires).getTime();
if (!isNaN(exp)) return exp;
}
if (typeof sess?.cookie?.maxAge === 'number') {
return Date.now() + sess.cookie.maxAge;
}
return Date.now() + this.ttlMs;
}
private serializeSession(sess: session.SessionData): string {
const clone: Record<string, any> = { ...sess };
if (typeof clone.portalCookies === 'string' && clone.portalCookies.length > 0 && !clone.portalCookies.startsWith('enc:')) {
clone.portalCookies = encryptCredential(clone.portalCookies);
}
return JSON.stringify(clone);
}
private deserializeSession(rawJson: string): session.SessionData | null {
try {
const parsed = JSON.parse(rawJson);
if (typeof parsed.portalCookies === 'string' && parsed.portalCookies.startsWith('enc:')) {
parsed.portalCookies = decryptCredential(parsed.portalCookies);
}
return parsed as session.SessionData;
} catch {
return null;
}
}
public pruneExpired(): number {
try {
if (!this.db.open) return 0;
const info = this.db
.prepare('DELETE FROM sessions WHERE expire <= ?')
.run(Date.now());
return info.changes;
} catch {
return 0;
}
}
public get(
sid: string,
callback: (err: any, session?: session.SessionData | null) => void
): void {
try {
const row = this.db
.prepare('SELECT sess, expire FROM sessions WHERE sid = ?')
.get(sid) as { sess: string; expire: number } | undefined;
if (!row) {
return callback(null, null);
}
if (row.expire <= Date.now()) {
this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
return callback(null, null);
}
const sess = this.deserializeSession(row.sess);
return callback(null, sess);
} catch (err) {
return callback(err);
}
}
public set(
sid: string,
sess: session.SessionData,
callback?: (err?: any) => void
): void {
try {
const expire = this.computeExpireTimestamp(sess);
const serialized = this.serializeSession(sess);
this.db
.prepare(
'INSERT INTO sessions (sid, sess, expire) VALUES (?, ?, ?) ON CONFLICT(sid) DO UPDATE SET sess = excluded.sess, expire = excluded.expire'
)
.run(sid, serialized, expire);
if (callback) callback(null);
} catch (err) {
if (callback) callback(err);
}
}
public destroy(sid: string, callback?: (err?: any) => void): void {
try {
this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
if (callback) callback(null);
} catch (err) {
if (callback) callback(err);
}
}
public touch(
sid: string,
sess: session.SessionData,
callback?: () => void
): void {
try {
const expire = this.computeExpireTimestamp(sess);
this.db
.prepare('UPDATE sessions SET expire = ? WHERE sid = ?')
.run(expire, sid);
if (callback) callback();
} catch {
if (callback) callback();
}
}
public length(callback: (err: any, length?: number) => void): void {
try {
this.pruneExpired();
const row = this.db
.prepare('SELECT COUNT(*) as cnt FROM sessions')
.get() as { cnt: number };
callback(null, row.cnt);
} catch (err) {
callback(err);
}
}
public clear(callback?: (err?: any) => void): void {
try {
this.db.prepare('DELETE FROM sessions').run();
if (callback) callback(null);
} catch (err) {
if (callback) callback(err);
}
}
public all(
callback: (
err: any,
obj?: session.SessionData[] | { [sid: string]: session.SessionData } | null
) => void
): void {
try {
this.pruneExpired();
const rows = this.db
.prepare('SELECT sid, sess FROM sessions WHERE expire > ?')
.all(Date.now()) as Array<{ sid: string; sess: string }>;
const sessions: Record<string, session.SessionData> = {};
for (const r of rows) {
const parsed = this.deserializeSession(r.sess);
if (parsed) {
sessions[r.sid] = parsed;
}
}
callback(null, sessions);
} catch (err) {
callback(err);
}
}
public stopPruning(): void {
if (this.pruneTimer) {
clearInterval(this.pruneTimer);
this.pruneTimer = null;
}
}
}

View file

@ -1,5 +1,6 @@
import { Lesson } from '../types';
import { InsightService } from './insight';
import { SupportedLocale, translate } from './i18n';
export const DAY_NAMES: Record<number, string> = {
1: 'Pazartesi',
@ -167,7 +168,8 @@ export class SyllabusService {
public static getCurrentLessonStatus(
dayLessons: Lesson[],
currentDayNumber: number,
refDate: Date = new Date()
refDate: Date = new Date(),
locale: SupportedLocale = 'tr'
): { currentLesson: Lesson | null; nextLesson: Lesson | null; statusText: string | null } {
const todayDay = refDate.getDay(); // 1 = Mon, ..., 5 = Fri
if (todayDay !== currentDayNumber) {
@ -199,9 +201,17 @@ export class SyllabusService {
let statusText: string | null = null;
if (current) {
statusText = `Now in session: ${current.period} — ${current.subject} (${current.time})`;
statusText = translate(locale, 'syllabus.nowInSession', {
period: current.period,
subject: current.subject,
time: current.time
});
} else if (next) {
statusText = `Next up: ${next.period} — ${next.subject} at ${next.startTime}`;
statusText = translate(locale, 'syllabus.nextUp', {
period: next.period,
subject: next.subject,
time: next.startTime
});
}
return { currentLesson: current, nextLesson: next, statusText };