/** * The HTTP surface, over a real socket. * * A real socket rather than a mocked handler, because half of what this file * asserts — the body cap closing the connection, the response headers, the * status codes — does not exist above the transport. * * Every server binds `127.0.0.1` on a port the OS chooses, and every one is * closed in `afterEach` rather than at the end of the happy path: a failing * assertion returns first, so a test that cleans up last leaks a listener * exactly when it fails (CLAUDE.md §5.7). */ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { relayConfig } from '../src/config.js'; import { startRelay, type RunningRelay } from '../src/server.js'; import { RelayStore } from '../src/store.js'; import { IN_WEEK_34, keyFor, signedSubmission } from './helpers.js'; let store: RelayStore; let relay: RunningRelay; let clock = IN_WEEK_34; beforeEach(async () => { clock = IN_WEEK_34; store = RelayStore.open(':memory:'); relay = await startRelay({ store, config: relayConfig(), // The clock is injected so a test can cross a week boundary without // waiting for one. now: () => clock }); }); afterEach(async () => { await relay.close(); store.close(); }); function url(path: string): string { return `http://127.0.0.1:${relay.port}${path}`; } async function post(path: string, body: unknown): Promise<{ status: number; json: any }> { const res = await fetch(url(path), { method: 'POST', headers: { 'content-type': 'application/json' }, body: typeof body === 'string' ? body : JSON.stringify(body) }); return { status: res.status, json: await res.json() }; } describe('GET /health', () => { it('publishes the relay week, so a client can stop guessing', () => { // The player's day is a LOCAL day and the relay's week is a UTC week, so // near a boundary the two disagree. This endpoint is the repair. return fetch(url('/health')) .then((r) => r.json()) .then((body) => { expect(body.ok).toBe(true); expect(body.weekId).toBe('2026-W34'); expect(body.xpCeiling).toBe(5000); }); }); it('says out loud what a signature proves', async () => { const body = await fetch(url('/health')).then((r) => r.json()); expect(body.signatureProves).toBe('who submitted, not that the number is true'); }); it('publishes no counts, no uptime and nothing about anybody', async () => { const body = await fetch(url('/health')).then((r) => r.json()); expect(Object.keys(body).sort()).toEqual([ 'displayNameMaxChars', 'ok', 'signatureProves', 'weekId', 'xpCeiling' ]); }); }); describe('POST /submit', () => { it('accepts a signed submission and reports what was stored', async () => { const { status, json } = await post('/submit', signedSubmission(keyFor(1))); expect(status).toBe(200); expect(json.ok).toBe(true); expect(json.xp).toBe(1240); expect(json.clamped).toBe(false); expect(store.count()).toBe(1); }); it('reports the clamp rather than silently recording a different number', async () => { // A client that submitted 8 000 000 and was quietly recorded at 5 000 would // show its user a number that is not on the board. const { json } = await post('/submit', signedSubmission(keyFor(1), { xp: 8_000_000 })); expect(json.xp).toBe(5000); expect(json.clamped).toBe(true); }); it('answers a bad signature with 400 and the reason, and writes nothing', async () => { const honest = signedSubmission(keyFor(1)); const { status, json } = await post('/submit', { ...honest, xp: 999_999 }); expect(status).toBe(400); expect(json.error.code).toBe('relay/bad-signature'); expect(store.count()).toBe(0); }); it('answers a stale week with 409, because the client can repair that one', async () => { const { status, json } = await post('/submit', signedSubmission(keyFor(1), { weekId: '2026-W33' })); expect(status).toBe(409); expect(json.error.code).toBe('relay/stale-week'); expect(store.count()).toBe(0); }); it('follows the clock across a week boundary', async () => { // What was current a moment ago is stale a moment later, with no restart // and no cached week. const submission = signedSubmission(keyFor(1), { weekId: '2026-W34' }); expect((await post('/submit', submission)).status).toBe(200); clock = Date.UTC(2026, 7, 24, 0, 0, 0); // Monday — 2026-W35 expect((await post('/submit', submission)).status).toBe(409); }); it('answers unparseable JSON with a named error and does not echo the body', async () => { const { status, json } = await post('/submit', '{"pubkey": '); expect(status).toBe(400); expect(json.error.code).toBe('relay/malformed-body'); // Reflecting untrusted input back into a response gives a payload a // delivery mechanism. The parser's message names the offset; that is enough. expect(JSON.stringify(json)).not.toContain('pubkey":'); }); it('refuses an oversized body instead of buffering it', async () => { const huge = JSON.stringify({ pubkey: 'A'.repeat(64 * 1024) }); // The connection is destroyed mid-body, so `fetch` may see either a 413 or // a transport error depending on how much got through first. Both are the // cap doing its job; what must NOT happen is a 200 or a stored row. let status = 0; try { status = (await post('/submit', huge)).status; } catch { status = 0; // socket closed under us — the cap fired early. } expect(status).not.toBe(200); expect(store.count()).toBe(0); }); }); describe('GET /league/', () => { it('serves the current week ranked, and nothing else', async () => { await post('/submit', signedSubmission(keyFor(1), { displayName: 'tereza', xp: 1900 })); await post('/submit', signedSubmission(keyFor(2), { displayName: 'jkubicek', xp: 700 })); const body = await fetch(url('/league/domus.eng')).then((r) => r.json()); expect(body.weekId).toBe('2026-W34'); expect(body.rows.map((r: { displayName: string }) => r.displayName)).toEqual([ 'tereza', 'jkubicek' ]); expect(Object.keys(body.rows[0]).sort()).toEqual(['displayName', 'pubkey', 'rank', 'xp']); }); it('handles a league id that needs escaping', async () => { await post('/submit', signedSubmission(keyFor(1), { leagueId: 'domus eng/2' })); const body = await fetch(url(`/league/${encodeURIComponent('domus eng/2')}`)).then((r) => r.json() ); expect(body.rows).toHaveLength(1); }); it('returns an empty board rather than a 404 for a league nobody joined', async () => { const res = await fetch(url('/league/nobody.here')); expect(res.status).toBe(200); expect((await res.json()).rows).toEqual([]); }); }); describe('the response headers', () => { it('sets no cookie, on any route', async () => { for (const path of ['/health', '/league/domus.eng']) { const res = await fetch(url(path)); expect(res.headers.get('set-cookie')).toBeNull(); } const res = await fetch(url('/submit'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(signedSubmission(keyFor(1))) }); expect(res.headers.get('set-cookie')).toBeNull(); }); it('allows any origin and no credentials', async () => { // Open is correct for a public board; open PLUS credentials would be the // dangerous combination, and there are no credentials to send. const res = await fetch(url('/health')); expect(res.headers.get('access-control-allow-origin')).toBe('*'); expect(res.headers.get('access-control-allow-credentials')).toBeNull(); }); it('marks every response uncacheable', async () => { const res = await fetch(url('/league/domus.eng')); expect(res.headers.get('cache-control')).toBe('no-store'); }); it('answers a CORS preflight without touching the database', async () => { const res = await fetch(url('/submit'), { method: 'OPTIONS' }); expect(res.status).toBe(204); expect(store.count()).toBe(0); }); }); describe('anything else', () => { it('404s an unknown route with the list of real ones', async () => { const res = await fetch(url('/participants')); expect(res.status).toBe(404); const body = await res.json(); expect(body.error.code).toBe('relay/no-such-route'); }); it('404s a GET on the write route rather than doing something surprising', async () => { expect((await fetch(url('/submit'))).status).toBe(404); }); });