From ee8a344c42b8f5b9adf05caca93540d476a8951d Mon Sep 17 00:00:00 2001 From: analiaacosta2023 Date: Wed, 24 Jun 2026 18:57:10 -0300 Subject: [PATCH 1/5] chore: format the repo with Prettier and add .prettierignore Brings the whole tree to Prettier code style and ignores build output and generated migration metadata so formatting drift can't land again. Co-Authored-By: Claude Opus 4.8 (1M context) --- .prettierignore | 12 +++ app/[locale]/opengraph-image.tsx | 90 +++++++++---------- app/api/matches/route.ts | 4 +- app/apple-icon.tsx | 52 ++++++----- app/icon.tsx | 52 ++++++----- components/game/interstitial-ad.tsx | 7 +- components/game/match-results.tsx | 4 +- components/game/play-stage.tsx | 13 ++- components/game/runner-lobby.tsx | 7 +- .../locale-theme-toggle.module.scss | 4 +- components/leaderboard/leaderboard-table.tsx | 11 ++- components/leaderboard/ranking-table.tsx | 11 ++- components/ui/container/index.tsx | 7 +- lib/nostr/signers.ts | 6 +- lib/rate-limit.ts | 11 ++- lib/schemas/match.ts | 6 +- tests/unit/app/api/matches.test.ts | 5 +- tests/unit/lib/game/track.test.ts | 8 +- .../unit/lib/multiplayer/match-client.test.ts | 15 ++-- tests/unit/lib/multiplayer/store.test.ts | 14 +-- tests/unit/lib/nostr/nip46-login.test.ts | 6 +- tests/unit/lib/nostr/signers.test.ts | 10 ++- tests/unit/lib/schemas/match.test.ts | 13 ++- 23 files changed, 223 insertions(+), 145 deletions(-) create mode 100644 .prettierignore 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/app/[locale]/opengraph-image.tsx b/app/[locale]/opengraph-image.tsx index 9b40adb..7b6abcd 100644 --- a/app/[locale]/opengraph-image.tsx +++ b/app/[locale]/opengraph-image.tsx @@ -32,57 +32,55 @@ export default async function OpengraphImage({ const sub = tagline(m.metadata.siteTitle, m.metadata.description); return new ImageResponse( - ( -
- {/* Brand blocks */} -
- {BLOCKS.map((color) => ( -
- ))} -
- - {/* Wordmark + tagline */} -
-
- - BitByBit - - - RUN - -
- + {/* Brand blocks */} +
+ {BLOCKS.map((color) => ( +
- {sub} + /> + ))} +
+ + {/* Wordmark + tagline */} +
+
+ + BitByBit + + + RUN
+ + {sub} +
- ), +
, { ...size } ); } diff --git a/app/api/matches/route.ts b/app/api/matches/route.ts index cc930ad..4b2b72b 100644 --- a/app/api/matches/route.ts +++ b/app/api/matches/route.ts @@ -40,7 +40,9 @@ export async function POST(req: NextRequest): Promise { const match = parsed.data; // The submitter must be one of the match's players (host or any participant). - const isParticipant = match.standings.some((s) => s.pubkey === session.pubkey); + const isParticipant = match.standings.some( + (s) => s.pubkey === session.pubkey + ); if (!isParticipant) { return NextResponse.json({ error: "forbidden" }, { status: 403 }); } diff --git a/app/apple-icon.tsx b/app/apple-icon.tsx index 0ac41ae..a4a0c83 100644 --- a/app/apple-icon.tsx +++ b/app/apple-icon.tsx @@ -12,33 +12,31 @@ const BLOCKS = ["#ff4d85", "#16a06b", "#f5b500"]; // primary / secondary / highl export default function AppleIcon() { return new ImageResponse( - ( -
- {BLOCKS.map((color) => ( -
- ))} -
- ), +
+ {BLOCKS.map((color) => ( +
+ ))} +
, { ...size } ); } diff --git a/app/icon.tsx b/app/icon.tsx index dfc8a1c..02be0ae 100644 --- a/app/icon.tsx +++ b/app/icon.tsx @@ -13,33 +13,31 @@ const BLOCKS = ["#ff4d85", "#16a06b", "#f5b500"]; // primary / secondary / highl export default function Icon() { return new ImageResponse( - ( -
- {BLOCKS.map((color) => ( -
- ))} -
- ), +
+ {BLOCKS.map((color) => ( +
+ ))} +
, { ...size } ); } diff --git a/components/game/interstitial-ad.tsx b/components/game/interstitial-ad.tsx index 40abc10..c3d365e 100644 --- a/components/game/interstitial-ad.tsx +++ b/components/game/interstitial-ad.tsx @@ -87,12 +87,7 @@ export function InterstitialAd({ onDone }: { onDone: () => void }) { {t(`ads.${ad.id}.title`)} -
diff --git a/components/game/match-results.tsx b/components/game/match-results.tsx index 9f78203..4e24480 100644 --- a/components/game/match-results.tsx +++ b/components/game/match-results.tsx @@ -68,7 +68,9 @@ export function MatchResults({ {timedOut && ( -

{t("timedOut", { winner: winnerName })}

+

+ {t("timedOut", { winner: winnerName })} +

)} setPractice(false)} /> + setPractice(false)} + /> ); } @@ -348,10 +350,7 @@ function LobbyAndRace({ // crucially this stops a returning player from re-creating/restarting it. if (!amInRoster) { return ( - + ); } diff --git a/components/game/runner-lobby.tsx b/components/game/runner-lobby.tsx index 007745b..cf84110 100644 --- a/components/game/runner-lobby.tsx +++ b/components/game/runner-lobby.tsx @@ -199,7 +199,12 @@ function WiredLobby({ ); } -function LocalLobby({ currentUser, onClaim, onStart, onLeave }: RunnerLobbyProps) { +function LocalLobby({ + currentUser, + onClaim, + onStart, + onLeave, +}: RunnerLobbyProps) { const [claimedId, setClaimedId] = useState(null); const occupants = useMemo>>( diff --git a/components/layout/locale-theme-toggle/locale-theme-toggle.module.scss b/components/layout/locale-theme-toggle/locale-theme-toggle.module.scss index 536fb83..1816183 100644 --- a/components/layout/locale-theme-toggle/locale-theme-toggle.module.scss +++ b/components/layout/locale-theme-toggle/locale-theme-toggle.module.scss @@ -54,7 +54,9 @@ font-weight: $font-weight-bold; font-family: $font-display; line-height: 1; - transition: color 0.2s ease, background 0.2s ease; + transition: + color 0.2s ease, + background 0.2s ease; &:hover { color: $color-primary; diff --git a/components/leaderboard/leaderboard-table.tsx b/components/leaderboard/leaderboard-table.tsx index a40d1db..5dda0a5 100644 --- a/components/leaderboard/leaderboard-table.tsx +++ b/components/leaderboard/leaderboard-table.tsx @@ -34,11 +34,18 @@ export async function LeaderboardTable({ // Each numeric column is a sort toggle: clicking re-ranks the board by it and // resets to page 1. The active column shows a ▼ and is highlighted. - const sortColumn = (key: LeaderboardSort, label: string, collapsible = false) => ({ + const sortColumn = ( + key: LeaderboardSort, + label: string, + collapsible = false + ) => ({ label, collapsible, active: sort === key, - sortHref: { pathname: "/leaderboard" as const, query: { sort: key, page: 1 } }, + sortHref: { + pathname: "/leaderboard" as const, + query: { sort: key, page: 1 }, + }, sortLabel: t("sortBy", { column: label }), }); diff --git a/components/leaderboard/ranking-table.tsx b/components/leaderboard/ranking-table.tsx index aaeea74..a796572 100644 --- a/components/leaderboard/ranking-table.tsx +++ b/components/leaderboard/ranking-table.tsx @@ -70,13 +70,20 @@ export function RankingTable({ )} scope="col" aria-sort={ - col.sortHref ? (col.active ? "descending" : "none") : undefined + col.sortHref + ? col.active + ? "descending" + : "none" + : undefined } > {col.sortHref ? ( {col.label} diff --git a/components/ui/container/index.tsx b/components/ui/container/index.tsx index 8527e02..90c5986 100644 --- a/components/ui/container/index.tsx +++ b/components/ui/container/index.tsx @@ -11,7 +11,12 @@ interface ContainerProps { fill?: boolean; } -export function Container({ children, className, center, fill }: ContainerProps) { +export function Container({ + children, + className, + center, + fill, +}: ContainerProps) { return (
{ 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/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/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( From b5ed02ffc2aa37f0a6bce8656bb166d24ea0f748 Mon Sep 17 00:00:00 2001 From: analiaacosta2023 Date: Wed, 24 Jun 2026 18:57:18 -0300 Subject: [PATCH 2/5] fix(game): resolve food strictly by the nearest lane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Food now resolves against the runner's rounded lane only, so a mid-tween merge toward a booster can't clip the junk in the lane being left — keeping booster gauntlets dodgeable as designed. Also reads the per-match track length from the active track instead of the shared default, removing a latent mismatch if a future seed changes length. Co-Authored-By: Claude Opus 4.8 (1M context) --- lib/game/scenes/race-scene.ts | 42 ++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 15 deletions(-) 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` ); From 4d8ef1b114b5fedff791736f7db340e3a39f8996 Mon Sep 17 00:00:00 2001 From: analiaacosta2023 Date: Wed, 24 Jun 2026 18:57:28 -0300 Subject: [PATCH 3/5] feat(multiplayer): host-only race start + robust lobby host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The control (start) event now carries its signer (the host's real identity) and the reducer only advances the lifecycle when that signer matches the match host — so a rogue peer on the channel can't force-start the race for everyone. Best-effort while the host is still unknown (no authoritative server). Also derives the lobby card's host from the host's own presence rather than whichever seat arrived first. Co-Authored-By: Claude Opus 4.8 (1M context) --- lib/multiplayer/discovery.ts | 14 ++++++--- lib/multiplayer/events.ts | 10 +++++-- lib/multiplayer/match-state.ts | 9 +++++- .../unit/lib/multiplayer/match-state.test.ts | 30 ++++++++++++++++++- 4 files changed, 54 insertions(+), 9 deletions(-) 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/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); From c00b03901a4f5ab270b0652ab9fa30a533208536 Mon Sep 17 00:00:00 2001 From: analiaacosta2023 Date: Wed, 24 Jun 2026 18:57:36 -0300 Subject: [PATCH 4/5] feat(auth): durable NIP-98 anti-replay via Postgres Single-use login nonces move from in-process memory to an auth_nonces table (idempotent insert + ON CONFLICT DO NOTHING + expired-row sweep), so a captured Authorization header can't be replayed by landing on a different Vercel serverless instance. Adds the migration, a unit test (mocked DB) and an integration test against the real Neon test branch; test:integration now auto-loads .env.test so it runs locally. Co-Authored-By: Claude Opus 4.8 (1M context) --- app/api/auth/nostr/route.ts | 7 +- drizzle/0004_furry_hex.sql | 6 + drizzle/meta/0004_snapshot.json | 416 +++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + lib/db/schema.ts | 18 + lib/nostr/nonce-store.ts | 50 +-- package.json | 2 +- tests/integration/nonce-store.test.ts | 43 +++ tests/integration/setup.ts | 9 + tests/unit/lib/nostr/nonce-store.test.ts | 79 ++++- 10 files changed, 595 insertions(+), 42 deletions(-) create mode 100644 drizzle/0004_furry_hex.sql create mode 100644 drizzle/meta/0004_snapshot.json create mode 100644 tests/integration/nonce-store.test.ts diff --git a/app/api/auth/nostr/route.ts b/app/api/auth/nostr/route.ts index 88a5c7b..55f9680 100644 --- a/app/api/auth/nostr/route.ts +++ b/app/api/auth/nostr/route.ts @@ -27,7 +27,7 @@ import { claimNonce } from "@/lib/nostr/nonce-store"; * from: * - the `u` tag binding the event to this exact URL * - the `method` tag binding it to POST - * - the ±30s `created_at` window (validateNip98AuthEvent) + * - the ±10s `created_at` window (validateNip98AuthEvent) * * The signer method (extension / nsec / nip46) and the user's * locale travel in custom `["bbr_signer", ...]` and @@ -104,8 +104,9 @@ export async function POST(req: NextRequest): Promise { const event = validation.event; // Single-use: a valid event is honored once. Replaying the captured header - // within the ±10s window (to mint a second session) is rejected here. - if (!claimNonce(event.id)) { + // within the ±10s window (to mint a second session) is rejected here. Backed + // by Postgres so the guard holds across serverless instances/cold starts. + if (!(await claimNonce(event.id))) { return NextResponse.json({ error: "auth_replayed" }, { status: 400 }); } diff --git a/drizzle/0004_furry_hex.sql b/drizzle/0004_furry_hex.sql new file mode 100644 index 0000000..05e62ff --- /dev/null +++ b/drizzle/0004_furry_hex.sql @@ -0,0 +1,6 @@ +CREATE TABLE "auth_nonces" ( + "id" varchar(64) PRIMARY KEY NOT NULL, + "expires_at" timestamp NOT NULL +); +--> 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/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/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/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); }); }); From f54243a1995dcfe0cf6a3271f5779ba71fcc03b2 Mon Sep 17 00:00:00 2001 From: analiaacosta2023 Date: Wed, 24 Jun 2026 18:57:48 -0300 Subject: [PATCH 5/5] docs: sync documentation and UI copy with the implementation Corrects session TTL, auth methods (NIP-07/46/nsec), scoring table, junk-food copy (bounded bathroom setback), and the security/anti-replay/host-start behavior; adds PWA, the live demo link, food variety, the account menu and the lud16/sync-profile routes; refreshes the project structure and removes stale 'in progress / future work' notes. Co-Authored-By: Claude Opus 4.8 (1M context) --- CHANGELOG.md | 39 ++++++++++++++++++++ CONTRIBUTING.md | 24 +++++++------ README.md | 20 ++++++++--- docs/ARCHITECTURE.md | 86 +++++++++++++++++++++++++++++--------------- docs/AUTH.md | 35 +++++++++++++++--- docs/GAME-DESIGN.md | 51 ++++++++++++++------------ docs/MULTIPLAYER.md | 13 ++++--- docs/PWA.md | 7 ---- docs/README.md | 22 ++++++------ docs/TESTING.md | 71 ++++++++++++++++++++---------------- docs/TOUR.md | 18 +++++----- messages/en.json | 2 +- messages/es.json | 2 +- 13 files changed, 255 insertions(+), 135 deletions(-) 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. +