import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createTestApp, PASSWORD, sampleQuestions, type TestApp } from './helpers.ts'; import { queueIdle } from '../server/services/documents.ts'; let t: TestApp; beforeEach(async () => { t = await createTestApp(); }); afterEach(() => t.close()); async function makeClass(name = 'Pharmacology') { const res = await t.api('POST', '/api/classes', { name }); expect(res.status).toBe(201); return res.body.class as { id: string; name: string }; } describe('authentication', () => { it('requires the setup code, then a session, for private routes', async () => { const fresh = await createTestApp({ login: false }); try { expect((await fresh.api('GET', '/api/auth/status')).body).toEqual({ configured: false, authenticated: false }); expect((await fresh.api('GET', '/api/classes')).status).toBe(401); const bad = await fresh.api('POST', '/api/auth/setup', { code: 'WRONG-CODE', password: PASSWORD }); expect(bad.status).toBe(403); expect(fs.existsSync(path.join(fresh.dir, 'setup-code.txt'))).toBe(true); const code = fs.readFileSync(path.join(fresh.dir, 'setup-code.txt'), 'utf8').trim(); const ok = await fresh.raw('POST', '/api/auth/setup', { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, password: PASSWORD }) }); expect(ok.status).toBe(200); const cookie = ok.headers.get('set-cookie') ?? ''; expect(cookie).toMatch(/HttpOnly/i); expect(cookie).toMatch(/SameSite=Lax/i); expect(fs.existsSync(path.join(fresh.dir, 'setup-code.txt'))).toBe(false); // Setup cannot be repeated. expect((await fresh.api('POST', '/api/auth/setup', { code, password: 'another password' })).status).toBe(409); fresh.cookie = cookie.split(';')[0]; expect((await fresh.api('GET', '/api/classes')).status).toBe(200); } finally { fresh.close(); } }); it('rejects wrong passwords, rate-limits, and logs out', async () => { expect((await t.api('POST', '/api/auth/login', { password: 'nope' }, { cookie: null })).status).toBe(401); const good = await t.raw('POST', '/api/auth/login', { cookie: null, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ password: PASSWORD }) }); expect(good.status).toBe(200); for (let i = 0; i < 8; i += 1) await t.api('POST', '/api/auth/login', { password: 'nope' }, { cookie: null }); const limited = await t.api('POST', '/api/auth/login', { password: PASSWORD }, { cookie: null }); expect(limited.status).toBe(429); expect(limited.headers.get('retry-after')).toBeTruthy(); expect((await t.api('POST', '/api/auth/logout')).status).toBe(200); expect((await t.api('GET', '/api/classes')).status).toBe(401); }); it('blocks state-changing requests without the CSRF header or from another site', async () => { const noHeader = await t.hono.request('/api/classes', { method: 'POST', headers: { cookie: t.cookie, 'content-type': 'application/json' }, body: JSON.stringify({ name: 'X' }) }); expect(noHeader.status).toBe(403); const crossSite = await t.api('POST', '/api/classes', { name: 'X' }, { headers: { 'sec-fetch-site': 'cross-site' } }); expect(crossSite.status).toBe(403); }); it('changes the password and signs out other sessions', async () => { const other = await t.raw('POST', '/api/auth/login', { cookie: null, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ password: PASSWORD }) }); const otherCookie = (other.headers.get('set-cookie') ?? '').split(';')[0]; expect((await t.api('POST', '/api/auth/password', { current: 'wrong', next: 'a new password!' })).status).toBe(403); expect((await t.api('POST', '/api/auth/password', { current: PASSWORD, next: 'a new password!' })).status).toBe(200); expect((await t.api('GET', '/api/classes')).status).toBe(200); expect((await t.api('GET', '/api/classes', undefined, { cookie: otherCookie })).status).toBe(401); expect((await t.api('POST', '/api/auth/login', { password: 'a new password!' }, { cookie: null })).status).toBe(200); }); }); describe('classes, quizzes and questions', () => { it('creates, edits, duplicates, moves and deletes', async () => { const cls = await makeClass(); const other = await makeClass('Pediatrics'); const folder = (await t.api('POST', `/api/classes/${cls.id}/folders`, { name: 'Unit 1' })).body.folder; const created = await t.api('POST', '/api/quizzes', { classId: cls.id, folderId: folder.id, title: 'Electrolytes', questions: sampleQuestions }); expect(created.status).toBe(201); const quizId = created.body.quiz.id; let detail = (await t.api('GET', `/api/quizzes/${quizId}`)).body; expect(detail.questions).toHaveLength(3); expect(detail.questions[0].options.every((o: any) => typeof o.id === 'string')).toBe(true); // Validation: multiple choice with two correct answers is rejected with a clear message. const invalid = await t.api('PATCH', `/api/questions/${detail.questions[0].id}`, { ...sampleQuestions[0], options: sampleQuestions[0].options.map((o) => ({ ...o, correct: true })) }); expect(invalid.status).toBe(422); expect(invalid.body.error.message).toMatch(/exactly one correct/i); // Editing keeps option ids for unchanged text. const before = detail.questions[0]; const edited = await t.api('PATCH', `/api/questions/${before.id}`, { ...sampleQuestions[0], stem: 'Edited stem?' }); expect(edited.body.question.stem).toBe('Edited stem?'); expect(edited.body.question.options.map((o: any) => o.id)).toEqual(before.options.map((o: any) => o.id)); const dup = await t.api('POST', `/api/quizzes/${quizId}/duplicate`, {}); expect(dup.status).toBe(201); expect(dup.body.quiz.title).toBe('Electrolytes (copy)'); await t.api('POST', '/api/items/move', { items: [{ kind: 'quiz', id: dup.body.quiz.id }], classId: other.id }); const otherDetail = (await t.api('GET', `/api/classes/${other.id}`)).body; expect(otherDetail.items.map((i: any) => i.title)).toContain('Electrolytes (copy)'); await t.api('POST', `/api/quizzes/${quizId}/questions/reorder`, { ids: [...detail.questions].reverse().map((q: any) => q.id) }); detail = (await t.api('GET', `/api/quizzes/${quizId}`)).body; expect(detail.questions[0].topic).toBe('Electrolytes'); expect(detail.questions[2].stem).toBe('Edited stem?'); expect((await t.api('DELETE', `/api/quizzes/${quizId}`)).status).toBe(200); expect((await t.api('GET', `/api/quizzes/${quizId}`)).status).toBe(404); const search = await t.api('GET', '/api/search?q=digoxin'); expect(search.body.results.some((r: any) => r.kind === 'question')).toBe(true); expect((await t.api('DELETE', `/api/classes/${other.id}`)).status).toBe(200); expect((await t.api('GET', '/api/classes')).body.classes).toHaveLength(1); }); }); describe('quiz sessions', () => { it('runs a practice session with resume, scoring, history and missed-question review', async () => { const cls = await makeClass(); const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Electrolytes', questions: sampleQuestions })).body.quiz.id; const started = await t.api('POST', '/api/attempts', { mode: 'practice', source: { type: 'quiz', quizId }, shuffleQuestions: false, shuffleOptions: true }); expect(started.status).toBe(201); const attempt = started.body.attempt; expect(attempt.questions).toHaveLength(3); const pick = (q: any, correct: boolean) => q.options.filter((o: any) => o.correct === correct).map((o: any) => o.id); const [q1, q2, q3] = attempt.questions; // Q1 correct, Q2 partially correct (2 of 3), Q3 wrong. await t.api('PATCH', `/api/attempts/${attempt.id}`, { answers: { [q1.id]: { selected: pick(q1, true), checked: true } }, currentIndex: 1, elapsedSec: 20 }); // Resume: the session is listed as active and keeps its answers and position. const active = (await t.api('GET', '/api/attempts?status=active')).body.attempts; expect(active).toHaveLength(1); expect(active[0].answeredCount).toBe(1); const resumed = (await t.api('GET', `/api/attempts/${attempt.id}`)).body.attempt; expect(resumed.currentIndex).toBe(1); expect(resumed.answers[q1.id].checked).toBe(true); // A checked practice answer cannot be changed afterwards. await t.api('PATCH', `/api/attempts/${attempt.id}`, { answers: { [q1.id]: { selected: pick(q1, false).slice(0, 1), checked: true } } }); await t.api('PATCH', `/api/attempts/${attempt.id}`, { answers: { [q2.id]: { selected: pick(q2, true).slice(0, 2), checked: true }, [q3.id]: { selected: pick(q3, false).slice(0, 1), checked: true } }, elapsedSec: 95, }); const done = (await t.api('POST', `/api/attempts/${attempt.id}/complete`, { elapsedSec: 100 })).body.attempt; expect(done.status).toBe('completed'); expect(done.maxScore).toBe(3); expect(done.score).toBeCloseTo(1 + 2 / 3 + 0, 5); expect(done.results[q1.id].correct).toBe(true); expect(done.results[q2.id].correct).toBe(false); expect(done.elapsedSec).toBe(100); const quiz = (await t.api('GET', `/api/quizzes/${quizId}`)).body; expect(quiz.history).toHaveLength(1); expect(quiz.questionStats[q3.id]).toEqual({ seen: 1, correct: 0, lastCorrect: false }); // Retake only what was missed. const retake = await t.api('POST', '/api/attempts', { mode: 'practice', source: { type: 'retake', attemptId: attempt.id } }); expect(retake.status).toBe(201); expect(retake.body.attempt.questions.map((q: any) => q.id).sort()).toEqual([q2.id, q3.id].sort()); const overview = (await t.api('GET', '/api/overview')).body; expect(overview.totals.questionsAnswered).toBe(3); expect(overview.missedCount).toBe(2); expect(overview.activity.at(-1).questions).toBe(3); const missed = await t.api('POST', '/api/attempts', { mode: 'practice', source: { type: 'missed', classId: cls.id } }); expect(missed.body.attempt.questions).toHaveLength(2); }); it('scores exams with blanks as wrong and survives quiz edits mid-session', async () => { const cls = await makeClass(); const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Exam', questions: sampleQuestions })).body.quiz.id; const attempt = (await t.api('POST', '/api/attempts', { mode: 'exam', source: { type: 'quiz', quizId }, timeLimitMin: 10 })).body.attempt; expect(attempt.settings.timeLimitSec).toBe(600); const q = attempt.questions[0]; // Exam answers stay editable until submission. await t.api('PATCH', `/api/attempts/${attempt.id}`, { answers: { [q.id]: { selected: [q.options.find((o: any) => !o.correct).id] } } }); await t.api('PATCH', `/api/attempts/${attempt.id}`, { answers: { [q.id]: { selected: q.options.filter((o: any) => o.correct).map((o: any) => o.id) } }, flags: [q.id] }); // Deleting the quiz while the exam is open must not break the session snapshot. const live = (await t.api('GET', `/api/quizzes/${quizId}`)).body.questions; await t.api('DELETE', `/api/questions/${live[1].id}`); const done = (await t.api('POST', `/api/attempts/${attempt.id}/complete`, {})).body.attempt; expect(done.maxScore).toBe(3); expect(done.score).toBe(1); expect(done.questions).toHaveLength(3); expect(done.flags).toEqual([q.id]); expect((await t.api('PATCH', `/api/attempts/${attempt.id}`, { currentIndex: 2 })).status).toBe(400); }); }); describe('flashcards and spaced repetition', () => { it('schedules reviews with FSRS, respects the daily new-card limit, and undoes', async () => { const cls = await makeClass(); const cards = Array.from({ length: 30 }, (_, i) => ({ front: `Term ${i + 1}`, back: `Definition ${i + 1}` })); const deckId = (await t.api('POST', '/api/decks', { classId: cls.id, title: 'Terms', cards })).body.deck.id; let queue = (await t.api('GET', `/api/review/queue?deckId=${deckId}`)).body; expect(queue.cards).toHaveLength(20); // default new cards per day expect(queue.counts).toMatchObject({ new: 20, review: 0, learning: 0 }); expect(queue.cards[0].previews.map((p: any) => p.label)).toEqual(['Again', 'Hard', 'Good', 'Easy']); const first = queue.cards[0].card; const easy = (await t.api('POST', '/api/review/answer', { cardId: first.id, rating: 4 })).body.result; expect(easy.card.state).toBe(2); // straight to review expect(easy.card.due).toBeGreaterThan(Date.now() + 86_400_000); expect(easy.card.reps).toBe(1); const second = queue.cards[1].card; const again = (await t.api('POST', '/api/review/answer', { cardId: second.id, rating: 1 })).body.result; expect(again.card.state).toBe(1); // learning, due within minutes expect(again.card.due).toBeLessThan(Date.now() + 20 * 60_000); queue = (await t.api('GET', `/api/review/queue?deckId=${deckId}`)).body; expect(queue.counts.learning).toBe(1); expect(queue.counts.new).toBe(18); expect(queue.cards[0].card.id).toBe(second.id); // learning cards come first const undone = (await t.api('POST', '/api/review/undo', { cardId: first.id })).body.result; expect(undone.card.state).toBe(0); expect(undone.card.reps).toBe(0); const deck = (await t.api('GET', `/api/decks/${deckId}`)).body; expect(deck.stats).toMatchObject({ total: 30, new: 29, learning: 1 }); // Suspended cards leave the queue; resetting restores them as new. await t.api('PATCH', `/api/cards/${second.id}`, { suspended: true }); expect((await t.api('GET', `/api/review/queue?deckId=${deckId}`)).body.counts.learning).toBe(0); // Cram progress is saved and restored. await t.api('PUT', `/api/decks/${deckId}/session`, { state: { order: ['a', 'b'], index: 1 } }); expect((await t.api('GET', `/api/decks/${deckId}`)).body.session.state).toEqual({ order: ['a', 'b'], index: 1 }); await t.api('POST', '/api/review/cram', { cardId: first.id, known: true }); expect((await t.api('GET', '/api/overview')).body.activity.at(-1).cards).toBeGreaterThanOrEqual(2); }); }); describe('sharing', () => { it('serves shared content anonymously and stops when revoked', async () => { const cls = await makeClass(); const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Shared quiz', questions: sampleQuestions })).body.quiz.id; const privateQuizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Private quiz', questions: sampleQuestions })).body.quiz.id; const share = (await t.api('POST', '/api/shares', { kind: 'quiz', targetId: quizId })).body.share; expect(share.token.length).toBeGreaterThanOrEqual(32); const anon = { cookie: null }; const pub = await t.api('GET', `/api/public/${share.token}`, undefined, anon); expect(pub.status).toBe(200); expect(pub.body.kind).toBe('quiz'); expect(pub.body.questions).toHaveLength(3); expect(pub.headers.get('x-robots-tag')).toMatch(/noindex/); // Visitors cannot reach anything else. expect((await t.api('GET', `/api/quizzes/${privateQuizId}`, undefined, anon)).status).toBe(401); expect((await t.api('GET', `/api/public/${share.token}/items/quiz/${privateQuizId}`, undefined, anon)).status).toBe(404); expect((await t.api('PATCH', `/api/quizzes/${quizId}`, { title: 'hacked' }, anon)).status).toBe(401); expect((await t.api('POST', `/api/public/${share.token}`, { x: 1 }, anon)).status).toBe(401); expect((await t.api('GET', '/api/public/not-a-real-token-000000000000000000', undefined, anon)).status).toBe(404); // Disable, re-enable, rotate, delete. await t.api('PATCH', `/api/shares/${share.id}`, { enabled: false }); expect((await t.api('GET', `/api/public/${share.token}`, undefined, anon)).status).toBe(404); await t.api('PATCH', `/api/shares/${share.id}`, { enabled: true }); const rotated = (await t.api('POST', `/api/shares/${share.id}/rotate`)).body.share; expect(rotated.token).not.toBe(share.token); expect((await t.api('GET', `/api/public/${share.token}`, undefined, anon)).status).toBe(404); expect((await t.api('GET', `/api/public/${rotated.token}`, undefined, anon)).status).toBe(200); await t.api('DELETE', `/api/shares/${share.id}`); expect((await t.api('GET', `/api/public/${rotated.token}`, undefined, anon)).status).toBe(404); }); it("shares a class as a collection without exposing other classes' content", async () => { const cls = await makeClass(); const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Q', questions: sampleQuestions })).body.quiz.id; const deckId = (await t.api('POST', '/api/decks', { classId: cls.id, title: 'D', cards: [{ front: 'a', back: 'b' }] })).body.deck.id; await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Empty quiz' }); const other = await makeClass('Other'); const otherQuiz = (await t.api('POST', '/api/quizzes', { classId: other.id, title: 'Other', questions: sampleQuestions })).body.quiz.id; // Documents in the shared class are included once processed (see revision1.test.ts); other classes' never are. await t.api('POST', '/api/documents/text', { classId: other.id, title: 'Secret notes', text: 'private lecture content' }); await queueIdle(t.ctx); const share = (await t.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share; const anon = { cookie: null }; const pub = (await t.api('GET', `/api/public/${share.token}`, undefined, anon)).body; expect(pub.kind).toBe('collection'); expect(pub.items.map((i: any) => i.kind).sort()).toEqual(['deck', 'quiz']); expect(JSON.stringify(pub)).not.toContain('Secret notes'); expect((await t.api('GET', `/api/public/${share.token}/items/quiz/${quizId}`, undefined, anon)).body.questions).toHaveLength(3); expect((await t.api('GET', `/api/public/${share.token}/items/deck/${deckId}`, undefined, anon)).body.cards).toHaveLength(1); expect((await t.api('GET', `/api/public/${share.token}/items/quiz/${otherQuiz}`, undefined, anon)).status).toBe(404); expect((await t.api('GET', `/api/public/${share.token}/file`, undefined, anon)).status).toBe(404); // Deleting the class removes its links. await t.api('DELETE', `/api/classes/${cls.id}`); expect((await t.api('GET', `/api/public/${share.token}`, undefined, anon)).status).toBe(404); }); }); describe('import, export and templates', () => { it('round-trips a quiz and a deck through export and import', async () => { const cls = await makeClass(); const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Electrolytes', questions: sampleQuestions })).body.quiz.id; const exported = (await t.api('GET', `/api/quizzes/${quizId}/export`)).body; expect(exported).toMatchObject({ format: 'studydesk', version: 2, kind: 'quiz', title: 'Electrolytes' }); const imported = await t.api('POST', '/api/import', { classId: cls.id, items: [exported] }); expect(imported.status).toBe(201); const copy = (await t.api('GET', `/api/quizzes/${imported.body.created[0].id}`)).body; expect(copy.questions.map((q: any) => q.stem)).toEqual(sampleQuestions.map((q) => q.stem)); // V1 format is accepted as-is. const v1 = { type: 'quiz', quizName: 'Old quiz', questions: [{ type: 'sata', prompt: 'Pick two', category: 'cat', rationale: 'r', options: [{ text: 'a', correct: true }, { text: 'b', correct: true }, { text: 'c', correct: false }] }] }; const fromV1 = await t.api('POST', '/api/import', { classId: cls.id, items: [v1] }); expect(fromV1.status).toBe(201); const v1Quiz = (await t.api('GET', `/api/quizzes/${fromV1.body.created[0].id}`)).body; expect(v1Quiz.questions[0]).toMatchObject({ type: 'multi', topic: 'cat' }); // Invalid content is rejected with a pointer to the problem, and nothing is created. const bad = await t.api('POST', '/api/import', { classId: cls.id, items: [{ kind: 'quiz', title: 'Bad', questions: [{ stem: 'No correct answer', options: [{ text: 'a' }, { text: 'b' }] }] }] }); expect(bad.status).toBe(422); expect(bad.body.error.message).toMatch(/question 1/i); const bundle = (await t.api('GET', '/api/export/all')).body; expect(bundle.classes[0].quizzes).toHaveLength(3); const restored = await t.api('POST', '/api/import/bundle', bundle); expect(restored.body.summary).toMatchObject({ classes: 1, quizzes: 3 }); expect((await t.api('GET', '/api/classes')).body.classes.map((c: any) => c.name)).toContain('Pharmacology (imported)'); }); it('lists built-in templates, saves a quiz as a template and creates from it', async () => { const cls = await makeClass(); const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Source', questions: sampleQuestions })).body.quiz.id; const list = (await t.api('GET', '/api/templates')).body.templates; expect(list.filter((x: any) => x.builtin).length).toBeGreaterThanOrEqual(8); const tpl = (await t.api('POST', '/api/templates/from', { kind: 'quiz', id: quizId, name: 'My template' })).body.template; const used = await t.api('POST', `/api/templates/${tpl.id}/use`, { classId: cls.id, title: 'From template' }); expect(used.status).toBe(201); expect((await t.api('GET', `/api/quizzes/${used.body.created.id}`)).body.questions).toHaveLength(3); expect((await t.api('DELETE', '/api/templates/builtin-gen-nclex')).status).toBe(404); expect((await t.api('DELETE', `/api/templates/${tpl.id}`)).status).toBe(200); }); }); describe('persistence and backups', () => { it('keeps data across a restart and writes a usable snapshot', async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studydesk-persist-')); const first = await createTestApp({ dir }); const cls = (await first.api('POST', '/api/classes', { name: 'Persistent' })).body.class; await first.api('POST', '/api/quizzes', { classId: cls.id, title: 'Kept', questions: sampleQuestions }); const backup = (await first.api('POST', '/api/backups')).body.backup; expect(fs.statSync(path.join(dir, 'backups', backup.name)).size).toBeGreaterThan(1000); first.close(); const second = await createTestApp({ dir }); try { const classes = (await second.api('GET', '/api/classes')).body.classes; expect(classes.map((c: any) => c.name)).toEqual(['Persistent']); expect(classes[0].counts.quizzes).toBe(1); const zip = await second.raw('GET', '/api/backup/download'); expect(zip.status).toBe(200); const bytes = new Uint8Array(await zip.arrayBuffer()); expect(String.fromCharCode(bytes[0], bytes[1])).toBe('PK'); } finally { second.close(); fs.rmSync(dir, { recursive: true, force: true }); } }); });