diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..54cc10f --- /dev/null +++ b/.prettierignore @@ -0,0 +1,12 @@ +# Build output & caches +.next/ +out/ +coverage/ + +# Dependency lockfiles & generated TS artifacts +package-lock.json +next-env.d.ts +tsconfig.tsbuildinfo + +# Drizzle-generated migration metadata (machine-written; not hand-edited) +drizzle/meta/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 256d5b2..63e31b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -155,6 +155,45 @@ compare links at the bottom are pointed at the `v1.0.0` tag. wraps long lines onto a second line, so both stay fully readable (desktop is unchanged). +#### Gameplay + +- **Food is no longer clipped from an adjacent lane mid-merge:** food now + resolves strictly against the runner's nearest lane, so sliding toward a + booster can't accidentally eat the junk in the lane you're leaving — booster + gauntlets stay dodgeable as designed. + +#### Internals + +- **Per-match track length** is read from the active track instead of the + shared default, removing a latent mismatch if a future seed changes length. +- **Lobby host/track** are read from the host's own presence rather than + whichever seat happened to arrive first. + +#### Tooling & docs + +- **Repo is Prettier-clean** and CI now runs `format:check` (added a + `.prettierignore` for build output and generated migration metadata), so + formatting drift can't land again. +- **Integration tests run locally and in CI:** `test:integration` auto-loads + `.env.test` (via `--env-file-if-exists`), and a new + `tests/integration/nonce-store.test.ts` covers the durable `auth_nonces` + replay guard against a real Neon test branch. +- **Docs corrected to match the implementation:** rolling 7-day session (not a + 60-minute timeout), auth methods are NIP-07 / NIP-46 / nsec (not `nostr-login`), + `.env.local` setup, the scoring table (booster bonus added, the unimplemented + sprint/overtake row removed), the ±10s NIP-98 window, and the junk-food copy + (bounded bathroom setback, not "back to the start"). + +### Security + +- **Host-only race start:** the `control` (start) event is now verified against + the match host (signed by the host's identity), so a rogue peer subscribed to + the channel can no longer force-start the race for everyone. +- **Durable NIP-98 replay protection:** single-use login nonces moved from + in-process memory to a Postgres `auth_nonces` table, so a captured + `Authorization` header can't be replayed by landing on a different Vercel + serverless instance. + statement-breakpoint +CREATE INDEX "auth_nonces_expires_idx" ON "auth_nonces" USING btree ("expires_at"); \ No newline at end of file diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..3281a9c --- /dev/null +++ b/drizzle/meta/0004_snapshot.json @@ -0,0 +1,416 @@ +{ + "id": "2e9dfaed-88b6-4245-aa31-e6488b38f46d", + "prevId": "9ff88bb9-ef8b-4745-bee0-258c07bce518", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.auth_nonces": { + "name": "auth_nonces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar(64)", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "auth_nonces_expires_idx": { + "name": "auth_nonces_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.matches": { + "name": "matches", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "nostr_id": { + "name": "nostr_id", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "track_id": { + "name": "track_id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "host_pubkey": { + "name": "host_pubkey", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "matches_host_idx": { + "name": "matches_host_idx", + "columns": [ + { + "expression": "host_pubkey", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "matches_nostr_id_unique": { + "name": "matches_nostr_id_unique", + "nullsNotDistinct": false, + "columns": [ + "nostr_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.results": { + "name": "results", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "match_id": { + "name": "match_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pubkey": { + "name": "pubkey", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "points": { + "name": "points", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "finish_time": { + "name": "finish_time", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "results_match_idx": { + "name": "results_match_idx", + "columns": [ + { + "expression": "match_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "results_pubkey_idx": { + "name": "results_pubkey_idx", + "columns": [ + { + "expression": "pubkey", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "results_match_pubkey_idx": { + "name": "results_match_pubkey_idx", + "columns": [ + { + "expression": "match_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pubkey", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "results_match_id_matches_id_fk": { + "name": "results_match_id_matches_id_fk", + "tableFrom": "results", + "tableTo": "matches", + "columnsFrom": [ + "match_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "pubkey": { + "name": "pubkey", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(40)", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "bio": { + "name": "bio", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "banner_url": { + "name": "banner_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lud16": { + "name": "lud16", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "locale": { + "name": "locale", + "type": "varchar(2)", + "primaryKey": false, + "notNull": true, + "default": "'es'" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_pubkey_idx": { + "name": "users_pubkey_idx", + "columns": [ + { + "expression": "pubkey", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_slug_idx": { + "name": "users_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_active_idx": { + "name": "users_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_pubkey_unique": { + "name": "users_pubkey_unique", + "nullsNotDistinct": false, + "columns": [ + "pubkey" + ] + }, + "users_slug_unique": { + "name": "users_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 43386ba..75d4fee 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1780803281720, "tag": "0003_solid_black_bolt", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1782333986254, + "tag": "0004_furry_hex", + "breakpoints": true } ] } \ No newline at end of file diff --git a/lib/db/schema.ts b/lib/db/schema.ts index 96251b0..a807412 100644 --- a/lib/db/schema.ts +++ b/lib/db/schema.ts @@ -46,6 +46,24 @@ export const users = pgTable( ] ); +// --- Auth nonces --- +// Single-use guard for NIP-98 login events (anti-replay). Each accepted auth +// event's id is recorded here so a captured `Authorization: Nostr …` header +// can't be replayed within its freshness window to mint a second session. +// Durable (not in-process memory) so it holds across Vercel's serverless +// instances and cold starts. Rows are short-lived: `expires_at` is ~the +// validation window, and the login path sweeps expired rows so the table +// stays tiny without a cron. +export const authNonces = pgTable( + "auth_nonces", + { + // The Nostr event id (sha256 hex) — the natural idempotency key. + id: varchar("id", { length: 64 }).primaryKey(), + expires_at: timestamp("expires_at").notNull(), + }, + (table) => [index("auth_nonces_expires_idx").on(table.expires_at)] +); + // --- Matches --- // One row per *completed* race that gets persisted. The live match runs // entirely over Nostr (no server); we only write to the DB when a match diff --git a/lib/game/scenes/race-scene.ts b/lib/game/scenes/race-scene.ts index 25fa2a2..1277f26 100644 --- a/lib/game/scenes/race-scene.ts +++ b/lib/game/scenes/race-scene.ts @@ -31,7 +31,7 @@ import type { RaceNet } from "../race-net"; import type { RunnerStatus } from "@/lib/multiplayer/types"; /** - * RaceScene — Phase 1, single-player. + * RaceScene — the Phaser race (single-player, practice, and multiplayer). * * Fake-2.5D daytime athletics track. The player runs at the bottom edge * (distance d = 0) and the world scrolls toward them; everything "ahead" is @@ -42,7 +42,6 @@ import type { RunnerStatus } from "@/lib/multiplayer/types"; const NEAR = 230; // perspective strength (bigger = flatter) const VIEW_DISTANCE = 750; // how far ahead food/signs are rendered -const HIT_LANE_TOLERANCE = 0.5; // how close to a lane center counts as "in it" const FOOD_POOL_SIZE = 20; // reusable emoji slots for visible food const SIGN_POOL_SIZE = 6; // reusable billboards for visible signs // Signs only render once their perspective scale passes SIGN_MIN_SCALE, i.e. @@ -150,7 +149,7 @@ export class RaceScene extends Phaser.Scene { // Player state. private now = 0; // last frame timestamp (ms) - private playerDistance = 0; // 0..TRACK.length + private playerDistance = 0; // 0..this.track.length private playerLane = (LANES - 1) / 2; // fractional, tweened private targetLane = Math.round((LANES - 1) / 2); private startLane = Math.round((LANES - 1) / 2); // set from the chosen character @@ -600,7 +599,7 @@ export class RaceScene extends Phaser.Scene { const raw = window.sessionStorage.getItem(key); if (raw === null) return null; const dist = Number(raw); - return Number.isFinite(dist) && dist > 0 && dist < TRACK.length + return Number.isFinite(dist) && dist > 0 && dist < this.track.length ? dist : null; } catch { @@ -616,7 +615,10 @@ export class RaceScene extends Phaser.Scene { if (this.resumeSaveAcc < 1) return; // ~1 Hz is plenty this.resumeSaveAcc = 0; try { - window.sessionStorage.setItem(key, String(Math.round(this.playerDistance))); + window.sessionStorage.setItem( + key, + String(Math.round(this.playerDistance)) + ); } catch { // Storage unavailable (private mode / quota) — resume is best-effort. } @@ -765,7 +767,7 @@ export class RaceScene extends Phaser.Scene { /** Broadcast the local runner over the match (no-op without a RaceNet). */ private publishSelf() { this.net?.publishSelf({ - progress: Math.min(1, this.playerDistance / TRACK.length), + progress: Math.min(1, this.playerDistance / this.track.length), lane: Phaser.Math.Clamp(Math.round(this.playerLane), 0, LANES - 1), speed: this.currentSpeed, energy: this.energy, @@ -823,10 +825,12 @@ export class RaceScene extends Phaser.Scene { } private resolveFood() { + // The runner always occupies exactly one (nearest) lane — the fractional + // `playerLane` is only the visual tween. Resolving food strictly by the + // rounded lane means a mid-tween merge can't clip food in the lane you're + // leaving (so a booster gauntlet stays dodgeable as documented). const lane = Math.round(this.playerLane); - const inLane = (f: FoodItem) => - Math.abs(f.lane - this.playerLane) <= HIT_LANE_TOLERANCE || - f.lane === lane; + const inLane = (f: FoodItem) => f.lane === lane; for (const f of [ ...this.track.goodFood, @@ -902,7 +906,7 @@ export class RaceScene extends Phaser.Scene { } private checkFinish() { - if (this.playerDistance >= TRACK.length) { + if (this.playerDistance >= this.track.length) { this.finished = true; this.status = "finished"; this.points += POINTS.finishBonus; @@ -1193,7 +1197,7 @@ export class RaceScene extends Phaser.Scene { g.clear(); // Finish line — a black/white checker band, if within view. - const finishD = TRACK.length - this.playerDistance; + const finishD = this.track.length - this.playerDistance; if (finishD >= 0 && finishD <= VIEW_DISTANCE) { const l = this.project(finishD, -0.5); const r = this.project(finishD, LANES - 0.5); @@ -1361,7 +1365,10 @@ export class RaceScene extends Phaser.Scene { g.clear(); const visible = this.remotes - .map((r) => ({ r, d: r.progress * TRACK.length - this.playerDistance })) + .map((r) => ({ + r, + d: r.progress * this.track.length - this.playerDistance, + })) .filter(({ d }) => d >= 0 && d <= VIEW_DISTANCE) .sort((a, b) => b.d - a.d); @@ -1486,7 +1493,12 @@ export class RaceScene extends Phaser.Scene { g.fillStyle(0xffffff, 0.9); g.fillCircle(x, top, 3); // finish marker - const plot = (progress: number, lane: number, color: number, self: boolean) => { + const plot = ( + progress: number, + lane: number, + color: number, + self: boolean + ) => { const py = bottom - Phaser.Math.Clamp(progress, 0, 1) * h; const px = x + (lane - (LANES - 1) / 2) * 7; g.fillStyle(color, 1); @@ -1499,7 +1511,7 @@ export class RaceScene extends Phaser.Scene { for (const r of this.remotes) plot(r.progress, r.lane, r.color, false); plot( - Math.min(1, this.playerDistance / TRACK.length), + Math.min(1, this.playerDistance / this.track.length), this.playerLane, laneColor(this.startLane), true @@ -1537,7 +1549,7 @@ export class RaceScene extends Phaser.Scene { 6 ); - const pct = Math.min(100, (this.playerDistance / TRACK.length) * 100); + const pct = Math.min(100, (this.playerDistance / this.track.length) * 100); this.statusText.setText( `${pct.toFixed(0)}% · ${this.points} pts · ${this.elapsed.toFixed(1)}s` ); diff --git a/lib/multiplayer/discovery.ts b/lib/multiplayer/discovery.ts index 3737df8..9508dda 100644 --- a/lib/multiplayer/discovery.ts +++ b/lib/multiplayer/discovery.ts @@ -84,13 +84,19 @@ export function selectOpenMatches( const updatedAt = Math.max(...entries.map((s) => s.createdAt)); if (now - updatedAt > FRESH_WINDOW_MS) continue; // stale / abandoned - const host = entries[0].host; + // The host is the peer whose own presence names itself as host (every seat + // echoes the same host pubkey, but reading it from the host's own seat is + // robust to a joiner's presence arriving first or echoing a stale value). + const host = + Object.keys(seats).find((pk) => seats[pk]!.host === pk) ?? + entries[0].host; + const hostSeat = seats[host]; matches.push({ matchId, host, - hostName: seats[host]?.name, - raceName: seats[host]?.raceName, - trackId: entries[0].trackId, + hostName: hostSeat?.name, + raceName: hostSeat?.raceName, + trackId: hostSeat?.trackId ?? entries[0].trackId, players: entries.length, updatedAt, }); diff --git a/lib/multiplayer/events.ts b/lib/multiplayer/events.ts index d92a377..e4c5789 100644 --- a/lib/multiplayer/events.ts +++ b/lib/multiplayer/events.ts @@ -99,11 +99,13 @@ export function buildFinishEvent( * event's outer Nostr author (the key that actually signed it) — which is the * sender's ephemeral session key, *not* the real identity in `data.pubkey`. * Clients verify it matches the `sessionKey` that identity announced in its - * presence, so a peer can't spoof frames as someone else. + * presence, so a peer can't spoof frames as someone else. For `control`, + * `signer` is the real identity that signed the start event; the reducer + * checks it against the match host so only the host can drive the lifecycle. */ export type ParsedEvent = | { type: "discovery"; data: MatchDiscovery } - | { type: "control"; data: MatchControl } + | { type: "control"; data: MatchControl; signer: string } | { type: "runner"; data: RunnerState; signer: string } | { type: "finish"; data: MatchFinish; signer: string }; @@ -127,7 +129,9 @@ export function parseEvent(event: NostrEvent): ParsedEvent | null { } case KIND.CONTROL: { const r = MatchControlSchema.safeParse(content); - return r.success ? { type: "control", data: r.data } : null; + return r.success + ? { type: "control", data: r.data, signer: event.pubkey } + : null; } case KIND.RUNNER: { const r = RunnerStateSchema.safeParse(content); diff --git a/lib/multiplayer/match-state.ts b/lib/multiplayer/match-state.ts index 153f733..f8dbabf 100644 --- a/lib/multiplayer/match-state.ts +++ b/lib/multiplayer/match-state.ts @@ -226,6 +226,11 @@ export function applyEvent( case "control": { if (event.data.matchId !== state.matchId) return state; + // Only the host may drive the lifecycle: the start event is signed by the + // host's real identity, so reject one signed by anyone else. If we don't + // yet know the host (their presence hasn't propagated), accept best-effort + // — matching the no-authoritative-server scope (ARCHITECTURE §0). + if (state.host && event.signer !== state.host) return state; // Only ever advance the lifecycle forward. if (state.status !== "waiting") { return { ...state, startAt: event.data.startAt }; @@ -250,7 +255,9 @@ export function applyEvent( const finishes = { ...state.finishes, [event.data.pubkey]: event.data }; // The grace deadline is anchored to the *earliest* finish, so every // client converges on the same countdown end without a server clock. - const earliest = Math.min(...Object.values(finishes).map((f) => f.finishTime)); + const earliest = Math.min( + ...Object.values(finishes).map((f) => f.finishTime) + ); const next: MatchSnapshot = { ...state, finishes, diff --git a/lib/nostr/nonce-store.ts b/lib/nostr/nonce-store.ts index f3ea8ab..6a881f3 100644 --- a/lib/nostr/nonce-store.ts +++ b/lib/nostr/nonce-store.ts @@ -1,41 +1,47 @@ import "server-only"; +import { lt } from "drizzle-orm"; +import { getDb } from "@/lib/db"; +import { authNonces } from "@/lib/db/schema"; + /** * Single-use guard for NIP-98 auth events (anti-replay). * * The login route accepts a signed event whose `created_at` is within a ±10s * window. Without this, a captured `Authorization: Nostr …` header could be * replayed within that window to mint a second session for the same pubkey. - * We remember each event id we've honored until its window has surely passed, - * and reject a repeat. + * We record each event id we've honored and reject a repeat. * - * The set lives in process memory (per instance) and is swept on a TTL, so it - * stays small and needs no extra infrastructure. + * The record lives in Postgres (`auth_nonces`), **not** process memory, so it + * holds across Vercel's serverless instances and cold starts — an in-memory + * `Set` would only guard a single lambda, letting a replay slip through on a + * different instance. Login is infrequent (and already hits the DB for the user + * row), so the extra round-trip is negligible. */ // Keep ids a bit longer than the validation window so a replay can't outlast // the memory of it (the event itself is rejected as too-old past ~10s anyway). const TTL_MS = 60_000; -const seen = new Map(); // event id → expiry (unix ms) -let lastSweep = 0; - -function sweep(now: number): void { - if (now - lastSweep < TTL_MS) return; - lastSweep = now; - for (const [id, expiry] of seen) { - if (now >= expiry) seen.delete(id); - } -} - /** - * Record `id` as used; returns false if it was already used (a replay). + * Record `id` as used; resolves false if it was already used (a replay). * `id` is the Nostr event id (a 64-char hex sha256 of the event). + * + * Implemented as an idempotent insert: `ON CONFLICT DO NOTHING` writes no row + * for a repeat id, so an empty `returning()` is the replay signal. Expired rows + * are swept first — login is rare, so the extra indexed delete keeps the table + * self-cleaning without a cron. */ -export function claimNonce(id: string, now: number = Date.now()): boolean { - sweep(now); - const expiry = seen.get(id); - if (expiry !== undefined && now < expiry) return false; - seen.set(id, now + TTL_MS); - return true; +export async function claimNonce( + id: string, + now: number = Date.now() +): Promise { + const db = getDb(); + await db.delete(authNonces).where(lt(authNonces.expires_at, new Date(now))); + const inserted = await db + .insert(authNonces) + .values({ id, expires_at: new Date(now + TTL_MS) }) + .onConflictDoNothing({ target: authNonces.id }) + .returning({ id: authNonces.id }); + return inserted.length > 0; } diff --git a/lib/nostr/signers.ts b/lib/nostr/signers.ts index d0d4697..4e25bf0 100644 --- a/lib/nostr/signers.ts +++ b/lib/nostr/signers.ts @@ -9,7 +9,11 @@ * policy. */ -import { finalizeEvent, generateSecretKey, getPublicKey } from "nostr-tools/pure"; +import { + finalizeEvent, + generateSecretKey, + getPublicKey, +} from "nostr-tools/pure"; import type { BunkerSigner } from "nostr-tools/nip46"; import type { NostrEvent, UnsignedNostrEvent } from "./types"; import type { SignerType } from "@/lib/schemas/auth"; diff --git a/lib/rate-limit.ts b/lib/rate-limit.ts index 992f3d3..8d57eb5 100644 --- a/lib/rate-limit.ts +++ b/lib/rate-limit.ts @@ -59,7 +59,10 @@ export function rateLimit( w.count += 1; return { ok: true, retryAfter: 0 }; } - return { ok: false, retryAfter: Math.max(1, Math.ceil((w.resetAt - now) / 1000)) }; + return { + ok: false, + retryAfter: Math.max(1, Math.ceil((w.resetAt - now) / 1000)), + }; } /** Best-effort client IP from the proxy headers (Vercel sets these). */ @@ -80,7 +83,11 @@ export function enforceRateLimit( limit: number, windowMs: number ): NextResponse | null { - const { ok, retryAfter } = rateLimit(`${scope}:${clientIp(req)}`, limit, windowMs); + const { ok, retryAfter } = rateLimit( + `${scope}:${clientIp(req)}`, + limit, + windowMs + ); if (ok) return null; return NextResponse.json( { error: "rate_limited" }, diff --git a/lib/schemas/match.ts b/lib/schemas/match.ts index 8d9f6be..9b51dd6 100644 --- a/lib/schemas/match.ts +++ b/lib/schemas/match.ts @@ -21,7 +21,11 @@ import { /** Per-race score, bounded to a sane range so a forged frame/POST can't write * an absurd value (anti-abuse clamp, not the gameplay cap). */ -const PointsSchema = z.number().int().min(MATCH_POINTS_MIN).max(MATCH_POINTS_MAX); +const PointsSchema = z + .number() + .int() + .min(MATCH_POINTS_MIN) + .max(MATCH_POINTS_MAX); /** Finishing place — 1-based, never beyond the lane (player) count. */ const PositionSchema = z.number().int().min(1).max(LANES); diff --git a/messages/en.json b/messages/en.json index 5240d8c..f216855 100644 --- a/messages/en.json +++ b/messages/en.json @@ -18,7 +18,7 @@ }, "landing": { "title": "BitByBit RUN", - "subtitle": "Race down the track. Grab the good food to sprint, dodge the junk or you'll be sent back to the start. First to the finish wins.", + "subtitle": "Race down the track. Grab the good food to sprint, dodge the junk or it'll send you to the bathroom and cost you ground. First to the finish wins.", "tagline": "Run, Eat, Win 🏃💨\nCardio never paid this well.", "play": "Play", "howToPlay": "How to play" diff --git a/messages/es.json b/messages/es.json index d39a9c5..9f9b639 100644 --- a/messages/es.json +++ b/messages/es.json @@ -18,7 +18,7 @@ }, "landing": { "title": "BitByBit RUN", - "subtitle": "Corré por la pista. Agarrá la comida buena para acelerar, esquivá la chatarra o volvés al principio. El primero en llegar gana.", + "subtitle": "Corré por la pista. Agarrá la comida buena para acelerar, esquivá la chatarra o te manda al baño y perdés terreno. El primero en llegar gana.", "tagline": "Corré, Comé, Ganá 🏃💨\nEl cardio nunca pagó tan bien.", "play": "Jugar", "howToPlay": "Cómo jugar" diff --git a/package.json b/package.json index 23c1560..c3658c6 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "test": "vitest run", "test:watch": "vitest", "test:unit": "vitest run tests/unit", - "test:integration": "vitest run tests/integration --passWithNoTests", + "test:integration": "node --env-file-if-exists=.env.test ./node_modules/vitest/vitest.mjs run tests/integration --passWithNoTests", "db:generate": "drizzle-kit generate", "db:migrate": "tsx scripts/migrate.ts", "test:db:migrate": "MIGRATE_ENV_FILE=.env.test tsx scripts/migrate.ts", diff --git a/tests/integration/nonce-store.test.ts b/tests/integration/nonce-store.test.ts new file mode 100644 index 0000000..0ce2516 --- /dev/null +++ b/tests/integration/nonce-store.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment node +import { describe, it, expect, beforeEach } from "vitest"; +import { claimNonce } from "@/lib/nostr/nonce-store"; +import { cleanNonces } from "./setup"; + +/** + * Exercises the durable NIP-98 anti-replay guard against the real Neon test + * branch (the `auth_nonces` table + `ON CONFLICT DO NOTHING` semantics). + * Skipped when no DATABASE_URL is configured so the unit suite still runs + * anywhere; run with `.env.test` loaded. + */ +const HAS_DB = !!process.env.DATABASE_URL; + +// A fixed base time well inside the timestamp range (the store stamps +// `expires_at = now + TTL`); the unit suite mocks the DB, this hits Postgres. +const NOW = 1_700_000_000_000; + +describe.skipIf(!HAS_DB)("nonce-store (integration)", () => { + beforeEach(async () => { + await cleanNonces(); + }); + + it("honors an id once, then rejects a replay", async () => { + const id = "a".repeat(64); + expect(await claimNonce(id, NOW)).toBe(true); // first use → row inserted + expect(await claimNonce(id, NOW + 1_000)).toBe(false); // replay → conflict + }); + + it("tracks distinct ids independently", async () => { + expect(await claimNonce("b".repeat(64), NOW)).toBe(true); + expect(await claimNonce("c".repeat(64), NOW)).toBe(true); + }); + + it("sweeps expired rows, so an id past its TTL is free again", async () => { + const id = "d".repeat(64); + expect(await claimNonce(id, NOW)).toBe(true); + // TTL is 60s; a claim well past it deletes the expired row first, so the + // same id can be inserted again. (In production the NIP-98 ±10s freshness + // check rejects such a late replay upstream — this just proves the store + // self-cleans rather than growing forever.) + expect(await claimNonce(id, NOW + 120_000)).toBe(true); + }); +}); diff --git a/tests/integration/setup.ts b/tests/integration/setup.ts index 414113b..1101a56 100644 --- a/tests/integration/setup.ts +++ b/tests/integration/setup.ts @@ -13,3 +13,12 @@ export async function cleanDb(): Promise { sql`truncate table results, matches restart identity cascade` ); } + +/** + * Wipe the `auth_nonces` table (the durable NIP-98 anti-replay store). Kept + * separate from `cleanDb` since it's independent of the match tables. + */ +export async function cleanNonces(): Promise { + const db = getDb(); + await db.execute(sql`truncate table auth_nonces`); +} diff --git a/tests/unit/app/api/matches.test.ts b/tests/unit/app/api/matches.test.ts index b340514..5f13a78 100644 --- a/tests/unit/app/api/matches.test.ts +++ b/tests/unit/app/api/matches.test.ts @@ -22,7 +22,10 @@ function post(body: unknown): NextRequest { // A fresh IP per request so the (real) rate limiter never interferes. return new NextRequest("https://x.test/api/matches", { method: "POST", - headers: { "content-type": "application/json", "x-forwarded-for": `10.0.0.${ip++}` }, + headers: { + "content-type": "application/json", + "x-forwarded-for": `10.0.0.${ip++}`, + }, body: typeof body === "string" ? body : JSON.stringify(body), }); } diff --git a/tests/unit/lib/game/track.test.ts b/tests/unit/lib/game/track.test.ts index ab252b1..dcec2e8 100644 --- a/tests/unit/lib/game/track.test.ts +++ b/tests/unit/lib/game/track.test.ts @@ -14,8 +14,12 @@ describe("buildTrack (seeded per-match layout)", () => { const a = buildTrack("match-abc"); const b = buildTrack("match-xyz"); // Food positions should differ across seeds (not the same fixed track). - const posA = a.goodFood.map((f) => `${f.lane}:${Math.round(f.at)}`).join(","); - const posB = b.goodFood.map((f) => `${f.lane}:${Math.round(f.at)}`).join(","); + const posA = a.goodFood + .map((f) => `${f.lane}:${Math.round(f.at)}`) + .join(","); + const posB = b.goodFood + .map((f) => `${f.lane}:${Math.round(f.at)}`) + .join(","); expect(posA).not.toBe(posB); }); diff --git a/tests/unit/lib/multiplayer/match-client.test.ts b/tests/unit/lib/multiplayer/match-client.test.ts index b116fe0..7e40814 100644 --- a/tests/unit/lib/multiplayer/match-client.test.ts +++ b/tests/unit/lib/multiplayer/match-client.test.ts @@ -242,10 +242,13 @@ describe("MatchClient plausibility guard (anti-cheat)", () => { await guest.announceSelf({ lane: 1, name: "Guest" }); // A legit frame (signed by guest's session key) is accepted. - await guest.broadcastRunner({ ...moving, lane: 1, progress: 0.5 }, { force: true }); - expect(host.getSnapshot().runners[guestSigner.pubkey]?.progress).toBeCloseTo( - 0.5 + await guest.broadcastRunner( + { ...moving, lane: 1, progress: 0.5 }, + { force: true } ); + expect( + host.getSnapshot().runners[guestSigner.pubkey]?.progress + ).toBeCloseTo(0.5); // An impostor forges a frame *claiming* to be the guest, signed by a foreign // key. The binding check drops it, so the guest's state is unchanged. @@ -262,9 +265,9 @@ describe("MatchClient plausibility guard (anti-cheat)", () => { }) ) ); - expect(host.getSnapshot().runners[guestSigner.pubkey]?.progress).toBeCloseTo( - 0.5 - ); + expect( + host.getSnapshot().runners[guestSigner.pubkey]?.progress + ).toBeCloseTo(0.5); host.leave(); guest.leave(); diff --git a/tests/unit/lib/multiplayer/match-state.test.ts b/tests/unit/lib/multiplayer/match-state.test.ts index f1243c9..4ad8b8a 100644 --- a/tests/unit/lib/multiplayer/match-state.test.ts +++ b/tests/unit/lib/multiplayer/match-state.test.ts @@ -149,6 +149,7 @@ describe("match-state control + countdown", () => { trackId: "classic-v1", startAt: 999, }, + signer: A, }; const s = applyEvent(base(), event); expect(s.status).toBe("countdown"); @@ -161,9 +162,35 @@ describe("match-state control + countdown", () => { const countdown = { ...waiting, status: "countdown" as const, startAt: 1 }; expect(beginPlaying(countdown).status).toBe("playing"); }); + + it("only the host can start: a non-host control event is ignored", () => { + const hosted = { ...base(), host: A }; + const control = (signer: string): ParsedEvent => ({ + type: "control", + data: { type: "start", matchId: "m1", trackId: "classic-v1", startAt: 5 }, + signer, + }); + // A rogue peer (B) cannot force-start the race. + expect(applyEvent(hosted, control(B))).toBe(hosted); + // The host (A) can. + expect(applyEvent(hosted, control(A)).status).toBe("countdown"); + }); + + it("accepts control best-effort when the host is not yet known", () => { + // host === "" (presence still propagating) → can't verify, so accept. + const s = applyEvent(base(), { + type: "control", + data: { type: "start", matchId: "m1", trackId: "classic-v1", startAt: 5 }, + signer: B, + }); + expect(s.status).toBe("countdown"); + }); }); -function runnerEvent(pubkey: string, over: Partial = {}): ParsedEvent { +function runnerEvent( + pubkey: string, + over: Partial = {} +): ParsedEvent { return { type: "runner", data: runner(pubkey, over), signer: pubkey }; } @@ -293,6 +320,7 @@ describe("match-state leaving a match", () => { const started: ParsedEvent = { type: "control", data: { type: "start", matchId: "m1", trackId: "classic-v1", startAt: 1 }, + signer: A, }; let s = base(); s = applyEvent(s, started); diff --git a/tests/unit/lib/multiplayer/store.test.ts b/tests/unit/lib/multiplayer/store.test.ts index 8f74b49..c0b2d93 100644 --- a/tests/unit/lib/multiplayer/store.test.ts +++ b/tests/unit/lib/multiplayer/store.test.ts @@ -28,7 +28,14 @@ vi.mock("@/lib/db", () => { // awaiting it resolves to the canned rows (Drizzle query builders are // thenable the same way). const qb: Record = {}; - for (const m of ["select", "from", "leftJoin", "groupBy", "limit", "offset"]) { + for (const m of [ + "select", + "from", + "leftJoin", + "groupBy", + "limit", + "offset", + ]) { qb[m] = () => qb; } qb.orderBy = (...args: unknown[]) => { @@ -40,10 +47,7 @@ vi.mock("@/lib/db", () => { return { getDb: () => qb }; }); -import { - getLeaderboard, - LEADERBOARD_SORTS, -} from "@/lib/multiplayer/store"; +import { getLeaderboard, LEADERBOARD_SORTS } from "@/lib/multiplayer/store"; describe("getLeaderboard", () => { it("coerces the driver's string counts to numbers", async () => { diff --git a/tests/unit/lib/nostr/nip46-login.test.ts b/tests/unit/lib/nostr/nip46-login.test.ts index 555386f..03847d5 100644 --- a/tests/unit/lib/nostr/nip46-login.test.ts +++ b/tests/unit/lib/nostr/nip46-login.test.ts @@ -40,7 +40,11 @@ import { } from "@/lib/nostr/nip46-login"; const PUBKEY = "a".repeat(64); -const POINTER = { relays: ["wss://relay.example"], pubkey: PUBKEY, secret: null }; +const POINTER = { + relays: ["wss://relay.example"], + pubkey: PUBKEY, + secret: null, +}; // Minimal in-memory localStorage — the suite runs in the node environment, // where there's no DOM, but nip46-login only needs get/set/remove. diff --git a/tests/unit/lib/nostr/nonce-store.test.ts b/tests/unit/lib/nostr/nonce-store.test.ts index 020eb07..0cbe752 100644 --- a/tests/unit/lib/nostr/nonce-store.test.ts +++ b/tests/unit/lib/nostr/nonce-store.test.ts @@ -1,25 +1,72 @@ // @vitest-environment node -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +/** + * Unit coverage for the durable (Postgres-backed) NIP-98 anti-replay guard. + * We stub `@/lib/db` with an in-memory stand-in for the `auth_nonces` table so + * the insert/`onConflictDoNothing`/`returning` contract is exercised without a + * database (the real SQL is covered by the DB-gated integration suite). + */ + +// In-memory stand-in for the auth_nonces table: id → expiry (ms). +const rows = new Map(); +let deleteCalls = 0; + +vi.mock("@/lib/db", () => { + const db = { + // delete(table).where(cond) — we can't read the drizzle condition, so the + // test drives expiry directly via the exported helper below; here we just + // record that the sweep was issued. + delete: () => ({ + where: () => { + deleteCalls += 1; + return Promise.resolve([]); + }, + }), + // insert(table).values(v).onConflictDoNothing().returning() — first write + // of an id returns a row; a repeat returns [] (conflict did nothing). + insert: () => { + let pending: { id: string; expires_at: Date } | null = null; + const builder = { + values: (v: { id: string; expires_at: Date }) => { + pending = v; + return builder; + }, + onConflictDoNothing: () => builder, + returning: () => { + const { id, expires_at } = pending!; + if (rows.has(id)) return Promise.resolve([]); // replay + rows.set(id, expires_at.getTime()); + return Promise.resolve([{ id }]); + }, + }; + return builder; + }, + }; + return { getDb: () => db, authNonces: {} }; +}); + import { claimNonce } from "@/lib/nostr/nonce-store"; -describe("claimNonce (NIP-98 anti-replay)", () => { - it("honors an id once, then rejects a replay within the window", () => { - const id = `e${Math.random()}`; - const t0 = 1_000_000; - expect(claimNonce(id, t0)).toBe(true); // first use - expect(claimNonce(id, t0 + 100)).toBe(false); // replay +beforeEach(() => { + rows.clear(); + deleteCalls = 0; +}); + +describe("claimNonce (NIP-98 anti-replay, durable)", () => { + it("honors an id once, then rejects a replay", async () => { + const id = "e".repeat(64); + expect(await claimNonce(id, 1_000_000)).toBe(true); // first use + expect(await claimNonce(id, 1_000_100)).toBe(false); // replay }); - it("allows the id again once its window has elapsed", () => { - const id = `e${Math.random()}`; - const t0 = 2_000_000; - expect(claimNonce(id, t0)).toBe(true); - expect(claimNonce(id, t0 + 61_000)).toBe(true); // past TTL → fresh + it("tracks distinct ids independently", async () => { + expect(await claimNonce("a".repeat(64), 3_000_000)).toBe(true); + expect(await claimNonce("b".repeat(64), 3_000_000)).toBe(true); }); - it("tracks distinct ids independently", () => { - const t0 = 3_000_000; - expect(claimNonce(`a${Math.random()}`, t0)).toBe(true); - expect(claimNonce(`b${Math.random()}`, t0)).toBe(true); + it("sweeps expired rows before each claim", async () => { + await claimNonce("c".repeat(64), 4_000_000); + expect(deleteCalls).toBe(1); }); }); diff --git a/tests/unit/lib/nostr/signers.test.ts b/tests/unit/lib/nostr/signers.test.ts index 13eeebb..ad19307 100644 --- a/tests/unit/lib/nostr/signers.test.ts +++ b/tests/unit/lib/nostr/signers.test.ts @@ -13,7 +13,15 @@ const EVENT = { }; function signed() { - return { id: "id", pubkey: PUBKEY, created_at: 0, kind: 1, tags: [], content: "", sig: "sig" }; + return { + id: "id", + pubkey: PUBKEY, + created_at: 0, + kind: 1, + tags: [], + content: "", + sig: "sig", + }; } /** Minimal BunkerSigner stand-in — only the methods makeNip46Signer touches. */ diff --git a/tests/unit/lib/schemas/match.test.ts b/tests/unit/lib/schemas/match.test.ts index a936404..1507f8f 100644 --- a/tests/unit/lib/schemas/match.test.ts +++ b/tests/unit/lib/schemas/match.test.ts @@ -83,8 +83,10 @@ describe("schemas/match RunnerStateSchema", () => { it("rejects absurd points so a forged frame can't inflate standings", () => { expect( - RunnerStateSchema.safeParse({ ...validRunner, points: MATCH_POINTS_MAX + 1 }) - .success + RunnerStateSchema.safeParse({ + ...validRunner, + points: MATCH_POINTS_MAX + 1, + }).success ).toBe(false); }); }); @@ -188,7 +190,12 @@ describe("schemas/match PersistMatchSchema", () => { // out-of-range placements, or inconsistent standings. it("rejects points beyond the anti-abuse ceiling", () => { const standings = [ - { pubkey: PK, position: 1, points: MATCH_POINTS_MAX + 1, finishTime: 100 }, + { + pubkey: PK, + position: 1, + points: MATCH_POINTS_MAX + 1, + finishTime: 100, + }, { pubkey: "c".repeat(64), position: 2, points: 0, finishTime: null }, ]; expect(PersistMatchSchema.safeParse({ ...base, standings }).success).toBe(