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:
+1
-1
@@ -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 ? ' <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;
|
||||
// Sync button in case role changed after panel was opened
|
||||
if (isAdmin) {
|
||||
|
||||
@@ -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' },
|
||||
]};
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
+1
-1
@@ -496,7 +496,7 @@
|
||||
<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>
|
||||
</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="Показать пароль">
|
||||
<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>
|
||||
|
||||
@@ -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 || '<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 || '';
|
||||
const safeCat = LS.esc(node.category || '');
|
||||
const catColor = CAT_HEX[node.category] || '#22c55e';
|
||||
document.getElementById('ni-stat').innerHTML =
|
||||
`<span style="color:${CAT_HEX[node.category]||'#22c55e'};font-weight:700">${node.category}</span>` +
|
||||
(node.description ? `<br><span style="color:#a8d5b0;font-size:11px;line-height:1.5">${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(', ')}` : '') +
|
||||
(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(', ')}` : '');
|
||||
`<span style="color:${catColor};font-weight:700">${safeCat}</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> Охотится: ${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> Хищники: ${LS.esc(predators.slice(0,3).join(', '))}` : '');
|
||||
|
||||
// Show slider
|
||||
document.getElementById('slider-wrap').style.display = 'block';
|
||||
|
||||
Reference in New Issue
Block a user