fix: persist default secrets across restarts, auto-relogin on portal expiry, and remove legacy json migration

This commit is contained in:
tyuXX 2026-11-12 08:02:57 +00:00
parent 5d576137ae
commit 43f3891e9e
10 changed files with 835 additions and 625 deletions

View file

@ -24,10 +24,8 @@ import { Assignment, Lesson, ExamReportDetail } from '../src/types';
// Configure isolated temporary directory BEFORE any server/db singleton initialization
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-'));
const testDbPath = path.join(tempDir, 'test-bekultur.db');
const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json');
process.env.NODE_ENV = 'test';
process.env.DB_PATH = testDbPath;
process.env.LEGACY_JSON_PATH = testLegacyJsonPath;
import { shouldTriggerMondayWeeklySync, syncWeeklyStudentData } from '../src/server';
@ -733,219 +731,6 @@ async function runAllTests() {
db.clearCredentials(testId);
});
await test('LocalDatabase: Zero-Data-Loss Migration from legacy db.json to SQLite (preserving v1 credentials & filtering synthetic test records)', () => {
const migJsonPath = path.join(tempDir, 'legacy-db.json');
const migDbPath = path.join(tempDir, 'migrated-bekultur.db');
// Encrypt a password using the legacy v1 scheme (`enc:<iv>:<tag>:<cipher>` with default legacy key)
const legacyKey = crypto.scryptSync('bekultur_secret_key_change_in_production', 'bekultur_credential_salt', 32);
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', legacyKey, iv);
let encrypted = cipher.update('MyLegacyPortalPassword99', 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
const legacyCiphertext = `enc:${iv.toString('hex')}:${authTag}:${encrypted}`;
const legacyPayload = {
students: {
'415': {
studentId: '415',
lastSynced: '2026-10-25T12:00:00.000Z',
rememberedCredentials: {
studentId: '415',
password: legacyCiphertext
},
assignments: {
hw_completed_1: {
id: 'hw_completed_1',
subject: 'AYT Matematik',
type: 'Yayın',
unit: 'Türev',
topic: 'Limit ve Süreklilik',
startDate: '20.10.2026',
endDate: '27.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-27',
description: '3D AYT Sayfa 100-120',
detectedCheckDate: '27 ekim',
status: 'completed',
completed: true,
completedAt: '2026-10-24T18:30:00.000Z',
excluded: false
},
hw_excluded_2: {
id: 'hw_excluded_2',
subject: 'Biyoloji',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '27.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-27',
description: 'Diğer şube ödevi',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null,
excluded: true
}
},
syllabus: {
weekId: '2026-W43',
weekRange: '19.10.2026 - 23.10.2026',
lastSynced: '2026-10-25T12:00:00.000Z',
selectedStation: 'İst-4',
advisoryTeacher: 'CAN TÜRKOĞLU',
days: { 1: [], 2: [], 3: [], 4: [], 5: [] }
},
privateLessons: {
lastSynced: '2026-10-25T12:00:00.000Z',
detectedAdvisor: 'CAN TÜRKOĞLU',
lessons: [
{
id: 'pl_legacy_1',
subject: 'Fizik',
teacherName: 'CAN TÜRKOĞLU',
teacherPhoto: null,
date: '26.10.2026',
parsedDate: '2026-10-26',
isUpcoming: true
}
]
},
exams: {
lastSynced: '2026-10-25T12:00:00.000Z',
reports: {
'3366': {
summary: {
id: '3366',
name: '12 YKS-04 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 90,
totalWrong: 16,
totalEmpty: 14,
totalNet: 86.0,
totalScore: 86.0,
generalRank: 7
},
subjects: [],
hasAnswerKey: true
}
},
topicWeaknesses: {
'3366': [
{
examId: '3366',
examName: '12 YKS-04 MF',
subjectName: 'Fizik',
topicName: 'Optik',
totalCount: 3,
correctCount: 1,
wrongCount: 2,
emptyCount: 0,
successRate: 33
}
]
},
questions: {
'3366_Y': [
{
questionNumber: 5,
correctAnswer: 'D',
studentAnswer: 'B',
imageUrl: 'https://example.com/q5.png',
status: 'wrong',
subjectId: '14',
subjectName: 'Fizik'
}
]
}
}
},
test_student_99999: {
studentId: 'test_student_99999',
lastSynced: null,
assignments: {}
},
audit_security_student: {
studentId: 'audit_security_student',
lastSynced: null,
assignments: {}
}
}
};
fs.writeFileSync(migJsonPath, JSON.stringify(legacyPayload, null, 2), 'utf-8');
// Instantiate LocalDatabase pointing to the legacy JSON file
const migratedDb = new LocalDatabase(migDbPath, migJsonPath);
// 1. Verify backup file was created
assert(fs.existsSync(`${migJsonPath}.bak`), 'Non-destructive backup legacy-db.json.bak must be created');
// 2. Verify real student 415 data was 100% preserved
const store415 = migratedDb.getStudentStore('415');
assert.strictEqual(store415.lastSynced, '2026-10-25T12:00:00.000Z');
assert(store415.assignments['hw_completed_1'], 'Completed assignment must be migrated');
assert.strictEqual(store415.assignments['hw_completed_1'].completed, true);
assert.strictEqual(store415.assignments['hw_completed_1'].completedAt, '2026-10-24T18:30:00.000Z');
assert(store415.assignments['hw_excluded_2'], 'Excluded assignment must be migrated');
assert.strictEqual(store415.assignments['hw_excluded_2'].excluded, true);
// 3. Verify legacy v1 encrypted password decrypts seamlessly and was upgraded to v2 at rest
const creds415 = migratedDb.getRememberedCredentials('415');
assert(creds415 !== null, 'Legacy credentials must be migrated and decryptable');
assert.strictEqual(creds415.password, 'MyLegacyPortalPassword99');
// 4. Verify syllabus, private lessons, and exam reports migrated intact
const syl415 = migratedDb.getSyllabus('415');
assert.strictEqual(syl415?.selectedStation, 'İst-4');
assert.strictEqual( migratedDb.getStudentAdvisoryTeacher('415'), 'CAN TÜRKOĞLU');
const pl415 = migratedDb.getPrivateLessons('415');
assert.strictEqual(pl415?.lessons.length, 1);
assert.strictEqual(pl415?.lessons[0].subject, 'Fizik');
const exams415 = migratedDb.getExamReports('415');
assert(exams415?.reports['3366'], 'Exam report 3366 must be migrated');
assert.strictEqual(exams415?.reports['3366'].summary.totalNet, 86.0);
assert.strictEqual(migratedDb.getTopicWeaknesses('415', '3366')?.[0].topicName, 'Optik');
assert.strictEqual(migratedDb.getExamQuestions('415', '3366_Y')?.[0].questionNumber, 5);
// 5. Verify synthetic test_student_* and audit_* records were filtered out
const rowTest = migratedDb
.getSqliteDb()
.prepare('SELECT student_id FROM students WHERE student_id IN (?, ?)')
.all('test_student_99999', 'audit_security_student');
assert.strictEqual(rowTest.length, 0, 'Synthetic test_student_* and audit_* records must be skipped during migration');
// 6. Toggle hw_excluded_2 as completed in SQLite, close DB (simulating container restart), and reopen
migratedDb.toggleAssignment('415', 'hw_excluded_2', true);
migratedDb.close();
// Modify legacy db.json (e.g. adding a new student 416 while 415 still has hw_excluded_2 completed: false in JSON)
const updatedLegacy = JSON.parse(fs.readFileSync(migJsonPath, 'utf-8'));
updatedLegacy.students['416'] = {
studentId: '416',
lastSynced: '2026-10-26T10:00:00.000Z',
assignments: {}
};
fs.writeFileSync(migJsonPath, JSON.stringify(updatedLegacy, null, 2), 'utf-8');
const reopenedDb = new LocalDatabase(migDbPath, migJsonPath);
const reopened415 = reopenedDb.getStudentStore('415');
assert.strictEqual(
reopened415.assignments['hw_excluded_2'].completed,
true,
'Restart/re-migration must NEVER overwrite newer completed state in SQLite!'
);
const reopened416 = reopenedDb.getStudentStore('416');
assert.strictEqual(reopened416.lastSynced, '2026-10-26T10:00:00.000Z', 'Additive migration must import newly added student 416');
reopenedDb.close();
});
await test('SQLiteSessionStore: persists sessions, encrypts portalCookies at rest, and prunes expired sessions', async () => {
const db = LocalDatabase.getInstance();
const store = new SQLiteSessionStore({ db: db.getSqliteDb(), pruneIntervalMs: 0 });
@ -1292,6 +1077,149 @@ async function runAllTests() {
}
});
// 14. Persistent Default Secret Generation, Zombie Password Cleanup, and Portal Session Auto-Relogin Tests
await test('Persistent Secrets & Zombie Password Cleanup: preserves generated secret in SQLite meta + .secrets.json across restarts and deletes undecryptable passwords', () => {
const db = LocalDatabase.getInstance();
const sqlite = db.getSqliteDb();
// 1. Verify persistent secrets are stored in SQLite meta table
const sessSecretRow = sqlite
.prepare('SELECT value FROM meta WHERE key = ?')
.get('persistent_session_secret') as { value: string } | undefined;
const encSecretRow = sqlite
.prepare('SELECT value FROM meta WHERE key = ?')
.get('persistent_encryption_secret') as { value: string } | undefined;
assert(sessSecretRow && sessSecretRow.value.length >= 64, 'Persistent session secret must be stored in SQLite meta');
assert(encSecretRow && encSecretRow.value.length >= 64, 'Persistent encryption secret must be stored in SQLite meta');
// 2. Insert a zombie undecryptable password (encrypted with an unknown random key)
const zombieStudentId = 'audit_zombie_password_student';
const randomKey = crypto.randomBytes(32);
const randomSalt = crypto.randomBytes(16);
const randomIv = crypto.randomBytes(12);
const zombieCipher = crypto.createCipheriv('aes-256-gcm', randomKey, randomIv);
let zEnc = zombieCipher.update('OldDeadPassword', 'utf8', 'hex');
zEnc += zombieCipher.final('hex');
const zTag = zombieCipher.getAuthTag().toString('hex');
const undecryptablePayload = `enc:v2:${randomSalt.toString('hex')}:${randomIv.toString('hex')}:${zTag}:${zEnc}`;
db.getStudentStore(zombieStudentId);
sqlite
.prepare('UPDATE students SET remembered_password = ? WHERE student_id = ?')
.run(undecryptablePayload, zombieStudentId);
// Verify getRememberedCredentials returns null and deletes the zombie password from SQLite
const retrievedZombie = db.getRememberedCredentials(zombieStudentId);
assert.strictEqual(retrievedZombie, null, 'Undecryptable zombie password must return null');
assert.strictEqual(
db.getRawEncryptedPassword(zombieStudentId),
null,
'Undecryptable zombie password must be deleted from SQLite'
);
// 3. Verify legacy password encrypted with bekultur_secret_session_key_change_in_production is upgraded to primary v2 key
const envDefaultStudentId = 'audit_env_default_student';
const envDefaultKey = crypto.scryptSync('bekultur_secret_session_key_change_in_production', 'bekultur_credential_salt', 32);
const envIv = crypto.randomBytes(12);
const envCipher = crypto.createCipheriv('aes-256-gcm', envDefaultKey, envIv);
let envEnc = envCipher.update('ValidPortalPass2026', 'utf8', 'hex');
envEnc += envCipher.final('hex');
const envTag = envCipher.getAuthTag().toString('hex');
const envLegacyPayload = `enc:${envIv.toString('hex')}:${envTag}:${envEnc}`;
db.getStudentStore(envDefaultStudentId);
sqlite
.prepare('UPDATE students SET remembered_password = ? WHERE student_id = ?')
.run(envLegacyPayload, envDefaultStudentId);
const sanitizeRes = db.sanitizeStoredCredentials();
assert(sanitizeRes.upgradedCount >= 1, 'sanitizeStoredCredentials must upgrade legacy-key password to primary key');
const upgradedRaw = db.getRawEncryptedPassword(envDefaultStudentId);
assert(upgradedRaw && upgradedRaw.startsWith('enc:v2:'), 'Upgraded password must use enc:v2: format');
const upgradedCreds = db.getRememberedCredentials(envDefaultStudentId);
assert.strictEqual(upgradedCreds?.password, 'ValidPortalPass2026');
});
await test('Portal Session Expiration Recovery: automatically decrypts stored password and re-logs into portal when cookies expire', async () => {
// Verify ScraperService.isSessionExpiredResponse accurately detects 302 login redirects, 401, and girisForm HTML
assert.strictEqual(
ScraperService.isSessionExpiredResponse({ status: 302, headers: { location: '/Giris' } }),
true
);
assert.strictEqual(
ScraperService.isSessionExpiredResponse({ status: 401 }),
true
);
assert.strictEqual(
ScraperService.isSessionExpiredResponse({ status: 200, data: '<form id="girisForm" action="/Giris"></form>' }),
true
);
assert.strictEqual(
ScraperService.isSessionExpiredResponse({ status: 200, data: '<div class="kltr-card">Valid Content</div>' }),
false
);
const db = LocalDatabase.getInstance();
const studentId = 'relogin_recovery_student_415';
db.saveCredentials(studentId, 'StoredDecryptablePass!');
const origLogin = ScraperService.login;
const origScrapeRecent = ScraperService.scrapeMultiplePages;
const origScrapeExams = ScraperService.scrapeAllExamDetails;
const origScrapeSyllabus = ScraperService.scrapeSyllabus;
let loginAttempts = 0;
let usedFreshCookies = false;
ScraperService.login = async (id: string, pass: string) => {
loginAttempts++;
assert.strictEqual(id, studentId);
assert.strictEqual(pass, 'StoredDecryptablePass!');
return {
success: true,
cookies: 'fresh_portal_cookie=valid123',
studentName: 'Test Student'
};
};
ScraperService.scrapeMultiplePages = async (cookies: string) => {
if (cookies === 'expired_cookie=old') {
throw new Error('Session expired or unauthorized. Please log in again.');
}
if (cookies === 'fresh_portal_cookie=valid123') {
usedFreshCookies = true;
}
return { totalPages: 1, assignments: [] };
};
ScraperService.scrapeSyllabus = async (cookies: string) => {
if (cookies === 'expired_cookie=old') {
throw new Error('Session expired or unauthorized. Please log in again.');
}
return { 1: [], 2: [], 3: [], 4: [], 5: [] };
};
ScraperService.scrapeAllExamDetails = async (cookies: string) => {
if (cookies === 'expired_cookie=old') {
throw new Error('Session expired or unauthorized. Please log in again.');
}
return [];
};
try {
await syncWeeklyStudentData(studentId, 'expired_cookie=old', new Date('2026-10-26T09:00:00.000+03:00'));
assert.strictEqual(loginAttempts, 1, 'Concurrent expired tasks must deduplicate to a single portal login call');
assert.strictEqual(usedFreshCookies, true, 'Scraper must retry with fresh cookies obtained from decrypted credentials');
} finally {
ScraperService.login = origLogin;
ScraperService.scrapeMultiplePages = origScrapeRecent;
ScraperService.scrapeAllExamDetails = origScrapeExams;
ScraperService.scrapeSyllabus = origScrapeSyllabus;
}
});
// Optional Live Portal Test (via environment variables only)
const testStudentId = process.env.TEST_STUDENT_ID;
const testPassword = process.env.TEST_PASSWORD;