Phone panels (reviewed + QA'd, matrix of 22 layouts with real taps/bounding boxes): - selected-tower action bar over the board (Upgrade/Sell/Target/close), info panel updated in place so taps are never lost, scrollable palette for 7+ towers, overlays with pinned footers (Help "Got it", Play solo, Join always visible), tappable room chip to invite, reduced-motion/contrast/forced-colors fixes, paused state, partner cursor labels, bigger level pips and owner flags - touch input rewritten around "pointerdown commits nothing": pinch never builds, 10px tap slop, palm-proof pinch, long-press pings with any tool armed, nudge arrows for precise placement, hotkey repeat guard, proportional wheel zoom - new e2e: select/sell, info-panel stability, UI states, touch precision; camera unit tests Proxy/server (reproduced against real nginx 1.26 with NPM v2.16 config): - Origin check works when the proxy drops a non-default port, TRUSTED_PROXIES for proxies on global IPv6/CGNAT addresses, service worker no longer serves nginx's 502 page, DEPLOY.md corrected (NPM default read timeout is 90 s, Advanced-tab limits, path-prefix, cookie size, per-IP cap behaviour) Content: - Orbital Uplink: 4-level endgame tower (450 + 500/800/1200 credits): piercing armour-ignoring beam, blast and lingering slow, ground+air, range 11-14; glyph, beam effect, sound, help text, unit tests - Maps: The Canyon, Archipelago, Fortress, Pinwheel (7 maps total) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
11 KiB
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
pingMsthe 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 (nginxproxy_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 intrustedProxies), take the client IP fromX-Forwarded-For(elseX-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/falseforce it.maxConnPerIp: 0disables the cap. Reject extra sockets with HTTP429on upgrade. - Origin check (see below) accepts: Origin host ==
Hostheader; or ==X-Forwarded-Hostwhen the proxy is trusted; or, when the proxy is trusted andHosthas no port, the same host name on any port (nginx'sHost $host, which nginx Proxy Manager uses, drops the port ofhttps://game.example.com:8443); or the Origin is listed inallowedOrigins. Compare scheme-lesshost[: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)withhttp->ws,https->wss), sohttps://x.example/netwall/proxied to/works. The server therefore accepts the upgrade on path/wsonly (the proxy strips any prefix). HEAD/GET /healthzreturns200 okfor proxy health checks.- Do not trust
X-Forwarded-Protofor anything security relevant. - Disable
wsper-message-deflate (default for the server) - snapshots are small and CPU is better spent elsewhere.
HTTP
GET|HEADof files underpublic/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 outsidepublic/. 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 anOriginheader, its host must equal theHostheader (or one of the trusted-proxy /allowedOriginscases above), else403(stops random web pages from driving a LAN server). NoOrigin(non-browser clients/tests) is fine. - A socket that has not sent a valid
joinwithin 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? }
pid^[A-Za-z0-9_-]{8,40}$- random, generated by the client, kept insessionStorage(stable across reloads).nameany string; server trims, strips control chars, caps at 16 chars, default"Player".roomabsent -> create a room.mapmust be a key ofTD.MAPS(default'open'). Server generates a 4 character code fromABCDEFGHJKLMNPQRSTUVWXYZ23456789, unique among rooms.roompresent (^[A-Za-z0-9]{4}$, case-insensitive -> upper-cased) -> 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.
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
joinwhosepidalready holds a slot in that room re-binds to it (resumed:true); the old socket, if still open, is closed with 4001. Nofullerror for the pid that owns the slot. - Grace: when a socket closes the player stays in the room with
online:falseforgraceMs, then is removed (andplayersre-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 / 'target' id,mode / 'wave' / 'auto' v / 'continue' |
other sim commands, same path |
{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} |
host only: replace the sim with a fresh new Sim({map}); resets pause/speed |
{t:'leave'} |
leave now |
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.
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 }
seqincrements by 1 per snapshot per room.- Snapshots are sent every
1000/snapshotHzms 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. evevents are drained from the sim once per snapshot, so every client sees every event exactly once.- Because WebSocket is reliable and ordered,
twdeltas cannot be lost;snap.revlets a client detect a bug/desync (revdiffers from therevit last applied and notwcame along) and ask forsync.
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.