[relay] Relay: The league relay from Ludus, byte for byte, with the slice of the schema it imports
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Test fixtures for the relay.
|
||||
*
|
||||
* These sign with `@noble/curves` and `submissionBytes` from `@ludus/schema` —
|
||||
* which is the SAME function the player signs with, because `@ludus/identity`
|
||||
* re-exports it. So the canonical encoding under test here is the real one, not
|
||||
* a restatement of it, and a change to the field order breaks both sides at
|
||||
* once instead of silently rejecting every honest submission.
|
||||
*
|
||||
* No test here touches a real key, a real relay or anyone's data. Every database
|
||||
* is `:memory:` and every socket is on `127.0.0.1` with a port the OS chose.
|
||||
*/
|
||||
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
import { submissionBytes, type LeagueSubmission } from '@ludus/schema';
|
||||
|
||||
export function toBase64Url(bytes: Uint8Array): string {
|
||||
return Buffer.from(bytes).toString('base64url');
|
||||
}
|
||||
|
||||
export interface TestKey {
|
||||
readonly privateKey: Uint8Array;
|
||||
readonly pubkey: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A deterministic keypair from a one-byte label.
|
||||
*
|
||||
* Deterministic on purpose: a failing assertion names the same key every run,
|
||||
* and `keyFor(1)` always sorts the same way against `keyFor(2)` — which the
|
||||
* board's tie-break test depends on.
|
||||
*/
|
||||
export function keyFor(label: number): TestKey {
|
||||
const seed = new Uint8Array(32);
|
||||
seed.fill(label);
|
||||
return { privateKey: seed, pubkey: toBase64Url(ed25519.getPublicKey(seed)) };
|
||||
}
|
||||
|
||||
export interface SubmissionOverrides {
|
||||
readonly displayName?: string;
|
||||
readonly leagueId?: string;
|
||||
readonly weekId?: string;
|
||||
readonly xp?: number;
|
||||
}
|
||||
|
||||
/** A correctly signed submission. */
|
||||
export function signedSubmission(
|
||||
key: TestKey,
|
||||
overrides: SubmissionOverrides = {}
|
||||
): LeagueSubmission {
|
||||
const fields = {
|
||||
pubkey: key.pubkey,
|
||||
displayName: overrides.displayName ?? 'tereza',
|
||||
leagueId: overrides.leagueId ?? 'domus.eng',
|
||||
weekId: overrides.weekId ?? '2026-W34',
|
||||
xp: overrides.xp ?? 1240
|
||||
};
|
||||
const sig = ed25519.sign(submissionBytes(fields), key.privateKey);
|
||||
return { ...fields, sig: toBase64Url(sig) };
|
||||
}
|
||||
|
||||
/** Epoch ms inside ISO week 2026-W34 (Wednesday 2026-08-19, midday UTC). */
|
||||
export const IN_WEEK_34 = Date.UTC(2026, 7, 19, 12, 0, 0);
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Signer and verifier are two different Ed25519 implementations. Prove they agree.
|
||||
*
|
||||
* The player signs through `crypto.subtle` (`@ludus/identity`'s `sign`, because
|
||||
* a WebCrypto key can be non-extractable and a JavaScript one cannot). The relay
|
||||
* verifies with `@noble/curves`, because it runs in Node and has no key material
|
||||
* of its own to protect.
|
||||
*
|
||||
* Two implementations of the same algorithm are a place where a signature can
|
||||
* fail for a reason that has nothing to do with an attacker — a PKCS#8 wrapper,
|
||||
* a byte order, a hash choice — and the symptom would be indistinguishable from
|
||||
* a hostile client. So this test does the player's half with Node's own
|
||||
* WebCrypto, which is the same API `@ludus/identity` calls, and hands the result
|
||||
* to the relay's real gate.
|
||||
*
|
||||
* It does NOT import `@ludus/identity`: the relay may import `@ludus/schema` and
|
||||
* nothing else from this repository (CLAUDE.md §2). What it shares with the
|
||||
* player is the part that matters — `submissionBytes`, the one canonical
|
||||
* encoding, which now lives in `@ludus/schema` for exactly this reason.
|
||||
*/
|
||||
import { webcrypto } from 'node:crypto';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { submissionBytes } from '@ludus/schema';
|
||||
import { DEFAULT_RELAY_CONFIG } from '../src/config.js';
|
||||
import { checkSubmission } from '../src/verify.js';
|
||||
|
||||
const subtle = webcrypto.subtle;
|
||||
|
||||
function toBase64Url(bytes: Uint8Array): string {
|
||||
return Buffer.from(bytes).toString('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw 32-byte public key from a WebCrypto Ed25519 key.
|
||||
*
|
||||
* `spki` is what WebCrypto exports; the last 32 bytes of it are the key. The
|
||||
* 12-byte prefix is the fixed ASN.1 header for Ed25519 — same family of detail
|
||||
* as the PKCS#8 wrapper in `@ludus/identity`, and the same place this goes
|
||||
* wrong.
|
||||
*/
|
||||
async function rawPublicKey(key: CryptoKey): Promise<Uint8Array> {
|
||||
const spki = new Uint8Array(await subtle.exportKey('spki', key));
|
||||
return spki.slice(spki.length - 32);
|
||||
}
|
||||
|
||||
describe('WebCrypto signs, @noble verifies', () => {
|
||||
it('accepts a submission signed the way the player signs it', async () => {
|
||||
const pair = (await subtle.generateKey({ name: 'Ed25519' }, true, [
|
||||
'sign',
|
||||
'verify'
|
||||
])) as CryptoKeyPair;
|
||||
|
||||
const pubkey = toBase64Url(await rawPublicKey(pair.publicKey));
|
||||
const fields = {
|
||||
pubkey,
|
||||
displayName: 'mnovak',
|
||||
leagueId: 'domus.eng',
|
||||
weekId: '2026-W34',
|
||||
xp: 1240
|
||||
};
|
||||
|
||||
const signature = new Uint8Array(
|
||||
await subtle.sign({ name: 'Ed25519' }, pair.privateKey, submissionBytes(fields))
|
||||
);
|
||||
|
||||
const result = checkSubmission(
|
||||
{ ...fields, sig: toBase64Url(signature) },
|
||||
{ currentWeekId: '2026-W34', config: DEFAULT_RELAY_CONFIG }
|
||||
);
|
||||
|
||||
expect(result.ok, result.ok ? '' : result.error.message).toBe(true);
|
||||
});
|
||||
|
||||
it('still rejects a WebCrypto-signed submission that was altered afterwards', async () => {
|
||||
// The interop test must not become a test that accepts everything. Same
|
||||
// key, same real signature, one field changed after signing.
|
||||
const pair = (await subtle.generateKey({ name: 'Ed25519' }, true, [
|
||||
'sign',
|
||||
'verify'
|
||||
])) as CryptoKeyPair;
|
||||
|
||||
const pubkey = toBase64Url(await rawPublicKey(pair.publicKey));
|
||||
const fields = {
|
||||
pubkey,
|
||||
displayName: 'mnovak',
|
||||
leagueId: 'domus.eng',
|
||||
weekId: '2026-W34',
|
||||
xp: 1240
|
||||
};
|
||||
const signature = new Uint8Array(
|
||||
await subtle.sign({ name: 'Ed25519' }, pair.privateKey, submissionBytes(fields))
|
||||
);
|
||||
|
||||
const result = checkSubmission(
|
||||
{ ...fields, xp: 4999, sig: toBase64Url(signature) },
|
||||
{ currentWeekId: '2026-W34', config: DEFAULT_RELAY_CONFIG }
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-signature');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* 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/<id>', () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* The database.
|
||||
*
|
||||
* The first two tests are the most valuable in this service and are the reason
|
||||
* the file exists: they read the schema back out of SQLite and assert that it
|
||||
* has SIX columns in ONE table. CLAUDE.md §4 says a seventh column is a design
|
||||
* discussion rather than a migration, and a rule with no test behind it is a
|
||||
* rule that erodes on a busy afternoon.
|
||||
*
|
||||
* Every database here is `:memory:`. Nothing touches a real deployment, a real
|
||||
* key, or anyone's history (CLAUDE.md §5.5).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { PARTICIPANT_COLUMNS, RelayStore } from '../src/store.js';
|
||||
import type { AcceptedSubmission } from '../src/verify.js';
|
||||
import { keyFor } from './helpers.js';
|
||||
|
||||
let store: RelayStore;
|
||||
|
||||
beforeEach(() => {
|
||||
store = RelayStore.open(':memory:');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// In `afterEach` rather than at the end of each test: a failing assertion
|
||||
// returns first, so cleanup on the happy path leaks exactly when it fails
|
||||
// (CLAUDE.md §5.7).
|
||||
store.close();
|
||||
});
|
||||
|
||||
function accepted(overrides: Partial<AcceptedSubmission> = {}): AcceptedSubmission {
|
||||
return {
|
||||
pubkey: keyFor(1).pubkey,
|
||||
displayName: 'tereza',
|
||||
leagueId: 'domus.eng',
|
||||
weekId: '2026-W34',
|
||||
xp: 1240,
|
||||
clamped: false,
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('the schema is the promise', () => {
|
||||
it('has exactly the six columns CLAUDE.md §4 names, and no seventh', () => {
|
||||
expect(store.columns()).toEqual([...PARTICIPANT_COLUMNS]);
|
||||
expect(store.columns()).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('has exactly one table, so there is nothing to join to', () => {
|
||||
expect(store.tables()).toEqual(['participants']);
|
||||
});
|
||||
|
||||
it('names no column that could identify a connection', () => {
|
||||
// Stated as a deny-list as well as an allow-list, because the allow-list
|
||||
// test passes if someone renames a column rather than adding one.
|
||||
const forbidden = ['ip', 'addr', 'address', 'agent', 'referer', 'referrer', 'host', 'session'];
|
||||
for (const column of store.columns()) {
|
||||
for (const word of forbidden) {
|
||||
expect(column.includes(word), `column \`${column}\` looks like ${word}`).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a value of the wrong type, because the table is STRICT', () => {
|
||||
// Without STRICT, SQLite puts the string "lots" in an INTEGER column
|
||||
// happily — which is exactly what untrusted input turns up to do.
|
||||
expect(() =>
|
||||
store.record({ ...accepted(), xp: 'lots' as unknown as number }, 1)
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('recording a standing', () => {
|
||||
it('keeps ONE row per participant, however many times they submit', () => {
|
||||
const key = keyFor(1);
|
||||
store.record(accepted({ pubkey: key.pubkey, xp: 100 }), 1);
|
||||
store.record(accepted({ pubkey: key.pubkey, xp: 400 }), 2);
|
||||
store.record(accepted({ pubkey: key.pubkey, xp: 900 }), 3);
|
||||
|
||||
expect(store.count()).toBe(1);
|
||||
expect(store.board('domus.eng', '2026-W34', 10).rows[0]?.xp).toBe(900);
|
||||
});
|
||||
|
||||
it('accumulates no history — last week is overwritten, not archived', () => {
|
||||
const key = keyFor(1);
|
||||
store.record(accepted({ pubkey: key.pubkey, weekId: '2026-W34', xp: 1200 }), 1);
|
||||
store.record(accepted({ pubkey: key.pubkey, weekId: '2026-W35', xp: 30 }), 2);
|
||||
|
||||
expect(store.count()).toBe(1);
|
||||
// The old week is GONE. This is the privacy property: the relay's disk
|
||||
// never holds a record of which weeks a person studied.
|
||||
expect(store.board('domus.eng', '2026-W34', 10).rows).toHaveLength(0);
|
||||
expect(store.board('domus.eng', '2026-W35', 10).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('accepts a lower XP than last time', () => {
|
||||
// A learner who moves to a second device legitimately submits a smaller
|
||||
// number. A monotonicity rule would break that honest case to slow down a
|
||||
// dishonest one who can simply submit the larger number instead.
|
||||
const key = keyFor(1);
|
||||
store.record(accepted({ pubkey: key.pubkey, xp: 900 }), 1);
|
||||
store.record(accepted({ pubkey: key.pubkey, xp: 120 }), 2);
|
||||
expect(store.board('domus.eng', '2026-W34', 10).rows[0]?.xp).toBe(120);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reading a board', () => {
|
||||
it('ranks by XP, highest first', () => {
|
||||
store.record(accepted({ pubkey: keyFor(1).pubkey, displayName: 'a', xp: 300 }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(2).pubkey, displayName: 'b', xp: 900 }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(3).pubkey, displayName: 'c', xp: 600 }), 1);
|
||||
|
||||
const board = store.board('domus.eng', '2026-W34', 10);
|
||||
expect(board.rows.map((r) => r.displayName)).toEqual(['b', 'c', 'a']);
|
||||
expect(board.rows.map((r) => r.rank)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('breaks ties deterministically, so ranks do not shuffle between reads', () => {
|
||||
store.record(accepted({ pubkey: keyFor(1).pubkey, displayName: 'one', xp: 500 }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(2).pubkey, displayName: 'two', xp: 500 }), 1);
|
||||
|
||||
const first = store.board('domus.eng', '2026-W34', 10);
|
||||
const second = store.board('domus.eng', '2026-W34', 10);
|
||||
expect(first.rows.map((r) => r.pubkey)).toEqual(second.rows.map((r) => r.pubkey));
|
||||
});
|
||||
|
||||
it('never serves the last-submission timestamp to other participants', () => {
|
||||
// Stored so the relay can forget rows that stopped arriving; NOT served,
|
||||
// because "she last studied at 02:14" is a fact about a person's night that
|
||||
// a leaderboard has no business publishing.
|
||||
store.record(accepted(), 1_755_600_000_000);
|
||||
const row = store.board('domus.eng', '2026-W34', 10).rows[0];
|
||||
expect(row).toBeDefined();
|
||||
expect(Object.keys(row as object).sort()).toEqual(['displayName', 'pubkey', 'rank', 'xp']);
|
||||
});
|
||||
|
||||
it('shows only the league that was asked for', () => {
|
||||
store.record(accepted({ pubkey: keyFor(1).pubkey, leagueId: 'domus.eng' }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(2).pubkey, leagueId: 'somewhere.else' }), 1);
|
||||
expect(store.board('domus.eng', '2026-W34', 10).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('shows only the week that was asked for, mid-rollover', () => {
|
||||
// In the first hours of a new week the table holds a mixture: people who
|
||||
// have submitted, and people who have not and still carry last week's row.
|
||||
// Filtering is what makes that mixture harmless.
|
||||
store.record(accepted({ pubkey: keyFor(1).pubkey, weekId: '2026-W34', xp: 5000 }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(2).pubkey, weekId: '2026-W35', xp: 20 }), 1);
|
||||
|
||||
const board = store.board('domus.eng', '2026-W35', 10);
|
||||
expect(board.rows).toHaveLength(1);
|
||||
expect(board.rows[0]?.xp).toBe(20);
|
||||
});
|
||||
|
||||
it('honours the row limit', () => {
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
store.record(accepted({ pubkey: keyFor(i).pubkey, xp: i * 10 }), 1);
|
||||
}
|
||||
expect(store.board('domus.eng', '2026-W34', 3).rows).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('returns an empty board rather than failing, for a league nobody joined', () => {
|
||||
const board = store.board('nobody.here', '2026-W34', 10);
|
||||
expect(board.rows).toEqual([]);
|
||||
expect(board.leagueId).toBe('nobody.here');
|
||||
});
|
||||
});
|
||||
|
||||
describe('forgetting', () => {
|
||||
it('drops rows for every week but the one named', () => {
|
||||
store.record(accepted({ pubkey: keyFor(1).pubkey, weekId: '2026-W33' }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(2).pubkey, weekId: '2026-W34' }), 1);
|
||||
store.record(accepted({ pubkey: keyFor(3).pubkey, weekId: '2026-W35' }), 1);
|
||||
|
||||
expect(store.forgetOtherWeeks('2026-W34')).toBe(2);
|
||||
expect(store.count()).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* The gate.
|
||||
*
|
||||
* The two tests this file exists for are `rejects a submission whose signature
|
||||
* does not match` and `rejects a submission for a week that is not current`.
|
||||
* Everything else is the surrounding fence.
|
||||
*
|
||||
* REGRESSION HONESTY. Both were verified by breaking the code, not by watching
|
||||
* them go green: with the `ed25519.verify` call replaced by `true`, the
|
||||
* tampered-field and wrong-key cases fail; with the `weekIdField.value !==
|
||||
* currentWeekId` comparison removed, the two stale-week cases fail. Recorded
|
||||
* here because a test whose failure mode nobody has seen is a test nobody knows
|
||||
* the meaning of (CLAUDE.md §5.3).
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
import { submissionBytes } from '@ludus/schema';
|
||||
import { DEFAULT_RELAY_CONFIG, relayConfig } from '../src/config.js';
|
||||
import { checkSubmission } from '../src/verify.js';
|
||||
import { keyFor, signedSubmission, toBase64Url } from './helpers.js';
|
||||
|
||||
const WEEK = '2026-W34';
|
||||
const opts = { currentWeekId: WEEK, config: DEFAULT_RELAY_CONFIG };
|
||||
|
||||
describe('checkSubmission — the happy day', () => {
|
||||
it('accepts a correctly signed submission for the current week', () => {
|
||||
const result = checkSubmission(signedSubmission(keyFor(1)), opts);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.xp).toBe(1240);
|
||||
expect(result.value.clamped).toBe(false);
|
||||
expect(result.value.displayName).toBe('tereza');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkSubmission — the signature', () => {
|
||||
it('rejects a submission whose signature does not match the fields', () => {
|
||||
// The exact attack the check exists for: take a valid submission and raise
|
||||
// the XP. Every other field, including the signature, is untouched and
|
||||
// authentic.
|
||||
const honest = signedSubmission(keyFor(1), { xp: 1240 });
|
||||
const tampered = { ...honest, xp: 999_999 };
|
||||
|
||||
const result = checkSubmission(tampered, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-signature');
|
||||
});
|
||||
|
||||
it('rejects a submission tampered in a field nobody thinks about', () => {
|
||||
// `displayName` is signed too, so it cannot be swapped in flight — which is
|
||||
// what stops a relay from being a way to relabel someone else's score.
|
||||
const honest = signedSubmission(keyFor(1), { displayName: 'tereza' });
|
||||
const result = checkSubmission({ ...honest, displayName: 'not-tereza' }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-signature');
|
||||
});
|
||||
|
||||
it('rejects a submission signed by a different key than the one it claims', () => {
|
||||
const impostor = keyFor(2);
|
||||
const victim = keyFor(1);
|
||||
const fields = {
|
||||
pubkey: victim.pubkey,
|
||||
displayName: 'tereza',
|
||||
leagueId: 'domus.eng',
|
||||
weekId: WEEK,
|
||||
xp: 4000
|
||||
};
|
||||
// Genuinely signed — just not by the key in `pubkey`.
|
||||
const sig = toBase64Url(ed25519.sign(submissionBytes(fields), impostor.privateKey));
|
||||
|
||||
const result = checkSubmission({ ...fields, sig }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-signature');
|
||||
});
|
||||
|
||||
it('rejects a signature of the right shape that is simply wrong', () => {
|
||||
const honest = signedSubmission(keyFor(1));
|
||||
const sig = toBase64Url(new Uint8Array(64).fill(7));
|
||||
const result = checkSubmission({ ...honest, sig }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-signature');
|
||||
});
|
||||
|
||||
it('rejects a signature that is not 64 bytes', () => {
|
||||
const honest = signedSubmission(keyFor(1));
|
||||
const result = checkSubmission({ ...honest, sig: toBase64Url(new Uint8Array(32)) }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-signature');
|
||||
});
|
||||
|
||||
it('rejects a pubkey that is not 32 bytes, before it reaches the curve', () => {
|
||||
const honest = signedSubmission(keyFor(1));
|
||||
const result = checkSubmission({ ...honest, pubkey: toBase64Url(new Uint8Array(16)) }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-pubkey');
|
||||
});
|
||||
|
||||
it('rejects a pubkey that is not base64url at all', () => {
|
||||
// `Buffer.from(_, 'base64')` does not throw on rubbish, it skips what it
|
||||
// cannot read — so without the character-class test this decodes to
|
||||
// something short and is reported as the wrong problem, or worse, as none.
|
||||
const honest = signedSubmission(keyFor(1));
|
||||
const result = checkSubmission({ ...honest, pubkey: '!!!!not a key!!!!' }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-pubkey');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkSubmission — the week', () => {
|
||||
it('rejects a submission for a week that has passed', () => {
|
||||
const stale = signedSubmission(keyFor(1), { weekId: '2026-W33' });
|
||||
const result = checkSubmission(stale, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/stale-week');
|
||||
// The message has to name BOTH weeks, because the client's only repair is
|
||||
// to re-derive its week — and it cannot do that without knowing the relay's.
|
||||
expect(result.error.message).toContain('2026-W34');
|
||||
expect(result.error.message).toContain('2026-W33');
|
||||
});
|
||||
|
||||
it('rejects a submission for a week that has not arrived', () => {
|
||||
const early = signedSubmission(keyFor(1), { weekId: '2026-W35' });
|
||||
const result = checkSubmission(early, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/stale-week');
|
||||
});
|
||||
|
||||
it('rejects a stale week BEFORE spending a signature verification on it', () => {
|
||||
// Ordering matters: verifying Ed25519 is the most expensive thing this
|
||||
// process does, and replaying last week's genuine traffic would otherwise
|
||||
// buy an attacker unlimited CPU with valid signatures.
|
||||
//
|
||||
// The observable proof is that a submission which is BOTH stale and
|
||||
// unsigned-nonsense reports the week, not the signature.
|
||||
const stale = signedSubmission(keyFor(1), { weekId: '2026-W33' });
|
||||
const result = checkSubmission({ ...stale, sig: toBase64Url(new Uint8Array(64)) }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/stale-week');
|
||||
});
|
||||
|
||||
it('rejects a weekId that is not a week id', () => {
|
||||
const result = checkSubmission({ ...signedSubmission(keyFor(1)), weekId: 'lastweek' }, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-field');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkSubmission — the XP ceiling', () => {
|
||||
it('clamps rather than rejects, and says that it clamped', () => {
|
||||
const greedy = signedSubmission(keyFor(1), { xp: 8_000_000 });
|
||||
const result = checkSubmission(greedy, opts);
|
||||
// Accepted, because rejecting would cost an honest heavy user their week.
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.xp).toBe(DEFAULT_RELAY_CONFIG.xpCeiling);
|
||||
expect(result.value.clamped).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves a submission exactly at the ceiling alone', () => {
|
||||
const config = relayConfig({ xpCeiling: 1240 });
|
||||
const result = checkSubmission(signedSubmission(keyFor(1), { xp: 1240 }), {
|
||||
currentWeekId: WEEK,
|
||||
config
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.xp).toBe(1240);
|
||||
expect(result.value.clamped).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects XP that is negative, fractional or not a number', () => {
|
||||
for (const xp of [-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, '1240' as unknown as number]) {
|
||||
const result = checkSubmission({ ...signedSubmission(keyFor(1)), xp }, opts);
|
||||
expect(result.ok, `xp=${String(xp)} should be rejected`).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkSubmission — the fields', () => {
|
||||
it('rejects a body that is not an object', () => {
|
||||
for (const body of [null, 42, 'submission', [signedSubmission(keyFor(1))]]) {
|
||||
const result = checkSubmission(body, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/malformed-body');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an unknown field rather than ignoring it', () => {
|
||||
// The shape is frozen at six keys (CLAUDE.md §6.3). A relay that silently
|
||||
// drops a seventh is a relay that will one day store a meaning it guessed.
|
||||
const result = checkSubmission(
|
||||
{ ...signedSubmission(keyFor(1)), ipAddress: '203.0.113.7' },
|
||||
opts
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/unknown-field');
|
||||
expect(result.error.message).toContain('ipAddress');
|
||||
});
|
||||
|
||||
it('rejects a display name longer than the relay accepts, without truncating', () => {
|
||||
const long = 'x'.repeat(DEFAULT_RELAY_CONFIG.displayNameMaxChars + 1);
|
||||
const result = checkSubmission(signedSubmission(keyFor(1), { displayName: long }), opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-field');
|
||||
// Truncating would change the bytes that were signed, so the stored row
|
||||
// would no longer match its own signature. Say so in the message.
|
||||
expect(result.error.message).toContain('shortened');
|
||||
});
|
||||
|
||||
it('rejects a newline in a signed string field', () => {
|
||||
// `\n` separates the fields inside `submissionBytes`. A name containing one
|
||||
// could be split into two by a chosen `leagueId`, so two DIFFERENT
|
||||
// submissions would produce identical signed bytes — a valid signature for
|
||||
// a submission nobody made.
|
||||
const sneaky = signedSubmission(keyFor(1), { displayName: 'tereza\ndomus.eng' });
|
||||
const result = checkSubmission(sneaky, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.code).toBe('relay/bad-field');
|
||||
});
|
||||
|
||||
it('demonstrates the collision the newline rule prevents', () => {
|
||||
// Without the rule these two submissions sign the same bytes: one claims
|
||||
// the name `tereza` in league `x\ndomus.eng`, the other the name
|
||||
// `tereza\nx` in league `domus.eng`.
|
||||
const a = submissionBytes({
|
||||
pubkey: 'k',
|
||||
displayName: 'tereza',
|
||||
leagueId: 'x\ndomus.eng',
|
||||
weekId: WEEK,
|
||||
xp: 10
|
||||
});
|
||||
const b = submissionBytes({
|
||||
pubkey: 'k',
|
||||
displayName: 'tereza\nx',
|
||||
leagueId: 'domus.eng',
|
||||
weekId: WEEK,
|
||||
xp: 10
|
||||
});
|
||||
expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects an empty display name or league id', () => {
|
||||
for (const field of ['displayName', 'leagueId'] as const) {
|
||||
const result = checkSubmission({ ...signedSubmission(keyFor(1)), [field]: '' }, opts);
|
||||
expect(result.ok, `empty ${field} should be rejected`).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a missing field', () => {
|
||||
const { sig: _sig, ...withoutSig } = signedSubmission(keyFor(1));
|
||||
const result = checkSubmission(withoutSig, opts);
|
||||
expect(result.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* The relay's week.
|
||||
*
|
||||
* Half of these are boundary cases that occur twice a year at most, which is
|
||||
* exactly why they are pinned here: a week-numbering bug is invisible for
|
||||
* eleven months and then rejects every submission in the first days of January.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { currentWeekId, isWeekIdShape } from '../src/week.js';
|
||||
|
||||
describe('currentWeekId', () => {
|
||||
it('numbers an ordinary mid-year week', () => {
|
||||
// Wednesday 2026-08-19 — the week the fixtures use.
|
||||
expect(currentWeekId(Date.UTC(2026, 7, 19, 12))).toBe('2026-W34');
|
||||
});
|
||||
|
||||
it('keeps Monday and the following Sunday in the same week', () => {
|
||||
const monday = Date.UTC(2026, 7, 17, 0, 0, 0);
|
||||
const sunday = Date.UTC(2026, 7, 23, 23, 59, 59);
|
||||
expect(currentWeekId(monday)).toBe(currentWeekId(sunday));
|
||||
});
|
||||
|
||||
it('rolls over at Monday 00:00 UTC and not a millisecond earlier', () => {
|
||||
const lastMs = Date.UTC(2026, 7, 23, 23, 59, 59, 999);
|
||||
const firstMs = Date.UTC(2026, 7, 24, 0, 0, 0, 0);
|
||||
expect(currentWeekId(lastMs)).toBe('2026-W34');
|
||||
expect(currentWeekId(firstMs)).toBe('2026-W35');
|
||||
});
|
||||
|
||||
it('puts early January into the PREVIOUS year when ISO says so', () => {
|
||||
// 2027-01-01 is a Friday, so it belongs to the week that started
|
||||
// 2026-12-28 — ISO week 53 of 2026. Deriving the year from the calendar
|
||||
// year is the classic bug and would call this `2027-W53`.
|
||||
expect(currentWeekId(Date.UTC(2027, 0, 1, 12))).toBe('2026-W53');
|
||||
});
|
||||
|
||||
it('puts late December into the NEXT year when ISO says so', () => {
|
||||
// 2025-12-29 is a Monday, and 2026-01-01 is a Thursday — so that week is
|
||||
// week 01 of 2026 even though three of its days are in 2025.
|
||||
expect(currentWeekId(Date.UTC(2025, 11, 29, 12))).toBe('2026-W01');
|
||||
});
|
||||
|
||||
it('zero-pads single-digit weeks', () => {
|
||||
expect(currentWeekId(Date.UTC(2026, 0, 8, 12))).toBe('2026-W02');
|
||||
});
|
||||
|
||||
it('accepts only the padded YYYY-Www shape', () => {
|
||||
expect(isWeekIdShape('2026-W34')).toBe(true);
|
||||
expect(isWeekIdShape('2026-W01')).toBe(true);
|
||||
expect(isWeekIdShape('2026-W53')).toBe(true);
|
||||
expect(isWeekIdShape('2026-W1')).toBe(false);
|
||||
expect(isWeekIdShape('2026-W00')).toBe(false);
|
||||
expect(isWeekIdShape('2026-W54')).toBe(false);
|
||||
expect(isWeekIdShape('2026-34')).toBe(false);
|
||||
// Anchoring. An unanchored pattern accepts this, and a week id is a key.
|
||||
expect(isWeekIdShape('x2026-W34y')).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user