The nightly rollup keeps what the access log forgets; two doors get a limit

Three sysadmin items ahead of the public announcement's arrivals.

deploy/wizwar-rollup.sh writes one JSON line per UTC day to
/var/lib/wizwar/rollup.jsonl at 00:10: yesterday's traffic from Caddy's
access log (requests, human vs bot addresses as counts only, socket
connects, path mix, external referrers), the table's growth (new
rooms, human seats and names, lifetime game totals, reports and
replies), and the box's vitals (service memory and peak, disk, load,
protocol errors, service starts, ledger size). Re-rolling a day
replaces its line. It checks in to a Sentry cron monitor of its own,
whose URL deploy.sh derives from the backup monitor's on first
install, alongside the cron entry. The pulse gains a Trends section
that reads the last week of it. Caddy keeps 30 log files instead of 5
as the raw backing.

Per-address limits on the two doors anyone may use unseated: 12 new
rooms and 6 reports per address per hour, in a sliding window keyed by
the address Caddy forwards. The per-connection cap stays; it reset on
reconnect, which is what a script would do.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jm2auWk6RP71CjaAb4FMoG
This commit is contained in:
Eric Wagoner
2026-09-03 11:30:44 -04:00
co-authored by Claude Fable 5.1
parent 3f909b485b
commit ca108f83a6
7 changed files with 205 additions and 6 deletions
+15 -1
View File
@@ -67,6 +67,7 @@ import {
import { engagementStats, recordHotseat } from "./stats";
import { appendFeedback, readFeedback, readClips, clipAssetPath } from "./store";
import { clipsIndexHtml, clipPageHtml } from "./clips";
import { SlidingLimit, clientAddress } from "./ratelimit";
import { getShare, loadShares, mintShare } from "./shares";
import { renderSharePng } from "./ogimage";
import { BOT_LINES, type BanterTrigger } from "./banter";
@@ -81,6 +82,10 @@ if (process.env.SENTRY_DSN) {
const MAX_SOCKETS = 300; // concurrent connections
const MAX_ROOMS = 5000; // total rooms on the server
const MAX_ROOMS_PER_CONN = 10; // rooms one connection may create
// Per-address limits, held across reconnects: a table of friends never
// nears them; a script filling the vault or the reports desk does.
const roomsPerAddress = new SlidingLimit(12, 60 * 60 * 1000);
const reportsPerAddress = new SlidingLimit(6, 60 * 60 * 1000);
const MAX_COMMAND_BYTES = 16384; // serialized game command
const MAX_MYGAMES_SEATS = 50; // seats checked per myGames request
const CATCHUP_COOLDOWN_MS = 3000; // full-game replays are CPU-heavy
@@ -409,6 +414,8 @@ interface Session {
spectator: boolean;
/** The raw seat token this connection authenticated with (memory only). */
token: string | null;
/** Where the connection came from, for the per-address limits. */
address: string;
claimFails: number;
// Token bucket: refills at 15 msg/s up to a burst of 30.
bucket: number;
@@ -579,7 +586,7 @@ function broadcastRoomState(room: Room): void {
}
}
wss.on("connection", (socket) => {
wss.on("connection", (socket, req) => {
if (sessions.size >= MAX_SOCKETS) {
send(socket, { type: "error", message: "the tavern is packed — try again shortly" });
socket.close();
@@ -587,6 +594,7 @@ wss.on("connection", (socket) => {
}
const session: Session = {
socket, playerId: null, roomId: null, spectator: false, token: null, claimFails: 0,
address: clientAddress(req.headers, req.socket.remoteAddress),
bucket: 30, lastRefill: Date.now(), overLimitStrikes: 0,
roomsCreated: 0, lastCatchUpAt: 0, hotseatReports: 0,
};
@@ -626,6 +634,9 @@ wss.on("connection", (socket) => {
if (session.roomsCreated >= MAX_ROOMS_PER_CONN || roomCount() >= MAX_ROOMS) {
return send(socket, { type: "error", message: "no new rooms right now — try again later" });
}
if (!roomsPerAddress.allow(session.address)) {
return send(socket, { type: "error", message: "that's a lot of new tables from one place — try again in an hour" });
}
session.roomsCreated++;
leaveGallery(session);
const { room, token } = createRoom(name);
@@ -868,6 +879,9 @@ wss.on("connection", (socket) => {
String(raw ?? "").replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, " ").trim().slice(0, 2000);
const happened = clean(msg.happened);
if (!happened) return send(socket, { type: "error", message: "say what happened" });
if (!reportsPerAddress.allow(session.address)) {
return send(socket, { type: "error", message: "the desk has plenty from you for now — more in an hour" });
}
appendFeedback({
id: randomBytes(4).toString("hex"),
at: new Date().toISOString(),
+40
View File
@@ -0,0 +1,40 @@
// A per-key sliding-window limiter for the two doors anyone may walk
// through unseated: creating rooms and filing reports. Per-connection
// caps reset on reconnect; these are keyed by client address and hold
// for the window. Memory is bounded by pruning keys whose windows have
// emptied.
export class SlidingLimit {
private hits = new Map<string, number[]>();
private lastSweep = 0;
constructor(private readonly max: number, private readonly windowMs: number) {}
/** Record a hit for `key` if it is under the limit; false if it is not. */
allow(key: string, now = Date.now()): boolean {
this.sweep(now);
const cutoff = now - this.windowMs;
const times = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
if (times.length >= this.max) { this.hits.set(key, times); return false; }
times.push(now);
this.hits.set(key, times);
return true;
}
private sweep(now: number): void {
if (now - this.lastSweep < this.windowMs) return;
this.lastSweep = now;
const cutoff = now - this.windowMs;
for (const [k, times] of this.hits) {
if (!times.some((t) => t > cutoff)) this.hits.delete(k);
}
}
}
/** The client's address as Caddy reports it — the first hop in
* X-Forwarded-For — falling back to the socket's own peer. */
export function clientAddress(headers: Record<string, string | string[] | undefined>, remote: string | undefined): string {
const fwd = headers["x-forwarded-for"];
const first = (Array.isArray(fwd) ? fwd[0] : fwd)?.split(",")[0]?.trim();
return first || remote || "unknown";
}