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:
@@ -25,7 +25,10 @@ if (!fs.existsSync(dbPath) && fs.existsSync(oldPath)) {
|
||||
const db = new DatabaseSync(dbPath);
|
||||
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA synchronous = NORMAL'); // safe with WAL, ~5x faster than FULL
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA cache_size = -16000'); // 16 MB page cache (was default ~2 MB)
|
||||
db.exec('PRAGMA temp_store = MEMORY'); // temp tables in RAM, not disk
|
||||
|
||||
/**
|
||||
* Run a synchronous function inside a BEGIN/COMMIT/ROLLBACK transaction.
|
||||
|
||||
@@ -908,6 +908,40 @@ db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_live_sessions_class ON live_sessions(class_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_live_answers_session ON live_answers(live_session_id);
|
||||
`);
|
||||
|
||||
// Migration: add question_id to live_answers + recreate unique constraint
|
||||
// (so history is preserved when teacher switches between questions in one session)
|
||||
{
|
||||
const cols = db.prepare('PRAGMA table_info(live_answers)').all();
|
||||
const hasQid = cols.some(c => c.name === 'question_id');
|
||||
if (!hasQid) {
|
||||
db.exec('PRAGMA foreign_keys = OFF');
|
||||
db.exec(`
|
||||
CREATE TABLE live_answers_v2 (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
live_session_id INTEGER NOT NULL REFERENCES live_sessions(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||
question_id INTEGER REFERENCES questions(id) ON DELETE SET NULL,
|
||||
option_id INTEGER REFERENCES options(id),
|
||||
answer_text TEXT,
|
||||
is_correct INTEGER,
|
||||
answered_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE(live_session_id, user_id, question_id)
|
||||
)
|
||||
`);
|
||||
// Migrate existing rows — old answers don't have question_id, set NULL
|
||||
db.exec(`
|
||||
INSERT INTO live_answers_v2 (id, live_session_id, user_id, option_id, answer_text, is_correct, answered_at)
|
||||
SELECT id, live_session_id, user_id, option_id, answer_text, is_correct, answered_at FROM live_answers
|
||||
`);
|
||||
db.exec('DROP TABLE live_answers');
|
||||
db.exec('ALTER TABLE live_answers_v2 RENAME TO live_answers');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_live_answers_session ON live_answers(live_session_id)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_live_answers_question ON live_answers(live_session_id, question_id)');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
console.log('✓ Migrated live_answers → added question_id');
|
||||
}
|
||||
}
|
||||
console.log('✓ Live quiz tables ready');
|
||||
|
||||
/* ── Submission audit log ──────────────────────────────────────────────── */
|
||||
|
||||
Reference in New Issue
Block a user