Upstream/docs/API.md
jvanvik 3c23c51902 Phase 4: close loot/refund leaks, landing-site garrisons, speed-scaled shipping, update/offsite tooling, broad e2e
Built:
- Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds).
- End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x).
- Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in.
- e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English.

Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented).
NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-12 00:58:12 +02:00

24 KiB

API

REST JSON under /api/v1/. The machine-readable contract is docs/openapi.json, generated from the route table (npm run openapi); this file covers conventions and per-resource notes.

Conventions

  • Auth: Authorization: Bearer <token> (opaque, one per device; POST /auth/login or /auth/signup issues one, POST /auth/logout and DELETE /auth/tokens/:id revoke). No cookies.
  • Every response is an object with serverTime (integer ms since epoch, server clock). Clients compute countdowns from the offset.
  • Errors: { serverTime, error: { code, message, details } }. Clients switch on code. All codes: x-error-codes in openapi.json.
  • Mutating POSTs accept Idempotency-Key (8-64 chars A-Za-z0-9_.:-); a replay returns the stored response with Idempotent-Replay: true (keys are kept 24 h); the same key with a different request is idempotency_key_reuse.
  • Lists are cursor-paginated: ?after=<id>&limit=<n>, response next is the cursor or null.
  • Rate limits (token buckets, server/http.js): per client address 30 requests/s sustained, burst 90 (IPv6 clients share one bucket per /64); per token 15/s, burst 45; login and signup per address about 1 per 10 s, burst 8, plus a per-username login throttle. 429 rate_limited with Retry-After / details.retryAfter. Request bodies are capped at 32 KB. Message and WebSocket limits are separate (below, PROTOCOL.md).
  • The client never sends computed amounts, only intents. The server recomputes everything with public/js/rules.js.

Accounts, POPs, map (stage 0-2)

Route Purpose
POST /auth/signup {username, password, invite?, worldId?, device?} account + token (201); founds the capital POP; invite is required only when the server has SIGNUP_CODE set (signup_closed otherwise)
POST /auth/login token for another device (invalid_credentials, forbidden when banned)
GET /auth/tokens, DELETE /auth/tokens/:tokenId, POST /auth/logout list this account's active device tokens, revoke one, revoke the current one
GET /me user, operators (per world), POPs
POST /me/join {worldId?} an account with no operator (world reset, new world) founds its capital POP (201, returns /me); 409 conflict if already joined
GET /towns/:id full POP state: resources {amount, rate, cap} at serverTime (cap = Rack hall size minus the goods escrowed in open trade offers, escrow = those goods per resource), power, buildings with the server's build plan, queue
POST /towns/:id/build {key} build/upgrade one level of a field (f1..f18) or an infrastructure building
DELETE /towns/:id/queue/:eventId cancel a running build, 80% refund
POST /towns/:id/rename {name} rename a POP (2-40 chars)
GET /map?x&y&r rural areas, incumbent sites, POPs in the viewport
GET /notifications?after&limit durable notification feed (build done, ...), pruned after 30 days

Social (stage 5)

worldId is optional everywhere a caller's operator is needed (default: their oldest operator). Most commands are idempotent where that makes sense and answer { changed: false } when there was nothing to do (leaving twice, kicking someone already gone, accepting an invite twice). forbidden carries details.need (the missing permission).

Alliances. Roles leader, diplomat, officer, member; the permission table is SOCIAL.permissions in data.js (GET /alliances/mine returns the caller's permissions). Founding and joining need a Peering office level >= 1 on one of the operator's POPs (peering_office_required). Size cap: 10 + 2 * level of the founder's best Peering office when founding, stored; it is raised (never lowered) whenever a command runs that depends on it (invite, accept, transfer) if the current leader's best office would give more; reads show the effective cap. One alliance per operator.

Route Purpose
POST /alliances {name, tag} found (201); name 3-30 chars, tag 2-5 letters/digits, both unique per world, case-insensitive
GET /alliances?q&after&limit, GET /alliances/mine, GET /alliances/:id directory (cursor: id), your alliance + role + permissions, public profile (size, leader, summed footprint, your relation)
GET /alliances/:id/members members only: role, POP count, footprint, lastOnline (newest token use of the user, updated at most once a minute); bounded by the cap, so not paginated (next is always null)
POST /alliances/:id/invite {operatorId | name}, GET /alliances/:id/invites, DELETE /alliances/:id/invites/:inviteId invite (201; repeating returns the pending invite with 200), list sent, cancel. Invites expire after 7 days (real time)
GET /alliance-invites, POST /alliance-invites/:id/accept, POST /alliance-invites/:id/decline the invitee's side
POST /alliances/:id/leave, /kick {operatorId}, /role {operatorId, role}, /transfer {operatorId}, /disband leaving (the leader must transfer first, or is alone and disbands), kick (only members the actor outranks), set role (leader only), hand over leadership, disband
GET/POST /alliances/:id/notes, POST/DELETE /alliances/:id/notes/:noteId pinned notes (max 10, 1000 chars, plain text)

Diplomacy. States war, neutral, nap, confed. POST /alliances/:id/diplomacy {targetId, state} answers with result: applied (declaring war from neutral takes effect at once), proposed (pacts, and peace out of war: the other alliance must accept within 72 h, real time) or scheduled (cancelling a pact, or going to war out of one, takes 24 h / world speed: effectiveAt, applied by the diploChange event). While a change is scheduled the old state holds and further changes between the pair are diplomacy_pending; the alliance that started it can take it back. The move table is SOCIAL.diplomacyMoves.

Route Purpose
GET /alliances/:id/diplomacy members only: relations (with scheduled change), incoming and outgoing open proposals
POST /diplomacy/proposals/:proposalId/accept / .../decline, DELETE /diplomacy/proposals/:proposalId answer (receiving alliance) / withdraw (proposing alliance); all need diplomacy
DELETE /alliances/:id/diplomacy/:otherId/pending revoke a scheduled cancel you started

Notification types written: alliance_invite, alliance_invite_declined, alliance_member_joined, alliance_member_left, alliance_kicked, alliance_role, alliance_leader, alliance_disbanded, diplomacy_proposal, diplomacy_declined, diplomacy_changed, diplomacy_cancel_pending, diplomacy_cancel_revoked, message, alliance_message.

Messages. Plain text, 1-2000 characters; control characters, bidi overrides and invisible characters are stripped (server/text.js) before anything is stored. Lists are newest first and the cursor is the last id of the previous page (?after=<next> gives the next, older page). Sending is limited per sender by counting their recent messages (15 DMs / 10 min, 60 DMs / h, 20 alliance broadcasts / h, SOCIAL.messageLimits): 429 rate_limited with details.retryAfter. Deleting removes only your own copy. A recipient who blocked the sender gets nothing; the sender is not told (recipients: 0).

Route Purpose
POST /messages {toOperatorId | toName | toAlliance, text} send (201)
GET /messages/inbox?unread, /messages/outbox, /messages/thread/:operatorId, /messages/alliance lists; the inbox also returns unread
GET /messages/:id, DELETE /messages/:id, POST /messages/read {ids | all} one message, delete own copy, mark read
GET/POST /messages/blocks, DELETE /messages/blocks/:operatorId block list (max 100)

Rankings. GET /rankings/operators (footprint, rules.footprintAt over the operator's POPs), /rankings/alliances (sum over members), /rankings/battles?by=attack|defense|total (from operator_stats, available: false and empty when that table does not exist). The cursor is a rank offset (next = ranks already seen). Each response has total and you (the caller's own entry).

GET /me operators and GET /map town owners now carry alliance: { id, tag, name } | null next to allianceId.

Military and expansion (stages 3-4)

Units are plain { unitId: count } objects with the generic ids of data.UNITS (port_scanner, soc_analyst, blue_team, honeypot, script_crew, botnet, ddos_rig, exploit_kit, rollout_crew, ma_team); names live in i18n.js. GET /towns/:id now carries town.military: units at home (online flag, offlineSince), reinforcements standing here and away, units.garrisoned [{siteId, x, y, units}] (this POP's units standing in backbone landing sites: they draw this POP's power), the training queue, what can be trained (cost, time, missing requirements), research levels and queue, transport links, and this POP's outgoing/incoming movements. Nothing resolves when you send it: combat, loot and arrival happen in the event queue at the arrival time, and reports and notifications (incoming, report, train_done, research_done, movement_returned, movement_lost, transport_arrived, transport_delivered, reinforcements_sent_home, units_offline, units_decommissioned, town_lost, town_gained; build_done for buildings) tell you afterwards.

Route Purpose
POST /towns/:id/train {unit, count} queue a batch (201). Batches of one training building (NOC / Ops lab / Rollout depot) run in order, buildings in parallel; queue limit 8 per building (queue_full)
POST /towns/:id/research {unit, stat} +5% attack or defence per level for one unit type, one research at a time per POP, level n needs a Research lab of level n + 2
POST /movements {fromTownId, type, toTownId | x,y, units, ...} send scan, raid, attack, takeover, reinforce, settle (201). type: transport carries cargo: {fiber, hardware, capital} (Internet exchange: level = concurrent transports, each carries rules.transportCapacity(speed) = 1000 x the world speed; the POP view's transport.capacityPerLink already says the real number). Extra fields: target (building for exploit kits), wild (two field types for a new POP), confirmEndProtection
GET /movements your active movements (full detail, recallableUntil) and incoming ones from others: origin and ETA only, type: "unknown"
POST /movements/:id/recall turn an outbound movement around within the first 90 s (recall_expired after)
POST /towns/:id/withdraw {ownerTownId, units?} reinforcements in this POP go home (host kicks them out, or their owner calls them back)
GET /reports?after&limit&unread, GET /reports/:id, POST /reports/:id/read, POST /reports/read-all reports, newest first: after = id of the last report you have, the next page holds older ones. One shared row per battle, per-user read flag; kept 14 days
GET /map/tile?x&y public facts about one tile for the send dialog: what is there, owner/protection, distance from each of your POPs, whether you could settle it (settle.possible/code)

Rules the server enforces on POST /movements (error codes in x-error-codes): not_enough_units, units_offline (battery empty), invalid_target (details.reason: own town, nothing there, pact partner, not allied, occupied tile ...), target_protected (beginner protection still running at the arrival time; scans are allowed), protection_active (attacking from protected status needs confirmEndProtection: true and ends your protection), cannot_takeover (last POP), footprint_too_low / out_of_range (settle and takeover), capacity_exceeded / no_transport_link (transport). Pact partners (same alliance, NAP, confederation) cannot raid, attack or take over each other; only the same alliance or a confederation may reinforce. The server re-checks target, protection and pact when the movement arrives and bounces it (units come home, a movement_failed report says why) if something changed.

Report types: raid, attack, takeover (the same combat report: outcome, both sides' units and losses, attack/defence values, firewall, loot, lootLeft (what the raiders could carry and the target had, but their home Rack hall had no room for: it stayed with the target), siege, takeover/loyalty), scan (attacker; intel when it succeeded), scan_detected (defender; attacker identity only if the defender's scanners won), incumbent, settle, reinforce, movement_failed.

Later stages append their routes here and to the route table.

Trade, end game, shared reports (stage 5 rest, stage 7 start)

Internet exchange trade. Offers "give X of A for Y of B within Z tiles". Amounts are whole numbers, each side 1..1000 (one transport link), the two amounts differ by at most 1:2, the resources differ; maxDistance 1..300. Lists are newest first, after = id of the last offer you have (older ones follow). status: open, accepted, completed, cancelled, expired, void.

Route Purpose
POST /trade/offers {townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance} post (201). The offered amount leaves the POP (escrow) and one transport link is held in reserve. trade_ratio, capacity_exceeded, no_transport_link (no exchange, or all links busy/reserved), not_enough_resources
GET /trade/offers?worldId&townId&give&want&after&limit open offers of others that one of your POPs (or townId) can take: within min(maxDistance, 10 x exchange level). Each carries acceptableFrom: [{townId, distance}]; exchangeLevels lists your exchanges and their reach
GET /trade/offers/mine?worldId&status&after&limit offers you posted or accepted, any status, with role
GET /trade/offers/:id one offer: open ones to every operator of the world, closed ones to the two parties (not_found otherwise)
DELETE /trade/offers/:id cancel your open offer; the escrow returns to the POP and always fits: open escrow keeps its room in the Rack hall (GET /towns/:id resources[r].cap is hall size minus escrow, escrow lists it). Only a Rack hall shot down meanwhile can clip the refund; returned.amount is what was credited and a trade_refund_clipped notification says what was lost (BALANCE.md S2). offer_closed when it is not open
POST /trade/offers/:id/accept {townId} take it with one of your POPs (201): two transports leave at once (your payment, their goods); own_offer, offer_closed, trade_out_of_range, no_room_for_goods (your Rack hall would not have room for the goods when they arrive, projected with production and other cargo on its way: refused up front because overflow on arrival is destroyed), no_transport_link, not_enough_resources; all or nothing

Notifications: trade_accepted (poster), trade_completed (both, when both transports arrived), trade_expired (returned = what was credited), trade_refund_clipped {offerId, townId, resource, lost, credited} (a refund did not fit, rare), trade_void (the POP was taken over). Delivery notifications are the existing transport_arrived / transport_delivered. Direct transports (own POPs, any player) stay POST /movements with type: "transport".

World status and the end game. The backbone sites open at world day 100 (real days x speed).

Route Purpose
GET /worlds/:id/status phase (running, backbone_open, ended), ageDays, opensAt, the 7 sites (empty before opening: id (null until first touched), index, x, y, holder {allianceId, tag, name} or null = incumbent, takenBy, level/maxLevel/progress, pool (stockpile), build {toLevel, startedAt, dueAt}, next {toLevel, cost, durationMs}), winner, endsAt (set once somebody won), endedAt
GET /worlds/:id/results the final snapshot once ended (available: false before): winner, results.{operators, alliances, attackers, defenders, sites, totals} (top 100 each, ranked)
GET /backbone/:id one site (shieldUntil is set while a site that just changed hands cannot be attacked); holders also get contributions (who shipped what), you {holder, canBuild, canShip, canAttack, canReinforce}, defence {static, garrison, total} and garrison [{ownerTownId, townName, operator, units, online, power, mine}] (the units its members stationed there)
POST /backbone/:id/withdraw {fromTownId, units?} call units of one of YOUR POPs home from the site's garrison (201; default all of them; only their owner; works whoever holds the site); not_enough_units, not_found
POST /backbone/:id/ship {fromTownId, cargo} send resources to a site your alliance holds (201, a transport: same links and capacity); arrives into the stockpile, or rides home if the site changed hands
POST /backbone/:id/build start the next node level (201), paid from the stockpile at once, one level at a time, any holder with backboneBuild; max_level, already_queued, not_enough_resources, forbidden (not a holder), backbone_closed

Taking a site is POST /movements with type: "scan" or "attack" and the site's x, y (no toTownId): needs an alliance, not against the own alliance or a NAP/confederation partner (invalid_target, details.reason: no_alliance, own_site, pact, landing_scan_or_attack_only, site_shielded + details.until); before opening backbone_closed. Settling a landing tile is invalid_target (backbone_site), also before it opens. Garrison: POST /movements with type: "reinforce" and the site's x, y stations units there; only members of the holding alliance (invalid_target, details.reason: not_holder; checked again at arrival, the units turn back with a movement_failed report otherwise). Defence = static (incumbentDefence x M x (1 + 0.03 x node level), M 12 unheld / 2 held) + the garrison (online groups, with their owners' research); a scan report shows intel.static, intel.garrison {units, power} and intel.defence (the sum). A landing report adds defender.garrison (per owner POP: sent, lost, survivors, offline) and power.static / power.garrison. Reports: scans as scan (with site.type: "backbone"), attacks as the new type landing (outcome, attack/defence, taken; recipients: the attacker and every member of the previous holder). GET /map lists open sites in specials as type: "backbone" with site: {id, index, holder, level, maxLevel}; GET /map/tile returns type: "backbone" and backbone: {siteId, holder, level, pool, build, mine, canAttack}.

Notifications: backbone_open (first touch), backbone_taken / backbone_lost (alliance members), backbone_incoming (holder members: a scan or attack was sent at their site, {siteId, index, x, y, arriveAt}, no type, no sender), garrison_arrived / garrison_released (the owner of the units; reason: alliance_dissolved, left_alliance, town_lost), backbone_level (every 10th level and the last, holder members), backbone_delivered / backbone_ship_bounced (sender), backbone_won (everybody), world_ended (everybody).

An ended world answers every game command with 409 world_ended (build, send, train, trade, alliances, diplomacy, backbone, report sharing, ...). Still allowed: GET everything (map, reports, rankings, towns, status, results), POST /reports/read-all, POST /reports/:id/read, messages (send, read, delete, block).

Shared report folder. POST /reports/:id/share puts one of YOUR reports into your alliance's folder (needs shareReport; the report is kept 14 days from the share), DELETE /reports/:id/share takes it out (the sharer, or unshareReport: leader, officer), GET /alliances/:id/reports?after&limit lists the folder newest first (cursor: id of the last report seen), GET /alliances/:id/reports/:reportId reads one with its full data. Members with viewSharedReports only; GET /alliances/mine permissions list the new keys.

Allied incoming. GET /movements has a new alliedIncoming list: movements heading for POPs of your alliance mates and of confederated alliances, same shape as incoming (type unknown, origin and ETA only) plus ally: true and toOperator. Friendly traffic (from partners of the target) is left out.

Notification types (complete list)

Every row of GET /notifications has type and a payload; derived from the notify calls in server/ (the list grows: clients treat an unknown type as generic). WebSocket hint {type:"notification", id, kind} carries the same type as kind (docs/PROTOCOL.md). cargoLost is {resource: amount} of what did not fit the Rack hall, exact, only the resources that lost something (rest of the cargo was stored).

type to payload
build_done owner {townId, key, type, level}
train_done owner {townId, unit, count}
research_done owner {townId, unit, stat, level, key}
incoming target's owner {movementId, toTownId, fromTownId, arriveAt} (movement type hidden)
report report recipients {reportId, type, role}
movement_returned owner {movementId, townId, units, cargo, cargoLost}; also for a bounced shipment that carries cargo home (backbone, trade): cargoLost says exactly what the full hall destroyed
movement_lost owner {movementId} (no POP left to go home to)
transport_arrived receiver {movementId, townId, fromTownId, cargo, cargoLost, own}
transport_delivered sender (when not the receiver) {movementId, toTownId, cargo, cargoLost}
reinforcements_sent_home owner of the units {hostTownId, ownerTownId, units}
units_offline owner {townId, since} (battery empty)
units_decommissioned owner {townId, units} (24 h offline)
town_lost / town_gained old / new owner {townId, name, by} / {townId, name}
trade_accepted poster {offerId, townId, byTownId, give, want}
trade_completed both parties see the trade section
trade_expired poster {offerId, townId, returned: {resource, amount}}
trade_refund_clipped poster {offerId, townId, resource, lost, credited}
trade_void poster {offerId, townId} (the POP changed hands)
backbone_open everybody {sites: [{siteId, index, x, y}]} (first touch after the sites open)
backbone_taken / backbone_lost attacker's / old holder alliance site and alliance brief
backbone_incoming holder alliance {siteId, index, x, y, arriveAt} (a scan or attack was sent; no type, no sender)
backbone_level holder alliance {siteId, index, level}
backbone_delivered sender {movementId, siteId, cargo}
backbone_ship_bounced sender {movementId, siteId, cargo} (site changed hands: the cargo rides home, movement_returned follows with cargoLost)
backbone_won everybody {allianceId, name, tag, siteId, endsAt}
world_ended everybody {winner, endedAt}
garrison_arrived owner of the units {siteId, index, ownerTownId, units}
garrison_released owner of the units {siteId, index, ownerTownId, reason, units, movementId}; reason: alliance_dissolved, left_alliance, town_lost (a voluntary withdraw sends no notification)
alliance_invite / alliance_invite_declined invited operator / inviter {inviteId, allianceId, tag, name, by, expiresAt} / {inviteId, allianceId, by}
alliance_member_joined / alliance_member_left alliance members {allianceId, operatorId, name} (kicked on left)
alliance_kicked the kicked operator {allianceId, tag, name}
alliance_role the operator {allianceId, tag, from, role}
alliance_leader alliance members {allianceId, operatorId, name, from}
alliance_disbanded alliance members {reason, ...alliance brief}
alliance_message / message recipient {messageId, ...} (from, allianceId/tag)
diplomacy_proposal / diplomacy_declined leader + diplomat of the other / proposing alliance {proposalId, from | by, state, expiresAt?}
diplomacy_changed both alliances {allianceId, other, from, to} (also reason: "disbanded")
diplomacy_cancel_pending / diplomacy_cancel_revoked both alliances {allianceId, other, ...} (a pact cancel is scheduled / was revoked)