From 67f9b199ecdd4978eb7c566f85b1e2ea20a37a6e Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 12 Nov 2026 20:55:35 +0000 Subject: [PATCH] Add HTTP server: event store, optional login, static files Standard library only. Config from env vars, validated at startup. State is an append-only events.jsonl (idempotent appends, torn-line tolerant) plus notes and settings written atomically. Optional AUTH_PASSWORD login with signed HttpOnly SameSite=Strict cookies and per-IP backoff. CSRF: JSON-only writes plus an Origin check. Strict CSP, ETag + gzip, BASE_PATH support. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3 --- package.json | 12 ++ server/auth.js | 117 +++++++++++++++++++ server/config.js | 91 +++++++++++++++ server/index.js | 245 +++++++++++++++++++++++++++++++++++++++ server/static.js | 102 +++++++++++++++++ server/store.js | 273 ++++++++++++++++++++++++++++++++++++++++++++ test/server.test.js | 193 +++++++++++++++++++++++++++++++ 7 files changed, 1033 insertions(+) create mode 100644 package.json create mode 100644 server/auth.js create mode 100644 server/config.js create mode 100644 server/index.js create mode 100644 server/static.js create mode 100644 server/store.js create mode 100644 test/server.test.js diff --git a/package.json b/package.json new file mode 100644 index 0000000..8accc8f --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "elorasmus", + "version": "1.0.0", + "private": true, + "description": "Pick-one-of-two Elo ranking of CTU FEL exchange partner schools, mobile-first.", + "type": "module", + "engines": { "node": ">=22.6" }, + "scripts": { + "start": "node server/index.js", + "test": "node --test test/" + } +} diff --git a/server/auth.js b/server/auth.js new file mode 100644 index 0000000..64c7e7e --- /dev/null +++ b/server/auth.js @@ -0,0 +1,117 @@ +// Optional single-password login. Enabled only when AUTH_PASSWORD is set. +// +// Session = signed cookie "."; payload is base64url JSON { iat, exp }. +// The HMAC key mixes SESSION_SECRET with a hash of the password, so changing AUTH_PASSWORD +// invalidates every existing session. If SESSION_SECRET is unset, a random secret is +// generated once and kept in DATA_DIR/session-secret (chmod 600) so restarts keep sessions. + +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; + +export const COOKIE_NAME = 'elorasmus_session'; + +const sha256 = (s) => crypto.createHash('sha256').update(s).digest(); +const b64url = (buf) => Buffer.from(buf).toString('base64url'); + +function loadOrCreateSecret(dataDir) { + const file = path.join(dataDir, 'session-secret'); + try { + const s = fs.readFileSync(file, 'utf8').trim(); + if (s.length >= 32) return s; + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + const s = crypto.randomBytes(32).toString('hex'); + fs.writeFileSync(file, s + '\n', { mode: 0o600 }); + return s; +} + +export class Auth { + constructor(config) { + this.enabled = Boolean(config.authPassword); + this.config = config; + this.failures = new Map(); // ip -> { count, until } + if (!this.enabled) return; + const secret = config.sessionSecret ?? loadOrCreateSecret(config.dataDir); + this.key = crypto.createHmac('sha256', secret).update('elorasmus-v1:').update(sha256(config.authPassword)).digest(); + this.passwordDigest = sha256(config.authPassword); + } + + #sign(payload) { + return b64url(crypto.createHmac('sha256', this.key).update(payload).digest()); + } + + issueCookie(secure) { + const now = Math.floor(Date.now() / 1000); + const maxAge = this.config.sessionDays * 86400; + const payload = b64url(JSON.stringify({ iat: now, exp: now + maxAge })); + return cookieString(`${payload}.${this.#sign(payload)}`, maxAge, secure, this.config.basePath); + } + + clearCookie(secure) { + return cookieString('', 0, secure, this.config.basePath); + } + + /** True if the request carries a valid, unexpired session cookie (always true when auth is off). */ + isAuthenticated(req) { + if (!this.enabled) return true; + const token = parseCookies(req.headers.cookie)[COOKIE_NAME]; + if (!token) return false; + const [payload, sig] = token.split('.'); + if (!payload || !sig) return false; + const expected = Buffer.from(this.#sign(payload)); + const given = Buffer.from(sig); + if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) return false; + try { + const { exp } = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')); + return typeof exp === 'number' && exp > Date.now() / 1000; + } catch { + return false; + } + } + + /** Seconds the client must wait before another attempt (0 = allowed). */ + retryAfter(ip) { + const f = this.failures.get(ip); + if (!f) return 0; + return Math.max(0, Math.ceil((f.until - Date.now()) / 1000)); + } + + /** Constant-time password check with exponential backoff after 5 failures per IP. */ + checkPassword(ip, password) { + const ok = typeof password === 'string' && crypto.timingSafeEqual(sha256(password), this.passwordDigest); + if (ok) { + this.failures.delete(ip); + return true; + } + const f = this.failures.get(ip) ?? { count: 0, until: 0 }; + f.count += 1; + // 5 free attempts, then 2s, 4s, 8s ... capped at 15 minutes. + const delay = f.count <= 5 ? 0 : Math.min(900, 2 ** (f.count - 5)) * 1000; + f.until = Date.now() + delay; + this.failures.set(ip, f); + if (this.failures.size > 10000) this.failures.clear(); // bound memory under abuse + return false; + } +} + +function cookieString(value, maxAge, secure, basePath) { + return [ + `${COOKIE_NAME}=${value}`, + `Path=${basePath}`, + `Max-Age=${maxAge}`, + 'HttpOnly', + 'SameSite=Strict', + secure ? 'Secure' : null, + ].filter(Boolean).join('; '); +} + +export function parseCookies(header = '') { + const out = {}; + for (const part of header.split(';')) { + const i = part.indexOf('='); + if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim(); + } + return out; +} diff --git a/server/config.js b/server/config.js new file mode 100644 index 0000000..53ba0ed --- /dev/null +++ b/server/config.js @@ -0,0 +1,91 @@ +// Runtime configuration, read once from environment variables. +// Every variable is documented in .env.example and README.md; keep the three in sync. + +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +function str(env, name, fallback) { + const v = env[name]; + return v === undefined || v.trim() === '' ? fallback : v.trim(); +} + +function int(env, name, fallback, min, max) { + const raw = str(env, name, null); + if (raw === null) return fallback; + const n = Number(raw); + if (!Number.isInteger(n) || n < min || n > max) { + throw new Error(`${name} must be an integer between ${min} and ${max} (got "${raw}")`); + } + return n; +} + +function num(env, name, fallback, min, max) { + const raw = str(env, name, null); + if (raw === null) return fallback; + const n = Number(raw); + if (!Number.isFinite(n) || n < min || n > max) { + throw new Error(`${name} must be a number between ${min} and ${max} (got "${raw}")`); + } + return n; +} + +function bool(env, name, fallback) { + const raw = str(env, name, null); + if (raw === null) return fallback; + if (/^(1|true|yes|on)$/i.test(raw)) return true; + if (/^(0|false|no|off)$/i.test(raw)) return false; + throw new Error(`${name} must be true or false (got "${raw}")`); +} + +function oneOf(env, name, fallback, allowed) { + const raw = str(env, name, fallback).toLowerCase(); + if (!allowed.includes(raw)) throw new Error(`${name} must be one of ${allowed.join(', ')} (got "${raw}")`); + return raw; +} + +/** Normalise BASE_PATH to "/", or "/sub/path/" (leading and trailing slash). */ +function basePath(env) { + const raw = str(env, 'BASE_PATH', '/'); + if (!/^[A-Za-z0-9/_.-]*$/.test(raw) || raw.includes('..')) { + throw new Error(`BASE_PATH may only contain letters, digits, "/", "_", "-", "." (got "${raw}")`); + } + const trimmed = raw.replace(/^\/+|\/+$/g, ''); + return trimmed ? `/${trimmed}/` : '/'; +} + +export function loadConfig(env = process.env) { + const authPassword = env.AUTH_PASSWORD ?? ''; + const config = { + host: str(env, 'HOST', '127.0.0.1'), + port: int(env, 'PORT', 8317, 1, 65535), + basePath: basePath(env), + dataDir: path.resolve(ROOT, str(env, 'DATA_DIR', 'var')), + publicDir: path.join(ROOT, 'public'), + authPassword: authPassword.length ? authPassword : null, + sessionSecret: str(env, 'SESSION_SECRET', null), + sessionDays: int(env, 'SESSION_DAYS', 180, 1, 3650), + cookieSecure: oneOf(env, 'COOKIE_SECURE', 'auto', ['auto', 'true', 'false']), + trustProxy: bool(env, 'TRUST_PROXY', false), + logRequests: bool(env, 'LOG_REQUESTS', false), + app: { + title: str(env, 'APP_TITLE', 'Elorasmus').slice(0, 60), + stayMonths: num(env, 'STAY_MONTHS', 5, 1, 12), + eloInitial: int(env, 'ELO_INITIAL', 1500, 100, 5000), + eloKMax: int(env, 'ELO_K_MAX', 48, 4, 200), + eloKMin: int(env, 'ELO_K_MIN', 16, 1, 200), + eurCzk: num(env, 'EUR_CZK', null, 1, 100), + }, + }; + if (config.authPassword && config.authPassword.length < 8) { + throw new Error('AUTH_PASSWORD must be at least 8 characters (or unset to disable login)'); + } + if (config.sessionSecret && config.sessionSecret.length < 32) { + throw new Error('SESSION_SECRET must be at least 32 characters (or unset to auto-generate one)'); + } + if (config.app.eloKMin > config.app.eloKMax) { + throw new Error('ELO_K_MIN must not be larger than ELO_K_MAX'); + } + return config; +} diff --git a/server/index.js b/server/index.js new file mode 100644 index 0000000..32d4df6 --- /dev/null +++ b/server/index.js @@ -0,0 +1,245 @@ +// Elorasmus HTTP server: static app + a small JSON API over the event store. +// No dependencies beyond Node's standard library. Run: node server/index.js + +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { loadConfig } from './config.js'; +import { Auth } from './auth.js'; +import { StaticFiles } from './static.js'; +import { Store, ValidationError } from './store.js'; + +const SECURITY_HEADERS = { + 'Content-Security-Policy': [ + "default-src 'self'", "script-src 'self'", "style-src 'self'", "img-src 'self' data:", + "connect-src 'self'", "font-src 'self'", "manifest-src 'self'", "base-uri 'self'", + "form-action 'self'", "frame-ancestors 'none'", "object-src 'none'", + ].join('; '), + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'no-referrer', + 'X-Frame-Options': 'DENY', + 'Cross-Origin-Opener-Policy': 'same-origin', + 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), interest-cohort=()', +}; +const BODY_LIMIT = 256 * 1024; +const IMPORT_LIMIT = 32 * 1024 * 1024; + +class HttpError extends Error { + constructor(status, message, headers = {}) { + super(message); + this.status = status; + this.headers = headers; + } +} + +function sendJson(res, status, body, headers = {}) { + const data = Buffer.from(JSON.stringify(body)); + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': data.length, + 'Cache-Control': 'no-store', + ...headers, + }); + res.end(data); +} + +async function readJson(req, limit) { + const type = req.headers['content-type'] ?? ''; + // Requiring JSON blocks cross-site form posts (CSRF): browsers can't send it cross-origin without CORS. + if (!/^application\/json\b/i.test(type)) throw new HttpError(415, 'Content-Type must be application/json'); + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > limit) throw new HttpError(413, `Request body larger than ${limit} bytes`); + chunks.push(chunk); + } + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8') || 'null'); + } catch { + throw new HttpError(400, 'Malformed JSON'); + } +} + +export function loadSchoolCodes(publicDir) { + const file = path.join(publicDir, 'data', 'schools.json'); + let data; + try { + data = JSON.parse(fs.readFileSync(file, 'utf8')); + } catch (err) { + throw new Error(`Cannot load ${file} (${err.message}). Build it with: python3 -I scripts/build_data.py`); + } + return { codes: new Set(data.schools.map((s) => s.code)), generatedAt: data.generatedAt }; +} + +export function createApp(config) { + const { codes, generatedAt } = loadSchoolCodes(config.publicDir); + const store = new Store(config.dataDir, codes); + const auth = new Auth(config); + const files = new StaticFiles(config.publicDir, { basePath: config.basePath, title: config.app.title }); + const version = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; + + const clientIp = (req) => + (config.trustProxy && req.headers['x-forwarded-for']?.split(',')[0].trim()) || req.socket.remoteAddress || '?'; + const isSecure = (req) => + config.cookieSecure === 'true' || + (config.cookieSecure === 'auto' && + (req.socket.encrypted || (config.trustProxy && req.headers['x-forwarded-proto'] === 'https'))); + + function checkOrigin(req) { + const origin = req.headers.origin; + if (!origin) return; // same-origin fetches from older browsers may omit it; Content-Type check still applies + const host = (config.trustProxy && req.headers['x-forwarded-host']) || req.headers.host; + let originHost; + try { + originHost = new URL(origin).host; + } catch { + throw new HttpError(403, 'Bad Origin header'); + } + if (originHost !== host) throw new HttpError(403, 'Cross-origin request refused'); + } + + async function api(req, res, route) { + const method = req.method; + if (method !== 'GET' && method !== 'HEAD') checkOrigin(req); + + if (route === 'config' && method === 'GET') { + return sendJson(res, 200, { + title: config.app.title, + version, + dataGeneratedAt: generatedAt, + authRequired: auth.enabled, + authenticated: auth.isAuthenticated(req), + defaults: { stayMonths: config.app.stayMonths }, + elo: { initial: config.app.eloInitial, kMax: config.app.eloKMax, kMin: config.app.eloKMin }, + eurCzk: config.app.eurCzk, + }); + } + if (route === 'login' && method === 'POST') { + if (!auth.enabled) return sendJson(res, 200, { ok: true }); + const ip = clientIp(req); + const wait = auth.retryAfter(ip); + if (wait > 0) throw new HttpError(429, `Too many attempts; retry in ${wait}s`, { 'Retry-After': String(wait) }); + const body = await readJson(req, 4096); + if (!auth.checkPassword(ip, body?.password)) throw new HttpError(401, 'Wrong password'); + return sendJson(res, 200, { ok: true }, { 'Set-Cookie': auth.issueCookie(isSecure(req)) }); + } + if (route === 'logout' && method === 'POST') { + return sendJson(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie(isSecure(req)) }); + } + + if (!auth.isAuthenticated(req)) throw new HttpError(401, 'Login required'); + + if (route === 'state' && method === 'GET') { + const since = Number(new URL(req.url, 'http://x').searchParams.get('since') ?? 0) || 0; + return sendJson(res, 200, { + seq: store.seq, + events: store.eventsSince(since), + notes: store.notes, + settings: store.settings, + }); + } + if (route === 'events' && method === 'POST') { + const body = await readJson(req, BODY_LIMIT); + return sendJson(res, 200, store.append(body?.events)); + } + if (route.startsWith('notes/') && method === 'PUT') { + const code = decodeURIComponent(route.slice('notes/'.length)); + const body = await readJson(req, BODY_LIMIT); + return sendJson(res, 200, { note: store.setNote(code, body?.text) }); + } + if (route === 'settings' && method === 'PUT') { + const body = await readJson(req, BODY_LIMIT); + return sendJson(res, 200, { settings: store.updateSettings(body) }); + } + if (route === 'export' && method === 'GET') { + const stamp = new Date().toISOString().slice(0, 10); + return sendJson(res, 200, store.exportAll(), { + 'Content-Disposition': `attachment; filename="elorasmus-${stamp}.json"`, + }); + } + if (route === 'import' && method === 'POST') { + const body = await readJson(req, IMPORT_LIMIT); + return sendJson(res, 200, store.importAll(body)); + } + throw new HttpError(404, 'No such API route'); + } + + async function handle(req, res) { + for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.setHeader(k, v); + const url = new URL(req.url, 'http://placeholder'); + const pathname = url.pathname; + + if (pathname === '/healthz' || pathname === `${config.basePath}healthz`) { + return sendJson(res, 200, { ok: true }); + } + if (pathname === config.basePath.slice(0, -1) && config.basePath !== '/') { + res.writeHead(308, { Location: config.basePath }); + return res.end(); + } + if (!pathname.startsWith(config.basePath)) throw new HttpError(404, 'Not found'); + const rel = pathname.slice(config.basePath.length); + + if (rel.startsWith('api/')) return api(req, res, rel.slice(4)); + if (req.method !== 'GET' && req.method !== 'HEAD') throw new HttpError(405, 'Method not allowed'); + // The app shell is public so it can render the login form; the research data is not. + if (rel.startsWith('data/') && !auth.isAuthenticated(req)) throw new HttpError(401, 'Login required'); + if (!files.serve(req, res, rel)) throw new HttpError(404, 'Not found'); + } + + const server = http.createServer((req, res) => { + const started = Date.now(); + handle(req, res) + .catch((err) => { + if (err instanceof ValidationError) err = new HttpError(400, err.message); + if (!(err instanceof HttpError)) { + console.error(`[error] ${req.method} ${req.url?.split('?')[0]}:`, err); + err = new HttpError(500, 'Internal error'); + } + if (!res.headersSent) sendJson(res, err.status, { error: err.message }, err.headers); + else res.destroy(); + }) + .finally(() => { + if (config.logRequests) { + console.log(`${req.method} ${req.url?.split('?')[0]} ${res.statusCode} ${Date.now() - started}ms`); + } + }); + }); + server.headersTimeout = 20_000; + server.requestTimeout = 60_000; + return { server, store, auth }; +} + +// Started directly (not imported by tests)? +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + let config; + try { + config = loadConfig(); + } catch (err) { + console.error(`Configuration error: ${err.message}`); + process.exit(2); + } + let app; + try { + app = createApp(config); + } catch (err) { + console.error(`Startup error: ${err.message}`); + process.exit(1); + } + for (const w of app.store.warnings) console.warn(`[warn] ${w}`); + app.server.listen(config.port, config.host, () => { + console.log(`Elorasmus listening on http://${config.host}:${config.port}${config.basePath}`); + console.log(`Data directory: ${config.dataDir}`); + console.log(app.auth.enabled + ? 'Login: enabled (AUTH_PASSWORD is set)' + : 'Login: DISABLED. Fine on loopback, an SSH tunnel or a VPN; set AUTH_PASSWORD before exposing it publicly.'); + }); + const stop = (signal) => { + console.log(`${signal} received, shutting down`); + app.server.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 5000).unref(); + }; + process.on('SIGTERM', () => stop('SIGTERM')); + process.on('SIGINT', () => stop('SIGINT')); +} diff --git a/server/static.js b/server/static.js new file mode 100644 index 0000000..2230a95 --- /dev/null +++ b/server/static.js @@ -0,0 +1,102 @@ +// Static files from public/, cached in memory (the set is small and fixed per container). +// Every response gets an ETag and "no-cache" (= always revalidate), so a redeploy is picked up +// immediately without cache-busting file names. Compressible types are gzipped once. + +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; + +const TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.webmanifest': 'application/manifest+json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.txt': 'text/plain; charset=utf-8', +}; +const COMPRESSIBLE = new Set(['.html', '.js', '.css', '.json', '.webmanifest', '.svg', '.txt']); + +export class StaticFiles { + constructor(publicDir, { basePath, title }) { + this.root = path.resolve(publicDir); + this.basePath = basePath; + this.title = title; + this.cache = new Map(); + } + + /** Resolve a URL path (relative to the base path) to a file inside public/, or null. */ + #resolve(rel) { + let decoded; + try { + decoded = decodeURIComponent(rel); + } catch { + return null; + } + if (decoded.includes('\0')) return null; + const file = path.resolve(this.root, '.' + path.posix.normalize('/' + decoded)); + if (file !== this.root && !file.startsWith(this.root + path.sep)) return null; // traversal + return file; + } + + #load(file) { + let entry = this.cache.get(file); + if (entry) return entry; + let stat; + try { + stat = fs.statSync(file); + } catch { + return null; + } + if (!stat.isFile()) return null; + const ext = path.extname(file).toLowerCase(); + let body = fs.readFileSync(file); + if (file === path.join(this.root, 'index.html')) { + // The page uses relative URLs; makes them work under any BASE_PATH. + body = Buffer.from(body.toString('utf8') + .replace('', ``) + .replaceAll('%APP_TITLE%', escapeHtml(this.title))); + } + entry = { + body, + gz: COMPRESSIBLE.has(ext) && body.length > 1024 ? zlib.gzipSync(body, { level: 9 }) : null, + type: TYPES[ext] ?? 'application/octet-stream', + etag: `"${crypto.createHash('sha1').update(body).digest('base64url')}"`, + }; + this.cache.set(file, entry); + return entry; + } + + /** Serve `rel` (path below the base, '' = index). Returns false if no such file. */ + serve(req, res, rel) { + const file = this.#resolve(rel === '' ? 'index.html' : rel); + if (!file) return false; + const entry = this.#load(file); + if (!entry) return false; + const headers = { + 'Content-Type': entry.type, + 'Cache-Control': 'no-cache', + ETag: entry.etag, + Vary: 'Accept-Encoding', + }; + if (req.headers['if-none-match'] === entry.etag) { + res.writeHead(304, headers); + res.end(); + return true; + } + const useGzip = entry.gz && /\bgzip\b/.test(req.headers['accept-encoding'] ?? ''); + const body = useGzip ? entry.gz : entry.body; + if (useGzip) headers['Content-Encoding'] = 'gzip'; + headers['Content-Length'] = body.length; + res.writeHead(200, headers); + res.end(req.method === 'HEAD' ? undefined : body); + return true; + } +} + +function escapeHtml(s) { + return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); +} diff --git a/server/store.js b/server/store.js new file mode 100644 index 0000000..255cd00 --- /dev/null +++ b/server/store.js @@ -0,0 +1,273 @@ +// Persistent state, kept as plain files in DATA_DIR so it is easy to inspect and back up: +// +// events.jsonl append-only log of user actions (one JSON object per line). +// Ratings are never stored; clients replay this log to compute them. +// notes.json { "": { text, updatedAt } } +// settings.json synced user preferences (validated, whitelisted keys) +// backups/ copies made automatically before an import replaces state +// +// Why an event log: picks from a phone and a laptop can interleave without either device +// overwriting the other, undo is just another event, and the full history stays auditable. + +import fs from 'node:fs'; +import path from 'node:path'; + +const EVENT_ID = /^[A-Za-z0-9_-]{8,64}$/; +const EVENT_TYPES = new Set(['match', 'drop', 'restore', 'review', 'undo']); +const RESULTS = new Set(['a', 'b', 'draw']); +const LEVELS = new Set(['A1', 'A2', 'B1', 'B2', 'C1', 'C2']); +const NOTE_MAX = 5000; + +export class ValidationError extends Error {} + +function writeFileAtomic(file, data) { + const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const fd = fs.openSync(tmp, 'w', 0o600); + try { + fs.writeSync(fd, data); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + fs.renameSync(tmp, file); +} + +function readJson(file, fallback) { + try { + return JSON.parse(fs.readFileSync(file, 'utf8')); + } catch (err) { + if (err.code === 'ENOENT') return fallback; + throw new Error(`Cannot read ${file}: ${err.message}`); + } +} + +/** Validate user settings; unknown keys are rejected so typos surface instead of being ignored. */ +export function validateSettings(input) { + if (!input || typeof input !== 'object' || Array.isArray(input)) throw new ValidationError('settings must be an object'); + const out = {}; + for (const [key, value] of Object.entries(input)) { + switch (key) { + case 'stayMonths': + if (typeof value !== 'number' || !(value >= 1 && value <= 12)) throw new ValidationError('stayMonths must be 1-12'); + out[key] = Math.round(value * 2) / 2; + break; + case 'currency': + if (!['EUR', 'CZK'].includes(value)) throw new ValidationError('currency must be EUR or CZK'); + out[key] = value; + break; + case 'pairing': + if (!['smart', 'random'].includes(value)) throw new ValidationError('pairing must be smart or random'); + out[key] = value; + break; + case 'fewerOpportunities': + case 'greenTravel': + case 'countHostFunding': + if (typeof value !== 'boolean') throw new ValidationError(`${key} must be true or false`); + out[key] = value; + break; + case 'languages': + if (!Array.isArray(value) || value.length > 12) throw new ValidationError('languages must be a list (max 12)'); + out[key] = value.map((l) => { + if (!l || !/^[a-z]{2}$/.test(l.lang) || !LEVELS.has(l.level)) { + throw new ValidationError('each language needs a 2-letter code and a CEFR level A1-C2'); + } + return { lang: l.lang, level: l.level }; + }); + break; + default: + throw new ValidationError(`unknown setting "${key}"`); + } + } + return out; +} + +export class Store { + /** + * @param {string} dir data directory (created if missing) + * @param {Set} codes valid school codes; events naming anything else are rejected + */ + constructor(dir, codes) { + this.dir = dir; + this.codes = codes; + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + this.eventsFile = path.join(dir, 'events.jsonl'); + this.notesFile = path.join(dir, 'notes.json'); + this.settingsFile = path.join(dir, 'settings.json'); + this.warnings = []; + this.#loadEvents(); + this.notes = readJson(this.notesFile, {}); + this.settings = readJson(this.settingsFile, {}); + } + + #loadEvents() { + this.events = []; + this.byId = new Map(); + this.undone = new Set(); + let raw = ''; + try { + raw = fs.readFileSync(this.eventsFile, 'utf8'); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + // A crash mid-append can leave a partial last line; isolate it so the next append starts clean. + if (raw && !raw.endsWith('\n')) fs.appendFileSync(this.eventsFile, '\n'); + raw.split('\n').forEach((line, i) => { + if (!line.trim()) return; + try { + const ev = JSON.parse(line); + if (!EVENT_ID.test(ev.id) || this.byId.has(ev.id)) throw new Error('bad or duplicate id'); + this.#index(ev); + } catch (err) { + this.warnings.push(`events.jsonl line ${i + 1} ignored: ${err.message}`); + } + }); + this.seq = this.events.reduce((m, e) => Math.max(m, e.seq || 0), 0); + } + + #index(ev) { + this.events.push(ev); + this.byId.set(ev.id, ev); + if (ev.type === 'undo') this.undone.add(ev.target); + } + + /** Throws ValidationError unless `ev` is a well-formed client event. Returns a clean copy. */ + validateEvent(ev, pending = new Map()) { + if (!ev || typeof ev !== 'object') throw new ValidationError('event must be an object'); + if (typeof ev.id !== 'string' || !EVENT_ID.test(ev.id)) throw new ValidationError('event id must be 8-64 chars [A-Za-z0-9_-]'); + if (!EVENT_TYPES.has(ev.type)) throw new ValidationError(`unknown event type "${ev.type}"`); + const t = typeof ev.t === 'string' && ev.t.length <= 40 && !Number.isNaN(Date.parse(ev.t)) ? ev.t : null; + if (!t) throw new ValidationError('event t must be an ISO timestamp'); + const clean = { id: ev.id, t, type: ev.type }; + const school = (c, field) => { + if (typeof c !== 'string' || !this.codes.has(c)) throw new ValidationError(`${field}: unknown school code`); + return c; + }; + switch (ev.type) { + case 'match': + clean.a = school(ev.a, 'a'); + clean.b = school(ev.b, 'b'); + if (clean.a === clean.b) throw new ValidationError('a school cannot play itself'); + if (!RESULTS.has(ev.r)) throw new ValidationError('match r must be a, b or draw'); + clean.r = ev.r; + break; + case 'drop': + case 'restore': + case 'review': + clean.code = school(ev.code, 'code'); + break; + case 'undo': { + // `pending` holds earlier events of the same batch, so "pick + undo" can arrive together. + const target = this.byId.get(ev.target) ?? pending.get(ev.target); + if (!target) throw new ValidationError('undo target does not exist'); + if (target.type === 'undo') throw new ValidationError('cannot undo an undo'); + const undoneInBatch = [...pending.values()].some((p) => p.type === 'undo' && p.target === ev.target); + if (this.undone.has(ev.target) || undoneInBatch) throw new ValidationError('event already undone'); + clean.target = ev.target; + break; + } + } + return clean; + } + + /** + * Append client events. Idempotent: ids already stored are skipped, so a client may safely + * resend its outbox after a lost response. All-or-nothing on validation errors. + */ + append(events) { + if (!Array.isArray(events) || events.length === 0 || events.length > 500) { + throw new ValidationError('events must be a non-empty list (max 500)'); + } + const fresh = []; + const pending = new Map(); + for (const ev of events) { + if (ev && this.byId.has(ev.id)) continue; // already stored (retry) + if (ev && pending.has(ev.id)) throw new ValidationError('duplicate id in batch'); + const clean = this.validateEvent(ev, pending); + pending.set(clean.id, clean); + fresh.push(clean); + } + if (fresh.length) { + const now = new Date().toISOString(); + const stored = fresh.map((ev) => ({ seq: ++this.seq, st: now, ...ev })); + const fd = fs.openSync(this.eventsFile, 'a', 0o600); + try { + fs.writeSync(fd, stored.map((e) => JSON.stringify(e)).join('\n') + '\n'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + stored.forEach((e) => this.#index(e)); + } + return { accepted: fresh.length, duplicates: events.length - fresh.length, seq: this.seq }; + } + + eventsSince(seq = 0) { + return seq > 0 ? this.events.filter((e) => e.seq > seq) : this.events.slice(); + } + + setNote(code, text) { + if (!this.codes.has(code)) throw new ValidationError('unknown school code'); + if (typeof text !== 'string' || text.length > NOTE_MAX) throw new ValidationError(`note must be a string up to ${NOTE_MAX} chars`); + if (text.trim()) this.notes[code] = { text, updatedAt: new Date().toISOString() }; + else delete this.notes[code]; + writeFileAtomic(this.notesFile, JSON.stringify(this.notes, null, 1)); + return this.notes[code] ?? null; + } + + updateSettings(patch) { + this.settings = { ...this.settings, ...validateSettings(patch) }; + writeFileAtomic(this.settingsFile, JSON.stringify(this.settings, null, 1)); + return this.settings; + } + + exportAll() { + return { + format: 'elorasmus-export', + version: 1, + exportedAt: new Date().toISOString(), + events: this.events, + notes: this.notes, + settings: this.settings, + }; + } + + /** Replace all state with an export. Validates everything first; backs up current files. */ + importAll(data) { + if (!data || data.format !== 'elorasmus-export' || data.version !== 1) { + throw new ValidationError('not an Elorasmus export (format/version mismatch)'); + } + if (!Array.isArray(data.events) || data.events.length > 200000) throw new ValidationError('events must be a list'); + // Validate against a scratch store so a bad file never leaves us half-imported. + const scratch = Object.create(Store.prototype); + Object.assign(scratch, { codes: this.codes, events: [], byId: new Map(), undone: new Set() }); + const clean = []; + for (const ev of [...data.events].sort((x, y) => (x.seq ?? 0) - (y.seq ?? 0))) { + if (scratch.byId.has(ev?.id)) continue; + const c = scratch.validateEvent(ev); + scratch.byId.set(c.id, c); + if (c.type === 'undo') scratch.undone.add(c.target); + clean.push({ ...c, seq: clean.length + 1, st: typeof ev.st === 'string' ? ev.st : new Date().toISOString() }); + } + const notes = {}; + for (const [code, n] of Object.entries(data.notes ?? {})) { + if (!this.codes.has(code) || typeof n?.text !== 'string' || n.text.length > NOTE_MAX) { + throw new ValidationError(`invalid note for "${code}"`); + } + notes[code] = { text: n.text, updatedAt: typeof n.updatedAt === 'string' ? n.updatedAt : new Date().toISOString() }; + } + const settings = validateSettings(data.settings ?? {}); + + const backup = path.join(this.dir, 'backups', new Date().toISOString().replace(/[:.]/g, '-')); + fs.mkdirSync(backup, { recursive: true, mode: 0o700 }); + for (const f of [this.eventsFile, this.notesFile, this.settingsFile]) { + if (fs.existsSync(f)) fs.copyFileSync(f, path.join(backup, path.basename(f))); + } + writeFileAtomic(this.eventsFile, clean.map((e) => JSON.stringify(e)).join('\n') + (clean.length ? '\n' : '')); + writeFileAtomic(this.notesFile, JSON.stringify(notes, null, 1)); + writeFileAtomic(this.settingsFile, JSON.stringify(settings, null, 1)); + this.#loadEvents(); + this.notes = notes; + this.settings = settings; + return { events: clean.length, backup: path.basename(backup) }; + } +} diff --git a/test/server.test.js b/test/server.test.js new file mode 100644 index 0000000..151cb79 --- /dev/null +++ b/test/server.test.js @@ -0,0 +1,193 @@ +// End-to-end tests of the HTTP API against a real server on a random port. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { loadConfig } from '../server/config.js'; +import { createApp } from '../server/index.js'; + +const PASSWORD = 'correct horse battery'; +let app; +let base; +let dataDir; +let cookie = ''; +const schools = JSON.parse(fs.readFileSync(new URL('../public/data/schools.json', import.meta.url))).schools; +const [A, B] = schools.map((s) => s.code); + +async function call(method, url, { body, headers = {}, raw = false } = {}) { + const res = await fetch(base + url, { + method, + headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...(cookie ? { Cookie: cookie } : {}), ...headers }, + body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body), + redirect: 'manual', + }); + return raw ? res : { status: res.status, body: await res.json().catch(() => null), headers: res.headers }; +} + +before(async () => { + dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'elorasmus-test-')); + const config = loadConfig({ DATA_DIR: dataDir, AUTH_PASSWORD: PASSWORD, BASE_PATH: '/elo', PORT: '1' }); + app = createApp(config); + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)); + base = `http://127.0.0.1:${app.server.address().port}/elo/`; +}); + +after(() => { + app.server.close(); + fs.rmSync(dataDir, { recursive: true, force: true }); +}); + +test('health check is public, at root and under the base path', async () => { + assert.equal((await fetch(base.replace('/elo/', '/healthz'))).status, 200); + assert.equal((await call('GET', 'healthz')).status, 200); +}); + +test('app shell is public and carries the base path and security headers', async () => { + const res = await call('GET', '', { raw: true }); + assert.equal(res.status, 200); + const html = await res.text(); + assert.match(html, //); + assert.match(res.headers.get('content-security-policy'), /script-src 'self'/); + assert.equal(res.headers.get('x-content-type-options'), 'nosniff'); +}); + +test('data and API need a login when AUTH_PASSWORD is set', async () => { + assert.equal((await call('GET', 'data/schools.json')).status, 401); + assert.equal((await call('GET', 'api/state')).status, 401); + const cfg = await call('GET', 'api/config'); + assert.equal(cfg.body.authRequired, true); + assert.equal(cfg.body.authenticated, false); +}); + +test('wrong password is refused, right one sets an HttpOnly cookie', async () => { + assert.equal((await call('POST', 'api/login', { body: { password: 'nope' } })).status, 401); + const ok = await call('POST', 'api/login', { body: { password: PASSWORD } }); + assert.equal(ok.status, 200); + const set = ok.headers.get('set-cookie'); + assert.match(set, /HttpOnly/); + assert.match(set, /SameSite=Strict/); + assert.match(set, /Path=\/elo\//); + cookie = set.split(';')[0]; + assert.equal((await call('GET', 'api/state')).status, 200); +}); + +test('tampered session cookie is rejected', async () => { + const saved = cookie; + cookie = saved.slice(0, -3) + 'abc'; + assert.equal((await call('GET', 'api/state')).status, 401); + cookie = saved; +}); + +test('events: append, idempotent retry, validation', async () => { + const match = { id: 'match00000001', t: new Date().toISOString(), type: 'match', a: A, b: B, r: 'a' }; + const r1 = await call('POST', 'api/events', { body: { events: [match] } }); + assert.deepEqual([r1.status, r1.body.accepted], [200, 1]); + const r2 = await call('POST', 'api/events', { body: { events: [match] } }); + assert.deepEqual([r2.body.accepted, r2.body.duplicates], [0, 1], 'resending is harmless'); + + const bad = [ + { ...match, id: 'bad00000001', a: 'NOPE' }, + { ...match, id: 'bad00000002', b: A }, + { ...match, id: 'bad00000003', r: 'x' }, + { id: 'bad00000004', t: match.t, type: 'undo', target: 'missing000001' }, + { id: 'short', t: match.t, type: 'drop', code: A }, + ]; + for (const e of bad) assert.equal((await call('POST', 'api/events', { body: { events: [e] } })).status, 400, JSON.stringify(e)); + + const undo = { id: 'undo00000001', t: match.t, type: 'undo', target: match.id }; + assert.equal((await call('POST', 'api/events', { body: { events: [undo] } })).status, 200); + const again = { ...undo, id: 'undo00000002' }; + assert.equal((await call('POST', 'api/events', { body: { events: [again] } })).status, 400, 'double undo refused'); + + const state = await call('GET', 'api/state'); + assert.equal(state.body.events.length, 2); + assert.equal(state.body.events[0].seq, 1); + const since = await call('GET', 'api/state?since=1'); + assert.equal(since.body.events.length, 1); +}); + +test('pick and its undo can arrive in one batch', async () => { + const t = new Date().toISOString(); + const res = await call('POST', 'api/events', { body: { events: [ + { id: 'batch0000001', t, type: 'match', a: B, b: A, r: 'draw' }, + { id: 'batch0000002', t, type: 'undo', target: 'batch0000001' }, + ] } }); + assert.equal(res.status, 200); + assert.equal(res.body.accepted, 2); +}); + +test('CSRF: JSON content type and same origin are required for writes', async () => { + const form = await call('POST', 'api/events', { body: 'x=1', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); + assert.equal(form.status, 415); + const cross = await call('POST', 'api/events', { body: { events: [] }, headers: { Origin: 'https://evil.example' } }); + assert.equal(cross.status, 403); +}); + +test('notes and settings round-trip and validate', async () => { + const code = encodeURIComponent(A); + assert.equal((await call('PUT', `api/notes/${code}`, { body: { text: 'great labs' } })).status, 200); + assert.equal((await call('PUT', 'api/notes/NOPE', { body: { text: 'x' } })).status, 400); + assert.equal((await call('PUT', 'api/settings', { body: { stayMonths: 10, currency: 'CZK' } })).status, 200); + assert.equal((await call('PUT', 'api/settings', { body: { stayMonths: 99 } })).status, 400); + assert.equal((await call('PUT', 'api/settings', { body: { hacked: true } })).status, 400); + const state = await call('GET', 'api/state'); + assert.equal(state.body.notes[A].text, 'great labs'); + assert.equal(state.body.settings.currency, 'CZK'); +}); + +test('export, then import restores state and keeps a backup', async () => { + const exp = await call('GET', 'api/export'); + assert.equal(exp.status, 200); + assert.match(exp.headers.get('content-disposition'), /attachment/); + await call('POST', 'api/events', { body: { events: [{ id: 'later0000001', t: new Date().toISOString(), type: 'drop', code: A }] } }); + const imp = await call('POST', 'api/import', { body: exp.body }); + assert.equal(imp.status, 200); + const state = await call('GET', 'api/state'); + assert.equal(state.body.events.length, exp.body.events.length); + assert.ok(fs.readdirSync(path.join(dataDir, 'backups')).length >= 1); + assert.equal((await call('POST', 'api/import', { body: { format: 'other' } })).status, 400); +}); + +test('state survives a restart (events.jsonl on disk)', async () => { + const config = loadConfig({ DATA_DIR: dataDir, PORT: '1' }); + const second = createApp(config); + assert.equal(second.store.events.length, app.store.events.length); + assert.deepEqual(second.store.settings, app.store.settings); +}); + +test('a torn last line in events.jsonl is skipped, not fatal', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'elorasmus-torn-')); + fs.writeFileSync(path.join(dir, 'events.jsonl'), + JSON.stringify({ seq: 1, id: 'good00000001', t: 'x', type: 'drop', code: A }) + '\n{"seq":2,"id":"tor'); + const { store } = createApp(loadConfig({ DATA_DIR: dir, PORT: '1' })); + assert.equal(store.events.length, 1); + assert.equal(store.warnings.length, 1); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test('static files: no path traversal, unknown paths 404', async () => { + for (const p of ['../package.json', '%2e%2e/package.json', 'js/../../server/index.js']) { + const res = await call('GET', p); + assert.ok([400, 404].includes(res.status), `${p} -> ${res.status}`); + } + assert.equal((await call('GET', 'nope.html')).status, 404); +}); + +test('gzip is used when accepted, ETag revalidation works', async () => { + const res = await call('GET', 'data/schools.json', { raw: true, headers: { 'Accept-Encoding': 'gzip' } }); + assert.equal(res.status, 200); + const etag = res.headers.get('etag'); + await res.arrayBuffer(); + const again = await call('GET', 'data/schools.json', { raw: true, headers: { 'If-None-Match': etag } }); + assert.equal(again.status, 304); +}); + +test('config validation rejects bad values', () => { + assert.throws(() => loadConfig({ PORT: 'abc' }), /PORT/); + assert.throws(() => loadConfig({ AUTH_PASSWORD: 'short' }), /AUTH_PASSWORD/); + assert.throws(() => loadConfig({ BASE_PATH: '/../x' }), /BASE_PATH/); + assert.throws(() => loadConfig({ ELO_K_MIN: '50', ELO_K_MAX: '20' }), /ELO_K_MIN/); + assert.equal(loadConfig({ BASE_PATH: 'sub/path/' }).basePath, '/sub/path/'); + assert.equal(loadConfig({}).authPassword, null); +});