towerdef/server/index.js
Claude a5bd09d505 Phone UI and touch precision overhaul, proxy fixes, Orbital Uplink, four new maps
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
2026-10-10 18:03:24 +00:00

321 lines
15 KiB
JavaScript

'use strict';
/*
* Netwall server: static files + one WebSocket endpoint (/ws) running authoritative co-op game rooms.
* See docs/PROTOCOL.md (wire contract) and docs/DEPLOY.md (running it behind nginx Proxy Manager).
*
* const { createServer } = require('./server');
* const srv = await createServer({ port: 8080 }); // srv.port, srv.addresses, srv.close(), srv.rooms
*
* Run directly: PORT=8080 HOST=:: TRUST_PROXY=auto TRUSTED_PROXIES=100.64.0.0/10 ALLOWED_ORIGINS=https://game.example.com node server/index.js
*/
const http = require('http');
const path = require('path');
const { WebSocketServer } = require('ws');
const TD = require('../public/js/sim.js');
const { RoomManager } = require('./room');
const { createStaticHandler, applySecurityHeaders, CSP } = require('./static');
const { parseTrustProxy, parseTrustedProxies, isTrustedPeer, clientIp, originAllowed, TokenBucket, listenDual, listUrls } = require('./net');
const MAX_PAYLOAD = 2048; // bytes per client frame
const RATE_PER_SEC = 60, RATE_BURST = 120;
const MAX_BAD_MESSAGES = 20;
const PID_RE = /^[A-Za-z0-9_-]{8,40}$/;
const ROOM_RE = /^[A-Za-z0-9]{4}$/;
const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
// Close codes for a failed join (the 'error' message carries the machine-readable code).
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const noop = () => {};
function cleanName(v) {
if (typeof v !== 'string') return 'Player';
const s = Array.from(v.replace(NAME_STRIP, '').trim()).slice(0, 16).join('').trim();
return s || 'Player';
}
function defaultLog(msg) { console.log(new Date().toISOString() + ' ' + msg); }
async function createServer(userOpts) {
const o = {
port: 8080, host: '::', publicDir: path.join(__dirname, '..', 'public'),
graceMs: 60000, snapshotHz: 20, maxRooms: 50,
trustProxy: 'auto', trustedProxies: null, allowedOrigins: [], maxConnPerIp: 40, pingMs: 25000, log: defaultLog,
joinTimeoutMs: 10000, // not in the protocol's option list: lets tests shorten the 10 s join window
};
for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k];
o.trustProxy = parseTrustProxy(o.trustProxy);
o.trustedProxies = parseTrustedProxies(o.trustedProxies); // null, or { list, has(ip) }: extra proxy addresses for 'auto'
o.allowedOrigins = (o.allowedOrigins || []).map(String).filter(Boolean);
o.snapshotHz = Math.min(60, Math.max(1, Number(o.snapshotHz) || 20));
const log = typeof o.log === 'function' ? o.log : noop;
const manager = new RoomManager({ maxRooms: o.maxRooms, graceMs: o.graceMs, snapshotHz: o.snapshotHz, log });
const serveStatic = createStaticHandler(o.publicDir);
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
wss.on('error', (err) => log('websocket server error: ' + (err && err.message)));
let closing = false;
const ipCount = new Map(); // client ip -> open websockets
const sockets = new Set(); // every raw TCP socket, so close() can finish the job
// ---------------------------------------------------------------- HTTP
const server = http.createServer((req, res) => {
applySecurityHeaders(res);
const pathOnly = (req.url || '').split(/[?#]/)[0];
if (pathOnly === '/healthz') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405, { Allow: 'GET, HEAD', 'Content-Length': 0 });
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': 2, 'Cache-Control': 'no-store' });
return res.end(req.method === 'HEAD' ? undefined : 'ok');
}
if (pathOnly === '/ws') { // a plain GET of the socket endpoint
res.writeHead(426, { Upgrade: 'websocket', Connection: 'Upgrade', 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': 17 });
return res.end(req.method === 'HEAD' ? undefined : 'Upgrade Required\n');
}
serveStatic(req, res).catch((err) => {
log('static error: ' + (err && err.message));
if (!res.headersSent) { res.writeHead(500, { 'Content-Length': 0 }); res.end(); } else res.destroy();
});
});
// Longer than the typical 60 s idle timeout of reverse proxies, so a keep-alive upstream connection is
// never closed from under them (the classic intermittent 502).
server.keepAliveTimeout = 65000;
server.headersTimeout = 66000;
server.on('connection', (s) => { sockets.add(s); s.once('close', () => sockets.delete(s)); });
// ---------------------------------------------------------------- WebSocket upgrade
function refuse(socket, status, text) {
socket.end('HTTP/1.1 ' + status + ' ' + text + '\r\nConnection: close\r\nContent-Length: 0\r\n' +
'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: ' + CSP + '\r\n\r\n');
}
server.on('upgrade', (req, socket, head) => {
socket.on('error', noop);
if (closing) return refuse(socket, 503, 'Service Unavailable');
if ((req.url || '').split('?')[0] !== '/ws') return refuse(socket, 404, 'Not Found');
if (!originAllowed(req, o)) {
log('refused websocket from ' + clientIp(req, o.trustProxy, o.trustedProxies) + ': Origin ' + JSON.stringify(req.headers.origin) +
' does not match Host ' + JSON.stringify(req.headers.host) + (isTrustedPeer(req, o.trustProxy, o.trustedProxies)
? ' (see ALLOWED_ORIGINS)'
: ' (this connection is not from a trusted proxy: see TRUST_PROXY, TRUSTED_PROXIES and ALLOWED_ORIGINS)'));
return refuse(socket, 403, 'Forbidden');
}
const ip = clientIp(req, o.trustProxy, o.trustedProxies);
if (o.maxConnPerIp > 0 && (ipCount.get(ip) || 0) >= o.maxConnPerIp) {
log('refused websocket from ' + ip + ': too many connections');
return refuse(socket, 429, 'Too Many Requests');
}
ipCount.set(ip, (ipCount.get(ip) || 0) + 1);
socket.once('close', () => {
const n = (ipCount.get(ip) || 1) - 1;
if (n > 0) ipCount.set(ip, n); else ipCount.delete(ip);
});
wss.handleUpgrade(req, socket, head, (ws) => onConnection(ws, ip));
});
// ---------------------------------------------------------------- one socket
function send(ctx, obj) {
if (ctx.ws.readyState === 1) { try { ctx.ws.send(JSON.stringify(obj)); } catch (e) { /* closing */ } }
}
// Close from our side. Anything the client still sends afterwards is ignored.
function kill(ctx, code, reason) {
if (ctx.dead) return;
ctx.dead = true;
try { ctx.ws.close(code, reason); } catch (e) { /* already closed */ }
ctx.killTimer = setTimeout(() => { try { ctx.ws.terminate(); } catch (e) { /* gone */ } }, 2000);
}
function failJoin(ctx, code, msg) {
send(ctx, { t: 'error', code, msg });
kill(ctx, JOIN_CLOSE[code] || 4400, code);
}
function onConnection(ws, ip) {
const ctx = {
ws, ip, bucket: new TokenBucket(RATE_PER_SEC, RATE_BURST), bad: 0,
player: null, room: null, dead: false, alive: true, joinTimer: null, killTimer: null,
};
ws.ctx = ctx;
ws.on('error', noop); // oversize frames etc.: ws closes the socket itself right after
ws.on('pong', () => { ctx.alive = true; });
// A bug must never take the whole process (and every other room) down: drop just this socket.
ws.on('message', (data, isBinary) => {
try { onMessage(ctx, data, isBinary); } catch (err) {
log('error handling a message from ' + ip + ': ' + (err && err.stack || err));
kill(ctx, 1011, 'internal error');
}
});
ws.on('close', () => { try { onClose(ctx); } catch (err) { log('error in close handler: ' + (err && err.stack || err)); } });
ctx.joinTimer = setTimeout(() => {
ctx.joinTimer = null;
if (!ctx.player) kill(ctx, 4408, 'join timeout');
}, o.joinTimeoutMs);
}
function onClose(ctx) {
ctx.dead = true;
if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; }
if (ctx.killTimer) { clearTimeout(ctx.killTimer); ctx.killTimer = null; }
if (ctx.room && ctx.player) ctx.room.disconnect(ctx);
}
function malformed(ctx) {
if (!ctx.player) return failJoin(ctx, 'bad_request', 'expected a valid join message');
if (++ctx.bad > MAX_BAD_MESSAGES) kill(ctx, 4400, 'too many malformed messages');
}
function onMessage(ctx, data, isBinary) {
if (ctx.dead) return;
if (!ctx.bucket.take()) { log('rate limit exceeded by ' + ctx.ip); return kill(ctx, 4429, 'rate limit'); }
if (isBinary) return malformed(ctx);
let msg;
try { msg = JSON.parse(data.toString('utf8')); } catch (e) { return malformed(ctx); }
if (!msg || typeof msg !== 'object' || Array.isArray(msg) || typeof msg.t !== 'string') return malformed(ctx);
if (!ctx.player) {
if (msg.t !== 'join') return malformed(ctx);
return handleJoin(ctx, msg);
}
if (msg.t === 'leave') {
const room = ctx.room;
room.leave(ctx);
kill(ctx, 1000, 'left');
return;
}
if (!ctx.room.handleMessage(ctx.player, msg)) malformed(ctx);
}
function handleJoin(ctx, msg) {
if (closing) return kill(ctx, 1001, 'server shutting down');
if (typeof msg.pid !== 'string' || !PID_RE.test(msg.pid)) return failJoin(ctx, 'bad_request', 'pid must match ^[A-Za-z0-9_-]{8,40}$');
const creating = msg.room === undefined || msg.room === null;
if (!creating && (typeof msg.room !== 'string' || !ROOM_RE.test(msg.room))) return failJoin(ctx, 'bad_request', 'room must be 4 letters or digits');
const name = cleanName(msg.name);
let room, why;
if (creating) {
let map = 'open';
if (msg.map !== undefined && msg.map !== null) {
if (typeof msg.map !== 'string' || !hasOwn(TD.MAPS, msg.map)) return failJoin(ctx, 'bad_map', 'unknown map');
map = msg.map;
}
room = manager.create(map);
if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit');
why = 'created';
} else {
room = manager.get(msg.room.toUpperCase());
if (!room) return failJoin(ctx, 'no_room', 'no such room');
}
const r = room.join(msg.pid, name, ctx);
if (!r) return failJoin(ctx, 'full', 'both slots in this room are taken');
ctx.player = r.player;
ctx.room = room;
if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; }
send(ctx, room.joinedMsg(r.player, r.resumed));
room.broadcastPlayers(ctx);
room.log(name + ' ' + (r.resumed ? 'resumed' : (why || 'joined')) + ' as slot ' + r.player.slot + (r.player.host ? ' (host)' : '') + ' from ' + ctx.ip);
}
// ---------------------------------------------------------------- listen / close
const bound = await listenDual(server, o.port, o.host, log);
const addr = server.address();
const port = addr && typeof addr === 'object' ? addr.port : o.port;
server.on('error', (err) => log('http server error: ' + (err && err.message))); // e.g. EMFILE while accepting
// ---------------------------------------------------------------- keep-alive
// Protocol-level ping every pingMs; a socket that did not pong since the previous round is terminated
// (it then enters the room's grace period). Keeps idle proxies (nginx proxy_read_timeout) happy.
let pingTimer = null;
if (o.pingMs > 0) {
pingTimer = setInterval(() => {
for (const ws of wss.clients) {
const ctx = ws.ctx;
if (!ctx) continue;
if (!ctx.alive) { ws.terminate(); continue; }
ctx.alive = false;
try { ws.ping(); } catch (e) { /* closing */ }
}
}, o.pingMs);
}
let closePromise = null;
function close() {
if (closePromise) return closePromise;
closePromise = (async () => {
closing = true;
if (pingTimer) { clearInterval(pingTimer); pingTimer = null; }
manager.close();
const stopped = new Promise((resolve) => server.close(() => resolve()));
for (const ws of wss.clients) {
const ctx = ws.ctx;
if (ctx) { ctx.dead = true; if (ctx.joinTimer) clearTimeout(ctx.joinTimer); }
try { ws.close(1001, 'server shutting down'); } catch (e) { /* closing */ }
}
const deadline = Date.now() + 1000;
while (wss.clients.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10));
for (const ws of wss.clients) { try { ws.terminate(); } catch (e) { /* gone */ } }
if (typeof server.closeAllConnections === 'function') server.closeAllConnections();
for (const s of sockets) s.destroy();
await new Promise((r) => wss.close(() => r()));
await stopped;
})();
return closePromise;
}
return { port, host: bound, addresses: [bound], close, rooms: manager.rooms, options: o };
}
// ---------------------------------------------------------------- run directly
function envInt(name, def) {
const v = process.env[name];
if (v === undefined || v === '') return def;
const n = Number(v);
if (!Number.isInteger(n) || n < 0) throw new Error(name + ' must be a non-negative integer (got ' + JSON.stringify(v) + ')');
return n;
}
async function main() {
const opts = {
port: envInt('PORT', 8080),
host: process.env.HOST || '::',
trustProxy: process.env.TRUST_PROXY || 'auto',
trustedProxies: process.env.TRUSTED_PROXIES || '',
allowedOrigins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean),
};
if (process.env.MAX_CONN_PER_IP) opts.maxConnPerIp = envInt('MAX_CONN_PER_IP', 40);
if (process.env.GRACE_MS) opts.graceMs = envInt('GRACE_MS', 60000);
const srv = await createServer(opts);
const shownProxy = parseTrustProxy(opts.trustProxy);
console.log('Netwall is listening on ' + (srv.host.includes(':') ? '[' + srv.host + ']' : srv.host) + ':' + srv.port +
(srv.host === '::' ? ' (dual stack: IPv4 + IPv6)' : srv.host === '0.0.0.0' ? ' (IPv4 only)' : ''));
console.log(' trust proxy: ' + shownProxy + (srv.options.trustedProxies && shownProxy === 'auto'
? ' + ' + srv.options.trustedProxies.list.join(', ') : '') +
', extra allowed origins: ' + (opts.allowedOrigins.join(', ') || '(none)'));
console.log('Open:');
for (const u of listUrls(srv.host, srv.port)) console.log(' ' + u);
let stopping = false;
const stop = (sig) => {
if (stopping) { console.log('second ' + sig + ', exiting now'); process.exit(0); }
stopping = true;
console.log('received ' + sig + ', shutting down');
const force = setTimeout(() => { console.log('shutdown timed out, exiting'); process.exit(0); }, 5000);
force.unref();
srv.close().then(() => process.exit(0), (err) => { console.error(err); process.exit(0); });
};
process.on('SIGINT', () => stop('SIGINT'));
process.on('SIGTERM', () => stop('SIGTERM'));
}
module.exports = { createServer, cleanName };
if (require.main === module) {
main().catch((err) => {
console.error('Netwall failed to start: ' + (err && err.message || err));
process.exit(1);
});
}