[relay] Relay: The league relay from Ludus, byte for byte, with the slice of the schema it imports

This commit is contained in:
Marek Novák
2026-11-23 02:02:35 +01:00
parent beb920cb68
commit 6a2ab2f3f5
29 changed files with 3705 additions and 0 deletions
+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);
}