[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
+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"]
}