feat(server)!: websocket lobby, server-run matches, server economy, new schema (P1-2, P1-4, P2-1, P2-1b, P2-5)
Replaces the Firebase-style /db facade (rtdb, rules, nodes tree) with explicit REST endpoints and a WebSocket hub. Login by name or optional e-mail, seed accounts via npm run db:reset. BREAKING CHANGE: old clients (lobby/netfight over /db) no longer work against this server; database is new.
This commit is contained in:
73
server/test/economy.test.js
Normal file
73
server/test/economy.test.js
Normal file
@@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
const { test, before, after } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { startServer } = require('./helpers');
|
||||
const RC = globalThis.RC;
|
||||
|
||||
let S;
|
||||
before(async () => { S = await startServer(); });
|
||||
after(() => S.close());
|
||||
|
||||
const part = slot => Object.values(RC.PARTS).find(p => p.slot === slot && !Object.values(RC.STARTER).includes(p.id));
|
||||
|
||||
test('online save needs a login', async () => {
|
||||
assert.equal((await S.json('GET', '/api/online')).status, 401);
|
||||
assert.equal((await S.json('POST', '/api/online/action', { type: 'buy', part: 'x' })).status, 401);
|
||||
});
|
||||
|
||||
test('shop actions run on the server and persist', async () => {
|
||||
const a = await S.account();
|
||||
const p = part('armour');
|
||||
const r = await S.json('POST', '/api/online/action', { type: 'buy', part: p.id }, a.idToken);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.ok, true);
|
||||
assert.equal(r.body.save.money, 800 - p.cost);
|
||||
const again = await S.json('GET', '/api/online', undefined, a.idToken);
|
||||
assert.equal(again.body.money, 800 - p.cost, 'stored');
|
||||
assert.equal(again.body.build.armour, p.id);
|
||||
});
|
||||
|
||||
test('refused actions return the authoritative save and change nothing', async () => {
|
||||
const a = await S.account();
|
||||
const expensive = Object.values(RC.PARTS).filter(p => p.slot !== 'weapon').sort((x, y) => y.cost - x.cost)[0];
|
||||
const r = await S.json('POST', '/api/online/action', { type: 'buy', part: expensive.id }, a.idToken);
|
||||
assert.equal(r.body.ok, false);
|
||||
assert.equal(r.body.error, 'NO_MONEY');
|
||||
assert.equal(r.body.save.money, 800);
|
||||
});
|
||||
|
||||
test('dev coins only for admins', async () => {
|
||||
const a = await S.account();
|
||||
const r = await S.json('POST', '/api/online/action', { type: 'devCoins', money: 99999 }, a.idToken);
|
||||
assert.equal(r.body.error, 'DENIED');
|
||||
});
|
||||
|
||||
test('cosmetics merge but money in the upload is ignored', async () => {
|
||||
const a = await S.account();
|
||||
const r = await S.json('PUT', '/api/online/save', { money: 1e9, fame: 1e9, flag: 'AT', robots: [{ name: 'Rusty', paint: { body: 0x00ff00, accent: 0, decal: null } }] }, a.idToken);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.money, 800);
|
||||
assert.equal(r.body.fame, 0);
|
||||
assert.equal(r.body.flag, 'AT');
|
||||
assert.equal(r.body.robotName, 'Rusty');
|
||||
});
|
||||
|
||||
test('ranking is public and only lists players with fame', async () => {
|
||||
const r = await S.json('GET', '/api/ranks');
|
||||
assert.equal(r.status, 200);
|
||||
assert.ok(Array.isArray(r.body));
|
||||
assert.ok(r.body.every(x => x.fame > 0));
|
||||
});
|
||||
|
||||
test('live settings: public read, admin-only write', async () => {
|
||||
const a = await S.account();
|
||||
assert.equal((await S.json('PUT', '/api/admin/live', { motd: { en: 'hi' } }, a.idToken)).status, 403);
|
||||
assert.equal((await S.json('GET', '/api/live')).status, 200);
|
||||
});
|
||||
|
||||
test('campaign cloud save round trip', async () => {
|
||||
const a = await S.account();
|
||||
await S.json('PUT', '/api/campaign', { money: 5, ts: 1 }, a.idToken);
|
||||
const r = await S.json('GET', '/api/campaign', undefined, a.idToken);
|
||||
assert.deepEqual(r.body, { money: 5, ts: 1 });
|
||||
});
|
||||
@@ -15,17 +15,19 @@ test('GET /healthz reports ok + version', async () => {
|
||||
assert.equal(typeof r.body.uptime, 'number');
|
||||
});
|
||||
|
||||
test('register -> login -> refresh rotates the refresh token', async () => {
|
||||
const reg = await S.json('POST', '/api/auth/register', { email: 'a@test.dev', pass: 'secret123', name: 'Alice' });
|
||||
test('register by name -> login by name (any case) -> refresh rotates the token', async () => {
|
||||
const reg = await S.json('POST', '/api/auth/register', { name: 'Alice', pass: 'secret123' });
|
||||
assert.equal(reg.status, 200);
|
||||
assert.ok(reg.body.idToken && reg.body.refreshToken && reg.body.uid);
|
||||
|
||||
const login = await S.json('POST', '/api/auth/login', { email: 'A@test.dev ', pass: 'secret123' });
|
||||
const login = await S.json('POST', '/api/auth/login', { login: ' ALICE ', pass: 'secret123' });
|
||||
assert.equal(login.status, 200);
|
||||
assert.equal(login.body.uid, reg.body.uid);
|
||||
assert.equal(login.body.name, 'Alice');
|
||||
|
||||
const me = await S.json('GET', '/api/me', undefined, login.body.idToken);
|
||||
assert.equal(me.body.uid, reg.body.uid);
|
||||
assert.equal(me.body.admin, false);
|
||||
|
||||
const r1 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken });
|
||||
assert.equal(r1.status, 200);
|
||||
@@ -33,7 +35,25 @@ test('register -> login -> refresh rotates the refresh token', async () => {
|
||||
assert.equal(r2.status, 401, 'an already used refresh token is rejected');
|
||||
});
|
||||
|
||||
test('wrong password is rejected', async () => {
|
||||
const r = await S.json('POST', '/api/auth/login', { email: 'a@test.dev', pass: 'nope-nope' });
|
||||
assert.equal(r.status, 400);
|
||||
test('register: optional e-mail works as login too; duplicates and weak passwords are refused', async () => {
|
||||
const r = await S.json('POST', '/api/auth/register', { name: 'Bob', pass: 'secret123', email: 'Bob@Test.dev' });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal((await S.json('POST', '/api/auth/login', { login: 'bob@test.dev', pass: 'secret123' })).status, 200);
|
||||
assert.equal((await S.json('POST', '/api/auth/register', { name: 'bob', pass: 'secret123' })).body.error, 'NAME_EXISTS');
|
||||
assert.equal((await S.json('POST', '/api/auth/register', { name: 'Carl', pass: 'short' })).body.error, 'WEAK_PASSWORD');
|
||||
assert.equal((await S.json('POST', '/api/auth/register', { name: 'x', pass: 'secret123' })).body.error, 'BAD_NAME');
|
||||
});
|
||||
|
||||
test('wrong password is rejected', async () => {
|
||||
const r = await S.json('POST', '/api/auth/login', { login: 'alice', pass: 'nope-nope' });
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error, 'INVALID_LOGIN');
|
||||
});
|
||||
|
||||
test('guest accounts get a token and an online save', async () => {
|
||||
const g = await S.json('POST', '/api/auth/guest', { name: 'Gast' });
|
||||
assert.equal(g.status, 200);
|
||||
assert.equal(g.body.guest, true);
|
||||
const s = await S.json('GET', '/api/online', undefined, g.body.idToken);
|
||||
assert.equal(s.body.money, 800);
|
||||
});
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
/* Test helpers: start the real server on a random port with an in-memory database. */
|
||||
/* Test helpers: start the real server on a random port with an in-memory database; WebSocket test clients. */
|
||||
'use strict';
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.DB_FILE = ':memory:';
|
||||
delete process.env.JWT_SECRET;
|
||||
|
||||
const { listen } = require('../app');
|
||||
const WebSocket = require('ws');
|
||||
const srvMod = require('../app');
|
||||
const RC = globalThis.RC;
|
||||
|
||||
let n = 0;
|
||||
async function startServer() {
|
||||
const srv = await listen(0);
|
||||
const base = 'http://127.0.0.1:' + srv.address().port;
|
||||
const srv = await srvMod.listen(0);
|
||||
const port = srv.address().port;
|
||||
const base = 'http://127.0.0.1:' + port;
|
||||
const json = async (method, path, body, token) => {
|
||||
const res = await fetch(base + path, {
|
||||
method,
|
||||
@@ -17,7 +21,56 @@ async function startServer() {
|
||||
});
|
||||
return { status: res.status, body: await res.json().catch(() => null) };
|
||||
};
|
||||
return { base, json, close: () => new Promise(r => { srv.closeAllConnections(); srv.close(r); }) };
|
||||
// a fresh registered account: { uid, idToken, ... }
|
||||
const account = async (name) => {
|
||||
const r = await json('POST', '/api/auth/register', { name: name || 'tester' + (++n), pass: 'secret123' });
|
||||
if (r.status !== 200) throw new Error('register failed ' + JSON.stringify(r.body));
|
||||
return r.body;
|
||||
};
|
||||
// connected, greeted WebSocket client with a message inbox
|
||||
const client = (token, opt = {}) => new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
const inbox = [], waiters = [];
|
||||
const c = {
|
||||
ws, inbox,
|
||||
send: m => ws.send(JSON.stringify(m)),
|
||||
// resolves with the first (already received or future) message matching type + predicate
|
||||
next(t, pred = () => true, ms = 3000) {
|
||||
const i = inbox.findIndex(m => m.t === t && pred(m));
|
||||
if (i >= 0) return Promise.resolve(inbox.splice(i, 1)[0]);
|
||||
return new Promise((res, rej) => {
|
||||
const w = { t, pred, res, timer: setTimeout(() => rej(new Error('timeout waiting for ' + t)), ms) };
|
||||
waiters.push(w);
|
||||
});
|
||||
},
|
||||
closed: new Promise(r => ws.on('close', (code, reason) => r({ code, reason: String(reason) }))),
|
||||
close: () => ws.close(),
|
||||
};
|
||||
ws.on('message', d => {
|
||||
const m = JSON.parse(d.toString());
|
||||
const wi = waiters.findIndex(w => w.t === m.t && w.pred(m));
|
||||
if (wi >= 0) { const w = waiters.splice(wi, 1)[0]; clearTimeout(w.timer); w.res(m); } else inbox.push(m);
|
||||
});
|
||||
ws.on('open', () => {
|
||||
if (opt.noHello) return resolve(c);
|
||||
c.send({ t: 'hello', v: opt.v !== undefined ? opt.v : RC.Proto.VERSION, token });
|
||||
if (opt.expectFail) return resolve(c);
|
||||
c.next('welcome').then(() => resolve(c), reject);
|
||||
});
|
||||
ws.on('error', reject);
|
||||
});
|
||||
const close = () => new Promise(r => {
|
||||
srvMod.runner.stop();
|
||||
for (const ws of srvMod.wss.clients) ws.terminate();
|
||||
srv.closeAllConnections(); srv.close(() => r());
|
||||
});
|
||||
return { base, port, json, account, client, close, runner: srvMod.runner, lobby: srvMod.lobby };
|
||||
}
|
||||
|
||||
module.exports = { startServer };
|
||||
// run every live room to its end without waiting for real time
|
||||
function fastForward(runner, maxTicks = 60 * 300) {
|
||||
runner.stop();
|
||||
for (let i = 0; i < maxTicks && runner.rooms.size; i++) for (const r of [...runner.rooms.values()]) r.tick();
|
||||
}
|
||||
|
||||
module.exports = { startServer, fastForward };
|
||||
|
||||
138
server/test/lobby.test.js
Normal file
138
server/test/lobby.test.js
Normal file
@@ -0,0 +1,138 @@
|
||||
'use strict';
|
||||
const { test, before, after } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { startServer, fastForward } = require('./helpers');
|
||||
const RC = globalThis.RC;
|
||||
|
||||
let S;
|
||||
before(async () => { S = await startServer(); });
|
||||
after(() => S.close());
|
||||
|
||||
test('socket must authenticate with hello first', async () => {
|
||||
const c = await S.client(null, { noHello: true });
|
||||
c.send({ t: 'room', room: 'DE' });
|
||||
assert.equal((await c.closed).code, 4001);
|
||||
const bad = await S.client('not-a-token', { expectFail: true });
|
||||
assert.equal((await bad.next('error')).code, 'UNAUTH');
|
||||
assert.equal((await bad.closed).code, 4003);
|
||||
});
|
||||
|
||||
test('old protocol version is told to reload', async () => {
|
||||
const a = await S.account();
|
||||
const c = await S.client(a.idToken, { v: 0, expectFail: true });
|
||||
assert.equal((await c.next('error')).code, 'OUTDATED');
|
||||
assert.equal((await c.closed).code, 4002);
|
||||
});
|
||||
|
||||
test('invalid messages get an error, the socket stays open', async () => {
|
||||
const a = await S.account();
|
||||
const c = await S.client(a.idToken);
|
||||
c.send({ t: 'input', seq: 1, throttle: 'fast' });
|
||||
assert.match((await c.next('error')).code, /BAD_FIELD/);
|
||||
c.ws.send('{not json');
|
||||
assert.equal((await c.next('error')).code, 'BAD_JSON');
|
||||
c.close();
|
||||
});
|
||||
|
||||
test('presence: join and leave are pushed to the others', async () => {
|
||||
const a = await S.account('Anna'), b = await S.account('Bert');
|
||||
const ca = await S.client(a.idToken);
|
||||
await ca.next('lobby');
|
||||
const cb = await S.client(b.idToken);
|
||||
const list = await cb.next('lobby');
|
||||
assert.ok(list.players.some(p => p.uid === a.uid && p.state === 'idle'));
|
||||
assert.equal((await ca.next('lobby.join', m => m.player.uid === b.uid)).player.name, 'Bert');
|
||||
cb.close();
|
||||
assert.equal((await ca.next('lobby.leave', m => m.uid === b.uid)).uid, b.uid);
|
||||
ca.close();
|
||||
});
|
||||
|
||||
test('challenge -> decline / cancel', async () => {
|
||||
const a = await S.account(), b = await S.account();
|
||||
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||
ca.send({ t: 'challenge', to: b.uid });
|
||||
assert.equal((await cb.next('challenge.in')).from, a.uid);
|
||||
cb.send({ t: 'challenge.decline', from: a.uid });
|
||||
assert.equal((await ca.next('challenge.gone')).reason, 'declined');
|
||||
ca.send({ t: 'challenge', to: b.uid });
|
||||
await cb.next('challenge.in');
|
||||
ca.send({ t: 'challenge.cancel' });
|
||||
assert.equal((await cb.next('challenge.gone')).reason, 'cancelled');
|
||||
ca.send({ t: 'challenge', to: a.uid });
|
||||
assert.equal((await ca.next('error')).code, 'NOT_AVAILABLE', 'cannot challenge yourself');
|
||||
ca.close(); cb.close();
|
||||
});
|
||||
|
||||
test('full live match over WebSocket: both get start, snapshots, and mirrored results with rewards', async () => {
|
||||
const a = await S.account(), b = await S.account();
|
||||
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||
ca.send({ t: 'challenge', to: b.uid });
|
||||
await cb.next('challenge.in');
|
||||
cb.send({ t: 'challenge.accept', from: a.uid });
|
||||
const [sa, sb] = await Promise.all([ca.next('match.start'), cb.next('match.start')]);
|
||||
assert.equal(sa.matchId, sb.matchId);
|
||||
assert.deepEqual([sa.seat, sb.seat].sort(), [0, 1]);
|
||||
assert.equal(sa.seed, sb.seed);
|
||||
assert.equal(sa.arena, sb.arena);
|
||||
assert.equal(sa.robots[sa.seat].uid, a.uid, 'my seat holds my robot');
|
||||
|
||||
// inputs flow in, then the server plays the rest at full speed
|
||||
ca.send({ t: 'input', seq: 1, throttle: 1, turn: 0, fire: true, fire2: false, fire3: false });
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
fastForward(S.runner);
|
||||
const [ea, eb] = await Promise.all([ca.next('match.end'), cb.next('match.end')]);
|
||||
assert.deepEqual(ea.result, eb.result, 'same seat-based result for both');
|
||||
const la = RC.Proto.localResult(ea.seat, ea.result).winner, lb = RC.Proto.localResult(eb.seat, eb.result).winner;
|
||||
if (ea.result.winner === -1) assert.ok(la === -1 && lb === -1);
|
||||
else assert.ok((la === 0) !== (lb === 0), 'exactly one player won');
|
||||
assert.equal(ea.save.games, 1);
|
||||
assert.equal(eb.save.games, 1);
|
||||
assert.ok(ca.inbox.some(m => m.t === 'snap'), 'snapshots arrived before the end');
|
||||
|
||||
// rewards were booked on the server
|
||||
const sA = await S.json('GET', '/api/online', undefined, a.idToken);
|
||||
assert.equal(sA.body.money, ea.save.money);
|
||||
ca.close(); cb.close();
|
||||
});
|
||||
|
||||
test('forfeit ends the match at once; disconnect + reconnect gets the running match back', async () => {
|
||||
const a = await S.account(), b = await S.account();
|
||||
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||
ca.send({ t: 'challenge', to: b.uid });
|
||||
await cb.next('challenge.in');
|
||||
cb.send({ t: 'challenge.accept', from: a.uid });
|
||||
const st = await ca.next('match.start');
|
||||
await cb.next('match.start');
|
||||
S.runner.stop();
|
||||
|
||||
// b drops and comes back: gets match.start again for the same match and seat
|
||||
cb.close(); await cb.closed;
|
||||
await ca.next('lobby.leave', m => m.uid === b.uid);
|
||||
const room = S.runner.get(st.matchId);
|
||||
assert.ok(room && !room.connected(1 - st.seat), 'room marks the seat as away');
|
||||
const cb2 = await S.client(b.idToken);
|
||||
const again = await cb2.next('match.start');
|
||||
assert.equal(again.matchId, st.matchId);
|
||||
assert.equal(again.seat, 1 - st.seat);
|
||||
assert.ok(room.connected(1 - st.seat));
|
||||
|
||||
ca.send({ t: 'match.leave' });
|
||||
await new Promise(r => setTimeout(r, 30));
|
||||
fastForward(S.runner);
|
||||
const ea = await ca.next('match.end'), eb = await cb2.next('match.end');
|
||||
assert.equal(RC.Proto.localResult(ea.seat, ea.result).winner, 1, 'the one who left lost');
|
||||
assert.equal(RC.Proto.localResult(eb.seat, eb.result).winner, 0);
|
||||
ca.close(); cb2.close();
|
||||
});
|
||||
|
||||
test('an invalid robot cannot challenge', async () => {
|
||||
const a = await S.account(), b = await S.account();
|
||||
// strip the battery via the economy: equip refuses required slots, so break the save directly
|
||||
const econ = require('../economy');
|
||||
const s = econ.load(a.uid); s.robots[0].build.battery = null; require('../db').OnlineSaves.put(a.uid, s);
|
||||
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||
ca.send({ t: 'challenge', to: b.uid });
|
||||
const e = await ca.next('error');
|
||||
assert.equal(e.code, 'INVALID_ROBOT');
|
||||
ca.close(); cb.close();
|
||||
});
|
||||
Reference in New Issue
Block a user