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:
@@ -6,3 +6,10 @@ JWT_EXPIRES_IN=7d
|
|||||||
|
|
||||||
# CORS — адрес фронтенда
|
# CORS — адрес фронтенда
|
||||||
CLIENT_ORIGIN=http://localhost:5500
|
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
|
||||||
|
|||||||
@@ -59,6 +59,10 @@ module.exports = Object.freeze({
|
|||||||
/* paths */
|
/* paths */
|
||||||
DB_PATH: _optional('DB_PATH', path.join(__dirname, '../data/learnspace.db')),
|
DB_PATH: _optional('DB_PATH', path.join(__dirname, '../data/learnspace.db')),
|
||||||
UPLOADS_DIR: _optional('UPLOADS_DIR', path.join(__dirname, '../uploads')),
|
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 */
|
/* constants */
|
||||||
BCRYPT_ROUNDS: 12,
|
BCRYPT_ROUNDS: 12,
|
||||||
MAX_FILE_SIZE: 50 * 1024 * 1024,
|
MAX_FILE_SIZE: 50 * 1024 * 1024,
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ async function register(req, res, next) {
|
|||||||
|
|
||||||
if (!email || !password || !name)
|
if (!email || !password || !name)
|
||||||
return res.status(400).json({ error: 'email, password and name are required' });
|
return res.status(400).json({ error: 'email, password and name are required' });
|
||||||
if (password.length < 6)
|
if (password.length < 8)
|
||||||
return res.status(400).json({ error: 'Password must be at least 6 characters' });
|
return res.status(400).json({ error: 'Password must be at least 8 characters' });
|
||||||
|
|
||||||
if (db.prepare('SELECT id FROM users WHERE email = ?').get(email))
|
if (db.prepare('SELECT id FROM users WHERE email = ?').get(email))
|
||||||
return res.status(409).json({ error: 'Email already registered' });
|
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: 'Текущий пароль обязателен' });
|
if (!currentPassword) return res.status(400).json({ error: 'Текущий пароль обязателен' });
|
||||||
const valid = await bcrypt.compare(currentPassword, user.password_hash);
|
const valid = await bcrypt.compare(currentPassword, user.password_hash);
|
||||||
if (!valid) return res.status(401).json({ error: 'Неверный текущий пароль' });
|
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);
|
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);
|
db.prepare('UPDATE users SET password_hash = ?, token_version = token_version + 1 WHERE id = ?').run(hash, user.id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -420,6 +420,10 @@ function myClasses(req, res) {
|
|||||||
|
|
||||||
/* ── GET /api/classes/:id/announcements ─────────────────────────────────── */
|
/* ── GET /api/classes/:id/announcements ─────────────────────────────────── */
|
||||||
function getAnnouncements(req, res) {
|
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(`
|
const announcements = db.prepare(`
|
||||||
SELECT a.id, a.text, a.created_at, u.name AS author_name
|
SELECT a.id, a.text, a.created_at, u.name AS author_name
|
||||||
FROM announcements a
|
FROM announcements a
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ const path = require('path');
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const { getOnlineUserIds } = require('../sse');
|
const { getOnlineUserIds } = require('../sse');
|
||||||
const { emitToUser, invalidateSession } = require('../ws-server');
|
const { emitToUser, invalidateSession, invalidateDrawCache } = require('../ws-server');
|
||||||
|
|
||||||
/* ── chat attachment uploads dir ─────────────────────────────────────── */
|
/* ── chat attachment uploads dir ─────────────────────────────────────── */
|
||||||
const CHAT_UPLOADS_DIR = path.join(__dirname, '../../uploads/chat');
|
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))
|
if (!hasAccess(session, req.user.id, req.user.role))
|
||||||
return res.status(403).json({ error: 'Нет доступа' });
|
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
|
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=? 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').all(sessionId, pageNum);
|
: 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 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 pageRow = db.prepare('SELECT template, name FROM classroom_pages WHERE session_id=? AND page_num=?').get(sessionId, pageNum);
|
||||||
const template = pageRow?.template || 'blank';
|
const template = pageRow?.template || 'blank';
|
||||||
const name = pageRow?.name || null;
|
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 */
|
/* PATCH /api/classroom/:id/strokes/:strokeId — update image position/size */
|
||||||
@@ -870,6 +873,7 @@ function allowDraw(req, res) {
|
|||||||
db.prepare(
|
db.prepare(
|
||||||
'INSERT OR IGNORE INTO classroom_draw_permissions (session_id, user_id) VALUES (?,?)'
|
'INSERT OR IGNORE INTO classroom_draw_permissions (session_id, user_id) VALUES (?,?)'
|
||||||
).run(sessionId, targetId);
|
).run(sessionId, targetId);
|
||||||
|
invalidateDrawCache(sessionId, targetId);
|
||||||
|
|
||||||
emitToUser(targetId, { type: 'classroom_draw_permitted', sessionId });
|
emitToUser(targetId, { type: 'classroom_draw_permitted', sessionId });
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
@@ -887,6 +891,7 @@ function revokeDraw(req, res) {
|
|||||||
db.prepare(
|
db.prepare(
|
||||||
'DELETE FROM classroom_draw_permissions WHERE session_id=? AND user_id=?'
|
'DELETE FROM classroom_draw_permissions WHERE session_id=? AND user_id=?'
|
||||||
).run(sessionId, targetId);
|
).run(sessionId, targetId);
|
||||||
|
invalidateDrawCache(sessionId, targetId);
|
||||||
|
|
||||||
emitToUser(targetId, { type: 'classroom_draw_revoked', sessionId });
|
emitToUser(targetId, { type: 'classroom_draw_revoked', sessionId });
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
|
|||||||
@@ -788,13 +788,18 @@ function getXPHistory(req, res) {
|
|||||||
═══════════════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
/* POST /api/gamification/admin/award — award XP or coins to user */
|
/* POST /api/gamification/admin/award — award XP or coins to user */
|
||||||
|
const ADMIN_AWARD_MAX = 1_000_000;
|
||||||
function adminAward(req, res) {
|
function adminAward(req, res) {
|
||||||
const { userId, xp, coins, reason } = req.body;
|
const { userId, xp, coins, reason } = req.body;
|
||||||
if (!userId) return res.status(400).json({ error: 'userId required' });
|
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);
|
const user = stmts.checkUserById.get(userId);
|
||||||
if (!user) return res.status(404).json({ error: 'User not found' });
|
if (!user) return res.status(404).json({ error: 'User not found' });
|
||||||
if (xp && xp > 0) awardXP(userId, xp, reason || 'Admin award');
|
if (xpNum > 0) awardXP(userId, xpNum, reason || 'Admin award');
|
||||||
if (coins && coins > 0) awardCoins(userId, coins, reason || 'Admin award');
|
if (coinsNum > 0) awardCoins(userId, coinsNum, reason || 'Admin award');
|
||||||
const updated = stmts.getUserGamInfo.get(userId);
|
const updated = stmts.getUserGamInfo.get(userId);
|
||||||
res.json({ ok: true, ...updated });
|
res.json({ ok: true, ...updated });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ function setQuestion(req, res) {
|
|||||||
if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
|
if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
|
||||||
return res.status(403).json({ error: 'Forbidden' });
|
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=?`)
|
db.prepare(`UPDATE live_sessions SET question_id=?, status='active', show_results=0 WHERE id=?`)
|
||||||
.run(question_id, liveId);
|
.run(question_id, liveId);
|
||||||
|
|
||||||
@@ -67,9 +67,11 @@ function answer(req, res) {
|
|||||||
).get(live.class_id, userId);
|
).get(live.class_id, userId);
|
||||||
if (!isMember) return res.status(403).json({ error: 'Forbidden' });
|
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(
|
const existing = db.prepare(
|
||||||
'SELECT id FROM live_answers WHERE live_session_id=? AND user_id=?'
|
'SELECT id FROM live_answers WHERE live_session_id=? AND user_id=? AND question_id=?'
|
||||||
).get(liveId, userId);
|
).get(liveId, userId, live.question_id);
|
||||||
if (existing) return res.status(409).json({ error: 'Уже отвечено' });
|
if (existing) return res.status(409).json({ error: 'Уже отвечено' });
|
||||||
|
|
||||||
let is_correct = null;
|
let is_correct = null;
|
||||||
@@ -80,14 +82,20 @@ function answer(req, res) {
|
|||||||
is_correct = opt ? opt.is_correct : 0;
|
is_correct = opt ? opt.is_correct : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.prepare(
|
// Atomic INSERT — race-safe via UNIQUE(session, user, question_id)
|
||||||
`INSERT INTO live_answers (live_session_id, user_id, option_id, answer_text, is_correct)
|
try {
|
||||||
VALUES (?,?,?,?,?)`
|
db.prepare(
|
||||||
).run(liveId, userId, option_id || null, answer_text || null, is_correct);
|
`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(
|
const { c: count } = db.prepare(
|
||||||
'SELECT COUNT(*) AS c FROM live_answers WHERE live_session_id=?'
|
'SELECT COUNT(*) AS c FROM live_answers WHERE live_session_id=? AND question_id=?'
|
||||||
).get(liveId);
|
).get(liveId, live.question_id);
|
||||||
emit(live.teacher_id, { type: 'live_answer_count', liveId, count });
|
emit(live.teacher_id, { type: 'live_answer_count', liveId, count });
|
||||||
|
|
||||||
res.json({ ok: true, is_correct });
|
res.json({ ok: true, is_correct });
|
||||||
@@ -111,15 +119,15 @@ function results(req, res) {
|
|||||||
SELECT o.id, o.text, o.is_correct,
|
SELECT o.id, o.text, o.is_correct,
|
||||||
COUNT(la.id) AS chosen_count
|
COUNT(la.id) AS chosen_count
|
||||||
FROM options o
|
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=?
|
WHERE o.question_id=?
|
||||||
GROUP BY o.id ORDER BY o.order_index
|
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(
|
const stats = db.prepare(
|
||||||
`SELECT COUNT(*) AS total, SUM(is_correct) AS correct
|
`SELECT COUNT(*) AS total, SUM(is_correct) AS correct
|
||||||
FROM live_answers WHERE live_session_id=?`
|
FROM live_answers WHERE live_session_id=? AND question_id=?`
|
||||||
).get(liveId);
|
).get(liveId, live.question_id);
|
||||||
|
|
||||||
db.prepare('UPDATE live_sessions SET show_results=1 WHERE id=?').run(liveId);
|
db.prepare('UPDATE live_sessions SET show_results=1 WHERE id=?').run(liveId);
|
||||||
emitToClass(live.class_id, { type: 'live_results', liveId, question, options, stats });
|
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'
|
'SELECT id, text, order_index FROM options WHERE question_id=? ORDER BY order_index'
|
||||||
).all(live.question_id);
|
).all(live.question_id);
|
||||||
myAnswer = db.prepare(
|
myAnswer = db.prepare(
|
||||||
'SELECT option_id, is_correct FROM live_answers WHERE live_session_id=? AND 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);
|
).get(live.id, req.user.id, live.question_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ active: true, live, question, options, myAnswer, showResults: live.show_results });
|
res.json({ active: true, live, question, options, myAnswer, showResults: live.show_results });
|
||||||
|
|||||||
@@ -234,18 +234,11 @@ function buyBg(req, res) {
|
|||||||
if (!user) return res.status(404).json({ error: 'not found' });
|
if (!user) return res.status(404).json({ error: 'not found' });
|
||||||
const owned = _parseOwned(user.pet_bg_owned);
|
const owned = _parseOwned(user.pet_bg_owned);
|
||||||
if (!owned.includes(id)) {
|
if (!owned.includes(id)) {
|
||||||
if ((user.coins || 0) < item.price) return res.status(400).json({ error: 'insufficient_coins' });
|
// Atomic conditional UPDATE — race-safe even under concurrent purchase attempts
|
||||||
const buy = db.transaction(() => {
|
const result = db.prepare(
|
||||||
// Re-check balance inside transaction to prevent race
|
'UPDATE users SET coins = coins - ?, pet_bg_owned = ?, pet_bg = ? WHERE id = ? AND coins >= ?'
|
||||||
const fresh = db.prepare('SELECT coins FROM users WHERE id=?').get(req.user.id);
|
).run(item.price, JSON.stringify([...owned, id]), id, req.user.id, item.price);
|
||||||
if ((fresh.coins || 0) < item.price) throw new Error('insufficient_coins');
|
if (result.changes === 0) return res.status(400).json({ 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;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
db.prepare('UPDATE users SET pet_bg=? WHERE id=?').run(id, req.user.id);
|
db.prepare('UPDATE users SET pet_bg=? WHERE id=?').run(id, req.user.id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
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: 'Вы уже купили этот предмет' });
|
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 doPurchase = db.transaction(() => {
|
||||||
const user = db.prepare('SELECT coins FROM users WHERE id = ?').get(userId);
|
const upd = db.prepare(
|
||||||
if (!user || (user.coins || 0) < item.price) return { err: 'Недостаточно монет' };
|
'UPDATE users SET coins = coins - ? WHERE id = ? AND coins >= ?'
|
||||||
|
).run(item.price, userId, item.price);
|
||||||
db.prepare('UPDATE users SET coins = coins - ? WHERE id = ?').run(item.price, userId);
|
if (upd.changes === 0) return { err: 'Недостаточно монет' };
|
||||||
db.prepare('INSERT INTO user_purchases (user_id, item_id) VALUES (?, ?)').run(userId, itemId);
|
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);
|
const updated = db.prepare('SELECT coins FROM users WHERE id = ?').get(userId);
|
||||||
return { coins: (updated && updated.coins) || 0 };
|
return { coins: (updated && updated.coins) || 0 };
|
||||||
});
|
});
|
||||||
@@ -166,10 +165,14 @@ function adminDeleteItem(req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* POST /api/shop/admin/award-coins — award coins to user */
|
/* POST /api/shop/admin/award-coins — award coins to user */
|
||||||
|
const SHOP_AWARD_MAX = 1_000_000;
|
||||||
function adminAwardCoins(req, res) {
|
function adminAwardCoins(req, res) {
|
||||||
const { userId, amount, reason } = req.body;
|
const { userId, amount, reason } = req.body;
|
||||||
if (!userId || !amount || amount < 0) return res.status(400).json({ error: 'userId and positive amount required' });
|
const amt = Number(amount);
|
||||||
db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(amount, userId);
|
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);
|
const user = db.prepare('SELECT coins FROM users WHERE id = ?').get(userId);
|
||||||
res.json({ ok: true, coins: user?.coins || 0 });
|
res.json({ ok: true, coins: user?.coins || 0 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,10 @@ if (!fs.existsSync(dbPath) && fs.existsSync(oldPath)) {
|
|||||||
const db = new DatabaseSync(dbPath);
|
const db = new DatabaseSync(dbPath);
|
||||||
|
|
||||||
db.exec('PRAGMA journal_mode = WAL');
|
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 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.
|
* 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_sessions_class ON live_sessions(class_id, status);
|
||||||
CREATE INDEX IF NOT EXISTS idx_live_answers_session ON live_answers(live_session_id);
|
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');
|
console.log('✓ Live quiz tables ready');
|
||||||
|
|
||||||
/* ── Submission audit log ──────────────────────────────────────────────── */
|
/* ── Submission audit log ──────────────────────────────────────────────── */
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ setInterval(() => {
|
|||||||
}
|
}
|
||||||
}, 5 * 60 * 1000).unref();
|
}, 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
|
// Skip rate limiting in test environment
|
||||||
if (process.env.NODE_ENV === 'test') return (_req, _res, next) => next();
|
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);
|
_allStores.add(store);
|
||||||
|
|
||||||
return (req, res, next) => {
|
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();
|
const now = Date.now();
|
||||||
let entry = store.get(key);
|
let entry = store.get(key);
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,9 @@ const chatUpload = multer({
|
|||||||
const teacher = [authMiddleware, requireRole('teacher', 'admin')];
|
const teacher = [authMiddleware, requireRole('teacher', 'admin')];
|
||||||
const auth = [authMiddleware];
|
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
|
// Template library — MUST be before /:id to avoid shadowing
|
||||||
router.get('/admin/active', ...teacher, c.adminGetActiveSessions);
|
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.post('/:id/chat', ...auth, chatLimiter, c.sendChat);
|
||||||
router.get('/:id/chat', ...auth, c.getChat);
|
router.get('/:id/chat', ...auth, c.getChat);
|
||||||
router.post('/:id/chat/upload', ...auth, chatUpload.single('file'), c.uploadChatAttachment);
|
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
|
// WebRTC signaling
|
||||||
router.post('/:id/signal', ...auth, c.signal);
|
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);
|
router.delete('/:id/pages/:pageNum', ...teacher, c.deletePage);
|
||||||
|
|
||||||
// Hand raise
|
// Hand raise
|
||||||
router.post('/:id/hand', ...auth, c.raiseHand);
|
router.post('/:id/hand', ...auth, handLimiter, c.raiseHand);
|
||||||
router.delete('/:id/hand', ...auth, c.lowerHand);
|
router.delete('/:id/hand', ...auth, handLimiter, c.lowerHand);
|
||||||
router.get('/:id/hands', ...auth, c.getHands);
|
router.get('/:id/hands', ...auth, c.getHands);
|
||||||
|
|
||||||
// Whiteboard: clear page
|
// Whiteboard: clear page
|
||||||
|
|||||||
@@ -218,6 +218,23 @@ const _startTime = Date.now();
|
|||||||
const _pkg = require('../package.json');
|
const _pkg = require('../package.json');
|
||||||
const _db = require('./db/db');
|
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) => {
|
app.get('/api/health', (req, res) => {
|
||||||
let dbStatus = 'ok';
|
let dbStatus = 'ok';
|
||||||
let dbLatencyMs = null;
|
let dbLatencyMs = null;
|
||||||
@@ -319,6 +336,8 @@ require('./ws-server').attach(server);
|
|||||||
/* ── Graceful shutdown ── */
|
/* ── Graceful shutdown ── */
|
||||||
function shutdown(signal) {
|
function shutdown(signal) {
|
||||||
logger.info(`${signal} received — shutting down gracefully`);
|
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(() => {
|
server.close(() => {
|
||||||
try {
|
try {
|
||||||
const _shutDb = require('./db/db');
|
const _shutDb = require('./db/db');
|
||||||
|
|||||||
@@ -274,8 +274,10 @@ function _handleMessage(ws, msg) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ── WebSocket server ──────────────────────────────────────────────────── */
|
/* ── WebSocket server ──────────────────────────────────────────────────── */
|
||||||
|
let _wss = null;
|
||||||
function attach(httpServer) {
|
function attach(httpServer) {
|
||||||
const wss = new WebSocketServer({ server: httpServer, path: '/ws' });
|
const wss = new WebSocketServer({ server: httpServer, path: '/ws' });
|
||||||
|
_wss = wss;
|
||||||
|
|
||||||
wss.on('connection', (ws, req) => {
|
wss.on('connection', (ws, req) => {
|
||||||
/* ── Auth ── */
|
/* ── Auth ── */
|
||||||
@@ -328,4 +330,19 @@ function attach(httpServer) {
|
|||||||
return wss;
|
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,
|
||||||
|
};
|
||||||
|
|||||||
+1
-1
@@ -2605,7 +2605,7 @@
|
|||||||
try {
|
try {
|
||||||
const { user: u, sessions } = await LS.adminGetUserSessions(uid);
|
const { user: u, sessions } = await LS.adminGetUserSessions(uid);
|
||||||
activeUserRole = u.role;
|
activeUserRole = u.role;
|
||||||
document.getElementById('up-name').innerHTML = u.name + (u.is_banned ? ' <svg class="ic" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>' : '');
|
document.getElementById('up-name').innerHTML = LS.esc(u.name) + (u.is_banned ? ' <svg class="ic" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>' : '');
|
||||||
document.getElementById('up-email').textContent = u.email;
|
document.getElementById('up-email').textContent = u.email;
|
||||||
// Sync button in case role changed after panel was opened
|
// Sync button in case role changed after panel was opened
|
||||||
if (isAdmin) {
|
if (isAdmin) {
|
||||||
|
|||||||
@@ -35,12 +35,18 @@ class ClassroomRTC {
|
|||||||
this._muted = false;
|
this._muted = false;
|
||||||
|
|
||||||
this._vadTimers = new Map(); // uid → {ctx, timer} for VAD
|
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() {
|
async startAudio() {
|
||||||
try {
|
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 = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
|
||||||
this._localStream.getAudioTracks().forEach(t => { t.enabled = !this._muted; });
|
this._localStream.getAudioTracks().forEach(t => { t.enabled = !this._muted; });
|
||||||
this._startVAD(this._uid, this._localStream);
|
this._startVAD(this._uid, this._localStream);
|
||||||
@@ -277,8 +283,31 @@ class ClassroomRTC {
|
|||||||
|
|
||||||
_getPeer(uid) { return this._peers.get(uid) || null; }
|
_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) {
|
_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:stun.l.google.com:19302' },
|
||||||
{ urls: 'stun:stun1.l.google.com:19302' },
|
{ urls: 'stun:stun1.l.google.com:19302' },
|
||||||
]};
|
]};
|
||||||
|
|||||||
@@ -2073,17 +2073,31 @@ class Whiteboard {
|
|||||||
|
|
||||||
/* ── live stroke API (remote preview) ──────────────────────────────── */
|
/* ── 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) {
|
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();
|
this.render();
|
||||||
}
|
}
|
||||||
|
|
||||||
removeLiveStroke(liveId) {
|
removeLiveStroke(liveId) {
|
||||||
|
const cur = this._liveStrokes.get(liveId);
|
||||||
|
if (cur?._ttlTimer) clearTimeout(cur._ttlTimer);
|
||||||
if (this._liveStrokes.delete(liveId)) this.render();
|
if (this._liveStrokes.delete(liveId)) this.render();
|
||||||
}
|
}
|
||||||
|
|
||||||
clearAllLiveStrokes() {
|
clearAllLiveStrokes() {
|
||||||
if (this._liveStrokes.size === 0) return;
|
if (this._liveStrokes.size === 0) return;
|
||||||
|
for (const [, ls] of this._liveStrokes) {
|
||||||
|
if (ls?._ttlTimer) clearTimeout(ls._ttlTimer);
|
||||||
|
}
|
||||||
this._liveStrokes.clear();
|
this._liveStrokes.clear();
|
||||||
this.render();
|
this.render();
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -496,7 +496,7 @@
|
|||||||
<span class="auth-input-icon">
|
<span class="auth-input-icon">
|
||||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
|
||||||
</span>
|
</span>
|
||||||
<input class="auth-input has-eye" type="password" id="reg-pass" name="password" placeholder="Минимум 6 символов" autocomplete="new-password" required minlength="6" />
|
<input class="auth-input has-eye" type="password" id="reg-pass" name="password" placeholder="Минимум 8 символов" autocomplete="new-password" required minlength="8" />
|
||||||
<button type="button" class="auth-eye" onclick="toggleEye('reg-pass', this)" aria-label="Показать пароль">
|
<button type="button" class="auth-eye" onclick="toggleEye('reg-pass', this)" aria-label="Показать пароль">
|
||||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -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 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);
|
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('node-info').style.display = 'block';
|
||||||
document.getElementById('ni-name').innerHTML = `${node.icon || '<svg class="ic" viewBox="0 0 24 24"><path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12"/></svg>'} ${node.name_ru}`;
|
const ICON_DEFAULT = '<svg class="ic" viewBox="0 0 24 24"><path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12"/></svg>';
|
||||||
|
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 || '';
|
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 =
|
document.getElementById('ni-stat').innerHTML =
|
||||||
`<span style="color:${CAT_HEX[node.category]||'#22c55e'};font-weight:700">${node.category}</span>` +
|
`<span style="color:${catColor};font-weight:700">${safeCat}</span>` +
|
||||||
(node.description ? `<br><span style="color:#a8d5b0;font-size:11px;line-height:1.5">${node.description.slice(0, 100)}…</span>` : '') +
|
(node.description ? `<br><span style="color:#a8d5b0;font-size:11px;line-height:1.5">${LS.esc(node.description.slice(0, 100))}…</span>` : '') +
|
||||||
(preys.length ? `<br><svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="currentColor" stroke="none"/></svg> Охотится: ${preys.slice(0,3).join(', ')}` : '') +
|
(preys.length ? `<br><svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="currentColor" stroke="none"/></svg> Охотится: ${LS.esc(preys.slice(0,3).join(', '))}` : '') +
|
||||||
(predators.length? `<br><svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="currentColor" stroke="none"/></svg> Хищники: ${predators.slice(0,3).join(', ')}` : '');
|
(predators.length? `<br><svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="currentColor" stroke="none"/></svg> Хищники: ${LS.esc(predators.slice(0,3).join(', '))}` : '');
|
||||||
|
|
||||||
// Show slider
|
// Show slider
|
||||||
document.getElementById('slider-wrap').style.display = 'block';
|
document.getElementById('slider-wrap').style.display = 'block';
|
||||||
|
|||||||
@@ -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) {
|
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) {
|
async function finishSession(session_id) {
|
||||||
|
|||||||
Reference in New Issue
Block a user