towerdef/docs/PROTOCOL.md
Claude b4ae6cb57d Difficulty picker (Easy/Normal/Hard) and a balance pass
Difficulty:
- TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated
  create-room / newgame option, state carries it; solo menu picker and co-op lobby
  picker (44px segmented control, reachable on every layout), HUD/room/end-screen
  labels, best-wave record per map AND difficulty (Normal keeps the legacy key),
  Play again keeps the running game's difficulty for host and guest

Balance (12 bot runs, deterministic, 48/48 games replay identically in QA):
- Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open
- credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling
  eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at
  wave 30: 1309 -> 335
- IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only
  dies by wave 7); Mortar, Arc and Filter buffed
- Orbital Uplink price step per owned unit 30% (buy and upgrade)
- remaining imbalances documented in docs/BALANCE.md

Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix
reachability of the picker. 156 unit tests, 17 e2e scenarios.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-10 23:41:21 +00:00

219 lines
17 KiB
Markdown

# Netwall multiplayer protocol (v1)
Two people play **the same map together**: one shared base, one shared credit pool, one shared set of lives.
The Node server runs the game (the same `public/js/sim.js` the browser uses for solo play) and is the
single source of truth. Clients send *commands*; the server steps the simulation and broadcasts *snapshots*.
Clients never simulate in multiplayer; they render (with interpolation) what the server says.
Transport: one WebSocket per player at `ws(s)://<host>/ws`, JSON text frames, one object per frame, field `t`
= message type. Client -> server frames are capped at **2048 bytes** (`maxPayload`).
## Server
`server/index.js` exports `createServer(opts)` and, when run directly (`node server/index.js`), starts it.
```
createServer({ port = 8080, host = '::', publicDir = <repo>/public,
graceMs = 60000, snapshotHz = 20, maxRooms = 50,
trustProxy = 'auto', trustedProxies = null, allowedOrigins = [], maxConnPerIp = 40, pingMs = 25000,
log = console.log })
-> Promise<{ port, addresses: string[], close(): Promise<void>, rooms: Map }>
```
Env when run directly: `PORT` (8080), `HOST` (`::`), `TRUST_PROXY` (`auto`|`1`|`0`), `TRUSTED_PROXIES` (comma separated
IPs / CIDRs added to the private ranges that `auto` trusts; a bad entry stops the start-up), `ALLOWED_ORIGINS`
(comma separated, e.g. `https://game.example.com`; include `:port` when it is not 80/443), `MAX_CONN_PER_IP`, `GRACE_MS`.
Prints `http://localhost:PORT/` and every non-internal LAN URL from `os.networkInterfaces()` (IPv4 as
`http://a.b.c.d:PORT/`, IPv6 as `http://[addr]:PORT/`, skip link-local `fe80::`).
Handles SIGINT/SIGTERM by closing sockets and exiting 0.
### Dual stack
Default `host` is `::` and the listen call must pass `ipv6Only: false` so that one socket serves **IPv4 and
IPv6** (IPv4 arrives as `::ffff:a.b.c.d`; normalise it for logs). If binding `::` fails with `EAFNOSUPPORT`,
`EADDRNOTAVAIL` or similar (IPv6 disabled in the container), fall back to `0.0.0.0` and log that. Any explicit
`host` (e.g. `127.0.0.1` in tests, or `HOST=0.0.0.0`) is honoured as given. `addresses` lists what is bound.
### Behind a reverse proxy (nginx Proxy Manager, nginx, Caddy, Traefik)
The server is meant to sit behind TLS-terminating proxies with "Websockets Support" enabled and must work both
at a domain root and under a path prefix the proxy strips.
* **Keep-alive.** Every `pingMs` the server sends a WebSocket *protocol* ping to each socket and terminates sockets
that did not pong since the previous round (so a dead mobile client is noticed within ~2 rounds and goes into the
grace period). The pings are for dead-peer detection: a joined socket gets ~20 snapshots/s anyway, which is what
keeps a proxy's idle timer (nginx `proxy_read_timeout`; 60 s by default, 90 s in nginx Proxy Manager) quiet.
* **Real client IP** is used only for logging and the per-IP socket cap `maxConnPerIp`. `trustProxy:'auto'`
means: if the TCP peer is loopback / RFC1918 / `fc00::/7` / link-local (or listed in `trustedProxies`), take the client IP from
`X-Forwarded-For` (else `X-Real-IP`): the *rightmost* entry that is not a private address (proxies append, so
entries further left are the client's own forgeable claim); otherwise use the TCP peer and ignore those headers.
`true`/`false` force it. `maxConnPerIp: 0` disables the cap. Reject extra sockets with HTTP `429` on upgrade.
* **Origin check** (see below) accepts: Origin host == `Host` header; or == `X-Forwarded-Host` when the proxy is
trusted; or, when the proxy is trusted and `Host` has **no port**, the same host name on any port (nginx's
`Host $host`, which nginx Proxy Manager uses, drops the port of `https://game.example.com:8443`); or the Origin is
listed in `allowedOrigins`. Compare scheme-less `host[:port]`, treat default ports (80/443) as equal to "no port",
case-insensitive.
* **No absolute URLs, no hard-coded port** anywhere in served content; the client builds the socket URL relative
to the page (`new URL('ws', location.href)` with `http->ws`, `https->wss`), so `https://x.example/netwall/`
proxied to `/` works. The server therefore accepts the upgrade on path `/ws` only (the proxy strips any prefix).
* `HEAD`/`GET /healthz` returns `200 ok` for proxy health checks.
* Do **not** trust `X-Forwarded-Proto` for anything security relevant.
* Disable `ws` per-message-deflate (default for the server) - snapshots are small and CPU is better spent elsewhere.
### HTTP
* `GET|HEAD` of files under `public/` only. `/` -> `index.html`. Correct MIME (html, js, css, json, svg,
png, jpg, ico, woff2, mp3, ogg, wav, txt). `Cache-Control: no-cache`.
* Path traversal (`..`, `%2e%2e`, `%2f`, backslash, NUL, absolute paths, dotfiles) -> 400/404, never a file
outside `public/`. Other methods -> 405.
* `GET /healthz` -> `200 ok`.
* Headers on every response: `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`,
`Content-Security-Policy: default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' data:; base-uri 'none'; frame-ancestors 'none'`.
### WebSocket upgrade
* Only on path `/ws`. If the request has an `Origin` header, its host must equal the `Host` header (or one of the
trusted-proxy / `allowedOrigins` cases above), else `403` (stops random web pages from driving a LAN server). No
`Origin` (non-browser clients/tests) is fine.
* A socket that has not sent a valid `join` within **10 s** is closed (4408).
* Per-socket rate limit: token bucket 60 msg/s, burst 120; beyond that close with 4429.
* More than 20 malformed/unknown messages on a socket -> close 4400.
## Handshake
Client's first message:
```
{ t:'join', pid, name, room?, map?, difficulty? }
```
* `pid` `^[A-Za-z0-9_-]{8,40}$` - random, generated by the client, kept in `sessionStorage` (stable across reloads).
* `name` any string; server trims, strips control chars, caps at 16 chars, default `"Player"`.
* `room` absent -> **create** a room. `map` must be a key of `TD.MAPS` (default `'open'`). `difficulty` must be a key of
`TD.DIFFICULTIES` (`'easy'`, `'normal'`, `'hard'`; default `'normal'`, `null` counts as absent), see "Difficulty" below.
Server generates a 4 character code from `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, unique among rooms.
* `room` present (`^[A-Za-z0-9]{4}$`, case-insensitive -> upper-cased) -> **join**. `map` and `difficulty` are ignored on a join (not even
validated): the joiner gets the room's, in `state.map` / `state.difficulty` of the `joined` message. A reconnect (same `pid`) is a join.
Failure: `{ t:'error', code, msg }` then the server closes the socket (code 4000+).
Codes: `bad_request`, `no_room`, `full` (two *other* pids already hold the slots), `too_many_rooms`, `bad_map`, `bad_difficulty`
(a creating join whose `difficulty` is not one of the table's keys: wrong type, `'toString'`, `'__proto__'`, ... all refused, no room is
created, the socket closes with 4400; a bad `map` is checked first).
Success: reply to the joiner
```
{ t:'joined', room, resumed, you:{ pid, slot, host },
players:[ { pid, slot, name, host, online } ], // everyone incl. you
state: <sim.fullState()>, snap: <sim.snapshot()>, speed, paused }
```
then broadcast `{ t:'players', players:[...] }` to all *other* players.
`pid` is the reconnect secret (whoever presents it takes the slot), so in every `players` list it is the viewer's own
pid for the viewer's own entry and an opaque, stable per-room alias for the other player's entry. Compare entries by
`pid` within the lists you receive and find yourself with `you.pid`; never expect to see the other player's real pid.
* A player owns a **slot** (0 or 1), the lowest free one, kept until they leave for good.
* **Host** = creator; if the host leaves for good the other player becomes host.
* **Reconnect**: a `join` whose `pid` already holds a slot in that room re-binds to it (`resumed:true`); the old
socket, if still open, is closed with 4001. No `full` error for the pid that owns the slot.
* **Grace**: when a socket closes the player stays in the room with `online:false` for `graceMs`, then is removed
(and `players` re-broadcast). A player who sent `{t:'leave'}` is removed immediately.
* The simulation **only ticks while at least one player is online**. A room with no one left is deleted.
## Client -> server (after joining)
| message | meaning |
|---|---|
| `{t:'cmd', c:'place', type, x, y}` | build. Server calls `sim.cmd({...msg, by: slot})` (never trust a `by` from the client) |
| `{t:'cmd', c:'sell', id}` / `'upgrade'` `id, lv?` / `'target'` `id,mode` / `'wave'` `n?` / `'auto'` `v` / `'continue'` | other sim commands, same path. `lv` and `n` make `upgrade` and `wave` idempotent, see below |
| `{t:'ctl', c:'pause', v:bool}` / `{t:'ctl', c:'speed', v:1\|2\|3}` | room-level; reflected in `snap.pa` / `snap.sp` |
| `{t:'cursor', x, y}` | hover position in cell units (floats) or `x:null` to hide; clamp to board, round to 2 dp |
| `{t:'mark', x, y}` | map ping; at most 1 per 400 ms per player; server broadcasts `mark` (below) |
| `{t:'rtt', ts}` | latency probe; reply immediately with the same `ts` |
| `{t:'sync'}` | ask for a full state resend |
| `{t:'newgame', map?, difficulty?}` | **host only**: replace the sim with a fresh `new Sim({map, difficulty})`; resets pause/speed. An absent (or `null`) `map` / `difficulty` keeps the room's current one, so a plain `{t:'newgame'}` is "play again" |
| `{t:'leave'}` | leave now |
**Idempotent `upgrade` and `wave`.** Two players who press Upgrade (or Next wave) at the same moment both send the command; without
a guard the tower would be upgraded twice and the second player charged for a level they never asked for, or two waves would start.
Both commands therefore carry what the sender *saw*: `lv` (upgrade) is the tower level on the sender's screen, `n` (wave) is the wave
number the sender expects the command to start (the wave counter they saw, plus one). The sim applies the command only if that still
holds; otherwise nothing changes and the sender gets `{ t:'reject', c, reason:'stale', id? }`. Clients treat `stale` as "your partner
was a moment faster" and show nothing. Both fields are optional (no field, no check: older clients, the balance bot and the server's
own auto-wave timer send none); when present they must be integers, anything else is a malformed message. `stale` is checked after
`over` / `no_tower` and before `max` / `gold`, so a sender who is behind is told it is stale rather than that the tower is maxed out.
Command validation is the server's job: `t:'cmd'` must carry a string `c` in the whitelist above; unknown
`c`, non-object, etc. count as malformed. A command the sim refuses (`{ok:false, reason}`) gets
`{ t:'reject', c, reason, x?, y?, id? }` sent **to the sender only** (echo `x,y`/`id` when present).
Successful commands send nothing extra; the effect arrives via `snap`.
`newgame` from a non-host -> `reject` with `reason:'not_host'`; `newgame` with a bad map -> `reject` `bad_map`; with a bad difficulty
-> `reject` `bad_difficulty` (checked in the order not_host, bad_map, bad_difficulty; a rejected `newgame` changes nothing and sends no `state`).
## Client behaviour that the protocol relies on
* **Dead connections.** A joined socket gets ~20 `snap`s per second even when the game is paused, so the client treats 5 s without any
frame as a dead socket (a half-open connection after a Wi-Fi / cell switch or a NAT / proxy drop never delivers a close for a minute
or more). It shows its "reconnecting" state at once, detaches the old socket and opens a new one with the same `join` (same `pid`);
the server hands the seat to the new connection and closes the old one with 4001, which the abandoned socket ignores. A socket that
has not reached `joined` 10 s after it was opened is abandoned the same way. Retries back off up to 5 s, 14 in all.
* **Tower lists.** `tw` is sent once per `rev` change and must never be lost, whatever the render rate: a client that is stalled (hidden
tab, long frame) and gets a burst of snapshots keeps the newest undisplayed `tw` when it trims its interpolation buffer, and asks for
`sync` if `snap.rev` and the rev of the last applied list ever disagree.
* **"No such room" after a reconnect** (`error` / `no_room` in answer to a `join` for the room the client was in) means the server
restarted (rooms live in memory only) or the room expired. The client says so ("The server restarted, your game was lost.") and
forgets the saved room; after a plain connection failure it keeps the saved room, because the seat is held for `graceMs`.
## Server -> client
```
{ t:'snap', seq, ...sim.snapshot(), ev:[ ...sim.drainEvents() ],
cur:[ [slot, x, y], ... ], // other players' cursors (only those currently set), all players included
pa:0|1, sp:1|2|3,
tw?: sim.towerList() } // ONLY when sim.rev changed since the previous snap was sent to the room
{ t:'state', state:<fullState>, snap:<snapshot>, speed, paused, newgame?:true } // reply to sync / newgame
{ t:'players', players:[...] }
{ t:'mark', slot, x, y } // to everyone in the room, including the sender
{ t:'rtt', ts }
{ t:'reject', c, reason, ... }
{ t:'error', code, msg }
```
* `state.difficulty` (also in the `joined` message) is the room's difficulty id. It is a field of `fullState()`, added next to `map`,
`rev`, `towers`, `winWave` and `maxLives`; an older server sends none and a client then assumes `'normal'`. The per-tick `snap` does
not repeat it: it cannot change without a `state` message (only the host's `newgame` changes it, and that sends one).
* `seq` increments by 1 per snapshot per room.
* Snapshots are sent every `1000/snapshotHz` ms **whether or not** the sim advanced (paused rooms still send, so
cursors keep moving) but only to online players, and only if at least one player is online.
* `ev` events are drained from the sim once per snapshot, so every client sees every event exactly once.
* **Tower rows** (`tw`, `state.towers`) are `[id, type, x, y, level, mode, spent, owner, pm]`; `pm` is the price multiplier the tower was bought at (1 for
almost every tower; the Orbital Uplink gets dearer for every one owned, and its upgrades cost the same multiple). Clients that ignore the ninth
field still work; the UI uses it to show the same upgrade price the sim will charge.
* **Monster entries** in `snap.mo` are `[id, kindIndex, x, y, hp, maxhp, slow]`. `kindIndex` indexes `TD.ENEMY_ORDER` (append-only, so
old and new clients agree). Two encodings keep the format fixed: a **shielded** enemy (the Proxy) sends `hp = hp + shield` and
`maxhp = maxhp + maxShield` (the client derives the shield part from the kind's base hp : shield ratio); and the `slow` flag is `1`
while the enemy is slowed **or stunned** (a stunned enemy simply stops moving, the client infers the stun from that).
* New events: `stun {x, y, r, n}` (a Sandbox pulse: centre, radius, number of enemies hit) and `heal {x, y, r}` (a Daemon pulse), besides
the Orbital Uplink's `beam {x, y, tx, ty, w, bx, by, br}`.
* Because WebSocket is reliable and ordered, `tw` deltas cannot be lost; `snap.rev` lets a client detect a
bug/desync (`rev` differs from the `rev` it last applied and no `tw` came along) and ask for `sync`.
## Difficulty
`TD.DIFFICULTIES` (`sim.js`) has one row per difficulty, `{ id, name, gold, lives, hp, reward }`, every number a multiplier on the normal
game; `TD.DIFFICULTY_ORDER` is `['easy', 'normal', 'hard']` (append-only: the ids are on the wire). `new Sim({ map, difficulty })`:
* `gold`, `lives`: the starting credits and integrity are `START_GOLD` / `START_LIVES` times it (rounded, integrity at least 1;
`state.maxLives` follows). An explicit `gold` / `lives` option of the Sim (tests, the balance bot) is used as given.
* `hp`: the hit points of every enemy **and its shield**, so the snapshot's `hp + shield` / `maxhp + maxShield` encoding (the client splits
the two by the kind's base ratio) stays right.
* `reward`: what a kill pays (at least 1). The wave clear bonus and the tower prices do not change.
* An unknown value in `new Sim` is `'normal'`; the server refuses it (`bad_difficulty`) instead.
Normal is all 1: it plays the base tables of `sim.js` as they are (those tables were retuned in the wave 4 balance pass, see `docs/BALANCE.md`). The room's difficulty is fixed for a game: the host picks
it when creating the room (`join.difficulty`) or when starting a new game (`newgame.difficulty`).
## Tick loop
Fixed step `TD.STEP` (1/60 s) with an accumulator driven by `process.hrtime.bigint()`; real time elapsed is
multiplied by `speed` (1-3) and ignored while `paused`; clamp elapsed per iteration to 250 ms so a stalled event
loop does not fast-forward the game. Drive it with a `setInterval` of ~8 ms (or setTimeout chain) per room, or one
global loop for all rooms. Must keep working with several rooms at once.
## Events (`ev`), produced by the sim
`place`, `sell`, `up`, `shot`, `arc`, `boom`, `kill`, `leak`, `wave`, `clear`, `win`, `lose` (see `sim.js`).
Treat them as opaque JSON.