elorasmus/server/index.js
agent 67f9b199ec 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3
2026-11-12 20:55:35 +00:00

245 lines
9.6 KiB
JavaScript

// 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'));
}