Upstream/server/push.js
jvanvik b18645dca1 Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push
(docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels.
Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js,
rankings DoS, static headers, ...): fixes follow in the next commit.
NOT done: bots/balance, e2e suite, real-device checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 19:05:03 +02:00

201 lines
9.9 KiB
JavaScript

'use strict';
/*
* WebSocket push (stage 6): transport and connection registry only, no game knowledge (that lives in pushHooks.js).
* Push is a HINT: small JSON messages saying "something changed, refetch over REST". See docs/PROTOCOL.md.
*
* const push = createPush({ clock, authenticate, tokenValid, townOwner, opts, log });
* httpServer.on('upgrade', push.onUpgrade);
* push.toUser(userId, { type: 'town', townId: 7 }); // all sockets of that user
* push.toTown(7, { type: 'town', townId: 7 }); // the user who owns POP 7 right now
* await push.close(); // 1001 to everybody, resolves when the sockets are gone
*
* Deps: authenticate(header, now) -> { user, tokenId } | null (auth.authenticate), tokenValid(tokenId) -> bool (re-checked on
* every ping tick: revoked token or banned user), townOwner(townId) -> userId | null, opts (the createServer options:
* trustProxy, trustedProxies, allowedOrigins, maxConnPerIp, optional wsAuthTimeoutMs / wsPingMs / wsRate / wsBurst / wsBadBudget).
*/
const { WebSocketServer } = require('ws');
const { originAllowed, clientIp, TokenBucket } = require('./net');
const CLOSE = { SHUTDOWN: 1001, BAD_MESSAGES: 4400, UNAUTHORIZED: 4401, AUTH_TIMEOUT: 4408, RATE_LIMITED: 4429 };
const MAX_PAYLOAD = 1024; // bytes per client message
const MAX_BUFFERED = 1024 * 1024; // a client that does not read 1 MB of hints is dead weight
function createPush(deps) {
const { clock, authenticate, tokenValid, townOwner, opts } = deps;
const log = deps.log || (() => {});
const cfg = {
authTimeoutMs: opts.wsAuthTimeoutMs || 10000, pingMs: opts.wsPingMs || 30000,
rate: opts.wsRate || 5, burst: opts.wsBurst || 15, badBudget: opts.wsBadBudget || 5,
maxConnPerIp: opts.maxConnPerIp === undefined ? 40 : opts.maxConnPerIp, closeGraceMs: 1000,
};
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false, clientTracking: false });
const conns = new Set();
const byUser = new Map(); // userId -> Set<conn> (authenticated sockets)
const perIp = new Map(); // ip -> open sockets (also not yet authenticated ones)
let closing = false;
// ------------------------------------------------------------ upgrade
function refuse(socket, status, text, why) {
log('refused ws ' + why);
try { socket.write('HTTP/1.1 ' + status + ' ' + text + '\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); } catch (e) { /* gone */ }
socket.destroy();
}
function onUpgrade(req, socket, head) {
socket.on('error', () => {}); // a reset during the handshake must not crash the process
let pathname = '';
try { pathname = new URL(req.url || '/', 'http://x').pathname; } catch (e) { /* stays '' */ }
const ip = clientIp(req, opts.trustProxy, opts.trustedProxies);
if (pathname !== '/ws') return refuse(socket, 404, 'Not Found', 'path=' + JSON.stringify(pathname.slice(0, 60)) + ' ip=' + ip);
if (closing) return refuse(socket, 503, 'Service Unavailable', 'shutting down ip=' + ip);
if (!originAllowed(req, opts)) return refuse(socket, 403, 'Forbidden', 'origin=' + JSON.stringify(String(req.headers.origin).slice(0, 100)) + ' ip=' + ip);
if (cfg.maxConnPerIp > 0 && (perIp.get(ip) || 0) >= cfg.maxConnPerIp) return refuse(socket, 429, 'Too Many Requests', 'conn_cap ip=' + ip + ' max=' + cfg.maxConnPerIp);
// handleUpgrade calls back synchronously on success and not at all when the handshake is malformed, so the per-IP
// count is taken in the callback: nothing can leak it.
wss.handleUpgrade(req, socket, head, (ws) => accept(ws, ip));
}
// ------------------------------------------------------------ connections
function accept(ws, ip) {
perIp.set(ip, (perIp.get(ip) || 0) + 1);
const c = {
ws, ip, userId: null, tokenId: null, alive: true, bad: 0, bucket: new TokenBucket(cfg.rate, cfg.burst),
out: new Map(), flushing: false, authTimer: null, killTimer: null, gone: false,
};
conns.add(c);
if (ws._socket && ws._socket.setNoDelay) ws._socket.setNoDelay(true);
c.authTimer = setTimeout(() => { log('ws closed auth_timeout ip=' + ip); closeConn(c, CLOSE.AUTH_TIMEOUT, 'auth_timeout'); }, cfg.authTimeoutMs);
ws.on('message', (data, isBinary) => onMessage(c, data, isBinary));
ws.on('pong', () => { c.alive = true; });
ws.on('error', (err) => { log('ws error ip=' + ip + ': ' + (err && err.message)); }); // 'close' follows
ws.on('close', () => drop(c));
}
function drop(c) {
if (c.gone) return;
c.gone = true;
clearTimeout(c.authTimer); clearTimeout(c.killTimer);
conns.delete(c);
const n = (perIp.get(c.ip) || 1) - 1;
if (n > 0) perIp.set(c.ip, n); else perIp.delete(c.ip);
if (c.userId !== null) {
const set = byUser.get(c.userId);
if (set) { set.delete(c); if (!set.size) byUser.delete(c.userId); }
}
}
function closeConn(c, code, reason) {
if (c.gone || c.closing) return;
c.closing = true;
try { c.ws.close(code, reason); } catch (e) { try { c.ws.terminate(); } catch (e2) { /* gone */ } }
c.killTimer = setTimeout(() => { try { c.ws.terminate(); } catch (e) { /* gone */ } }, cfg.closeGraceMs);
if (c.killTimer.unref) c.killTimer.unref();
}
function sendNow(c, obj) {
if (c.gone || c.closing || c.ws.readyState !== 1) return false;
if (c.ws.bufferedAmount > MAX_BUFFERED) { log('ws terminated: client not reading ip=' + c.ip); c.ws.terminate(); return false; }
c.ws.send(JSON.stringify(obj));
return true;
}
// Hints are coalesced: identical messages produced in the same tick (many events of one catch-up) go out once.
function queue(c, msg) {
if (c.userId === null || c.gone || c.closing) return;
c.out.set(JSON.stringify(msg), true);
if (!c.flushing) { c.flushing = true; setImmediate(() => flush(c)); }
}
function flush(c) {
c.flushing = false;
const items = c.out; c.out = new Map();
if (c.gone || c.closing || c.ws.readyState !== 1) return;
for (const text of items.keys()) {
if (c.ws.bufferedAmount > MAX_BUFFERED) { log('ws terminated: client not reading ip=' + c.ip); c.ws.terminate(); return; }
c.ws.send(text);
}
}
function bad(c, why) {
c.bad++;
log('ws bad message (' + why + ') ip=' + c.ip + ' user=' + c.userId + ' ' + c.bad + '/' + cfg.badBudget);
if (c.bad >= cfg.badBudget) closeConn(c, CLOSE.BAD_MESSAGES, 'too_many_bad_messages');
}
function onMessage(c, data, isBinary) {
if (c.gone || c.closing) return;
c.alive = true;
if (!c.bucket.take()) { log('refused ws rate_limited ip=' + c.ip + ' user=' + c.userId); return closeConn(c, CLOSE.RATE_LIMITED, 'rate_limited'); }
let m = null;
if (!isBinary) { try { m = JSON.parse(data.toString('utf8')); } catch (e) { m = null; } }
const ok = m && typeof m === 'object' && !Array.isArray(m) && typeof m.type === 'string';
if (c.userId === null) { // the FIRST message must authenticate; anything else is fatal
if (!ok || m.type !== 'auth') { log('refused ws unauthorized (first message is not auth) ip=' + c.ip); return closeConn(c, CLOSE.UNAUTHORIZED, 'auth_required'); }
const a = typeof m.token === 'string' && m.token.length <= 200 ? authenticate('Bearer ' + m.token, clock.now()) : null;
if (!a) { log('refused ws unauthorized (bad token) ip=' + c.ip); return closeConn(c, CLOSE.UNAUTHORIZED, 'invalid_token'); }
clearTimeout(c.authTimer); c.authTimer = null;
c.userId = a.user.id; c.tokenId = a.tokenId;
let set = byUser.get(c.userId);
if (!set) { set = new Set(); byUser.set(c.userId, set); }
set.add(c);
sendNow(c, { type: 'ready', serverTime: clock.now() });
return;
}
if (!ok) return bad(c, isBinary ? 'binary' : 'not a JSON object with a type');
if (m.type === 'ping') { sendNow(c, { type: 'pong', serverTime: clock.now() }); return; }
return bad(c, 'unknown type ' + JSON.stringify(m.type.slice(0, 20)));
}
// ------------------------------------------------------------ keepalive + revocation
function tick() {
for (const c of conns) {
if (c.gone || c.closing) continue;
if (!c.alive) { log('ws dead, terminating ip=' + c.ip + ' user=' + c.userId); try { c.ws.terminate(); } catch (e) { /* gone */ } continue; }
if (c.tokenId !== null) {
let valid = true;
try { valid = tokenValid(c.tokenId); } catch (e) { log('ws token check failed: ' + e.message); }
if (!valid) { log('ws closed token_revoked user=' + c.userId); closeConn(c, CLOSE.UNAUTHORIZED, 'token_revoked'); continue; }
}
c.alive = false;
try { c.ws.ping(); } catch (e) { /* closing */ }
}
}
const timer = setInterval(tick, cfg.pingMs);
if (timer.unref) timer.unref();
// ------------------------------------------------------------ public API
function toUser(userId, msg) {
const set = byUser.get(userId);
if (set) for (const c of set) queue(c, msg);
}
function toTown(townId, msg) {
if (!byUser.size) return; // nobody connected: no lookup
const owner = townOwner(townId);
if (owner) toUser(owner, msg);
}
function close() {
if (closing) return closing_;
closing = true;
clearInterval(timer);
closing_ = new Promise((resolve) => {
for (const c of conns) { if (c.flushing) flush(c); closeConn(c, CLOSE.SHUTDOWN, 'shutdown'); }
const done = () => { wss.close(); resolve(); };
if (!conns.size) return done();
const wait = setInterval(() => { if (!conns.size) { clearInterval(wait); done(); } }, 10);
setTimeout(() => { for (const c of conns) { try { c.ws.terminate(); } catch (e) { /* gone */ } } }, cfg.closeGraceMs + 50).unref();
});
return closing_;
}
let closing_ = null;
return {
onUpgrade, toUser, toTown, close,
stats: () => ({ connections: conns.size, users: byUser.size, ips: perIp.size }),
CLOSE,
};
}
module.exports = { createPush, CLOSE, MAX_PAYLOAD };