Files

260 lines
10 KiB
TypeScript

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