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