diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2e8fb25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +*.db +*.db-wal +*.db-shm diff --git a/README.md b/README.md new file mode 100644 index 0000000..55f241c --- /dev/null +++ b/README.md @@ -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). diff --git a/package.json b/package.json new file mode 100644 index 0000000..e6162f4 --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..dd583c3 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1347 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: {} + + relay: + dependencies: + '@ludus/schema': + specifier: workspace:* + version: link:../schema + '@noble/curves': + specifier: ^2.3.0 + version: 2.4.0 + better-sqlite3: + specifier: ^12.11.1 + version: 12.11.1 + devDependencies: + '@types/better-sqlite3': + specifier: ^7.6.13 + version: 7.6.13 + '@types/node': + specifier: ^22.10.2 + version: 22.20.5 + tsx: + specifier: ^4.23.12 + version: 4.23.15 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@22.20.5)(tsx@4.23.15) + + schema: + devDependencies: + typescript: + specifier: ^5.7.2 + version: 5.9.3 + +packages: + + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@noble/curves@2.4.0': + resolution: {integrity: sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==} + engines: {node: '>= 20.19.0'} + + '@noble/hashes@2.4.0': + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==} + engines: {node: '>= 20.19.0'} + + '@rollup/rollup-android-arm-eabi@4.68.8': + resolution: {integrity: sha512-7l9FdeCGjhmMTVePgndK4t9u5tLR+VuTTMoyc0PscqZDdYjS07ZsQ0vQYsWsODu/ZZYPG7WVJwbUZ77n1hVT+w==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.68.8': + resolution: {integrity: sha512-kXkkIiJujBjArHwEToz99BQqIqibn4xdV6SjsoaxuZzvLUCVEzoHQ1Lp62m7xOhpLRpWpCtxL2ZUy/ADKuz9/g==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-android-x64@4.68.8': + resolution: {integrity: sha512-KYoBygnHs3zUOLR0z7SaqhMnUrSF9pbuTOJT/uHK3PrgCXdv/xaMubZD8jCpg6NTo46deasLgZRq38xFTyu8uw==} + cpu: [x64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.68.8': + resolution: {integrity: sha512-YmBUNjgm5bsjOByO+H1TFbuGZe+ZnHcYtPXYj9+L1cwTu/BG8zjuUzO2PH9KwS85P0UH+WJDSb+mQ2hqjp5uBQ==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.68.8': + resolution: {integrity: sha512-XMX5ybuOmkwiM13KJtsBxakZ69pyaR9thRYU2fMejhaB0VuzLMIkIc+9TBsu2rv34eEf6XaSMOaLOyEgHGWHTQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.68.8': + resolution: {integrity: sha512-WuBXScWJDaqPJKwVrotUe1sM9DHWMN937C23RClt0MVHVt7A1rBy285ZfZTLccPEVMxmGJMt2jvdHMOI33lrKA==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.68.8': + resolution: {integrity: sha512-kegwGqP3rMenEMaKo8OzMBb5WvLW2h2jrQ3iKuYptTTF8C/yuxz+hinjBPrtYuIPLJDwxHc/hv2e4u5pmrqo9A==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.68.8': + resolution: {integrity: sha512-Qct0oLM1zGNbvqs1udQnuchg+Q9uHbkMcQqCfs3M7foNn7HvEkUypfFn9o5fklimUI5OF3A2nMknd4/vrEyeVg==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.68.8': + resolution: {integrity: sha512-xTH5vD+lW/5MU3kL/Op8RSSG/O9fxUQZuJcSBmmBeYem9uXYvCq6PDHx/oDSNeyLD/p4pGujG2PVI0R8MjAhSw==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.68.8': + resolution: {integrity: sha512-lPPStmynSHvwWpSrAsuemPFB+EWFObXjwz44EK4Hph47U6SBAk1Kehq5MkI7i8EYVjrXddaAV7YkJH8mX8QSZQ==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.68.8': + resolution: {integrity: sha512-kZkvIYAihM6l6M+giSUHayDDf/JL+TYR5bYWiAX7/jUFWvMkMmysA4GV2F0HOsXQNEyctW3x1xLjww1GqW7Q1w==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.68.8': + resolution: {integrity: sha512-XZKLEIY977OJr6zUtK6nlQcLXme34c8HqVp3+WmKQxKVN6Nj+b9qE3ZHWIDHXznHJsGl2AsaMOgB0GL0fkZGUg==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-loong64-musl@4.68.8': + resolution: {integrity: sha512-+sN+Fj6F9suk8SkL6boIfXDmj9iJwSKPCTeCy8/pfTOHuzNX+duhTb9uyj6154oVK8Odl5zgL4DXRZzXjsRKcw==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.68.8': + resolution: {integrity: sha512-EBCu3uDFaGwSodUl+XR8yubvVFUkSo6QK9YAIOV1vljqntzTF2/mXLM6utgLaSGf/8oM+qEe8Ai0Jd4+tyMoIQ==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-ppc64-musl@4.68.8': + resolution: {integrity: sha512-hRC0jWdsLBckCijx2wiUfk7zW1SqEW47yMsCNoDGmQfoqq0AjW+9UYZqxg3LTmG76PyHNdNGBSuspB3CqrhGIA==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.68.8': + resolution: {integrity: sha512-OZKrTRWyGnLITUTipbeXDdtb2dxQPyFk/Fbw9qER8pIvd2Ja9hHELkY0Fv5p9yYYkimqtzVhApKKXGv0cWGQGw==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.68.8': + resolution: {integrity: sha512-HmhSRSQ+dOeOntPfmYux4rCpOQLtsGbcGLQu4nm8ig3tuVqe/bKfDHorg36LKAqYq4X/nwFr79ImtaFHHsn4ug==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.68.8': + resolution: {integrity: sha512-wk1Ci1hsMREaBELoKPSnzRAh1oUULI+8kfb2F5vVmTD2IcfR9AKMskCusizZhIAvojOtPZihPj4OdKy6ifZwhQ==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.68.8': + resolution: {integrity: sha512-mDufoUJ6fnKZnCyjV3sGEDvXQQkM6j1UmINHheGX4Emau3TZWJzX3sCVmbzkNB+W2G84BiFQdDCcF09lv0i0VA==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.68.8': + resolution: {integrity: sha512-7EGVL9rYRYQZe3UC8JQzfBN9rxk484Rfs4u/yGWumTYKUdJt6tmdP+0Y3qHvAvzJCQ+JQM5rSqZbVyrJARlGpA==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openbsd-x64@4.68.8': + resolution: {integrity: sha512-Umklz+QSGwKWQVlVrsMJrwFx1oNRYHgrxSGiZM8pJCMpzWnMDMinDhPILf0BvRXfA1QOArsDcs+AE7Jd6dQxvA==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.68.8': + resolution: {integrity: sha512-BlRp6uzQDK5rczAdaXQ8dlSIRFRlkDRBqpb8GGtv8iwZxQdOjoigdFU5t5dcxpnpU0caMoT9mH27MyAl4dWwKw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.68.8': + resolution: {integrity: sha512-Sc8Mkf/fVfcV0hBJNDRIM82BjS4kJn2Of0jP8dgQ+TodquxtCZ/5D6FgSsY3uN5IBmNi8Zrb/OHd60IEYKaw+Q==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.68.8': + resolution: {integrity: sha512-XPTFXclN+I+Cfu3ONWDsw+uvgSZjTJa1B2u2EvtdKlSdgNU6mrOZdgeaMkvN+2T2KPTEXn6fnRY8IODlRg3/Tg==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.68.8': + resolution: {integrity: sha512-63dWiHgvpWcienfdr465lT3SIn4u3535vbDfaLKhSn0F2KJ06bbcUsewDGJZUPZCbJ67qESrPDhb85UnWdb5ew==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.68.8': + resolution: {integrity: sha512-/W1LBsMeQAdiCuH3Z2gkRspl3mlxL+butknhq4vXjmxO45vuT08BqhehxDoE4YS+m6s9lhpq6M9/PjTEAg8PYw==} + cpu: [x64] + os: [win32] + + '@types/better-sqlite3@7.6.13': + resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/node@22.20.5': + resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + + '@vitest/expect@3.2.7': + resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==} + + '@vitest/mocker@3.2.7': + resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@3.2.7': + resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==} + + '@vitest/runner@3.2.7': + resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==} + + '@vitest/snapshot@3.2.7': + resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==} + + '@vitest/spy@3.2.7': + resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==} + + '@vitest/utils@3.2.7': + resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + better-sqlite3@12.11.1: + resolution: {integrity: sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==} + engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} + + bindings@1.5.0: + resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + chownr@1.1.4: + resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expand-template@2.0.3: + resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} + engines: {node: '>=6'} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-uri-to-path@1.0.0: + resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} + + fs-constants@1.0.0: + resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + github-from-package@0.0.0: + resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + + js-tokens@9.0.1: + resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + napi-build-utils@2.0.0: + resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + + node-abi@3.104.0: + resolution: {integrity: sha512-J2lVAHTQ8v1J7hl2k1eX70d/Fm+HE1EyUes2dOew59JgBlAW6NB7DABI8kdrgRPehhepJd18p1ivekA8BF7AOg==} + engines: {node: '>=10'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.33: + resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} + engines: {node: ^10 || ^12 || >=14} + + prebuild-install@7.1.3: + resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} + engines: {node: '>=10'} + deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. + hasBin: true + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + rc@1.2.8: + resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} + hasBin: true + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + rollup@4.68.8: + resolution: {integrity: sha512-IHx4DeeTGhoAPke6p1Wlg0JEQFyQoZQQjEe1iD+nhEERk7eoeHK9zyOpVJiGc54Z1MCgI96rN1tD7Ttub8XyPA==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} + engines: {node: '>=10'} + hasBin: true + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + + source-map-js@1.2.4: + resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==} + engines: {node: '>=6.0.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-json-comments@2.0.1: + resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} + engines: {node: '>=0.10.0'} + + strip-literal@3.1.0: + resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + + tar-fs@2.1.5: + resolution: {integrity: sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==} + + tar-stream@2.2.0: + resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} + engines: {node: '>=6'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@2.0.0: + resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==} + engines: {node: '>=14.0.0'} + + tinyspy@4.0.6: + resolution: {integrity: sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==} + engines: {node: '>=14.0.0'} + + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + + tunnel-agent@0.6.0: + resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + vite-node@3.2.4: + resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + + vite@7.3.8: + resolution: {integrity: sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + jiti: '>=1.21.0' + less: ^4.0.0 + lightningcss: ^1.21.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@3.2.7: + resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/debug': ^4.1.12 + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@vitest/browser': 3.2.7 + '@vitest/ui': 3.2.7 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/debug': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + +snapshots: + + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@noble/curves@2.4.0': + dependencies: + '@noble/hashes': 2.4.0 + + '@noble/hashes@2.4.0': {} + + '@rollup/rollup-android-arm-eabi@4.68.8': + optional: true + + '@rollup/rollup-android-arm64@4.68.8': + optional: true + + '@rollup/rollup-android-x64@4.68.8': + optional: true + + '@rollup/rollup-darwin-arm64@4.68.8': + optional: true + + '@rollup/rollup-darwin-x64@4.68.8': + optional: true + + '@rollup/rollup-freebsd-arm64@4.68.8': + optional: true + + '@rollup/rollup-freebsd-x64@4.68.8': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.68.8': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.68.8': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.68.8': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.68.8': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.68.8': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.68.8': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.68.8': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.68.8': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.68.8': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.68.8': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.68.8': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.68.8': + optional: true + + '@rollup/rollup-linux-x64-musl@4.68.8': + optional: true + + '@rollup/rollup-openbsd-x64@4.68.8': + optional: true + + '@rollup/rollup-openharmony-arm64@4.68.8': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.68.8': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.68.8': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.68.8': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.68.8': + optional: true + + '@types/better-sqlite3@7.6.13': + dependencies: + '@types/node': 22.20.5 + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.10': {} + + '@types/node@22.20.5': + dependencies: + undici-types: 6.21.0 + + '@vitest/expect@3.2.7': + dependencies: + '@types/chai': 5.2.3 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.3.3 + tinyrainbow: 2.0.0 + + '@vitest/mocker@3.2.7(vite@7.3.8(@types/node@22.20.5)(tsx@4.23.15))': + dependencies: + '@vitest/spy': 3.2.7 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.8(@types/node@22.20.5)(tsx@4.23.15) + + '@vitest/pretty-format@3.2.7': + dependencies: + tinyrainbow: 2.0.0 + + '@vitest/runner@3.2.7': + dependencies: + '@vitest/utils': 3.2.7 + pathe: 2.0.3 + strip-literal: 3.1.0 + + '@vitest/snapshot@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@3.2.7': + dependencies: + tinyspy: 4.0.6 + + '@vitest/utils@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + loupe: 3.2.1 + tinyrainbow: 2.0.0 + + assertion-error@2.0.1: {} + + base64-js@1.5.1: {} + + better-sqlite3@12.11.1: + dependencies: + bindings: 1.5.0 + prebuild-install: 7.1.3 + + bindings@1.5.0: + dependencies: + file-uri-to-path: 1.0.0 + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + + cac@6.7.14: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + check-error@2.1.3: {} + + chownr@1.1.4: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + + deep-eql@5.0.2: {} + + deep-extend@0.6.0: {} + + detect-libc@2.1.2: {} + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + + es-module-lexer@1.7.0: {} + + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.10 + + expand-template@2.0.3: {} + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + file-uri-to-path@1.0.0: {} + + fs-constants@1.0.0: {} + + fsevents@2.3.3: + optional: true + + github-from-package@0.0.0: {} + + ieee754@1.2.1: {} + + inherits@2.0.4: {} + + ini@1.3.8: {} + + js-tokens@9.0.1: {} + + loupe@3.2.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + mimic-response@3.1.0: {} + + minimist@1.2.8: {} + + mkdirp-classic@0.5.3: {} + + ms@2.1.3: {} + + nanoid@3.3.20: {} + + napi-build-utils@2.0.0: {} + + node-abi@3.104.0: + dependencies: + semver: 7.8.6 + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + pathe@2.0.3: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.33: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.4 + + prebuild-install@7.1.3: + dependencies: + detect-libc: 2.1.2 + expand-template: 2.0.3 + github-from-package: 0.0.0 + minimist: 1.2.8 + mkdirp-classic: 0.5.3 + napi-build-utils: 2.0.0 + node-abi: 3.104.0 + pump: 3.0.4 + rc: 1.2.8 + simple-get: 4.0.1 + tar-fs: 2.1.5 + tunnel-agent: 0.6.0 + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + + rc@1.2.8: + dependencies: + deep-extend: 0.6.0 + ini: 1.3.8 + minimist: 1.2.8 + strip-json-comments: 2.0.1 + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + + rollup@4.68.8: + dependencies: + '@types/estree': 1.0.10 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.68.8 + '@rollup/rollup-android-arm64': 4.68.8 + '@rollup/rollup-android-x64': 4.68.8 + '@rollup/rollup-darwin-arm64': 4.68.8 + '@rollup/rollup-darwin-x64': 4.68.8 + '@rollup/rollup-freebsd-arm64': 4.68.8 + '@rollup/rollup-freebsd-x64': 4.68.8 + '@rollup/rollup-linux-arm-gnueabihf': 4.68.8 + '@rollup/rollup-linux-arm-musleabihf': 4.68.8 + '@rollup/rollup-linux-arm64-gnu': 4.68.8 + '@rollup/rollup-linux-arm64-musl': 4.68.8 + '@rollup/rollup-linux-loong64-gnu': 4.68.8 + '@rollup/rollup-linux-loong64-musl': 4.68.8 + '@rollup/rollup-linux-ppc64-gnu': 4.68.8 + '@rollup/rollup-linux-ppc64-musl': 4.68.8 + '@rollup/rollup-linux-riscv64-gnu': 4.68.8 + '@rollup/rollup-linux-riscv64-musl': 4.68.8 + '@rollup/rollup-linux-s390x-gnu': 4.68.8 + '@rollup/rollup-linux-x64-gnu': 4.68.8 + '@rollup/rollup-linux-x64-musl': 4.68.8 + '@rollup/rollup-openbsd-x64': 4.68.8 + '@rollup/rollup-openharmony-arm64': 4.68.8 + '@rollup/rollup-win32-arm64-msvc': 4.68.8 + '@rollup/rollup-win32-ia32-msvc': 4.68.8 + '@rollup/rollup-win32-x64-gnu': 4.68.8 + '@rollup/rollup-win32-x64-msvc': 4.68.8 + fsevents: 2.3.3 + + safe-buffer@5.2.1: {} + + semver@7.8.6: {} + + siginfo@2.0.0: {} + + simple-concat@1.0.1: {} + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + + source-map-js@1.2.4: {} + + stackback@0.0.2: {} + + std-env@3.10.0: {} + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + + strip-json-comments@2.0.1: {} + + strip-literal@3.1.0: + dependencies: + js-tokens: 9.0.1 + + tar-fs@2.1.5: + dependencies: + chownr: 1.1.4 + mkdirp-classic: 0.5.3 + pump: 3.0.4 + tar-stream: 2.2.0 + + tar-stream@2.2.0: + dependencies: + bl: 4.1.0 + end-of-stream: 1.4.5 + fs-constants: 1.0.0 + inherits: 2.0.4 + readable-stream: 3.6.2 + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinypool@1.1.1: {} + + tinyrainbow@2.0.0: {} + + tinyspy@4.0.6: {} + + tsx@4.23.15: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + + tunnel-agent@0.6.0: + dependencies: + safe-buffer: 5.2.1 + + typescript@5.9.3: {} + + undici-types@6.21.0: {} + + util-deprecate@1.0.2: {} + + vite-node@3.2.4(@types/node@22.20.5)(tsx@4.23.15): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 2.0.3 + vite: 7.3.8(@types/node@22.20.5)(tsx@4.23.15) + transitivePeerDependencies: + - '@types/node' + - jiti + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + vite@7.3.8(@types/node@22.20.5)(tsx@4.23.15): + dependencies: + esbuild: 0.28.2 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + postcss: 8.5.33 + rollup: 4.68.8 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 22.20.5 + fsevents: 2.3.3 + tsx: 4.23.15 + + vitest@3.2.7(@types/node@22.20.5)(tsx@4.23.15): + dependencies: + '@types/chai': 5.2.3 + '@vitest/expect': 3.2.7 + '@vitest/mocker': 3.2.7(vite@7.3.8(@types/node@22.20.5)(tsx@4.23.15)) + '@vitest/pretty-format': 3.2.7 + '@vitest/runner': 3.2.7 + '@vitest/snapshot': 3.2.7 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.17 + tinypool: 1.1.1 + tinyrainbow: 2.0.0 + vite: 7.3.8(@types/node@22.20.5)(tsx@4.23.15) + vite-node: 3.2.4(@types/node@22.20.5)(tsx@4.23.15) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 22.20.5 + transitivePeerDependencies: + - jiti + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wrappy@1.0.2: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..3be4676 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +packages: + - 'schema' + - 'relay' diff --git a/relay/.gitignore b/relay/.gitignore new file mode 100644 index 0000000..52ded31 --- /dev/null +++ b/relay/.gitignore @@ -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 diff --git a/relay/package.json b/relay/package.json new file mode 100644 index 0000000..60b4b56 --- /dev/null +++ b/relay/package.json @@ -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" + } +} diff --git a/relay/src/bin.ts b/relay/src/bin.ts new file mode 100644 index 0000000..4ac5f43 --- /dev/null +++ b/relay/src/bin.ts @@ -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); + }); + }); +} diff --git a/relay/src/config.ts b/relay/src/config.ts new file mode 100644 index 0000000..7029bed --- /dev/null +++ b/relay/src/config.ts @@ -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 { + return { ...DEFAULT_RELAY_CONFIG, ...overrides }; +} diff --git a/relay/src/index.ts b/relay/src/index.ts new file mode 100644 index 0000000..ac8a270 --- /dev/null +++ b/relay/src/index.ts @@ -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'; diff --git a/relay/src/server.ts b/relay/src/server.ts new file mode 100644 index 0000000..cc88a7f --- /dev/null +++ b/relay/src/server.ts @@ -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> = { + '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 { + 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 { + 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/ 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; +} + +/** + * 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 { + 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((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(); + }) + }); + }); + }); +} diff --git a/relay/src/store.ts b/relay/src/store.ts new file mode 100644 index 0000000..47b7513 --- /dev/null +++ b/relay/src/store.ts @@ -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(); + } +} diff --git a/relay/src/verify.ts b/relay/src/verify.ts new file mode 100644 index 0000000..513d1a0 --- /dev/null +++ b/relay/src/verify.ts @@ -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 { + 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 { + 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; + + // 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(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 + }); +} diff --git a/relay/src/week.ts b/relay/src/week.ts new file mode 100644 index 0000000..3e18033 --- /dev/null +++ b/relay/src/week.ts @@ -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); +} diff --git a/relay/test/helpers.ts b/relay/test/helpers.ts new file mode 100644 index 0000000..4861037 --- /dev/null +++ b/relay/test/helpers.ts @@ -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); diff --git a/relay/test/interop.test.ts b/relay/test/interop.test.ts new file mode 100644 index 0000000..a2df303 --- /dev/null +++ b/relay/test/interop.test.ts @@ -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 { + 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'); + }); +}); diff --git a/relay/test/server.test.ts b/relay/test/server.test.ts new file mode 100644 index 0000000..f912a66 --- /dev/null +++ b/relay/test/server.test.ts @@ -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/', () => { + 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); + }); +}); diff --git a/relay/test/store.test.ts b/relay/test/store.test.ts new file mode 100644 index 0000000..ab2856b --- /dev/null +++ b/relay/test/store.test.ts @@ -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 { + 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); + }); +}); diff --git a/relay/test/verify.test.ts b/relay/test/verify.test.ts new file mode 100644 index 0000000..6ed5fcb --- /dev/null +++ b/relay/test/verify.test.ts @@ -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); + }); +}); diff --git a/relay/test/week.test.ts b/relay/test/week.test.ts new file mode 100644 index 0000000..f3daea8 --- /dev/null +++ b/relay/test/week.test.ts @@ -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); + }); +}); diff --git a/relay/tsconfig.json b/relay/tsconfig.json new file mode 100644 index 0000000..89601ff --- /dev/null +++ b/relay/tsconfig.json @@ -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" + ] +} diff --git a/relay/tsconfig.test.json b/relay/tsconfig.test.json new file mode 100644 index 0000000..1383c68 --- /dev/null +++ b/relay/tsconfig.test.json @@ -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" + ] +} diff --git a/relay/vitest.config.ts b/relay/vitest.config.ts new file mode 100644 index 0000000..2115bce --- /dev/null +++ b/relay/vitest.config.ts @@ -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 + } +}); diff --git a/schema/package.json b/schema/package.json new file mode 100644 index 0000000..85c7698 --- /dev/null +++ b/schema/package.json @@ -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" + } +} diff --git a/schema/src/index.ts b/schema/src/index.ts new file mode 100644 index 0000000..05283b4 --- /dev/null +++ b/schema/src/index.ts @@ -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'; diff --git a/schema/src/league.ts b/schema/src/league.ts new file mode 100644 index 0000000..6824d71 --- /dev/null +++ b/schema/src/league.ts @@ -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; + +/** + * 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); +} diff --git a/schema/src/result.ts b/schema/src/result.ts new file mode 100644 index 0000000..2af4916 --- /dev/null +++ b/schema/src/result.ts @@ -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 = { readonly ok: true; readonly value: T }; + +export type Err = { readonly ok: false; readonly error: E }; + +export type Result = Ok | Err; + +export function ok(value: T): Ok { + return { ok: true, value }; +} + +export function err(error: E): Err { + return { ok: false, error }; +} + +export function isOk(r: Result): r is Ok { + return r.ok; +} + +export function isErr(r: Result): r is Err { + 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>; +} + +export function ludusError( + code: string, + message: string, + extra?: { pointer?: string; detail?: Record } +): 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); +} diff --git a/schema/tsconfig.json b/schema/tsconfig.json new file mode 100644 index 0000000..cfae34c --- /dev/null +++ b/schema/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { "noEmit": true }, + "include": ["src/**/*.ts"] +} diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..23a037b --- /dev/null +++ b/tsconfig.base.json @@ -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 + } +}