# 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 ` (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=&limit=`, 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=` 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, 500 each). 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.