security+perf: полное ревью — 17 фиксов P0/P1 (XSS, IDOR, race conditions, rate limits, TURN, WAL)
## P0 - admin.html:2608, red-book-ecosystem.html:489-495 — XSS: u.name/node.name_ru/description обернуты в LS.esc() - classController.js getAnnouncements — добавлена проверка teacher_id (B14: учитель A не может читать объявления класса B) ## P1 — auth & validation - authController.js — минимум пароля 6→8 символов (register + change password + login.html) - gamificationController adminAward — валидация max XP/coins (1M), Number coercion - shopController adminAwardCoins — валидация max + проверка changes>0 ## P1 — race conditions - petController.buyBg — atomic UPDATE WHERE coins>=? (race-safe) - shopController.purchaseItem — atomic conditional UPDATE - liveController — добавлен question_id в live_answers (миграция с пересозданием таблицы), история ответов сохраняется при смене вопроса учителем - ws-server: invalidateDrawCache экспортирован, classroomController grant/revoke вызывают его → permission revoke применяется мгновенно (раньше до 10s stale) ## P1 — rate limits & retry - rateLimit middleware: новый параметр byUser=true (использует req.user.id вместо IP — не блокирует пользователей за NAT) - routes/classroom.js: reactionLimiter (15/5s) на /chat/:msgId/react, handLimiter (5/5s) на raise/lower hand - api.js sendAnswer — retry 3x с exp backoff (300/1200/2700ms), не повторяет на 4xx (F5) ## P1 — performance - classroomController.getStrokes — LIMIT 5000 + флаг hasMore (защита от OOM на 10K+ strokes) - whiteboard.js _liveStrokes — TTL 1.5s на каждый live preview (auto-cleanup при крашe ремоут юзера) ## Infrastructure - config.js: TURN_URL/USER/PASS env vars - server.js: GET /api/ice-servers возвращает STUN + опциональный TURN из env - classroom-rtc.js: фетчит /api/ice-servers вместо хардкода (поддержка TURN для NAT/CGNAT школьных сетей) - .env.example: документация TURN - db.js: PRAGMA synchronous=NORMAL (5x быстрее с WAL), cache_size 16MB, temp_store=MEMORY - ws-server.js closeAll() + server.js shutdown — graceful WS shutdown при SIGTERM ## False positives (не баги, агенты ошиблись) - assignmentController FK на tests — на самом деле users (migrate.js:317-318) - .env в git — gitignore корректно исключает - admin.html без requireAuth — есть LS.initPage() который вызывает requireAuth - submissionsController IDOR — обе ручки уже проверяют teacher_id - screenSender = null inside try/catch — на самом деле снаружи - SSE без backoff — есть exponential 2s→30s - sessionController NOT IN на пустом массиве — есть guard usedIds.length>0 - getChat без LIMIT — есть LIMIT 100/200 - trust proxy — установлен на server.js:105 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -36,7 +36,7 @@ function setQuestion(req, res) {
|
||||
if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
|
||||
return res.status(403).json({ error: 'Forbidden' });
|
||||
|
||||
db.prepare('DELETE FROM live_answers WHERE live_session_id=?').run(liveId);
|
||||
// Don't delete old answers — they're scoped per (session, user, question_id) so history is preserved
|
||||
db.prepare(`UPDATE live_sessions SET question_id=?, status='active', show_results=0 WHERE id=?`)
|
||||
.run(question_id, liveId);
|
||||
|
||||
@@ -67,9 +67,11 @@ function answer(req, res) {
|
||||
).get(live.class_id, userId);
|
||||
if (!isMember) return res.status(403).json({ error: 'Forbidden' });
|
||||
|
||||
if (!live.question_id) return res.status(400).json({ error: 'No active question' });
|
||||
|
||||
const existing = db.prepare(
|
||||
'SELECT id FROM live_answers WHERE live_session_id=? AND user_id=?'
|
||||
).get(liveId, userId);
|
||||
'SELECT id FROM live_answers WHERE live_session_id=? AND user_id=? AND question_id=?'
|
||||
).get(liveId, userId, live.question_id);
|
||||
if (existing) return res.status(409).json({ error: 'Уже отвечено' });
|
||||
|
||||
let is_correct = null;
|
||||
@@ -80,14 +82,20 @@ function answer(req, res) {
|
||||
is_correct = opt ? opt.is_correct : 0;
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
`INSERT INTO live_answers (live_session_id, user_id, option_id, answer_text, is_correct)
|
||||
VALUES (?,?,?,?,?)`
|
||||
).run(liveId, userId, option_id || null, answer_text || null, is_correct);
|
||||
// Atomic INSERT — race-safe via UNIQUE(session, user, question_id)
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO live_answers (live_session_id, user_id, question_id, option_id, answer_text, is_correct)
|
||||
VALUES (?,?,?,?,?,?)`
|
||||
).run(liveId, userId, live.question_id, option_id || null, answer_text || null, is_correct);
|
||||
} catch (e) {
|
||||
if (String(e.message).includes('UNIQUE')) return res.status(409).json({ error: 'Уже отвечено' });
|
||||
throw e;
|
||||
}
|
||||
|
||||
const { c: count } = db.prepare(
|
||||
'SELECT COUNT(*) AS c FROM live_answers WHERE live_session_id=?'
|
||||
).get(liveId);
|
||||
'SELECT COUNT(*) AS c FROM live_answers WHERE live_session_id=? AND question_id=?'
|
||||
).get(liveId, live.question_id);
|
||||
emit(live.teacher_id, { type: 'live_answer_count', liveId, count });
|
||||
|
||||
res.json({ ok: true, is_correct });
|
||||
@@ -111,15 +119,15 @@ function results(req, res) {
|
||||
SELECT o.id, o.text, o.is_correct,
|
||||
COUNT(la.id) AS chosen_count
|
||||
FROM options o
|
||||
LEFT JOIN live_answers la ON la.option_id=o.id AND la.live_session_id=?
|
||||
LEFT JOIN live_answers la ON la.option_id=o.id AND la.live_session_id=? AND la.question_id=?
|
||||
WHERE o.question_id=?
|
||||
GROUP BY o.id ORDER BY o.order_index
|
||||
`).all(liveId, live.question_id);
|
||||
`).all(liveId, live.question_id, live.question_id);
|
||||
|
||||
const stats = db.prepare(
|
||||
`SELECT COUNT(*) AS total, SUM(is_correct) AS correct
|
||||
FROM live_answers WHERE live_session_id=?`
|
||||
).get(liveId);
|
||||
FROM live_answers WHERE live_session_id=? AND question_id=?`
|
||||
).get(liveId, live.question_id);
|
||||
|
||||
db.prepare('UPDATE live_sessions SET show_results=1 WHERE id=?').run(liveId);
|
||||
emitToClass(live.class_id, { type: 'live_results', liveId, question, options, stats });
|
||||
@@ -167,8 +175,8 @@ function getActive(req, res) {
|
||||
'SELECT id, text, order_index FROM options WHERE question_id=? ORDER BY order_index'
|
||||
).all(live.question_id);
|
||||
myAnswer = db.prepare(
|
||||
'SELECT option_id, is_correct FROM live_answers WHERE live_session_id=? AND user_id=?'
|
||||
).get(live.id, req.user.id);
|
||||
'SELECT option_id, is_correct FROM live_answers WHERE live_session_id=? AND user_id=? AND question_id=?'
|
||||
).get(live.id, req.user.id, live.question_id);
|
||||
}
|
||||
|
||||
res.json({ active: true, live, question, options, myAnswer, showResults: live.show_results });
|
||||
|
||||
Reference in New Issue
Block a user