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

@ -128,3 +128,85 @@ nothing is spent. New POPs start with every field at level 0, no infrastructure,
## S3-9 — Moving units between your own POPs
`reinforce` to an own POP puts the units into `town_units` of the target (they live there now). Only units of OTHER operators are
`stationed` rows.
## S6-1 — Push hints leave only after the commit, through an outbox
`scheduler.notify` runs inside the transaction of the event or command, so pushing there would announce changes that may still roll
back. `notify` queues into `scheduler.outbox` (only when a listener is set); `process()` and `commands.run` flush it after COMMIT
(`db.depth === 0`) and truncate it to their mark on rollback. `town` hints use the existing `scheduler.onEvent` (post-commit already)
and a new `commands.hooks.onCommand`. `push.js` itself knows no game rules (it gets `townOwner` / `tokenValid` injected), the routing
lives in `pushHooks.js`. No new dependency (`ws` was already listed).
## S6-2 — Revocation is polled, not pushed
Tokens are revoked by plain SQL in routes and the admin tool. Instead of hooking each place, the ping tick (30 s) re-checks
`tokens.revoked_at` and `users.banned` for every authenticated socket and closes with 4401. Worst case 30 s of hints after logout on
another device; hints carry no data, so nothing leaks. If that is ever not good enough, call a `push.disconnectToken(id)` from the routes.
## S6-3 — Hints are merged per tick, `town` is not sent to the target at launch
Identical JSON hints produced in one tick (a catch-up) are deduplicated per socket via `setImmediate`. A launched movement tells the
target's owner `incoming` (town + ETA) and no plain `town` hint, so the type and origin of a launch cannot be inferred from extra traffic.
## E1 — A landing site is a row of its own, not a POP
`landing_sites(world_id, idx, x, y, holder_alliance_id, holder_operator_id, level, stockpile, build_*)` (migration 004), positions from
`rules.backboneSites(seed, radius)`. A town row of kind `landing` owned by the leader was considered and rejected: a "POP" that nobody plays
would have to be excluded from footprint rankings, the last-POP / capital / footprint-gate counts, `homeTownFor`, `/me`, spawn spacing and
the Rack hall cap (shipped resources would be thrown away at 250), and a leader change would have to re-own it. The holder is the
alliance (`holder_alliance_id`, FK `ON DELETE SET NULL`, the disband hook also clears it), `holder_operator_id` only records who took it.
Consequence, on purpose and to be revisited after the first world: **no units can stand at a site**, so there is no garrison and no
reinforcement. A site is defended by the static value `incumbentDefence x 12 x (1 + 0.03 x level)` only, i.e. exactly the "incumbent
with a backbone multiplier" of DESIGN.md; holders defend by growing the node (higher level = harder to take), attackers can scan the exact
number. Hooks into the military code are small: `combat.arriveSite` hands `backbone` tiles to `military/landing.js`,
`arrivals.arriveTransport` hands shipments (`extra.siteId`) to `endgame.deliverShipment`, `sendMovement` calls `endgame.checkLandingTarget`.
## E2 — Site rows are created lazily, there is no timer event
`ensureSites` creates the 7 rows when something first touches a site (an attack/scan sent or arriving, a shipment, a build) once the world is
at day 100 / speed; that first call also writes a `backbone_open` notification for every operator. Reads (`/worlds/:id/status`, `/map`, tile
info) never write: untouched sites are shown as the incumbent's, level 0, `id: null`. A `backboneOpen` event at world creation was
dropped: a pending event 100 days ahead sits in every quiet world and breaks tooling that counts pending events (the admin CLI test).
Cost: nobody is pushed the moment the sites appear unless a first touch happens; clients see `phase: backbone_open` when they poll status.
## E3 — The winner is fixed at level 100; the world is frozen when it ends
The holder of a node whose level completes at 100 wins (`worlds.winner_*`, once per world) and `worldEnd` is scheduled
`graceDays x 24 h / speed` later. Losing the node meanwhile does not change the winner (the race is over; the grace days are for the ranking
and the post-game). If a level-100 node is taken while nobody holds it (the holder disbanded mid-build) the new holder wins. `worldEnd`
writes the ranking snapshot, sets `status = 'ended'`, closes open trade offers (`expired`, escrow back in its POP: every unit stays accounted
for) and CANCELS every other pending event of the world: nothing arrives, trains,
expires or builds after the snapshot, so the stored ranking stays the truth. Movements still `out` and queued builds stay as they were.
A running build of a site continues for whoever holds the site when it lands (the level belongs to the site; the cost was paid from the
stockpile at the start); the stockpile and the ledger stay with the site when it is taken.
## E4 — `world_ended` is one gate in `commands.run`, found by probing the arguments
`ownedTown`, `operatorOf` and `requireRole` are shared with reads (rankings, map), so gating there would break "readable after the end".
`commands.run` calls `endgame.guard(db, name, args)`: the world is `args.worldId`, else the world of `townId/fromTownId/hostTownId`,
`allianceId`, `movementId`, `inviteId`, `proposalId`, `offerId`, `siteId`, `reportId`, else the caller's oldest operator (the default every
command already uses). Allowed after the end: `markReportRead`, `messageSend/Read/Delete`, `messageBlock/Unblock`. New commands are gated
automatically as long as they carry one of those arguments.
## E5 — Backbone cost curve is not the building curve
`4000 x 1.28^99` is unreachable; the node has its own `ENDGAME.costGrowth = 1.045` and `timeGrowth = 1.025` (about 7.2 M of each resource and
about 36 world days of building in total, level 100 alone 312 k each and 23 h). Pure guesses until a bot run (stage 7) says how much an
alliance can ship; nothing here is balanced.
## T1 — Trade: escrow, one link per side, reach by exchange level
- Offers are escrowed in `trade_offers` and hold one transport link of the poster's POP while open (`movements.activeLinks` counts open
offers), so accepting never fails for lack of a link on the poster's side and cannot exceed the exchange level.
- Each side of an offer must fit ONE transport (<= 500); larger deals are several offers. The ratio band is count-based 1:2.
- Escrow returns without the Rack hall cap (conservation beats the cap here); deliveries keep the existing cap rule (`cargoLost`).
- Reach: `10 tiles x exchange level` of the taker's POP, and the offer's own `maxDistance`; the poster's level only matters for the number of
offers they can hold open.
- A POP changing hands voids its open offers (`combat.transferTown` calls `trade.onTownTransferred`); the escrow stays in the POP.
- `transportArrived` hook: `server/trade.js` registers itself when required (both `commands/index.js` and `events/index.js` load it), so the
consumer exists in every test fixture that builds commands or events.
- Offer expiry: one `tradeExpire` event per offer, cancelled on accept/cancel/void, idempotent (acts only while `open`).
## T2 — Shared reports extend the report's life
Sharing sets `expires_at = max(expires_at, now + 14 days)` on the single shared `reports` row, so the folder is not emptied by a report that
was nearly due; the cascade `report_shares.report_id ... ON DELETE CASCADE` removes the share when the report is cleaned up.
## G1 — `buildDone` adds one level to what the building is NOW
Each build event adds exactly one level to the current level (never lowers, never above the queued `toLevel`), so an upgrade in flight
cannot undo exploit-kit damage; a building knocked to 0 comes back at 1. The notification reports the real level.
## G2 — Allied incoming is a separate list
`GET /movements` keeps `incoming` as "heading for YOUR POPs" and adds `alliedIncoming` for partners' POPs (own alliance + confederations),
each entry with `ally: true` and `toOperator`. Mixing them would make clients count allies' attacks as their own.