Upstream/docs/API.md
jvanvik 931f59e11e Phase 3: trade/end-game client, bot simulator, first balance pass
Built:
- Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE.
- tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number.
- Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs).
- Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow.

Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots.

NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md.

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

17 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; 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: per IP, per token, stricter on login/signup. 429 rate_limited with Retry-After.
  • The client never sends computed amounts, only intents. The server recomputes everything with public/js/rules.js.

Resources (stage 0-2)

Route Purpose
POST /auth/signup, POST /auth/login account + token (signup also founds the capital POP)
GET /me user, operators (per world), POPs
GET /towns/:id full POP state: resources {amount, rate, cap} at serverTime, 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
GET /map?x&y&r rural areas, incumbent sites, POPs in the viewport
GET /notifications?after&limit durable notification feed (build done, ...)

Social (stage 5, no marketplace/transport yet)

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, 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, transport_arrived, units_offline, units_decommissioned, town_lost, town_gained) 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, 1000 each, D.TRANSPORT.capacityPerLink). 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, 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 (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_transport_link, not_enough_resources; all or nothing

Notifications: trade_accepted (poster), trade_completed (both, when both transports arrived), trade_expired, 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; holders also get contributions (who shipped what) and you {holder, canBuild, canShip, canAttack}
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); before opening backbone_closed. Settling a landing tile is invalid_target (backbone_site), also before it opens. Defence is static: incumbentDefence x 12 x (1 + 0.03 x node level); a scan report shows it. 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_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.