[repo] Merge: feature/relay (The league relay from Ludus, public under CPAL-1.0, PR #1)

This commit was merged in pull request #1.
This commit is contained in:
2026-11-23 02:03:57 +01:00
29 changed files with 3705 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
dist/
*.db
*.db-wal
*.db-shm
+48
View File
@@ -0,0 +1,48 @@
# LudusPublic
The public parts of **Ludus**, a local-first learning app. Today that is one thing: **the league relay**, the
optional, self-hostable server a group of learners can run to share a weekly league board.
Ludus itself is private. The relay is public for one reason: it is the only part of Ludus that receives anything
from a learner's device, and a promise about what a server keeps is worth only as much as your ability to read the
server. So you can read it here, run it yourself, and check that it keeps what is listed below and nothing else.
## What the relay stores
One SQLite table with six columns and no joins: the participant's Ed25519 public key, the display name they chose,
the league, the ISO week, the XP (clamped to a weekly ceiling), and when the last submission arrived (stored, never
served). There is no IP address in any form, no user agent, no referrer, no request log, no cookie, no session, and
no history: one row per participant, replaced on every submission. `relay/test/store.test.ts` reads the schema back
out of SQLite and fails if a seventh column appears.
A submission's signature proves who sent it, not that the number is true. A client computes its own score and can
lie. The relay's defences are the cheap ones: a weekly XP ceiling, a current-week check, and leagues small enough
that the people in them know each other.
## Layout
| Folder | What |
| :-- | :-- |
| `relay/` | the relay: `src/bin.ts` starts it, `src/server.ts` serves it, `src/store.ts` keeps the six columns |
| `schema/` | the slice of Ludus's schema the relay imports (`@ludus/schema`): the league submission and the `Result` type |
```bash
pnpm install
pnpm test # the relay's tests
pnpm typecheck
pnpm --filter @ludus/relay start
```
## Where this code comes from
Ludus develops the relay in its private repository (`services/relay`). This repository carries the same files.
`relay/src`, `relay/test` and `schema/src/{league,result}.ts` are byte-for-byte copies, and a test in Ludus fails
if a copy here differs from the code Ludus ships. This repository started from Ludus at `52d7a0c` (2026-11-23).
## Licence
**CPAL-1.0** (Common Public Attribution License 1.0): see [`LICENSE`](LICENSE). Anyone who redistributes this code,
or runs it as a service for others, must show the Exhibit B credit: **Built on Domi**, linking to
https://aula.marek-novak.cz, with the notice *Copyright (c) 2026 Marek Novák*.
The dependencies keep their own licences (`@noble/curves` and `better-sqlite3`: MIT).
+13
View File
@@ -0,0 +1,13 @@
{
"name": "ludus-public",
"version": "0.1.0",
"private": true,
"license": "CPAL-1.0",
"type": "module",
"description": "The public parts of Ludus: the self-hostable league relay, and the slice of the schema it needs.",
"packageManager": "pnpm@9.12.3",
"scripts": {
"test": "pnpm -r test",
"typecheck": "pnpm -r typecheck"
}
}
+1347
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
packages:
- 'schema'
- 'relay'
+9
View File
@@ -0,0 +1,9 @@
# A relay's database is other people's public keys and chosen names. It is
# runtime state on whoever's machine is hosting, and it never enters git —
# same rule as `dist/`, for a stronger reason.
#
# WAL mode means three files, not one. Listing only `*.db` would leave the
# write-ahead log — which holds the same rows — untracked-but-committable.
*.db
*.db-wal
*.db-shm
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@ludus/relay",
"version": "0.1.0",
"private": true,
"license": "CPAL-1.0",
"type": "module",
"description": "OPTIONAL, self-hostable league relay. Six columns, one table, no joins. Deleting this directory must leave the player fully functional.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"bin": {
"ludus-relay": "./src/bin.ts"
},
"scripts": {
"build": "tsc -p tsconfig.json --noEmit",
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit",
"test": "vitest run --reporter=verbose",
"start": "tsx src/bin.ts"
},
"dependencies": {
"@ludus/schema": "workspace:*",
"@noble/curves": "^2.3.0",
"better-sqlite3": "^12.11.1"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^22.10.2",
"tsx": "^4.23.12",
"typescript": "^5.7.2",
"vitest": "^3.2.7"
}
}
+63
View File
@@ -0,0 +1,63 @@
/**
* `pnpm --filter @ludus/relay start` — run a relay.
*
* Configuration is environment variables and nothing else: no config file to
* leave lying around with a hostname in it, and no flags to get wrong at three
* in the morning.
*
* LUDUS_RELAY_HOST default 127.0.0.1 — see the binding note below
* LUDUS_RELAY_PORT default 8787
* LUDUS_RELAY_DB default ./ludus-relay.db
* LUDUS_RELAY_XP_CEILING default 5000
*
* THE DEFAULT HOST IS LOOPBACK ON PURPOSE. A relay belongs behind a reverse
* proxy that terminates TLS; `POST /submit` is unauthenticated by design (the
* authentication is the signature in the body, not the connection), so a
* default of `0.0.0.0` would put a write endpoint on every interface of
* whatever machine someone typed `start` on. Setting it is a decision a human
* makes once, in an env file, next to the proxy they configured.
*/
import { relayConfig } from './config.js';
import { startRelay } from './server.js';
import { RelayStore } from './store.js';
import { currentWeekId } from './week.js';
function intFromEnv(name: string, fallback: number): number {
const raw = process.env[name];
if (raw === undefined || raw.trim() === '') return fallback;
const value = Number(raw);
if (!Number.isInteger(value) || value < 0) {
// Refuse rather than fall back. A typo in `LUDUS_RELAY_XP_CEILING` that
// silently became 5000 would be discovered by a participant, not by an
// operator.
console.error(`[relay] ${name} must be a non-negative integer; got ${JSON.stringify(raw)}.`);
process.exit(1);
}
return value;
}
const host = process.env['LUDUS_RELAY_HOST'] ?? '127.0.0.1';
const port = intFromEnv('LUDUS_RELAY_PORT', 8787);
const dbPath = process.env['LUDUS_RELAY_DB'] ?? './ludus-relay.db';
const config = relayConfig({ xpCeiling: intFromEnv('LUDUS_RELAY_XP_CEILING', 5000) });
const store = RelayStore.open(dbPath);
const running = await startRelay({ store, config, host, port });
// The only two lines this process writes on a good day. Neither contains
// anything about anybody: a week id, a bind address a human chose, and the
// column list, printed so an operator can see the promise rather than read it.
console.log(
`[relay] listening on http://${host}:${running.port} · week ${currentWeekId(Date.now())} · db ${dbPath}`
);
console.log('[relay] stores: pubkey, display name, league id, week id, xp, last-submission time. Nothing else.');
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => {
void running.close().then(() => {
store.close();
console.log('[relay] stopped.');
process.exit(0);
});
});
}
+73
View File
@@ -0,0 +1,73 @@
/**
* What a relay will accept. Policy, not contract.
*
* The submission *shape* is `@ludus/schema`'s and is the same everywhere. These
* limits are this relay's opinion, and a self-hoster is entitled to a different
* one — which is the point of the service being ~400 lines and self-hostable.
*
* Every value here is a CHEAP defence. Read `SIGNATURE_PROVES` in
* `@ludus/schema` before adding an expensive one: a local-first client computes
* its own score, so it can lie, and a defence that implies otherwise is worse
* than no defence at all (CLAUDE.md §6.3).
*/
export interface RelayConfig {
/**
* Hard ceiling on the XP one participant may hold in one week.
*
* Submissions above it are CLAMPED, not rejected. Rejecting would punish an
* honest heavy user with a lost week; clamping bounds what a dishonest one
* gains, which is all a ceiling can do.
*
* The number is derived from the session contract rather than picked: six to
* eight items a day (`SESSION_MIN_ITEMS`/`SESSION_MAX_ITEMS`) at roughly 20 XP
* an item is ~160 XP on a full day, ~1 120 in a week. 5 000 leaves room for
* bonuses, catch-up days and a scoring change, and still makes "I earned
* 400 000 XP this week" impossible to submit.
*/
readonly xpCeiling: number;
/**
* Longest display name stored, in UTF-16 code units.
*
* A relay serves this string back to every other participant in the league.
* It is untrusted text from an anonymous device, so it is bounded here and
* refused — not truncated — above the bound: truncating changes the bytes that
* were signed, and the row would then disagree with its own signature.
*/
readonly displayNameMaxChars: number;
/** Longest league id accepted. Ids are chosen by whoever runs the league. */
readonly leagueIdMaxChars: number;
/**
* Largest request body read, in bytes.
*
* A submission is a few hundred bytes. The cap exists so an unauthenticated
* POST cannot make the process buffer a gigabyte; the connection is closed as
* soon as the limit is passed rather than after the body finishes arriving.
*/
readonly maxBodyBytes: number;
/**
* Most rows one board read returns.
*
* A league is a cohort of ~30 by design — an empty-looking global board with
* eleven people on it is worse than no board (CLAUDE.md §8). The cap is
* generous rather than exact so that a self-hoster running larger cohorts is
* not silently truncated at a number they never chose.
*/
readonly boardMaxRows: number;
}
export const DEFAULT_RELAY_CONFIG: RelayConfig = {
xpCeiling: 5_000,
displayNameMaxChars: 32,
leagueIdMaxChars: 64,
maxBodyBytes: 8 * 1024,
boardMaxRows: 200
};
export function relayConfig(overrides: Partial<RelayConfig> = {}): RelayConfig {
return { ...DEFAULT_RELAY_CONFIG, ...overrides };
}
+29
View File
@@ -0,0 +1,29 @@
/**
* @ludus/relay — the OPTIONAL league relay.
*
* ══════════════════════════════════════════════════════════════════════════
* THIS DIRECTORY MUST STAY DELETABLE.
* ══════════════════════════════════════════════════════════════════════════
*
* If removing `services/relay` breaks the player, the social layer has stopped
* being optional and that is a blocker finding (CLAUDE.md §2, `docs/ROADMAP.md`
* §4 Phase 5 gate). Nothing under `apps/` or `packages/` may import this
* package, and `test/deletable.test.ts` asserts that by reading the tree rather
* than by trusting the rule.
*
* The dependency runs one way and one way only: this service imports
* `@ludus/schema` for the submission shape, and never `@ludus/engine`. It holds
* no opinion about learning — no grading, no scheduling, no XP arithmetic. XP
* arrives as an integer somebody else computed, and this service's entire
* relationship with it is a ceiling.
*/
export { DEFAULT_RELAY_CONFIG, relayConfig, type RelayConfig } from './config.js';
export { RelayStore, PARTICIPANT_COLUMNS, type Board, type BoardRow } from './store.js';
export { checkSubmission, type AcceptedSubmission } from './verify.js';
export { currentWeekId, isWeekIdShape } from './week.js';
export {
relayHandler,
startRelay,
type RelayServerOptions,
type RunningRelay
} from './server.js';
+308
View File
@@ -0,0 +1,308 @@
/**
* The HTTP surface. Three routes, and one of them writes.
*
* ══════════════════════════════════════════════════════════════════════════
* WHAT THIS PROCESS LOGS: server faults, and nothing else.
* ══════════════════════════════════════════════════════════════════════════
*
* Not the remote address, not the user agent, not the referrer, not the path,
* not the pubkey, not a rejection, not a count of rejections. CLAUDE.md §5.6
* rule 7 says the relay stores what §4 lists and nothing else, and a line in a
* log file is storage — it is on the same disk, it survives a restart, and it
* is the thing an operator actually greps.
*
* A rejection is reported to the ONE party entitled to know about it: the
* submitter, in the response body, with the reason named. That is not an error
* being swallowed (CLAUDE.md §7) — it is an error being delivered to the person
* who can act on it, which is the whole point of the typed `Result`.
*
* An unexpected exception IS logged, with its stack and without the request,
* because a self-hoster whose relay is 500ing has to be able to find out why.
*
* ── Binding ──────────────────────────────────────────────────────────────
* The default host is `127.0.0.1`. A relay is meant to sit behind a reverse
* proxy that terminates TLS; binding `0.0.0.0` by default would put an
* unauthenticated write endpoint on every interface of whatever machine ran
* `pnpm start`, including a laptop on a café network. Nothing in this
* repository listens on anything but loopback unless a human typed the address
* (CLAUDE.md §5.7).
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { ludusError, type LudusError } from '@ludus/schema';
import { DEFAULT_RELAY_CONFIG, type RelayConfig } from './config.js';
import { RelayStore } from './store.js';
import { checkSubmission } from './verify.js';
import { currentWeekId } from './week.js';
export interface RelayServerOptions {
readonly store: RelayStore;
readonly config?: RelayConfig;
/**
* The clock, injected.
*
* Not for purity theatre — the week boundary and the stored timestamp are the
* two things this service gets wrong in ways nobody notices, and a test that
* cannot move the clock cannot cover either.
*/
readonly now?: () => number;
}
/**
* CORS: open, and credential-free.
*
* `*` because a relay is a public board and any player build may read it; no
* `Access-Control-Allow-Credentials`, because there are no credentials — no
* cookie is ever set, no session exists, and authentication is a signature
* inside the body rather than anything the browser attaches automatically. An
* open origin plus credentials would be the dangerous combination; open alone
* on a resource with no ambient authority is not.
*/
const CORS_HEADERS: Readonly<Record<string, string>> = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, OPTIONS',
'access-control-allow-headers': 'content-type',
'access-control-max-age': '86400'
};
function send(res: ServerResponse, status: number, body: unknown): void {
const payload = JSON.stringify(body);
res.writeHead(status, {
...CORS_HEADERS,
'content-type': 'application/json; charset=utf-8',
'content-length': Buffer.byteLength(payload),
// A board is current-week data that changes on every submission, and the
// relay is the only thing that knows when. Nothing here is cacheable.
'cache-control': 'no-store',
// Belt and braces on a JSON-only surface: neither header should matter
// because nothing is ever served as HTML, and both are free.
'x-content-type-options': 'nosniff',
'referrer-policy': 'no-referrer'
});
res.end(payload);
}
function sendError(res: ServerResponse, status: number, error: LudusError): void {
send(res, status, { ok: false, error: { code: error.code, message: error.message } });
}
/**
* Read a request body, refusing anything over the cap.
*
* The connection is destroyed the moment the limit is passed, not after the
* body finishes arriving — otherwise the cap describes what is parsed rather
* than what is buffered, and an unauthenticated POST can still make the process
* hold a gigabyte.
*/
function readBody(req: IncomingMessage, maxBytes: number): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
req.on('data', (chunk: Buffer) => {
size += chunk.length;
if (size > maxBytes) {
req.destroy();
reject(
ludusError(
'relay/body-too-large',
`A submission is a few hundred bytes; this relay reads at most ${maxBytes}.`
)
);
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', (cause) =>
reject(ludusError('relay/read-failed', 'The request body could not be read.', {
detail: { reason: String(cause) }
}))
);
});
}
function isLudusError(value: unknown): value is LudusError {
return typeof value === 'object' && value !== null && 'code' in value && 'message' in value;
}
/**
* Build the request handler.
*
* Exported separately from `startRelay` so a test can drive it through a real
* socket without a test needing to know a port number, and so a self-hoster who
* already runs an HTTP server can mount it.
*/
export function relayHandler(options: RelayServerOptions) {
const config = options.config ?? DEFAULT_RELAY_CONFIG;
const now = options.now ?? Date.now;
const { store } = options;
return async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
try {
if (req.method === 'OPTIONS') {
res.writeHead(204, CORS_HEADERS);
res.end();
return;
}
// `req.url` is a path with an optional query, never an absolute URL for a
// normal request. The base is a placeholder that is never contacted; it
// exists because `URL` refuses a relative input without one.
const url = new URL(req.url ?? '/', 'http://relay.invalid');
const week = currentWeekId(now());
if (req.method === 'GET' && url.pathname === '/health') {
// Deliberately thin. It publishes the relay's WEEK, because a client
// whose local week disagrees needs somewhere to read the authoritative
// one (see `week.ts`), and its LIMITS, so a client can tell the user
// what will happen before it submits. It publishes no counts of
// anything and no uptime.
send(res, 200, {
ok: true,
weekId: week,
xpCeiling: config.xpCeiling,
displayNameMaxChars: config.displayNameMaxChars,
// Said in the protocol, not only in the README, because a client
// author reads this and a README is optional.
signatureProves: 'who submitted, not that the number is true'
});
return;
}
if (req.method === 'GET' && url.pathname.startsWith('/league/')) {
const leagueId = decodeURIComponent(url.pathname.slice('/league/'.length));
if (leagueId === '' || leagueId.length > config.leagueIdMaxChars) {
sendError(
res,
400,
ludusError(
'relay/bad-league-id',
`A league id is 1 to ${config.leagueIdMaxChars} characters.`
)
);
return;
}
// Always the CURRENT week. There is no way to ask for a past one,
// because there is no past one — the relay keeps no history.
send(res, 200, { ok: true, ...store.board(leagueId, week, config.boardMaxRows) });
return;
}
if (req.method === 'POST' && url.pathname === '/submit') {
const raw = await readBody(req, config.maxBodyBytes);
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (cause) {
sendError(
res,
400,
ludusError('relay/malformed-body', 'The request body is not valid JSON.', {
// The parser's own message, which names the offset. NOT the body:
// echoing untrusted input back into a response is how a reflected
// payload gets a delivery mechanism.
detail: { reason: String(cause) }
})
);
return;
}
const checked = checkSubmission(parsed, { currentWeekId: week, config });
if (!checked.ok) {
// 409 for a stale week: the submission is well-formed and correctly
// signed, and the only thing wrong with it is WHEN. A client can act
// on that (re-derive the week from /health and resubmit) in a way it
// cannot act on a 400.
const status = checked.error.code === 'relay/stale-week' ? 409 : 400;
sendError(res, status, checked.error);
return;
}
store.record(checked.value, now());
send(res, 200, {
ok: true,
weekId: week,
// What was actually STORED, and whether it differs from what was
// sent. A client that submitted 400 000 and was silently recorded at
// 5 000 would show its user a number that is not on the board.
xp: checked.value.xp,
clamped: checked.value.clamped
});
return;
}
sendError(
res,
404,
ludusError(
'relay/no-such-route',
'This relay serves GET /health, GET /league/<id> and POST /submit.'
)
);
} catch (cause) {
if (isLudusError(cause)) {
// A body that was too large or unreadable. Named, and reported to the
// submitter rather than logged.
sendError(res, 413, cause);
return;
}
// A genuine bug. Logged with its stack and WITHOUT the request, because a
// self-hoster whose relay is 500ing must be able to find out why, and
// because the request is the part that identifies a person.
console.error('[relay] unhandled fault:', cause);
if (!res.headersSent) {
sendError(res, 500, ludusError('relay/fault', 'The relay failed to handle this request.'));
} else {
res.end();
}
}
};
}
export interface RunningRelay {
readonly server: Server;
readonly port: number;
close(): Promise<void>;
}
/**
* Start a relay.
*
* Port `0` asks the OS for a free one, which is what the tests use — a fixed
* test port is a test that fails when the developer happens to be running the
* real thing.
*/
export function startRelay(
options: RelayServerOptions & { readonly host?: string; readonly port?: number }
): Promise<RunningRelay> {
const handler = relayHandler(options);
const server = createServer((req, res) => {
void handler(req, res);
});
const host = options.host ?? '127.0.0.1';
const port = options.port ?? 0;
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, host, () => {
const address = server.address();
const boundPort = typeof address === 'object' && address !== null ? address.port : port;
resolve({
server,
port: boundPort,
close: () =>
new Promise<void>((done, fail) => {
server.close((cause) => (cause ? fail(cause) : done()));
// Sockets kept alive by an agent would otherwise hold the process
// open past `close()`, and a test that leaks a listener is a test
// that hangs the suite it is in (CLAUDE.md §5.7).
server.closeAllConnections();
})
});
});
});
}
+220
View File
@@ -0,0 +1,220 @@
/**
* The database. ONE table, SIX columns, NO joins.
*
* ══════════════════════════════════════════════════════════════════════════
* THE COLUMN LIST IS THE PRODUCT. Everything else here is plumbing.
* ══════════════════════════════════════════════════════════════════════════
*
* CLAUDE.md §4 fixes what a relay holds per participant: public key, chosen
* display name, league id, week id, XP integer, and the timestamp of the last
* submission. Six. It has no other columns and no join to anything, and a
* seventh column is a design discussion, not a migration.
*
* What is deliberately absent, so that nobody has to infer it from silence:
*
* - no IP address, ever, in any form, hashed or otherwise
* - no user agent, no referrer, no `Accept-Language`
* - no request log, no access log, no error log carrying a request in it
* - no history: last week's row is OVERWRITTEN, not archived
* - no per-submission timing beyond the single `last_seen_ms` above
* - no analytics, not aggregate, not anonymised, not behind a toggle
*
* `services/relay/test/store.test.ts` asserts the column list and the table
* count directly against `PRAGMA table_info` and `sqlite_master`, so a seventh
* column fails a test rather than passing a review.
*
* WHY `PRIMARY KEY (pubkey)` AND NOT `(pubkey, week_id)`.
*
* A composite key would let rows accumulate one per participant per week, which
* is a history — and a history of when a person was studying, week by week, is
* exactly the thing this product promises not to keep. One row per participant,
* replaced on every submission, means the relay's disk holds the current week
* and nothing else.
*
* The cost is stated plainly and is real: **this relay cannot compute promotion
* and relegation**, because that needs last week's standing and last week's
* standing is gone. See `.agents/features/014_league_relay.md` §4.
*/
import Database from 'better-sqlite3';
import type { AcceptedSubmission } from './verify.js';
/**
* The six columns, in order, as the migration writes them.
*
* Exported so the test can assert against this list rather than restating it —
* a test that restates the schema passes when both copies are wrong together.
*/
export const PARTICIPANT_COLUMNS = [
'pubkey',
'display_name',
'league_id',
'week_id',
'xp',
'last_seen_ms'
] as const;
/**
* `STRICT` is not decoration. Without it SQLite will happily put the string
* `"lots"` in an INTEGER column, which is precisely the kind of thing untrusted
* input arrives to do.
*/
const CREATE_TABLE = `
CREATE TABLE IF NOT EXISTS participants (
pubkey TEXT NOT NULL PRIMARY KEY,
display_name TEXT NOT NULL,
league_id TEXT NOT NULL,
week_id TEXT NOT NULL,
xp INTEGER NOT NULL,
last_seen_ms INTEGER NOT NULL
) STRICT;
`;
/** One row of a league board, as it is handed to a client. */
export interface BoardRow {
/** 1-based. Computed on read, never stored — a stored rank is a rank that lies. */
readonly rank: number;
readonly pubkey: string;
readonly displayName: string;
readonly xp: number;
}
export interface Board {
readonly leagueId: string;
readonly weekId: string;
readonly rows: readonly BoardRow[];
}
export class RelayStore {
readonly #db: Database.Database;
private constructor(db: Database.Database) {
this.#db = db;
// WAL so a read of the board does not block a submission. It is also the
// only pragma set here: everything else is SQLite's default on purpose.
this.#db.pragma('journal_mode = WAL');
this.#db.exec(CREATE_TABLE);
}
/**
* `':memory:'` for tests, a path for a real deployment.
*
* There is no migration framework and there is not going to be one. A schema
* with six frozen columns migrates by not changing.
*/
static open(path: string): RelayStore {
return new RelayStore(new Database(path));
}
/**
* Write a participant's standing, replacing whatever was there.
*
* `INSERT … ON CONFLICT DO UPDATE` rather than `INSERT OR REPLACE`: the latter
* DELETEs and re-INSERTs, which would fire delete triggers and renumber the
* rowid for no reason. This is one row, upserted.
*
* `xp` is written as submitted-then-clamped and is NOT required to increase.
* A learner who moves to a second device legitimately submits a smaller
* number, and a rule that refused it would break an honest case to slow down
* a dishonest one who can simply submit the larger number instead.
*/
record(submission: AcceptedSubmission, nowMs: number): void {
this.#db
.prepare(
`INSERT INTO participants (pubkey, display_name, league_id, week_id, xp, last_seen_ms)
VALUES (@pubkey, @displayName, @leagueId, @weekId, @xp, @nowMs)
ON CONFLICT(pubkey) DO UPDATE SET
display_name = excluded.display_name,
league_id = excluded.league_id,
week_id = excluded.week_id,
xp = excluded.xp,
last_seen_ms = excluded.last_seen_ms`
)
.run({
pubkey: submission.pubkey,
displayName: submission.displayName,
leagueId: submission.leagueId,
weekId: submission.weekId,
xp: submission.xp,
nowMs
});
}
/**
* The board for one league in one week.
*
* `last_seen_ms` IS NOT SELECTED, and that is a decision rather than an
* oversight. It is stored because a relay has to be able to forget rows that
* stopped arriving; it is not served because "Tereza last studied at 02:14"
* is a fact about a person's night that her league-mates did not ask for and
* do not need to see a leaderboard.
*
* Rows from other weeks are excluded rather than deleted. During the first
* hours of a new week the table holds a mixture — everyone who has submitted
* this week, plus everyone who has not yet and still carries last week's row —
* and filtering is what makes that mixture harmless. Each stale row is
* overwritten the moment its owner next submits.
*
* The tie-break on `pubkey` makes the order total, so two reads of an
* unchanged board return the same list. Without it SQLite is free to return
* equal-XP rows in either order and the client sees ranks shuffle for no
* reason.
*/
board(leagueId: string, weekId: string, limit: number): Board {
const rows = this.#db
.prepare(
`SELECT pubkey, display_name AS displayName, xp
FROM participants
WHERE league_id = ? AND week_id = ?
ORDER BY xp DESC, pubkey ASC
LIMIT ?`
)
.all(leagueId, weekId, limit) as Array<{
pubkey: string;
displayName: string;
xp: number;
}>;
return {
leagueId,
weekId,
rows: rows.map((row, index) => ({ rank: index + 1, ...row }))
};
}
/**
* Drop rows for any week other than `weekId`.
*
* Not called on a timer and not called by the server. It exists because a
* self-hoster is entitled to make the relay forget on demand, and because a
* row for someone who stopped submitting three months ago is a name and a key
* being retained for no purpose at all. Retention that nobody can trigger is
* not retention policy, it is an accident.
*/
forgetOtherWeeks(weekId: string): number {
return this.#db.prepare(`DELETE FROM participants WHERE week_id <> ?`).run(weekId).changes;
}
/** Row count. For tests and for a `GET /health` that reports nothing else. */
count(): number {
const row = this.#db.prepare(`SELECT COUNT(*) AS n FROM participants`).get() as { n: number };
return row.n;
}
/** The column names actually present, read from SQLite rather than assumed. */
columns(): string[] {
const rows = this.#db.pragma('table_info(participants)') as Array<{ name: string }>;
return rows.map((r) => r.name);
}
/** Every table in the database. There is one. */
tables(): string[] {
const rows = this.#db
.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all() as Array<{ name: string }>;
return rows.map((r) => r.name);
}
close(): void {
this.#db.close();
}
}
+259
View File
@@ -0,0 +1,259 @@
/**
* The gate. Nothing reaches the database that has not been through this file.
*
* ══════════════════════════════════════════════════════════════════════════
* BE HONEST ABOUT WHAT THIS DOES.
* ══════════════════════════════════════════════════════════════════════════
*
* It establishes that the holder of `pubkey` produced these exact five fields,
* that the week is the one the relay is currently in, and that the numbers and
* strings are within bounds. It establishes NOTHING about whether the XP is
* true. A local-first client computes its own score and can therefore submit
* any number it likes; signing proves who submitted, not that the number is
* honest (CLAUDE.md §6.3, `docs/ROADMAP.md` §4 Phase 5).
*
* That is not a gap waiting for a clever fix. It is a property of the
* architecture, and the only defences worth having are the cheap ones — a
* weekly ceiling, a current-week check, an on-device implausible-latency filter
* that runs BEFORE XP is computed and that the relay never sees — plus the one
* that actually works: scoping a league to a circle where social trust already
* does the job. Do not add an elaborate defence here. An elaborate defence is
* worse than none, because it implies a guarantee this design cannot make.
*
* Every failure is a `Result`, never a throw, and every message names the
* actual problem: this is untrusted input arriving from elsewhere, so a
* rejection is a normal state of the world that the submitter must be able to
* act on (CLAUDE.md §7).
*/
import { ed25519 } from '@noble/curves/ed25519.js';
import {
err,
isWeekId,
ludusError,
ok,
submissionBytes,
type Result
} from '@ludus/schema';
import type { RelayConfig } from './config.js';
/**
* A submission that passed every check, with `xp` already clamped.
*
* `xp` here is what will be STORED, which is not necessarily what was
* submitted — see `clamped`. The store takes this type and nothing else, so a
* raw body cannot reach a table by any route that compiles.
*/
export interface AcceptedSubmission {
readonly pubkey: string;
readonly displayName: string;
readonly leagueId: string;
readonly weekId: string;
/** Non-negative integer, at most `config.xpCeiling`. */
readonly xp: number;
/** True when the submitted value was above the ceiling and was cut down. */
readonly clamped: boolean;
}
/** The exact set of keys a submission may carry. Anything else is a rejection. */
const SUBMISSION_KEYS = ['pubkey', 'displayName', 'leagueId', 'weekId', 'xp', 'sig'] as const;
/**
* base64url, no padding. Length is checked against the DECODED byte count
* rather than the string length, because base64url of 32 bytes is 43
* characters and asserting on 43 encodes the same fact less legibly.
*/
const BASE64URL = /^[A-Za-z0-9_-]+$/;
function decodeBase64Url(value: string, expectedBytes: number): Uint8Array | null {
// The character-class test first, because `Buffer.from(_, 'base64')` does not
// throw on rubbish — it SKIPS characters it does not recognise and returns a
// short buffer. Without the test, `"!!!!"` and `""` are indistinguishable.
if (!BASE64URL.test(value)) return null;
const bytes = Buffer.from(value.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
if (bytes.length !== expectedBytes) return null;
return new Uint8Array(bytes);
}
/**
* Reject any control character, and `\n` above all.
*
* `\n` is the separator in `submissionBytes`. A display name containing one
* could be split into two fields by a chosen `leagueId`, so two different
* submissions would produce identical signed bytes — a signature that verifies
* for a submission nobody made. The other control characters are refused for
* the ordinary reason: this string is rendered on other people's screens.
*/
// Written as escapes rather than as literal bytes: a literal control character
// in a source file is invisible in every diff and in every review.
const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
function checkString(
value: unknown,
field: string,
maxChars: number
): Result<string> {
if (typeof value !== 'string') {
return err(ludusError('relay/bad-field', `\`${field}\` must be a string.`));
}
if (value.length === 0) {
return err(ludusError('relay/bad-field', `\`${field}\` must not be empty.`));
}
if (value.length > maxChars) {
return err(
ludusError(
'relay/bad-field',
`\`${field}\` is ${value.length} characters; this relay accepts at most ${maxChars}. ` +
'It is refused rather than shortened, because shortening it would change the bytes ' +
'that were signed.'
)
);
}
if (CONTROL_CHARS.test(value)) {
return err(
ludusError(
'relay/bad-field',
`\`${field}\` contains a control character. Newlines especially: they separate the ` +
'fields that are signed, so a name containing one would make two different ' +
'submissions sign identically.'
)
);
}
return ok(value);
}
/**
* Check a decoded request body and, if it is sound, return what to store.
*
* `currentWeekId` is passed in rather than computed here. The relay's clock is
* the only one that decides which week is current, and a function that read it
* from the environment could not be tested at a week boundary — which is the
* one moment this check has to be right.
*/
export function checkSubmission(
raw: unknown,
options: { readonly currentWeekId: string; readonly config: RelayConfig }
): Result<AcceptedSubmission> {
const { currentWeekId, config } = options;
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
return err(
ludusError('relay/malformed-body', 'A submission must be a JSON object.')
);
}
const body = raw as Record<string, unknown>;
// Unknown fields are refused rather than ignored. A relay that silently drops
// a field it does not understand is a relay that will one day accept a
// submission whose meaning it got wrong — and this shape is frozen at six
// keys by CLAUDE.md §6.3, so a seventh is a design discussion, not traffic.
const allowed = new Set<string>(SUBMISSION_KEYS);
const unknown = Object.keys(body).filter((k) => !allowed.has(k));
if (unknown.length > 0) {
return err(
ludusError(
'relay/unknown-field',
`A submission carries exactly ${SUBMISSION_KEYS.length} fields; this one also had ` +
`${unknown.map((k) => `\`${k}\``).join(', ')}.`
)
);
}
const displayName = checkString(body['displayName'], 'displayName', config.displayNameMaxChars);
if (!displayName.ok) return displayName;
const leagueId = checkString(body['leagueId'], 'leagueId', config.leagueIdMaxChars);
if (!leagueId.ok) return leagueId;
const weekIdField = checkString(body['weekId'], 'weekId', 16);
if (!weekIdField.ok) return weekIdField;
if (!isWeekId(weekIdField.value)) {
return err(
ludusError('relay/bad-field', '`weekId` must look like `2026-W34`.')
);
}
const pubkeyField = checkString(body['pubkey'], 'pubkey', 64);
if (!pubkeyField.ok) return pubkeyField;
const pubkeyBytes = decodeBase64Url(pubkeyField.value, 32);
if (pubkeyBytes === null) {
return err(
ludusError(
'relay/bad-pubkey',
'`pubkey` must be a 32-byte Ed25519 public key in unpadded base64url.'
)
);
}
const sigField = checkString(body['sig'], 'sig', 128);
if (!sigField.ok) return sigField;
const sigBytes = decodeBase64Url(sigField.value, 64);
if (sigBytes === null) {
return err(
ludusError(
'relay/bad-signature',
'`sig` must be a 64-byte Ed25519 signature in unpadded base64url.'
)
);
}
const xpRaw = body['xp'];
if (typeof xpRaw !== 'number' || !Number.isInteger(xpRaw) || xpRaw < 0) {
return err(
ludusError('relay/bad-field', '`xp` must be a non-negative integer.')
);
}
/* ---------------------------------------------------------------- *
* The week check comes BEFORE the signature check on purpose.
*
* Verifying an Ed25519 signature is the most expensive thing this
* process does, and a stale week is decidable for free. Ordering it
* the other way would let anyone spend the relay's CPU by replaying
* last week's traffic — which is valid traffic, correctly signed, and
* so would pass the expensive check every time.
* ---------------------------------------------------------------- */
if (weekIdField.value !== currentWeekId) {
return err(
ludusError(
'relay/stale-week',
`This relay is in week ${currentWeekId}; the submission is for ${weekIdField.value}. ` +
'Only the current week is accepted — the relay keeps no history, so a submission ' +
'for a past week has nowhere to go. `GET /health` publishes the relay\'s week.',
{ detail: { relayWeek: currentWeekId, submittedWeek: weekIdField.value } }
)
);
}
const signed = submissionBytes({
pubkey: pubkeyField.value,
displayName: displayName.value,
leagueId: leagueId.value,
weekId: weekIdField.value,
xp: xpRaw
});
if (!ed25519.verify(sigBytes, signed, pubkeyBytes)) {
return err(
ludusError(
'relay/bad-signature',
'The signature does not match the submission. Either a field was altered in ' +
'transit, or it was signed by a different key than the one in `pubkey`.'
)
);
}
// Clamp, do not reject. Rejecting would cost an honest heavy user their week;
// clamping bounds what a dishonest one gains, which is the whole of what a
// ceiling can do.
const clamped = xpRaw > config.xpCeiling;
return ok({
pubkey: pubkeyField.value,
displayName: displayName.value,
leagueId: leagueId.value,
weekId: weekIdField.value,
xp: clamped ? config.xpCeiling : xpRaw,
clamped
});
}
+69
View File
@@ -0,0 +1,69 @@
/**
* Which week it is, according to THE RELAY.
*
* ══════════════════════════════════════════════════════════════════════════
* THE RELAY'S WEEK IS A UTC WEEK, AND THE PLAYER'S DAY IS A LOCAL DAY.
* ══════════════════════════════════════════════════════════════════════════
*
* That is a deliberate asymmetry, and it has a visible consequence, so it is
* written down here rather than discovered at a week boundary.
*
* The player computes a learner's day through `engine/src/time/localDay.ts`,
* because a streak that breaks at UTC midnight is a streak the learner actually
* kept (CLAUDE.md §8). A relay cannot do that: it serves participants in many
* zones and has no business knowing anyone's, so it has exactly one week and
* that week is UTC.
*
* So near a boundary the two disagree. A learner in Auckland at 11:00 on Monday
* local is still in the previous UTC week; a learner in Los Angeles at 17:00 on
* Sunday local is already in the next one. If their client submits the week id
* it derived locally, the relay will reject it as not current, and the honest
* fix is on the CLIENT: submit `weekId` derived from the relay's clock — which
* `GET /health` publishes for exactly this reason — not from the device's.
*
* The alternative, a grace window that accepts the neighbouring week, was
* considered and rejected: it doubles the window in which a participant can
* hold XP in two weeks at once, to fix a problem a client can fix for free.
*
* Nothing here uses `Date.now()`. `now` is always a parameter, so the boundary
* cases are testable rather than reachable twice a year.
*/
import { WEEK_ID_PATTERN } from '@ludus/schema';
/**
* ISO 8601 week number of `now`, in UTC, as `YYYY-Www`.
*
* ISO weeks start on Monday and week 01 is the one containing the first
* Thursday of the year — which is why the year in a week id is NOT always the
* calendar year of the date: 2027-01-01 is a Friday and belongs to `2026-W53`.
* Deriving the year from `getUTCFullYear()` is the classic bug here and would
* silently orphan every submission made in the first days of January.
*/
export function currentWeekId(now: number): string {
const d = new Date(now);
// Shift to the Thursday of this ISO week. Thursday's calendar year IS the
// ISO week-numbering year, by definition, which removes the January problem
// rather than special-casing it.
const dayOfWeek = (d.getUTCDay() + 6) % 7; // Monday = 0 … Sunday = 6
const thursday = new Date(
Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - dayOfWeek + 3)
);
const isoYear = thursday.getUTCFullYear();
const firstThursday = new Date(Date.UTC(isoYear, 0, 4));
const firstDayOfWeek = (firstThursday.getUTCDay() + 6) % 7;
const week1Monday = new Date(
Date.UTC(isoYear, 0, 4 - firstDayOfWeek)
);
const msPerWeek = 7 * 24 * 60 * 60 * 1000;
const week = Math.floor((thursday.getTime() - week1Monday.getTime()) / msPerWeek) + 1;
return `${isoYear}-W${String(week).padStart(2, '0')}`;
}
/** Shape check only — says nothing about whether the week is current. */
export function isWeekIdShape(value: string): boolean {
return WEEK_ID_PATTERN.test(value);
}
+62
View File
@@ -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);
+103
View File
@@ -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');
});
});
+225
View File
@@ -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);
});
});
+178
View File
@@ -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);
});
});
+269
View File
@@ -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);
});
});
+58
View File
@@ -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);
});
});
+17
View File
@@ -0,0 +1,17 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"types": ["node"],
"module": "NodeNext",
"moduleResolution": "NodeNext"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"dist",
"node_modules"
]
}
+19
View File
@@ -0,0 +1,19 @@
{
"//": "See docs/TYPECHECK_COVERS_TESTS.md (G5.28). tsconfig.json carries rootDir 'src', so test/ cannot be added to its include; this is the second project that covers both, and `pnpm typecheck` runs it alongside the first. Deliberately the same strictness as src. services/ingest needs no such file — its own tsconfig has covered test/ since the day it landed, and it is the shape the other ten were brought into line with.",
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"noEmit": true,
"declaration": false,
"declarationMap": false
},
"include": [
"src/**/*.ts",
"test/**/*.ts",
"vitest.config.ts"
],
"exclude": [
"dist",
"node_modules"
]
}
+77
View File
@@ -0,0 +1,77 @@
import { defineConfig } from 'vitest/config';
/**
* THE SIXTH INSTANCE OF ONE FAILURE, IN THE FIFTH PACKAGE — AND THE ONE THAT
* ARRIVED WHILE THE SENTENCE PREDICTING IT WAS BEING WRITTEN.
*
* ── WHAT HAPPENED ────────────────────────────────────────────────────────────
*
* 2026-11-01, run 6026, job 15130, on `fix/identity-crypto-timeout` — the
* branch that bounds `packages/identity`:
*
* FAIL test/server.test.ts > POST /submit
* > accepts a signed submission and reports what was stored
* FAIL test/verify.test.ts > checkSubmission — the happy day
* > accepts a correctly signed submission for the current week
* Error: Test timed out in 5000ms. (both)
*
* Test Files 2 failed | 4 passed (6)
* Tests 2 failed | 68 passed (70)
*
* Nothing failed an assertion. Both cases call `signedSubmission(keyFor(1))`,
* so both do real Ed25519 key generation and signing; the container was
* slower than vitest's 5s default.
*
* G5.50's row, written one commit earlier on this same branch, says: *"seven
* packages have no `testTimeout` at all and are red the first time the
* container is slow on one of their cases."* That is this, four hours later.
* The row deferred the sweep on the grounds that a bound chosen by analogy is
* how the engine's 80x claim got written — which is still right, and is why
* this file says below exactly which number here is measured and which is
* borrowed.
*
* ── WHAT THE CONTAINER ACTUALLY SHOWED, AND WHAT IT DID NOT ─────────────────
*
* Read off run 6026's log, 506,073 bytes, rather than inferred: the relay's
* OTHER cases were fine in the same container —
*
* GET /health > publishes the relay week … 860ms
* recording a standing > keeps ONE row per participant … 320ms
* checkSubmission — the XP ceiling > leaves a submission … 498ms
* guardedFetch > turns a hung server into a timeout reason 35ms
*
* — so this is not a slow suite. It is **two cases that generate and use a
* keypair**, which is the same signature the four earlier instances have:
* `packages/identity`'s crypto cases, and `packages/engine`'s seeded property
* sweeps. Everything else in this package is tens to hundreds of ms.
*
* **The local baseline was NOT measured, deliberately.** The box was at
* **93.1% CPU** with five agents working in parallel worktrees, and §5.7
* rule 3 forbids quoting a timing from a loaded machine — a number taken at
* 93% cannot be told apart later from one taken on an idle box, which is the
* whole reason that rule exists. So the ratio here is **borrowed from
* `packages/identity`'s measured 19x–99x**, and it is borrowed rather than
* derived. If a seventh instance lands in this package, measure it properly
* before touching this number.
*
* ── WHY 120 SECONDS ─────────────────────────────────────────────────────────
*
* The same value as `packages/engine` and `packages/identity`. One timeout in
* this repository is easier to defend than five, and **none of them is a
* performance guard.** These cases assert that a signature verifies and that a
* submission is stored; they say nothing about speed. At 120s the cost of
* being generous is that a genuinely hung test takes two minutes to report;
* the cost of being tight is a red `main` that says nothing about the product,
* six times over.
*
* **Do not tighten this into a benchmark.** If the relay's signing speed is
* ever worth guarding, that wants its own assertion with its own measured
* bound and §5.7 rule 3's load beside it — a timeout dressed up as a benchmark
* reports "too slow" and "broken" with the same red tick.
*/
export default defineConfig({
test: {
environment: 'node',
testTimeout: 120_000
}
});
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@ludus/schema",
"version": "0.1.0",
"private": true,
"license": "CPAL-1.0",
"type": "module",
"description": "The slice of Ludus's schema the relay needs: the league submission and the Result type. Each file is a byte-for-byte copy of Ludus's, and a test there fails if they differ.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"devDependencies": {
"typescript": "^5.7.2"
}
}
+4
View File
@@ -0,0 +1,4 @@
// The slice of Ludus's `@ludus/schema` that the relay imports. Each file beside this one is a byte-for-byte copy
// of Ludus's; this index is the only file that is LudusPublic's own.
export * from './result.js';
export * from './league.js';
+96
View File
@@ -0,0 +1,96 @@
/**
* The league submission — CLAUDE.md §6.3.
*
* ══════════════════════════════════════════════════════════════════════════
* WHY THIS LIVES IN `@ludus/schema` AND NOT IN `@ludus/identity`.
* ══════════════════════════════════════════════════════════════════════════
*
* Two processes have to agree on it byte for byte: the player, which signs a
* submission with `@ludus/identity`, and `services/relay`, which verifies it.
* The dependency direction in CLAUDE.md §2 lets the relay import `@ludus/schema`
* and nothing else from this repository — so if the canonical byte encoding had
* stayed in `@ludus/identity`, the relay would have had to restate it.
*
* A restated encoding does not fail loudly. Signing over `pubkey\ndisplayName…`
* and verifying over `{"pubkey":…}` produces "invalid signature" for every
* honest submission, and the bug reads exactly like a malicious client. One
* definition, imported by both sides, is the only version of this that cannot
* drift. `@ludus/identity` re-exports `submissionBytes` so the signer's call
* site is unchanged.
*
* This file is a CONTRACT, not a policy. It says what a submission *is*. What a
* relay will *accept* — the XP ceiling, the display-name cap, which week counts
* as current — is the relay's business and lives in `services/relay`, because a
* self-hoster is entitled to set those differently.
*/
/**
* What the player sends, when the user has opted in and only then.
*
* Six fields, and the fifth is a number the client computed about itself. See
* `SIGNATURE_PROVES` below before designing anything on top of it.
*/
export interface LeagueSubmission {
/** base64url Ed25519 public key, 32 bytes. The participant's only identifier. */
readonly pubkey: string;
/** Chosen freely by the user. Not verified, not unique, not an account name. */
readonly displayName: string;
/** Which cohort this is a submission to. Asserted by the client. */
readonly leagueId: string;
/** ISO week, `YYYY-Www`. */
readonly weekId: string;
/** Non-negative integer. Computed on the device, so it can be any number. */
readonly xp: number;
/** base64url Ed25519 signature over `submissionBytes()` of the five above. */
readonly sig: string;
}
/** The submission minus its signature — what actually gets signed. */
export type SignedSubmissionFields = Omit<LeagueSubmission, 'sig'>;
/**
* What a valid signature on a submission does and does not establish.
*
* It establishes that the holder of `pubkey` produced these exact five fields.
* It establishes nothing whatsoever about whether `xp` is true: a local-first
* client computes its own score and can therefore lie about it, and no amount
* of signing changes that (CLAUDE.md §6.3, `docs/ROADMAP.md` §4 Phase 5).
*
* Kept as an exported string so that it turns up in editor hovers and in a
* grep, rather than only in a comment nobody opens.
*/
export const SIGNATURE_PROVES =
'who submitted, not that the number is true';
/**
* `YYYY-Www`, e.g. `2026-W34`. Two digits in the week, zero-padded, 01–53.
*
* Anchored at both ends: an unanchored pattern accepts `x2026-W34y`, and a week
* id is a key that ends up in a database row.
*/
export const WEEK_ID_PATTERN = /^\d{4}-W(0[1-9]|[1-4]\d|5[0-3])$/;
export function isWeekId(value: string): boolean {
return WEEK_ID_PATTERN.test(value);
}
/**
* Canonical bytes for a league submission, so signer and verifier agree.
*
* Field order is fixed and explicit rather than relying on `JSON.stringify` key
* order, which would make a signature depend on the order the object happened to
* be constructed in. `\n` is the separator; none of the five fields may contain
* one, which the relay enforces before it verifies (a display name with a
* newline in it could otherwise be split into two fields by a chosen
* `leagueId`, and two different submissions would hash the same).
*/
export function submissionBytes(fields: SignedSubmissionFields): Uint8Array {
const canonical = [
fields.pubkey,
fields.displayName,
fields.leagueId,
fields.weekId,
String(fields.xp)
].join('\n');
return new TextEncoder().encode(canonical);
}
+74
View File
@@ -0,0 +1,74 @@
/**
* The typed Result returned by anything that can fail on untrusted input — pack
* loading, signature verification, ingestion.
*
* Those failures are *expected*, not exceptional: a malformed pack and a bad
* signature are normal states of the world when the input arrives from
* elsewhere. They must be shown to the user with the reason, which is why they
* are values rather than exceptions.
*
* The convention this exists to kill is `catch {}` — a swallowed error turns a
* condition the user needs to see into a screen that renders nothing, and their
* report becomes "it does not work" (.agents/lessons/code.md).
*
* Reserve `throw` for genuine bugs.
*/
export type Ok<T> = { readonly ok: true; readonly value: T };
export type Err<E> = { readonly ok: false; readonly error: E };
export type Result<T, E = LudusError> = Ok<T> | Err<E>;
export function ok<T>(value: T): Ok<T> {
return { ok: true, value };
}
export function err<E>(error: E): Err<E> {
return { ok: false, error };
}
export function isOk<T, E>(r: Result<T, E>): r is Ok<T> {
return r.ok;
}
export function isErr<T, E>(r: Result<T, E>): r is Err<E> {
return !r.ok;
}
/**
* What went wrong, in terms a user can act on.
*
* `message` is shown to a person, so it names the actual problem. "Invalid pack"
* is not a message, it is a shrug — the validator's whole value is that its
* failures say which rule fired and where.
*/
export interface LudusError {
/** Stable machine-readable code, e.g. `pack/dangling-reference`. */
readonly code: string;
/** Shown to the user. Names the actual problem. */
readonly message: string;
/** JSON Pointer into the offending document, when there is one. */
readonly pointer?: string;
/** Anything that helps a person fix it. Never raw untrusted content. */
readonly detail?: Readonly<Record<string, unknown>>;
}
export function ludusError(
code: string,
message: string,
extra?: { pointer?: string; detail?: Record<string, unknown> }
): LudusError {
return {
code,
message,
...(extra?.pointer !== undefined ? { pointer: extra.pointer } : {}),
...(extra?.detail !== undefined ? { detail: extra.detail } : {})
};
}
/** Collect a list of errors, keeping the first `limit` so a broken pack cannot
* produce a hundred thousand findings. */
export function takeErrors(errors: readonly LudusError[], limit = 50): LudusError[] {
return errors.slice(0, limit);
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": { "noEmit": true },
"include": ["src/**/*.ts"]
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
}
}