Add co-op server, deploy docs, e2e suite and wire in the music tracks
- server/: Node (ws) static server + authoritative co-op rooms; dual-stack listen, proxy-aware client IP and Origin check, keep-alive pings, per-socket rate limits, graceful shutdown; 59 node:test tests - docs/DEPLOY.md + deploy/netwall.service: Debian 13 LXC, systemd, nginx Proxy Manager walk-through, path prefix, troubleshooting - e2e/: Playwright suite (smoke, touch, end flow, two-browser co-op incl. reconnect, 14-size layout matrix); npm run e2e - Music: tracks.json now points at the uploaded theme/battle/boss/win/lose files; stingers fade out when a new game starts - PAUSED indicator, refreshed icon Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
parent
1c2071e6db
commit
faf0cfa603
27 changed files with 3383 additions and 28 deletions
315
server/index.js
Normal file
315
server/index.js
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
'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 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, 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', 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.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) + ': Origin ' + JSON.stringify(req.headers.origin) +
|
||||
' does not match Host ' + JSON.stringify(req.headers.host) + ' (see ALLOWED_ORIGINS)');
|
||||
return refuse(socket, 403, 'Forbidden');
|
||||
}
|
||||
const ip = clientIp(req, o.trustProxy);
|
||||
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',
|
||||
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 + ', 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);
|
||||
});
|
||||
}
|
||||
225
server/net.js
Normal file
225
server/net.js
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Networking helpers: client IP / reverse-proxy awareness, Origin check, token bucket,
|
||||
* dual-stack listen and the "what URLs can I open" list for the start-up banner.
|
||||
* No dependencies beyond Node core.
|
||||
*/
|
||||
const net = require('net');
|
||||
const os = require('os');
|
||||
const { performance } = require('perf_hooks');
|
||||
|
||||
// ---------------------------------------------------------------- addresses
|
||||
// "::ffff:1.2.3.4" -> "1.2.3.4"; strips an IPv6 zone ("fe80::1%eth0"); lower-cases.
|
||||
function normalizeIp(addr) {
|
||||
if (typeof addr !== 'string') return '';
|
||||
let a = addr.trim().toLowerCase();
|
||||
const z = a.indexOf('%');
|
||||
if (z >= 0) a = a.slice(0, z);
|
||||
if (a.startsWith('::ffff:') && net.isIPv4(a.slice(7))) a = a.slice(7);
|
||||
return a;
|
||||
}
|
||||
|
||||
// Loopback, RFC1918, link-local, unique-local (fc00::/7) and the unspecified address.
|
||||
function isPrivateIp(addr) {
|
||||
const ip = normalizeIp(addr);
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number);
|
||||
return a === 127 || a === 10 || a === 0 ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 169 && b === 254);
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
if (ip === '::1' || ip === '::') return true;
|
||||
const first = ip.startsWith('::') ? 0 : parseInt(ip.split(':')[0], 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 'auto' | true | false, also from env-style strings ('1', '0', 'true', 'off' ...).
|
||||
function parseTrustProxy(v) {
|
||||
if (v === undefined || v === null || v === '') return 'auto';
|
||||
if (v === true || v === false) return v;
|
||||
if (typeof v === 'number') return v !== 0;
|
||||
const s = String(v).trim().toLowerCase();
|
||||
if (s === 'auto') return 'auto';
|
||||
if (['1', 'true', 'yes', 'on'].includes(s)) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(s)) return false;
|
||||
throw new Error('invalid trustProxy value: ' + JSON.stringify(v) + " (use 'auto', '1' or '0')");
|
||||
}
|
||||
|
||||
function peerIp(req) {
|
||||
return normalizeIp(req.socket && req.socket.remoteAddress) || 'unknown';
|
||||
}
|
||||
|
||||
// Does this request come from a proxy whose X-Forwarded-* headers we believe?
|
||||
function isTrustedPeer(req, trustProxy) {
|
||||
if (trustProxy === true) return true;
|
||||
if (trustProxy === false) return false;
|
||||
return isPrivateIp(peerIp(req));
|
||||
}
|
||||
|
||||
// One entry of a forwarding header ("203.0.113.9", "[2001:db8::5]:443", "1.2.3.4:5555") -> bare IP or null.
|
||||
function parseForwardedEntry(raw) {
|
||||
let a = String(raw).trim();
|
||||
if (!a) return null;
|
||||
if (a[0] === '[') { const e = a.indexOf(']'); if (e < 0) return null; a = a.slice(1, e); }
|
||||
else if (/^\d+\.\d+\.\d+\.\d+:\d+$/.test(a)) a = a.slice(0, a.lastIndexOf(':'));
|
||||
a = normalizeIp(a);
|
||||
return net.isIP(a) ? a : null;
|
||||
}
|
||||
|
||||
// First address of a header value like "203.0.113.9, 10.0.0.2" (used for X-Real-IP, which holds one address).
|
||||
function firstForwardedIp(value) {
|
||||
return typeof value === 'string' ? parseForwardedEntry(value.split(',')[0]) : null;
|
||||
}
|
||||
|
||||
// The client address in an X-Forwarded-For built by proxies that APPEND (nginx $proxy_add_x_forwarded_for, which is
|
||||
// what nginx Proxy Manager does): everything left of the proxy's own entry is whatever the client chose to send, so
|
||||
// the first entry is forgeable (it lets a client dodge the per-IP cap or use up somebody else's). Walk from the
|
||||
// right instead, skip the private addresses of our own proxy hops and take the first public one. A chain that is
|
||||
// private all the way (LAN clients) yields its rightmost entry, i.e. what the nearest proxy saw; junk -> null.
|
||||
function forwardedClientIp(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const parts = value.split(',');
|
||||
let nearest = null;
|
||||
for (let i = parts.length - 1; i >= 0; i--) {
|
||||
const ip = parseForwardedEntry(parts[i]);
|
||||
if (!ip) return nearest;
|
||||
if (!isPrivateIp(ip)) return ip;
|
||||
if (!nearest) nearest = ip;
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
// The address used for logging and the per-IP socket cap.
|
||||
function clientIp(req, trustProxy) {
|
||||
const peer = peerIp(req);
|
||||
if (!isTrustedPeer(req, trustProxy)) return peer;
|
||||
return forwardedClientIp(req.headers['x-forwarded-for']) ||
|
||||
firstForwardedIp(req.headers['x-real-ip']) || peer;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Origin check
|
||||
// Scheme-less, lower-case "host[:port]" with the default ports 80 / 443 dropped.
|
||||
// Accepts a bare host ("Game.Example.com:443"), a Host header, or a full origin ("https://x.example").
|
||||
function normalizeHost(s) {
|
||||
if (typeof s !== 'string') return null;
|
||||
let v = s.trim();
|
||||
if (!v) return null;
|
||||
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) {
|
||||
if (!/^[a-z0-9._:\[\]-]+$/i.test(v)) return null; // a bare host[:port], nothing else
|
||||
v = 'http://' + v;
|
||||
}
|
||||
let u;
|
||||
try { u = new URL(v); } catch (e) { return null; }
|
||||
if (!u.hostname) return null;
|
||||
const port = u.port; // '' for the scheme's own default
|
||||
const h = u.hostname.toLowerCase(); // IPv6 keeps its brackets
|
||||
return port && port !== '80' && port !== '443' ? h + ':' + port : h;
|
||||
}
|
||||
|
||||
// Returns true when a WebSocket upgrade with this Origin may proceed.
|
||||
// no Origin header -> true (non-browser clients)
|
||||
// Origin host == Host -> true
|
||||
// Origin host == X-Forwarded-Host (first) -> true, only when the peer is a trusted proxy
|
||||
// Origin host in allowedOrigins -> true
|
||||
function originAllowed(req, opts) {
|
||||
const origin = req.headers.origin;
|
||||
if (origin === undefined) return true;
|
||||
const o = (typeof origin === 'string' && origin.toLowerCase() !== 'null' && /^[a-z][a-z0-9+.-]*:\/\//i.test(origin))
|
||||
? normalizeHost(origin) : null;
|
||||
if (!o) return false;
|
||||
if (o === normalizeHost(req.headers.host)) return true;
|
||||
if (isTrustedPeer(req, opts.trustProxy)) {
|
||||
const xfh = req.headers['x-forwarded-host'];
|
||||
if (typeof xfh === 'string' && o === normalizeHost(xfh.split(',')[0])) return true;
|
||||
}
|
||||
for (const a of opts.allowedOrigins || []) if (o === normalizeHost(a)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- token bucket
|
||||
class TokenBucket {
|
||||
constructor(ratePerSec, burst) {
|
||||
this.rate = ratePerSec; this.burst = burst;
|
||||
this.tokens = burst; this.last = performance.now();
|
||||
}
|
||||
// true when the event is allowed. `now` (ms) defaults to a monotonic clock: with Date.now() a wall-clock step
|
||||
// backwards (NTP, a VM resume) would stop the refill for as long as the step is large and get sockets closed 4429.
|
||||
take(now) {
|
||||
now = now === undefined ? performance.now() : now;
|
||||
const dt = now - this.last;
|
||||
if (dt > 0) { this.tokens = Math.min(this.burst, this.tokens + dt * this.rate / 1000); this.last = now; }
|
||||
if (this.tokens < 1) return false;
|
||||
this.tokens -= 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- listen
|
||||
const V6_FALLBACK_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EPROTONOSUPPORT', 'ENOTSUP', 'EINVAL', 'ENOPROTOOPT', 'EPFNOSUPPORT']);
|
||||
|
||||
function listenOnce(server, opts) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (err) => { server.removeListener('listening', onListening); reject(err); };
|
||||
const onListening = () => { server.removeListener('error', onError); resolve(); };
|
||||
server.once('error', onError);
|
||||
server.once('listening', onListening);
|
||||
try { server.listen(opts); } catch (err) { onError(err); }
|
||||
});
|
||||
}
|
||||
|
||||
// Binds `host`. The default '::' is bound dual-stack (ipv6Only:false: one socket for IPv4 and IPv6);
|
||||
// if IPv6 is unavailable (EAFNOSUPPORT, EADDRNOTAVAIL, ...) it falls back to 0.0.0.0. Any other host is
|
||||
// used as given, and any other failure (EADDRINUSE, EACCES) is rejected, never papered over.
|
||||
// Resolves to the host that ended up bound.
|
||||
async function listenDual(server, port, host, log) {
|
||||
if (host !== '::') { await listenOnce(server, { port, host }); return host; }
|
||||
try {
|
||||
await listenOnce(server, { port, host: '::', ipv6Only: false });
|
||||
return '::';
|
||||
} catch (err) {
|
||||
if (!err || !V6_FALLBACK_CODES.has(err.code)) throw err;
|
||||
if (log) log('IPv6 is not available (' + err.code + '); falling back to 0.0.0.0 (IPv4 only)');
|
||||
await listenOnce(server, { port, host: '0.0.0.0' });
|
||||
return '0.0.0.0';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- start-up banner
|
||||
function fmtUrl(host, port) {
|
||||
return 'http://' + (host.includes(':') ? '[' + host + ']' : host) + ':' + port + '/';
|
||||
}
|
||||
|
||||
// os.networkInterfaces() throws in some sandboxes (seccomp / RestrictAddressFamilies without AF_NETLINK, certain
|
||||
// containers). The banner is cosmetic, so that must never stop a server that is already listening.
|
||||
function interfaces() {
|
||||
try { return os.networkInterfaces(); } catch (e) { return {}; }
|
||||
}
|
||||
|
||||
// URLs worth printing for a server bound to `bound` on `port`.
|
||||
function listUrls(bound, port, ifaces) {
|
||||
const out = ['http://localhost:' + port + '/'];
|
||||
if (bound !== '::' && bound !== '0.0.0.0') {
|
||||
if (bound !== '127.0.0.1' && bound !== '::1') out.push(fmtUrl(bound, port));
|
||||
return out;
|
||||
}
|
||||
ifaces = ifaces || interfaces();
|
||||
for (const name of Object.keys(ifaces)) {
|
||||
for (const a of ifaces[name] || []) {
|
||||
if (a.internal) continue;
|
||||
const v4 = a.family === 'IPv4' || a.family === 4;
|
||||
if (v4) out.push(fmtUrl(a.address, port));
|
||||
else if (bound === '::' && !/^fe80:/i.test(a.address)) out.push(fmtUrl(a.address.split('%')[0], port));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeIp, isPrivateIp, parseTrustProxy, peerIp, isTrustedPeer, firstForwardedIp, forwardedClientIp, clientIp,
|
||||
normalizeHost, originAllowed, TokenBucket, listenDual, listUrls, fmtUrl,
|
||||
};
|
||||
411
server/room.js
Normal file
411
server/room.js
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Rooms: one authoritative Sim per room, two player slots, fixed-step tick loop and snapshot broadcast.
|
||||
* A "conn" is the per-socket context object created in index.js ({ ws, player, room, dead, ... }); this file
|
||||
* only touches conn.ws, conn.player and conn.room and never throws on a dead socket.
|
||||
*/
|
||||
const crypto = require('crypto');
|
||||
const TD = require('../public/js/sim.js'); // fixed path on purpose: independent of publicDir
|
||||
|
||||
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'wave', 'auto', 'continue']);
|
||||
const OPEN = 1; // WebSocket.OPEN
|
||||
const LOOP_MS = 8; // global tick loop period
|
||||
const MAX_CATCHUP_S = 0.25; // clamp one loop iteration (stalled event loop)
|
||||
const STEP_BUDGET_NS = 20000000n; // never spend more than 20 ms stepping one room per iteration
|
||||
const MARK_GAP_MS = 400;
|
||||
const MAX_BUFFERED = 512 * 1024; // a socket this far behind is dropped; it reconnects and resumes
|
||||
const MAX_MONSTER_LOAD = 1500; // monsters + queued spawns; refuse 'wave' beyond this (CPU/bandwidth guard)
|
||||
|
||||
const ALIAS_KEY = crypto.randomBytes(32); // per process; see Room.alias()
|
||||
const nowMs = () => Number(process.hrtime.bigint() / 1000000n);
|
||||
|
||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||
const round2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
function sendRaw(conn, str) {
|
||||
const ws = conn && conn.ws;
|
||||
if (!ws || ws.readyState !== OPEN) return false;
|
||||
try { ws.send(str); return true; } catch (e) { return false; }
|
||||
}
|
||||
|
||||
class Room {
|
||||
constructor(manager, code, mapId) {
|
||||
this.manager = manager;
|
||||
this.code = code;
|
||||
this.sim = new TD.Sim({ map: mapId });
|
||||
this.speed = 1;
|
||||
this.paused = false;
|
||||
this.seq = 0;
|
||||
this.players = [null, null]; // slot -> player
|
||||
this.acc = 0; // accumulated game seconds not yet stepped
|
||||
this.lastNs = null; // hrtime of the previous loop iteration
|
||||
this.nextSnapNs = 0n;
|
||||
this.lastSentRev = this.sim.rev; // 'tw' is attached only when rev moves past this
|
||||
this.destroyed = false;
|
||||
this.createdAt = Date.now();
|
||||
this.emptySince = null; // nowMs() when the last online player went away; null while somebody is online
|
||||
}
|
||||
|
||||
log(msg) { this.manager.log('[' + this.code + '] ' + msg); }
|
||||
|
||||
// ---------------------------------------------------------------- players
|
||||
onlinePlayers() { return this.players.filter((p) => p && p.conn); }
|
||||
anyPlayers() { return this.players.some(Boolean); }
|
||||
|
||||
// A pid is the reconnect secret (whoever presents it takes over the slot), so it only ever goes to its owner.
|
||||
// The other player appears under a stable alias: unguessable, different per room, useless as a pid.
|
||||
alias(pid) {
|
||||
return crypto.createHmac('sha256', ALIAS_KEY).update(this.code + ':' + pid).digest('base64url').slice(0, 22);
|
||||
}
|
||||
|
||||
// The player list as `viewer` may see it: their own entry carries their pid, everyone else's an alias.
|
||||
publicPlayers(viewer) {
|
||||
const out = [];
|
||||
for (const p of this.players) {
|
||||
if (p) out.push({ pid: p === viewer ? p.pid : p.alias, slot: p.slot, name: p.name, host: p.host, online: !!p.conn });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
send(player, obj) { return !!player && sendRaw(player.conn, JSON.stringify(obj)); }
|
||||
|
||||
// Same string to everyone online (optionally except one conn).
|
||||
broadcast(obj, exceptConn) {
|
||||
const str = JSON.stringify(obj);
|
||||
for (const p of this.players) if (p && p.conn && p.conn !== exceptConn) sendRaw(p.conn, str);
|
||||
}
|
||||
|
||||
// One message per recipient (each sees their own pid), to everyone online except `exceptConn`.
|
||||
broadcastPlayers(exceptConn) {
|
||||
for (const p of this.players) {
|
||||
if (p && p.conn && p.conn !== exceptConn) this.send(p, { t: 'players', players: this.publicPlayers(p) });
|
||||
}
|
||||
}
|
||||
|
||||
stateMsg(extra) {
|
||||
return Object.assign({ t: 'state', state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused }, extra);
|
||||
}
|
||||
|
||||
joinedMsg(player, resumed) {
|
||||
return {
|
||||
t: 'joined', room: this.code, resumed,
|
||||
you: { pid: player.pid, slot: player.slot, host: player.host },
|
||||
players: this.publicPlayers(player),
|
||||
state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused,
|
||||
};
|
||||
}
|
||||
|
||||
// Binds `conn` to a slot. Returns { player, resumed } or null when both slots belong to other pids.
|
||||
join(pid, name, conn) {
|
||||
let p = this.players.find((x) => x && x.pid === pid);
|
||||
let resumed = false;
|
||||
if (p) {
|
||||
resumed = true;
|
||||
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
|
||||
const old = p.conn;
|
||||
p.conn = conn;
|
||||
p.name = name;
|
||||
if (old && old !== conn) { // a second tab / a reconnect racing the dead socket
|
||||
old.player = null; old.room = null; old.dead = true;
|
||||
try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ }
|
||||
}
|
||||
} else {
|
||||
const slot = this.players.indexOf(null);
|
||||
if (slot < 0) return null;
|
||||
p = {
|
||||
pid, alias: this.alias(pid), slot, name, host: !this.players.some((x) => x && x.host),
|
||||
conn, cursor: null, lastMarkAt: -Infinity, graceTimer: null,
|
||||
};
|
||||
this.players[slot] = p;
|
||||
}
|
||||
p.cursor = null;
|
||||
this.touchPresence();
|
||||
return { player: p, resumed };
|
||||
}
|
||||
|
||||
// Keeps `emptySince` in step with who is online (the manager evicts the longest-abandoned room first).
|
||||
touchPresence() {
|
||||
if (this.onlinePlayers().length) this.emptySince = null;
|
||||
else if (this.emptySince === null) this.emptySince = nowMs();
|
||||
}
|
||||
|
||||
// The socket of `conn` closed (not a deliberate leave): keep the slot for graceMs.
|
||||
disconnect(conn) {
|
||||
const p = conn.player;
|
||||
if (this.destroyed || !p || p.conn !== conn) return;
|
||||
p.conn = null;
|
||||
p.cursor = null;
|
||||
this.touchPresence();
|
||||
this.log(p.name + ' (slot ' + p.slot + ') disconnected; holding the slot for ' + this.manager.graceMs + ' ms');
|
||||
p.graceTimer = setTimeout(() => { p.graceTimer = null; this.removePlayer(p, 'grace expired'); }, this.manager.graceMs);
|
||||
this.broadcastPlayers();
|
||||
}
|
||||
|
||||
// Frees the slot for good, migrates the host, deletes the room when nobody is left.
|
||||
removePlayer(p, why) {
|
||||
if (this.destroyed || this.players[p.slot] !== p) return;
|
||||
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
|
||||
this.players[p.slot] = null;
|
||||
p.conn = null;
|
||||
p.cursor = null;
|
||||
this.log(p.name + ' (slot ' + p.slot + ') removed: ' + why);
|
||||
if (!this.anyPlayers()) { this.manager.deleteRoom(this, 'empty'); return; }
|
||||
if (p.host) {
|
||||
const next = this.players.find(Boolean);
|
||||
next.host = true;
|
||||
this.log('host is now ' + next.name + ' (slot ' + next.slot + ')');
|
||||
}
|
||||
this.touchPresence();
|
||||
this.broadcastPlayers();
|
||||
}
|
||||
|
||||
leave(conn) {
|
||||
const p = conn.player;
|
||||
if (!p || p.conn !== conn) return;
|
||||
conn.player = null; conn.room = null;
|
||||
this.removePlayer(p, 'left');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- messages after join
|
||||
// Returns false when the message is malformed (the caller counts those).
|
||||
handleMessage(p, msg) {
|
||||
switch (msg.t) {
|
||||
case 'cmd': return this.handleCmd(p, msg);
|
||||
case 'ctl': return this.handleCtl(msg);
|
||||
case 'cursor': return this.handleCursor(p, msg);
|
||||
case 'mark': return this.handleMark(p, msg);
|
||||
case 'rtt':
|
||||
if (!finite(msg.ts) && !(typeof msg.ts === 'string' && msg.ts.length <= 32)) return false;
|
||||
this.send(p, { t: 'rtt', ts: msg.ts });
|
||||
return true;
|
||||
case 'sync': this.send(p, this.stateMsg()); return true;
|
||||
case 'newgame': return this.handleNewgame(p, msg);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
reject(p, c, reason, msg) {
|
||||
const out = { t: 'reject', c, reason };
|
||||
if (msg) {
|
||||
if (finite(msg.x)) out.x = msg.x;
|
||||
if (finite(msg.y)) out.y = msg.y;
|
||||
if (finite(msg.id)) out.id = msg.id;
|
||||
}
|
||||
this.send(p, out);
|
||||
}
|
||||
|
||||
handleCmd(p, msg) {
|
||||
const c = msg.c;
|
||||
if (typeof c !== 'string' || !CMDS.has(c)) return false;
|
||||
const sim = this.sim;
|
||||
if (c === 'wave' && sim.monsters.length + sim.spawnQ.length > MAX_MONSTER_LOAD) {
|
||||
this.reject(p, c, 'busy', msg);
|
||||
return true;
|
||||
}
|
||||
// Whitelisted fields only; `by` always comes from the socket's slot, never from the client.
|
||||
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, by: p.slot };
|
||||
let r;
|
||||
try { r = sim.cmd(cmd); } catch (e) { this.log('sim.cmd threw: ' + (e && e.stack || e)); r = { ok: false, reason: 'error' }; }
|
||||
if (!r || !r.ok) this.reject(p, c, (r && r.reason) || 'error', msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
handleCtl(msg) {
|
||||
if (msg.c === 'pause' && typeof msg.v === 'boolean') { this.paused = msg.v; return true; }
|
||||
if (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3)) { this.speed = msg.v; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
boardPoint(msg) {
|
||||
const b = this.sim.board;
|
||||
return [round2(clamp(msg.x, 0, b.cols)), round2(clamp(msg.y, 0, b.rows))];
|
||||
}
|
||||
|
||||
handleCursor(p, msg) {
|
||||
if (msg.x === null) { p.cursor = null; return true; }
|
||||
if (!finite(msg.x) || !finite(msg.y)) return false;
|
||||
p.cursor = this.boardPoint(msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
handleMark(p, msg) {
|
||||
if (!finite(msg.x) || !finite(msg.y)) return false;
|
||||
const now = nowMs(); // monotonic: immune to wall-clock steps
|
||||
if (now - p.lastMarkAt < MARK_GAP_MS) return true; // rate limited: dropped silently
|
||||
p.lastMarkAt = now;
|
||||
const pt = this.boardPoint(msg);
|
||||
this.broadcast({ t: 'mark', slot: p.slot, x: pt[0], y: pt[1] });
|
||||
return true;
|
||||
}
|
||||
|
||||
handleNewgame(p, msg) {
|
||||
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
|
||||
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
|
||||
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
|
||||
this.sim = new TD.Sim({ map });
|
||||
this.speed = 1; this.paused = false; this.acc = 0;
|
||||
this.lastSentRev = this.sim.rev; // the 'state' below carries the tower list
|
||||
this.log('new game on map ' + map + ' started by ' + p.name);
|
||||
this.broadcast(this.stateMsg({ newgame: true }));
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loop
|
||||
// Called every LOOP_MS by the manager with process.hrtime.bigint().
|
||||
step(now) {
|
||||
const last = this.lastNs;
|
||||
this.lastNs = now;
|
||||
const online = this.onlinePlayers().length > 0;
|
||||
const sim = this.sim;
|
||||
|
||||
if (!online || this.paused || sim.state !== 'playing' || last === null) {
|
||||
this.acc = 0; // no catch-up after a pause / an empty room
|
||||
} else {
|
||||
let dt = Number(now - last) / 1e9;
|
||||
if (dt > MAX_CATCHUP_S) dt = MAX_CATCHUP_S;
|
||||
this.acc += dt * this.speed;
|
||||
let n = 0;
|
||||
const t0 = process.hrtime.bigint();
|
||||
while (this.acc >= TD.STEP) {
|
||||
sim.tick(TD.STEP);
|
||||
this.acc -= TD.STEP;
|
||||
if ((++n & 7) === 0 && process.hrtime.bigint() - t0 > STEP_BUDGET_NS) { // overloaded: run slower, do not freeze the server
|
||||
this.acc = Math.min(this.acc, TD.STEP);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!online) { this.nextSnapNs = now; return; }
|
||||
if (now >= this.nextSnapNs) {
|
||||
this.broadcastSnap();
|
||||
this.nextSnapNs += this.manager.snapPeriodNs;
|
||||
if (this.nextSnapNs <= now) this.nextSnapNs = now + this.manager.snapPeriodNs;
|
||||
}
|
||||
}
|
||||
|
||||
// Serialised once, the same string goes to every online player.
|
||||
broadcastSnap() {
|
||||
const sim = this.sim;
|
||||
const cur = [];
|
||||
for (const p of this.players) if (p && p.conn && p.cursor) cur.push([p.slot, p.cursor[0], p.cursor[1]]);
|
||||
const msg = Object.assign({ t: 'snap', seq: ++this.seq }, sim.snapshot(), {
|
||||
ev: sim.drainEvents(), cur, pa: this.paused ? 1 : 0, sp: this.speed,
|
||||
});
|
||||
if (sim.rev !== this.lastSentRev) { msg.tw = sim.towerList(); this.lastSentRev = sim.rev; }
|
||||
const str = JSON.stringify(msg);
|
||||
for (const p of this.players) {
|
||||
if (!p || !p.conn) continue;
|
||||
const ws = p.conn.ws;
|
||||
if (ws.bufferedAmount > MAX_BUFFERED) { // hopelessly behind: dropping a snap could lose 'tw'/'ev'
|
||||
this.log(p.name + ' is too slow (' + ws.bufferedAmount + ' bytes queued); dropping the connection');
|
||||
try { ws.terminate(); } catch (e) { /* gone */ }
|
||||
continue;
|
||||
}
|
||||
sendRaw(p.conn, str);
|
||||
}
|
||||
}
|
||||
|
||||
// Something threw inside the loop: tell everyone and drop the room rather than the whole process.
|
||||
crash(err) {
|
||||
this.log('room crashed: ' + (err && err.stack || err));
|
||||
for (const p of this.players) {
|
||||
if (!p || !p.conn) continue;
|
||||
sendRaw(p.conn, JSON.stringify({ t: 'error', code: 'server_error', msg: 'internal error' }));
|
||||
try { p.conn.ws.close(1011, 'internal error'); } catch (e) { /* gone */ }
|
||||
}
|
||||
this.manager.deleteRoom(this, 'crashed');
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
for (const p of this.players) {
|
||||
if (p && p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RoomManager {
|
||||
constructor(opts) {
|
||||
this.rooms = new Map();
|
||||
this.maxRooms = opts.maxRooms;
|
||||
this.graceMs = opts.graceMs;
|
||||
this.snapPeriodNs = BigInt(Math.max(1, Math.round(1e9 / opts.snapshotHz)));
|
||||
this.log = opts.log;
|
||||
this.timer = null;
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
newCode() {
|
||||
for (let tries = 0; tries < 200; tries++) {
|
||||
let c = '';
|
||||
for (let i = 0; i < 4; i++) c += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
|
||||
if (!this.rooms.has(c)) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
get(code) { return this.rooms.get(code); }
|
||||
|
||||
// The room nobody has been online in for the longest time, or null.
|
||||
abandonedRoom() {
|
||||
let oldest = null;
|
||||
for (const r of this.rooms.values()) if (r.emptySince !== null && (oldest === null || r.emptySince < oldest.emptySince)) oldest = r;
|
||||
return oldest;
|
||||
}
|
||||
|
||||
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
|
||||
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by
|
||||
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
|
||||
create(mapId) {
|
||||
if (this.closed) return null;
|
||||
if (this.rooms.size >= this.maxRooms) {
|
||||
const victim = this.abandonedRoom();
|
||||
if (!victim) return null;
|
||||
this.deleteRoom(victim, 'evicted: the server is full and nobody is online in it');
|
||||
}
|
||||
const code = this.newCode();
|
||||
if (!code) return null;
|
||||
const room = new Room(this, code, mapId);
|
||||
this.rooms.set(code, room);
|
||||
room.log('created (map ' + mapId + '); ' + this.rooms.size + ' room(s)');
|
||||
this.startLoop();
|
||||
return room;
|
||||
}
|
||||
|
||||
deleteRoom(room, why) {
|
||||
if (this.rooms.get(room.code) !== room) return;
|
||||
room.destroy();
|
||||
this.rooms.delete(room.code);
|
||||
room.log('deleted (' + why + '); ' + this.rooms.size + ' room(s) left');
|
||||
if (!this.rooms.size) this.stopLoop();
|
||||
}
|
||||
|
||||
startLoop() {
|
||||
if (this.timer || this.closed) return;
|
||||
this.timer = setInterval(() => this.tick(), LOOP_MS);
|
||||
}
|
||||
|
||||
stopLoop() {
|
||||
if (this.timer) { clearInterval(this.timer); this.timer = null; }
|
||||
}
|
||||
|
||||
tick() {
|
||||
const now = process.hrtime.bigint();
|
||||
for (const room of Array.from(this.rooms.values())) {
|
||||
try { room.step(now); } catch (err) { room.crash(err); }
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.stopLoop();
|
||||
for (const room of Array.from(this.rooms.values())) room.destroy();
|
||||
this.rooms.clear();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Room, RoomManager, CODE_ALPHABET, CMDS, MAX_MONSTER_LOAD, MAX_BUFFERED };
|
||||
181
server/static.js
Normal file
181
server/static.js
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Minimal, safe static file server for public/.
|
||||
* - GET / HEAD only (405 otherwise), never serves anything outside the root (also not via symlinks)
|
||||
* - rejects "..", %2e%2e, %2f, %5c, backslashes, NUL and control characters (400), dotfiles (404)
|
||||
* - ETag / If-None-Match / Last-Modified (304) with Cache-Control: no-cache
|
||||
* - single-range requests (206): iOS Safari will not play <audio>/<video> without them
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { pipeline } = require('stream');
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.htm': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.woff': 'font/woff',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.wav': 'audio/wav',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
const CSP = "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'";
|
||||
|
||||
// Headers every response carries (static files, /healthz, errors).
|
||||
function applySecurityHeaders(res) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('Content-Security-Policy', CSP);
|
||||
}
|
||||
|
||||
function sendText(req, res, status, text, extra) {
|
||||
const body = Buffer.from(text, 'utf8');
|
||||
res.writeHead(status, Object.assign({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Length': body.length,
|
||||
'Cache-Control': 'no-cache',
|
||||
}, extra));
|
||||
res.end(req.method === 'HEAD' ? undefined : body);
|
||||
}
|
||||
|
||||
// Turns a raw request target into path segments, or an HTTP status to answer with.
|
||||
function parseTarget(rawUrl) {
|
||||
if (typeof rawUrl !== 'string' || rawUrl[0] !== '/') return { status: 400 };
|
||||
const cut = rawUrl.search(/[?#]/);
|
||||
const raw = cut < 0 ? rawUrl : rawUrl.slice(0, cut);
|
||||
if (/%(2f|5c)/i.test(raw) || raw.includes('\\')) return { status: 400 };
|
||||
let dec;
|
||||
try { dec = decodeURIComponent(raw); } catch (e) { return { status: 400 }; }
|
||||
if (/[\x00-\x1f\x7f\\]/.test(dec)) return { status: 400 };
|
||||
const segs = dec.split('/').filter((s) => s !== ''); // '//' collapses
|
||||
for (const s of segs) {
|
||||
if (s === '.' || s === '..') return { status: 400 };
|
||||
if (s[0] === '.') return { status: 404 }; // dotfiles and dot-directories
|
||||
}
|
||||
return { segs, trailingSlash: dec.endsWith('/') };
|
||||
}
|
||||
|
||||
function etagOf(st) { return 'W/"' + st.size.toString(16) + '-' + Math.floor(st.mtimeMs).toString(16) + '"'; }
|
||||
|
||||
function etagMatches(header, etag) {
|
||||
if (!header) return false;
|
||||
if (header.trim() === '*') return true;
|
||||
const weak = (s) => s.trim().replace(/^W\//, '');
|
||||
const mine = weak(etag);
|
||||
return header.split(',').some((t) => weak(t) === mine);
|
||||
}
|
||||
|
||||
// Parses "bytes=a-b" for a file of `size` bytes.
|
||||
// -> null (ignore the header, serve everything) | 'unsatisfiable' | { start, end }
|
||||
function parseRange(header, size) {
|
||||
if (!header) return null;
|
||||
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); // multiple ranges: ignore, serve all
|
||||
if (!m || (m[1] === '' && m[2] === '')) return null;
|
||||
let start, end;
|
||||
if (m[1] === '') { // suffix: last N bytes
|
||||
const n = parseInt(m[2], 10);
|
||||
if (n === 0) return 'unsatisfiable';
|
||||
start = Math.max(0, size - n); end = size - 1;
|
||||
} else {
|
||||
start = parseInt(m[1], 10);
|
||||
end = m[2] === '' ? size - 1 : Math.min(parseInt(m[2], 10), size - 1);
|
||||
if (m[2] !== '' && parseInt(m[2], 10) < start) return null; // malformed spec: ignore
|
||||
}
|
||||
if (start >= size) return 'unsatisfiable';
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function createStaticHandler(publicDir) {
|
||||
const root = path.resolve(publicDir);
|
||||
|
||||
async function resolveFile(segs, trailingSlash) {
|
||||
let file = path.join(root, ...segs);
|
||||
if (file !== root && !file.startsWith(root + path.sep)) return { status: 404 };
|
||||
let st;
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
if (st.isDirectory()) {
|
||||
if (!trailingSlash && segs.length) return { redirect: encodeURIComponent(segs[segs.length - 1]) + '/' };
|
||||
file = path.join(file, 'index.html');
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
}
|
||||
if (!st.isFile()) return { status: 404 };
|
||||
let real, realRoot;
|
||||
try {
|
||||
real = await fs.promises.realpath(file);
|
||||
realRoot = await fs.promises.realpath(root);
|
||||
} catch (e) { return { status: 404 }; }
|
||||
if (real !== realRoot && !real.startsWith(realRoot + path.sep)) return { status: 404 }; // symlink escape
|
||||
return { file: real, st };
|
||||
}
|
||||
|
||||
return async function handle(req, res) {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
return sendText(req, res, 405, 'Method Not Allowed', { Allow: 'GET, HEAD' });
|
||||
}
|
||||
const target = parseTarget(req.url);
|
||||
if (target.status) return sendText(req, res, target.status, target.status === 400 ? 'Bad Request' : 'Not Found');
|
||||
let r;
|
||||
try { r = await resolveFile(target.segs, target.trailingSlash); } catch (e) { r = { status: 404 }; }
|
||||
if (r.redirect) {
|
||||
// Relative on purpose: it keeps working when a proxy serves us under a path prefix.
|
||||
return sendText(req, res, 301, 'Moved Permanently', { Location: r.redirect });
|
||||
}
|
||||
if (r.status) return sendText(req, res, r.status, 'Not Found');
|
||||
|
||||
const { file, st } = r;
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
const etag = etagOf(st);
|
||||
const lastModified = st.mtime.toUTCString();
|
||||
const base = {
|
||||
'Content-Type': MIME[ext] || 'application/octet-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'ETag': etag,
|
||||
'Last-Modified': lastModified,
|
||||
'Accept-Ranges': 'bytes',
|
||||
};
|
||||
|
||||
const inm = req.headers['if-none-match'];
|
||||
const ims = req.headers['if-modified-since'];
|
||||
const fresh = inm ? etagMatches(inm, etag)
|
||||
: (ims && Math.floor(st.mtimeMs / 1000) <= Math.floor(Date.parse(ims) / 1000));
|
||||
if (fresh) {
|
||||
res.writeHead(304, { 'Cache-Control': base['Cache-Control'], 'ETag': etag, 'Last-Modified': lastModified });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let range = parseRange(req.headers.range, st.size);
|
||||
const ifRange = req.headers['if-range'];
|
||||
if (range && ifRange && ifRange.trim() !== etag && ifRange.trim() !== lastModified) range = null;
|
||||
if (range === 'unsatisfiable') {
|
||||
res.writeHead(416, { 'Content-Range': 'bytes */' + st.size, 'Content-Length': 0, 'Cache-Control': 'no-cache' });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let status = 200, start = 0, end = st.size - 1;
|
||||
if (range) {
|
||||
status = 206; start = range.start; end = range.end;
|
||||
base['Content-Range'] = 'bytes ' + start + '-' + end + '/' + st.size;
|
||||
}
|
||||
base['Content-Length'] = st.size === 0 ? 0 : end - start + 1;
|
||||
res.writeHead(status, base);
|
||||
if (req.method === 'HEAD' || st.size === 0) return res.end();
|
||||
pipeline(fs.createReadStream(file, { start, end }), res, () => { /* client went away: nothing to do */ });
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createStaticHandler, applySecurityHeaders, parseTarget, parseRange, MIME, CSP };
|
||||
Loading…
Add table
Add a link
Reference in a new issue