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

View file

@ -1,6 +1,6 @@
'use strict';
/* Registers every REST route. One file per resource; each exports register(router, services). */
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports')];
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports'), require('./sharedReports'), require('./trade'), require('./world')];
function register(router, services) {
for (const f of files) f.register(router, services);

View file

@ -32,7 +32,7 @@ const schemas = {
}),
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }),
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }),
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] }, site: { type: 'object', additionalProperties: true } }, ['x', 'y', 'type', 'bonus']),
MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }),
BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }),
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
@ -78,5 +78,6 @@ const schemas = {
};
require('./schemasMilitary')(schemas, { int, num, str, bool, obj, arr });
require('./schemasEndgame')(schemas, { int, num, str, bool, obj, arr });
module.exports = { schemas, int, num, str, bool, obj, arr };

View file

@ -0,0 +1,45 @@
'use strict';
/* Response schemas of trade, the end game and the shared report folder (merged into routes/schemas.js). Documentation
* only, like the others (test helpers can check them with createTestServer({ contract: true })). */
module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj, arr }) {
const nint = { type: ['integer', 'null'] };
const nstr = { type: ['string', 'null'] };
const free = { type: 'object', additionalProperties: true };
const Cost = { $ref: 'Cost' };
Object.assign(schemas, {
// ---- trade
TradeAmount: obj({ resource: str, amount: int }),
TradeOffer: obj({
id: int, status: str, worldId: int, townId: int, townName: nstr, x: nint, y: nint, operator: obj({ id: int, name: nstr }),
give: { $ref: 'TradeAmount' }, want: { $ref: 'TradeAmount' }, maxDistance: int, createdAt: int, expiresAt: int, acceptedAt: nint, closedAt: nint,
role: str, acceptableFrom: arr(obj({ townId: int, distance: num })),
}, ['id', 'status', 'townId', 'operator', 'give', 'want', 'maxDistance', 'createdAt', 'expiresAt']),
TradeOfferList: obj({ serverTime: int, items: arr({ $ref: 'TradeOffer' }), next: nint, exchangeLevels: arr(obj({ townId: int, level: int, reach: num })) }, ['serverTime', 'items', 'next']),
TradeOfferResponse: obj({ serverTime: int, offer: { $ref: 'TradeOffer' } }),
TradeCancelled: obj({ serverTime: int, offerId: int, status: str, returned: { $ref: 'TradeAmount' } }),
TradeAccepted: obj({ serverTime: int, offerId: int, status: str, goodsMovementId: int, paymentMovementId: int, distance: num, arriveAt: int, give: { $ref: 'TradeAmount' }, want: { $ref: 'TradeAmount' } }),
// ---- end game
LandingSite: obj({
id: nint, index: int, x: int, y: int, holder: { type: ['object', 'null'], properties: { allianceId: int, tag: str, name: str }, additionalProperties: true },
takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, level: int, maxLevel: int, progress: num, pool: Cost,
build: { type: ['object', 'null'], properties: { toLevel: int, startedAt: int, dueAt: int }, additionalProperties: true },
next: { type: ['object', 'null'], properties: { toLevel: int, cost: Cost, durationMs: int }, additionalProperties: true },
}),
WorldStatus: obj({
serverTime: int, worldId: int, name: str, speed: num, status: str, phase: str, ageDays: num, openDay: int, opensAt: int,
sites: arr({ $ref: 'LandingSite' }), winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, endedAt: nint,
}),
WorldResults: obj({ serverTime: int, available: bool, status: str, winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, results: { type: ['object', 'null'], additionalProperties: true } }),
LandingSiteResponse: obj({
serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool }),
contributions: arr(obj({ operatorId: int, name: str, fiber: int, hardware: int, capital: int })),
}, ['serverTime', 'site', 'you']),
BackboneBuildStarted: obj({ serverTime: int, siteId: int, eventId: int, toLevel: int, startedAt: int, dueAt: int, cost: Cost }),
// ---- shared reports
ReportShared: obj({ serverTime: int, changed: bool, reportId: int, allianceId: int }),
SharedReportItem: obj({ id: int, type: str, createdAt: int, sharedAt: int, sharedBy: obj({ operatorId: int, name: str }), summary: free }),
SharedReportList: obj({ serverTime: int, items: arr({ $ref: 'SharedReportItem' }), next: nint }),
SharedReport: obj({ id: int, type: str, createdAt: int, expiresAt: int, sharedAt: int, sharedBy: obj({ operatorId: int, name: str }), summary: free, data: free }),
SharedReportResponse: obj({ serverTime: int, report: { $ref: 'SharedReport' } }),
});
};

View file

@ -17,7 +17,7 @@ module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj
id: int, type: str, status: str, ownerId: int, from: { $ref: 'MovementEnd' }, to: { $ref: 'MovementEnd' }, units: Units, cargo: free,
departAt: int, arriveAt: int, recallableUntil: nint, target: { type: ['string', 'null'] }, parentId: nint, incoming: bool,
}, ['id', 'type', 'status', 'from', 'to', 'departAt', 'arriveAt']),
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }),
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }), alliedIncoming: arr({ $ref: 'Movement' }) }, ['serverTime', 'outgoing', 'incoming']),
Marked: obj({ serverTime: int, marked: int }),
ReportItem: obj({ id: int, type: str, createdAt: int, role: str, read: bool, summary: free }),
ReportList: obj({ serverTime: int, items: arr({ $ref: 'ReportItem' }), next: nint, unread: int }),

View file

@ -0,0 +1,30 @@
'use strict';
/* The alliance's shared report folder: share one of your reports, list and read the folder, take one out. */
const { createSharedReportQueries } = require('../sharedReports');
function register(router, services) {
const { commands } = services;
const folder = createSharedReportQueries(services);
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.post('/reports/:id/share', {
summary: 'Put one of your reports into your alliance\'s shared folder (needs shareReport; keeps the report for another 14 days)', tag: 'reports',
response: { $ref: 'ReportShared' }, errors: errs.concat(['not_in_alliance', 'forbidden', 'world_ended']),
}, ({ user, params }) => commands.run('reportShare', { userId: user.id, reportId: params.id }));
router.del('/reports/:id/share', {
summary: 'Take a report out of the alliance folder (whoever shared it, or leader/officer)', tag: 'reports',
response: { $ref: 'ReportShared' }, errors: errs.concat(['forbidden', 'world_ended']),
}, ({ user, params }) => commands.run('reportUnshare', { userId: user.id, reportId: params.id }));
router.get('/alliances/:id/reports', {
summary: 'The alliance\'s shared reports, newest first (cursor: after = id of the last report seen; members only)', tag: 'reports',
query: { type: 'object', properties: { after: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 } } },
response: { $ref: 'SharedReportList' }, errors: errs.concat(['forbidden']),
}, ({ user, params, query }) => folder.list(user.id, params.id, query));
router.get('/alliances/:id/reports/:reportId', {
summary: 'One shared report with its full data (members only)', tag: 'reports', response: { $ref: 'SharedReportResponse' }, errors: errs.concat(['forbidden']),
}, ({ user, params }) => folder.get(user.id, params.id, params.reportId));
}
module.exports = { register };

53
server/routes/trade.js Normal file
View file

@ -0,0 +1,53 @@
'use strict';
/* Internet exchange: open offers, your offers, create / cancel / accept. Direct transports (to your own POPs or any player)
* are POST /movements with type "transport". */
const { reply } = require('../http');
const { createTradeQueries } = require('../tradeQueries');
const D = require('../../public/js/data.js');
const int1 = { type: 'integer', minimum: 1 };
const res = { type: 'string', enum: D.RESOURCES };
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
function register(router, services) {
const { commands } = services;
const trade = createTradeQueries(services);
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.get('/trade/offers', {
summary: 'Open offers you can take: within the offer\'s max distance and the reach of one of your Internet exchanges (newest first, cursor: after = last id seen)', tag: 'trade',
query: { type: 'object', properties: Object.assign({ worldId: int1, townId: int1, give: res, want: res }, page) }, response: { $ref: 'TradeOfferList' }, errors: errs,
}, ({ user, query }) => trade.offers(user.id, query));
router.get('/trade/offers/mine', {
summary: 'Offers you posted or accepted, any status (newest first)', tag: 'trade',
query: { type: 'object', properties: Object.assign({ worldId: int1, status: { type: 'string', enum: ['open', 'accepted', 'completed', 'cancelled', 'expired', 'void'] } }, page) },
response: { $ref: 'TradeOfferList' }, errors: errs,
}, ({ user, query }) => trade.mineOffers(user.id, query));
router.get('/trade/offers/:id', {
summary: 'One offer (open ones to every operator of the world, closed ones to the two parties)', tag: 'trade', response: { $ref: 'TradeOfferResponse' }, errors: errs,
}, ({ user, params }) => trade.offer(user.id, params.id));
router.post('/trade/offers', {
summary: 'Post an offer from one of your POPs: give X of A for Y of B within a max distance. The offered amount is escrowed and a transport link reserved',
tag: 'trade', status: 201,
body: {
type: 'object', required: ['townId', 'giveRes', 'giveAmount', 'wantRes', 'wantAmount', 'maxDistance'],
properties: { townId: int1, giveRes: res, giveAmount: int1, wantRes: res, wantAmount: int1, maxDistance: { type: 'integer', minimum: 1, maximum: D.TRADE.maxDistance } },
},
response: { $ref: 'TradeOfferResponse' }, errors: errs.concat(['trade_ratio', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
}, ({ user, body }) => reply(201, commands.run('tradeOffer', Object.assign({ userId: user.id }, body))));
router.del('/trade/offers/:id', {
summary: 'Cancel your open offer; the escrow returns to the POP', tag: 'trade', response: { $ref: 'TradeCancelled' }, errors: errs.concat(['offer_closed', 'world_ended']),
}, ({ user, params }) => commands.run('tradeCancel', { userId: user.id, offerId: params.id }));
router.post('/trade/offers/:id/accept', {
summary: 'Take an open offer with one of your POPs: two transports leave at once (your payment, their goods) and the offer is settled when both arrive', tag: 'trade', status: 201,
body: { type: 'object', required: ['townId'], properties: { townId: int1 } },
response: { $ref: 'TradeAccepted' },
errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']),
}, ({ user, params, body }) => reply(201, commands.run('tradeAccept', { userId: user.id, offerId: params.id, townId: body.townId })));
}
module.exports = { register };

41
server/routes/world.js Normal file
View file

@ -0,0 +1,41 @@
'use strict';
/* End game: the race (world status), the final results, landing sites (read, feed the stockpile, build the node). Taking a site is
* POST /movements (scan / attack at its x,y). */
const { reply } = require('../http');
const { createEndgameQueries } = require('../endgameQueries');
const D = require('../../public/js/data.js');
function register(router, services) {
const { commands } = services;
const eg = createEndgameQueries(services);
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.get('/worlds/:id/status', {
summary: 'The state of the world: phase (running, backbone_open, ended), world age, the landing sites with holder, node level, stockpile and build progress, the winner', tag: 'world',
response: { $ref: 'WorldStatus' }, errors: errs,
}, ({ user, params }) => eg.status(user.id, params.id));
router.get('/worlds/:id/results', {
summary: 'The final ranking snapshot (operators, alliances, attackers, defenders, winner); available once the world has ended', tag: 'world',
response: { $ref: 'WorldResults' }, errors: errs,
}, ({ user, params }) => eg.results(user.id, params.id));
router.get('/backbone/:id', {
summary: 'One landing site; members of the holding alliance also see the contribution ledger and what they may do', tag: 'world',
response: { $ref: 'LandingSiteResponse' }, errors: errs,
}, ({ user, params }) => eg.site(user.id, params.id));
router.post('/backbone/:id/ship', {
summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 500 each)', tag: 'world', status: 201,
body: { type: 'object', required: ['fromTownId', 'cargo'], properties: { fromTownId: { type: 'integer', minimum: 1 }, cargo: { type: 'object', additionalProperties: true, description: 'fiber/hardware/capital -> amount' } } },
response: { $ref: 'MovementSent' },
errors: errs.concat(['forbidden', 'backbone_closed', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
}, ({ user, params, body }) => reply(201, commands.run('backboneShip', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, cargo: body.cargo })));
router.post('/backbone/:id/build', {
summary: 'Start the next Backbone node level on a landing site your alliance holds (paid from the site\'s stockpile; one level at a time, up to level ' + D.ENDGAME.maxLevel + ')', tag: 'world', status: 201,
response: { $ref: 'BackboneBuildStarted' },
errors: errs.concat(['forbidden', 'backbone_closed', 'max_level', 'already_queued', 'not_enough_resources', 'world_ended']),
}, ({ user, params }) => reply(201, commands.run('backboneBuild', { userId: user.id, siteId: params.id })));
}
module.exports = { register };