952a54f97c
## 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>
52 lines
1.9 KiB
JavaScript
52 lines
1.9 KiB
JavaScript
const { DatabaseSync } = require('node:sqlite');
|
|
const path = require('path');
|
|
|
|
const fs = require('fs');
|
|
// Resolve DB_PATH: if absolute — use as-is; if relative — resolve from backend/ dir;
|
|
// fallback to __dirname-relative default so CWD never matters.
|
|
const _rawPath = process.env.DB_PATH;
|
|
const _backendDir = path.join(__dirname, '../../');
|
|
const dbPath = _rawPath
|
|
? (path.isAbsolute(_rawPath) ? _rawPath : path.resolve(_backendDir, _rawPath))
|
|
: path.join(__dirname, '../../data/learnspace.db');
|
|
const dbDir = path.dirname(dbPath);
|
|
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
|
|
|
|
// Auto-migrate from old location (backend/learnspace.db → backend/data/learnspace.db)
|
|
const oldPath = path.join(__dirname, '../../learnspace.db');
|
|
if (!fs.existsSync(dbPath) && fs.existsSync(oldPath)) {
|
|
fs.copyFileSync(oldPath, dbPath);
|
|
// Also copy WAL/SHM if present
|
|
if (fs.existsSync(oldPath + '-wal')) fs.copyFileSync(oldPath + '-wal', dbPath + '-wal');
|
|
if (fs.existsSync(oldPath + '-shm')) fs.copyFileSync(oldPath + '-shm', dbPath + '-shm');
|
|
console.log('[db] Migrated database from', oldPath, '→', dbPath);
|
|
}
|
|
|
|
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.
|
|
* Returns the value returned by fn(), or rethrows on error.
|
|
*/
|
|
db.transaction = function transaction(fn) {
|
|
return (...args) => {
|
|
db.exec('BEGIN');
|
|
try {
|
|
const result = fn(...args);
|
|
db.exec('COMMIT');
|
|
return result;
|
|
} catch (err) {
|
|
db.exec('ROLLBACK');
|
|
throw err;
|
|
}
|
|
};
|
|
};
|
|
|
|
module.exports = db;
|