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
This commit is contained in:
parent
226e5f46f8
commit
67f9b199ec
7 changed files with 1033 additions and 0 deletions
273
server/store.js
Normal file
273
server/store.js
Normal file
|
|
@ -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 { "<school code>": { 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<string>} 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) };
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue