Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 19:05:03 +02:00
parent 249818a7aa
commit b18645dca1
87 changed files with 10201 additions and 71 deletions

193
test/push-ws.test.js Normal file
View file

@ -0,0 +1,193 @@
'use strict';
/* WebSocket transport (server/push.js): auth, limits, keepalive, revocation, shutdown. Real `ws` client against
* createServer on port 0 with the fake clock. Game hints are in push-game.test.js. */
const test = require('node:test');
const assert = require('node:assert');
const WebSocket = require('ws');
const { createTestServer } = require('./helpers');
const { connect, login, sleep, within } = require('./push-helpers');
test('auth: ready carries the server clock, ping gets pong, REST token works as ws token', async () => {
const t = await createTestServer();
try {
const u = await t.signup('alice');
t.clock.advance(12345);
const c = await connect(t.srv);
c.auth(u.token);
const ready = await c.waitFor((m) => m.type === 'ready');
assert.deepEqual(Object.keys(ready).sort(), ['serverTime', 'type']);
assert.equal(ready.serverTime, t.clock.now());
c.send({ type: 'ping' });
const pong = await c.waitFor((m) => m.type === 'pong');
assert.equal(pong.serverTime, t.clock.now());
assert.equal(t.srv.push.stats().users, 1);
c.ws.close();
await c.closed;
await sleep(20);
assert.deepEqual(t.srv.push.stats(), { connections: 0, users: 0, ips: 0 }, 'registry is empty after close');
} finally { await t.close(); }
});
test('auth: bad token, first message not auth, junk first message: close 4401, never a ready', async () => {
const t = await createTestServer();
try {
const u = await t.signup('alice');
for (const first of [{ type: 'auth', token: 'x'.repeat(43) }, { type: 'auth' }, { type: 'auth', token: 12345 }, { type: 'ping' }, 'not json', '[1,2]', { type: 'auth', token: u.token + 'x' }]) {
const c = await connect(t.srv);
c.send(first);
const r = await within(c.closed, 2000, JSON.stringify(first));
assert.equal(r.code, 4401, JSON.stringify(first));
assert.ok(!c.msgs.some((m) => m.type === 'ready'));
}
// a token in the URL is ignored: auth is the first MESSAGE only
const c = await connect(t.srv, { path: '/ws?token=' + u.token });
c.send({ type: 'ping' });
assert.equal((await c.closed).code, 4401);
await sleep(30);
assert.equal(t.srv.push.stats().connections, 0);
} finally { await t.close(); }
});
test('auth timeout: no message within wsAuthTimeoutMs closes 4408', async () => {
const t = await createTestServer({ server: { wsAuthTimeoutMs: 150 } });
try {
const c = await connect(t.srv);
const r = await within(c.closed, 2000);
assert.equal(r.code, 4408);
} finally { await t.close(); }
});
test('upgrade checks: origin, path, per-IP cap (released on close)', async () => {
const t = await createTestServer({ server: { maxConnPerIp: 2, allowedOrigins: ['https://game.example.com'] } });
try {
const u = await t.signup('alice');
await assert.rejects(connect(t.srv, { headers: { Origin: 'https://evil.example' } }), { status: 403 });
await assert.rejects(connect(t.srv, { headers: { Origin: 'null' } }), { status: 403 });
await assert.rejects(connect(t.srv, { path: '/socket' }), { status: 404 });
const ok1 = await login(t.srv, u.token, { headers: { Origin: 'https://game.example.com' } }); // allowlisted
const ok2 = await login(t.srv, u.token, { headers: { Origin: 'http://127.0.0.1:' + t.srv.port } }); // same host as Host
await assert.rejects(connect(t.srv), { status: 429 }, 'third socket from one address');
ok1.ws.close(); await ok1.closed; await sleep(20);
const ok3 = await login(t.srv, u.token); // no Origin: non-browser client
assert.equal(t.srv.push.stats().connections, 2);
ok2.ws.close(); ok3.ws.close();
await Promise.all([ok2.closed, ok3.closed]);
// refused requests never leaked a count
await sleep(20);
assert.equal(t.srv.push.stats().ips, 0);
} finally { await t.close(); }
});
test('rate limit per socket closes 4429; the bucket refills', async () => {
const t = await createTestServer({ server: { wsRate: 2, wsBurst: 4 } });
try {
const u = await t.signup('alice');
const calm = await login(t.srv, u.token);
for (let i = 0; i < 3; i++) { calm.send({ type: 'ping' }); await sleep(600); } // 1.7 msg/s: fine
assert.equal(calm.msgs.filter((m) => m.type === 'pong').length, 3);
calm.ws.close();
const c = await login(t.srv, u.token);
for (let i = 0; i < 12; i++) c.send({ type: 'ping' }); // burst of 12 > 4 + refill
assert.equal((await within(c.closed, 2000)).code, 4429);
} finally { await t.close(); }
});
test('bad-message budget closes 4400; oversize payload closes 1009', async () => {
const t = await createTestServer({ server: { wsBadBudget: 3 } });
try {
const u = await t.signup('alice');
const c = await login(t.srv, u.token);
c.send({ type: 'subscribe' });
c.send('not json');
c.send({ type: 'auth', token: u.token }); // already authenticated: counts as bad
assert.equal((await within(c.closed, 2000)).code, 4400);
const big = await login(t.srv, u.token);
big.send(JSON.stringify({ type: 'ping', pad: 'x'.repeat(2000) }));
assert.equal((await within(big.closed, 2000)).code, 1009);
const bin = await login(t.srv, u.token);
bin.ws.send(Buffer.from([1, 2, 3])); // binary frames are bad messages too
bin.ws.send(Buffer.from([1, 2, 3]));
bin.ws.send(Buffer.from([1, 2, 3]));
assert.equal((await within(bin.closed, 2000)).code, 4400);
} finally { await t.close(); }
});
test('keepalive: a socket that never answers pings is terminated', async () => {
const t = await createTestServer({ server: { wsPingMs: 60 } });
try {
const u = await t.signup('alice');
const live = await login(t.srv, u.token); // answers pings (ws default)
const dead = await login(t.srv, u.token, { wsOptions: { autoPong: false } }); // swallows them
const r = await within(dead.closed, 2000, 'dead socket should be dropped');
assert.equal(r.code, 1006);
await sleep(200);
assert.equal(live.ws.readyState, WebSocket.OPEN, 'a healthy socket stays');
assert.equal(t.srv.push.stats().connections, 1);
live.ws.close();
} finally { await t.close(); }
});
test('revoked token and banned user are disconnected at the next ping tick; other devices stay', async () => {
const t = await createTestServer({ server: { wsPingMs: 60 } });
try {
const u = await t.signup('alice');
const login2 = await t.api('/auth/login', { method: 'POST', body: { username: 'alice', password: 'correct horse battery' } });
const phone = login2.body.token;
const a = await login(t.srv, u.token), b = await login(t.srv, phone);
let r = await t.api('/auth/logout', { method: 'POST' }, u.token); // revoke device 1
assert.equal(r.status, 200);
const res = await within(a.closed, 2000, 'revoked socket');
assert.equal(res.code, 4401); assert.equal(res.reason, 'token_revoked');
await sleep(150);
assert.equal(b.ws.readyState, WebSocket.OPEN, 'the phone token is still valid');
// and a revoked token cannot open a new socket
const c = await connect(t.srv);
c.auth(u.token);
assert.equal((await within(c.closed, 2000)).code, 4401);
// ban
t.srv.db.run('UPDATE users SET banned = 1 WHERE id = ?', u.userId);
assert.equal((await within(b.closed, 2000, 'banned user')).code, 4401);
} finally { await t.close(); }
});
test('shutdown: srv.close() closes every socket with 1001 and completes promptly', async () => {
const t = await createTestServer();
const u = await t.signup('alice');
const socks = [await login(t.srv, u.token), await login(t.srv, u.token), await connect(t.srv)]; // two authed, one silent
const started = Date.now();
await within(t.close(), 4000, 'srv.close()');
assert.ok(Date.now() - started < 3000, 'close took ' + (Date.now() - started) + ' ms');
for (const s of socks) assert.equal((await within(s.closed, 1000)).code, 1001);
});
test('REST works fully with no socket, with an idle socket, and a failing command pushes nothing', async () => {
const t = await createTestServer();
try {
const u = await t.signup('alice');
// no socket at all: build, finish, notification row, all over REST
let r = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
t.clock.advance(r.body.dueAt - t.clock.now() + 1000);
r = await t.api('/notifications', {}, u.token);
assert.equal(r.status, 200);
assert.ok(r.body.items.some((n) => n.type === 'build_done'));
// a connected socket sees no hint for a refused command (rolled back, nothing happened)
const c = await login(t.srv, u.token);
r = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token);
assert.equal(r.status, 201); // sanity: this one is valid
await c.waitFor((m) => m.type === 'town'); // the valid build's own hint
await c.settle(50); c.msgs.length = 0;
const bad = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token); // queue/resources: refused
assert.ok(bad.status >= 400, 'second build of the same field is refused: ' + bad.status);
assert.deepEqual(await c.settle(100), [], 'no hint for a refused command');
// an unauthenticated socket gets no hints either
const idle = await connect(t.srv);
t.clock.advance(24 * 3600e3);
t.srv.scheduler.runDue();
assert.deepEqual(await idle.settle(100), []);
assert.equal(c.msgs.filter((m) => m.type === 'town').length >= 1, true, 'the authenticated one got its hint');
idle.ws.close(); c.ws.close();
} finally { await t.close(); }
});