diff --git a/backend/.env.example b/backend/.env.example
index a40555a..6f1d71d 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -6,3 +6,10 @@ JWT_EXPIRES_IN=7d
# CORS — адрес фронтенда
CLIENT_ORIGIN=http://localhost:5500
+
+# WebRTC TURN (нужен для клиентов за симметричным NAT/CGNAT — школьные сети, мобильный)
+# Без TURN установка соединения может не пройти. STUN-серверы Google добавляются автоматически.
+# Пример: coturn, Twilio Network Traversal Service
+# TURN_URL=turn:turn.example.com:3478
+# TURN_USER=username
+# TURN_PASS=password
diff --git a/backend/src/config.js b/backend/src/config.js
index ec40902..7c29dd4 100644
--- a/backend/src/config.js
+++ b/backend/src/config.js
@@ -59,6 +59,10 @@ module.exports = Object.freeze({
/* paths */
DB_PATH: _optional('DB_PATH', path.join(__dirname, '../data/learnspace.db')),
UPLOADS_DIR: _optional('UPLOADS_DIR', path.join(__dirname, '../uploads')),
+ /* WebRTC ICE servers — TURN required for clients behind symmetric NAT/CGNAT (school networks) */
+ TURN_URL: _optional('TURN_URL'), // e.g. turn:turn.example.com:3478
+ TURN_USER: _optional('TURN_USER'),
+ TURN_PASS: _optional('TURN_PASS'),
/* constants */
BCRYPT_ROUNDS: 12,
MAX_FILE_SIZE: 50 * 1024 * 1024,
diff --git a/backend/src/controllers/authController.js b/backend/src/controllers/authController.js
index cd3bfaa..5f42e91 100644
--- a/backend/src/controllers/authController.js
+++ b/backend/src/controllers/authController.js
@@ -19,8 +19,8 @@ async function register(req, res, next) {
if (!email || !password || !name)
return res.status(400).json({ error: 'email, password and name are required' });
- if (password.length < 6)
- return res.status(400).json({ error: 'Password must be at least 6 characters' });
+ if (password.length < 8)
+ return res.status(400).json({ error: 'Password must be at least 8 characters' });
if (db.prepare('SELECT id FROM users WHERE email = ?').get(email))
return res.status(409).json({ error: 'Email already registered' });
@@ -84,7 +84,7 @@ async function updateProfile(req, res, next) {
if (!currentPassword) return res.status(400).json({ error: 'Текущий пароль обязателен' });
const valid = await bcrypt.compare(currentPassword, user.password_hash);
if (!valid) return res.status(401).json({ error: 'Неверный текущий пароль' });
- if (newPassword.length < 6) return res.status(400).json({ error: 'Пароль минимум 6 символов' });
+ if (newPassword.length < 8) return res.status(400).json({ error: 'Пароль минимум 8 символов' });
const hash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
db.prepare('UPDATE users SET password_hash = ?, token_version = token_version + 1 WHERE id = ?').run(hash, user.id);
}
diff --git a/backend/src/controllers/classController.js b/backend/src/controllers/classController.js
index 14afcf3..b7babe4 100644
--- a/backend/src/controllers/classController.js
+++ b/backend/src/controllers/classController.js
@@ -420,6 +420,10 @@ function myClasses(req, res) {
/* ── GET /api/classes/:id/announcements ─────────────────────────────────── */
function getAnnouncements(req, res) {
+ const cls = stmts.getClassOwner.get(req.params.id);
+ if (!cls) return res.status(404).json({ error: 'Not found' });
+ if (req.user.role !== 'admin' && cls.teacher_id !== req.user.id)
+ return res.status(403).json({ error: 'Forbidden' });
const announcements = db.prepare(`
SELECT a.id, a.text, a.created_at, u.name AS author_name
FROM announcements a
diff --git a/backend/src/controllers/classroomController.js b/backend/src/controllers/classroomController.js
index 9bf12b2..dba18b4 100644
--- a/backend/src/controllers/classroomController.js
+++ b/backend/src/controllers/classroomController.js
@@ -3,7 +3,7 @@ const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { getOnlineUserIds } = require('../sse');
-const { emitToUser, invalidateSession } = require('../ws-server');
+const { emitToUser, invalidateSession, invalidateDrawCache } = require('../ws-server');
/* ── chat attachment uploads dir ─────────────────────────────────────── */
const CHAT_UPLOADS_DIR = path.join(__dirname, '../../uploads/chat');
@@ -616,17 +616,20 @@ function getStrokes(req, res) {
if (!hasAccess(session, req.user.id, req.user.role))
return res.status(403).json({ error: 'Нет доступа' });
+ // LIMIT 5000 — guards against OOM on very long sessions; client paginates via since_seq
+ const STROKES_PAGE_LIMIT = 5000;
const rows = sinceSeq >= 0
- ? db.prepare('SELECT id, tool, data, seq FROM classroom_strokes WHERE session_id=? AND page_num=? AND seq > ? ORDER BY seq').all(sessionId, pageNum, sinceSeq)
- : db.prepare('SELECT id, tool, data, seq FROM classroom_strokes WHERE session_id=? AND page_num=? ORDER BY seq').all(sessionId, pageNum);
+ ? db.prepare('SELECT id, tool, data, seq FROM classroom_strokes WHERE session_id=? AND page_num=? AND seq > ? ORDER BY seq LIMIT ?').all(sessionId, pageNum, sinceSeq, STROKES_PAGE_LIMIT)
+ : db.prepare('SELECT id, tool, data, seq FROM classroom_strokes WHERE session_id=? AND page_num=? ORDER BY seq LIMIT ?').all(sessionId, pageNum, STROKES_PAGE_LIMIT);
const strokes = rows.map(r => ({ ...r, data: JSON.parse(r.data) }));
+ const hasMore = rows.length === STROKES_PAGE_LIMIT;
const pageRow = db.prepare('SELECT template, name FROM classroom_pages WHERE session_id=? AND page_num=?').get(sessionId, pageNum);
const template = pageRow?.template || 'blank';
const name = pageRow?.name || null;
- res.json({ strokes, template, name });
+ res.json({ strokes, template, name, hasMore });
}
/* PATCH /api/classroom/:id/strokes/:strokeId — update image position/size */
@@ -870,6 +873,7 @@ function allowDraw(req, res) {
db.prepare(
'INSERT OR IGNORE INTO classroom_draw_permissions (session_id, user_id) VALUES (?,?)'
).run(sessionId, targetId);
+ invalidateDrawCache(sessionId, targetId);
emitToUser(targetId, { type: 'classroom_draw_permitted', sessionId });
res.json({ ok: true });
@@ -887,6 +891,7 @@ function revokeDraw(req, res) {
db.prepare(
'DELETE FROM classroom_draw_permissions WHERE session_id=? AND user_id=?'
).run(sessionId, targetId);
+ invalidateDrawCache(sessionId, targetId);
emitToUser(targetId, { type: 'classroom_draw_revoked', sessionId });
res.json({ ok: true });
diff --git a/backend/src/controllers/gamificationController.js b/backend/src/controllers/gamificationController.js
index c1d5f70..e8a4581 100644
--- a/backend/src/controllers/gamificationController.js
+++ b/backend/src/controllers/gamificationController.js
@@ -788,13 +788,18 @@ function getXPHistory(req, res) {
═══════════════════════════════════════════════════════════════════════ */
/* POST /api/gamification/admin/award — award XP or coins to user */
+const ADMIN_AWARD_MAX = 1_000_000;
function adminAward(req, res) {
const { userId, xp, coins, reason } = req.body;
if (!userId) return res.status(400).json({ error: 'userId required' });
+ const xpNum = Number(xp) || 0;
+ const coinsNum = Number(coins) || 0;
+ if (xpNum < 0 || xpNum > ADMIN_AWARD_MAX) return res.status(400).json({ error: `xp must be 0..${ADMIN_AWARD_MAX}` });
+ if (coinsNum < 0 || coinsNum > ADMIN_AWARD_MAX) return res.status(400).json({ error: `coins must be 0..${ADMIN_AWARD_MAX}` });
const user = stmts.checkUserById.get(userId);
if (!user) return res.status(404).json({ error: 'User not found' });
- if (xp && xp > 0) awardXP(userId, xp, reason || 'Admin award');
- if (coins && coins > 0) awardCoins(userId, coins, reason || 'Admin award');
+ if (xpNum > 0) awardXP(userId, xpNum, reason || 'Admin award');
+ if (coinsNum > 0) awardCoins(userId, coinsNum, reason || 'Admin award');
const updated = stmts.getUserGamInfo.get(userId);
res.json({ ok: true, ...updated });
}
diff --git a/backend/src/controllers/liveController.js b/backend/src/controllers/liveController.js
index 3d24e7e..020b88f 100644
--- a/backend/src/controllers/liveController.js
+++ b/backend/src/controllers/liveController.js
@@ -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 });
diff --git a/backend/src/controllers/petController.js b/backend/src/controllers/petController.js
index 13ce618..0309df9 100644
--- a/backend/src/controllers/petController.js
+++ b/backend/src/controllers/petController.js
@@ -234,18 +234,11 @@ function buyBg(req, res) {
if (!user) return res.status(404).json({ error: 'not found' });
const owned = _parseOwned(user.pet_bg_owned);
if (!owned.includes(id)) {
- if ((user.coins || 0) < item.price) return res.status(400).json({ error: 'insufficient_coins' });
- const buy = db.transaction(() => {
- // Re-check balance inside transaction to prevent race
- const fresh = db.prepare('SELECT coins FROM users WHERE id=?').get(req.user.id);
- if ((fresh.coins || 0) < item.price) throw new Error('insufficient_coins');
- db.prepare('UPDATE users SET coins=coins-?, pet_bg_owned=?, pet_bg=? WHERE id=?')
- .run(item.price, JSON.stringify([...owned, id]), id, req.user.id);
- });
- try { buy(); } catch (e) {
- if (e.message === 'insufficient_coins') return res.status(400).json({ error: 'insufficient_coins' });
- throw e;
- }
+ // Atomic conditional UPDATE — race-safe even under concurrent purchase attempts
+ const result = db.prepare(
+ 'UPDATE users SET coins = coins - ?, pet_bg_owned = ?, pet_bg = ? WHERE id = ? AND coins >= ?'
+ ).run(item.price, JSON.stringify([...owned, id]), id, req.user.id, item.price);
+ if (result.changes === 0) return res.status(400).json({ error: 'insufficient_coins' });
} else {
db.prepare('UPDATE users SET pet_bg=? WHERE id=?').run(id, req.user.id);
}
diff --git a/backend/src/controllers/shopController.js b/backend/src/controllers/shopController.js
index 6e639ec..3b4ff20 100644
--- a/backend/src/controllers/shopController.js
+++ b/backend/src/controllers/shopController.js
@@ -30,14 +30,13 @@ function purchaseItem(req, res) {
const alreadyOwned = db.prepare('SELECT 1 FROM user_purchases WHERE user_id = ? AND item_id = ?').get(userId, itemId);
if (alreadyOwned) return res.status(400).json({ error: 'Вы уже купили этот предмет' });
- // Atomic: check balance + deduct + insert purchase in one transaction
+ // Atomic: conditional UPDATE (race-safe even under concurrent purchases)
const doPurchase = db.transaction(() => {
- const user = db.prepare('SELECT coins FROM users WHERE id = ?').get(userId);
- if (!user || (user.coins || 0) < item.price) return { err: 'Недостаточно монет' };
-
- db.prepare('UPDATE users SET coins = coins - ? WHERE id = ?').run(item.price, userId);
+ const upd = db.prepare(
+ 'UPDATE users SET coins = coins - ? WHERE id = ? AND coins >= ?'
+ ).run(item.price, userId, item.price);
+ if (upd.changes === 0) return { err: 'Недостаточно монет' };
db.prepare('INSERT INTO user_purchases (user_id, item_id) VALUES (?, ?)').run(userId, itemId);
-
const updated = db.prepare('SELECT coins FROM users WHERE id = ?').get(userId);
return { coins: (updated && updated.coins) || 0 };
});
@@ -166,10 +165,14 @@ function adminDeleteItem(req, res) {
}
/* POST /api/shop/admin/award-coins — award coins to user */
+const SHOP_AWARD_MAX = 1_000_000;
function adminAwardCoins(req, res) {
const { userId, amount, reason } = req.body;
- if (!userId || !amount || amount < 0) return res.status(400).json({ error: 'userId and positive amount required' });
- db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(amount, userId);
+ const amt = Number(amount);
+ if (!userId || !Number.isFinite(amt) || amt <= 0 || amt > SHOP_AWARD_MAX)
+ return res.status(400).json({ error: `userId and amount (1..${SHOP_AWARD_MAX}) required` });
+ const result = db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(amt, userId);
+ if (result.changes === 0) return res.status(404).json({ error: 'User not found' });
const user = db.prepare('SELECT coins FROM users WHERE id = ?').get(userId);
res.json({ ok: true, coins: user?.coins || 0 });
}
diff --git a/backend/src/db/db.js b/backend/src/db/db.js
index 953a7cb..6a600b6 100644
--- a/backend/src/db/db.js
+++ b/backend/src/db/db.js
@@ -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.
diff --git a/backend/src/db/migrate.js b/backend/src/db/migrate.js
index 9ad506a..c61a094 100644
--- a/backend/src/db/migrate.js
+++ b/backend/src/db/migrate.js
@@ -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 ──────────────────────────────────────────────── */
diff --git a/backend/src/middleware/rateLimit.js b/backend/src/middleware/rateLimit.js
index 926615b..2c65672 100644
--- a/backend/src/middleware/rateLimit.js
+++ b/backend/src/middleware/rateLimit.js
@@ -11,7 +11,7 @@ setInterval(() => {
}
}, 5 * 60 * 1000).unref();
-module.exports = function rateLimit({ windowMs = 60_000, max = 10, message = 'Too many requests, please try again later' } = {}) {
+module.exports = function rateLimit({ windowMs = 60_000, max = 10, message = 'Too many requests, please try again later', byUser = false } = {}) {
// Skip rate limiting in test environment
if (process.env.NODE_ENV === 'test') return (_req, _res, next) => next();
@@ -20,7 +20,11 @@ module.exports = function rateLimit({ windowMs = 60_000, max = 10, message = 'To
_allStores.add(store);
return (req, res, next) => {
- const key = req.ip || req.socket?.remoteAddress || 'unknown';
+ // Per-user key (when authenticated and byUser=true) avoids penalising users who share a NAT;
+ // otherwise fall back to IP. trust proxy is set in server.js so req.ip honors X-Forwarded-For.
+ const key = (byUser && req.user?.id != null)
+ ? `u:${req.user.id}`
+ : (req.ip || req.socket?.remoteAddress || 'unknown');
const now = Date.now();
let entry = store.get(key);
diff --git a/backend/src/routes/classroom.js b/backend/src/routes/classroom.js
index 4c4df8a..060f383 100644
--- a/backend/src/routes/classroom.js
+++ b/backend/src/routes/classroom.js
@@ -27,7 +27,9 @@ const chatUpload = multer({
const teacher = [authMiddleware, requireRole('teacher', 'admin')];
const auth = [authMiddleware];
-const chatLimiter = rateLimit({ windowMs: 5_000, max: 5, message: 'Слишком много сообщений, подождите' });
+const chatLimiter = rateLimit({ windowMs: 5_000, max: 5, message: 'Слишком много сообщений, подождите', byUser: true });
+const reactionLimiter = rateLimit({ windowMs: 5_000, max: 15, message: 'Слишком много реакций, подождите', byUser: true });
+const handLimiter = rateLimit({ windowMs: 5_000, max: 5, message: 'Не так часто', byUser: true });
// Template library — MUST be before /:id to avoid shadowing
router.get('/admin/active', ...teacher, c.adminGetActiveSessions);
@@ -59,7 +61,7 @@ router.get('/:id/attendance', ...teacher, c.getAttendance);
router.post('/:id/chat', ...auth, chatLimiter, c.sendChat);
router.get('/:id/chat', ...auth, c.getChat);
router.post('/:id/chat/upload', ...auth, chatUpload.single('file'), c.uploadChatAttachment);
-router.post('/:id/chat/:msgId/react', ...auth, c.reactToMessage);
+router.post('/:id/chat/:msgId/react', ...auth, reactionLimiter, c.reactToMessage);
// WebRTC signaling
router.post('/:id/signal', ...auth, c.signal);
@@ -82,8 +84,8 @@ router.post('/:id/pages/:pageNum/duplicate', ...teacher, c.duplicatePage);
router.delete('/:id/pages/:pageNum', ...teacher, c.deletePage);
// Hand raise
-router.post('/:id/hand', ...auth, c.raiseHand);
-router.delete('/:id/hand', ...auth, c.lowerHand);
+router.post('/:id/hand', ...auth, handLimiter, c.raiseHand);
+router.delete('/:id/hand', ...auth, handLimiter, c.lowerHand);
router.get('/:id/hands', ...auth, c.getHands);
// Whiteboard: clear page
diff --git a/backend/src/server.js b/backend/src/server.js
index 81231ae..0ac084c 100644
--- a/backend/src/server.js
+++ b/backend/src/server.js
@@ -218,6 +218,23 @@ const _startTime = Date.now();
const _pkg = require('../package.json');
const _db = require('./db/db');
+/* GET /api/ice-servers — WebRTC ICE config (STUN + optional TURN from env)
+ Required for clients behind symmetric NAT/CGNAT (school/corporate networks). */
+app.get('/api/ice-servers', (req, res) => {
+ const iceServers = [
+ { urls: 'stun:stun.l.google.com:19302' },
+ { urls: 'stun:stun1.l.google.com:19302' },
+ ];
+ if (config.TURN_URL && config.TURN_USER && config.TURN_PASS) {
+ iceServers.push({
+ urls: config.TURN_URL,
+ username: config.TURN_USER,
+ credential: config.TURN_PASS,
+ });
+ }
+ res.json({ iceServers });
+});
+
app.get('/api/health', (req, res) => {
let dbStatus = 'ok';
let dbLatencyMs = null;
@@ -319,6 +336,8 @@ require('./ws-server').attach(server);
/* ── Graceful shutdown ── */
function shutdown(signal) {
logger.info(`${signal} received — shutting down gracefully`);
+ // Close WebSocket connections first so HTTP server can stop accepting new requests cleanly
+ try { require('./ws-server').closeAll(); } catch (e) { logger.error('ws close error', { err: e.message }); }
server.close(() => {
try {
const _shutDb = require('./db/db');
diff --git a/backend/src/ws-server.js b/backend/src/ws-server.js
index 2d6b46e..43ab4c2 100644
--- a/backend/src/ws-server.js
+++ b/backend/src/ws-server.js
@@ -274,8 +274,10 @@ function _handleMessage(ws, msg) {
}
/* ── WebSocket server ──────────────────────────────────────────────────── */
+let _wss = null;
function attach(httpServer) {
const wss = new WebSocketServer({ server: httpServer, path: '/ws' });
+ _wss = wss;
wss.on('connection', (ws, req) => {
/* ── Auth ── */
@@ -328,4 +330,19 @@ function attach(httpServer) {
return wss;
}
-module.exports = { attach, broadcastToSession, emitToUser, invalidateSession: _invalidateSession };
+function closeAll() {
+ if (!_wss) return;
+ for (const ws of _wss.clients) {
+ try { ws.close(1001, 'Server shutting down'); } catch {}
+ }
+ try { _wss.close(); } catch {}
+}
+
+module.exports = {
+ attach,
+ broadcastToSession,
+ emitToUser,
+ invalidateSession: _invalidateSession,
+ invalidateDrawCache: _invalidateDrawCache,
+ closeAll,
+};
diff --git a/frontend/admin.html b/frontend/admin.html
index c058c64..3576b5b 100644
--- a/frontend/admin.html
+++ b/frontend/admin.html
@@ -2605,7 +2605,7 @@
try {
const { user: u, sessions } = await LS.adminGetUserSessions(uid);
activeUserRole = u.role;
- document.getElementById('up-name').innerHTML = u.name + (u.is_banned ? ' ' : '');
+ document.getElementById('up-name').innerHTML = LS.esc(u.name) + (u.is_banned ? ' ' : '');
document.getElementById('up-email').textContent = u.email;
// Sync button in case role changed after panel was opened
if (isAdmin) {
diff --git a/frontend/js/classroom-rtc.js b/frontend/js/classroom-rtc.js
index 80f60b9..ba8ffa3 100644
--- a/frontend/js/classroom-rtc.js
+++ b/frontend/js/classroom-rtc.js
@@ -35,12 +35,18 @@ class ClassroomRTC {
this._muted = false;
this._vadTimers = new Map(); // uid → {ctx, timer} for VAD
+ this._iceServers = null; // populated lazily before first peer
+
+ // Pre-fetch ICE servers in background so first peer creation has them.
+ this._fetchIceServers().then(s => { this._iceServers = s; }).catch(() => {});
}
- /* ── Audio ───────────────────────────────────────────��───────────────── */
+ /* ── Audio ────────────────────────────────────────────��──────────────── */
async startAudio() {
try {
+ // Make sure ICE servers are loaded before we accept incoming connections
+ if (!this._iceServers) this._iceServers = await this._fetchIceServers();
this._localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
this._localStream.getAudioTracks().forEach(t => { t.enabled = !this._muted; });
this._startVAD(this._uid, this._localStream);
@@ -277,8 +283,31 @@ class ClassroomRTC {
_getPeer(uid) { return this._peers.get(uid) || null; }
+ // Cached promise for ICE servers (fetched once per page load).
+ // Server returns STUN + optional TURN from env (TURN_URL/USER/PASS).
+ static _iceServersPromise = null;
+ _fetchIceServers() {
+ if (!ClassroomRTC._iceServersPromise) {
+ ClassroomRTC._iceServersPromise = fetch('/api/ice-servers', {
+ headers: { Authorization: 'Bearer ' + (localStorage.getItem('ls_token') || '') },
+ })
+ .then(r => r.ok ? r.json() : null)
+ .then(d => d?.iceServers || [
+ { urls: 'stun:stun.l.google.com:19302' },
+ { urls: 'stun:stun1.l.google.com:19302' },
+ ])
+ .catch(() => [
+ { urls: 'stun:stun.l.google.com:19302' },
+ { urls: 'stun:stun1.l.google.com:19302' },
+ ]);
+ }
+ return ClassroomRTC._iceServersPromise;
+ }
+
_createPeer(uid) {
- const ICE = { iceServers: [
+ // Use cached server-side ICE config if loaded; otherwise fall back to STUN-only synchronously.
+ // (RTCPeerConnection constructor needs config at create-time, so we use whatever is ready.)
+ const ICE = { iceServers: this._iceServers || [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
]};
diff --git a/frontend/js/whiteboard.js b/frontend/js/whiteboard.js
index 093a862..72ca9b1 100644
--- a/frontend/js/whiteboard.js
+++ b/frontend/js/whiteboard.js
@@ -2073,17 +2073,31 @@ class Whiteboard {
/* ── live stroke API (remote preview) ──────────────────────────────── */
+ // TTL for live (preview) strokes — if remote user crashes mid-stroke, ghost preview disappears.
+ // A normal stroke gets refreshed every ~50ms, so 1500ms is generous.
+ _LIVE_STROKE_TTL_MS = 1500;
+
setLiveStroke(liveId, tool, data, userName, color) {
- this._liveStrokes.set(liveId, { tool, data, userName, color });
+ const prev = this._liveStrokes.get(liveId);
+ if (prev?._ttlTimer) clearTimeout(prev._ttlTimer);
+ const _ttlTimer = setTimeout(() => {
+ if (this._liveStrokes.delete(liveId)) this.render();
+ }, this._LIVE_STROKE_TTL_MS);
+ this._liveStrokes.set(liveId, { tool, data, userName, color, _ttlTimer });
this.render();
}
removeLiveStroke(liveId) {
+ const cur = this._liveStrokes.get(liveId);
+ if (cur?._ttlTimer) clearTimeout(cur._ttlTimer);
if (this._liveStrokes.delete(liveId)) this.render();
}
clearAllLiveStrokes() {
if (this._liveStrokes.size === 0) return;
+ for (const [, ls] of this._liveStrokes) {
+ if (ls?._ttlTimer) clearTimeout(ls._ttlTimer);
+ }
this._liveStrokes.clear();
this.render();
}
diff --git a/frontend/login.html b/frontend/login.html
index e939faa..1222709 100644
--- a/frontend/login.html
+++ b/frontend/login.html
@@ -496,7 +496,7 @@
-
+
diff --git a/frontend/red-book-ecosystem.html b/frontend/red-book-ecosystem.html
index 0080cc8..3638c6e 100644
--- a/frontend/red-book-ecosystem.html
+++ b/frontend/red-book-ecosystem.html
@@ -486,13 +486,16 @@ function selectNode(id) {
const preys = graph.links.filter(l => l.source === id).map(l => graph.nodes.find(n => n.id === l.target)?.name_ru).filter(Boolean);
const predators = graph.links.filter(l => l.target === id).map(l => graph.nodes.find(n => n.id === l.source)?.name_ru).filter(Boolean);
document.getElementById('node-info').style.display = 'block';
- document.getElementById('ni-name').innerHTML = `${node.icon || ''} ${node.name_ru}`;
+ const ICON_DEFAULT = '';
+ document.getElementById('ni-name').innerHTML = `${node.icon ? LS.esc(node.icon) : ICON_DEFAULT} ${LS.esc(node.name_ru)}`;
document.getElementById('ni-lat').textContent = node.name_lat || '';
+ const safeCat = LS.esc(node.category || '');
+ const catColor = CAT_HEX[node.category] || '#22c55e';
document.getElementById('ni-stat').innerHTML =
- `${node.category}` +
- (node.description ? `
${node.description.slice(0, 100)}…` : '') +
- (preys.length ? `
Охотится: ${preys.slice(0,3).join(', ')}` : '') +
- (predators.length? `
Хищники: ${predators.slice(0,3).join(', ')}` : '');
+ `${safeCat}` +
+ (node.description ? `
${LS.esc(node.description.slice(0, 100))}…` : '') +
+ (preys.length ? `
Охотится: ${LS.esc(preys.slice(0,3).join(', '))}` : '') +
+ (predators.length? `
Хищники: ${LS.esc(predators.slice(0,3).join(', '))}` : '');
// Show slider
document.getElementById('slider-wrap').style.display = 'block';
diff --git a/js/api.js b/js/api.js
index 3f4afc6..d250428 100644
--- a/js/api.js
+++ b/js/api.js
@@ -81,7 +81,22 @@ async function startSession(subject_slug, mode = 'exam', count = 25, topic_id =
}
async function sendAnswer(session_id, question_id, option_id, time_spent_sec, answer_text, chosen_options) {
- return req('POST', `/sessions/${session_id}/answer`, { question_id, option_id, time_spent_sec, answer_text, chosen_options });
+ // Retry up to 3x on network failures (loss of answer is unacceptable mid-test).
+ // Server is idempotent: same (session, question) overwrites; safe to retry.
+ // Don't retry on 4xx (validation/auth errors).
+ const body = { question_id, option_id, time_spent_sec, answer_text, chosen_options };
+ let lastErr;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ return await req('POST', `/sessions/${session_id}/answer`, body);
+ } catch (e) {
+ lastErr = e;
+ const code = e?.status || 0;
+ if (code >= 400 && code < 500) throw e; // permanent error — abort
+ await new Promise(r => setTimeout(r, 300 * (attempt + 1) ** 2)); // 300, 1200, 2700ms
+ }
+ }
+ throw lastErr;
}
async function finishSession(session_id) {