Split The code is public; the app answers only to the crew.

Security: the leaderboard is forgeable — `/api/match` takes any name with no forge identity #42

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

vesper/cs:vesper/34-security-the-leaderboard-is-forgeable-ap → main 5 commits fork 1 thread · 1 unresolved

  • Merged. vesper/34-security-the-leaderboard-is-forgeable-ap was merged into main as ef2fbc6.

Review

Sign in to review this change.
18 files changed +812 −73
README.md +39 −9
@@ -78,7 +78,9 @@ wants one, but the running server never reads it.
7878 footstep only carries so far, but the bomb's beep and the blast that ends it
7979 carry across the whole map. The leaderboard is a real SQLite table under
8080 `FORGE_APP_DATA`, also served as plain JSON from `GET /api/leaderboard` for
81 the terminal or any other client.
81 the terminal or any other client — with a `guest` flag per row instead of the
82 identity it comes from, because a guest's identity is the session cookie that
83 owns their matches and that does not travel.
8284 - **Generated, not licensed.** The map (`de_forge`), the textures, the player and
8385 weapon models and every sound are produced in code at start-up. There are no
8486 asset files and nothing from the real game is used — the numbers follow CS's
@@ -92,8 +94,17 @@ wants one, but the running server never reads it.
9294 - **Simulated.** The opponents are bots, and the match runs entirely in your
9395 browser: there is no multiplayer and no server-side authority. Scores are
9496 client-reported, so the server checks them against what a match can produce
95 (kills fit in the rounds, headshots fit in the kills) and rejects the rest.
96 Treat the leaderboard as a scoreboard among friends, not as a ranking.
97 (kills fit in the rounds, headshots fit in the kills, the clock fits the
98 rounds) and rejects the rest. Treat the leaderboard as a scoreboard among
99 friends, not as a ranking.
100 - **Signed, not claimed.** The numbers on a result are the browser's to report;
101 the name on them is not. A match is credited to the forge identity that posted
102 it — the `x-forge-identity` and `x-forge-signature` headers the forge puts on
103 a proxied request, verified with `FORGE_APP_IDENTITY_KEY` in `src/who.ts` —
104 and a browser nobody signed for is recorded as a guest (`guest 4f2a`, one per
105 session cookie), never under a name it asked for. The name in the menu is
106 what the match calls you and goes nowhere near the board. Standings group by
107 identity, so a forge rename follows the player instead of splitting the row.
97108
98109 ## Playing
99110
@@ -187,7 +198,10 @@ with the canvas as you turn; nobody re-walks the grid to draw it.
187198 `src/client/weights.ts`.
188199 - `src/server.ts` — the HTTP server and the security floor. `src/db.ts` is the
189200 schema and its queries, `src/result.ts` validates what a browser may claim,
190 `src/pages/game.ts` renders the page.
201 `src/who.ts` verifies the forge's signed identity headers, `src/player.ts`
202 turns "who is asking" into who a match is credited to, `src/limit.ts` is the
203 rate limit `POST /api/match` stands behind, and `src/pages/game.ts` renders
204 the page.
191205 - `src/bundle.ts` bundles the client; `src/server.ts` runs it at start-up and
192206 serves the result from memory as `/static/app.<hash>.js`, cached for a year.
193207 `scripts/build.ts` is a thin CLI over the same function, for a file on disk.
@@ -197,13 +211,29 @@ with the canvas as you turn; nobody re-walks the grid to draw it.
197211
198212 It also has a terminal: the exact command is in `FORGE_APP_SSH` when the app
199213 runs (the app is the login name, the forge is the host). It opens `src/tty.ts`
200 on a real pty over the same database: the same standings, the same matches, and
201 `x` removes one. <kbd>Tab</kbd> walks the three tabs — the third is the policy
202 card the page shows, which the tab key could not reach until now.
214 on a real pty over the same database: the same standings, the same matches, a
215 `who` column that says `signed` or `guest` (a terminal has no markup, so the
216 tag a name cannot fake is a column of its own), and `x` removes one.
217 <kbd>Tab</kbd> walks the three tabs — the third is the policy card the page
218 shows, which the tab key could not reach until now.
203219
204220 The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV` (`production` or
205 `preview`), `FORGE_APP_URL`, `FORGE_APP_SSH` and `FORGE_APP_COMMIT` when it
206 starts the app. `forge.json` says how.
221 `preview`), `FORGE_APP_URL`, `FORGE_APP_SSH`, `FORGE_APP_COMMIT` and
222 `FORGE_APP_IDENTITY_KEY` when it starts the app. `forge.json` says how.
223 Without that key nothing can be verified, so everybody is a guest and the
224 board is a board of guests — there is no password and no way around it. The
225 server says so in one line at start-up and the terminal says so at the bottom
226 of the screen, because a leaderboard of nothing but guests is a missing secret
227 and not a bug in the app.
228
229 `POST /api/match` is the one endpoint that writes. It is same-origin only,
230 capped at the bytes actually read, and rate limited: 30 results a minute for a
231 signed player, and for a guest 30 a minute for their session inside 240 a
232 minute for their socket address — the one thing a guest cannot mint, and behind
233 the forge's proxy a ceiling all guests share. A match id belongs to the
234 identity that first sent it: anyone else posting it gets a 409. A database
235 written before identity existed is migrated on open — those rows were never
236 signed for, so they become the guests they always were.
207237
208238 ## The bots
209239
src/client/main.ts +3 −2
@@ -203,13 +203,14 @@ function boot(): void {
203203 // lost pointer lock already gets: a match is never left running unseen.
204204 attachFullscreen(wrapper, [fullscreenMenuButton, fullscreenPauseButton], () => controls.onPause());
205205
206 // --- results, sent as the match goes rather than only at the end
206 // --- results, sent as the match goes rather than only at the end.
207 // No name goes up: the server credits the result to whoever the forge says
208 // posted it, and the name in the menu is only what the match calls you.
207209 async function postResult(final: boolean): Promise<void> {
208210 if (world === null) return;
209211 const me = world.me;
210212 const body = {
211213 matchId,
212 name: nameField.value,
213214 rounds: world.match.score.t + world.match.score.ct,
214215 scoreMine: world.match.score[me.team],
215216 scoreTheirs: world.match.score[me.team === "t" ? "ct" : "t"],
src/db.test.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * The store: who a row belongs to, who owns a match id, and what happens to a
3 * database written before identity existed.
4 */
5
6 import { expect, test } from "bun:test";
7 import { Database } from "bun:sqlite";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { openDatabase, recentMatches, saveMatch, standings } from "./db.ts";
12 import type { Result } from "./result.ts";
13
14 const dir = (): string => mkdtempSync(join(tmpdir(), "db-"));
15
16 const result = (over: Partial<Result> = {}): Result => ({
17 matchId: crypto.randomUUID(),
18 rounds: 5, scoreMine: 3, scoreTheirs: 2,
19 kills: 9, deaths: 4, headshots: 3, damage: 1200, seconds: 420, finished: true,
20 ...over,
21 });
22
23 const writer = (identity: string, name: string, session = "0".repeat(32)) => ({ identity, name, session, guest: identity.startsWith("guest:") });
24
25 test("the standings group by identity, not by the name on a row", () => {
26 const db = openDatabase(dir());
27 // One person, renamed on the forge between two matches: one row, latest name.
28 const first = result();
29 expect(saveMatch(db, writer("user:u_1", "ada"), first)).toBe(true);
30 // `updated_at` counts whole seconds, and both of these land in the same one:
31 // age the first match so "most recent" means something here.
32 db.query("UPDATE match SET updated_at = datetime('now', '-1 hour') WHERE id = ?1").run(first.matchId);
33 expect(saveMatch(db, writer("user:u_1", "ada the second"), result())).toBe(true);
34 // Someone else who took the same name is still someone else.
35 expect(saveMatch(db, writer("guest:abcd", "ada"), result())).toBe(true);
36 const table = standings(db);
37 expect(table).toHaveLength(2);
38 expect(table.find((s) => s.identity === "user:u_1")?.matches).toBe(2);
39 expect(table.find((s) => s.identity === "user:u_1")?.name).toBe("ada the second");
40 expect(table.find((s) => s.identity === "guest:abcd")?.matches).toBe(1);
41 });
42
43 test("a match belongs to the identity that started it", () => {
44 const db = openDatabase(dir());
45 const match = result();
46 expect(saveMatch(db, writer("user:u_1", "ada"), match)).toBe(true);
47 // The same session, another identity — and another session, same identity.
48 expect(saveMatch(db, writer("guest:same-session", "guest ffff"), match)).toBe(false);
49 expect(saveMatch(db, writer("user:u_1", "ada", "f".repeat(32)), { ...match, kills: 11 })).toBe(true);
50 expect(recentMatches(db)[0]?.kills).toBe(11);
51 });
52
53 test("rows written before identity existed become the guests they always were", () => {
54 const where = dir();
55 // The old schema, and a row under a name nobody signed for.
56 const old = new Database(join(where, "app.db"));
57 old.exec(`CREATE TABLE match (
58 id TEXT PRIMARY KEY, session TEXT NOT NULL, name TEXT NOT NULL,
59 kills INTEGER NOT NULL, deaths INTEGER NOT NULL, headshots INTEGER NOT NULL,
60 damage INTEGER NOT NULL, rounds INTEGER NOT NULL, score_mine INTEGER NOT NULL,
61 score_theirs INTEGER NOT NULL, finished INTEGER NOT NULL, seconds INTEGER NOT NULL,
62 created_at TEXT NOT NULL DEFAULT (datetime('now')),
63 updated_at TEXT NOT NULL DEFAULT (datetime('now')))`);
64 old.query(
65 `INSERT INTO match (id, session, name, kills, deaths, headshots, damage, rounds, score_mine, score_theirs, finished, seconds)
66 VALUES ('m1', 'deadbeefdeadbeefdeadbeefdeadbeef', 'Vesper', 9, 4, 3, 1200, 5, 3, 2, 1, 420)`,
67 ).run();
68 old.close();
69
70 const db = openDatabase(where);
71 const [row] = standings(db);
72 expect(row?.identity).toBe("guest:deadbeefdeadbeefdeadbeefdeadbeef");
73 expect(row?.name).toBe("guest dead");
74 expect(row?.matches).toBe(1);
75 // ...and the browser that played it still owns its own match id.
76 expect(saveMatch(db, writer("guest:deadbeefdeadbeefdeadbeefdeadbeef", "guest dead"), result({ matchId: "m1", kills: 10 }))).toBe(true);
77 expect(saveMatch(db, writer("user:u_9", "thief"), result({ matchId: "m1", kills: 20 }))).toBe(false);
78 });
src/db.ts +41 −12
@@ -2,15 +2,24 @@
22 * The match records, in SQLite under FORGE_APP_DATA. One row per match, keyed
33 * by the id the browser generated for it, so a match that is still being
44 * played updates its own row instead of filling the table with fragments.
5 *
6 * A row belongs to an identity — `user:<forge id>` for someone the forge
7 * signed for, `guest:<session>` for a browser nobody vouched for — and that,
8 * not the name in the body of a request, is what the standings group by.
59 */
610
711 import { Database } from "bun:sqlite";
812 import { mkdirSync } from "node:fs";
913 import { join } from "node:path";
14 import type { Player } from "./player.ts";
1015 import type { Result } from "./result.ts";
1116
17 /** Who wrote a row: the credited player, plus the session that sent it. */
18 export type Writer = Player & { session: string };
19
1220 export type MatchRow = {
1321 id: string;
22 identity: string;
1423 session: string;
1524 name: string;
1625 kills: number;
@@ -26,7 +35,9 @@ export type MatchRow = {
2635 };
2736
2837 export type Standing = {
38 identity: string;
2939 name: string;
40 last: string;
3041 matches: number;
3142 kills: number;
3243 deaths: number;
@@ -42,6 +53,7 @@ export function openDatabase(dir = process.env.FORGE_APP_DATA ?? "./data"): Data
4253 db.exec("PRAGMA journal_mode = WAL");
4354 db.exec(`CREATE TABLE IF NOT EXISTS match (
4455 id TEXT PRIMARY KEY,
56 identity TEXT NOT NULL DEFAULT '',
4557 session TEXT NOT NULL,
4658 name TEXT NOT NULL,
4759 kills INTEGER NOT NULL,
@@ -57,19 +69,29 @@ export function openDatabase(dir = process.env.FORGE_APP_DATA ?? "./data"): Data
5769 updated_at TEXT NOT NULL DEFAULT (datetime('now'))
5870 )`);
5971 db.exec("CREATE INDEX IF NOT EXISTS match_by_time ON match (updated_at DESC)");
72 // A database written before identity existed holds names nobody signed for.
73 // They become what they always were: one guest per browser session.
74 const columns = db.query<{ name: string }, []>("PRAGMA table_info(match)").all().map((c) => c.name);
75 if (!columns.includes("identity")) {
76 db.exec("ALTER TABLE match ADD COLUMN identity TEXT NOT NULL DEFAULT ''");
77 db.exec("UPDATE match SET identity = 'guest:' || session, name = 'guest ' || substr(session, 1, 4)");
78 }
79 db.exec("CREATE INDEX IF NOT EXISTS match_by_identity ON match (identity)");
6080 return db;
6181 }
6282
6383 /**
64 * Write a result. A match belongs to the session that started it: another
65 * session sending the same id is ignored rather than allowed to overwrite it.
84 * Write a result, credited to the writer's identity and under the writer's
85 * name — never a name the request asked for. A match belongs to the identity
86 * that started it: anyone else sending the same id is ignored rather than
87 * allowed to overwrite it.
6688 */
67 export function saveMatch(db: Database, session: string, result: Result): boolean {
68 const existing = db.query<{ session: string }, [string]>("SELECT session FROM match WHERE id = ?1").get(result.matchId);
69 if (existing !== null && existing.session !== session) return false;
89 export function saveMatch(db: Database, writer: Writer, result: Result): boolean {
90 const existing = db.query<{ identity: string }, [string]>("SELECT identity FROM match WHERE id = ?1").get(result.matchId);
91 if (existing !== null && existing.identity !== writer.identity) return false;
7092 db.query(
71 `INSERT INTO match (id, session, name, kills, deaths, headshots, damage, rounds, score_mine, score_theirs, finished, seconds)
72 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
93 `INSERT INTO match (id, identity, session, name, kills, deaths, headshots, damage, rounds, score_mine, score_theirs, finished, seconds)
94 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
7395 ON CONFLICT(id) DO UPDATE SET
7496 name = excluded.name, kills = excluded.kills, deaths = excluded.deaths,
7597 headshots = excluded.headshots, damage = excluded.damage, rounds = excluded.rounds,
@@ -77,7 +99,7 @@ export function saveMatch(db: Database, session: string, result: Result): boolea
7799 finished = excluded.finished, seconds = excluded.seconds,
78100 updated_at = datetime('now')`,
79101 ).run(
80 result.matchId, session, result.name, result.kills, result.deaths, result.headshots,
102 result.matchId, writer.identity, writer.session, writer.name, result.kills, result.deaths, result.headshots,
81103 result.damage, result.rounds, result.scoreMine, result.scoreTheirs, result.finished ? 1 : 0, result.seconds,
82104 );
83105 return true;
@@ -85,15 +107,22 @@ export function saveMatch(db: Database, session: string, result: Result): boolea
85107
86108 export const recentMatches = (db: Database, limit = 10): MatchRow[] =>
87109 db.query<MatchRow, [number]>(
88 `SELECT id, session, name, kills, deaths, headshots, damage, rounds,
110 `SELECT id, identity, session, name, kills, deaths, headshots, damage, rounds,
89111 score_mine, score_theirs, finished, seconds, updated_at
90112 FROM match WHERE rounds > 0 ORDER BY updated_at DESC LIMIT ?1`,
91113 ).all(limit);
92114
93 /** The table people actually look at: one row a name, best first. */
115 /**
116 * The table people actually look at: one row an identity, best first. The name
117 * shown is the one on that identity's most recent match — SQLite takes a bare
118 * column from the row `MAX(updated_at)` picked — so a forge rename follows the
119 * player instead of splitting their record in two.
120 */
94121 export const standings = (db: Database, limit = 10): Standing[] =>
95122 db.query<Standing, [number]>(
96 `SELECT name,
123 `SELECT identity,
124 name,
125 MAX(updated_at) AS last,
97126 COUNT(*) AS matches,
98127 SUM(kills) AS kills,
99128 SUM(deaths) AS deaths,
@@ -102,7 +131,7 @@ export const standings = (db: Database, limit = 10): Standing[] =>
102131 SUM(CASE WHEN finished = 1 AND score_mine > score_theirs THEN 1 ELSE 0 END) AS wins,
103132 SUM(rounds) AS rounds
104133 FROM match WHERE rounds > 0
105 GROUP BY name
134 GROUP BY identity
106135 ORDER BY kills DESC, damage DESC
107136 LIMIT ?1`,
108137 ).all(limit);
src/limit.test.ts added +37
@@ -0,0 +1,37 @@
1 /** The rate limit: a ceiling per key, a window that opens again, bounded memory. */
2
3 import { expect, test } from "bun:test";
4 import { createLimiter } from "./limit.ts";
5
6 test("a key gets its allowance and no more", () => {
7 const limiter = createLimiter(3, 1000);
8 const now = 10_000;
9 expect([0, 1, 2].map(() => limiter.take("a", now).ok)).toEqual([true, true, true]);
10 const refused = limiter.take("a", now);
11 expect(refused.ok).toBe(false);
12 expect(refused.retryAfter).toBe(1);
13 });
14
15 test("one key's flood is not another's", () => {
16 const limiter = createLimiter(1, 1000);
17 expect(limiter.take("a", 0).ok).toBe(true);
18 expect(limiter.take("a", 0).ok).toBe(false);
19 expect(limiter.take("b", 0).ok).toBe(true);
20 });
21
22 test("the window opens again once it has passed", () => {
23 const limiter = createLimiter(2, 1000);
24 expect(limiter.take("a", 0).ok).toBe(true);
25 expect(limiter.take("a", 500).ok).toBe(true);
26 expect(limiter.take("a", 900).ok).toBe(false);
27 // Retry-After counts the milliseconds left, rounded up to a whole second.
28 expect(limiter.take("a", 900).retryAfter).toBe(1);
29 expect(limiter.take("a", 1000).ok).toBe(true);
30 });
31
32 test("keys nobody uses are forgotten, so a flood of them is not memory we owe", () => {
33 const limiter = createLimiter(1, 1000, 8);
34 for (let i = 0; i < 1000; i += 1) expect(limiter.take(`key-${i}`, i).ok).toBe(true);
35 // The oldest are gone — and the ceiling still holds for a key in the window.
36 expect(limiter.take("key-999", 999).ok).toBe(false);
37 });
src/limit.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * A rate limit, in memory. One counter per key over a fixed window: a match
3 * posts once a round and once more at the end, so a person playing is nowhere
4 * near the ceiling and a script writing rows as fast as it can is.
5 *
6 * The map is bounded — a key nobody has used since its window closed is
7 * dropped, and past the cap the oldest keys go first — so an attacker cannot
8 * turn "remember every address" into memory we do not have.
9 */
10
11 export type Decision = { ok: boolean; retryAfter: number }; // seconds until the window opens
12
13 export type Limiter = { take(key: string, now?: number): Decision };
14
15 type Window = { start: number; count: number };
16
17 export function createLimiter(limit: number, windowMs: number, maxKeys = 4096): Limiter {
18 const windows = new Map<string, Window>();
19
20 const prune = (now: number): void => {
21 for (const [key, window] of windows) {
22 if (now - window.start >= windowMs) windows.delete(key);
23 }
24 // Still over the cap: Map keeps insertion order, so the oldest go first.
25 for (const key of windows.keys()) {
26 if (windows.size <= maxKeys) break;
27 windows.delete(key);
28 }
29 };
30
31 return {
32 take(key, now = Date.now()) {
33 const window = windows.get(key);
34 if (window === undefined || now - window.start >= windowMs) {
35 if (windows.size >= maxKeys) prune(now);
36 windows.set(key, { start: now, count: 1 });
37 return { ok: true, retryAfter: 0 };
38 }
39 if (window.count < limit) {
40 window.count += 1;
41 return { ok: true, retryAfter: 0 };
42 }
43 return { ok: false, retryAfter: Math.max(1, Math.ceil((window.start + windowMs - now) / 1000)) };
44 },
45 };
46 }
src/pages/game.test.ts +5 −1
@@ -3,10 +3,14 @@ import { mkdtempSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { openDatabase } from "../db.ts";
6 import { credit } from "../player.ts";
67 import { gamePage } from "./game.ts";
78
89 const db = openDatabase(mkdtempSync(join(tmpdir(), "game-page-")));
9 const options = { env: "development", pull: undefined, commit: "", script: "/static/app.js", ssh: undefined };
10 // The page is always rendered for somebody: here, a guest, the way a visitor
11 // the forge has not signed for arrives.
12 const player = credit({ role: "anon" }, "0".repeat(32));
13 const options = { env: "development", pull: undefined, commit: "", script: "/static/app.js", ssh: undefined, player };
1014
1115 /** A `<div id="X" ...>`'s own body, whatever else is on its tag, to its matching `</div>`. */
1216 function element(html: string, id: string): string {
src/pages/game.ts +42 −13
@@ -6,29 +6,42 @@
66
77 import type { Database } from "bun:sqlite";
88 import { headshotShare, ratio, recentMatches, standings, type MatchRow, type Standing } from "../db.ts";
9 import { isGuest, type Player } from "../player.ts";
10 import { FORGE_LINK_ATTRS, signInHref } from "../who.ts";
911 import { CARD } from "../client/weights.ts";
1012
1113 export const escape = (s: string): string =>
1214 s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] ?? c);
1315
14 /** The leaderboard block. Also what POST /api/match answers with. */
15 export function statsHtml(db: Database): string {
16 /**
17 * The leaderboard block. Also what POST /api/match answers with, so the line
18 * that says who you are playing as is rendered here and travels with it.
19 *
20 * The "guest" tag comes from the identity, not from the name: a name is only
21 * text, and a row nobody signed for has to look like one.
22 */
23 export function statsHtml(db: Database, player: Player): string {
1624 const table = standings(db, 10);
1725 const recent = recentMatches(db, 8);
26 const tag = (identity: string): string => (isGuest(identity) ? ` <span class="tag">guest</span>` : "");
1827 const rows = table
1928 .map(
20 (s, i) => `<tr><td>${i + 1}</td><td>${escape(s.name)}</td><td>${s.matches}</td><td>${s.kills}</td>` +
29 (s, i) => `<tr><td>${i + 1}</td><td>${escape(s.name)}${tag(s.identity)}</td><td>${s.matches}</td><td>${s.kills}</td>` +
2130 `<td>${ratio(s.kills, s.deaths)}</td><td>${headshotShare(s.headshots, s.kills)}</td><td>${s.wins}</td></tr>`,
2231 )
2332 .join("");
2433 const feed = recent
2534 .map(
26 (m) => `<li><b>${escape(m.name)}</b> ${m.score_mine}–${m.score_theirs} ` +
35 (m) => `<li><b>${escape(m.name)}${tag(m.identity)}</b> ${m.score_mine}–${m.score_theirs} ` +
2736 `<span>${m.kills}k ${m.deaths}d · ${m.damage} damage${m.finished === 1 ? "" : " · in progress"}</span> ` +
2837 `<time>${escape(m.updated_at)}</time></li>`,
2938 )
3039 .join("");
3140 return `<h2>Leaderboard</h2>
41 <p class="you">${player.guest
42 ? `You are playing as <b>${escape(player.name)}</b>. ` +
43 `<a href="${escape(signInHref())}" ${FORGE_LINK_ATTRS}>Sign in on the forge</a> to put your matches on the board under your name.`
44 : `Signed in as <b>${escape(player.name)}</b> — your matches land under that name.`}</p>
3245 ${table.length === 0
3346 ? `<p class="empty">No matches yet. Play one and it lands here.</p>`
3447 : `<table><thead><tr><th>#</th><th>player</th><th>matches</th><th>kills</th><th>K/D</th><th>HS</th><th>wins</th></tr></thead><tbody>${rows}</tbody></table>`}
@@ -37,15 +50,24 @@ ${table.length === 0
3750 }
3851
3952 export type LeaderboardJson = {
40 standings: Standing[];
41 recent: Omit<MatchRow, "session">[];
53 standings: (Omit<Standing, "identity"> & { guest: boolean })[];
54 recent: (Omit<MatchRow, "session" | "identity"> & { guest: boolean })[];
4255 };
4356
44 /** The same leaderboard as statsHtml, as data: what GET /api/leaderboard answers. */
57 /**
58 * The same leaderboard as statsHtml, as data: what GET /api/leaderboard
59 * answers. The session never travels, and neither does the identity that
60 * holds it — a guest's is `guest:<session>`, which is the cookie that owns
61 * their matches. What a reader needs from it is the one bit the page shows as
62 * a tag, so that is what goes out.
63 */
4564 export function leaderboardJson(db: Database): LeaderboardJson {
4665 return {
47 standings: standings(db, 10),
48 recent: recentMatches(db, 8).map(({ session: _session, ...match }) => match),
66 standings: standings(db, 10).map(({ identity, ...standing }) => ({ ...standing, guest: isGuest(identity) })),
67 recent: recentMatches(db, 8).map(({ session: _session, identity, ...match }) => ({
68 ...match,
69 guest: isGuest(identity),
70 })),
4971 };
5072 }
5173
@@ -85,6 +107,7 @@ small.commit { color:var(--dim); font-size:.75rem; }
85107 .overlay p { margin:.2rem 0; color:var(--dim); max-width:34rem; }
86108 .row { display:flex; gap:.5rem; flex-wrap:wrap; justify-content:center; align-items:center; }
87109 label { display:flex; flex-direction:column; gap:.25rem; font-size:.8rem; color:var(--dim); text-align:left; }
110 label small { font-size:.7rem; }
88111 input, select { min-height:44px; padding:.5rem .7rem; font:inherit; color:var(--text);
89112 background:#0f131a; border:1px solid var(--line); border-radius:.45rem; }
90113 button { min-height:44px; min-width:44px; padding:.6rem 1.1rem; font:inherit; border:1px solid var(--line);
@@ -124,7 +147,10 @@ th, td { text-align:left; padding:.35rem .5rem; border-bottom:1px solid var(--li
124147 th { color:var(--dim); font-weight:500; }
125148 ul.recent { list-style:none; padding:0; margin:0; font-size:.86rem; }
126149 ul.recent li { padding:.35rem 0; border-bottom:1px solid var(--line); display:flex; gap:.5rem; flex-wrap:wrap; }
127 ul.recent span, ul.recent time, .empty { color:var(--dim); }
150 ul.recent span, ul.recent time, .empty, .you { color:var(--dim); }
151 .you { font-size:.86rem; margin:.2rem 0 .6rem; }
152 .you b { color:var(--text); }
153 .tag { font-size:.7rem; color:var(--dim); border:1px solid var(--line); border-radius:999px; padding:0 .35rem; font-weight:400; }
128154 kbd { background:#1b2230; border:1px solid var(--line); border-radius:.25rem; padding:0 .3rem; font-size:.82rem; }
129155 footer { color:var(--dim); font-size:.8rem; padding:1rem; text-align:center; }
130156 code { background:#141821; padding:.1rem .35rem; border-radius:.25rem; }
@@ -133,6 +159,7 @@ code { background:#141821; padding:.1rem .35rem; border-radius:.25rem; }
133159
134160 export type PageOptions = {
135161 env: string;
162 player: Player;
136163 pull: string | undefined;
137164 commit: string;
138165 script: string;
@@ -163,7 +190,7 @@ export function gamePage(db: Database, options: PageOptions): string {
163190 <h2>Defuse or detonate</h2>
164191 <p>Five against five on <b>de_forge</b>. Bomb rounds, CS movement and economy, bots that push the sites.</p>
165192 <div class="row">
166 <label>Name<input id="name" maxlength="24" placeholder="you" autocomplete="nickname"></label>
193 <label>Name<input id="name" maxlength="24" placeholder="you" autocomplete="nickname"><small>in the match only</small></label>
167194 <label>Match<select id="length"><option value="short">Short — first to 5</option><option value="long">Competitive — first to 13</option></select></label>
168195 <label>Side<select id="side"><option value="ct">Counter-Terrorists</option><option value="t">Terrorists</option></select></label>
169196 <label>Sensitivity<input id="sens" type="number" min="0.2" max="12" step="0.1" value="2.2"></label>
@@ -227,7 +254,7 @@ export function gamePage(db: Database, options: PageOptions): string {
227254 </div>
228255 </div>
229256
230 <section id="stats">${statsHtml(db)}</section>
257 <section id="stats">${statsHtml(db, options.player)}</section>
231258
232259 <section>
233260 <h2>What this is</h2>
@@ -247,7 +274,9 @@ export function gamePage(db: Database, options: PageOptions): string {
247274 bot's own skill still decides how fast it can turn, how steady its hands are and how long it
248275 takes to react, so there is still a ladder from fodder to uncomfortable.</p>
249276 <p>The match runs entirely in your browser; the leaderboard here is what your browser
250 reported about it.</p>
277 reported about it. The numbers are yours to report, but the name on them is not: a result
278 is credited to the forge identity that posted it, and a browser the forge has not signed
279 for is recorded as a guest. The name in the menu is what you are called inside the match.</p>
251280 <p>${options.ssh === undefined
252281 ? "The app's terminal is off."
253282 : `The same leaderboard in a terminal: <code>${escape(options.ssh)}</code>`}</p>
src/player.test.ts added +32
@@ -0,0 +1,32 @@
1 /** Who a match is credited to: a forge name, or a guest — never a claim. */
2
3 import { expect, test } from "bun:test";
4 import { credit, isGuest, oneLine } from "./player.ts";
5
6 const session = "0123456789abcdef0123456789abcdef";
7
8 test("a signed identity is credited by name, under its own id", () => {
9 const player = credit({ role: "user", id: "u_7", name: "ada" }, session);
10 expect(player).toEqual({ identity: "user:u_7", name: "ada", guest: false });
11 expect(isGuest(player.identity)).toBe(false);
12 // The same person from another browser is the same row on the board.
13 expect(credit({ role: "user", id: "u_7", name: "ada" }, "f".repeat(32)).identity).toBe("user:u_7");
14 });
15
16 test("anyone the forge did not sign for is a guest, one per session", () => {
17 const player = credit({ role: "anon" }, session);
18 expect(player.guest).toBe(true);
19 expect(player.identity).toBe(`guest:${session}`);
20 expect(player.name).toBe("guest 0123");
21 expect(isGuest(player.identity)).toBe(true);
22 expect(credit({ role: "anon" }, "f".repeat(32)).identity).not.toBe(player.identity);
23 });
24
25 test("a name is one line of printable text, however it arrived", () => {
26 expect(oneLine(" spaced ", "player")).toBe("spaced");
27 expect(oneLine("two\nlines", "player")).toBe("two lines");
28 // An escape sequence would paint the app's terminal, so it does not survive.
29 expect(oneLine("\u001b[31mred", "player")).toBe("[31mred");
30 expect(oneLine("a".repeat(100), "player")).toHaveLength(24);
31 expect(oneLine(" ", "player")).toBe("player");
32 });
src/player.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Who a match is credited to. The game reports its own numbers, but it does
3 * not get to say whose they are: a signed forge identity is a named player,
4 * and a browser we cannot verify is a guest — one guest per session, under a
5 * name that is visibly a guest's and never a name someone else answers to.
6 */
7
8 import type { Who } from "./who.ts";
9
10 export type Player = { identity: string; name: string; guest: boolean };
11
12 const GUEST = "guest:";
13
14 /** One line of printable text, short, never empty: this ends up in HTML and in a terminal. */
15 export function oneLine(value: string, fallback: string): string {
16 const stripped = value.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 24);
17 return stripped.length === 0 ? fallback : stripped;
18 }
19
20 /**
21 * The player a request's result belongs to. The session only distinguishes one
22 * guest from another; it never earns a name.
23 */
24 export function credit(who: Who, session: string): Player {
25 if (who.role === "anon")
26 return { identity: `${GUEST}${session}`, name: `guest ${session.slice(0, 4)}`, guest: true };
27 return { identity: `user:${who.id}`, name: oneLine(who.name, "player"), guest: false };
28 }
29
30 export const isGuest = (identity: string): boolean => identity.startsWith(GUEST);
src/result.test.ts added +43
@@ -0,0 +1,43 @@
1 /** The boundary the leaderboard stands on: what a browser may claim about a match. */
2
3 import { expect, test } from "bun:test";
4 import { parseResult, won } from "./result.ts";
5
6 const result = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
7 matchId: crypto.randomUUID(),
8 rounds: 5, scoreMine: 3, scoreTheirs: 2,
9 kills: 9, deaths: 4, headshots: 3, damage: 1200, seconds: 420, finished: true,
10 ...over,
11 });
12
13 test("a match that could have been played parses", () => {
14 const parsed = parseResult(result());
15 expect(parsed?.rounds).toBe(5);
16 expect(parsed?.seconds).toBe(420);
17 expect(won(parsed!)).toBe(true);
18 });
19
20 test("the clock has to fit the rounds", () => {
21 // Five rounds cannot take three hours...
22 expect(parseResult(result({ seconds: 6000 }))).toBe(null);
23 // ...and they cannot be played in nine seconds either.
24 expect(parseResult(result({ seconds: 9 }))).toBe(null);
25 // The edges of what a real match can produce still go through: a long
26 // thirteen-round win, and five rounds of nothing but instant wipes.
27 expect(parseResult(result({ rounds: 13, scoreMine: 13, scoreTheirs: 0, deaths: 13, seconds: 2600 }))).not.toBe(null);
28 expect(parseResult(result({ seconds: 60 }))).not.toBe(null);
29 // A match still in its first round has no rounds and a clock all the same.
30 expect(parseResult(result({ rounds: 0, scoreMine: 0, scoreTheirs: 0, kills: 0, deaths: 0, headshots: 0, seconds: 90, finished: false }))).not.toBe(null);
31 });
32
33 test("a result carries no name: the body does not get to say whose match it was", () => {
34 expect(Object.keys(parseResult(result({ name: "somebody" })) ?? {})).not.toContain("name");
35 });
36
37 test("nonsense is refused rather than clamped", () => {
38 expect(parseResult(result({ matchId: "../../etc" }))).toBe(null);
39 expect(parseResult(result({ kills: -1 }))).toBe(null);
40 expect(parseResult(result({ rounds: 31, scoreMine: 31, scoreTheirs: 0 }))).toBe(null);
41 expect(parseResult(result({ damage: Number.POSITIVE_INFINITY }))).toBe(null);
42 expect(parseResult(undefined)).toBe(null);
43 });
src/result.ts +11 −9
@@ -7,7 +7,6 @@
77
88 export type Result = {
99 matchId: string;
10 name: string;
1110 rounds: number;
1211 scoreMine: number;
1312 scoreTheirs: number;
@@ -21,6 +20,13 @@ export type Result = {
2120
2221 const MAX_ROUNDS = 30;
2322 const KILLS_PER_ROUND = 5; // five enemies is all there are
23 // What a round costs on the clock. At most: 12s of freeze, a 115s round, a
24 // 40s bomb and 5s after it ends, with slack — and one round of that is allowed
25 // on top, because a result is posted as the match goes and the round being
26 // played is not in the score yet. At least: the freeze time and a fight, even
27 // when every round is a five-second wipe.
28 const MAX_SECONDS_PER_ROUND = 200;
29 const MIN_SECONDS_PER_ROUND = 10;
2430
2531 const integer = (value: unknown, max: number): number | null => {
2632 if (typeof value !== "number" || !Number.isFinite(value)) return null;
@@ -28,13 +34,6 @@ const integer = (value: unknown, max: number): number | null => {
2834 return n < 0 || n > max ? null : n;
2935 };
3036
31 /** A name is one line of printable text, short, and never empty. */
32 export function cleanName(value: unknown): string {
33 if (typeof value !== "string") return "anon";
34 const stripped = value.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 24);
35 return stripped.length === 0 ? "anon" : stripped;
36 }
37
3837 /** Parse a submitted result, or null if it is not one. */
3938 export function parseResult(value: unknown): Result | null {
4039 if (typeof value !== "object" || value === null) return null;
@@ -59,9 +58,12 @@ export function parseResult(value: unknown): Result | null {
5958 if (headshots > kills) return null;
6059 if (deaths > rounds) return null;
6160 if (kills > rounds * KILLS_PER_ROUND) return null;
61 // A clock nobody could have played through: thirty rounds do not fit in a
62 // minute, and one round does not take an hour.
63 if (seconds > (rounds + 1) * MAX_SECONDS_PER_ROUND) return null;
64 if (seconds < rounds * MIN_SECONDS_PER_ROUND) return null;
6265 return {
6366 matchId,
64 name: cleanName(body.name),
6567 rounds, scoreMine, scoreTheirs, kills, deaths, headshots, damage, seconds,
6668 finished: body.finished === true,
6769 };
src/server.test.ts +121 −16
@@ -4,13 +4,22 @@ import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { bundle } from "./bundle.ts";
66 import { parseResult } from "./result.ts";
7 import { stamp } from "./who.ts";
78
89 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
910 process.env.PORT = "0";
11 const KEY = "a-key-only-the-forge-and-this-app-know";
12 process.env.FORGE_APP_IDENTITY_KEY = KEY;
1013 const { serve } = await import("./server.ts");
1114 const server = await serve();
1215 const base = `http://${server.hostname}:${server.port}`;
1316
17 /** The headers the forge puts on a request it proxies for a signed-in person. */
18 const forge = (id: string, name: string, key = KEY): Record<string, string> => {
19 const identity = `${id}|${name}|user|${Date.now() + 60_000}`;
20 return { "x-forge-identity": identity, "x-forge-signature": stamp(key, identity) };
21 };
22
1423 const result = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
1524 matchId: crypto.randomUUID(),
1625 name: "tester",
@@ -19,10 +28,10 @@ const result = (over: Record<string, unknown> = {}): Record<string, unknown> =>
1928 ...over,
2029 });
2130
22 const post = (body: unknown, cookie = ""): Promise<Response> =>
31 const post = (body: unknown, cookie = "", headers: Record<string, string> = {}): Promise<Response> =>
2332 fetch(base + "/api/match", {
2433 method: "POST",
25 headers: { "content-type": "application/json", ...(cookie === "" ? {} : { cookie }) },
34 headers: { "content-type": "application/json", ...(cookie === "" ? {} : { cookie }), ...headers },
2635 body: JSON.stringify(body),
2736 });
2837
@@ -55,6 +64,15 @@ test("a first visit is given a session cookie that javascript cannot read", asyn
5564 expect(cookie).toContain("SameSite=Lax");
5665 });
5766
67 test("the page says who your matches will be credited to", async () => {
68 const guest = await (await fetch(base + "/")).text();
69 expect(guest).toContain("You are playing as <b>guest ");
70 expect(guest).toContain("/__forge/signin");
71 const signed = await (await fetch(base + "/", { headers: forge("u_page", "ada") })).text();
72 expect(signed).toContain("Signed in as <b>ada</b>");
73 expect(signed).not.toContain("/__forge/signin");
74 });
75
5876 test("stands on the security floor", async () => {
5977 const response = await fetch(base + "/");
6078 expect(response.headers.get("content-security-policy")).toContain("default-src 'self'");
@@ -63,7 +81,7 @@ test("stands on the security floor", async () => {
6381 });
6482
6583 test("a result is stored and comes back as the leaderboard", async () => {
66 const response = await post(result({ name: "Vesper" }));
84 const response = await post(result(), "", forge("u_1", "Vesper"));
6785 expect(response.status).toBe(200);
6886 const body = await response.text();
6987 expect(body).toContain("Vesper");
@@ -71,8 +89,35 @@ test("a result is stored and comes back as the leaderboard", async () => {
7189 expect(await (await fetch(base + "/")).text()).toContain("Vesper");
7290 });
7391
74 test("a name is escaped, not run", async () => {
75 await post(result({ name: "<img src=x onerror=alert(1)>" }));
92 test("a name in the body is not a name: an unsigned poster is a guest", async () => {
93 // Anyone with curl can send this. Nobody signed for it, so it lands as a
94 // guest — never under the name it asked for.
95 const response = await post(result({ name: "Champion" }), "cs_session=" + "b".repeat(32));
96 expect(response.status).toBe(200);
97 const body = await response.text();
98 expect(body).toContain("guest bbbb");
99 expect(body).not.toContain("Champion");
100 });
101
102 test("a signed result is attributed to the forge identity, whatever the body says", async () => {
103 await post(result({ name: "somebody else" }), "", forge("u_2", "ada"));
104 const page = await (await fetch(base + "/")).text();
105 expect(page).toContain("ada");
106 expect(page).not.toContain("somebody else");
107 // ...and the row is not tagged as a guest, while an unsigned one is.
108 const row = page.slice(page.indexOf(">ada<"), page.indexOf(">ada<") + 80);
109 expect(row).not.toContain("guest");
110 });
111
112 test("an identity signed with the wrong key is nobody", async () => {
113 await post(result(), "cs_session=" + "c".repeat(32), forge("u_3", "impostor", "not-the-forge"));
114 const page = await (await fetch(base + "/")).text();
115 expect(page).not.toContain("impostor");
116 expect(page).toContain("guest cccc");
117 });
118
119 test("a signed name is escaped, not run", async () => {
120 await post(result(), "", forge("u_4", "<img src=x onerror=alert(1)>"));
76121 const page = await (await fetch(base + "/")).text();
77122 expect(page).not.toContain("<img src=x");
78123 expect(page).toContain("&lt;img src=x");
@@ -88,14 +133,23 @@ test("numbers that no match could produce are refused", async () => {
88133
89134 test("another browser cannot overwrite a match it did not play", async () => {
90135 const id = crypto.randomUUID();
91 const first = await post(result({ matchId: id, name: "owner" }));
136 const first = await post(result({ matchId: id }));
92137 const cookie = (first.headers.get("set-cookie") ?? "").split(";")[0];
93138 expect(cookie).toContain("cs_session=");
94 const same = await post(result({ matchId: id, name: "owner", kills: 11 }), cookie);
139 const same = await post(result({ matchId: id, kills: 11 }), cookie);
95140 expect(same.status).toBe(200);
96 const other = await post(result({ matchId: id, name: "thief", kills: 20 }), "cs_session=" + "a".repeat(32));
141 const other = await post(result({ matchId: id, kills: 20 }), "cs_session=" + "a".repeat(32));
97142 expect(other.status).toBe(409);
98 expect(await (await fetch(base + "/")).text()).not.toContain("thief");
143 });
144
145 test("a signed player's match is theirs: a guest holding the cookie cannot rewrite it", async () => {
146 const id = crypto.randomUUID();
147 const mine = await post(result({ matchId: id }), "", forge("u_5", "bo"));
148 expect(mine.status).toBe(200);
149 const cookie = (mine.headers.get("set-cookie") ?? "").split(";")[0];
150 expect((await post(result({ matchId: id, kills: 20 }), cookie)).status).toBe(409);
151 expect((await post(result({ matchId: id, kills: 20 }), cookie, forge("u_6", "thief"))).status).toBe(409);
152 expect((await post(result({ matchId: id, kills: 11 }), cookie, forge("u_5", "bo"))).status).toBe(200);
99153 });
100154
101155 test("a body is capped by the bytes read, whatever it claims", async () => {
@@ -153,21 +207,72 @@ test("the script is served immutable, as javascript, under the security floor",
153207 });
154208
155209 test("the leaderboard is also plain JSON, for a terminal or another client", async () => {
156 await post(result({ name: "Jsonface" }));
210 // The name in the JSON is the forge's, like everywhere else. The match is a
211 // big one so the row sits at the top of a board these tests have filled.
212 const big = { rounds: 13, scoreMine: 13, scoreTheirs: 0, kills: 65, deaths: 13, headshots: 30, damage: 9000, seconds: 2000 };
213 await post(result(big), "", forge("u_json", "Jsonface"));
157214 const response = await fetch(base + "/api/leaderboard");
158215 expect(response.status).toBe(200);
159216 expect(response.headers.get("content-type")).toBe("application/json; charset=utf-8");
160217 expect(response.headers.get("content-security-policy")).toContain("default-src 'self'");
161 const body = (await response.json()) as { standings: unknown[]; recent: Record<string, unknown>[] };
162 expect(body.standings.some((s) => (s as { name: string }).name === "Jsonface")).toBe(true);
163 expect(body.recent.some((m) => m.name === "Jsonface")).toBe(true);
164 expect(body.recent.every((m) => !("session" in m))).toBe(true);
218 const body = (await response.json()) as {
219 standings: Record<string, unknown>[];
220 recent: Record<string, unknown>[];
221 };
222 expect(body.standings.some((s) => s.name === "Jsonface" && s.guest === false)).toBe(true);
223 expect(body.standings.every((s) => typeof s.guest === "boolean")).toBe(true);
224 expect(body.recent.length).toBeGreaterThan(0);
225 expect(body.recent.every((m) => !("session" in m) && typeof m.guest === "boolean")).toBe(true);
226 });
227
228 test("the leaderboard JSON hands out no session, in a cookie's clothing or otherwise", async () => {
229 // A guest's identity is `guest:<session>` — the cookie that owns their
230 // matches. It stays on this side of the wire; the tag it becomes travels.
231 const session = "7".repeat(32);
232 await post(result(), "cs_session=" + session);
233 const text = await (await fetch(base + "/api/leaderboard")).text();
234 expect(text).not.toContain(session);
235 expect(text).not.toContain("guest:");
236 const body = (await (await fetch(base + "/api/leaderboard")).json()) as {
237 standings: Record<string, unknown>[];
238 recent: Record<string, unknown>[];
239 };
240 for (const row of [...body.standings, ...body.recent]) {
241 expect(row).not.toHaveProperty("session");
242 expect(row).not.toHaveProperty("identity");
243 expect(typeof row.guest).toBe("boolean");
244 }
165245 });
166246
167247 test("a result parses to exactly what was sent, and nothing else", () => {
168 const parsed = parseResult({ ...result({ name: " spaced " }), extra: "ignored" });
169 expect(parsed?.name).toBe("spaced");
248 const parsed = parseResult({ ...result(), extra: "ignored", name: "nobody" });
249 expect(parsed?.kills).toBe(9);
170250 expect(Object.keys(parsed ?? {})).not.toContain("extra");
251 // The name never survives the boundary: attribution is not the body's job.
252 expect(Object.keys(parsed ?? {})).not.toContain("name");
171253 expect(parseResult(null)).toBe(null);
172254 expect(parseResult("no")).toBe(null);
173255 });
256
257 test("the endpoint is rate limited, and one player's flood is their own", async () => {
258 // A signed identity gets its own bucket, so this burst cannot lock anyone
259 // else out — and the tests above, which post as guests, are unaffected.
260 const them = forge("u_flood", "flooder");
261 let last = 200;
262 for (let i = 0; i < 40 && last !== 429; i += 1) last = (await post(result(), "", them)).status;
263 expect(last).toBe(429);
264 const refused = await post(result(), "", them);
265 expect(refused.status).toBe(429);
266 expect(Number(refused.headers.get("retry-after"))).toBeGreaterThan(0);
267 // Someone else is still served.
268 expect((await post(result(), "", forge("u_calm", "calm"))).status).toBe(200);
269 });
270
271 test("a guest is limited too, by the session they hold", async () => {
272 const cookie = "cs_session=" + "e".repeat(32);
273 let last = 200;
274 for (let i = 0; i < 40 && last !== 429; i += 1) last = (await post(result(), cookie)).status;
275 expect(last).toBe(429);
276 // A different guest, from the same address, is still under the wider ceiling.
277 expect((await post(result(), "cs_session=" + "d".repeat(32))).status).toBe(200);
278 });
src/server.ts +51 −7
@@ -9,8 +9,11 @@
99 import { join } from "node:path";
1010 import { bundle } from "./bundle.ts";
1111 import { openDatabase, saveMatch } from "./db.ts";
12 import { createLimiter, type Decision } from "./limit.ts";
1213 import { escape, gamePage, leaderboardJson, statsHtml } from "./pages/game.ts";
14 import { credit } from "./player.ts";
1315 import { parseResult } from "./result.ts";
16 import { identityWarning, whoIs, type Who } from "./who.ts";
1417
1518 const env = process.env.FORGE_APP_ENV ?? "local";
1619 const pull = process.env.FORGE_APP_PULL;
@@ -107,6 +110,28 @@ const newSession = (): string =>
107110 const sessionCookie = (session: string): string =>
108111 `${SESSION_COOKIE}=${session}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000${secure ? "; Secure" : ""}`;
109112
113 // How fast results may arrive. A match posts once a round and once more when
114 // it ends, so thirty a minute is several matches at once and a script writing
115 // rows as fast as curl can is over it in a second.
116 //
117 // A signed player is limited as themselves: one person's flood cannot lock
118 // another out. A guest has no identity to be limited as, so they are limited
119 // twice — by their session, which keeps one guest off another guest's back,
120 // and by the socket address, which is the only thing they cannot mint. Behind
121 // the forge's proxy that address is the proxy, so the second ceiling is one
122 // all guests share; it is set high enough to be a wall for a script and not
123 // for a game. A forwarded-for header is whatever the client wrote in it and
124 // is not consulted.
125 const MATCH_WINDOW_MS = 60_000;
126 const perPlayer = createLimiter(30, MATCH_WINDOW_MS);
127 const perAddress = createLimiter(240, MATCH_WINDOW_MS);
128
129 const matchGate = (who: Who, session: string, address: string | undefined): Decision => {
130 if (who.role !== "anon") return perPlayer.take(`user:${who.id}`);
131 const wide = perAddress.take(`ip:${address ?? "unknown"}`);
132 return wide.ok ? perPlayer.take(`session:${session}`) : wide;
133 };
134
110135 export async function serve(): Promise<ReturnType<typeof Bun.serve>> {
111136 const db = openDatabase();
112137
@@ -128,12 +153,23 @@ export async function serve(): Promise<ReturnType<typeof Bun.serve>> {
128153 const server = Bun.serve({
129154 port: Number(process.env.PORT ?? 8080),
130155 hostname: process.env.HOST ?? "127.0.0.1",
131 async fetch(request) {
156 async fetch(request, self) {
132157 const url = new URL(request.url);
133158 if (request.method === "POST" && !sameOrigin(request))
134159 return new Response("forbidden", { status: 403, headers: SECURITY });
135160
136161 if (request.method === "POST" && url.pathname === "/api/match") {
162 // Who the result belongs to is decided here and nowhere else: the
163 // forge signs for a name, and a browser that cannot show a signature
164 // is a guest. Nothing in the body names a player.
165 const who = whoIs(request.headers);
166 const session = readSession(request) ?? newSession();
167 const gate = matchGate(who, session, self?.requestIP(request)?.address);
168 if (!gate.ok)
169 return new Response("slow down", {
170 status: 429,
171 headers: { ...SECURITY, "retry-after": String(gate.retryAfter) },
172 });
137173 const body = await readBody(request);
138174 if (body === undefined) return new Response("too large", { status: 413, headers: SECURITY });
139175 let parsed: unknown;
@@ -144,10 +180,10 @@ export async function serve(): Promise<ReturnType<typeof Bun.serve>> {
144180 }
145181 const result = parseResult(parsed);
146182 if (result === null) return new Response("bad result", { status: 422, headers: SECURITY });
147 const session = readSession(request) ?? newSession();
148 const stored = saveMatch(db, session, result);
183 const player = credit(who, session);
184 const stored = saveMatch(db, { ...player, session }, result);
149185 if (!stored) return new Response("not yours", { status: 409, headers: SECURITY });
150 return html(statsHtml(db), 200, { "set-cookie": sessionCookie(session) });
186 return html(statsHtml(db, player), 200, { "set-cookie": sessionCookie(session) });
151187 }
152188
153189 // The same leaderboard as the page's first paint, as data: what a
@@ -161,9 +197,14 @@ export async function serve(): Promise<ReturnType<typeof Bun.serve>> {
161197
162198 // HEAD is GET without the body: a health check sees the app up.
163199 if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) {
164 const session = readSession(request);
165 const page = gamePage(db, { env, pull, commit, script, ssh });
166 const response = html(page, 200, session === null ? { "set-cookie": sessionCookie(newSession()) } : {});
200 // A first visit is given its session here, and the page is rendered
201 // with the same one it is about to be handed: the guest a visitor is
202 // told they are is the guest their next result lands under.
203 const existing = readSession(request);
204 const session = existing ?? newSession();
205 const player = credit(whoIs(request.headers), session);
206 const page = gamePage(db, { env, pull, commit, script, ssh, player });
207 const response = html(page, 200, existing === null ? { "set-cookie": sessionCookie(session) } : {});
167208 return request.method === "HEAD"
168209 ? new Response(null, { status: response.status, headers: response.headers })
169210 : response;
@@ -204,6 +245,9 @@ export async function serve(): Promise<ReturnType<typeof Bun.serve>> {
204245 console.log(
205246 `cs listening on http://${server.hostname}:${server.port} (${env}) serving ${script} (built in ${buildMs}ms)`,
206247 );
248 // A board that is silently all guests is a missing secret, not a quiet app.
249 const notice = identityWarning();
250 if (notice !== null) console.warn(notice);
207251 return server;
208252 }
209253
src/tty.test.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * The terminal, run for real: it boots against a database, draws the
3 * standings, and says who a row belongs to. A terminal has no markup, so the
4 * only thing that can tell a guest from a signed player is a column of its own
5 * — a forge name is text like any other and could read "guest aaaa".
6 */
7
8 import { expect, test } from "bun:test";
9 import { mkdtempSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { openDatabase, saveMatch } from "./db.ts";
13 import type { Result } from "./result.ts";
14
15 const result = (over: Partial<Result> = {}): Result => ({
16 matchId: crypto.randomUUID(),
17 rounds: 5, scoreMine: 3, scoreTheirs: 2,
18 kills: 9, deaths: 4, headshots: 3, damage: 1200, seconds: 420, finished: true,
19 ...over,
20 });
21
22 /** One frame of the terminal, with its escape sequences taken out. */
23 async function draw(dir: string, env: Record<string, string> = {}): Promise<string> {
24 const child = Bun.spawn(["bun", "run", join(import.meta.dir, "tty.ts")], {
25 env: { ...process.env, FORGE_APP_DATA: dir, ...env },
26 stdin: "ignore",
27 stdout: "pipe",
28 stderr: "pipe",
29 });
30 // It draws once at start-up and then waits on keys; one frame is all we need.
31 await Bun.sleep(700);
32 child.kill();
33 const text = await new Response(child.stdout).text();
34 // eslint-disable-next-line no-control-regex
35 return text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
36 }
37
38 test("the terminal says who a row belongs to, in a column a name cannot fake", async () => {
39 const dir = mkdtempSync(join(tmpdir(), "tty-"));
40 const db = openDatabase(dir);
41 const session = "a".repeat(32);
42 // A forge player who took a guest's shape as their name, and an actual guest.
43 saveMatch(db, { identity: "user:u_1", name: "guest aaaa", guest: false, session }, result());
44 saveMatch(db, { identity: `guest:${session}`, name: "guest aaaa", guest: true, session }, result());
45 db.close();
46
47 const frame = await draw(dir, { FORGE_APP_IDENTITY_KEY: "a-key" });
48 expect(frame).toContain("player");
49 expect(frame).toContain("who");
50 expect(frame).toContain("signed");
51 expect(frame).toContain("guest");
52 // Two rows that read the same in the name column, told apart beside it.
53 expect(frame).toMatch(/guest aaaa\s+signed/);
54 expect(frame).toMatch(/guest aaaa\s+guest/);
55 }, 10_000);
56
57 test("the terminal says when identity is off and everybody is a guest", async () => {
58 const dir = mkdtempSync(join(tmpdir(), "tty-"));
59 openDatabase(dir).close();
60 const frame = await draw(dir, { FORGE_APP_IDENTITY_KEY: "" });
61 expect(frame).toContain("FORGE_APP_IDENTITY_KEY is not set");
62 expect(await draw(dir, { FORGE_APP_IDENTITY_KEY: "a-key" })).not.toContain("FORGE_APP_IDENTITY_KEY is not set");
63 }, 10_000);
src/tty.ts +13 −4
@@ -8,6 +8,8 @@
88 */
99
1010 import { headshotShare, matchCount, openDatabase, ratio, recentMatches, standings, deleteMatch } from "./db.ts";
11 import { isGuest } from "./player.ts";
12 import { identityWarning } from "./who.ts";
1113 import { CARD } from "./client/weights.ts";
1214 import { nextTab, TABS, type Tab } from "./tabs.ts";
1315
@@ -21,6 +23,11 @@ const esc = "\x1b[";
2123 const out = (s: string): void => { process.stdout.write(s); };
2224 const pad = (s: string, n: number): string => (s.length > n ? s.slice(0, n - 1) + "…" : s.padEnd(n));
2325
26 // The page tags a guest row with markup a name cannot produce; a terminal has
27 // no markup, so the tag is its own column instead. A forge player called
28 // "guest aaaa" still reads `signed` here.
29 const who = (identity: string): string => (isGuest(identity) ? "guest" : "signed");
30
2431 let tab: Tab = "standings";
2532 let cursor = 0;
2633 let note = "";
@@ -51,18 +58,18 @@ function draw(): void {
5158 lines.push("");
5259 lines.push(` ${esc}2mretrain with: bun run scripts/train.ts --iters 1000${esc}0m`);
5360 } else if (tab === "standings") {
54 lines.push(`${esc}2m ${pad("player", 26)}${pad("matches", 9)}${pad("kills", 7)}${pad("K/D", 7)}${pad("HS", 6)}wins${esc}0m`);
61 lines.push(`${esc}2m ${pad("player", 26)}${pad("who", 8)}${pad("matches", 9)}${pad("kills", 7)}${pad("K/D", 7)}${pad("HS", 6)}wins${esc}0m`);
5562 if (table.length === 0) lines.push(`${esc}2m nothing played yet${esc}0m`);
5663 table.forEach((s, i) => {
57 const line = `${pad(s.name, 26)}${pad(String(s.matches), 9)}${pad(String(s.kills), 7)}` +
64 const line = `${pad(s.name, 26)}${pad(who(s.identity), 8)}${pad(String(s.matches), 9)}${pad(String(s.kills), 7)}` +
5865 `${pad(ratio(s.kills, s.deaths), 7)}${pad(headshotShare(s.headshots, s.kills), 6)}${s.wins}`;
5966 lines.push(i === cursor ? `${esc}7m▸ ${line}${esc}0m` : ` ${line}`);
6067 });
6168 } else {
62 lines.push(`${esc}2m ${pad("player", 22)}${pad("score", 8)}${pad("k/d", 8)}${pad("damage", 8)}when${esc}0m`);
69 lines.push(`${esc}2m ${pad("player", 22)}${pad("who", 8)}${pad("score", 8)}${pad("k/d", 8)}${pad("damage", 8)}when${esc}0m`);
6370 if (matches.length === 0) lines.push(`${esc}2m no matches yet${esc}0m`);
6471 matches.forEach((m, i) => {
65 const line = `${pad(m.name, 22)}${pad(`${m.score_mine}-${m.score_theirs}`, 8)}` +
72 const line = `${pad(m.name, 22)}${pad(who(m.identity), 8)}${pad(`${m.score_mine}-${m.score_theirs}`, 8)}` +
6673 `${pad(`${m.kills}/${m.deaths}`, 8)}${pad(String(m.damage), 8)}${m.updated_at}` +
6774 `${m.finished === 1 ? "" : " (live)"}`;
6875 lines.push(i === cursor ? `${esc}7m▸ ${line}${esc}0m` : ` ${line}`);
@@ -73,6 +80,8 @@ function draw(): void {
7380 lines.push(ssh === undefined
7481 ? `${esc}2mthe app's terminal is off${esc}0m`
7582 : `${esc}2mreach this terminal with: ${ssh}${esc}0m`);
83 const notice = identityWarning();
84 if (notice !== null) lines.push(`${esc}33m${notice}${esc}0m`);
7685 if (note !== "") lines.push(`${esc}33m${note}${esc}0m`);
7786 out(`${esc}2J${esc}H` + lines.join("\r\n"));
7887 }
src/who.test.ts added +77
@@ -0,0 +1,77 @@
1 /** The identity check, on its own: what the forge signs, and what it does not. */
2
3 import { expect, test } from "bun:test";
4 import { identityConfigured, identityWarning, signInHref, stamp, whoIs } from "./who.ts";
5
6 const KEY = "a-key-only-the-forge-and-this-app-know";
7
8 /** Headers the way the forge sends them; the server tests use this shape too. */
9 const forge = (identity: string, key = KEY): Headers =>
10 new Headers({ "x-forge-identity": identity, "x-forge-signature": stamp(key, identity) });
11
12 const soon = (): number => Date.now() + 60_000;
13
14 const withKey = <T>(key: string | undefined, run: () => T): T => {
15 const had = process.env.FORGE_APP_IDENTITY_KEY;
16 if (key === undefined) delete process.env.FORGE_APP_IDENTITY_KEY;
17 else process.env.FORGE_APP_IDENTITY_KEY = key;
18 try {
19 return run();
20 } finally {
21 if (had === undefined) delete process.env.FORGE_APP_IDENTITY_KEY;
22 else process.env.FORGE_APP_IDENTITY_KEY = had;
23 }
24 };
25
26 test("a signed identity is the person the forge says it is", () => {
27 withKey(KEY, () => {
28 expect(whoIs(forge(`u_7|ada|admin|${soon()}`))).toEqual({ role: "admin", id: "u_7", name: "ada" });
29 expect(whoIs(forge(`u_8|bo|user|${soon()}`))).toEqual({ role: "user", id: "u_8", name: "bo" });
30 });
31 });
32
33 test("anything that cannot be verified is anonymous", () => {
34 withKey(KEY, () => {
35 const anon = { role: "anon" };
36 // no headers at all
37 expect(whoIs(new Headers())).toEqual(anon);
38 // the identity without its signature, and the signature without its identity
39 expect(whoIs(new Headers({ "x-forge-identity": `u_7|ada|user|${soon()}` }))).toEqual(anon);
40 expect(whoIs(new Headers({ "x-forge-signature": stamp(KEY, "x") }))).toEqual(anon);
41 // signed with the wrong key, or the payload changed after signing
42 expect(whoIs(forge(`u_7|ada|user|${soon()}`, "not-the-forge"))).toEqual(anon);
43 const tampered = forge(`u_7|ada|user|${soon()}`);
44 tampered.set("x-forge-identity", `u_7|mallory|user|${soon()}`);
45 expect(whoIs(tampered)).toEqual(anon);
46 // shapes that do not parse
47 expect(whoIs(forge("u_7|ada|user"))).toEqual(anon);
48 expect(whoIs(forge(`u_7|ada|user|${soon()}|extra`))).toEqual(anon);
49 expect(whoIs(forge(`|ada|user|${soon()}`))).toEqual(anon);
50 expect(whoIs(forge(`u_7||user|${soon()}`))).toEqual(anon);
51 expect(whoIs(forge(`u_7|ada|owner|${soon()}`))).toEqual(anon);
52 expect(whoIs(forge(`u_7|ada|USER|${soon()}`))).toEqual(anon);
53 expect(whoIs(forge("u_7|ada|user|soon"))).toEqual(anon);
54 // an expiry that has passed
55 expect(whoIs(forge(`u_7|ada|user|${Date.now() - 1}`))).toEqual(anon);
56 // and an identity longer than any forge sends
57 expect(whoIs(forge(`u_7|${"a".repeat(600)}|user|${soon()}`))).toEqual(anon);
58 });
59 });
60
61 test("with no key nothing can be verified, so nobody is anybody", () => {
62 const headers = withKey(KEY, () => forge(`u_7|ada|user|${soon()}`));
63 expect(withKey(undefined, () => whoIs(headers))).toEqual({ role: "anon" });
64 expect(withKey("", () => whoIs(headers))).toEqual({ role: "anon" });
65 });
66
67 test("an app with no key says so, because a board of guests is not a bug", () => {
68 expect(withKey(KEY, identityConfigured)).toBe(true);
69 expect(withKey(KEY, identityWarning)).toBe(null);
70 expect(withKey(undefined, identityConfigured)).toBe(false);
71 expect(withKey(undefined, identityWarning)).toContain("FORGE_APP_IDENTITY_KEY");
72 expect(withKey("", identityWarning)).toContain("guest");
73 });
74
75 test("the sign-in link comes back here", () => {
76 expect(signInHref("/")).toBe("/__forge/signin?to=%2F");
77 });
src/who.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * Who is asking. Identity is the forge's to assert and ours to verify.
3 *
4 * The forge puts two headers on every request it proxies: `x-forge-identity`,
5 * which is `<userId>|<username>|<role>|<expiresMs>`, and `x-forge-signature`,
6 * which is base64url(HMAC-SHA256(FORGE_APP_IDENTITY_KEY, identity)). We
7 * recompute the signature and compare it in constant time; anything we cannot
8 * verify — no headers, no key, a shape that does not parse, an expiry that has
9 * passed — is anonymous. There is no other way in: no password, no query
10 * parameter, no environment flag, and nothing here reads a cookie.
11 *
12 * The app's own session cookie still exists, but it only says "the browser
13 * that started this match". Identity and match ownership are different jobs.
14 */
15
16 import { createHmac, timingSafeEqual } from "node:crypto";
17
18 export type Who = { role: "anon" } | { role: "user" | "admin"; id: string; name: string };
19
20 export const IDENTITY_HEADER = "x-forge-identity";
21 export const SIGNATURE_HEADER = "x-forge-signature";
22
23 export const ANON: Who = { role: "anon" };
24
25 /** The signature the forge puts on an identity string; the tests sign with it too. */
26 export const stamp = (key: string, identity: string): string =>
27 createHmac("sha256", key).update(identity).digest("base64url");
28
29 /** Constant-time: a wrong signature must not be wrong faster in one place. */
30 function equals(a: string, b: string): boolean {
31 const left = Buffer.from(a);
32 const right = Buffer.from(b);
33 if (left.length !== right.length) return false;
34 return timingSafeEqual(left, right);
35 }
36
37 /** The forge's headers, verified. Anything we cannot prove is `{ role: "anon" }`. */
38 export function whoIs(headers: Headers, now = Date.now()): Who {
39 const key = process.env.FORGE_APP_IDENTITY_KEY;
40 if (!key) return ANON;

x

x

41
42 const identity = headers.get(IDENTITY_HEADER);
43 const signature = headers.get(SIGNATURE_HEADER);
44 if (!identity || !signature || identity.length > 512) return ANON;
45 if (!equals(signature, stamp(key, identity))) return ANON;
46
47 const fields = identity.split("|");
48 if (fields.length !== 4) return ANON;
49 const [id, name, role, expiresMs] = fields as [string, string, string, string];
50 if (id === "" || name === "") return ANON;
51 if (role !== "user" && role !== "admin") return ANON;
52 if (!/^\d{1,15}$/.test(expiresMs) || Number(expiresMs) <= now) return ANON;
53 return { role, id, name };
54 }
55
56 /** False when no FORGE_APP_IDENTITY_KEY is set: then nobody here is anybody. */
57 export const identityConfigured = (): boolean => Boolean(process.env.FORGE_APP_IDENTITY_KEY);
58
59 /**
60 * What to say when identity is off, and null when it is on. A missing key is
61 * not an error — the game plays, the board fills — but it turns every result
62 * into a guest's, and an operator who is not told that will read an empty
63 * leaderboard of guests as a bug in the app instead of a missing secret. The
64 * server prints it at start-up and the terminal prints it at the bottom.
65 */
66 export const identityWarning = (): string | null =>
67 identityConfigured()
68 ? null
69 : "FORGE_APP_IDENTITY_KEY is not set: no request can be verified, so every result is recorded as a guest";
70
71 /** Where a person goes to become someone: the forge's sign-in, and back here. */
72 export const signInHref = (to = "/"): string => `/__forge/signin?to=${encodeURIComponent(to)}`;
73
74 /**
75 * What a link to the forge's own endpoints carries. They share this origin, so
76 * a same-origin navigation would hand the current URL to `/__forge/signin` in
77 * the `Referer` header; nothing on this page is secret, but a sign-in link is
78 * not the place to start.
79 */
80 export const FORGE_LINK_ATTRS = 'rel="noreferrer"';

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs