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

@ -0,0 +1,40 @@
'use strict';
/*
* POST /backbone/:id/build: start the next Backbone node level on a landing site your alliance holds. The level's cost comes out
* of the site's stockpile (shipped in by the holders, see backboneShip) at once; one level at a time; the level lands when the
* `backboneDone` event runs. Needs the `backboneBuild` permission.
*/
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { loadWorld } = require('../state');
const A = require('../alliances');
const E = require('../endgame');
const ctxOf = require('../military/ctx');
// The site, the caller's operator in its world, and proof that the caller's alliance holds it. Shared with backboneShip.
function holderContext(db, userId, siteId, now) {
const site = E.siteRow(db, siteId);
if (!site) throw new GameError('not_found', { what: 'landing site' });
const world = loadWorld(db, site.world_id);
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, site.world_id);
if (!op) throw new GameError('not_found', { what: 'landing site' });
if (!E.isOpen(world, now)) throw new GameError('backbone_closed', { opensAtDay: require('../../public/js/data.js').ENDGAME.openDay });
const m = A.membership(db, op.id);
if (!site.holder_alliance_id || !m || m.alliance_id !== site.holder_alliance_id) throw new GameError('forbidden', { need: 'holder' });
return { site, world, op, member: m };
}
module.exports = function backboneBuild(ctx0, { userId, siteId }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const { site, world, op, member } = holderContext(db, userId, siteId, now);
if (!R.allianceCan(member.role, 'backboneBuild')) throw new GameError('forbidden', { need: 'backboneBuild', role: member.role });
const plan = R.backbonePlan({ level: site.level, build: site.build_to ? { to: site.build_to } : null, pool: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } }, world.speed);
if (!plan.ok) throw new GameError(plan.code, { siteId: site.id, toLevel: plan.toLevel, cost: plan.cost, have: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } });
const dueAt = now + plan.durationMs;
const ev = ctx.enqueue({ worldId: site.world_id, dueAt, type: 'backboneDone', payload: { siteId: site.id, toLevel: plan.toLevel, by: op.id } });
db.run(`UPDATE landing_sites SET fiber = fiber - ?, hardware = hardware - ?, capital = capital - ?, build_to = ?, build_event_id = ?, build_started_at = ?, build_due_at = ?, build_cost = ? WHERE id = ?`,
plan.cost.fiber, plan.cost.hardware, plan.cost.capital, plan.toLevel, ev, now, dueAt, JSON.stringify(plan.cost), site.id);
return { siteId: site.id, eventId: ev, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost };
};
module.exports.holderContext = holderContext;

View file

@ -0,0 +1,23 @@
'use strict';
/*
* POST /backbone/:id/ship {fromTownId, cargo}: send resources from one of your POPs to a landing site your alliance holds, to
* feed its stockpile. A normal transport (same links, 500 per link, 12 tiles/h) whose target is the site's tile; on arrival it is
* added to the stockpile if the sender's alliance still holds the site, otherwise it rides home.
*/
const { GameError } = require('../errors');
const { settle } = require('../state');
const { ownedTown } = require('./build');
const { launchTransport } = require('./sendTransport');
const { holderContext } = require('./backboneBuild');
const ctxOf = require('../military/ctx');
module.exports = function backboneShip(ctx0, { userId, siteId, fromTownId, cargo }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const { site } = holderContext(db, userId, siteId, now);
const from = ownedTown(db, userId, fromTownId);
if (from.worldId !== site.world_id) throw new GameError('not_found', { what: 'town' });
settle(db, from, now);
const mv = launchTransport(ctx, from, { x: site.x, y: site.y }, cargo || {}, { siteId: site.id });
return { movementId: mv.id, type: 'transport', siteId: site.id, fromTownId: from.id, toTownId: null, to: { x: site.x, y: site.y }, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt };
};

View file

@ -40,19 +40,35 @@ const handlers = {
messageDelete: require('./messageDelete'),
messageBlock: require('./messageBlock').messageBlock,
messageUnblock: require('./messageBlock').messageUnblock,
// trade, end game, shared reports
reportShare: require('./reportShare').reportShare,
reportUnshare: require('./reportShare').reportUnshare,
tradeOffer: require('./tradeOffer'),
tradeCancel: require('./tradeCancel'),
tradeAccept: require('./tradeAccept'),
backboneBuild: require('./backboneBuild'),
backboneShip: require('./backboneShip'),
};
function createCommands({ db, clock, scheduler }) {
// hooks.onCommand(name, args, out): optional, called after a command committed (stage 6 push). Never throws into the caller.
const hooks = { onCommand: null };
function run(name, args) {
const fn = handlers[name];
if (!fn) throw new Error('unknown command ' + name);
scheduler.runDue();
require('../endgame').guard(db, name, args); // an ended world refuses every command except reading state and chatting
const now = clock.now();
const out = db.tx(() => fn({ db, clock, now, scheduler }, args));
const mark = scheduler.outboxMark();
let out;
try { out = db.tx(() => fn({ db, clock, now, scheduler }, args)); }
catch (err) { scheduler.outboxRollback(mark); throw err; }
scheduler.flushOutbox(); // notifications written by the command go out now that it is committed
if (hooks.onCommand) { try { hooks.onCommand(name, args, out); } catch (e) { if (scheduler.log) scheduler.log('onCommand hook failed: ' + e.message); } }
scheduler.arm();
return out;
}
return { run, handlers };
return { run, handlers, hooks };
}
module.exports = { createCommands };

View file

@ -0,0 +1,51 @@
'use strict';
/*
* The alliance's shared report folder. Two commands in one file (registered separately in commands/index.js):
* reportShare { userId, reportId } put one of YOUR reports into your alliance's folder (needs `shareReport`)
* reportUnshare { userId, reportId } take it out again: whoever shared it, or `unshareReport` (leader, officer)
* The alliance is the caller's alliance in the report's world. Sharing an already shared report changes nothing
* ({ changed: false }). A shared report lives at least reportRetentionMs from the moment it was shared (the expiry is pushed
* out; it is one row for everybody, so the participants keep it that long too) and is deleted with the report.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const A = require('../alliances');
const { ensureCleanup } = require('../military/reports');
function context(db, userId, reportId) {
const rep = db.get(`SELECT r.id, r.world_id, r.expires_at FROM reports r JOIN report_recipients rr ON rr.report_id = r.id AND rr.user_id = ? WHERE r.id = ?`, userId, reportId);
if (!rep) throw new GameError('not_found', { what: 'report' }); // not yours: never reveal it exists
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, rep.world_id);
if (!op) throw new GameError('not_found', { what: 'report' });
const m = A.membership(db, op.id);
if (!m) throw new GameError('not_in_alliance');
return { rep, op, member: m };
}
function reportShare(ctx, { userId, reportId }) {
const { db, now } = ctx;
const { rep, op, member } = context(db, userId, reportId);
if (!R.allianceCan(member.role, 'shareReport')) throw new GameError('forbidden', { need: 'shareReport', role: member.role });
const r = db.run('INSERT OR IGNORE INTO report_shares (report_id, alliance_id, shared_by, created_at) VALUES (?, ?, ?, ?)', rep.id, member.alliance_id, op.id, now);
if (!r.changes) return { changed: false, reportId: rep.id, allianceId: member.alliance_id };
const until = now + D.MILITARY.reportRetentionMs;
if (rep.expires_at < until) db.run('UPDATE reports SET expires_at = ? WHERE id = ?', until, rep.id);
ensureCleanup(ctx, rep.world_id, now);
return { changed: true, reportId: rep.id, allianceId: member.alliance_id };
}
function reportUnshare(ctx, { userId, reportId }) {
const { db } = ctx;
// the report may no longer list the caller as a recipient (it is only theirs through the alliance): look the share up directly
const share = db.get(`SELECT s.*, r.world_id FROM report_shares s JOIN reports r ON r.id = s.report_id WHERE s.report_id = ?
AND s.alliance_id IN (SELECT m.alliance_id FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE o.user_id = ?)`, reportId, userId);
if (!share) throw new GameError('not_found', { what: 'shared report' });
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, share.world_id);
const member = A.membership(db, op.id);
if (op.id !== share.shared_by && !R.allianceCan(member.role, 'unshareReport')) throw new GameError('forbidden', { need: 'unshareReport', role: member.role });
db.run('DELETE FROM report_shares WHERE report_id = ? AND alliance_id = ?', share.report_id, share.alliance_id);
return { changed: true, reportId: share.report_id, allianceId: share.alliance_id };
}
module.exports = { reportShare, reportUnshare };

View file

@ -18,7 +18,7 @@ const TYPES = ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle'];
const HOSTILE = ['raid', 'attack', 'takeover'];
// The target of a movement: a POP (by id or by tile) or a bare tile. -> { town: row|null, x, y, tile }
function resolveTarget(db, world, args) {
function resolveTarget(db, world, args, now) {
let town = null, x, y;
if (args.toTownId !== undefined && args.toTownId !== null) {
town = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', args.toTownId, world.id);
@ -30,7 +30,7 @@ function resolveTarget(db, world, args) {
} else {
throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'give toTownId or x and y' }] });
}
const tile = R.tileAt(world.seed, world.map_radius, x, y);
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
if (tile.type === 'void') throw new GameError('invalid_target', { reason: 'outside_map' });
return { town, x, y, tile };
}
@ -52,7 +52,7 @@ module.exports = function sendMovement(ctx0, args) {
for (const k of Object.keys(units)) if ((home[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: home[k] || 0, want: units[k] });
if (!P.online(from, now)) throw new GameError('units_offline', { townId: from.id });
const tgt = resolveTarget(db, world, args);
const tgt = resolveTarget(db, world, args, now);
if (tgt.town && tgt.town.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' });
const dist = R.distance(from.x, from.y, tgt.x, tgt.y);
const arriveAt = now + R.movementMs(dist, units, world.speed);
@ -81,6 +81,10 @@ module.exports = function sendMovement(ctx0, args) {
}
} else if (tgt.tile.type === 'incumbent') {
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'incumbent_scan_or_attack_only' });
} else if (tgt.tile.type === 'backbone') {
require('../endgame').checkLandingTarget(db, world, op, tgt, type, now, ctx); // scan or attack only, alliance members, no pact partners
} else if (R.isBackboneSite(world.seed, world.map_radius, tgt.x, tgt.y)) {
throw new GameError('backbone_closed', { opensAtDay: D.ENDGAME.openDay }); // the landing site is not there yet
} else {
throw new GameError('invalid_target', { reason: 'nothing_there' });
}
@ -98,7 +102,7 @@ module.exports = function sendMovement(ctx0, args) {
const own = U.operatorTowns(db, op.id);
let nearest = Infinity;
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, tgt.x, tgt.y));
const chk2 = R.settleCheck({ tileType: tgt.tile.type, occupied: !!tgt.town, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
const chk2 = R.settleCheck({ tileType: tgt.tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, tgt.x, tgt.y), occupied: !!tgt.town, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
if (!chk2.ok) throw new GameError(chk2.code, chk2);
extra.wild = R.cleanWild(args.wild);
}

View file

@ -0,0 +1,54 @@
'use strict';
/*
* POST /trade/offers/:id/accept {townId}: take an open offer with one of your POPs. In ONE transaction:
* - the payment (the wanted resource) leaves the acceptor's POP as a transport to the poster's POP (needs a free link there,
* the usual transport rules: capacity, resources),
* - the poster's escrow leaves as a transport to the acceptor's POP (on the link the open offer held in reserve),
* - the offer becomes `accepted`; it is `completed` when both transports have been delivered (see server/trade.js).
* Any failure rolls everything back. Not your own offer; the acceptor's POP needs an Internet exchange and must be in range
* (the offer's max distance and the exchange's reach).
*/
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { settle, loadWorld } = require('../state');
const { ownedTown } = require('./build');
const { launchTransport } = require('./sendTransport');
const ctxOf = require('../military/ctx');
const M = require('../military/movements');
const T = require('../trade');
module.exports = function tradeAccept(ctx0, { userId, offerId, townId }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const o = T.getOffer(db, offerId);
const mine = ownedTown(db, userId, townId);
if (!o || o.world_id !== mine.worldId) throw new GameError('not_found', { what: 'offer' });
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
if (mine.ownerId === o.operator_id) throw new GameError('own_offer');
const poster = db.get('SELECT * FROM towns WHERE id = ?', o.town_id);
if (!poster || poster.owner_id !== o.operator_id) throw new GameError('offer_closed', { status: 'void' });
const level = R.transportLinks(mine);
const dist = R.distance(mine.x, mine.y, poster.x, poster.y);
if (level < 1) throw new GameError('no_transport_link', { links: 0, active: 0 });
if (!R.tradeInRange(dist, o.max_distance, level)) throw new GameError('trade_out_of_range', { distance: dist, maxDistance: o.max_distance, reach: R.tradeReach(level) });
settle(db, mine, now);
// acceptor -> poster: the wanted resource (validates links, capacity and resources, deducts, inserts the movement)
const pay = launchTransport(ctx, mine, poster, { [o.want_res]: o.want_amount }, { tradeId: o.id, role: 'payment' });
// poster -> acceptor: the escrow
const world = loadWorld(db, o.world_id);
const goods = M.insertMovement(ctx, {
worldId: o.world_id, ownerId: o.operator_id, type: 'transport', fromTownId: poster.id, toTownId: mine.id,
from: { x: poster.x, y: poster.y }, to: { x: mine.x, y: mine.y }, units: {}, cargo: { [o.give_res]: o.give_amount },
departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: { tradeId: o.id, role: 'goods' },
});
db.run("UPDATE trade_offers SET status = 'accepted', accepted_by_operator = ?, accepted_town_id = ?, accepted_at = ?, goods_movement_id = ?, payment_movement_id = ? WHERE id = ?",
mine.ownerId, mine.id, now, goods.id, pay.id, o.id);
if (o.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, o.expire_event_id);
const posterUser = T.userOfOperator(db, o.operator_id);
if (posterUser) ctx.notify(posterUser, o.world_id, 'trade_accepted', { offerId: o.id, townId: poster.id, byTownId: mine.id, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount } });
return {
offerId: o.id, status: 'accepted', goodsMovementId: goods.id, paymentMovementId: pay.id, distance: dist,
arriveAt: goods.arriveAt, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount },
};
};

View file

@ -0,0 +1,15 @@
'use strict';
/* DELETE /trade/offers/:id: take your open offer back; the escrow returns to the POP. */
const { GameError } = require('../errors');
const ctxOf = require('../military/ctx');
const T = require('../trade');
module.exports = function tradeCancel(ctx0, { userId, offerId }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const o = T.getOffer(db, offerId);
if (!o || T.userOfOperator(db, o.operator_id) !== userId) throw new GameError('not_found', { what: 'offer' });
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
T.closeOffer(ctx, o, 'cancelled', now);
return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: o.give_amount } };
};

View file

@ -0,0 +1,33 @@
'use strict';
/*
* POST /trade/offers: "give X of A for Y of B, max distance Z" from one of your POPs with an Internet exchange. The offered
* amount leaves the POP now (escrow), one transport link stays reserved for it, and the offer expires after TRADE.ttlHours
* (divided by world speed). Both amounts must fit one transport link and differ by at most 1:2.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, spend } = require('../state');
const { ownedTown } = require('./build');
const M = require('../military/movements');
const T = require('../trade');
module.exports = function tradeOffer(ctx, { userId, townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance }) {
const { db, now, scheduler } = ctx;
const town = ownedTown(db, userId, townId);
const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance });
if (!terms.ok) throw new GameError(terms.code, terms);
const links = R.transportLinks(town);
const inUse = M.activeLinks(db, town.id);
if (links < 1 || inUse >= links) throw new GameError('no_transport_link', { links, active: inUse });
settle(db, town, now);
if (R.resourcesAt(town, now).amounts[giveRes] + 1e-6 < giveAmount) throw new GameError('not_enough_resources', { resource: giveRes, want: giveAmount });
spend(db, town, { [giveRes]: giveAmount });
const expiresAt = now + T.expiryMs(town.speed);
const id = Number(db.run(`INSERT INTO trade_offers (world_id, town_id, operator_id, give_res, give_amount, want_res, want_amount, max_distance, status, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)`, town.worldId, town.id, town.ownerId, giveRes, giveAmount, wantRes, wantAmount, maxDistance, now, expiresAt).lastInsertRowid);
const ev = scheduler.enqueue({ worldId: town.worldId, dueAt: expiresAt, type: 'tradeExpire', townId: town.id, payload: { offerId: id } });
db.run('UPDATE trade_offers SET expire_event_id = ? WHERE id = ?', ev, id);
const o = T.getOffer(db, id);
return { offer: T.offerView(db, o, new Map([[town.id, town]])) };
};