Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios): - partner's tower changes are never dropped after a render stall or snapshot burst - half-open connections show "reconnecting" in ~6 s instead of 45-65 s - upgrade and next-wave are idempotent (stale commands refused), restart message, promoted host gets Play again, failed joins never kill a live game, listener leaks Audio / keyboard / a11y: - one Audio element per track, fade/stinger supersede tokens, play() retry on the next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with role/aria-modal/focus handling, accessible names for sound/speed/pause New content: - enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm); waves weave them in from wave 9 (waves 1-8 unchanged) - towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9 - glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink already owned makes the next one 25% dearer to buy AND to upgrade (each tower remembers its multiplier, carried in the tower list as a 9th field). Shared TD.priceFor/upgradePrice so the UI shows exactly what the sim charges. Also: tablet/foldable viewports in the layout matrix (tolerant colour check), docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
1670 lines
87 KiB
JavaScript
1670 lines
87 KiB
JavaScript
'use strict';
|
||
/*
|
||
* Multiplayer server tests: a real server on port 0 and real ws clients. Everything (helpers included) lives
|
||
* in this one file because `node --test` runs every file under test/.
|
||
* Needs only Node 18+ and the ws package: no fetch, no mock timers.
|
||
*/
|
||
const test = require('node:test');
|
||
const assert = require('node:assert/strict');
|
||
const http = require('http');
|
||
const net = require('net');
|
||
const fs = require('fs');
|
||
const os = require('os');
|
||
const path = require('path');
|
||
const EventEmitter = require('events');
|
||
const WebSocket = require('ws');
|
||
const { createServer } = require('../server');
|
||
const netx = require('../server/net');
|
||
const TD = require('../public/js/sim.js');
|
||
|
||
const noop = () => {};
|
||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
let pidCounter = 0;
|
||
const newPid = () => 'testpid' + String(++pidCounter).padStart(5, '0');
|
||
|
||
async function until(fn, ms = 3000, label = 'condition') {
|
||
const end = Date.now() + ms;
|
||
for (;;) {
|
||
const v = fn();
|
||
if (v) return v;
|
||
if (Date.now() > end) throw new Error('timed out waiting for ' + label);
|
||
await sleep(4);
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- ws client wrapper
|
||
class Client {
|
||
constructor(url, opts) {
|
||
this.msgs = []; this.rx = []; this.pos = 0;
|
||
this.closeInfo = null; this.status = null; this.error = null; this.opened = false; this.pings = 0;
|
||
const ws = this.ws = new WebSocket(url, opts);
|
||
ws.on('open', () => { this.opened = true; });
|
||
ws.on('message', (data) => {
|
||
let m;
|
||
try { m = JSON.parse(data.toString()); } catch (e) { m = { t: '?bad-json', raw: String(data) }; }
|
||
this.msgs.push(m); this.rx.push(Date.now());
|
||
});
|
||
ws.on('ping', () => { this.pings++; });
|
||
ws.on('close', (code, reason) => { this.closeInfo = { code, reason: reason.toString() }; });
|
||
ws.on('error', (err) => { this.error = err; });
|
||
ws.on('unexpected-response', (req, res) => { this.status = res.statusCode; res.resume(); });
|
||
}
|
||
async open(ms = 3000) {
|
||
await until(() => this.opened || this.error || this.status || this.closeInfo, ms, 'websocket open');
|
||
if (!this.opened) throw new Error('websocket did not open: ' + (this.status || (this.error && this.error.message) || JSON.stringify(this.closeInfo)));
|
||
return this;
|
||
}
|
||
send(obj) { this.ws.send(JSON.stringify(obj)); }
|
||
raw(s) { this.ws.send(s); }
|
||
// First not-yet-consumed message matching pred (skipped messages are dropped from consideration).
|
||
next(pred, ms = 3000, label = 'message') {
|
||
return until(() => {
|
||
for (let i = this.pos; i < this.msgs.length; i++) {
|
||
if (pred(this.msgs[i])) { this.pos = i + 1; return this.msgs[i]; }
|
||
}
|
||
return null;
|
||
}, ms, label + ' (have: ' + this.msgs.slice(-6).map((m) => m.t).join(',') + (this.closeInfo ? '; closed ' + this.closeInfo.code : '') + ')');
|
||
}
|
||
type(t, ms) { return this.next((m) => m.t === t, ms, t); }
|
||
snap(pred, ms) { return this.next((m) => m.t === 'snap' && (!pred || pred(m)), ms, 'snap'); }
|
||
closed(ms = 3000) { return until(() => this.closeInfo, ms, 'close'); }
|
||
of(t, from) { return this.msgs.slice(from || 0).filter((m) => m.t === t); }
|
||
// Round trip: when the echo is back, everything the server sent before it has been seen.
|
||
async barrier() {
|
||
const ts = Math.random();
|
||
this.send({ t: 'rtt', ts });
|
||
await this.next((m) => m.t === 'rtt' && m.ts === ts, 3000, 'barrier');
|
||
}
|
||
}
|
||
|
||
async function withServer(opts, fn) {
|
||
const srv = await createServer(Object.assign({ port: 0, host: '127.0.0.1', log: noop, graceMs: 400, pingMs: 0 }, opts));
|
||
const clients = [];
|
||
const S = {
|
||
srv,
|
||
url: 'ws://127.0.0.1:' + srv.port + '/ws',
|
||
port: srv.port,
|
||
client(wsOpts) { const c = new Client(S.url, wsOpts); clients.push(c); return c; },
|
||
// connect + join; returns { c, pid, r } where r is the first 'joined' or 'error' message
|
||
async join({ name = 'Alice', map, pid = newPid(), room, wsOpts } = {}) {
|
||
const c = S.client(wsOpts);
|
||
await c.open();
|
||
const m = { t: 'join', pid, name };
|
||
if (room !== undefined) m.room = room;
|
||
if (map !== undefined) m.map = map;
|
||
c.send(m);
|
||
const r = await c.next((x) => x.t === 'joined' || x.t === 'error', 3000, 'joined');
|
||
return { c, pid, r };
|
||
},
|
||
// host creates a room, guest joins it
|
||
async pair(o) {
|
||
const a = await S.join(Object.assign({ name: 'Alice' }, o));
|
||
const b = await S.join({ name: 'Bob', room: a.r.room });
|
||
await a.c.next((m) => m.t === 'players' && m.players.length === 2, 3000, 'players(2)');
|
||
return { a, b, room: a.r.room };
|
||
},
|
||
};
|
||
try { return await fn(S); } finally {
|
||
for (const c of clients) { try { c.ws.terminate(); } catch (e) { /* ignore */ } }
|
||
await srv.close();
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- http helpers
|
||
function request(port, rawPath, { method = 'GET', headers = {}, host = '127.0.0.1' } = {}) {
|
||
return new Promise((resolve, reject) => {
|
||
const req = http.request({ host, port, method, path: rawPath, headers, agent: false }, (res) => {
|
||
const chunks = [];
|
||
res.on('data', (c) => chunks.push(c));
|
||
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }));
|
||
});
|
||
req.on('error', reject);
|
||
req.end();
|
||
});
|
||
}
|
||
|
||
function rawHttp(port, text) {
|
||
return new Promise((resolve, reject) => {
|
||
const s = net.connect(port, '127.0.0.1');
|
||
let out = '';
|
||
s.on('data', (d) => { out += d.toString('latin1'); });
|
||
s.on('close', () => resolve(out));
|
||
s.on('error', reject);
|
||
s.write(text);
|
||
});
|
||
}
|
||
|
||
// Open a websocket and report what the server said to the upgrade request.
|
||
function probe(url, opts) {
|
||
return new Promise((resolve) => {
|
||
const ws = new WebSocket(url, opts);
|
||
ws.on('open', () => { ws.terminate(); resolve({ ok: true, status: 101 }); });
|
||
ws.on('unexpected-response', (req, res) => { res.resume(); ws.terminate(); resolve({ ok: false, status: res.statusCode }); });
|
||
ws.on('error', (e) => resolve({ ok: false, error: e.message }));
|
||
});
|
||
}
|
||
|
||
const curOf = (snap, slot) => snap.cur.find((c) => c[0] === slot);
|
||
|
||
// ================================================================ handshake
|
||
test('create + join flow: joined payload', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { c, pid, r } = await S.join({ name: 'Alice', map: 'twin' });
|
||
assert.equal(r.t, 'joined');
|
||
assert.match(r.room, /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/);
|
||
assert.equal(r.resumed, false);
|
||
assert.deepEqual(r.you, { pid, slot: 0, host: true });
|
||
assert.deepEqual(r.players, [{ pid, slot: 0, name: 'Alice', host: true, online: true }]);
|
||
assert.equal(r.state.map, 'twin');
|
||
assert.equal(r.state.rev, 0);
|
||
assert.deepEqual(r.state.towers, []);
|
||
assert.equal(r.state.maxLives, TD.START_LIVES);
|
||
assert.equal(r.snap.s, 'playing');
|
||
assert.equal(r.snap.g, TD.START_GOLD);
|
||
assert.equal(r.snap.l, TD.START_LIVES);
|
||
assert.equal(r.snap.rev, 0);
|
||
assert.equal(r.speed, 1);
|
||
assert.equal(r.paused, false);
|
||
assert.ok(S.srv.rooms.has(r.room));
|
||
assert.equal(S.srv.rooms.get(r.room).sim.mapId, 'twin');
|
||
// the default map is 'open'
|
||
const d = await S.join({});
|
||
assert.equal(d.r.state.map, 'open');
|
||
assert.notEqual(d.r.room, r.room);
|
||
assert.equal(c.closeInfo, null);
|
||
});
|
||
});
|
||
|
||
test('names are trimmed, stripped of control chars, capped at 16 and default to Player', async () => {
|
||
await withServer({}, async (S) => {
|
||
const a = await S.join({ name: ' \u0007Bob\n the builder of towers ' });
|
||
assert.equal(a.r.players[0].name, 'Bob the builde'); // control chars removed, then 16 chars
|
||
assert.ok(a.r.players[0].name.length <= 16);
|
||
const b = await S.join({ name: '\u0001\u0002 ' });
|
||
assert.equal(b.r.players[0].name, 'Player');
|
||
const c = await S.join({ name: 12345 });
|
||
assert.equal(c.r.players[0].name, 'Player');
|
||
const d = await S.join({ name: '\u{1F600}'.repeat(20) });
|
||
assert.equal(Array.from(d.r.players[0].name).length, 16);
|
||
});
|
||
});
|
||
|
||
test('second player joins (case-insensitive code) and the first gets players; third gets full', async () => {
|
||
await withServer({}, async (S) => {
|
||
const a = await S.join({ name: 'Alice' });
|
||
const b = await S.join({ name: 'Bob', room: a.r.room.toLowerCase() });
|
||
assert.equal(b.r.t, 'joined');
|
||
assert.equal(b.r.room, a.r.room);
|
||
assert.equal(b.r.resumed, false);
|
||
assert.deepEqual(b.r.you, { pid: b.pid, slot: 1, host: false });
|
||
assert.equal(b.r.players.length, 2);
|
||
assert.deepEqual(b.r.players.map((p) => [p.slot, p.name, p.host, p.online]), [[0, 'Alice', true, true], [1, 'Bob', false, true]]);
|
||
const pl = await a.c.type('players');
|
||
assert.deepEqual(pl.players.map((p) => [p.slot, p.name, p.host, p.online]),
|
||
[[0, 'Alice', true, true], [1, 'Bob', false, true]]);
|
||
assert.equal(pl.players[0].pid, a.pid, 'a player sees their own pid');
|
||
assert.notEqual(pl.players[1].pid, b.pid, 'but never the other player\'s: the pid is the reconnect secret (see the pid test)');
|
||
// the joiner does not get a 'players' echo of its own join (only the *other* players do)
|
||
await b.c.barrier();
|
||
assert.equal(b.c.of('players').length, 0);
|
||
|
||
const c = await S.join({ name: 'Carol', room: a.r.room });
|
||
assert.equal(c.r.t, 'error');
|
||
assert.equal(c.r.code, 'full');
|
||
assert.equal(typeof c.r.msg, 'string');
|
||
const cl = await c.c.closed();
|
||
assert.ok(cl.code >= 4000 && cl.code < 5000);
|
||
// the two real players are unaffected
|
||
await a.c.barrier();
|
||
assert.equal(a.c.closeInfo, null);
|
||
assert.equal(S.srv.rooms.get(a.r.room).players.filter(Boolean).length, 2);
|
||
});
|
||
});
|
||
|
||
test('a full room still admits the pid that owns a slot (no full error)', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
const again = await S.join({ pid: b.pid, name: 'Bob', room });
|
||
assert.equal(again.r.t, 'joined');
|
||
assert.equal(again.r.resumed, true);
|
||
assert.equal(again.r.you.slot, 1);
|
||
});
|
||
});
|
||
|
||
test('the reconnect secret (pid) never reaches the other player; an alias cannot take a slot over', async () => {
|
||
await withServer({ graceMs: 5000 }, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
const seenByA = a.c.of('players').pop().players;
|
||
const seenByB = b.r.players;
|
||
assert.equal(seenByA.find((p) => p.slot === 0).pid, a.pid, 'own entry carries the own pid');
|
||
assert.equal(seenByB.find((p) => p.slot === 1).pid, b.pid);
|
||
const hostAlias = seenByB.find((p) => p.slot === 0).pid;
|
||
const guestAlias = seenByA.find((p) => p.slot === 1).pid;
|
||
for (const al of [hostAlias, guestAlias]) assert.match(al, /^[A-Za-z0-9_-]{22}$/);
|
||
assert.notEqual(hostAlias, a.pid);
|
||
assert.notEqual(guestAlias, b.pid);
|
||
assert.notEqual(hostAlias, guestAlias);
|
||
|
||
// the host's pid is not anywhere in what the guest was sent (and the other way round)
|
||
await a.c.barrier(); await b.c.barrier();
|
||
assert.ok(!JSON.stringify(b.c.msgs).includes(a.pid), 'host pid leaked to the guest');
|
||
assert.ok(!JSON.stringify(a.c.msgs).includes(b.pid), 'guest pid leaked to the host');
|
||
|
||
// aliases are stable across 'players' updates and reconnects
|
||
b.c.ws.terminate();
|
||
const off = await a.c.next((m) => m.t === 'players' && !m.players[1].online);
|
||
assert.equal(off.players[1].pid, guestAlias);
|
||
assert.equal(off.players[0].pid, a.pid);
|
||
const b2 = await S.join({ pid: b.pid, room });
|
||
assert.equal(b2.r.resumed, true);
|
||
assert.equal(b2.r.players.find((p) => p.slot === 0).pid, hostAlias);
|
||
assert.equal(b2.r.players.find((p) => p.slot === 1).pid, b.pid);
|
||
const on = await a.c.next((m) => m.t === 'players' && m.players[1].online);
|
||
assert.equal(on.players[1].pid, guestAlias);
|
||
|
||
// presenting the alias as a pid takes nothing over: it is just a third (refused) player, the host stays connected
|
||
const evil = await S.join({ pid: hostAlias, room, name: 'Mallory' });
|
||
assert.equal(evil.r.code, 'full');
|
||
await a.c.barrier();
|
||
assert.equal(a.c.closeInfo, null, 'the host was not kicked');
|
||
assert.equal(S.srv.rooms.get(room).players[0].conn.ws.readyState, 1);
|
||
assert.equal(S.srv.rooms.get(room).players[0].name, 'Alice');
|
||
});
|
||
});
|
||
|
||
test('join failures: unknown room, bad pid / room / map, room limit', async () => {
|
||
await withServer({ maxRooms: 2 }, async (S) => {
|
||
const cases = [
|
||
[{ room: 'ZZZZ' }, 'no_room'],
|
||
[{ pid: 'short' }, 'bad_request'],
|
||
[{ pid: 'has spaces in it!' }, 'bad_request'],
|
||
[{ pid: 'x'.repeat(41) }, 'bad_request'],
|
||
[{ pid: 12345678 }, 'bad_request'],
|
||
[{ room: 'abc' }, 'bad_request'],
|
||
[{ room: 'abcde' }, 'bad_request'],
|
||
[{ room: 'ab-d' }, 'bad_request'],
|
||
[{ room: 1234 }, 'bad_request'],
|
||
[{ map: 'nope' }, 'bad_map'],
|
||
[{ map: 42 }, 'bad_map'],
|
||
[{ map: 'toString' }, 'bad_map'],
|
||
[{ map: '__proto__' }, 'bad_map'],
|
||
];
|
||
for (const [over, code] of cases) {
|
||
const c = S.client();
|
||
await c.open();
|
||
c.send(Object.assign({ t: 'join', pid: newPid(), name: 'X' }, over));
|
||
const e = await c.type('error');
|
||
assert.equal(e.code, code, JSON.stringify(over));
|
||
assert.equal(typeof e.msg, 'string');
|
||
const cl = await c.closed();
|
||
assert.ok(cl.code >= 4000, 'close code is 4000+ for ' + JSON.stringify(over) + ' (got ' + cl.code + ')');
|
||
}
|
||
assert.equal(S.srv.rooms.size, 0, 'failed joins must not leave rooms behind');
|
||
await S.join({}); await S.join({});
|
||
const third = await S.join({});
|
||
assert.equal(third.r.code, 'too_many_rooms');
|
||
assert.equal(S.srv.rooms.size, 2);
|
||
});
|
||
});
|
||
|
||
test('a full server evicts the room nobody is online in (longest abandoned first) instead of refusing a newcomer', async () => {
|
||
await withServer({ maxRooms: 2, graceMs: 30000 }, async (S) => {
|
||
const r1 = await S.join({ name: 'one' });
|
||
const r2 = await S.join({ name: 'two' });
|
||
const dropped = async (r) => {
|
||
r.c.ws.terminate();
|
||
await until(() => S.srv.rooms.get(r.r.room).players[0].conn === null, 2000, 'server to notice the disconnect');
|
||
};
|
||
await dropped(r1);
|
||
await sleep(15);
|
||
await dropped(r2);
|
||
// full, but nobody is online in either room: the one abandoned first makes way
|
||
const n1 = await S.join({ name: 'new1' });
|
||
assert.equal(n1.r.t, 'joined');
|
||
assert.equal(S.srv.rooms.size, 2);
|
||
assert.ok(!S.srv.rooms.has(r1.r.room), 'longest-abandoned room evicted');
|
||
assert.ok(S.srv.rooms.has(r2.r.room));
|
||
assert.equal((await S.join({ pid: r1.pid, room: r1.r.room })).r.code, 'no_room');
|
||
const back2 = await S.join({ pid: r2.pid, room: r2.r.room });
|
||
assert.equal(back2.r.resumed, true, 'the other abandoned room was still held for its owner');
|
||
// somebody is online in both rooms now: nothing may be evicted, the newcomer is refused
|
||
const n2 = await S.join({ name: 'new2' });
|
||
assert.equal(n2.r.code, 'too_many_rooms');
|
||
assert.equal(S.srv.rooms.size, 2);
|
||
await n1.c.barrier(); await back2.c.barrier();
|
||
assert.equal(n1.c.closeInfo, null);
|
||
assert.equal(back2.c.closeInfo, null);
|
||
});
|
||
});
|
||
|
||
test('creating rooms and dropping the sockets cannot lock everybody else out of the room table', async () => {
|
||
await withServer({ maxRooms: 5, graceMs: 30000 }, async (S) => {
|
||
for (let i = 0; i < 12; i++) { // more than twice the table size
|
||
const f = await S.join({ name: 'flood' + i });
|
||
assert.equal(f.r.t, 'joined', 'room creation ' + i);
|
||
f.c.ws.terminate();
|
||
await until(() => S.srv.rooms.get(f.r.room).players[0].conn === null, 2000, 'disconnect ' + i);
|
||
}
|
||
assert.ok(S.srv.rooms.size <= 5);
|
||
const innocent = await S.join({ name: 'innocent' });
|
||
assert.equal(innocent.r.t, 'joined');
|
||
await innocent.c.snap();
|
||
});
|
||
});
|
||
|
||
test('first message that is not a valid join is answered with bad_request and the socket is closed', async () => {
|
||
await withServer({}, async (S) => {
|
||
for (const first of ['garbage', '{', '[]', '{"t":"rtt","ts":1}', '{"t":"join"}', '{"t":"cmd","c":"wave"}']) {
|
||
const c = S.client();
|
||
await c.open();
|
||
c.raw(first);
|
||
const e = await c.type('error');
|
||
assert.equal(e.code, 'bad_request', first);
|
||
assert.equal((await c.closed()).code, 4400);
|
||
}
|
||
assert.equal(S.srv.rooms.size, 0);
|
||
});
|
||
});
|
||
|
||
test('a socket that never joins is closed with 4408', async () => {
|
||
await withServer({ joinTimeoutMs: 150 }, async (S) => {
|
||
const c = S.client();
|
||
await c.open();
|
||
const t0 = Date.now();
|
||
const cl = await c.closed();
|
||
assert.equal(cl.code, 4408);
|
||
assert.ok(Date.now() - t0 >= 100);
|
||
// a joined socket is not affected by the timer
|
||
const a = await S.join({});
|
||
await sleep(300);
|
||
assert.equal(a.c.closeInfo, null);
|
||
});
|
||
});
|
||
|
||
// ================================================================ commands
|
||
test('cmd place: accepted -> next snap carries tw + event; "by" forged by the client is ignored', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b } = await S.pair();
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 5, y: 5, by: 1 }); // forged: claims slot 1
|
||
const s1 = await a.c.snap((m) => m.tw);
|
||
assert.equal(s1.tw.length, 1);
|
||
assert.deepEqual(s1.tw[0].slice(0, 5), [1, 'filter', 5, 5, 1]);
|
||
assert.equal(s1.tw[0][7], 0, 'owner is the sender\'s slot (0), not the forged 1');
|
||
assert.equal(s1.g, TD.START_GOLD - TD.TOWERS.filter.levels[0].cost);
|
||
assert.equal(s1.rev, 1);
|
||
const place = s1.ev.find((e) => e.e === 'place');
|
||
assert.deepEqual(place, { e: 'place', id: 1, type: 'filter', x: 5, y: 5, by: 0 });
|
||
// the other player sees the very same snap content
|
||
const s1b = await b.c.snap((m) => m.tw);
|
||
assert.equal(s1b.seq, s1.seq);
|
||
assert.deepEqual(s1b.tw, s1.tw);
|
||
assert.deepEqual(s1b.ev, s1.ev);
|
||
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 6, y: 6, by: 0 }); // forged the other way round
|
||
const s2 = await b.c.snap((m) => m.tw && m.tw.length === 2);
|
||
assert.equal(s2.tw.find((t) => t[2] === 6)[7], 1);
|
||
assert.equal(s2.ev.find((e) => e.e === 'place').by, 1);
|
||
assert.equal(a.c.of('reject').length + b.c.of('reject').length, 0, 'accepted commands send no reject');
|
||
});
|
||
});
|
||
|
||
test('cmd rejected -> reject goes to the sender only, echoing x/y/id', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b } = await S.pair();
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 3, y: 3 });
|
||
await a.c.snap((m) => m.tw);
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 3, y: 3 });
|
||
const rj = await b.c.type('reject');
|
||
assert.deepEqual(rj, { t: 'reject', c: 'place', reason: 'occupied', x: 3, y: 3 });
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 99, y: 1 });
|
||
assert.deepEqual(await b.c.type('reject'), { t: 'reject', c: 'place', reason: 'bounds', x: 99, y: 1 });
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'nope', x: 1, y: 1 });
|
||
assert.equal((await b.c.type('reject')).reason, 'bad_type');
|
||
b.c.send({ t: 'cmd', c: 'sell', id: 999 });
|
||
assert.deepEqual(await b.c.type('reject'), { t: 'reject', c: 'sell', reason: 'no_tower', id: 999 });
|
||
b.c.send({ t: 'cmd', c: 'upgrade', id: 999 });
|
||
assert.equal((await b.c.type('reject')).c, 'upgrade');
|
||
b.c.send({ t: 'cmd', c: 'target', id: 1, mode: 'bogus' });
|
||
assert.equal((await b.c.type('reject')).reason, 'bad_mode');
|
||
// run the gold down: 140 - 5 (wall) = 135 -> two IDS (60) fit, the third does not
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'ids', x: 10, y: 10 });
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'ids', x: 11, y: 10 });
|
||
b.c.send({ t: 'cmd', c: 'place', type: 'ids', x: 12, y: 10 });
|
||
assert.equal((await b.c.type('reject')).reason, 'gold');
|
||
// the sender got every reject; the other player none
|
||
await a.c.barrier();
|
||
assert.equal(a.c.of('reject').length, 0);
|
||
assert.equal(b.c.closeInfo, null, 'rejected commands are not "malformed"');
|
||
});
|
||
});
|
||
|
||
test('upgrade / target / sell / auto / continue go through the same path', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a } = await S.pair();
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
|
||
await a.c.snap((m) => m.tw && m.tw.length === 1);
|
||
a.c.send({ t: 'cmd', c: 'upgrade', id: 1 });
|
||
const up = await a.c.snap((m) => m.tw && m.tw[0][4] === 2);
|
||
assert.ok(up.ev.some((e) => e.e === 'up' && e.level === 2));
|
||
a.c.send({ t: 'cmd', c: 'target', id: 1, mode: 'strong' });
|
||
const tg = await a.c.snap((m) => m.tw && m.tw[0][5] === 'strong');
|
||
assert.equal(tg.tw[0][5], 'strong');
|
||
a.c.send({ t: 'cmd', c: 'auto', v: true });
|
||
const au = await a.c.snap((m) => m.au === 1);
|
||
assert.ok(au.nw > 0);
|
||
a.c.send({ t: 'cmd', c: 'sell', id: 1 });
|
||
const sold = await a.c.snap((m) => m.tw && m.tw.length === 0);
|
||
assert.ok(sold.ev.some((e) => e.e === 'sell'));
|
||
a.c.send({ t: 'cmd', c: 'continue' });
|
||
assert.equal((await a.c.type('reject')).reason, 'not_won');
|
||
});
|
||
});
|
||
|
||
test('simultaneous Upgrade from both players: applied once, the second is rejected as stale (sender only), charged once (coop-5)', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
const sim = S.srv.rooms.get(room).sim;
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
|
||
await a.c.snap((m) => m.tw && m.tw.length === 1);
|
||
await b.c.snap((m) => m.tw && m.tw.length === 1);
|
||
const gold = sim.gold, cost = TD.TOWERS.filter.levels[1].cost;
|
||
// both saw level 1 and pressed Upgrade at the same moment
|
||
a.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 1 });
|
||
b.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 1 });
|
||
await a.c.barrier(); await b.c.barrier();
|
||
assert.equal(sim.towers[0].level, 2, 'level 2, not 3');
|
||
assert.equal(sim.gold, gold - cost, 'charged once');
|
||
const rejects = [...a.c.of('reject'), ...b.c.of('reject')];
|
||
assert.equal(rejects.length, 1, 'exactly one of them was refused');
|
||
assert.deepEqual(rejects[0], { t: 'reject', c: 'upgrade', reason: 'stale', id: 1 });
|
||
// a client that saw level 2 may continue; a command without lv is still applied (older clients)
|
||
a.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 2 });
|
||
await a.c.snap((m) => m.tw && m.tw[0][4] === 3);
|
||
sim.gold = 1000;
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 6, y: 4 });
|
||
await a.c.snap((m) => m.tw && m.tw.length === 2);
|
||
a.c.send({ t: 'cmd', c: 'upgrade', id: 2 });
|
||
await a.c.snap((m) => m.tw && m.tw[1][4] === 2);
|
||
});
|
||
});
|
||
|
||
test('simultaneous Next wave from both players starts one wave; the other is stale (coop-5)', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
const sim = S.srv.rooms.get(room).sim;
|
||
a.c.send({ t: 'cmd', c: 'wave', n: 1 });
|
||
b.c.send({ t: 'cmd', c: 'wave', n: 1 });
|
||
await a.c.barrier(); await b.c.barrier();
|
||
assert.equal(sim.wave, 1, 'one wave, not two');
|
||
const rejects = [...a.c.of('reject'), ...b.c.of('reject')];
|
||
assert.equal(rejects.length, 1);
|
||
assert.deepEqual(rejects[0], { t: 'reject', c: 'wave', reason: 'stale' });
|
||
b.c.send({ t: 'cmd', c: 'wave', n: 2 });
|
||
await b.c.snap((m) => m.w === 2);
|
||
a.c.send({ t: 'cmd', c: 'wave' }); // no number: always the next wave
|
||
await a.c.snap((m) => m.w === 3);
|
||
});
|
||
});
|
||
|
||
test('"lv" and "n" must be integers when present: anything else is a malformed command, never "stale"', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, room } = await S.pair();
|
||
const sim = S.srv.rooms.get(room).sim;
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
|
||
await a.c.snap((m) => m.tw && m.tw.length === 1);
|
||
for (const bad of [{ c: 'upgrade', id: 1, lv: '1' }, { c: 'upgrade', id: 1, lv: 1.5 }, { c: 'wave', n: 'x' }, { c: 'wave', n: {} }]) a.c.send(Object.assign({ t: 'cmd' }, bad));
|
||
await a.c.barrier();
|
||
assert.equal(sim.towers[0].level, 1); assert.equal(sim.wave, 0);
|
||
assert.equal(a.c.of('reject').length, 0, 'not rejected by the sim: dropped as malformed');
|
||
for (let i = 0; i < 17; i++) a.c.send({ t: 'cmd', c: 'wave', n: 'x' }); // 4 + 17 = 21 malformed messages
|
||
assert.equal((await a.c.closed()).code, 4400);
|
||
});
|
||
});
|
||
|
||
test('wave command spawns monsters that appear in snapshots; refused beyond the load cap', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, room } = await S.pair();
|
||
a.c.send({ t: 'ctl', c: 'speed', v: 3 });
|
||
a.c.send({ t: 'cmd', c: 'wave' });
|
||
const w = await a.c.snap((m) => m.ev.some((e) => e.e === 'wave'));
|
||
assert.deepEqual(w.ev.find((e) => e.e === 'wave'), { e: 'wave', n: 1, boss: false });
|
||
const withMo = await a.c.snap((m) => m.mo.length > 0, 4000);
|
||
const mo = withMo.mo[0];
|
||
assert.equal(mo.length, 7);
|
||
assert.equal(TD.ENEMY_ORDER[mo[1]], 'ping');
|
||
assert.ok(withMo.w === 1 && withMo.q >= 0);
|
||
|
||
// load cap (CPU / bandwidth guard against `wave` spam)
|
||
const sim = S.srv.rooms.get(room).sim;
|
||
for (let i = 0; i < 1600; i++) sim.spawnQ.push({ t: 1e9, k: 'ping', wave: 1 });
|
||
a.c.send({ t: 'cmd', c: 'wave' });
|
||
assert.equal((await a.c.type('reject')).reason, 'busy');
|
||
assert.equal(sim.wave, 1);
|
||
});
|
||
});
|
||
|
||
// ================================================================ snapshots
|
||
test('snapshots arrive at ~20 Hz with consecutive seq and the documented fields', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b } = await S.pair();
|
||
await a.c.snap();
|
||
const from = a.c.msgs.length;
|
||
const t0 = Date.now();
|
||
await sleep(1000);
|
||
const secs = (Date.now() - t0) / 1000;
|
||
const snaps = a.c.of('snap', from);
|
||
const hz = snaps.length / secs;
|
||
assert.ok(hz > 15 && hz < 25, 'snapshot rate was ' + hz.toFixed(1) + ' Hz');
|
||
for (let i = 1; i < snaps.length; i++) assert.equal(snaps[i].seq, snaps[i - 1].seq + 1);
|
||
const s = snaps[snaps.length - 1];
|
||
for (const k of ['t', 'seq', 'time', 'g', 'l', 'w', 's', 'au', 'nw', 'k', 'rev', 'mo', 'bu', 'tt', 'q', 'ev', 'cur', 'pa', 'sp']) {
|
||
assert.ok(k in s, 'snap has ' + k);
|
||
}
|
||
assert.equal(s.pa, 0);
|
||
assert.equal(s.sp, 1);
|
||
assert.equal(s.s, 'playing');
|
||
assert.ok(!('tw' in s));
|
||
// serialised once: both players get identical bytes' worth of content for the same seq
|
||
const same = b.c.msgs.find((m) => m.t === 'snap' && m.seq === s.seq);
|
||
if (same) assert.deepEqual(same, s);
|
||
});
|
||
});
|
||
|
||
test('slow clock check: snapshot rate follows snapshotHz', async () => {
|
||
await withServer({ snapshotHz: 10 }, async (S) => {
|
||
const { a } = await S.pair();
|
||
await a.c.snap();
|
||
const from = a.c.msgs.length;
|
||
await sleep(1000);
|
||
const n = a.c.of('snap', from).length;
|
||
assert.ok(n >= 6 && n <= 13, 'got ' + n + ' snaps in 1 s at 10 Hz');
|
||
});
|
||
});
|
||
|
||
test('"tw" is attached only when the tower rev changed', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a } = await S.pair();
|
||
const quiet = async (ms) => {
|
||
const from = a.c.msgs.length;
|
||
await sleep(ms);
|
||
const s = a.c.of('snap', from);
|
||
assert.ok(s.length >= 2);
|
||
assert.ok(s.every((x) => !('tw' in x)), 'no tw while rev is unchanged');
|
||
};
|
||
await quiet(300); // from the first snap on: no tw
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 2, y: 2 });
|
||
await a.c.snap((m) => m.tw);
|
||
await quiet(300); // exactly one snap carried it
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 2, y: 2 }); // refused: occupied
|
||
await a.c.type('reject');
|
||
await quiet(200); // a refused command does not bump rev
|
||
a.c.send({ t: 'cmd', c: 'target', id: 1, mode: 'last' });
|
||
const t = await a.c.snap((m) => m.tw);
|
||
assert.equal(t.tw[0][5], 'last');
|
||
assert.equal(t.rev, 2);
|
||
await quiet(200);
|
||
});
|
||
});
|
||
|
||
test('pause stops sim time and speed 2 doubles it (pa / sp reflect the room state)', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
const sim = () => S.srv.rooms.get(room).sim;
|
||
const rate = async (c) => { // game seconds per wall second, from snapshot arrival times
|
||
await c.snap();
|
||
const from = c.msgs.length;
|
||
await sleep(900);
|
||
const idx = c.msgs.map((m, i) => (i >= from && m.t === 'snap' ? i : -1)).filter((i) => i >= 0);
|
||
const f = idx[0], l = idx[idx.length - 1];
|
||
return (c.msgs[l].time - c.msgs[f].time) / ((c.rx[l] - c.rx[f]) / 1000);
|
||
};
|
||
const r1 = await rate(a.c);
|
||
assert.ok(r1 > 0.8 && r1 < 1.2, 'speed 1 ran at ' + r1.toFixed(2) + 'x');
|
||
|
||
b.c.send({ t: 'ctl', c: 'speed', v: 2 }); // either player may change the room speed
|
||
const s2 = await a.c.snap((m) => m.sp === 2);
|
||
assert.equal(s2.sp, 2);
|
||
const r2 = await rate(a.c);
|
||
assert.ok(r2 > 1.6 && r2 < 2.4, 'speed 2 ran at ' + r2.toFixed(2) + 'x');
|
||
|
||
a.c.send({ t: 'ctl', c: 'pause', v: true });
|
||
const p = await a.c.snap((m) => m.pa === 1);
|
||
assert.equal(p.sp, 2);
|
||
const frozen = sim().time;
|
||
await sleep(350);
|
||
const later = a.c.msgs[a.c.msgs.length - 1];
|
||
assert.equal(later.t, 'snap', 'paused rooms keep sending snapshots');
|
||
assert.equal(later.pa, 1);
|
||
assert.equal(later.time, p.time);
|
||
assert.equal(sim().time, frozen);
|
||
// building while paused still works
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 8, y: 8 });
|
||
assert.ok((await a.c.snap((m) => m.tw)).tw.length === 1);
|
||
|
||
a.c.send({ t: 'ctl', c: 'pause', v: false });
|
||
await a.c.snap((m) => m.pa === 0);
|
||
await sleep(300);
|
||
assert.ok(sim().time > frozen + 0.3, 'time advances again after unpausing');
|
||
// a late joiner / sync sees the current values
|
||
a.c.send({ t: 'sync' });
|
||
const st = await a.c.type('state');
|
||
assert.equal(st.speed, 2);
|
||
assert.equal(st.paused, false);
|
||
});
|
||
});
|
||
|
||
test('the sim only ticks while somebody is online; nothing is fast-forwarded on return', async () => {
|
||
await withServer({ graceMs: 1500 }, async (S) => {
|
||
const a = await S.join({});
|
||
const room = S.srv.rooms.get(a.r.room);
|
||
await sleep(200);
|
||
assert.ok(room.sim.time > 0.1);
|
||
a.c.ws.terminate();
|
||
await until(() => room.players[0].conn === null, 2000, 'server to notice the disconnect');
|
||
const t0 = room.sim.time;
|
||
await sleep(400);
|
||
assert.equal(room.sim.time, t0);
|
||
const back = await S.join({ pid: a.pid, room: a.r.room });
|
||
assert.equal(back.r.resumed, true);
|
||
assert.ok(back.r.snap.time - t0 < 0.1, 'no catch-up for the time spent offline');
|
||
await sleep(300);
|
||
assert.ok(room.sim.time > t0 + 0.2);
|
||
});
|
||
});
|
||
|
||
test('rooms are independent and several run at once', async () => {
|
||
await withServer({}, async (S) => {
|
||
const a = await S.join({ name: 'A' });
|
||
const b = await S.join({ name: 'B', map: 'hub' });
|
||
assert.notEqual(a.r.room, b.r.room);
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 1, y: 1 });
|
||
await a.c.snap((m) => m.tw);
|
||
await b.c.snap();
|
||
await sleep(150);
|
||
assert.ok(b.c.of('snap').every((s) => !s.tw && s.g === TD.START_GOLD), 'room B is untouched by room A');
|
||
assert.equal(S.srv.rooms.get(b.r.room).sim.mapId, 'hub');
|
||
assert.ok(S.srv.rooms.get(a.r.room).sim.time > 0 && S.srv.rooms.get(b.r.room).sim.time > 0);
|
||
});
|
||
});
|
||
|
||
// ================================================================ cursor / mark / rtt / sync
|
||
test('cursor relay: clamped, rounded to 2 dp, cleared by x:null; included for all players', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b } = await S.pair();
|
||
a.c.send({ t: 'cursor', x: 3.14159, y: 2.5 });
|
||
const s = await b.c.snap((m) => curOf(m, 0));
|
||
assert.deepEqual(curOf(s, 0), [0, 3.14, 2.5]);
|
||
const own = await a.c.snap((m) => curOf(m, 0)); // the sender sees it too (one payload per room)
|
||
assert.deepEqual(curOf(own, 0), [0, 3.14, 2.5]);
|
||
b.c.send({ t: 'cursor', x: 7.777, y: 1 });
|
||
const both = await a.c.snap((m) => curOf(m, 0) && curOf(m, 1));
|
||
assert.deepEqual(curOf(both, 1), [1, 7.78, 1]);
|
||
const cols = TD.MAPS.open.rows[0].length, rows = TD.MAPS.open.rows.length;
|
||
a.c.send({ t: 'cursor', x: 999, y: -4 });
|
||
const cl = await b.c.snap((m) => { const c = curOf(m, 0); return c && c[1] === cols; });
|
||
assert.deepEqual(curOf(cl, 0), [0, cols, 0]);
|
||
a.c.send({ t: 'cursor', x: -1, y: 1e9 });
|
||
const cl2 = await b.c.snap((m) => { const c = curOf(m, 0); return c && c[2] === rows; });
|
||
assert.deepEqual(curOf(cl2, 0), [0, 0, rows]);
|
||
a.c.send({ t: 'cursor', x: null });
|
||
const hidden = await b.c.snap((m) => !curOf(m, 0));
|
||
assert.deepEqual(hidden.cur, [[1, 7.78, 1]]);
|
||
// a cursor disappears when its owner goes offline
|
||
b.c.ws.terminate();
|
||
const gone = await a.c.snap((m) => m.cur.length === 0);
|
||
assert.deepEqual(gone.cur, []);
|
||
});
|
||
});
|
||
|
||
test('mark relay goes to everyone incl. the sender, at most 1 per 400 ms per player', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b } = await S.pair();
|
||
a.c.send({ t: 'mark', x: 4.5, y: 6.25 });
|
||
const ma = await a.c.type('mark');
|
||
const mb = await b.c.type('mark');
|
||
assert.deepEqual(ma, { t: 'mark', slot: 0, x: 4.5, y: 6.25 });
|
||
assert.deepEqual(mb, ma);
|
||
for (let i = 0; i < 6; i++) a.c.send({ t: 'mark', x: i, y: i }); // all inside the window: dropped
|
||
b.c.send({ t: 'mark', x: 1, y: 1 }); // the other player has their own budget
|
||
const mb2 = await a.c.type('mark');
|
||
assert.equal(mb2.slot, 1);
|
||
await a.c.barrier();
|
||
await b.c.barrier();
|
||
assert.equal(a.c.of('mark').length, 2, 'one mark from each player, the burst was dropped');
|
||
assert.equal(a.c.closeInfo, null, 'dropped marks are rate limiting, not malformed input');
|
||
await sleep(450);
|
||
a.c.send({ t: 'mark', x: 9, y: 9 });
|
||
const late = await a.c.next((m) => m.t === 'mark' && m.slot === 0 && m.x === 9);
|
||
assert.equal(late.y, 9);
|
||
});
|
||
});
|
||
|
||
test('rtt echoes ts immediately; sync returns the full state', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a } = await S.pair();
|
||
a.c.send({ t: 'rtt', ts: 12345.678 });
|
||
assert.deepEqual(await a.c.type('rtt'), { t: 'rtt', ts: 12345.678 });
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 7, y: 7 });
|
||
await a.c.snap((m) => m.tw);
|
||
a.c.send({ t: 'sync' });
|
||
const st = await a.c.type('state');
|
||
assert.equal(st.state.map, 'open');
|
||
assert.equal(st.state.rev, 1);
|
||
assert.equal(st.state.towers.length, 1);
|
||
assert.equal(st.snap.rev, 1);
|
||
assert.equal(st.speed, 1);
|
||
assert.equal(st.paused, false);
|
||
assert.ok(!('newgame' in st));
|
||
});
|
||
});
|
||
|
||
// ================================================================ newgame / host / leave / reconnect
|
||
test('newgame is host-only; host migrates when the host leaves', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 2, y: 2 });
|
||
a.c.send({ t: 'ctl', c: 'speed', v: 3 });
|
||
a.c.send({ t: 'ctl', c: 'pause', v: true });
|
||
await a.c.snap((m) => m.rev === 1 && m.pa === 1 && m.sp === 3);
|
||
|
||
b.c.send({ t: 'newgame', map: 'twin' });
|
||
assert.deepEqual(await b.c.type('reject'), { t: 'reject', c: 'newgame', reason: 'not_host' });
|
||
await a.c.barrier();
|
||
assert.equal(a.c.of('reject').length, 0);
|
||
assert.equal(S.srv.rooms.get(room).sim.mapId, 'open');
|
||
|
||
a.c.send({ t: 'newgame', map: 'nope' });
|
||
assert.deepEqual(await a.c.type('reject'), { t: 'reject', c: 'newgame', reason: 'bad_map' });
|
||
|
||
a.c.send({ t: 'newgame', map: 'twin' });
|
||
for (const c of [a.c, b.c]) {
|
||
const st = await c.type('state');
|
||
assert.equal(st.newgame, true);
|
||
assert.equal(st.state.map, 'twin');
|
||
assert.deepEqual(st.state.towers, []);
|
||
assert.equal(st.snap.g, TD.START_GOLD);
|
||
assert.equal(st.snap.time, 0);
|
||
assert.equal(st.speed, 1);
|
||
assert.equal(st.paused, false);
|
||
}
|
||
const after = await b.c.snap((m) => m.pa === 0 && m.sp === 1);
|
||
assert.equal(after.rev, 0);
|
||
assert.ok(!('tw' in after));
|
||
|
||
a.c.send({ t: 'newgame' }); // no map: restart the current one
|
||
assert.equal((await b.c.type('state')).state.map, 'twin');
|
||
|
||
// host leaves for good -> the other player becomes host and may now start games
|
||
a.c.send({ t: 'leave' });
|
||
assert.equal((await a.c.closed()).code, 1000);
|
||
const pl = await b.c.next((m) => m.t === 'players' && m.players.length === 1);
|
||
assert.deepEqual(pl.players.map((p) => [p.slot, p.host, p.online]), [[1, true, true]]);
|
||
b.c.send({ t: 'newgame', map: 'hub' });
|
||
assert.equal((await b.c.type('state')).state.map, 'hub');
|
||
assert.equal(b.c.of('reject').filter((r) => r.reason === 'not_host').length, 1);
|
||
// slots are reused: a newcomer takes the lowest free one (0) and is not host
|
||
const c = await S.join({ name: 'Carol', room });
|
||
assert.deepEqual(c.r.you, { pid: c.pid, slot: 0, host: false });
|
||
});
|
||
});
|
||
|
||
test('host migration also happens when the host\'s grace period expires', async () => {
|
||
await withServer({ graceMs: 250 }, async (S) => {
|
||
const { a, b } = await S.pair();
|
||
a.c.ws.terminate();
|
||
const off = await b.c.next((m) => m.t === 'players' && m.players.some((p) => !p.online));
|
||
assert.deepEqual(off.players.map((p) => [p.slot, p.host, p.online]), [[0, true, false], [1, false, true]]);
|
||
const gone = await b.c.next((m) => m.t === 'players' && m.players.length === 1, 2000);
|
||
assert.deepEqual(gone.players.map((p) => [p.slot, p.host, p.online]), [[1, true, true]]);
|
||
});
|
||
});
|
||
|
||
test('reconnect with the same pid resumes within grace; the old socket is closed with 4001', async () => {
|
||
await withServer({ graceMs: 5000 }, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 2, y: 2 });
|
||
await a.c.snap((m) => m.tw);
|
||
|
||
// (1) a second connection while the first is still open
|
||
const a2 = await S.join({ pid: a.pid, room, name: 'Alice2' });
|
||
assert.equal(a2.r.t, 'joined');
|
||
assert.equal(a2.r.resumed, true);
|
||
assert.deepEqual(a2.r.you, { pid: a.pid, slot: 0, host: true });
|
||
assert.equal(a2.r.state.towers.length, 1, 'the resumed player gets the current state');
|
||
assert.equal((await a.c.closed()).code, 4001);
|
||
const pl = await b.c.next((m) => m.t === 'players' && m.players[0].name === 'Alice2');
|
||
assert.ok(pl.players.every((p) => p.online));
|
||
await a2.c.snap();
|
||
|
||
// (2) the socket dies, the player is held offline, then comes back
|
||
a2.c.ws.terminate();
|
||
const off = await b.c.next((m) => m.t === 'players' && !m.players[0].online);
|
||
assert.equal(off.players[0].pid, b.r.players[0].pid, 'the host keeps the same alias in b\'s lists');
|
||
assert.notEqual(off.players[0].pid, a.pid);
|
||
assert.equal(off.players.length, 2);
|
||
const a3 = await S.join({ pid: a.pid, room });
|
||
assert.equal(a3.r.resumed, true);
|
||
assert.equal(a3.r.you.slot, 0);
|
||
assert.equal(a3.r.you.host, true);
|
||
const on = await b.c.next((m) => m.t === 'players' && m.players[0].online);
|
||
assert.equal(on.players.length, 2);
|
||
// the offline period never freed the slot: a stranger still gets 'full'
|
||
const c = await S.join({ room });
|
||
assert.equal(c.r.code, 'full');
|
||
});
|
||
});
|
||
|
||
test('a pid that is offline for longer than graceMs loses its slot; an empty room is deleted', async () => {
|
||
await withServer({ graceMs: 250 }, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
b.c.ws.terminate();
|
||
const off = await a.c.next((m) => m.t === 'players' && m.players.some((p) => !p.online));
|
||
assert.equal(off.players.length, 2);
|
||
await sleep(120);
|
||
assert.equal(S.srv.rooms.get(room).players.filter(Boolean).length, 2, 'still held inside the grace period');
|
||
const gone = await a.c.next((m) => m.t === 'players' && m.players.length === 1, 2000);
|
||
assert.equal(gone.players[0].pid, a.pid);
|
||
// coming back after the grace period is a fresh join into the lowest free slot
|
||
const b2 = await S.join({ pid: b.pid, room });
|
||
assert.equal(b2.r.resumed, false);
|
||
assert.equal(b2.r.you.slot, 1);
|
||
assert.equal(b2.r.you.host, false);
|
||
|
||
// everyone leaves: room deleted at once for 'leave', after the grace period for a dropped socket
|
||
a.c.send({ t: 'leave' });
|
||
await a.c.closed();
|
||
assert.ok(S.srv.rooms.has(room));
|
||
b2.c.ws.terminate();
|
||
await sleep(100);
|
||
assert.ok(S.srv.rooms.has(room), 'room survives while its last player is within the grace period');
|
||
await until(() => !S.srv.rooms.has(room), 2000, 'room deletion after grace');
|
||
const lost = await S.join({ room });
|
||
assert.equal(lost.r.code, 'no_room');
|
||
});
|
||
});
|
||
|
||
test('leave deletes the room at once when the last player goes', async () => {
|
||
await withServer({}, async (S) => {
|
||
const a = await S.join({});
|
||
assert.equal(S.srv.rooms.size, 1);
|
||
a.c.send({ t: 'leave' });
|
||
assert.equal((await a.c.closed()).code, 1000);
|
||
await until(() => S.srv.rooms.size === 0, 1000, 'room deletion');
|
||
// and the loop is idle again: creating a room works from a clean slate
|
||
const b = await S.join({});
|
||
assert.equal(b.r.t, 'joined');
|
||
await b.c.snap();
|
||
});
|
||
});
|
||
|
||
// ================================================================ malformed input / limits
|
||
test('malformed messages are counted: the 20th is tolerated, the 21st closes with 4400', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a } = await S.pair();
|
||
const junk = [
|
||
() => a.c.raw('not json'),
|
||
() => a.c.raw('[]'),
|
||
() => a.c.raw('"str"'),
|
||
() => a.c.raw('{}'),
|
||
() => a.c.send({ t: 'bogus' }),
|
||
() => a.c.send({ t: 'cmd', c: 'nope' }),
|
||
() => a.c.send({ t: 'cmd' }),
|
||
() => a.c.send({ t: 'ctl', c: 'speed', v: 9 }),
|
||
() => a.c.send({ t: 'cursor', x: 'a', y: 1 }),
|
||
() => a.c.ws.send(Buffer.from([1, 2, 3])), // binary frame
|
||
];
|
||
for (let round = 0; round < 2; round++) for (const f of junk) f(); // 20 in total
|
||
await a.c.barrier(); // still alive: the 20th is tolerated
|
||
assert.equal(a.c.closeInfo, null);
|
||
a.c.raw('x'); // the 21st
|
||
assert.equal((await a.c.closed()).code, 4400);
|
||
|
||
// a second join on an already joined socket is malformed too
|
||
const b = await S.join({});
|
||
for (let i = 0; i < 20; i++) b.c.send({ t: 'join', pid: newPid() });
|
||
await b.c.barrier();
|
||
assert.equal(b.c.closeInfo, null);
|
||
b.c.send({ t: 'join', pid: newPid() });
|
||
assert.equal((await b.c.closed()).code, 4400);
|
||
});
|
||
});
|
||
|
||
test('oversize frames (> 2048 bytes) close the socket with 1009; exactly 2048 bytes is fine', async () => {
|
||
await withServer({}, async (S) => {
|
||
const { a } = await S.pair();
|
||
const base = JSON.stringify({ t: 'rtt', ts: 1, pad: '' });
|
||
const exact = JSON.stringify({ t: 'rtt', ts: 1, pad: 'x'.repeat(2048 - Buffer.byteLength(base)) });
|
||
assert.equal(Buffer.byteLength(exact), 2048);
|
||
a.c.raw(exact);
|
||
assert.equal((await a.c.type('rtt')).ts, 1);
|
||
a.c.raw('x'.repeat(3000));
|
||
assert.equal((await a.c.closed()).code, 1009);
|
||
// the server and the room survived
|
||
const b = await S.join({});
|
||
assert.equal(b.r.t, 'joined');
|
||
});
|
||
});
|
||
|
||
test('per-socket rate limit: a burst well over 120 messages closes with 4429, normal traffic does not', async () => {
|
||
await withServer({}, async (S) => {
|
||
const ok = await S.join({});
|
||
for (let i = 0; i < 100; i++) ok.c.send({ t: 'rtt', ts: i });
|
||
await until(() => ok.c.of('rtt').length === 100, 3000, '100 echoes');
|
||
assert.equal(ok.c.closeInfo, null);
|
||
|
||
const bad = await S.join({});
|
||
for (let i = 0; i < 400; i++) bad.c.send({ t: 'rtt', ts: i });
|
||
assert.equal((await bad.c.closed()).code, 4429);
|
||
assert.ok(bad.c.of('rtt').length < 400, 'the server stopped answering');
|
||
// another player is not affected
|
||
await ok.c.barrier();
|
||
// the room of the offender remains (grace), the offender is just offline
|
||
const room = S.srv.rooms.get(bad.r.room);
|
||
await until(() => room.players[0].conn === null, 1000, 'offender offline');
|
||
});
|
||
});
|
||
|
||
test('a crash inside one room (or one message handler) does not take the server or other rooms down', async () => {
|
||
await withServer({}, async (S) => {
|
||
const good = await S.join({ name: 'good' });
|
||
const bad = await S.join({ name: 'bad' });
|
||
const bad2 = await S.join({ name: 'bad2' });
|
||
// (1) the sim of one room throws while stepping
|
||
S.srv.rooms.get(bad.r.room).sim.tick = () => { throw new Error('boom (test)'); };
|
||
const e = await bad.c.type('error');
|
||
assert.equal(e.code, 'server_error');
|
||
assert.equal((await bad.c.closed()).code, 1011);
|
||
await until(() => !S.srv.rooms.has(bad.r.room), 1000, 'crashed room removed');
|
||
// (2) a handler throws for one socket
|
||
S.srv.rooms.get(bad2.r.room).handleMessage = () => { throw new Error('boom 2 (test)'); };
|
||
bad2.c.send({ t: 'rtt', ts: 1 });
|
||
assert.equal((await bad2.c.closed()).code, 1011);
|
||
// everybody else is fine
|
||
await good.c.snap();
|
||
const t0 = good.c.msgs.length;
|
||
await sleep(200);
|
||
assert.ok(good.c.of('snap', t0).length >= 2, 'the other room keeps getting snapshots');
|
||
const again = await S.join({});
|
||
assert.equal(again.r.t, 'joined');
|
||
});
|
||
});
|
||
|
||
test('a client that falls hopelessly behind (huge send backlog) is dropped and can resume', async () => {
|
||
await withServer({ graceMs: 3000 }, async (S) => {
|
||
const { a, b, room } = await S.pair();
|
||
const slow = S.srv.rooms.get(room).players[1].conn.ws;
|
||
Object.defineProperty(slow, 'bufferedAmount', { get: () => 10 * 1024 * 1024 }); // pretend the socket is backed up
|
||
assert.equal((await b.c.closed()).code, 1006, 'terminated rather than silently losing tw/ev data');
|
||
const off = await a.c.next((m) => m.t === 'players' && !m.players[1].online);
|
||
assert.equal(off.players[1].name, 'Bob');
|
||
assert.notEqual(off.players[1].pid, b.pid);
|
||
const b2 = await S.join({ pid: b.pid, room });
|
||
assert.equal(b2.r.resumed, true);
|
||
await b2.c.snap();
|
||
assert.equal(a.c.closeInfo, null);
|
||
});
|
||
});
|
||
|
||
// ================================================================ keep-alive
|
||
test('keep-alive: a socket that never pongs is terminated, one that does stays', async () => {
|
||
await withServer({ pingMs: 100, graceMs: 3000 }, async (S) => {
|
||
const good = await S.join({ name: 'good' });
|
||
const dead = await S.join({ name: 'dead', room: good.r.room, wsOpts: { autoPong: false } });
|
||
await good.c.next((m) => m.t === 'players' && m.players.length === 2);
|
||
const t0 = Date.now();
|
||
const cl = await dead.c.closed(2000);
|
||
assert.equal(cl.code, 1006, 'terminated without a close frame');
|
||
assert.ok(dead.c.pings >= 1, 'it did receive a protocol ping first');
|
||
assert.ok(Date.now() - t0 < 1200);
|
||
const off = await good.c.next((m) => m.t === 'players' && m.players.some((p) => !p.online));
|
||
assert.equal(off.players.find((p) => !p.online).name, 'dead');
|
||
await sleep(350); // several more rounds
|
||
assert.equal(good.c.closeInfo, null);
|
||
assert.ok(good.c.pings >= 3, 'got ' + good.c.pings + ' pings');
|
||
await good.c.barrier();
|
||
});
|
||
});
|
||
|
||
// ================================================================ origin / proxy
|
||
test('Origin check: same host ok, no Origin ok, foreign origin 403, "null" 403, wrong path 404', async () => {
|
||
await withServer({}, async (S) => {
|
||
const host = '127.0.0.1:' + S.port;
|
||
assert.equal((await probe(S.url)).ok, true, 'no Origin');
|
||
assert.equal((await probe(S.url, { origin: 'http://' + host })).ok, true, 'same host');
|
||
assert.equal((await probe(S.url + '?x=1', { origin: 'http://' + host })).ok, true, 'query string is ignored');
|
||
assert.equal((await probe(S.url, { origin: 'http://evil.example' })).status, 403);
|
||
assert.equal((await probe(S.url, { origin: 'http://127.0.0.1:' + (S.port === 65535 ? 1 : S.port + 1) })).status, 403, 'different port');
|
||
assert.equal((await probe(S.url, { origin: 'null' })).status, 403);
|
||
assert.equal((await probe(S.url, { origin: 'garbage' })).status, 403);
|
||
assert.equal((await probe('ws://127.0.0.1:' + S.port + '/nope')).status, 404);
|
||
assert.equal((await probe('ws://127.0.0.1:' + S.port + '/ws/')).status, 404);
|
||
assert.equal((await probe('ws://127.0.0.1:' + S.port + '/')).status, 404);
|
||
});
|
||
});
|
||
|
||
test('refused upgrades are plain HTTP responses with the security headers', async () => {
|
||
await withServer({}, async (S) => {
|
||
const send = (extra) => rawHttp(S.port, 'GET /ws HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n' +
|
||
'Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n' + extra + '\r\n');
|
||
const r = await send('Origin: http://evil.example\r\n');
|
||
assert.match(r, /^HTTP\/1\.1 403 Forbidden\r\n/);
|
||
assert.match(r, /X-Content-Type-Options: nosniff/i);
|
||
assert.match(r, /Referrer-Policy: no-referrer/i);
|
||
assert.match(r, /Content-Security-Policy: default-src 'self'; connect-src 'self' ws: wss:/i);
|
||
const nf = await rawHttp(S.port, 'GET /elsewhere HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n');
|
||
assert.match(nf, /^HTTP\/1\.1 404 Not Found\r\n/);
|
||
assert.match(nf, /X-Content-Type-Options: nosniff/i);
|
||
});
|
||
});
|
||
|
||
test('Origin check behind a proxy: Host/Origin default ports, X-Forwarded-Host (trusted proxy only), allowedOrigins', async () => {
|
||
// Host header rewritten by a proxy: https://game.example.com -> Host: game.example.com
|
||
await withServer({}, async (S) => {
|
||
assert.equal((await probe(S.url, { headers: { Host: 'game.example.com' }, origin: 'https://game.example.com' })).ok, true);
|
||
assert.equal((await probe(S.url, { headers: { Host: 'game.example.com' }, origin: 'https://GAME.Example.com:443' })).ok, true);
|
||
assert.equal((await probe(S.url, { headers: { Host: 'game.example.com:80' }, origin: 'http://game.example.com' })).ok, true);
|
||
assert.equal((await probe(S.url, { headers: { Host: 'game.example.com' }, origin: 'https://other.example.com' })).status, 403);
|
||
// proxy kept the upstream Host but sends X-Forwarded-Host: the peer is loopback -> trusted under 'auto'
|
||
const xfh = { 'X-Forwarded-Host': 'game.example.com', 'X-Forwarded-Proto': 'https' };
|
||
assert.equal((await probe(S.url, { headers: xfh, origin: 'https://game.example.com' })).ok, true);
|
||
assert.equal((await probe(S.url, { headers: { 'X-Forwarded-Host': 'game.example.com, inner.local' }, origin: 'https://game.example.com' })).ok, true, 'first entry');
|
||
assert.equal((await probe(S.url, { headers: { 'X-Forwarded-Host': 'inner.local, game.example.com' }, origin: 'https://game.example.com' })).status, 403, 'only the first entry counts');
|
||
assert.equal((await probe(S.url, { headers: xfh, origin: 'https://evil.example' })).status, 403);
|
||
});
|
||
await withServer({ trustProxy: false }, async (S) => {
|
||
assert.equal((await probe(S.url, { headers: { 'X-Forwarded-Host': 'game.example.com' }, origin: 'https://game.example.com' })).status, 403,
|
||
'X-Forwarded-Host is ignored when the proxy is not trusted');
|
||
});
|
||
await withServer({ trustProxy: true }, async (S) => {
|
||
assert.equal((await probe(S.url, { headers: { 'X-Forwarded-Host': 'game.example.com' }, origin: 'https://game.example.com' })).ok, true);
|
||
});
|
||
await withServer({ allowedOrigins: ['https://game.example.com', 'play.example.org:8443'], trustProxy: false }, async (S) => {
|
||
assert.equal((await probe(S.url, { origin: 'https://game.example.com' })).ok, true);
|
||
assert.equal((await probe(S.url, { origin: 'https://GAME.example.com' })).ok, true);
|
||
assert.equal((await probe(S.url, { origin: 'https://play.example.org:8443' })).ok, true);
|
||
assert.equal((await probe(S.url, { origin: 'https://play.example.org' })).status, 403);
|
||
assert.equal((await probe(S.url, { origin: 'https://evil.example' })).status, 403);
|
||
});
|
||
});
|
||
|
||
test('net helpers: normalizeHost / originAllowed / isPrivateIp / forwarded ip', () => {
|
||
assert.equal(netx.normalizeHost('Example.COM:443'), 'example.com');
|
||
assert.equal(netx.normalizeHost('example.com:80'), 'example.com');
|
||
assert.equal(netx.normalizeHost('https://example.com:443'), 'example.com');
|
||
assert.equal(netx.normalizeHost('http://example.com:8080'), 'example.com:8080');
|
||
assert.equal(netx.normalizeHost('[::1]:8080'), '[::1]:8080');
|
||
assert.equal(netx.normalizeHost('[::1]'), '[::1]');
|
||
assert.equal(netx.normalizeHost('a b'), null);
|
||
assert.equal(netx.normalizeHost('a/b'), null);
|
||
assert.equal(netx.normalizeHost(''), null);
|
||
assert.equal(netx.normalizeHost(undefined), null);
|
||
const req = (h, peer) => ({ headers: h, socket: { remoteAddress: peer || '::ffff:127.0.0.1' } });
|
||
const o = { trustProxy: 'auto', allowedOrigins: [] };
|
||
assert.equal(netx.originAllowed(req({ host: 'a.b' }), o), true);
|
||
assert.equal(netx.originAllowed(req({ host: 'a.b', origin: 'https://a.b' }), o), true);
|
||
assert.equal(netx.originAllowed(req({ host: 'a.b', origin: 'https://c.d' }), o), false);
|
||
assert.equal(netx.originAllowed(req({ host: 'a.b', origin: '' }), o), false);
|
||
// X-Forwarded-Host from a public peer is not believed under 'auto'
|
||
assert.equal(netx.originAllowed(req({ host: 'x', origin: 'https://c.d', 'x-forwarded-host': 'c.d' }, '203.0.113.9'), o), false);
|
||
assert.equal(netx.originAllowed(req({ host: 'x', origin: 'https://c.d', 'x-forwarded-host': 'c.d' }, '10.1.2.3'), o), true);
|
||
|
||
for (const ip of ['127.0.0.1', '::ffff:127.0.0.1', '10.0.0.5', '172.16.0.1', '172.31.255.1', '192.168.1.1', '169.254.1.1',
|
||
'::1', 'fc00::1', 'fd12:3456::1', 'fe80::1', 'fe80::1%eth0', '::ffff:192.168.0.9']) assert.equal(netx.isPrivateIp(ip), true, ip);
|
||
for (const ip of ['8.8.8.8', '172.32.0.1', '172.15.0.1', '192.169.0.1', '203.0.113.9', '2001:db8::1', '2a0a:3e40::1', 'fec0::1', '::ffff:8.8.8.8', 'not an ip', '']) {
|
||
assert.equal(netx.isPrivateIp(ip), false, ip);
|
||
}
|
||
assert.equal(netx.normalizeIp('::ffff:1.2.3.4'), '1.2.3.4');
|
||
assert.equal(netx.normalizeIp('FE80::1%eth0'), 'fe80::1');
|
||
assert.equal(netx.firstForwardedIp('203.0.113.9, 10.0.0.2'), '203.0.113.9');
|
||
assert.equal(netx.firstForwardedIp(' [2001:db8::5]:1234 , x'), '2001:db8::5');
|
||
assert.equal(netx.firstForwardedIp('203.0.113.9:5555'), '203.0.113.9');
|
||
assert.equal(netx.firstForwardedIp('::ffff:203.0.113.9'), '203.0.113.9');
|
||
assert.equal(netx.firstForwardedIp('unknown'), null);
|
||
assert.equal(netx.firstForwardedIp(undefined), null);
|
||
assert.equal(netx.parseTrustProxy(undefined), 'auto');
|
||
assert.equal(netx.parseTrustProxy('1'), true);
|
||
assert.equal(netx.parseTrustProxy('0'), false);
|
||
assert.equal(netx.parseTrustProxy('AUTO'), 'auto');
|
||
assert.throws(() => netx.parseTrustProxy('maybe'));
|
||
});
|
||
|
||
test('client ip: X-Forwarded-For / X-Real-IP are used only when the peer is a private/loopback proxy (or forced)', () => {
|
||
const req = (peer, h) => ({ headers: h || {}, socket: { remoteAddress: peer } });
|
||
const xff = { 'x-forwarded-for': '198.51.100.7, 10.0.0.2' };
|
||
assert.equal(netx.clientIp(req('::ffff:127.0.0.1', xff), 'auto'), '198.51.100.7');
|
||
assert.equal(netx.clientIp(req('192.168.1.10', xff), 'auto'), '198.51.100.7');
|
||
assert.equal(netx.clientIp(req('fd00::10', xff), 'auto'), '198.51.100.7');
|
||
assert.equal(netx.clientIp(req('::1', { 'x-real-ip': '198.51.100.8' }), 'auto'), '198.51.100.8');
|
||
assert.equal(netx.clientIp(req('::1', { 'x-forwarded-for': 'junk', 'x-real-ip': '198.51.100.8' }), 'auto'), '198.51.100.8');
|
||
assert.equal(netx.clientIp(req('::1', { 'x-forwarded-for': 'junk' }), 'auto'), '::1');
|
||
assert.equal(netx.clientIp(req('203.0.113.5', xff), 'auto'), '203.0.113.5', 'public peer: headers ignored');
|
||
assert.equal(netx.clientIp(req('::ffff:203.0.113.5', xff), 'auto'), '203.0.113.5');
|
||
assert.equal(netx.clientIp(req('203.0.113.5', xff), true), '198.51.100.7', 'forced on');
|
||
assert.equal(netx.clientIp(req('127.0.0.1', xff), false), '127.0.0.1', 'forced off');
|
||
assert.equal(netx.clientIp(req('127.0.0.1', {}), 'auto'), '127.0.0.1');
|
||
});
|
||
|
||
test('client ip: proxies append to X-Forwarded-For, so the left part is the client\'s own claim and is not believed', () => {
|
||
const req = (peer, h) => ({ headers: h || {}, socket: { remoteAddress: peer } });
|
||
const ip = (xff, peer, mode) => netx.clientIp(req(peer || '127.0.0.1', { 'x-forwarded-for': xff }), mode || 'auto');
|
||
// nginx proxy manager: the client sent "203.0.113.50"; the proxy appended the address it really saw
|
||
assert.equal(ip('203.0.113.50, 198.51.100.66'), '198.51.100.66');
|
||
assert.equal(ip('203.0.113.50, 198.51.100.66', '203.0.113.9', true), '198.51.100.66', 'also when forced on');
|
||
assert.equal(ip('203.0.113.50, 198.51.100.66, 10.0.0.2'), '198.51.100.66', 'own (private) hops are skipped');
|
||
assert.equal(ip('203.0.113.50, 198.51.100.66, 172.17.0.1, fd00::2'), '198.51.100.66');
|
||
assert.equal(ip('2001:db8::1, [2001:db8::99]:4000'), '2001:db8::99');
|
||
assert.equal(ip('198.51.100.7'), '198.51.100.7');
|
||
// LAN clients: private all the way -> what the nearest proxy saw, never the (forgeable) left end
|
||
assert.equal(ip('10.9.9.9, 192.168.1.5'), '192.168.1.5');
|
||
assert.equal(ip('192.168.1.5'), '192.168.1.5');
|
||
assert.equal(ip('junk, 10.0.0.2'), '10.0.0.2');
|
||
// junk where the proxy's entry should be: believe nothing from the header
|
||
assert.equal(ip('203.0.113.50, junk'), '127.0.0.1');
|
||
assert.equal(ip('unknown'), '127.0.0.1');
|
||
assert.equal(netx.forwardedClientIp('1.2.3.4, 5.6.7.8'), '5.6.7.8');
|
||
assert.equal(netx.forwardedClientIp(undefined), null);
|
||
assert.equal(netx.forwardedClientIp(''), null);
|
||
});
|
||
|
||
test('per-IP cap: a forged left part of X-Forwarded-For can neither dodge the cap nor use up somebody else\'s', async () => {
|
||
await withServer({ maxConnPerIp: 2 }, async (S) => {
|
||
// what nginx proxy manager forwards when a client itself sent "X-Forwarded-For: <claim>": "<claim>, <real address>"
|
||
const via = (claim) => ({ headers: { 'X-Forwarded-For': claim + ', 198.51.100.66' } });
|
||
const mallory1 = S.client(via('203.0.113.50')); await mallory1.open();
|
||
const mallory2 = S.client(via('203.0.113.50')); await mallory2.open();
|
||
assert.equal((await probe(S.url, via('192.0.2.1'))).status, 429, 'forging another address does not escape the cap');
|
||
assert.equal((await probe(S.url, via('192.0.2.2'))).status, 429);
|
||
// the address Mallory claimed was never charged: its real owner (the proxy sends just their address) connects fine
|
||
const victim = S.client({ headers: { 'X-Forwarded-For': '203.0.113.50' } });
|
||
await victim.open();
|
||
assert.equal(victim.opened, true);
|
||
});
|
||
});
|
||
|
||
test('start-up banner: os.networkInterfaces() throwing (restricted sandbox) does not matter', () => {
|
||
const real = os.networkInterfaces;
|
||
os.networkInterfaces = () => { throw new Error('A system error occurred: uv_interface_addresses returned Unknown system error 13'); };
|
||
try {
|
||
assert.deepEqual(netx.listUrls('::', 8080), ['http://localhost:8080/']);
|
||
assert.deepEqual(netx.listUrls('0.0.0.0', 8080), ['http://localhost:8080/']);
|
||
} finally { os.networkInterfaces = real; }
|
||
});
|
||
|
||
test('per-IP socket cap uses X-Forwarded-For behind a private/loopback peer; 429 on upgrade', async () => {
|
||
await withServer({ maxConnPerIp: 2 }, async (S) => {
|
||
const h = (ip) => ({ headers: { 'X-Forwarded-For': ip + ', 10.9.9.9' } });
|
||
const a1 = S.client(h('198.51.100.1')); await a1.open();
|
||
const a2 = S.client(h('198.51.100.1')); await a2.open();
|
||
assert.equal((await probe(S.url, h('198.51.100.1'))).status, 429, 'third socket for the same client ip');
|
||
assert.equal((await probe(S.url, h('198.51.100.2'))).ok, true, 'another client ip behind the same proxy is fine');
|
||
assert.equal((await probe(S.url, h('2001:db8::1'))).ok, true);
|
||
// closing frees the budget again
|
||
a1.ws.terminate();
|
||
let freed = false;
|
||
for (let i = 0; i < 100 && !freed; i++) { freed = (await probe(S.url, h('198.51.100.1'))).ok; if (!freed) await sleep(10); }
|
||
assert.ok(freed, 'cap released after a socket closed');
|
||
});
|
||
await withServer({ maxConnPerIp: 2, trustProxy: false }, async (S) => {
|
||
const h = (ip) => ({ headers: { 'X-Forwarded-For': ip } });
|
||
const [c1, c2] = [S.client(h('198.51.100.3')), S.client(h('198.51.100.4'))];
|
||
await c1.open(); await c2.open();
|
||
assert.equal((await probe(S.url, h('198.51.100.5'))).status, 429, 'spoofed headers are ignored: all sockets are 127.0.0.1');
|
||
});
|
||
await withServer({ maxConnPerIp: 0 }, async (S) => {
|
||
const cs = [];
|
||
for (let i = 0; i < 6; i++) { const c = S.client(); await c.open(); cs.push(c); }
|
||
assert.equal(cs.length, 6, 'cap disabled');
|
||
});
|
||
});
|
||
|
||
// ================================================================ proxy findings (docs/review-2026-10-09, proxy-*)
|
||
test('Origin check: a trusted proxy that drops the port from Host (nginx $host, nginx Proxy Manager) on a non-default public port', () => {
|
||
const req = (h, peer) => ({ headers: h, socket: { remoteAddress: peer || '10.0.0.2' } });
|
||
const o = { trustProxy: 'auto', allowedOrigins: [] };
|
||
// https://game.example.com:8443 -> proxy -> Host: game.example.com (no port), Origin keeps :8443
|
||
const stripped = { host: 'game.example.com', origin: 'https://game.example.com:8443' };
|
||
assert.equal(netx.originAllowed(req(stripped), o), true, 'private proxy peer');
|
||
assert.equal(netx.originAllowed(req(stripped, '::ffff:127.0.0.1'), o), true, 'loopback proxy peer');
|
||
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'http://GAME.example.com:8080' }), o), true, 'http on 8080');
|
||
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'https://game.example.com' }), o), true, 'default port still works');
|
||
// ...and must stay closed everywhere else
|
||
assert.equal(netx.originAllowed(req(stripped, '203.0.113.9'), o), false, 'public peer is not a proxy: Host must match exactly');
|
||
assert.equal(netx.originAllowed(req(stripped), { trustProxy: false, allowedOrigins: [] }), false, 'TRUST_PROXY=0');
|
||
assert.equal(netx.originAllowed(req(stripped, '203.0.113.9'), { trustProxy: true, allowedOrigins: [] }), true, 'TRUST_PROXY=1 believes any peer');
|
||
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'https://evil.example.com:8443' }), o), false, 'another host name');
|
||
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'https://game.example.com.evil.net:8443' }), o), false, 'name suffix trick');
|
||
assert.equal(netx.originAllowed(req({ host: 'game.example.com:8080', origin: 'https://game.example.com:8443' }), o), false,
|
||
'Host WITH a port (a direct connection, or a proxy that keeps it) must match exactly');
|
||
assert.equal(netx.originAllowed(req({ host: '127.0.0.1:8080', origin: 'http://127.0.0.1:9999' }, '127.0.0.1'), o), false, 'direct loopback, other port');
|
||
assert.equal(netx.originAllowed(req({ host: 'game.example.com' }), o), true, 'no Origin');
|
||
assert.equal(netx.originAllowed(req({ host: '[2001:db8::7]', origin: 'https://[2001:db8::7]:8443' }), o), true, 'IPv6 literal');
|
||
assert.equal(netx.originAllowed(req({ host: '[2001:db8::7]', origin: 'https://[2001:db8::8]:8443' }), o), false, 'other IPv6 literal');
|
||
assert.equal(netx.hostParts('Game.Example.com:8443').port, '8443');
|
||
assert.equal(netx.hostParts('https://game.example.com:443').port, '');
|
||
assert.equal(netx.hostParts('a b'), null);
|
||
});
|
||
|
||
test('Origin check over a real upgrade: Host without port + Origin with port is accepted from a trusted proxy peer only', async () => {
|
||
await withServer({}, async (S) => { // the test peer is loopback = a trusted proxy under auto
|
||
const ok = (host, origin) => probe(S.url, { headers: { Host: host }, origin });
|
||
assert.equal((await ok('highport.test', 'https://highport.test:8332')).ok, true);
|
||
assert.equal((await ok('highport.test', 'http://highport.test:8330')).ok, true);
|
||
assert.equal((await ok('highport.test', 'https://evil.test:8332')).status, 403);
|
||
assert.equal((await ok('highport.test:8330', 'https://highport.test:8332')).status, 403, 'Host has a port: exact match only');
|
||
});
|
||
await withServer({ trustProxy: false }, async (S) => {
|
||
assert.equal((await probe(S.url, { headers: { Host: 'highport.test' }, origin: 'https://highport.test:8332' })).status, 403);
|
||
});
|
||
});
|
||
|
||
test('TRUSTED_PROXIES: parseTrustedProxies accepts IPs and CIDRs (v4 + v6) and rejects typos', () => {
|
||
const t = netx.parseTrustedProxies(' 100.64.0.0/10, 2001:db8::6 ,2001:db8:1::/48,,192.0.2.1 ');
|
||
assert.deepEqual(t.list, ['100.64.0.0/10', '2001:db8::6', '2001:db8:1::/48', '192.0.2.1']);
|
||
for (const ip of ['100.64.1.1', '100.127.255.254', '::ffff:100.64.0.1', '2001:db8::6', '2001:DB8::6', '2001:db8:1:ffff::9', '192.0.2.1'])
|
||
assert.equal(t.has(ip), true, ip);
|
||
for (const ip of ['100.63.255.255', '100.128.0.1', '2001:db8::7', '2001:db8:2::1', '192.0.2.2', '8.8.8.8', 'junk', ''])
|
||
assert.equal(t.has(ip), false, ip);
|
||
assert.deepEqual(netx.parseTrustedProxies(['10.1.1.1', '2001:db8::/32']).list, ['10.1.1.1', '2001:db8::/32']);
|
||
for (const v of [undefined, null, '', ' , ', []]) assert.equal(netx.parseTrustedProxies(v), null);
|
||
for (const bad of ['nonsense', '100.64.0.0/33', '2001:db8::/129', '1.2.3.4/', '1.2.3.4/x', '1.2.3', '::ffff:10.0.0.0/104', '100.64.0.0/10, oops'])
|
||
assert.throws(() => netx.parseTrustedProxies(bad), /invalid TRUSTED_PROXIES entry/, bad);
|
||
});
|
||
|
||
test('TRUSTED_PROXIES: a proxy on a global IPv6 / CGNAT address is believed (isTrustedPeer, clientIp, Origin) once it is listed', async () => {
|
||
const req = (peer, h) => ({ headers: h || {}, socket: { remoteAddress: peer } });
|
||
const xff = { 'x-forwarded-for': '198.51.100.7' };
|
||
const t = netx.parseTrustedProxies('100.64.0.0/10,2001:db8::6');
|
||
// before: the built-in private list does not know these addresses, every player is "the proxy"
|
||
assert.equal(netx.clientIp(req('2001:db8::6', xff), 'auto'), '2001:db8::6');
|
||
assert.equal(netx.clientIp(req('100.64.1.1', xff), 'auto'), '100.64.1.1');
|
||
assert.equal(netx.isTrustedPeer(req('2001:db8::6'), 'auto'), false);
|
||
// after
|
||
assert.equal(netx.clientIp(req('2001:db8::6', xff), 'auto', t), '198.51.100.7');
|
||
assert.equal(netx.clientIp(req('::ffff:100.64.1.1', xff), 'auto', t), '198.51.100.7');
|
||
assert.equal(netx.isTrustedPeer(req('2001:db8::6'), 'auto', t), true);
|
||
assert.equal(netx.clientIp(req('2001:db8::7', xff), 'auto', t), '2001:db8::7', 'an unlisted neighbour is still not believed');
|
||
assert.equal(netx.clientIp(req('203.0.113.5', xff), 'auto', t), '203.0.113.5');
|
||
assert.equal(netx.clientIp(req('10.0.0.2', xff), 'auto', t), '198.51.100.7', 'the private ranges stay trusted: the list is an addition');
|
||
assert.equal(netx.clientIp(req('2001:db8::6', xff), false, t), '2001:db8::6', 'TRUST_PROXY=0 wins over the list');
|
||
assert.equal(netx.clientIp(req('2001:db8::6', xff), true), '198.51.100.7');
|
||
const o = { trustProxy: 'auto', allowedOrigins: [], trustedProxies: t };
|
||
const fwd = { host: 'x', origin: 'https://c.d', 'x-forwarded-host': 'c.d' };
|
||
assert.equal(netx.originAllowed(req('2001:db8::6', fwd), { trustProxy: 'auto', allowedOrigins: [] }), false);
|
||
assert.equal(netx.originAllowed(req('2001:db8::6', fwd), o), true, 'X-Forwarded-Host from a listed proxy');
|
||
assert.equal(netx.originAllowed(req('2001:db8::6', { host: 'game.example.com', origin: 'https://game.example.com:8443' }), o), true);
|
||
assert.equal(netx.originAllowed(req('2001:db8::7', { host: 'game.example.com', origin: 'https://game.example.com:8443' }), o), false);
|
||
// the server option: bad list stops the start, a good one is kept
|
||
await assert.rejects(createServer({ port: 0, host: '127.0.0.1', log: noop, trustedProxies: '100.64.0.0/40' }), /invalid TRUSTED_PROXIES entry/);
|
||
await withServer({ trustedProxies: '100.64.0.0/10, 2001:db8::6' }, async (S) => {
|
||
assert.deepEqual(S.srv.options.trustedProxies.list, ['100.64.0.0/10', '2001:db8::6']);
|
||
assert.equal((await probe(S.url, { headers: { 'X-Forwarded-For': '198.51.100.7' } })).ok, true);
|
||
});
|
||
});
|
||
|
||
// public/sw.js run in a vm with a fake Cache Storage, to see what a navigation gets while nginx answers 502 for a stopped app
|
||
function loadServiceWorker(net) {
|
||
const vm = require('vm');
|
||
const src = fs.readFileSync(path.join(__dirname, '..', 'public', 'sw.js'), 'utf8');
|
||
const BASE = 'https://game.test/';
|
||
const handlers = {}, store = new Map(), puts = [];
|
||
store.set(BASE, R(200, 'cached game')); store.set(BASE + 'index.html', R(200, 'cached shell'));
|
||
store.set(BASE + 'js/main.js', R(200, 'cached main.js'));
|
||
const caches = {
|
||
match: async (r) => store.get(typeof r === 'string' ? new URL(r, BASE + 'sw.js').href : r.url),
|
||
open: async () => ({ put: async (r, res) => { puts.push(r.url + ' ' + res.status); store.set(r.url, res); }, addAll: async () => {} }),
|
||
keys: async () => [], delete: async () => true,
|
||
};
|
||
const self = { location: new URL(BASE + 'sw.js'), skipWaiting() {}, clients: { claim() {} }, addEventListener: (t, f) => { handlers[t] = f; } };
|
||
vm.runInNewContext(src, { self, caches, fetch: net, URL, Response, Promise, Set, console });
|
||
return {
|
||
BASE, puts,
|
||
async get(url, mode) {
|
||
let out; const request = { method: 'GET', url, mode: mode || 'no-cors' };
|
||
handlers.fetch({ request, respondWith: (p) => { out = p; } });
|
||
const res = await out;
|
||
await new Promise((r) => setImmediate(r)); // the cache.put is fire-and-forget
|
||
return res;
|
||
},
|
||
};
|
||
}
|
||
function R(status, body) { return { status, body, ok: status >= 200 && status < 300, type: 'basic', clone() { return R(status, body); } }; }
|
||
|
||
test('service worker: 502/503/504 from the proxy fall back to the cache instead of showing nginx\'s error page', async () => {
|
||
for (const code of [502, 503, 504]) {
|
||
const sw = loadServiceWorker(async () => R(code, 'nginx error page'));
|
||
const B = sw.BASE;
|
||
assert.equal((await sw.get(B, 'navigate')).body, 'cached game', code + ': cached page, not the proxy error page');
|
||
assert.equal((await sw.get(B + '?room=ABCD', 'navigate')).body, 'cached shell', code + ': invite link -> cached app shell');
|
||
assert.equal((await sw.get(B + 'js/main.js')).body, 'cached main.js', code + ': cached script');
|
||
assert.equal((await sw.get(B + 'assets/music/battle.mp3')).status, code, code + ': never cached -> the real error, not index.html');
|
||
assert.deepEqual(sw.puts, [], code + ': an error response is never stored');
|
||
}
|
||
const down = loadServiceWorker(async () => { throw new TypeError('Failed to fetch'); });
|
||
assert.equal((await down.get(down.BASE, 'navigate')).body, 'cached game', 'network failure: cached page (unchanged behaviour)');
|
||
assert.equal((await down.get(down.BASE + '?room=ABCD', 'navigate')).body, 'cached shell');
|
||
assert.equal((await down.get(down.BASE + 'assets/music/battle.mp3')).type, 'error', 'a missing file is a network error, not index.html');
|
||
});
|
||
|
||
test('service worker: only complete 200 responses are cached (not a 206 range response, not a 404)', async () => {
|
||
const sw = loadServiceWorker(async (r) => R(r.url.endsWith('/range.mp3') ? 206 : r.url.endsWith('/missing.png') ? 404 : 200, 'fresh'));
|
||
const B = sw.BASE;
|
||
assert.equal((await sw.get(B + 'js/main.js')).body, 'fresh', 'healthy upstream: network first');
|
||
assert.equal((await sw.get(B + 'assets/range.mp3')).status, 206, 'a range response is passed through');
|
||
assert.equal((await sw.get(B + 'missing.png')).status, 404, 'a 404 is the upstream\'s answer');
|
||
assert.deepEqual(sw.puts, [B + 'js/main.js 200'], 'only the complete 200 is cached (not 206, not 404)');
|
||
});
|
||
|
||
// ================================================================ dual stack
|
||
test('listenDual: IPv6 fallback logic (stub server)', async () => {
|
||
const stub = (failWith) => {
|
||
const s = new EventEmitter();
|
||
s.calls = [];
|
||
s.listen = (opts) => {
|
||
s.calls.push(opts);
|
||
setImmediate(() => {
|
||
if (failWith && opts.host === '::') s.emit('error', Object.assign(new Error(failWith), { code: failWith }));
|
||
else s.emit('listening');
|
||
});
|
||
};
|
||
return s;
|
||
};
|
||
for (const code of ['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EPROTONOSUPPORT']) {
|
||
const s = stub(code); const logs = [];
|
||
assert.equal(await netx.listenDual(s, 1234, '::', (m) => logs.push(m)), '0.0.0.0');
|
||
assert.deepEqual(s.calls, [{ port: 1234, host: '::', ipv6Only: false }, { port: 1234, host: '0.0.0.0' }]);
|
||
assert.match(logs.join('\n'), /IPv6.*0\.0\.0\.0/);
|
||
assert.equal(s.listenerCount('error'), 0, 'no listener leaks');
|
||
assert.equal(s.listenerCount('listening'), 0);
|
||
}
|
||
const ok = stub(null);
|
||
assert.equal(await netx.listenDual(ok, 1, '::', noop), '::');
|
||
assert.deepEqual(ok.calls, [{ port: 1, host: '::', ipv6Only: false }], 'dual stack requested with ipv6Only:false');
|
||
// an address already in use is an error, not a reason to fall back
|
||
const busy = stub('EADDRINUSE');
|
||
await assert.rejects(() => netx.listenDual(busy, 1, '::', noop), { code: 'EADDRINUSE' });
|
||
assert.equal(busy.calls.length, 1);
|
||
// explicit hosts are honoured as given, never replaced
|
||
const explicit = stub('EAFNOSUPPORT');
|
||
assert.equal(await netx.listenDual(explicit, 5, '127.0.0.1', noop), '127.0.0.1');
|
||
assert.deepEqual(explicit.calls, [{ port: 5, host: '127.0.0.1' }]);
|
||
const v4 = stub(null);
|
||
assert.equal(await netx.listenDual(v4, 5, '0.0.0.0', noop), '0.0.0.0');
|
||
});
|
||
|
||
test('EADDRINUSE on a real port rejects createServer', async () => {
|
||
const blocker = net.createServer();
|
||
await new Promise((r) => blocker.listen(0, '127.0.0.1', r));
|
||
try {
|
||
await assert.rejects(() => createServer({ port: blocker.address().port, host: '127.0.0.1', log: noop }), { code: 'EADDRINUSE' });
|
||
} finally { await new Promise((r) => blocker.close(r)); }
|
||
});
|
||
|
||
test('dual stack: a "::" server answers on 127.0.0.1 and ::1 (skipped without IPv6)', async (t) => {
|
||
const v6 = await new Promise((res) => { const s = net.createServer(); s.once('error', () => res(false)); s.listen(0, '::1', () => s.close(() => res(true))); });
|
||
const dflt = await createServer({ port: 0, log: noop, pingMs: 0 }); // default host
|
||
try {
|
||
assert.ok(['::', '0.0.0.0'].includes(dflt.addresses[0]), 'default host is :: (or the logged IPv4 fallback)');
|
||
if (v6) assert.deepEqual(dflt.addresses, ['::']);
|
||
} finally { await dflt.close(); }
|
||
if (!v6) { t.skip('IPv6 loopback is not available in this environment'); return; }
|
||
await withServer({ host: '::' }, async (S) => {
|
||
assert.deepEqual(S.srv.addresses, ['::']);
|
||
for (const [host, wsHost] of [['127.0.0.1', '127.0.0.1'], ['::1', '[::1]']]) {
|
||
const hz = await request(S.port, '/healthz', { host });
|
||
assert.equal(hz.status, 200, host);
|
||
assert.equal(hz.body.toString(), 'ok');
|
||
const c = new Client('ws://' + wsHost + ':' + S.port + '/ws', { origin: 'http://' + wsHost + ':' + S.port });
|
||
try {
|
||
await c.open();
|
||
c.send({ t: 'join', pid: newPid(), name: 'v' + host });
|
||
const j = await c.type('joined');
|
||
assert.equal(j.you.slot, 0);
|
||
await c.snap();
|
||
} finally { c.ws.terminate(); }
|
||
}
|
||
// an IPv4 client is logged as IPv4, not ::ffff:a.b.c.d
|
||
assert.equal(netx.normalizeIp('::ffff:127.0.0.1'), '127.0.0.1');
|
||
});
|
||
});
|
||
|
||
// ================================================================ shutdown
|
||
test('close(): closes sockets with 1001, is idempotent, releases the port, leaves nothing running', async () => {
|
||
const srv = await createServer({ port: 0, host: '127.0.0.1', log: noop, pingMs: 50, graceMs: 100000 });
|
||
const url = 'ws://127.0.0.1:' + srv.port + '/ws';
|
||
const cs = [new Client(url), new Client(url)];
|
||
await cs[0].open(); await cs[1].open();
|
||
cs[0].send({ t: 'join', pid: newPid(), name: 'a' });
|
||
const j = await cs[0].type('joined');
|
||
cs[1].send({ t: 'join', pid: newPid(), name: 'b', room: j.room });
|
||
await cs[1].type('joined');
|
||
const idle = new Client(url); await idle.open(); // never joined
|
||
const t0 = Date.now();
|
||
await srv.close();
|
||
assert.ok(Date.now() - t0 < 1500, 'close took ' + (Date.now() - t0) + ' ms');
|
||
assert.equal((await cs[0].closed()).code, 1001);
|
||
assert.equal((await cs[1].closed()).code, 1001);
|
||
assert.equal((await idle.closed()).code, 1001);
|
||
assert.equal(srv.rooms.size, 0);
|
||
await srv.close(); // second call is fine
|
||
await assert.rejects(() => request(srv.port, '/healthz'), { code: 'ECONNREFUSED' });
|
||
});
|
||
|
||
// ================================================================ HTTP: static files and /healthz
|
||
test('/healthz and security headers', async () => {
|
||
await withServer({}, async (S) => {
|
||
const g = await request(S.port, '/healthz');
|
||
assert.equal(g.status, 200);
|
||
assert.equal(g.body.toString(), 'ok');
|
||
const h = await request(S.port, '/healthz', { method: 'HEAD' });
|
||
assert.equal(h.status, 200);
|
||
assert.equal(h.body.length, 0);
|
||
assert.equal((await request(S.port, '/healthz', { method: 'POST' })).status, 405);
|
||
assert.equal((await request(S.port, '/healthz?probe=1')).status, 200);
|
||
const ws = await request(S.port, '/ws');
|
||
assert.equal(ws.status, 426, 'plain GET of the socket endpoint');
|
||
for (const res of [g, h, ws, await request(S.port, '/definitely-missing'), await request(S.port, '/js/sim.js')]) {
|
||
assert.equal(res.headers['x-content-type-options'], 'nosniff');
|
||
assert.equal(res.headers['referrer-policy'], 'no-referrer');
|
||
assert.equal(res.headers['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'");
|
||
}
|
||
});
|
||
});
|
||
|
||
test('default publicDir is the repo\'s public/ (sim.js is served byte for byte)', async () => {
|
||
await withServer({}, async (S) => {
|
||
const r = await request(S.port, '/js/sim.js');
|
||
assert.equal(r.status, 200);
|
||
assert.equal(r.headers['content-type'], 'text/javascript; charset=utf-8');
|
||
assert.equal(r.headers['cache-control'], 'no-cache');
|
||
assert.ok(r.body.equals(fs.readFileSync(path.join(__dirname, '..', 'public', 'js', 'sim.js'))));
|
||
assert.equal(S.srv.options.publicDir, path.join(__dirname, '..', 'public'));
|
||
});
|
||
});
|
||
|
||
test('static server: files, MIME types, conditional + range requests, methods', async (t) => {
|
||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'netwall-static-'));
|
||
const pub = path.join(root, 'public');
|
||
for (const d of ['js', 'css', 'sub', '.git', 'assets']) fs.mkdirSync(path.join(pub, d), { recursive: true });
|
||
const audio = Buffer.alloc(1000); for (let i = 0; i < audio.length; i++) audio[i] = i % 251;
|
||
const files = {
|
||
'index.html': '<!doctype html><title>root</title>',
|
||
'sub/index.html': '<!doctype html><title>sub</title>',
|
||
'js/app.js': 'console.log(1)', 'js/.secret.js': 'SECRET', 'css/style.css': 'body{}',
|
||
'data.json': '{"a":1}', 'icon.svg': '<svg xmlns="http://www.w3.org/2000/svg"/>', 'logo.png': 'PNG', 'photo.jpg': 'JPG',
|
||
'favicon.ico': 'ICO', 'font.woff2': 'WOFF2', 'notes.txt': 'hello', 'a b.txt': 'space', 'noext': 'x', 'app.webmanifest': '{}',
|
||
'.hidden': 'SECRET', '.git/config': 'SECRET', 'empty.txt': '',
|
||
};
|
||
for (const [name, body] of Object.entries(files)) fs.writeFileSync(path.join(pub, name), body);
|
||
for (const n of ['s.mp3', 's.ogg', 's.wav']) fs.writeFileSync(path.join(pub, 'assets', n), audio);
|
||
fs.writeFileSync(path.join(root, 'secret.txt'), 'TOP SECRET');
|
||
let symlinks = true;
|
||
try { fs.symlinkSync(path.join(root, 'secret.txt'), path.join(pub, 'link-out')); fs.symlinkSync(root, path.join(pub, 'dir-out')); } catch (e) { symlinks = false; }
|
||
const srv = await createServer({ port: 0, host: '127.0.0.1', publicDir: pub, log: noop, pingMs: 0 });
|
||
t.after(async () => { await srv.close(); fs.rmSync(root, { recursive: true, force: true }); });
|
||
const get = (p, o) => request(srv.port, p, o);
|
||
|
||
await t.test('/ serves index.html; directories serve their index.html; /dir redirects relatively', async () => {
|
||
const r = await get('/');
|
||
assert.equal(r.status, 200);
|
||
assert.equal(r.headers['content-type'], 'text/html; charset=utf-8');
|
||
assert.equal(r.body.toString(), files['index.html']);
|
||
assert.equal((await get('/index.html')).body.toString(), files['index.html']);
|
||
assert.equal((await get('/index.html?cache=bust&x=%2e%2e')).status, 200);
|
||
assert.equal((await get('/sub/')).body.toString(), files['sub/index.html']);
|
||
const red = await get('/sub');
|
||
assert.equal(red.status, 301);
|
||
assert.equal(red.headers.location, 'sub/', 'relative redirect, so it also works under a path prefix');
|
||
assert.equal((await get('/js/')).status, 404, 'no index.html in js/: no directory listing');
|
||
assert.equal((await get('/a%20b.txt')).body.toString(), 'space');
|
||
assert.equal((await get('//index.html')).status, 200, 'duplicate slashes collapse');
|
||
});
|
||
|
||
await t.test('MIME types', async () => {
|
||
const want = {
|
||
'/index.html': 'text/html; charset=utf-8', '/js/app.js': 'text/javascript; charset=utf-8', '/css/style.css': 'text/css; charset=utf-8',
|
||
'/data.json': 'application/json; charset=utf-8', '/icon.svg': 'image/svg+xml', '/logo.png': 'image/png', '/photo.jpg': 'image/jpeg',
|
||
'/favicon.ico': 'image/x-icon', '/font.woff2': 'font/woff2', '/assets/s.mp3': 'audio/mpeg', '/assets/s.ogg': 'audio/ogg',
|
||
'/assets/s.wav': 'audio/wav', '/notes.txt': 'text/plain; charset=utf-8', '/noext': 'application/octet-stream',
|
||
'/app.webmanifest': 'application/manifest+json; charset=utf-8',
|
||
};
|
||
for (const [p, type] of Object.entries(want)) {
|
||
const r = await get(p);
|
||
assert.equal(r.status, 200, p);
|
||
assert.equal(r.headers['content-type'], type, p);
|
||
assert.equal(r.headers['cache-control'], 'no-cache', p);
|
||
assert.equal(r.headers['x-content-type-options'], 'nosniff');
|
||
}
|
||
assert.equal((await get('/empty.txt')).status, 200);
|
||
});
|
||
|
||
await t.test('HEAD, ETag/304, ranges', async () => {
|
||
const head = await get('/assets/s.mp3', { method: 'HEAD' });
|
||
assert.equal(head.status, 200);
|
||
assert.equal(head.headers['content-length'], '1000');
|
||
assert.equal(head.headers['accept-ranges'], 'bytes');
|
||
assert.equal(head.body.length, 0);
|
||
const full = await get('/assets/s.mp3');
|
||
assert.ok(full.body.equals(audio));
|
||
const etag = full.headers.etag;
|
||
assert.ok(etag);
|
||
const nm = await get('/assets/s.mp3', { headers: { 'If-None-Match': etag } });
|
||
assert.equal(nm.status, 304);
|
||
assert.equal(nm.body.length, 0);
|
||
assert.equal((await get('/assets/s.mp3', { headers: { 'If-None-Match': '"other"' } })).status, 200);
|
||
assert.equal((await get('/assets/s.mp3', { headers: { 'If-Modified-Since': full.headers['last-modified'] } })).status, 304);
|
||
|
||
const r1 = await get('/assets/s.mp3', { headers: { Range: 'bytes=0-9' } });
|
||
assert.equal(r1.status, 206);
|
||
assert.equal(r1.headers['content-range'], 'bytes 0-9/1000');
|
||
assert.ok(r1.body.equals(audio.subarray(0, 10)));
|
||
const r2 = await get('/assets/s.mp3', { headers: { Range: 'bytes=990-' } });
|
||
assert.equal(r2.status, 206);
|
||
assert.ok(r2.body.equals(audio.subarray(990)));
|
||
const r3 = await get('/assets/s.mp3', { headers: { Range: 'bytes=-5' } });
|
||
assert.equal(r3.status, 206);
|
||
assert.ok(r3.body.equals(audio.subarray(995)));
|
||
const r4 = await get('/assets/s.mp3', { headers: { Range: 'bytes=0-99999' } });
|
||
assert.equal(r4.status, 206);
|
||
assert.equal(r4.headers['content-range'], 'bytes 0-999/1000');
|
||
const r5 = await get('/assets/s.mp3', { headers: { Range: 'bytes=5000-' } });
|
||
assert.equal(r5.status, 416);
|
||
assert.equal(r5.headers['content-range'], 'bytes */1000');
|
||
assert.equal((await get('/assets/s.mp3', { headers: { Range: 'bytes=0-1,5-6' } })).status, 200, 'multi-range is ignored');
|
||
assert.equal((await get('/assets/s.mp3', { headers: { Range: 'nonsense' } })).status, 200);
|
||
assert.equal((await get('/assets/s.mp3', { headers: { Range: 'bytes=0-9', 'If-Range': '"stale"' } })).status, 200);
|
||
assert.equal((await get('/assets/s.mp3', { headers: { Range: 'bytes=0-9', 'If-Range': etag } })).status, 206);
|
||
});
|
||
|
||
await t.test('other methods get 405 with Allow', async () => {
|
||
for (const method of ['POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']) {
|
||
for (const p of ['/', '/index.html', '/nothing-here']) {
|
||
const r = await get(p, { method });
|
||
assert.equal(r.status, 405, method + ' ' + p);
|
||
assert.equal(r.headers.allow, 'GET, HEAD');
|
||
}
|
||
}
|
||
});
|
||
|
||
await t.test('404 for missing files', async () => {
|
||
for (const p of ['/nope', '/js/nope.js', '/nope/deeper/still', '/index.html/extra', '/sub/nope.html']) assert.equal((await get(p)).status, 404, p);
|
||
assert.equal((await get('/nope')).headers['cache-control'], 'no-cache');
|
||
});
|
||
|
||
await t.test('path traversal, encoded tricks, dotfiles, absolute paths never leak anything', async () => {
|
||
const expect400 = [
|
||
'/../secret.txt', '/../../secret.txt', '/js/../../secret.txt', '/%2e%2e/secret.txt', '/%2E%2E/secret.txt', '/.%2e/secret.txt',
|
||
'/js/%2e%2e/%2e%2e/secret.txt', '/..%2fsecret.txt', '/..%2Fsecret.txt', '/%2e%2e%2fsecret.txt', '/js%2f..%2f..%2fsecret.txt',
|
||
'/..\\secret.txt', '/..%5csecret.txt', '/%5c..%5csecret.txt', '/js\\..\\..\\secret.txt', '/%2fetc%2fpasswd',
|
||
'/index.html%00.png', '/%00', '/%00/../secret.txt', '/index.html%0d%0aX-Evil:1', '/%c0%ae%c0%ae/secret.txt', '/%',
|
||
'/%zz', '/./index.html',
|
||
];
|
||
for (const p of expect400) {
|
||
const r = await get(p);
|
||
assert.equal(r.status, 400, p);
|
||
assert.ok(!r.body.toString().includes('SECRET'), p);
|
||
}
|
||
const expect404 = ['/.hidden', '/js/.secret.js', '/.git/config', '/.git', '/%2ehidden', '/%2egit/config', '/etc/passwd', '//etc/passwd', '/secret.txt'];
|
||
for (const p of expect404) {
|
||
const r = await get(p);
|
||
assert.equal(r.status, 404, p);
|
||
assert.ok(!r.body.toString().includes('SECRET'), p);
|
||
}
|
||
if (symlinks) {
|
||
assert.equal((await get('/link-out')).status, 404, 'symlink pointing out of public/');
|
||
assert.equal((await get('/dir-out/secret.txt')).status, 404, 'symlinked directory pointing out of public/');
|
||
}
|
||
// absolute-form request target and a raw NUL byte straight on the wire
|
||
const abs = await rawHttp(srv.port, 'GET http://evil.example/index.html HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n');
|
||
assert.match(abs, /^HTTP\/1\.1 400 /);
|
||
const nul = await rawHttp(srv.port, 'GET /index.html\u0000 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n');
|
||
assert.match(nul, /^HTTP\/1\.1 (400|404) /);
|
||
assert.ok(!nul.includes('SECRET') && !nul.includes('<title>'));
|
||
const star = await rawHttp(srv.port, 'OPTIONS * HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n');
|
||
assert.match(star, /^HTTP\/1\.1 (400|405) /);
|
||
});
|
||
|
||
await t.test('static parser unit cases', () => {
|
||
const { parseTarget } = require('../server/static');
|
||
assert.deepEqual(parseTarget('/a/b.js?x=1#y'), { segs: ['a', 'b.js'], trailingSlash: false });
|
||
assert.deepEqual(parseTarget('/'), { segs: [], trailingSlash: true });
|
||
assert.deepEqual(parseTarget('/a%20b/'), { segs: ['a b'], trailingSlash: true });
|
||
assert.equal(parseTarget('/a/../b').status, 400);
|
||
assert.equal(parseTarget('a/b').status, 400);
|
||
assert.equal(parseTarget('/.env').status, 404);
|
||
});
|
||
});
|
||
|
||
test('rate limiting uses a monotonic clock: a wall-clock step backwards must not stop the refill', async () => {
|
||
const realNow = Date.now;
|
||
await withServer({}, async (S) => {
|
||
const { a } = await S.pair();
|
||
a.c.send({ t: 'mark', x: 1, y: 1 });
|
||
await a.c.type('mark');
|
||
const b = new netx.TokenBucket(60, 120);
|
||
while (b.take()) { /* drain the burst */ }
|
||
Date.now = () => realNow() - 3600 * 1000; // NTP / VM resume: the clock jumps back an hour
|
||
try {
|
||
await sleep(450);
|
||
assert.equal(b.take(), true, 'the bucket refills with real elapsed time');
|
||
a.c.send({ t: 'mark', x: 2, y: 2 });
|
||
const m = await a.c.next((x) => x.t === 'mark' && x.x === 2, 1500, 'mark after the clock step');
|
||
assert.equal(m.y, 2);
|
||
} finally { Date.now = realNow; }
|
||
});
|
||
});
|
||
|
||
test('TokenBucket: burst then steady rate', () => {
|
||
const b = new netx.TokenBucket(60, 120);
|
||
b.last = 1000; // drive it with a fake clock
|
||
let n = 0;
|
||
while (b.take(1000)) n++;
|
||
assert.equal(n, 120);
|
||
assert.equal(b.take(1000 + 15), false, 'a quarter of a token is not enough');
|
||
assert.equal(b.take(1000 + 20), true, 'one token after ~16.7 ms');
|
||
assert.equal(b.take(1000 + 20), false);
|
||
b.take(60000);
|
||
let m = 1;
|
||
while (b.take(60000)) m++;
|
||
assert.equal(m, 120, 'refill is capped at the burst size');
|
||
});
|