From 249818a7aa6871dcf181588ac8812025ffecad9b Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sun, 11 Oct 2026 18:32:36 +0200 Subject: [PATCH] Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances, roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map, alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js. Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push, bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14 --- deploy/upstream-admin | 21 + deploy/upstream-backup.service | 40 + deploy/upstream-backup.timer | 14 + deploy/upstream.service | 94 + docs/API.md | 90 + docs/DECISIONS.md | 95 + docs/DEPLOY.md | 397 ++ docs/DESIGN.md | 21 + docs/NEXT.md | 59 + docs/openapi.json | 6600 ++++++++++++++++++++++- package.json | 2 +- public/css/style.css | 324 ++ public/icons/icon-192.png | Bin 0 -> 29602 bytes public/icons/icon-512.png | Bin 0 -> 147924 bytes public/icons/icon-maskable-512.png | Bin 0 -> 92175 bytes public/icons/icon.svg | 17 + public/icons/sprite.svg | 49 + public/index.html | 46 + public/js/api.js | 203 + public/js/data.js | 138 +- public/js/i18n.js | 376 ++ public/js/main.js | 404 ++ public/js/render.js | 398 ++ public/js/rules.js | 366 +- public/js/screens/alerts.js | 84 + public/js/screens/auth.js | 100 + public/js/screens/map.js | 220 + public/js/screens/pop.js | 495 ++ public/js/screens/settings.js | 84 + public/js/ui.js | 132 + public/manifest.webmanifest | 17 + server/alliances.js | 180 + server/commands/allianceCreate.js | 35 + server/commands/allianceDisband.js | 9 + server/commands/allianceInvite.js | 32 + server/commands/allianceInviteAnswer.js | 41 + server/commands/allianceInviteCancel.js | 15 + server/commands/allianceKick.js | 19 + server/commands/allianceLeave.js | 23 + server/commands/allianceNote.js | 41 + server/commands/allianceRole.js | 17 + server/commands/allianceTransfer.js | 18 + server/commands/diploAnswer.js | 35 + server/commands/diploPropose.js | 54 + server/commands/diploRevoke.js | 22 + server/commands/diploWithdraw.js | 15 + server/commands/index.js | 30 + server/commands/markReportRead.js | 14 + server/commands/messageBlock.js | 31 + server/commands/messageDelete.js | 24 + server/commands/messageRead.js | 12 + server/commands/messageSend.js | 72 + server/commands/recallMovement.js | 30 + server/commands/research.js | 26 + server/commands/sendMovement.js | 120 + server/commands/sendTransport.js | 52 + server/commands/train.js | 37 + server/commands/withdrawStationed.js | 35 + server/diplomacy.js | 25 + server/errors.js | 28 + server/events/arrive.js | 19 + server/events/buildDone.js | 1 + server/events/diploChange.js | 15 + server/events/index.js | 8 + server/events/powerCheck.js | 3 + server/events/reportCleanup.js | 9 + server/events/researchDone.js | 12 + server/events/return.js | 28 + server/events/trainDone.js | 17 + server/http.js | 2 +- server/migrations/002_military.sql | 102 + server/migrations/003_social.sql | 113 + server/military/arrivals.js | 122 + server/military/combat.js | 282 + server/military/ctx.js | 8 + server/military/movements.js | 58 + server/military/power.js | 109 + server/military/reports.js | 32 + server/military/units.js | 153 + server/military/views.js | 155 + server/queries.js | 10 +- server/routes/alliances.js | 140 + server/routes/index.js | 2 +- server/routes/messages.js | 71 + server/routes/movements.js | 65 + server/routes/rankings.js | 28 + server/routes/reports.js | 26 + server/routes/schemas.js | 43 +- server/routes/schemasMilitary.js | 42 + server/routes/units.js | 21 + server/socialQueries.js | 313 ++ server/state.js | 4 + server/text.js | 26 + test/admin-cli.test.js | 284 + test/client-api.test.js | 186 + test/client-i18n.test.js | 71 + test/helpers.js | 111 + test/military-api.test.js | 121 + test/military-expansion.test.js | 203 + test/military-flow.test.js | 148 + test/military-helpers.js | 108 + test/military-moves.test.js | 182 + test/military-power.test.js | 151 + test/military-rules.test.js | 159 + test/social-alliances.test.js | 310 ++ test/social-diplomacy.test.js | 186 + test/social-messages.test.js | 171 + test/social-rankings.test.js | 76 + test/social-rules.test.js | 54 + test/spine-core.test.js | 228 + tools/admin.js | 719 +++ 111 files changed, 17472 insertions(+), 13 deletions(-) create mode 100755 deploy/upstream-admin create mode 100644 deploy/upstream-backup.service create mode 100644 deploy/upstream-backup.timer create mode 100644 deploy/upstream.service create mode 100644 docs/DEPLOY.md create mode 100644 public/css/style.css create mode 100644 public/icons/icon-192.png create mode 100644 public/icons/icon-512.png create mode 100644 public/icons/icon-maskable-512.png create mode 100644 public/icons/icon.svg create mode 100644 public/icons/sprite.svg create mode 100644 public/index.html create mode 100644 public/js/api.js create mode 100644 public/js/i18n.js create mode 100644 public/js/main.js create mode 100644 public/js/render.js create mode 100644 public/js/screens/alerts.js create mode 100644 public/js/screens/auth.js create mode 100644 public/js/screens/map.js create mode 100644 public/js/screens/pop.js create mode 100644 public/js/screens/settings.js create mode 100644 public/js/ui.js create mode 100644 public/manifest.webmanifest create mode 100644 server/alliances.js create mode 100644 server/commands/allianceCreate.js create mode 100644 server/commands/allianceDisband.js create mode 100644 server/commands/allianceInvite.js create mode 100644 server/commands/allianceInviteAnswer.js create mode 100644 server/commands/allianceInviteCancel.js create mode 100644 server/commands/allianceKick.js create mode 100644 server/commands/allianceLeave.js create mode 100644 server/commands/allianceNote.js create mode 100644 server/commands/allianceRole.js create mode 100644 server/commands/allianceTransfer.js create mode 100644 server/commands/diploAnswer.js create mode 100644 server/commands/diploPropose.js create mode 100644 server/commands/diploRevoke.js create mode 100644 server/commands/diploWithdraw.js create mode 100644 server/commands/markReportRead.js create mode 100644 server/commands/messageBlock.js create mode 100644 server/commands/messageDelete.js create mode 100644 server/commands/messageRead.js create mode 100644 server/commands/messageSend.js create mode 100644 server/commands/recallMovement.js create mode 100644 server/commands/research.js create mode 100644 server/commands/sendMovement.js create mode 100644 server/commands/sendTransport.js create mode 100644 server/commands/train.js create mode 100644 server/commands/withdrawStationed.js create mode 100644 server/diplomacy.js create mode 100644 server/events/arrive.js create mode 100644 server/events/diploChange.js create mode 100644 server/events/powerCheck.js create mode 100644 server/events/reportCleanup.js create mode 100644 server/events/researchDone.js create mode 100644 server/events/return.js create mode 100644 server/events/trainDone.js create mode 100644 server/migrations/002_military.sql create mode 100644 server/migrations/003_social.sql create mode 100644 server/military/arrivals.js create mode 100644 server/military/combat.js create mode 100644 server/military/ctx.js create mode 100644 server/military/movements.js create mode 100644 server/military/power.js create mode 100644 server/military/reports.js create mode 100644 server/military/units.js create mode 100644 server/military/views.js create mode 100644 server/routes/alliances.js create mode 100644 server/routes/messages.js create mode 100644 server/routes/movements.js create mode 100644 server/routes/rankings.js create mode 100644 server/routes/reports.js create mode 100644 server/routes/schemasMilitary.js create mode 100644 server/routes/units.js create mode 100644 server/socialQueries.js create mode 100644 server/text.js create mode 100644 test/admin-cli.test.js create mode 100644 test/client-api.test.js create mode 100644 test/client-i18n.test.js create mode 100644 test/helpers.js create mode 100644 test/military-api.test.js create mode 100644 test/military-expansion.test.js create mode 100644 test/military-flow.test.js create mode 100644 test/military-helpers.js create mode 100644 test/military-moves.test.js create mode 100644 test/military-power.test.js create mode 100644 test/military-rules.test.js create mode 100644 test/social-alliances.test.js create mode 100644 test/social-diplomacy.test.js create mode 100644 test/social-messages.test.js create mode 100644 test/social-rankings.test.js create mode 100644 test/social-rules.test.js create mode 100644 test/spine-core.test.js create mode 100644 tools/admin.js diff --git a/deploy/upstream-admin b/deploy/upstream-admin new file mode 100755 index 0000000..9ecb0cc --- /dev/null +++ b/deploy/upstream-admin @@ -0,0 +1,21 @@ +#!/bin/sh +# Run tools/admin.js as the service user, against the service's database. Install: +# install -m 0755 /opt/upstream/deploy/upstream-admin /usr/local/bin/upstream-admin +# upstream-admin help +# Running admin.js as root would create the database's -wal/-shm files owned by root and the game could no longer open +# the database, hence the runuser. DB_PATH comes from the environment, else /etc/upstream/upstream.env, else the default. +set -eu +APP_DIR=${UPSTREAM_DIR:-/opt/upstream} +ENV_FILE=${UPSTREAM_ENV_FILE:-/etc/upstream/upstream.env} +if [ -z "${DB_PATH:-}" ] && [ -r "$ENV_FILE" ]; then + DB_PATH=$(sed -n 's/^[[:space:]]*DB_PATH=//p' "$ENV_FILE" | tail -n 1 | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/") +fi +DB_PATH=${DB_PATH:-/var/lib/upstream/game.db} +if [ "$(id -u)" = 0 ]; then + exec runuser -u upstream -- env DB_PATH="$DB_PATH" node "$APP_DIR/tools/admin.js" "$@" +elif [ "$(id -un)" = upstream ]; then + exec env DB_PATH="$DB_PATH" node "$APP_DIR/tools/admin.js" "$@" +else + echo "upstream-admin: run as root (it switches to the upstream user) or as the upstream user" >&2 + exit 2 +fi diff --git a/deploy/upstream-backup.service b/deploy/upstream-backup.service new file mode 100644 index 0000000..3233ced --- /dev/null +++ b/deploy/upstream-backup.service @@ -0,0 +1,40 @@ +# One database snapshot (VACUUM INTO, verified, dated file name, old ones pruned). Started by upstream-backup.timer, +# or by hand: systemctl start upstream-backup. Safe while the game server is running (SQLite WAL: readers do not block +# the writer). See docs/DEPLOY.md, "Backups". +# +# install -m 0644 deploy/upstream-backup.service deploy/upstream-backup.timer /etc/systemd/system/ +# systemctl daemon-reload && systemctl enable --now upstream-backup.timer + +[Unit] +Description=Upstream - database snapshot +Documentation=file:///opt/upstream/docs/DEPLOY.md +# Not started from the main unit's dependency graph: a backup must also work while the game is stopped. + +[Service] +Type=oneshot +User=upstream +Group=upstream +WorkingDirectory=/opt/upstream +# Same state directory as upstream.service; snapshots go to /var/lib/upstream/backups (mode 0700). +StateDirectory=upstream +StateDirectoryMode=0700 +# Same override file, so DB_PATH follows the main service if you changed it there. +EnvironmentFile=-/etc/upstream/upstream.env +Environment=DB_PATH=/var/lib/upstream/game.db +# Keep the newest 14 snapshots (daily timer = two weeks). Edit here, or `systemctl edit upstream-backup`. +# --keep-days D works too; with both, a snapshot survives if either rule keeps it. +ExecStart=/usr/bin/env node /opt/upstream/tools/admin.js backup /var/lib/upstream/backups --keep 14 +# A failed snapshot (verification failed, disk full) must be visible: the unit fails and journalctl shows why. +TimeoutStartSec=15min +Nice=10 +IOSchedulingClass=idle + +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +RestrictAddressFamilies=AF_UNIX +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +UMask=0077 diff --git a/deploy/upstream-backup.timer b/deploy/upstream-backup.timer new file mode 100644 index 0000000..a88ec99 --- /dev/null +++ b/deploy/upstream-backup.timer @@ -0,0 +1,14 @@ +# Daily snapshot at 04:15 (+ up to 10 min jitter). Persistent: a run missed while the container was off happens at +# the next boot. Every 6 hours instead: OnCalendar=*-*-* 00/6:15:00 and raise --keep in upstream-backup.service. + +[Unit] +Description=Upstream - daily database snapshot + +[Timer] +OnCalendar=*-*-* 04:15:00 +RandomizedDelaySec=10min +Persistent=true +Unit=upstream-backup.service + +[Install] +WantedBy=timers.target diff --git a/deploy/upstream.service b/deploy/upstream.service new file mode 100644 index 0000000..9cf1770 --- /dev/null +++ b/deploy/upstream.service @@ -0,0 +1,94 @@ +# Upstream systemd unit (Debian 13 LXC; see docs/DEPLOY.md). +# +# install -m 0644 deploy/upstream.service /etc/systemd/system/upstream.service +# systemctl daemon-reload && systemctl enable --now upstream +# journalctl -u upstream -f +# +# Expects the app in /opt/upstream (server/, public/, node_modules/) and a Node >= 22.13 on the PATH (the Debian 13 +# package is Node 20 and is too old for node:sqlite: see docs/DEPLOY.md section 1). The database lives in +# /var/lib/upstream (systemd creates it, owned by the service user, from StateDirectory=). + +[Unit] +Description=Upstream - persistent network-operator strategy game (Node server, SQLite) +Documentation=file:///opt/upstream/docs/DEPLOY.md +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=upstream +Group=upstream +WorkingDirectory=/opt/upstream +# /usr/bin/env finds node on systemd's default PATH: /usr/local/bin (official tarball) before /usr/bin (NodeSource). +ExecStart=/usr/bin/env node /opt/upstream/server/index.js + +# ---- state -------------------------------------------------------------------------------------------------- +# Creates /var/lib/upstream owned by the service user (mode 0700) before start. This is the ONLY place the game +# writes. Do not put the database in /opt/upstream. +StateDirectory=upstream +StateDirectoryMode=0700 +# Optional file for settings and secrets (SIGNUP_CODE). Values in it override the Environment= lines below. +# Keep it root:upstream 0640. The leading "-" means: fine if it does not exist. +EnvironmentFile=-/etc/upstream/upstream.env + +# ---- configuration (see docs/DEPLOY.md, "Configuration") ---------------------------------------------------- +Environment=NODE_ENV=production +Environment=PORT=8080 +# "::" = one dual-stack socket for IPv4 + IPv6 (falls back to 0.0.0.0 if the kernel has no IPv6). +Environment=HOST=:: +Environment=DB_PATH=/var/lib/upstream/game.db +# auto: believe X-Forwarded-For / X-Forwarded-Host only from loopback / private-range peers (your proxy). +Environment=TRUST_PROXY=auto +# Only when the proxy reaches this server from a NON-private address (global IPv6, Tailscale / CGNAT 100.64.0.0/10): +#Environment=TRUSTED_PROXIES=100.64.0.0/10,2001:db8::6 +# Only when the proxy rewrites the Host header or you serve several public names (include the port if not 80/443): +#Environment=ALLOWED_ORIGINS=https://upstream.example.com +#Environment=MAX_CONN_PER_IP=40 +# World settings: only read when the database has NO world yet (first boot). Change them later with +# `upstream-admin create-world` / `reset-world`, not here. +#Environment=WORLD_SPEED=1 +#Environment=WORLD_RADIUS=50 +#Environment=WORLD_NAME=World 1 +# Invite code for signup. Empty/unset = open signup. Put the real value in /etc/upstream/upstream.env, not here. +#Environment=SIGNUP_CODE= + +# ---- lifecycle ---------------------------------------------------------------------------------------------- +Restart=on-failure +RestartSec=2 +# SIGTERM closes the listener and the database and exits 0 within about a second; SIGKILL after 15 s as a backstop. +# (A SIGKILL is still safe for SQLite: the WAL is replayed on the next start and overdue events are caught up.) +TimeoutStopSec=15 + +# ---- hardening that works in any container (no mount namespaces needed) ------------------------------------ +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +# AF_NETLINK: Node's os.networkInterfaces() (start-up banner) and glibc's resolver use it. +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +# New files (the database, its -wal/-shm, snapshots) are readable by the service user only: they hold password hashes. +UMask=0077 +# Do NOT add MemoryDenyWriteExecute=yes: V8's JIT needs writable+executable memory and Node would crash. + +# ---- optional extra hardening: needs mount namespaces ------------------------------------------------------ +# In an unprivileged Proxmox LXC these fail with "status=226/NAMESPACE" unless the container has the +# "Nesting" feature enabled (Proxmox: container > Options > Features > Nesting; then restart the CT). +# Unlike Netwall this app writes to disk, so ProtectSystem=strict needs the ReadWritePaths line next to it. +# (StateDirectory= already makes /var/lib/upstream writable under strict; ReadWritePaths is the explicit belt.) +#ProtectSystem=strict +#ReadWritePaths=/var/lib/upstream +#ProtectHome=yes +#PrivateTmp=yes +#PrivateDevices=yes +#ProtectKernelTunables=yes +#ProtectKernelModules=yes +#ProtectKernelLogs=yes +#ProtectControlGroups=yes +#ProtectClock=yes +#ProtectHostname=yes + +[Install] +WantedBy=multi-user.target diff --git a/docs/API.md b/docs/API.md index 3855869..f367292 100644 --- a/docs/API.md +++ b/docs/API.md @@ -27,4 +27,94 @@ REST JSON under `/api/v1/`. The machine-readable contract is `docs/openapi.json` | `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. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 24ad487..a8aebb2 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -33,3 +33,98 @@ committed file is stale, which satisfies "updated in the same commit as any rout ## D8 — Resource fields are slot-keyed Buildings table key: `f1..f18` for resource fields (type fixed at founding, 4 per type + 2 wild), the building type for infrastructure. Build "slots": 1 concurrent build, 2 from Core router 10 (queue = pending `buildDone` events). + +## S5-1 — Alliance size cap is stored, only ever raised +DESIGN says the Peering office level sets the size you can found. The cap is stored at founding (`10 + 2 * best level`). A lost or +downgraded building must never kick anyone, so the cap is monotonic: commands that depend on it (invite, accept, transfer) raise it if +the CURRENT leader's best office would give more; reads show `max(stored, formula)` without writing. The floor is therefore 10 even +for a leader without an office after a transfer. The office requirement (>= 1) is checked when founding and when accepting an invite, +not afterwards. + +## S5-2 — Diplomacy move table is data, three kinds of change +`SOCIAL.diplomacyMoves` (data.js) says for each (from, to) whether it is `immediate`, a `proposal` or `delayed`. War from neutral is +immediate (no consent needed). Anything that leaves a pact (nap/confed -> neutral/war, confed -> nap) is `delayed`: 24 h / world speed +via a `diploChange` event, so you cannot betray a partner without warning. Pacts and peace need acceptance. While a delayed change is +pending the pair is locked (`diplomacy_pending`); only the starter can revoke. A pair at `neutral` with nothing pending has no row in +`alliance_relations`. Acceptance re-validates against the current state, because the relation may have moved since the proposal. +`war -> confed` is not allowed (go through a pact first). + +## S5-3 — Membership lives in two tables, one writer +`operators.alliance_id` (from 001, cheap joins in /map, /me) and `alliance_members` (role, joined_at, one leader per alliance by a partial +unique index). `alliances.js` addMember/removeMember are the only writers. Alliance rows are hard-deleted on disband; messages keep a +`alliance_tag` snapshot and carry no foreign key to alliances so broadcasts survive. + +## S5-4 — Last online comes from tokens +No new column: `lastOnline` = newest `tokens.last_used_at` of the member's user, which auth.js refreshes at most once a minute. So it +is accurate to about a minute and includes revoked tokens (a logout still counts as having been online). + +## S5-5 — Message rate limit is DB-backed, not the in-memory Limiter +`server/http.js` Limiter keys on monotonic real time and forgets on restart; message limits are a product rule that should follow the +(fake) clock and survive restarts, so the sender's recent rows in `messages` are counted (`SOCIAL.messageLimits`, indexed by +`messages_sender`). The per-token/IP limiters still apply on top. + +## S5-6 — Messages: per-recipient rows, sanitising on write +One `messages` row plus one `message_recipients` row per recipient (broadcast fan-out at send time: members who join later do not see +old broadcasts; members who leave keep what they received). Read/delete state is per recipient; the sender's copy is hidden with +`sender_deleted_at`; the row is purged when nobody has a copy. A blocked sender is silently not delivered to (no row), so blocking does +not leak. Text is sanitised once on write (`server/text.js`): C0/C1 controls, bidi overrides and isolates, zero-width and invisible +tag characters are stripped, NFC, `\r\n` -> `\n`; ZWJ/ZWNJ are kept for emoji. Clients render with `textContent` only. + +## S5-7 — Rankings are computed per request, no cache +Footprint for a whole world comes from two queries (towns, buildings) and `rules.footprintAt`; fine for the expected 50-300 operators. +If it ever shows up in a profile, cache per (world, minute). Cursor is a rank offset because rankings are a computed snapshot, not rows. + +## S5-8 — Route params and list order +`inviteId`, `noteId`, `proposalId`, `otherId`, `operatorId` were added to `INT_PARAMS` in http.js. Lists that are newest-first (messages) +use the last id as the `after` cursor and return older items; this is the one place `after` does not mean "newer than". + +## S3-1 — Online/offline is computed lazily; `powerCheck` only does the side effects +Units are offline while the battery is empty and net power is negative. That is derived from the lazy battery value (`power.online`) at +the moment it matters (sending, combat, the town view), never from an event having run. The `powerCheck` event (one pending per POP, +re-armed by `power.reschedule` after anything that changes unit draw or building levels, including `buildDone`) only writes the +"units offline" notification and does the decommission after 24 h / world speed. Offline is all-or-nothing per POP (the contract of +`rules.unitsOnline`); the decommission then removes the most expensive units (home first, then reinforcements) until the draw fits the +output, not everything. Offline units are neither counted in defence nor hurt by a raid, but a full attack lost by the defender still +wipes them. Reinforcements draw from the host (`state.unitDraw` reads `stationed`); units in transit draw from nobody. + +## S3-2 — Research is per POP, speed bonus per operator +`town_research(town_id, unit, stat, level)`; level n needs a Research lab of level n + 2, one research at a time per POP. An attack uses a +snapshot of the origin POP's research taken at departure (`movements.extra.research`); defenders use the research of the POP each group +belongs to. Incumbent sites: +10% research speed per distinct site taken (cap +50%), and a one-time +2500 Hardware per site and operator. +Taking a site does not remove it: it stays a static fortress for everybody else. + +## S3-3 — One report row, many recipients; cleanup armed at the earliest expiry +A battle is one `reports` row shared through `report_recipients(report_id, user_id, role, read_at)`, so both sides see the same data (a +scan is two separate rows: intel for the scanner, "a scan happened" for the target, with the scanner's identity only if the target's +scanners won). `reportCleanup` is armed at the earliest `expires_at` (14 days, real time, not divided by world speed) and re-arms itself +only while reports remain: at most one pending cleanup per world, none on a quiet world. + +## S3-4 — Arrival re-validates everything and bounces +A movement is validated when it is sent and again when it arrives (the target may have changed owner, got protection, joined a pact, the +tile may have been taken). If it no longer holds, the units turn around with the loot they carry and the sender gets a `movement_failed` +report. Return legs whose origin POP changed hands go to the operator's capital (or oldest POP). + +## S3-5 — Takeover details +Only `takeover` movements (with an M&A team) can lower loyalty; one team per attack counts and is used up when it does. `takeoverBlock`: +a player's last POP wins over "capital" (refused at send); a capital with siblings is only dragged to loyalty 0. Loot is taken in the same +arrival, before the POP changes hands. On transfer the old owner's pending training/research is cancelled, pending builds are re-keyed to +the new owner's user, and that POP's units standing elsewhere are re-homed to the old owner's capital. A captured POP keeps its footprint. + +## S3-6 — Transport links +`links` = Internet exchange level, each carries 500 (`D.TRANSPORT`). A link is busy while the transport is out and while its empty carriers +drive back (a `return` movement with `extra.link`). Cargo above the receiver's Rack hall cap is lost (the notification says how much). +`transport` movements keep arbitrary `extra` and `movements.hooks.transportArrived` is called on delivery, so the trade stage needs no +change in the movement code. + +## S3-7 — Protection +Beginner protection blocks raid/attack/takeover in both directions. Sending one from a protected operator needs `confirmEndProtection` +and ends it at once; attacking an incumbent site does not end it; scans never do. The target's protection is compared with the ARRIVAL +time at send, and re-checked at arrival. + +## S3-8 — Footprint gate counts the operator's total +`footprintNeeded(n)` with n = POPs owned now (second POP: n = 1). Founding and takeover both need `sum(footprint of own POPs) >= need`, +nothing is spent. New POPs start with every field at level 0, no infrastructure, 250 of each resource and loyalty 100. + +## 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. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md new file mode 100644 index 0000000..ab5af6c --- /dev/null +++ b/docs/DEPLOY.md @@ -0,0 +1,397 @@ +# Deploying UPSTREAM + +UPSTREAM is one Node process: it serves the static client from `public/`, the REST API under `/api/v1/` and (stage 6) +a WebSocket at `/ws`. Unlike NETWALL it **keeps state**: one SQLite file, owned by that process. A restart loses +nothing: overdue events are caught up in order before the server accepts traffic. + +``` + phone / laptop --https--> nginx Proxy Manager (TLS, :443) --http (+ WebSocket)--> Debian 13 LXC: node :8080 + /opt/upstream (code, read-only) + /var/lib/upstream (game.db, backups/) +``` + +Same shape as NETWALL (`docs/DEPLOY.md` there): same proxy, same hardening notes, same env vars for the network +layer. The differences are the Node version (`node:sqlite` needs 22.13+), a state directory and backups. + +**What was and was not run while writing this** (so you know what to check on the real box): + +* **Run:** `systemd-analyze verify` on the three unit files (syntax and directives only), the CLI `tools/admin.js` + and its tests on a dev machine (Node 24.21), a backup, verify and prune cycle, `sh -n` on `deploy/upstream-admin`. +* **Taken from NETWALL's docs, not re-run for UPSTREAM:** everything about nginx Proxy Manager (labels, header + behaviour, "Client addresses"). NETWALL's guide records what was observed against NPM v2.16.0. +* **Never run:** a Proxmox LXC, a started unit under systemd, the timer firing on its own, a Node install from the + tarball or NodeSource on Debian 13, `rrsync`, Let's Encrypt, a restore on the real box. Treat those steps as a + checklist to confirm, and fix this file when reality differs. + +## 1. Requirements + +* Debian 13 (trixie) LXC with its own IPv4 (optionally IPv6) address the proxy can reach. 1 core, 512 MB RAM and 4 GB + disk are plenty for a small world; the database grows with the event and notification history (measure it with + `upstream-admin status`), and snapshots multiply it by the retention count. +* **Node 22.13 or newer.** Debian 13 ships `nodejs` **20.19.2** (checked on tracker.debian.org: stable has 20.19.2, + testing and unstable have 24.21). Node 20 has no `node:sqlite`, so `apt install nodejs` is **not enough**. `package.json` + says `"engines": {"node": ">=22.13"}`; 22.5 to 22.12 only have `node:sqlite` behind `--experimental-sqlite`, which + the unit does not pass. Development is on Node 24.21. +* A DNS name for the game (for example `upstream.example.com`) pointing at the proxy. + +### Getting a suitable Node (pick one) + +**A. Official tarball (no third-party apt repo, nothing piped into a shell).** Pick a current 24.x (Active LTS) or +22.x from https://nodejs.org/en/download and put its version in `V`: + +```sh +apt update && apt install -y curl xz-utils ca-certificates +V=24.21.0 # example: use the current 24.x (or >= 22.13) you picked +ARCH=linux-x64 # linux-arm64 on ARM hosts (uname -m: aarch64) +cd /tmp +curl -fsSLO https://nodejs.org/dist/v$V/node-v$V-$ARCH.tar.xz +curl -fsSLO https://nodejs.org/dist/v$V/SHASUMS256.txt +grep " node-v$V-$ARCH.tar.xz\$" SHASUMS256.txt | sha256sum -c - # must print: ... OK +tar -C /opt -xJf node-v$V-$ARCH.tar.xz +ln -sfn /opt/node-v$V-$ARCH /opt/node +ln -sf /opt/node/bin/node /usr/local/bin/node +ln -sf /opt/node/bin/npm /usr/local/bin/npm +ln -sf /opt/node/bin/npx /usr/local/bin/npx +``` + +(For extra assurance also verify the signature of `SHASUMS256.txt` as described on nodejs.org.) An upgrade later is +a new tarball and `ln -sfn` to it, then `systemctl restart upstream`. `upstream.service` starts `/usr/bin/env node`, and +systemd's default PATH lists `/usr/local/bin` before `/usr/bin`, so the tarball wins over any distro Node. + +**B. NodeSource apt repository** (follows their documentation; not run here). It puts Node in `/usr/bin/node`: + +```sh +apt install -y ca-certificates curl gnupg +install -d -m 0755 /etc/apt/keyrings +curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg +echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_24.x nodistro main" > /etc/apt/sources.list.d/nodesource.list +apt update && apt install -y nodejs # includes npm; do not also install Debian's npm package +``` + +**Verify either way** (all three must succeed): + +```sh +node --version # v22.13.0 or newer +node -e "require('node:sqlite'); console.log('node:sqlite ok')" +which -a node # the first one is the one the unit will use +``` + +On 22.x/24.x Node may print `ExperimentalWarning: SQLite is an experimental feature` to stderr; that is harmless (it +shows up in the journal once per start). `No such built-in module: node:sqlite` means Node is too old (or it is the +distro's 20.x earlier on the PATH). If `node:sqlite` ever misbehaves, `DECISIONS.md` D1 describes the one-file swap +to `better-sqlite3` in `server/db.js`; that would add a native dependency and a build toolchain to the LXC. + +## 2. Create the LXC (Proxmox) + +Container creation, the Proxmox UI way (CLI `pct create` works too): + +* Template `debian-13-standard`, **unprivileged**, hostname `upstream`, 1 core, 512 MB RAM (+256 MB swap), 4-8 GB disk. +* Network: a static address (or a DHCP reservation) on a bridge the NPM host can reach. The proxy forwards to that + address, so it must not change. +* Features: **Nesting** is optional; tick it only if you want the namespace-based hardening block in the unit + (section 3). Everything else works without it. +* Start on boot: yes. Timezone does not matter: the game uses UTC ms, the backup timer uses the container's clock. +* Proxmox's own CT backups (`vzdump`) are not a substitute for the snapshots in section 7: a running-container copy of + a SQLite file is crash-consistent at best. Use them for the OS and let the verified snapshots be the data backup. + +## 3. Install in the LXC + +Run as root inside the container (Node from section 1 is already in place). + +```sh +apt install -y rsync # for the copy below (or use git) + +# a dedicated, login-less user that only runs the game +useradd --system --home-dir /var/lib/upstream --shell /usr/sbin/nologin upstream + +# code: read-only for the service user, owned by root +mkdir -p /opt/upstream +# from your workstation: +# rsync -a --delete --exclude node_modules --exclude .git --exclude data --exclude e2e ./ root@:/opt/upstream/ +# (needs server/, public/, tools/, deploy/, docs/, package.json, package-lock.json; `test/` is optional) +cd /opt/upstream +npm ci --omit=dev # only "ws"; follows the lockfile exactly +chown -R root:root /opt/upstream + +# the admin helper on the PATH +install -m 0755 /opt/upstream/deploy/upstream-admin /usr/local/bin/upstream-admin + +# optional settings / secrets file (read by the unit and by upstream-admin) +install -d -m 0750 -o root -g upstream /etc/upstream +install -m 0640 -o root -g upstream /dev/null /etc/upstream/upstream.env +# edit it: SIGNUP_CODE=choose-a-long-random-string +# ALLOWED_ORIGINS=https://upstream.example.com + +# the units +install -m 0644 /opt/upstream/deploy/upstream.service /opt/upstream/deploy/upstream-backup.service /opt/upstream/deploy/upstream-backup.timer /etc/systemd/system/ +systemctl daemon-reload +systemctl enable --now upstream upstream-backup.timer +systemctl status upstream +journalctl -u upstream -f +``` + +The first start prints `applied migrations: 001_init.sql, ...`, `created world 1` and the listen banner with +`database: /var/lib/upstream/game.db`. Quick manual run as the service user instead of systemd (Ctrl-C to stop): +`runuser -u upstream -- env PORT=8080 DB_PATH=/var/lib/upstream/game.db node /opt/upstream/server/index.js`. + +### What the units do + +* `deploy/upstream.service`: user `upstream`, `WorkingDirectory=/opt/upstream`, `StateDirectory=upstream` (systemd creates + `/var/lib/upstream` owned by that user, mode 0700, so the game can write nowhere else), `Restart=on-failure`, + `EnvironmentFile=-/etc/upstream/upstream.env` (overrides the `Environment=` lines), `UMask=0077` (database and + snapshots hold password hashes: owner-only). +* Hardening that works in any container: `NoNewPrivileges`, empty capability set (port 8080 needs none), + `RestrictAddressFamilies`, `RestrictRealtime`, `RestrictSUIDSGID`, `LockPersonality`, `SystemCallArchitectures`. + No `MemoryDenyWriteExecute` (V8 would crash). +* The namespace block (`ProtectSystem=strict`, `ReadWritePaths=/var/lib/upstream`, `PrivateTmp`, ...) is commented out. + In an unprivileged LXC it fails with `status=226/NAMESPACE` unless **Options > Features > Nesting** is on. Because the + app writes to disk, `ProtectSystem=strict` needs the `ReadWritePaths=` line that is already next to it in the unit; + without it the database cannot be opened. +* Shutdown: SIGTERM stops the scheduler timer, closes the listener and the database and exits 0 in about a second. + Even a SIGKILL or power cut is survivable (WAL replay on the next open, then overdue events are caught up). +* `deploy/upstream-backup.service` (oneshot) and `.timer`: see section 7. + +## 4. Configuration + +Environment variables read by `node server/index.js`. Put changes in `/etc/upstream/upstream.env` (`KEY=value`, one per +line, no `export`) or in a `systemctl edit upstream` override, then `systemctl restart upstream`. + +| Variable | Default (unit) | Meaning | +|---|---|---| +| `PORT` | `8080` | TCP port. Unprivileged, so no capabilities needed. `0` picks a free one (banner prints it). | +| `HOST` | `::` | Bind address. `::` = one dual-stack socket for IPv4 and IPv6 (falls back to `0.0.0.0` if the kernel has no IPv6). `127.0.0.1` = this container only. | +| `DB_PATH` | `/var/lib/upstream/game.db` | SQLite file. The code default is `./data/game.db`; the unit overrides it. Its directory is created if missing, it must be writable by the service user. `-wal` and `-shm` files appear next to it: always copy via a snapshot (section 7), never with `cp` while running. | +| `TRUST_PROXY` | `auto` | `auto`: believe `X-Forwarded-For` / `X-Forwarded-Host` only from loopback / private-range peers. `1`: always (then firewall the port). `0`: never. Used for the per-IP rate limits and the log. | +| `TRUSTED_PROXIES` | empty | Extra IPs / CIDRs `auto` believes: needed when the proxy reaches the LXC from a global IPv6, Tailscale / CGNAT `100.64.0.0/10` or another routable address. | +| `ALLOWED_ORIGINS` | empty | Extra origins for the WebSocket origin check (stage 6), comma separated, with the port when it is not 80/443. The REST API uses bearer tokens (no cookies) and does not check origins. | +| `MAX_CONN_PER_IP` | `40` | Open connections per client address (WebSocket cap, stage 6). `0` disables. | +| `WORLD_SPEED` | unset (1) | World speed multiplier, **first boot only**, when the database has no world yet. | +| `WORLD_RADIUS` | unset (50) | Map radius in tiles (coordinates `-R..R`, so 50 = 101 x 101), **first boot only**. | +| `WORLD_NAME` | unset (`World 1`) | Name of the first world, **first boot only**. | +| `SIGNUP_CODE` | empty | If set, `POST /auth/signup` needs `"invite": ""` in the body or answers `signup_closed` (403). Empty = open signup. Keep it in `/etc/upstream/upstream.env`, not in the unit file. | +| `UPSTREAM_DIR`, `UPSTREAM_ENV_FILE` | `/opt/upstream`, `/etc/upstream/upstream.env` | Only for the `upstream-admin` wrapper. | + +Fixed in code (options of `createServer()`): per-IP and per-token rate limits (login and signup are stricter: about one +per 10 s sustained, burst 8, per client address), 32 KB request bodies, idempotency keys pruned hourly. + +### First boot + +An empty or missing database is created, all migrations are applied, and **one world is created** from `WORLD_SPEED`, +`WORLD_RADIUS`, `WORLD_NAME` (seed random). After that those variables are ignored: changing them does not touch the +existing world. More worlds, a different seed, ending or resetting a world are admin tasks (section 6). The first +player to sign up becomes an ordinary operator; there is no special admin account, admin work is the CLI on the box. + +## 5. nginx Proxy Manager + +In NPM: **Hosts > Proxy Hosts > Add Proxy Host**. + +| Tab / field | Value | +|---|---| +| Details: Domain Names | `upstream.example.com` | +| Details: Scheme | `http` | +| Details: Forward Hostname / IP | the LXC's address (for example `192.168.1.51`), not `127.0.0.1` when NPM runs elsewhere or in its own container | +| Details: Forward Port | `8080` | +| Details: Cache Assets | **off** (static files are `no-cache` and revalidated by ETag; the game must see new versions) | +| Details: Block Common Exploits | optional | +| Details: **Websockets Support** | **on.** The REST game works without it, but stage 6 adds `/ws` and it fails with HTTP 426 when this is off. Switch it on now so you do not forget. | +| Custom Locations | none needed | +| SSL | Request a new Let's Encrypt certificate, **Force SSL**, **HTTP/2** (HSTS optional) | +| Advanced (gear) | nothing required; optional gzip below | + +Optional, Advanced box, to compress JS/JSON for phones (the Node server does not compress; NPM's own `gzip on` only +covers HTML): + +```nginx +gzip on; +gzip_types text/css text/javascript application/javascript application/json application/manifest+json image/svg+xml; +``` + +Notes carried over from NETWALL's setup (observed there against NPM v2.16.0, not re-run for UPSTREAM): + +* NPM sends `Host` **without the public port** and no `X-Forwarded-Host`. On a public port other than 443 the browser + `Origin` then differs from `Host`; list the origin with its port in `ALLOWED_ORIGINS` (matters for `/ws`). +* A proxy on a non-private address (global IPv6, Tailscale) is not believed by `TRUST_PROXY=auto`: every player then + shares one rate-limit budget and the log shows the proxy's address. Fix: `TRUSTED_PROXIES=`. +* Clients on your own LAN can pick their address through NPM's `real_ip` handling, so the per-IP limits protect against + public abuse, not against LAN users. +* **Heads-up for stage 6:** NPM's default `proxy_read_timeout` is 90 s. NETWALL never idles because it streams 20 + snapshots a second; UPSTREAM's socket will be quiet for long stretches. The WebSocket server must send a ping + well under 90 s (NETWALL's pings every 25 s), or the proxy drops idle players. + +Firewall and dual stack: identical to NETWALL (`docs/DEPLOY.md` there, section 6): only the proxy needs to reach port +8080. `curl -i http://127.0.0.1:8080/healthz` and `curl -gi 'http://[::1]:8080/healthz'` check both families. + +## 6. Operating: `upstream-admin` + +`tools/admin.js` is the operator CLI (Node core only, uses the game's own `db.js`, `state.js`, `rules.js`). +`deploy/upstream-admin` runs it as the service user against the service's database (it reads `DB_PATH` from +`/etc/upstream/upstream.env`). **Do not run `node tools/admin.js` as root**: SQLite would create `game.db-wal` and +`-shm` owned by root and the game could no longer open its database (symptom in section 10). + +```sh +upstream-admin help +upstream-admin status # file, size, migrations, overdue events +upstream-admin worlds +upstream-admin create-world --name "Summer" --speed 2 --radius 60 --seed 1234 --end-in 90d +upstream-admin end-world 1 --yes +upstream-admin users [--banned] # no hashes or tokens are ever printed +upstream-admin operators [--world 1] +upstream-admin ban mallory # sets banned, revokes all tokens: old tokens give 401, login 403 +upstream-admin unban mallory +upstream-admin revoke-tokens ada # log out everywhere +upstream-admin inspect-operator ada # (--world N when the name exists in several worlds, --id N by operator id) +upstream-admin inspect-town 12 # resources now (rules.resourcesAt), buildings, queue, units if the table exists +upstream-admin events --pending [--type buildDone --town 12 --limit 100] +upstream-admin replay-events --until +6h # dry run: what the scheduler would process, in order +upstream-admin replay-events --until +6h --simulate # + run the real handlers on a scratch copy, report outcome and follow-ups +upstream-admin backup /var/lib/upstream/backups --keep 14 +upstream-admin verify-backup /var/lib/upstream/backups/upstream-20261011T041500Z.db +upstream-admin grant 12 --fiber 5000 --capital 2000 --yes # testing only +upstream-admin reset-world 1 --yes-destroy --backup /var/lib/upstream/backups --new-seed +upstream-admin migrate # apply pending migrations without starting the server +``` + +All commands take `--json` (machine output) and `--db FILE` (otherwise `$DB_PATH`, otherwise `./data/game.db`). +Exit codes: `0` ok, `1` failed, `2` usage error **or a destructive command missing its flag**, `3` not found. + +Safety rules the CLI follows: + +* Destructive or test-only commands refuse without a flag: `end-world` and `grant` need `--yes`; `reset-world` + needs `--yes-destroy` (without it, it prints what it would delete and exits 2). `ban`, `unban`, `revoke-tokens` are + reversible and need none. +* `reset-world` deletes the world's game rows (everything with a `world_id`, plus tables pointing at them: towns, + buildings, events, operators, alliances, messages, ... discovered from the schema, so tables added by later stages + are covered) and **keeps accounts and tokens**; players must join the world again. It resets `start_at`, clears + `end_at` and sets the world running. It rolls back if it would leave dangling references. Stop the game first + (`systemctl stop upstream`): the server does not know the world was swept while it is running. Use `--backup DIR`. +* Everything runs on a running server's database: writes are single short `BEGIN IMMEDIATE` transactions, the + connection is always closed, and SQLite's 5 s busy timeout covers collisions with the game (`database is locked` + from the CLI just means: try again). +* `grant` adds to the town's stored amounts (valid at its `res_at`); the lazy model carries them forward. Amounts above + the Rack hall cap are kept but stop growing, like a lowered cap. +* `inspect-town` shows values as of now **ignoring** overdue events; it says so when there are any (server stopped). + +## 7. Backups and restore + +`upstream-backup.timer` runs `upstream-backup.service` daily at 04:15 (10 min jitter, `Persistent=true`). It runs +`tools/admin.js backup /var/lib/upstream/backups --keep 14` as the service user. A snapshot is: + +1. `VACUUM INTO` a temporary `.partial-*` file: a consistent copy as of one moment, safe while the game runs (WAL readers do + not block the writer; the game keeps its own 5 s busy timeout); +2. verified: opened read-only, `PRAGMA integrity_check` = `ok`, `worlds` and `schema_migrations` present; +3. published under a dated name `upstream-YYYYMMDDTHHMMSSZ.db` (UTC) with a hard link, so an existing file is never + replaced (a same-second collision becomes `...Z-1.db`), mode 0600; +4. only then older snapshots are pruned: `--keep N` keeps the newest N, `--keep-days D` keeps those younger than D days, + both = survive if either keeps it, neither = no pruning. The newest snapshot and any file not matching the naming + pattern are never deleted. A failed verification leaves nothing behind and prunes nothing, and the unit fails + (`systemctl status upstream-backup`, `journalctl -u upstream-backup`). + +Snapshots are plain SQLite files (journal mode `delete`), not `-wal` dependent: copy a single file. + +```sh +systemctl list-timers upstream-backup.timer # next run +systemctl start upstream-backup # one right now +journalctl -u upstream-backup -n 20 +ls -l /var/lib/upstream/backups +``` + +Change the schedule or retention with `systemctl edit upstream-backup.timer` / `upstream-backup.service` (for every +6 hours: `OnCalendar=*-*-* 00/6:15:00` and a larger `--keep`). Before an upgrade or a `reset-world`, take one by hand. + +### Off-box copy + +Snapshots on the same disk die with the container. Pull them from another machine (NAS, workstation, the Proxmox host), +for example from cron or a timer there: + +```sh +rsync -a --ignore-existing root@:/var/lib/upstream/backups/ /srv/backups/upstream/ +``` + +`--ignore-existing` makes it append-only on your side (nothing already stored is overwritten, and snapshots pruned on +the LXC stay on the backup host until you decide otherwise). Better than a root key: a dedicated key restricted in +`authorized_keys` to `command="rrsync -ro /var/lib/upstream/backups",restrict ...` (`rrsync` comes with the `rsync` +package; not run here). The files are owner-only (`upstream`), so the reading user needs root or a group ACL. + +### Restore + +The restore is a file copy, and the time model makes it clean: the restored world simply fast-forwards. Every event that +fell due since the snapshot is processed in order at start-up, each at its own due time. What is lost is what players did after +the snapshot (builds started, signups, messages) and their tokens: players log in again. + +```sh +systemctl stop upstream-backup.timer upstream +upstream-admin verify-backup /var/lib/upstream/backups/upstream-20261011T041500Z.db # exit 0 or stop here +mkdir -p /var/lib/upstream/pre-restore +mv /var/lib/upstream/game.db* /var/lib/upstream/pre-restore/ 2>/dev/null # keep the old one, incl. -wal/-shm +install -o upstream -g upstream -m 0600 /var/lib/upstream/backups/upstream-20261011T041500Z.db /var/lib/upstream/game.db +systemctl start upstream upstream-backup.timer +journalctl -u upstream -n 20 # look for "caught up N overdue event(s)" +upstream-admin status +``` + +Restoring onto another machine works the same way (install code and Node, copy the file to `DB_PATH`). Migrations in +the snapshot are checksummed: if the code is newer than the snapshot, the missing migrations are applied at boot; run +code that is **older** than the snapshot's last migration (`upstream-admin status` shows it) only if you know the schema +still fits, the server does not check for that. + +## 8. Upgrading + +```sh +upstream-admin backup /var/lib/upstream/backups --keep 14 # 1. snapshot first +rsync -a --delete --exclude node_modules --exclude .git --exclude data ./ root@:/opt/upstream/ # 2. new code (from your workstation) +cd /opt/upstream && npm ci --omit=dev && chown -R root:root /opt/upstream # 3. dependencies, ownership +systemctl restart upstream # 4. migrations apply at boot +journalctl -u upstream -n 30 # 5. "applied migrations: ..." then the listen banner +curl -i http://127.0.0.1:8080/healthz +``` + +* Migrations are `server/migrations/NNN_name.sql`, applied in order inside a transaction each, **recorded with a + checksum and never edited after they shipped**. If one that was applied has changed, the server refuses to start + (`migration 001_init.sql was edited after it was applied`): restore that file from git and ship a **new** numbered + migration instead. `upstream-admin status` lists applied and pending migrations; `upstream-admin migrate` applies + them without starting the game. +* Each migration runs in its own transaction: a failing one rolls back and the server exits, earlier ones of the same + boot stay applied. Going back to the old code after a migration committed means restoring the pre-upgrade snapshot + (section 7). +* Updated unit files: `install -m 0644 ...`, `systemctl daemon-reload`, `systemctl restart upstream`. +* Players reconnecting after the restart need no action; clients get `serverTime` in every response and refetch. + +## 9. Health, logs, checks + +```sh +curl -i https://upstream.example.com/healthz # 200 ok (only says the process answers HTTP) +curl -I https://upstream.example.com/ # 200 + Content-Security-Policy +upstream-admin status # database, migrations, events pending / OVERDUE +journalctl -u upstream -f # live log; -p err for failures only +journalctl -u upstream --since "1 hour ago" | grep -E "failed|refused" +``` + +The log has: applied migrations, created world, caught-up events, `refused rate_limited(...) ip=...`, and +`event N (type) failed: ...` for a handler that threw (that event is marked `failed` and the queue moves on; list them +with `upstream-admin events --status failed`). Player IP addresses appear in the log; passwords and tokens never do. +A healthy server has **no overdue events** in `status`: the timer processes events within milliseconds of their due time. + +## 10. Troubleshooting + +| Symptom | Cause and fix | +|---|---| +| Service dies at start: `No such built-in module: node:sqlite` | Node is older than 22.13, or the distro's Node 20 is first on the PATH. `node --version`, `which -a node`, section 1. | +| `ExperimentalWarning: SQLite is an experimental feature` in the journal | Harmless. Printed once per start on some Node versions. | +| `SQLITE_CANTOPEN` / `unable to open database file` | `DB_PATH`'s directory is not writable by `upstream`: wrong path in `upstream.env`, `/var/lib/upstream` created by hand with other ownership (`chown -R upstream:upstream /var/lib/upstream`), or `ProtectSystem=strict` enabled without `ReadWritePaths=/var/lib/upstream`. | +| `attempt to write a readonly database` / `unable to open database file` right after using the CLI | `admin.js` was run as root and left root-owned `game.db-wal` / `-shm`. Stop the game, `chown upstream:upstream /var/lib/upstream/game.db*`, start. Use `upstream-admin`, which switches user. | +| `migration NNN_x.sql was edited after it was applied` | An applied migration changed on disk (checksum mismatch). Restore it from git; changes go in a new migration. | +| `UPSTREAM failed to start: ...` with `EADDRINUSE` | Another process on the port (`ss -ltnp \| grep 8080`) or two copies. Change `PORT` and the NPM forward port together. | +| `IPv6 is not available (...); falling back to 0.0.0.0` | The kernel has no IPv6. IPv4 keeps working; set `HOST=0.0.0.0` to silence it. | +| `status=226/NAMESPACE` | The optional namespace hardening is on in an LXC without Nesting: enable **Options > Features > Nesting** and restart the CT, or comment the block out. | +| `Cannot find module 'ws'` | `npm ci --omit=dev` was not run in `/opt/upstream`. | +| 502 Bad Gateway from NPM | Upstream unreachable: `systemctl status upstream`, `curl -i http://:8080/healthz` from the NPM host, forward IP/port, firewall. | +| Page loads but a new deploy still shows the old client | NPM *Cache Assets* is on, or a service layer ignores `no-cache`. Switch it off, hard-reload. | +| Signup answers 403 `signup_closed` | `SIGNUP_CODE` is set. Send `{"invite": ""}` in the signup body, or unset it and restart. | +| Login/signup answers 429 `rate_limited` for many players | They all arrive from one address: the proxy is not trusted so the per-IP budget is shared (log says `ip=`). Set `TRUSTED_PROXIES`. Login and signup allow about one request per 10 s per address, burst 8; a whole classroom behind one NAT can hit that. | +| Game seems frozen: builds never finish | `upstream-admin status`: `OVERDUE` events mean the scheduler is not running (server stopped or stuck) or handlers fail: `upstream-admin events --status failed`, journal `event N ... failed`. A restart catches up everything in order. | +| Banned user still plays | They cannot: `ban` revokes every token and blocks login. Check the username spelling (`upstream-admin users --banned`). | +| `database is locked` from the CLI | The game held a write lock longer than the 5 s busy timeout. Retry. | +| `upstream-backup.service` failed | `journalctl -u upstream-backup`. Typical: disk full, or the integrity check of the new snapshot failed (then nothing was kept and nothing pruned; check the disk and the `game.db` itself). | +| Backups not appearing | `systemctl list-timers upstream-backup.timer`; the timer must be **enabled** (`systemctl enable --now upstream-backup.timer`), not just installed. | +| World reset by mistake | Restore the snapshot taken before (section 7), or the one `reset-world --backup` wrote. | +| (stage 6) WebSocket upgrade answered 426 / 403 / 429 | 426: **Websockets Support** off in NPM. 403: origin check, see `ALLOWED_ORIGINS` and the notes in section 5. 429: more than `MAX_CONN_PER_IP` sockets from one address. | diff --git a/docs/DESIGN.md b/docs/DESIGN.md index bdf9bf3..ddeb1bf 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -184,6 +184,27 @@ POP view (buildings + queue), Resource view (slots), Map (pan/zoom, tile info, s station, movements list), Reports, Messages, Alliance, Exchange, Rankings, Profile/settings. Every countdown is computed from `serverTime`. +## Stage 3/4 clarifications (what the server does, where DESIGN.md was silent) + +- **Training/research:** training time = unit time x count / (1 + 0.03 x level of the training building) / world speed; batches of one + building queue one after another. Research cost = 8 x the unit's cost x 1.35^(level-1), time 30 min x 1.3^(level-1) / (1 + 0.03 x lab + level); research level n needs Research lab n + 2. +- **Roles per movement:** scan = port scanners only; raid = attackers and defenders (no siege); attack = + DDoS rigs and exploit kits; + takeover = + M&A teams (at least one); reinforce = anything that moves; settle = exactly three Rollout crews. Honeypots never move. +- **Combat:** formulas as above; ties go to the defender; a unit group loses `round(n x fraction)` per type. Raid: BOTH sides lose + `0.5 x (weaker/stronger)^1.5` whoever wins. Defenders are home crews plus each reinforcement group (own research each), counted only + while online. The cold-spare cache applies to raids only; a full attack takes loot from the whole stock. Loot is split evenly over Fiber, + Hardware, Capital, leftovers going to the others, capped by the survivors' carry. Exploit kits count by survivors. +- **Scan:** `sa` vs `sd` = scanners x (1 + 5% per defence-research level of port_scanner). Success needs `sa > sd`; `detail` is `basic` + (units, resources) and `full` at 2:1 (+ buildings, loyalty, the target's outgoing movements with their types). A failed scan loses all + scanners and reveals the scanner to the target; a successful one loses `0.5 x (sd/sa)^1.5`. +- **Incumbent site defence:** `600 x (1 +- 25% per site, seeded) x (1 + 4% x world days)`, world days = real days x speed; sites are scanned + or attacked, never raided or taken over, and never fight back. +- **Power:** when the battery is empty and net power is negative, all units in that POP are offline; after 24 h / speed the most + expensive are decommissioned until the draw fits. +- **Transport:** 12 tiles/h, 500 per link, links = Internet exchange level; a link is busy until the empty carriers are back. +- **Protection and recall:** see S3-4 and S3-7 in DECISIONS.md; the recall window is 90 s of real time (not divided by world speed). + ## Open questions - One or two defence stats per unit? diff --git a/docs/NEXT.md b/docs/NEXT.md index 38e42fa..2a90879 100644 --- a/docs/NEXT.md +++ b/docs/NEXT.md @@ -7,5 +7,64 @@ Honest status, updated at the end of every stage. - Stage 1 economy (server): lazy resources, buildings, build queue, storage caps, power battery. - Stage 2 world (server): seeded tiles, spawn ring, map viewport query. +## Stage 5 (partial): social, server only +Built (migration `003_social.sql`): alliances (found, invite/accept/decline/cancel, leave, kick, roles, leader transfer, disband, +pinned notes, member list with POP count and last online), diplomacy between alliances (war, neutral, NAP, confederation; +proposals; 24 h / speed pact cancel through the `diploChange` event; revoke), messages (DM, alliance broadcast, inbox/outbox/thread/ +alliance feed, read, delete own copy, block list, DB-backed rate limit, text sanitising), rankings (operators, alliances, battles), +`alliance` in `/me` and `/map`, lookup helpers in `server/alliances.js` (`operatorRelation`, `atWar`, `confederated`, `pactPartners`). +Tests: `test/social-*.test.js` (pure rules, alliances, diplomacy with the fake clock and event queue, messages, rankings), every +response in them is checked against its declared schema (`createTestServer({ contract: true })` in `test/helpers.js`). + +Not done: +- Marketplace / Internet exchange and resource transport (waits for the movement system of stage 3). +- Shared report folder of the alliance (needs reports from stage 3), confederation effects (reinforce, see incoming) and the pact + effect "no attacks inside a NAP/confederation": the military stage must call `alliances.pactPartners` / `confederated`; nothing + enforces it yet. +- No web client, no WebSocket push (notifications rows are written; stage 6 pushes them). +- Message retention/cleanup of old rows, alliance rename/description, mass-mail abuse reporting, sitter accounts. +- Rankings are not cached; battle rankings stay empty until the military stage writes `operator_stats`. +- Not run: Playwright, load, or any bot balance run; the social numbers in `SOCIAL` (limits, TTLs, role table) are first guesses. + +## Stage 3/4: military and expansion (server only) +Built (migration `002_military.sql`: `town_units`, `stationed`, `town_research`, `town_power`, `movements`, `reports`, `report_recipients`, +`operator_stats`, `incumbent_takes`): 10 unit types and research in `data.js`/`rules.js`; training queue (`trainDone` per batch, +sequential per building); research (`researchDone`); movements scan/raid/attack/takeover/reinforce/settle/transport with latency, ETA, +recall (90 s), return legs with loot; combat resolved at arrival in the event queue (full attack, raid, firewall vs DDoS rigs, exploit +kits on a chosen building, loot with Rack hall cache, losses, reinforcements, research, battle points in `operator_stats`); +scans with intel and detection; takeover with loyalty, capital and last-POP protection, footprint gate; founding POPs with wild-slot +choice; incumbent sites (static defence growing with world age, one-time Hardware bonus, +10% research speed per site); beginner +protection (both directions, re-checked at arrival); power: offline units when the battery is empty, decommission after 24 h +(`powerCheck`); incoming warnings with hidden type; reports (shared row, per-user read flag, 14 day cleanup event); transport movement +and arrival hook (`movements.hooks.transportArrived`) for the trade stage. Routes: see docs/API.md, all in `docs/openapi.json`. +Tests: `test/military-*.test.js` (rules as pure functions, train queue order, raid end to end, event order and determinism, takeover and +its protections, offline units and decommission, restart catch-up from a reopened DB file, protection, settle, incumbent, transport, +recall, research, reports/cursor/retention, API smoke over HTTP). Fake clock, in-memory DB, port 0; no Playwright. +Not done / not claimed: +- **Nothing is balanced.** All unit stats, costs, research curves, incumbent defence and the 50-unit-scale combat numbers are first guesses; + there was no bot run (`tools/bot.js` does not exist yet). Do not cite any of them as tuned. +- Training cannot be cancelled; reports cannot be shared to the alliance yet (the shared report folder needs a table in the social stage); + confederates do not see each other's incoming movements (only reinforce is wired); no sitter, no night protection. +- A building damaged by exploit kits that has an upgrade in flight jumps to the queued level when that finishes (`buildDone` sets absolute levels). +- Units in transit draw no power from anyone; an operator cannot choose a new capital POP (no command); a captured POP keeps its footprint. +- Backbone landing sites and the Backbone node (end game) are not part of this stage. + +## Client (stages 1-2 web client) +Built: `public/` vanilla JS, no build step, strict-CSP friendly (no inline scripts or handlers, no external requests). +- Shell (`js/main.js`): session, `App.registerScreen({id, titleKey, navKey, icon, hud, render, onShow, onHide, onLang})`, bottom nav + (left rail in landscape and on wide screens), live resource bar ticked with `rules.resourcesAt` from the server clock, hash routing. +- Screens (`js/screens/`): login/signup (invite field appears after `signup_closed`), POP (resource fields by type, infrastructure, + build queue with countdowns and cancel, power panel, detail sheet with the server's `next` plan, live affordability, rename), + map (`js/render.js` canvas: pan, pinch, wheel, keyboard, culling; chunked `GET /map` cache; tile info sheet), alerts + (`GET /notifications`), settings (language, device tokens + revoke, logout). +- `js/api.js`: bearer token, serverTime offset, retry/backoff (network, 429 + Retry-After, 502-504), `Idempotency-Key` per intent, + `ApiError.code`, event emitter with a reserved `push` event (no WebSocket client yet). +- `js/i18n.js`: en + nb, all player-facing names; `PWA`: manifest + icons (no service worker, so no offline mode). +- Tests: `test/client-i18n.test.js` (key parity, names, error codes, formatting), `test/client-api.test.js` (retry, idempotency, offset). +- Looked at with headless Chromium screenshots (phone portrait, phone landscape, desktop) and one scripted signup/build/cancel/map-tap + flow on a phone profile. Not run: real devices, Safari/iOS, Playwright suite. +Gaps: the unread badge is stored in localStorage (no "mark read" route); `/me` exposes the world seed which the client ignores; +no push, no service worker, canvas has no inertia/fling, no light theme. + ## Not done - Everything else. See CLAUDE.md "Working in stages". diff --git a/docs/openapi.json b/docs/openapi.json index c5d860c..663a494 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "UPSTREAM API", "version": "1.0.0", - "description": "Generated by tools/gen-openapi.js from server/routes. Every response carries serverTime; errors use the { error: { code, message, details } } envelope. Codes: bad_request, validation_failed, unauthorized, invalid_credentials, forbidden, not_found, method_not_allowed, conflict, request_in_progress, idempotency_key_reuse, payload_too_large, rate_limited, internal_error, signup_closed, username_taken, world_full, unknown_building, not_buildable, max_level, requirements_not_met, already_queued, queue_full, not_enough_resources" + "description": "Generated by tools/gen-openapi.js from server/routes. Every response carries serverTime; errors use the { error: { code, message, details } } envelope. Codes: bad_request, validation_failed, unauthorized, invalid_credentials, forbidden, not_found, method_not_allowed, conflict, request_in_progress, idempotency_key_reuse, payload_too_large, rate_limited, internal_error, signup_closed, username_taken, world_full, unknown_building, not_buildable, max_level, requirements_not_met, already_queued, queue_full, not_enough_resources, peering_office_required, already_in_alliance, not_in_alliance, alliance_name_taken, alliance_tag_taken, alliance_full, invite_expired, leader_must_transfer, notes_full, diplomacy_invalid, diplomacy_pending, proposal_exists, proposal_expired, unknown_unit, not_researchable, not_enough_units, units_offline, invalid_target, target_protected, protection_active, out_of_range, footprint_too_low, cannot_takeover, recall_expired, capacity_exceeded, no_transport_link" }, "servers": [ { @@ -11,6 +11,2106 @@ } ], "paths": { + "/alliance-invites": { + "get": { + "summary": "Open invites addressed to you", + "tags": [ + "alliances" + ], + "operationId": "getAllianceinvites", + "parameters": [], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceivedInviteList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliance-invites/{id}/accept": { + "post": { + "summary": "Accept an invite (needs Peering office 1+ and no alliance yet)", + "tags": [ + "alliances" + ], + "operationId": "postAllianceinvitesIdAccept", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: alliance_full, already_in_alliance, conflict, invite_expired, peering_office_required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliance-invites/{id}/decline": { + "post": { + "summary": "Decline an invite", + "tags": [ + "alliances" + ], + "operationId": "postAllianceinvitesIdDecline", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: alliance_full, already_in_alliance, conflict, invite_expired, peering_office_required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances": { + "get": { + "summary": "Alliance directory of a world, optional name/tag search (cursor: after = last id)", + "tags": [ + "alliances" + ], + "operationId": "getAlliances", + "parameters": [ + { + "name": "q", + "in": "query", + "required": false, + "schema": { + "type": "string", + "maxLength": 40 + } + }, + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "summary": "Found an alliance (needs Peering office 1+); you become its leader", + "tags": [ + "alliances" + ], + "operationId": "postAlliances", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name", + "tag" + ], + "properties": { + "name": { + "type": "string", + "minLength": 3, + "maxLength": 60 + }, + "tag": { + "type": "string", + "minLength": 2, + "maxLength": 5 + }, + "worldId": { + "type": "integer", + "minimum": 1 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceCreated" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: alliance_name_taken, alliance_tag_taken, already_in_alliance, peering_office_required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/mine": { + "get": { + "summary": "Your alliance, role and permissions (null alliance when you are not in one)", + "tags": [ + "alliances" + ], + "operationId": "getAlliancesMine", + "parameters": [ + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceMine" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}": { + "get": { + "summary": "Public alliance profile: size, leader, footprint, your role and relation to it", + "tags": [ + "alliances" + ], + "operationId": "getAlliancesId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceDetail" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/diplomacy": { + "get": { + "summary": "Relations with other alliances (with scheduled changes) and open proposals (members only)", + "tags": [ + "diplomacy" + ], + "operationId": "getAlliancesIdDiplomacy", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Diplomacy" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "summary": "Change the relation to another alliance (needs diplomacy): war applies at once from neutral, pacts need acceptance, cancelling a pact takes 24 h / world speed", + "tags": [ + "diplomacy" + ], + "operationId": "postAlliancesIdDiplomacy", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "targetId", + "state" + ], + "properties": { + "targetId": { + "type": "integer", + "minimum": 1 + }, + "state": { + "type": "string", + "enum": [ + "war", + "neutral", + "nap", + "confed" + ] + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiplomacyResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: diplomacy_invalid, diplomacy_pending, proposal_exists", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/diplomacy/{otherId}/pending": { + "delete": { + "summary": "Take back a scheduled cancel before it takes effect (the alliance that started it, needs diplomacy)", + "tags": [ + "diplomacy" + ], + "operationId": "deleteAlliancesIdDiplomacyOtherIdPending", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "otherId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/disband": { + "post": { + "summary": "Disband the alliance (leader only)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdDisband", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/invite": { + "post": { + "summary": "Invite an operator by id or name (needs invite). Repeating it returns the pending invite", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdInvite", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "operatorId": { + "type": "integer", + "minimum": 1 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: alliance_full, already_in_alliance, conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/invites": { + "get": { + "summary": "Pending invites sent by this alliance (needs viewInvites)", + "tags": [ + "alliances" + ], + "operationId": "getAlliancesIdInvites", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceInviteList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/invites/{inviteId}": { + "delete": { + "summary": "Cancel a pending invite (needs cancelInvite)", + "tags": [ + "alliances" + ], + "operationId": "deleteAlliancesIdInvitesInviteId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "inviteId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/kick": { + "post": { + "summary": "Remove a member you outrank (needs kick)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdKick", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "operatorId" + ], + "properties": { + "operatorId": { + "type": "integer", + "minimum": 1 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/leave": { + "post": { + "summary": "Leave the alliance. The leader must transfer first unless alone (then it is disbanded)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdLeave", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: leader_must_transfer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/members": { + "get": { + "summary": "Member list with role, POP count, footprint and last online (members only)", + "tags": [ + "alliances" + ], + "operationId": "getAlliancesIdMembers", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceMemberList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/notes": { + "get": { + "summary": "Pinned notes (members only)", + "tags": [ + "alliances" + ], + "operationId": "getAlliancesIdNotes", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceNoteList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "summary": "Pin a note (needs editNotes)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdNotes", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "text" + ], + "properties": { + "text": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceNoteResponse" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: notes_full", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/notes/{noteId}": { + "post": { + "summary": "Edit a pinned note (needs editNotes)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdNotesNoteId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "noteId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "text" + ], + "properties": { + "text": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllianceNoteResponse" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "summary": "Remove a pinned note (needs editNotes)", + "tags": [ + "alliances" + ], + "operationId": "deleteAlliancesIdNotesNoteId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "noteId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/role": { + "post": { + "summary": "Set a member role: diplomat, officer or member (leader only)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdRole", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "operatorId", + "role" + ], + "properties": { + "operatorId": { + "type": "integer", + "minimum": 1 + }, + "role": { + "type": "string", + "enum": [ + "diplomat", + "officer", + "member" + ] + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/alliances/{id}/transfer": { + "post": { + "summary": "Hand leadership to another member; you become an officer (leader only)", + "tags": [ + "alliances" + ], + "operationId": "postAlliancesIdTransfer", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "operatorId" + ], + "properties": { + "operatorId": { + "type": "integer", + "minimum": 1 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/auth/login": { "post": { "summary": "Log in on a device and get a bearer token", @@ -412,6 +2512,284 @@ } } }, + "/diplomacy/proposals/{proposalId}": { + "delete": { + "summary": "Withdraw a proposal your alliance made (needs diplomacy)", + "tags": [ + "diplomacy" + ], + "operationId": "deleteDiplomacyProposalsProposalId", + "parameters": [ + { + "name": "proposalId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/diplomacy/proposals/{proposalId}/accept": { + "post": { + "summary": "Accept a diplomatic proposal addressed to your alliance (needs diplomacy)", + "tags": [ + "diplomacy" + ], + "operationId": "postDiplomacyProposalsProposalIdAccept", + "parameters": [ + { + "name": "proposalId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict, diplomacy_invalid, diplomacy_pending, proposal_expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/diplomacy/proposals/{proposalId}/decline": { + "post": { + "summary": "Decline a diplomatic proposal addressed to your alliance (needs diplomacy)", + "tags": [ + "diplomacy" + ], + "operationId": "postDiplomacyProposalsProposalIdDecline", + "parameters": [ + { + "name": "proposalId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict, diplomacy_invalid, diplomacy_pending, proposal_expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/map": { "get": { "summary": "Map viewport: rural areas, incumbent sites and POPs within (x±r, y±r); land tiles are implied", @@ -519,6 +2897,103 @@ } } }, + "/map/tile": { + "get": { + "summary": "Public information about one tile for the send dialog: what is there, owner, distance from your POPs, whether you could settle it", + "tags": [ + "map" + ], + "operationId": "getMapTile", + "parameters": [ + { + "name": "x", + "in": "query", + "required": true, + "schema": { + "type": "integer", + "minimum": -1000, + "maximum": 1000 + } + }, + { + "name": "y", + "in": "query", + "required": true, + "schema": { + "type": "integer", + "minimum": -1000, + "maximum": 1000 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TileInfo" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/me": { "get": { "summary": "The current user, their operators and POPs", @@ -566,6 +3041,1323 @@ } } }, + "/messages": { + "post": { + "summary": "Send a message to an operator (toOperatorId or toName) or to your alliance (toAlliance). Plain text, max 2000 characters, rate-limited", + "tags": [ + "messages" + ], + "operationId": "postMessages", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "text" + ], + "properties": { + "text": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "toOperatorId": { + "type": "integer", + "minimum": 1 + }, + "toName": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "toAlliance": { + "type": "boolean" + }, + "worldId": { + "type": "integer", + "minimum": 1 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageSent" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: not_in_alliance", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Error codes: rate_limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/alliance": { + "get": { + "summary": "Broadcasts of your alliance, newest first", + "tags": [ + "messages" + ], + "operationId": "getMessagesAlliance", + "parameters": [ + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: not_in_alliance", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/blocks": { + "get": { + "summary": "Operators you blocked", + "tags": [ + "messages" + ], + "operationId": "getMessagesBlocks", + "parameters": [ + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlockList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "summary": "Block an operator: their messages are no longer delivered to you (they are not told)", + "tags": [ + "messages" + ], + "operationId": "postMessagesBlocks", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "operatorId" + ], + "properties": { + "operatorId": { + "type": "integer", + "minimum": 1 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/blocks/{operatorId}": { + "delete": { + "summary": "Unblock an operator", + "tags": [ + "messages" + ], + "operationId": "deleteMessagesBlocksOperatorId", + "parameters": [ + { + "name": "operatorId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/inbox": { + "get": { + "summary": "Received messages, newest first (cursor: after = last id of the previous page); `unread` counts all unread", + "tags": [ + "messages" + ], + "operationId": "getMessagesInbox", + "parameters": [ + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "unread", + "in": "query", + "required": false, + "schema": { + "type": "boolean" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/outbox": { + "get": { + "summary": "Sent messages, newest first", + "tags": [ + "messages" + ], + "operationId": "getMessagesOutbox", + "parameters": [ + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/read": { + "post": { + "summary": "Mark received messages read: a list of ids (max 100) or all", + "tags": [ + "messages" + ], + "operationId": "postMessagesRead", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ids": { + "type": "array", + "maxItems": 100, + "items": { + "type": "integer", + "minimum": 1 + } + }, + "all": { + "type": "boolean" + }, + "worldId": { + "type": "integer", + "minimum": 1 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/thread/{operatorId}": { + "get": { + "summary": "The conversation with one operator, both directions, newest first", + "tags": [ + "messages" + ], + "operationId": "getMessagesThreadOperatorId", + "parameters": [ + { + "name": "operatorId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/messages/{id}": { + "get": { + "summary": "One message you sent or received", + "tags": [ + "messages" + ], + "operationId": "getMessagesId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageResponse" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "summary": "Delete your own copy of a message (the other side keeps theirs)", + "tags": [ + "messages" + ], + "operationId": "deleteMessagesId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Changed" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/movements": { + "post": { + "summary": "Send units (scan, raid, attack, takeover, reinforce, settle) or resources (transport) from one of your POPs. Target = toTownId or the tile x,y", + "tags": [ + "movements" + ], + "operationId": "postMovements", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "fromTownId", + "type" + ], + "properties": { + "fromTownId": { + "type": "integer", + "minimum": 1 + }, + "type": { + "type": "string", + "enum": [ + "scan", + "raid", + "attack", + "takeover", + "reinforce", + "settle", + "transport" + ] + }, + "toTownId": { + "type": "integer", + "minimum": 1 + }, + "x": { + "type": "integer", + "minimum": -1000, + "maximum": 1000 + }, + "y": { + "type": "integer", + "minimum": -1000, + "maximum": 1000 + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + }, + "cargo": { + "type": "object", + "additionalProperties": true, + "description": "transport only: fiber/hardware/capital -> amount" + }, + "target": { + "type": "string", + "maxLength": 32, + "pattern": "^[a-z0-9_]+$", + "description": "exploit kits: the building (f1..f18 or an infrastructure type) to damage on a win" + }, + "wild": { + "type": "array", + "maxItems": 2, + "items": { + "type": "string", + "maxLength": 32 + }, + "description": "settle: the two wild slot field types of the new POP" + }, + "confirmEndProtection": { + "type": "boolean", + "description": "raid/attack/takeover from a protected operator: attacking ends beginner protection" + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MovementSent" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found, unknown_unit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: cannot_takeover, capacity_exceeded, footprint_too_low, invalid_target, no_transport_link, not_enough_resources, not_enough_units, out_of_range, protection_active, target_protected, units_offline", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "get": { + "summary": "Your active movements and other operators' movements heading for your POPs (incoming warnings: origin and ETA only, type hidden)", + "tags": [ + "movements" + ], + "operationId": "getMovements", + "parameters": [ + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MovementList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/movements/{id}/recall": { + "post": { + "summary": "Turn an outbound movement around within the first 90 seconds", + "tags": [ + "movements" + ], + "operationId": "postMovementsIdRecall", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecallResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict, recall_expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/notifications": { "get": { "summary": "Notifications for this user (cursor: after = last seen id)", @@ -643,6 +4435,611 @@ } } }, + "/rankings/alliances": { + "get": { + "summary": "Alliances by summed footprint of their members", + "tags": [ + "rankings" + ], + "operationId": "getRankingsAlliances", + "parameters": [ + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RankAlliances" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/rankings/battles": { + "get": { + "summary": "Attackers / defenders by battle points (`by`: attack, defense or total). Empty with available=false until the military stage records points", + "tags": [ + "rankings" + ], + "operationId": "getRankingsBattles", + "parameters": [ + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "by", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": [ + "attack", + "defense", + "total" + ] + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RankBattles" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/rankings/operators": { + "get": { + "summary": "Operators by footprint (cursor: after = number of ranks already seen)", + "tags": [ + "rankings" + ], + "operationId": "getRankingsOperators", + "parameters": [ + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RankOperators" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/reports": { + "get": { + "summary": "Your reports, newest first (cursor: after = id of the last report seen, returns older ones)", + "tags": [ + "reports" + ], + "operationId": "getReports", + "parameters": [ + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "unread", + "in": "query", + "required": false, + "schema": { + "type": "boolean" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/reports/read-all": { + "post": { + "summary": "Mark all your reports as read", + "tags": [ + "reports" + ], + "operationId": "postReportsReadall", + "parameters": [], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Marked" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/reports/{id}": { + "get": { + "summary": "One report with its full data", + "tags": [ + "reports" + ], + "operationId": "getReportsId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportResponse" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/reports/{id}/read": { + "post": { + "summary": "Mark a report as read", + "tags": [ + "reports" + ], + "operationId": "postReportsIdRead", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Marked" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/towns/{id}": { "get": { "summary": "Full state of one of your POPs: resources, power, buildings, build queue", @@ -996,6 +5393,342 @@ } } } + }, + "/towns/{id}/research": { + "post": { + "summary": "Research +5% attack or defence for one unit type (one research at a time per POP, needs a Research lab)", + "tags": [ + "units" + ], + "operationId": "postTownsIdResearch", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "unit", + "stat" + ], + "properties": { + "unit": { + "type": "string", + "maxLength": 32, + "pattern": "^[a-z_]+$" + }, + "stat": { + "type": "string", + "enum": [ + "attack", + "defence" + ] + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResearchResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found, unknown_unit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: max_level, not_enough_resources, not_researchable, queue_full, requirements_not_met", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/towns/{id}/train": { + "post": { + "summary": "Queue a batch of one unit type. Batches of the same training building run in order; units appear when the batch is done", + "tags": [ + "units" + ], + "operationId": "postTownsIdTrain", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "unit", + "count" + ], + "properties": { + "unit": { + "type": "string", + "maxLength": 32, + "pattern": "^[a-z_]+$" + }, + "count": { + "type": "integer", + "minimum": 1, + "maximum": 5000 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TrainResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found, unknown_unit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: not_enough_resources, queue_full, requirements_not_met", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/towns/{id}/withdraw": { + "post": { + "summary": "Send reinforcements standing in this POP home (host kicks them out, or the units' owner calls them back)", + "tags": [ + "movements" + ], + "operationId": "postTownsIdWithdraw", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ownerTownId" + ], + "properties": { + "ownerTownId": { + "type": "integer", + "minimum": 1 + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "defaults to the whole group" + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WithdrawResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found, unknown_unit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: not_enough_units", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } } }, "components": { @@ -1143,6 +5876,22 @@ "type": "integer", "nullable": true }, + "alliance": { + "type": "object", + "nullable": true, + "properties": { + "id": { + "type": "integer" + }, + "tag": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "additionalProperties": true + }, "protectionUntil": { "type": "integer" }, @@ -1161,6 +5910,7 @@ "name", "asNumber", "allianceId", + "alliance", "protectionUntil", "world", "towns" @@ -1536,6 +6286,9 @@ "capital" ], "additionalProperties": true + }, + "military": { + "$ref": "#/components/schemas/TownMilitary" } }, "required": [ @@ -1608,6 +6361,22 @@ "type": "integer", "nullable": true }, + "alliance": { + "type": "object", + "nullable": true, + "properties": { + "id": { + "type": "integer" + }, + "tag": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "additionalProperties": true + }, "protected": { "type": "boolean" } @@ -1617,6 +6386,7 @@ "name", "asNumber", "allianceId", + "alliance", "protected" ], "additionalProperties": true @@ -1811,6 +6581,986 @@ ], "additionalProperties": true }, + "AllianceBrief": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "tag": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "tag", + "name" + ], + "additionalProperties": true + }, + "OperatorBrief": { + "type": "object", + "properties": { + "operatorId": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "operatorId", + "name" + ], + "additionalProperties": true + }, + "AllianceInfo": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "worldId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "sizeCap": { + "type": "integer" + }, + "memberCount": { + "type": "integer" + }, + "leader": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "createdAt": { + "type": "integer" + } + }, + "required": [ + "id", + "worldId", + "name", + "tag", + "sizeCap", + "memberCount", + "leader", + "createdAt" + ], + "additionalProperties": true + }, + "AllianceDetail": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "alliance": { + "$ref": "#/components/schemas/AllianceInfo" + } + }, + "required": [ + "serverTime", + "alliance" + ], + "additionalProperties": true + }, + "AllianceMine": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "operatorId": { + "type": "integer" + }, + "worldId": { + "type": "integer" + }, + "alliance": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "role": { + "type": "string", + "nullable": true + }, + "permissions": { + "type": "array", + "items": { + "type": "string" + } + }, + "peeringLevel": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "operatorId", + "worldId", + "alliance", + "role", + "permissions", + "peeringLevel" + ], + "additionalProperties": true + }, + "AllianceList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AllianceInfo" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "AllianceMember": { + "type": "object", + "properties": { + "operatorId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "asNumber": { + "type": "integer" + }, + "role": { + "type": "string" + }, + "joinedAt": { + "type": "integer" + }, + "towns": { + "type": "integer" + }, + "footprint": { + "type": "number" + }, + "lastOnline": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "operatorId", + "name", + "asNumber", + "role", + "joinedAt", + "towns", + "footprint", + "lastOnline" + ], + "additionalProperties": true + }, + "AllianceMemberList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AllianceMember" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "AllianceCreated": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "allianceId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "sizeCap": { + "type": "integer" + }, + "role": { + "type": "string" + } + }, + "required": [ + "serverTime", + "allianceId", + "name", + "tag", + "sizeCap", + "role" + ], + "additionalProperties": true + }, + "AllianceInvite": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "operator": { + "$ref": "#/components/schemas/OperatorBrief" + }, + "invitedBy": { + "$ref": "#/components/schemas/OperatorBrief" + }, + "createdAt": { + "type": "integer" + }, + "expiresAt": { + "type": "integer" + } + }, + "required": [ + "id", + "operator", + "invitedBy", + "createdAt", + "expiresAt" + ], + "additionalProperties": true + }, + "AllianceInviteList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AllianceInvite" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "ReceivedInvite": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "operatorId": { + "type": "integer" + }, + "alliance": { + "$ref": "#/components/schemas/AllianceBrief" + }, + "invitedBy": { + "$ref": "#/components/schemas/OperatorBrief" + }, + "createdAt": { + "type": "integer" + }, + "expiresAt": { + "type": "integer" + } + }, + "required": [ + "id", + "operatorId", + "alliance", + "invitedBy", + "createdAt", + "expiresAt" + ], + "additionalProperties": true + }, + "ReceivedInviteList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReceivedInvite" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "InviteResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "inviteId": { + "type": "integer" + }, + "operatorId": { + "type": "integer" + }, + "expiresAt": { + "type": "integer" + }, + "changed": { + "type": "boolean" + } + }, + "required": [ + "serverTime", + "inviteId", + "operatorId", + "expiresAt", + "changed" + ], + "additionalProperties": true + }, + "Changed": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "changed": { + "type": "boolean" + } + }, + "required": [ + "serverTime", + "changed" + ], + "additionalProperties": true + }, + "AllianceNote": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "authorId": { + "type": "integer" + }, + "text": { + "type": "string" + }, + "createdAt": { + "type": "integer" + }, + "updatedAt": { + "type": "integer" + } + }, + "required": [ + "id", + "authorId", + "text", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "AllianceNoteResponse": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "note": { + "$ref": "#/components/schemas/AllianceNote" + } + }, + "required": [ + "serverTime", + "note" + ], + "additionalProperties": true + }, + "AllianceNoteList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AllianceNote" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "Relation": { + "type": "object", + "properties": { + "other": { + "type": "object", + "additionalProperties": true + }, + "state": { + "type": "string" + }, + "since": { + "type": "integer" + }, + "pending": { + "type": "object", + "nullable": true, + "additionalProperties": true + } + }, + "required": [ + "other", + "state", + "since", + "pending" + ], + "additionalProperties": true + }, + "Proposal": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "other": { + "type": "object", + "additionalProperties": true + }, + "state": { + "type": "string" + }, + "createdAt": { + "type": "integer" + }, + "expiresAt": { + "type": "integer" + } + }, + "required": [ + "id", + "other", + "state", + "createdAt", + "expiresAt" + ], + "additionalProperties": true + }, + "Diplomacy": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "allianceId": { + "type": "integer" + }, + "relations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Relation" + } + }, + "proposalsIn": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Proposal" + } + }, + "proposalsOut": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Proposal" + } + } + }, + "required": [ + "serverTime", + "allianceId", + "relations", + "proposalsIn", + "proposalsOut" + ], + "additionalProperties": true + }, + "DiplomacyResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "result": { + "type": "string" + }, + "from": { + "type": "string" + }, + "state": { + "type": "string" + } + }, + "required": [ + "serverTime", + "result", + "from", + "state" + ], + "additionalProperties": true + }, + "Message": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "kind": { + "type": "string" + }, + "direction": { + "type": "string" + }, + "thread": { + "type": "string" + }, + "from": { + "$ref": "#/components/schemas/OperatorBrief" + }, + "to": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "alliance": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "text": { + "type": "string" + }, + "createdAt": { + "type": "integer" + }, + "readAt": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "id", + "kind", + "direction", + "thread", + "from", + "to", + "alliance", + "text", + "createdAt", + "readAt" + ], + "additionalProperties": true + }, + "MessageList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Message" + } + }, + "next": { + "type": "integer", + "nullable": true + }, + "unread": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "MessageResponse": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "message": { + "$ref": "#/components/schemas/Message" + } + }, + "required": [ + "serverTime", + "message" + ], + "additionalProperties": true + }, + "MessageSent": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "messageId": { + "type": "integer" + }, + "kind": { + "type": "string" + }, + "recipients": { + "type": "integer" + }, + "createdAt": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "messageId", + "kind", + "recipients", + "createdAt" + ], + "additionalProperties": true + }, + "BlockList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "operatorId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "integer" + } + }, + "required": [ + "operatorId", + "name", + "createdAt" + ], + "additionalProperties": true + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "RankOperator": { + "type": "object", + "properties": { + "rank": { + "type": "integer" + }, + "operatorId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "asNumber": { + "type": "integer" + }, + "allianceId": { + "type": "integer", + "nullable": true + }, + "allianceTag": { + "type": "string", + "nullable": true + }, + "towns": { + "type": "integer" + }, + "footprint": { + "type": "number" + } + }, + "required": [ + "rank", + "operatorId", + "name", + "asNumber", + "allianceId", + "allianceTag", + "towns", + "footprint" + ], + "additionalProperties": true + }, + "RankAlliance": { + "type": "object", + "properties": { + "rank": { + "type": "integer" + }, + "allianceId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "members": { + "type": "integer" + }, + "towns": { + "type": "integer" + }, + "footprint": { + "type": "number" + } + }, + "required": [ + "rank", + "allianceId", + "name", + "tag", + "members", + "towns", + "footprint" + ], + "additionalProperties": true + }, + "RankBattle": { + "type": "object", + "properties": { + "rank": { + "type": "integer" + }, + "operatorId": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "allianceTag": { + "type": "string", + "nullable": true + }, + "attackPoints": { + "type": "number" + }, + "defensePoints": { + "type": "number" + } + }, + "required": [ + "rank", + "operatorId", + "name", + "allianceTag", + "attackPoints", + "defensePoints" + ], + "additionalProperties": true + }, + "RankOperators": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "you": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RankOperator" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "total", + "you", + "items", + "next" + ], + "additionalProperties": true + }, + "RankAlliances": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "you": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RankAlliance" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "total", + "you", + "items", + "next" + ], + "additionalProperties": true + }, + "RankBattles": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "by": { + "type": "string" + }, + "available": { + "type": "boolean" + }, + "total": { + "type": "integer" + }, + "you": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RankBattle" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "by", + "available", + "total", + "you", + "items", + "next" + ], + "additionalProperties": true + }, "Ok": { "type": "object", "properties": { @@ -1822,6 +7572,750 @@ "serverTime" ], "additionalProperties": true + }, + "Units": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + }, + "TrainResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "eventId": { + "type": "integer" + }, + "unit": { + "type": "string" + }, + "count": { + "type": "integer" + }, + "building": { + "type": "string" + }, + "startAt": { + "type": "integer" + }, + "dueAt": { + "type": "integer" + }, + "cost": { + "$ref": "#/components/schemas/Cost" + } + }, + "required": [ + "serverTime", + "eventId", + "unit", + "count", + "building", + "startAt", + "dueAt", + "cost" + ], + "additionalProperties": true + }, + "ResearchResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "eventId": { + "type": "integer" + }, + "unit": { + "type": "string" + }, + "stat": { + "type": "string" + }, + "toLevel": { + "type": "integer" + }, + "startedAt": { + "type": "integer" + }, + "dueAt": { + "type": "integer" + }, + "cost": { + "$ref": "#/components/schemas/Cost" + } + }, + "required": [ + "serverTime", + "eventId", + "unit", + "stat", + "toLevel", + "startedAt", + "dueAt", + "cost" + ], + "additionalProperties": true + }, + "MovementSent": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "movementId": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "fromTownId": { + "type": "integer" + }, + "toTownId": { + "type": "integer", + "nullable": true + }, + "to": { + "type": "object", + "properties": { + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + } + }, + "required": [ + "x", + "y" + ], + "additionalProperties": true + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + }, + "cargo": { + "type": "object", + "additionalProperties": true + }, + "departAt": { + "type": "integer" + }, + "arriveAt": { + "type": "integer" + }, + "protectionEnded": { + "type": "boolean" + } + }, + "required": [ + "serverTime", + "movementId", + "type", + "fromTownId", + "toTownId", + "departAt", + "arriveAt" + ], + "additionalProperties": true + }, + "RecallResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "recalled": { + "type": "integer" + }, + "returnMovementId": { + "type": "integer" + }, + "arriveAt": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "recalled", + "returnMovementId", + "arriveAt" + ], + "additionalProperties": true + }, + "WithdrawResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "movementId": { + "type": "integer" + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + }, + "arriveAt": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "movementId", + "units", + "arriveAt" + ], + "additionalProperties": true + }, + "MovementEnd": { + "type": "object", + "properties": { + "townId": { + "type": "integer", + "nullable": true + }, + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "name": { + "type": "string", + "nullable": true + }, + "owner": { + "type": "object", + "nullable": true, + "additionalProperties": true + } + }, + "required": [ + "townId", + "x", + "y" + ], + "additionalProperties": true + }, + "Movement": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "status": { + "type": "string" + }, + "ownerId": { + "type": "integer" + }, + "from": { + "$ref": "#/components/schemas/MovementEnd" + }, + "to": { + "$ref": "#/components/schemas/MovementEnd" + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + }, + "cargo": { + "type": "object", + "additionalProperties": true + }, + "departAt": { + "type": "integer" + }, + "arriveAt": { + "type": "integer" + }, + "recallableUntil": { + "type": "integer", + "nullable": true + }, + "target": { + "type": "string", + "nullable": true + }, + "parentId": { + "type": "integer", + "nullable": true + }, + "incoming": { + "type": "boolean" + } + }, + "required": [ + "id", + "type", + "status", + "from", + "to", + "departAt", + "arriveAt" + ], + "additionalProperties": true + }, + "MovementList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "outgoing": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Movement" + } + }, + "incoming": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Movement" + } + } + }, + "required": [ + "serverTime", + "outgoing", + "incoming" + ], + "additionalProperties": true + }, + "Marked": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "marked": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "marked" + ], + "additionalProperties": true + }, + "ReportItem": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "createdAt": { + "type": "integer" + }, + "role": { + "type": "string" + }, + "read": { + "type": "boolean" + }, + "summary": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "id", + "type", + "createdAt", + "role", + "read", + "summary" + ], + "additionalProperties": true + }, + "ReportList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReportItem" + } + }, + "next": { + "type": "integer", + "nullable": true + }, + "unread": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "items", + "next", + "unread" + ], + "additionalProperties": true + }, + "Report": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "createdAt": { + "type": "integer" + }, + "expiresAt": { + "type": "integer" + }, + "role": { + "type": "string" + }, + "read": { + "type": "boolean" + }, + "summary": { + "type": "object", + "additionalProperties": true + }, + "data": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "id", + "type", + "createdAt", + "expiresAt", + "role", + "read", + "summary", + "data" + ], + "additionalProperties": true + }, + "ReportResponse": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "report": { + "$ref": "#/components/schemas/Report" + } + }, + "required": [ + "serverTime", + "report" + ], + "additionalProperties": true + }, + "TileInfo": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "bonus": { + "type": "string", + "nullable": true + }, + "distances": { + "type": "array", + "items": { + "type": "object", + "properties": { + "townId": { + "type": "integer" + }, + "distance": { + "type": "number" + } + }, + "required": [ + "townId", + "distance" + ], + "additionalProperties": true + } + }, + "town": { + "type": "object", + "additionalProperties": true + }, + "incumbent": { + "type": "object", + "additionalProperties": true + }, + "settle": { + "type": "object", + "properties": { + "possible": { + "type": "boolean" + }, + "code": { + "type": "string", + "nullable": true + }, + "footprint": { + "type": "number" + }, + "footprintNeeded": { + "type": "number" + }, + "maxDistance": { + "type": "integer" + } + }, + "required": [ + "possible", + "code", + "footprint", + "footprintNeeded", + "maxDistance" + ], + "additionalProperties": true + } + }, + "required": [ + "serverTime", + "x", + "y", + "type", + "distances", + "settle" + ], + "additionalProperties": true + }, + "TownMilitary": { + "type": "object", + "properties": { + "units": { + "type": "object", + "properties": { + "home": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + }, + "online": { + "type": "boolean" + }, + "offlineSince": { + "type": "integer", + "nullable": true + }, + "stationedHere": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": true + } + }, + "stationedAway": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": true + } + } + }, + "required": [ + "home", + "online", + "offlineSince", + "stationedHere", + "stationedAway" + ], + "additionalProperties": true + }, + "training": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "unit": { + "type": "string" + }, + "count": { + "type": "integer" + }, + "building": { + "type": "string" + }, + "startAt": { + "type": "integer" + }, + "dueAt": { + "type": "integer" + } + }, + "required": [ + "id", + "unit", + "count", + "building", + "startAt", + "dueAt" + ], + "additionalProperties": true + } + }, + "trainable": { + "type": "array", + "items": { + "type": "object", + "properties": { + "unit": { + "type": "string" + }, + "building": { + "type": "string" + }, + "role": { + "type": "string" + }, + "cost": { + "$ref": "#/components/schemas/Cost" + }, + "timeMs": { + "type": "integer" + }, + "missing": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": true + } + }, + "locked": { + "type": "boolean" + } + }, + "required": [ + "unit", + "building", + "role", + "cost", + "timeMs", + "missing", + "locked" + ], + "additionalProperties": true + } + }, + "research": { + "type": "object", + "properties": { + "levels": { + "type": "object", + "additionalProperties": true + }, + "queue": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "speedBonus": { + "type": "number" + }, + "maxLevel": { + "type": "integer" + } + }, + "required": [ + "levels", + "queue", + "speedBonus", + "maxLevel" + ], + "additionalProperties": true + }, + "transport": { + "type": "object", + "properties": { + "links": { + "type": "integer" + }, + "active": { + "type": "integer" + }, + "capacityPerLink": { + "type": "integer" + } + }, + "required": [ + "links", + "active", + "capacityPerLink" + ], + "additionalProperties": true + }, + "movements": { + "type": "object", + "properties": { + "outgoing": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Movement" + } + }, + "incoming": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Movement" + } + } + }, + "required": [ + "outgoing", + "incoming" + ], + "additionalProperties": true + }, + "protectionUntil": { + "type": "integer" + } + }, + "required": [ + "units", + "training", + "trainable", + "research", + "transport", + "movements", + "protectionUntil" + ], + "additionalProperties": true } }, "securitySchemes": { @@ -1924,6 +8418,110 @@ "not_enough_resources": { "status": 409, "description": "Not enough resources." + }, + "peering_office_required": { + "status": 409, + "description": "A Peering office (level 1 or higher) is needed to found or join an alliance." + }, + "already_in_alliance": { + "status": 409, + "description": "That operator is already in an alliance." + }, + "not_in_alliance": { + "status": 409, + "description": "You are not in that alliance." + }, + "alliance_name_taken": { + "status": 409, + "description": "That alliance name is taken." + }, + "alliance_tag_taken": { + "status": 409, + "description": "That alliance tag is taken." + }, + "alliance_full": { + "status": 409, + "description": "The alliance has no room for more members." + }, + "invite_expired": { + "status": 409, + "description": "The invite has expired." + }, + "leader_must_transfer": { + "status": 409, + "description": "The leader must hand over leadership before leaving." + }, + "notes_full": { + "status": 409, + "description": "The alliance has reached its pinned-note limit." + }, + "diplomacy_invalid": { + "status": 409, + "description": "That diplomatic move is not allowed from the current state." + }, + "diplomacy_pending": { + "status": 409, + "description": "A diplomatic change between these alliances is already scheduled." + }, + "proposal_exists": { + "status": 409, + "description": "The other alliance already proposed this; accept their proposal instead." + }, + "proposal_expired": { + "status": 409, + "description": "The proposal has expired." + }, + "unknown_unit": { + "status": 404, + "description": "No such unit type." + }, + "not_researchable": { + "status": 409, + "description": "That unit stat cannot be researched." + }, + "not_enough_units": { + "status": 409, + "description": "Not enough units at home." + }, + "units_offline": { + "status": 409, + "description": "Those units are offline (the battery is empty)." + }, + "invalid_target": { + "status": 409, + "description": "That target is not valid for this kind of movement." + }, + "target_protected": { + "status": 409, + "description": "The target is under beginner protection." + }, + "protection_active": { + "status": 409, + "description": "Attacking ends your beginner protection; confirm to go ahead." + }, + "out_of_range": { + "status": 409, + "description": "The target is too far from your POPs." + }, + "footprint_too_low": { + "status": 409, + "description": "Your footprint is too low for another POP." + }, + "cannot_takeover": { + "status": 409, + "description": "That POP cannot be taken over." + }, + "recall_expired": { + "status": 409, + "description": "The recall window (first 90 seconds) has passed." + }, + "capacity_exceeded": { + "status": 409, + "description": "More than one transport link can carry." + }, + "no_transport_link": { + "status": 409, + "description": "All transport links are busy (or there is no Internet exchange)." } } } diff --git a/package.json b/package.json index 1d76a34..2706b9e 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "main": "server/index.js", "scripts": { "start": "node server/index.js", - "test": "node --test test/", + "test": "node --test test/*.test.js", "openapi": "node tools/gen-openapi.js", "e2e": "node e2e/run.js" }, diff --git a/public/css/style.css b/public/css/style.css new file mode 100644 index 0000000..df68459 --- /dev/null +++ b/public/css/style.css @@ -0,0 +1,324 @@ +/* UPSTREAM client styles. Dark "network ops console", phone-first. + * + * Layout modes (the shell is a grid on #app): + * portrait / narrow top bar, resource bar, scrolling view, bottom nav (thumb reach) + * rail (landscape and short) OR (width >= 900): nav becomes a left rail, so landscape phones keep their height + * Safe-area insets are applied once, on #app. Every interactive target is at least 44px tall. No hover-only affordances. + */ +:root { + --bg: #070b16; + --panel: #0c1322; + --panel2: #111b30; + --panel3: #16233d; + --line: #1d2c4c; + --line2: #2a3f6b; + --text: #d3e6ff; + --dim: #9bb2d6; + --dimmer: #7790b8; + --cyan: #4de3ff; + --amber: #ffd24d; + --red: #ff6b87; + --green: #35e0a1; + --violet: #b06cff; + --fiber: #4de3ff; + --hardware: #ff9f5a; + --capital: #5be08f; + --power: #ffd24d; + --safe-t: env(safe-area-inset-top, 0px); + --safe-r: env(safe-area-inset-right, 0px); + --safe-b: env(safe-area-inset-bottom, 0px); + --safe-l: env(safe-area-inset-left, 0px); + --nav-h: 58px; + --rail-w: 76px; + --radius: 14px; + --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; + color-scheme: dark; +} + +* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } +html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 15px/1.4 var(--font); overflow: hidden; overscroll-behavior: none; -webkit-text-size-adjust: 100%; } +button, input, select { font: inherit; color: inherit; } +button { cursor: pointer; touch-action: manipulation; } +h1, h2, h3, p, ul { margin: 0; padding: 0; } +ul { list-style: none; } +[hidden] { display: none !important; } +b { font-weight: 650; } +.mono { font-family: var(--mono); font-variant-numeric: tabular-nums; } +.dimmer { color: var(--dimmer); } +.small { font-size: 13px; } +svg.ic { width: 1.3em; height: 1.3em; flex: none; display: inline-block; vertical-align: middle; } + +:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; border-radius: 6px; } +button:focus:not(:focus-visible), [tabindex="-1"]:focus { outline: none; } + +/* ---------------------------------------------------------------- shell */ +#app { + position: fixed; inset: 0; height: 100dvh; + display: grid; grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto auto minmax(0, 1fr) auto; + grid-template-areas: "top" "hud" "view" "nav"; + padding: var(--safe-t) var(--safe-r) 0 var(--safe-l); + background: radial-gradient(1000px 520px at 15% -10%, #0e1d3a 0%, transparent 60%), radial-gradient(800px 460px at 100% 110%, #1a0f33 0%, transparent 55%), var(--bg); +} +#topbar { grid-area: top; display: flex; align-items: center; gap: 10px; padding: 8px 16px 6px; min-height: 44px; } +.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: .08em; font-size: 15px; } +.brand-mark { width: 18px; height: 18px; background: linear-gradient(135deg, var(--cyan), #3b82f6); clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); flex: none; } +.brand-mark.big { width: 40px; height: 40px; } +.netstate { margin-left: auto; font-size: 12px; padding: 4px 10px; border-radius: 999px; background: #3a1620; color: #ffb3c2; border: 1px solid #6b2236; } +.netstate.ok { background: #0f3a2c; color: #9af0cd; border-color: #1a6a4f; } +#hud { grid-area: hud; width: 100%; max-width: 1124px; justify-self: center; } +#view { grid-area: view; min-height: 0; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; overscroll-behavior: contain; } +#app[data-screen="map"] #view { overflow: hidden; } +#app[data-screen="auth"] #topbar, #app[data-state="out"] #topbar { display: none; } +.screen { min-height: 100%; } +.screen-map { height: 100%; min-height: 0; position: relative; } + +#nav { + grid-area: nav; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; + background: rgba(9, 15, 29, .96); border-top: 1px solid var(--line); + padding-bottom: var(--safe-b); +} +.nav-btn { background: none; border: 0; min-height: var(--nav-h); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; color: var(--dim); font-size: 12px; position: relative; padding: 4px 2px; } +.nav-btn[aria-current="page"] { color: var(--cyan); } +.nav-btn[aria-current="page"]::before { content: ""; position: absolute; top: 0; left: 28%; right: 28%; height: 3px; border-radius: 0 0 3px 3px; background: var(--cyan); } +.nav-ic { position: relative; display: inline-flex; } +.nav-ic svg.ic { width: 24px; height: 24px; } +.nav-badge { position: absolute; top: -5px; right: -9px; min-width: 17px; height: 17px; padding: 0 4px; border-radius: 9px; background: var(--red); color: #1a0710; font-size: 11px; font-weight: 700; display: grid; place-items: center; } +.nav-lbl { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) { + #app { + grid-template-columns: var(--rail-w) minmax(0, 1fr); + grid-template-rows: auto auto minmax(0, 1fr); + grid-template-areas: "nav top" "nav hud" "nav view"; + padding-bottom: var(--safe-b); + } + #app[data-state="out"] { grid-template-columns: minmax(0, 1fr); grid-template-areas: "view" "view" "view"; } + #nav { grid-auto-flow: row; grid-auto-columns: auto; grid-auto-rows: min-content; align-content: start; border-top: 0; border-right: 1px solid var(--line); padding: 6px 0; padding-bottom: 6px; overflow-y: auto; } + .nav-btn { min-height: 62px; } + .nav-btn[aria-current="page"]::before { top: 22%; bottom: 22%; left: 0; right: auto; width: 3px; height: auto; border-radius: 0 3px 3px 0; } + #topbar { padding-top: 4px; min-height: 36px; } +} + +.boot { display: grid; place-items: center; gap: 14px; padding: 48px 16px; color: var(--dim); text-align: center; } +.spinner { width: 28px; height: 28px; border: 3px solid var(--line2); border-top-color: var(--cyan); border-radius: 50%; animation: spin .9s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 3s; } * { scroll-behavior: auto !important; } } + +/* ---------------------------------------------------------------- resource bar */ +.hud { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; padding: 4px 12px 8px; } +.hud-chip { background: rgba(12, 19, 34, .9); border: 1px solid var(--line); border-radius: 12px; padding: 6px 8px 7px; min-width: 0; --c: var(--dim); } +.hud-chip.fiber { --c: var(--fiber); } .hud-chip.hardware { --c: var(--hardware); } .hud-chip.capital { --c: var(--capital); } .hud-chip.power { --c: var(--power); } +.hud-top { display: flex; align-items: center; gap: 4px; color: var(--c); white-space: nowrap; } +.hud-top svg.ic { width: 16px; height: 16px; } +.hud-top .val { color: var(--text); font-family: var(--mono); font-size: 15px; letter-spacing: -.02em; } +.hud-top .cap { color: var(--dimmer); font-size: 11px; font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; } +.hud-sub { font-size: 11px; color: var(--dim); font-family: var(--mono); margin: 1px 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.hud-chip.full { border-color: #6b5a1f; } +.hud-chip.full .rate { color: var(--amber); font-weight: 700; letter-spacing: .06em; } +.hud-chip.bad { border-color: #6b2236; } +.hud-chip.bad .val, .hud-chip.empty .rate { color: var(--red); } +.hud-chip.bad .bar i, .hud-chip.empty .bar i { background: var(--red); } +.bar { height: 4px; border-radius: 2px; background: #0a1020; overflow: hidden; } +.bar i { display: block; height: 100%; width: calc(var(--p, 0) * 100%); background: var(--c, var(--cyan)); border-radius: 2px; transition: width .4s linear; } +.hud-chip.full .bar i { background: var(--amber); } +@media (max-width: 400px) { .hud { gap: 4px; padding: 4px 8px 6px; } .hud-top .cap { display: none; } .hud-top .val { font-size: 14px; } } +@media (orientation: landscape) and (max-height: 520px) { .hud { padding-bottom: 4px; } .hud-chip { padding: 4px 8px 5px; } .hud-sub { margin-bottom: 2px; } } + +/* ---------------------------------------------------------------- generic parts */ +.page { padding: 8px 12px 24px; display: grid; gap: 12px; max-width: 720px; margin: 0 auto; } +.pad { padding: 28px 16px; } +.card { background: rgba(12, 19, 34, .88); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; } +.card-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; margin-bottom: 10px; } +.card-head h1, .card-head h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .1em; color: var(--dim); font-weight: 650; display: flex; align-items: center; gap: 6px; } +.card-head h1 { font-size: 15px; color: var(--text); } +.page-head { margin-bottom: 0; } +.empty { color: var(--dimmer); font-size: 14px; text-align: center; padding: 10px 6px; } +.row { display: flex; align-items: center; justify-content: space-between; gap: 10px; } +.kv { display: flex; justify-content: space-between; gap: 12px; padding: 7px 0; border-bottom: 1px solid var(--line); } +.kv:last-of-type { border-bottom: 0; } +.kv .k { color: var(--dimmer); } .kv .v { text-align: right; overflow-wrap: anywhere; } + +.pill { display: inline-flex; align-items: center; gap: 5px; padding: 3px 9px; border-radius: 999px; background: var(--panel3); border: 1px solid var(--line2); font-size: 12px; color: var(--dim); max-width: 100%; } +.pill svg.ic { width: 13px; height: 13px; } +.pill.accent { color: #06222b; background: var(--cyan); border-color: var(--cyan); font-weight: 650; } +.pill.green { color: #04241a; background: var(--green); border-color: var(--green); font-weight: 650; } +.pill.amber { color: #2b2204; background: var(--amber); border-color: var(--amber); font-weight: 600; } +.pill.dim { color: var(--dimmer); background: transparent; } +.pill.res-fiber { color: var(--fiber); } .pill.res-hardware { color: var(--hardware); } .pill.res-capital { color: var(--capital); } .pill.res-power { color: var(--power); } +.pill-row { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 8px; } + +.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 46px; padding: 0 18px; border-radius: 12px; border: 1px solid var(--line2); background: var(--panel3); color: var(--text); font-weight: 600; } +.btn:disabled { opacity: .45; cursor: not-allowed; } +.btn.primary { background: linear-gradient(180deg, #2fc4e6, #1b97c0); border-color: #55d6f2; color: #03202a; } +.btn.primary:disabled { background: var(--panel3); border-color: var(--line2); color: var(--dim); } +.btn.danger { background: #3a1620; border-color: #7a2a3f; color: #ffc4d0; } +.btn.wide { width: 100%; } +.btn.small { min-height: 36px; padding: 0 12px; font-size: 13px; } +.btn-row { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 10px; margin-top: 12px; } +.icon-btn { width: 44px; height: 44px; flex: none; display: inline-grid; place-items: center; border-radius: 12px; background: transparent; border: 1px solid transparent; color: var(--dim); } +.icon-btn:hover { background: var(--panel3); } +.linklike { background: none; border: 0; color: var(--cyan); min-height: 44px; text-decoration: underline; text-underline-offset: 3px; width: 100%; } +.chip-btn { min-width: 52px; min-height: 40px; border-radius: 999px; background: transparent; border: 1px solid var(--line2); color: var(--dim); padding: 0 14px; } +.chip-btn[aria-pressed="true"], .seg-btn[aria-pressed="true"] { background: var(--cyan); border-color: var(--cyan); color: #04222b; font-weight: 700; } +.seg { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 6px; } +.seg-btn { min-height: 46px; border-radius: 12px; background: var(--panel3); border: 1px solid var(--line2); color: var(--dim); } + +.field { display: grid; gap: 5px; margin-bottom: 12px; } +.field-lbl { font-size: 13px; color: var(--dim); } +.field-hint { font-size: 12px; color: var(--dimmer); } +input[type="text"], input[type="password"], select { width: 100%; min-height: 48px; padding: 0 14px; border-radius: 12px; background: #080e1c; border: 1px solid var(--line2); color: var(--text); font-size: 16px; } +input:focus-visible, select:focus-visible { outline: 2px solid var(--cyan); outline-offset: 1px; border-color: var(--cyan); } +.form-error { color: #ffc4d0; background: #3a1620; border: 1px solid #7a2a3f; border-radius: 10px; padding: 9px 12px; font-size: 14px; margin-bottom: 12px; } +.notice { color: var(--amber); font-size: 14px; margin-bottom: 12px; } + +/* ---------------------------------------------------------------- auth */ +.screen-auth { display: grid; place-items: center; padding: calc(16px + var(--safe-t)) 16px calc(16px + var(--safe-b)); min-height: 100%; } +.auth-card { width: min(100%, 400px); display: grid; gap: 14px; } +.auth-logo { display: flex; align-items: center; gap: 14px; justify-content: center; } +.auth-name { font-size: 28px; font-weight: 750; letter-spacing: .12em; } +.auth-tag { text-align: center; color: var(--dim); } +.auth-form { background: rgba(12, 19, 34, .9); border: 1px solid var(--line); border-radius: 18px; padding: 18px 16px 8px; } +.auth-h { font-size: 20px; margin-bottom: 14px; } +.lang-switch { display: flex; justify-content: center; gap: 8px; } + +/* ---------------------------------------------------------------- POP */ +.cols { display: grid; gap: 12px; padding: 4px 12px 24px; max-width: 1100px; margin: 0 auto; align-items: start; } +.col { display: grid; gap: 12px; min-width: 0; } +@media (min-width: 760px) { .cols { grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); } } +.pop-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: -4px 0 4px; } +.town-name { font-size: 22px; font-weight: 700; overflow-wrap: anywhere; } +.town-select { font-size: 18px; font-weight: 650; } +.pop-meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; color: var(--dim); font-size: 13px; } + +.queue { display: grid; gap: 8px; } +.q-item { display: flex; align-items: center; gap: 4px; background: var(--panel2); border: 1px solid #5a4a14; border-radius: 12px; padding-right: 2px; } +.q-main { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; background: none; border: 0; padding: 8px 6px 8px 10px; text-align: left; min-height: 56px; } +.q-main .bar { margin-top: 6px; --c: var(--amber); } +.q-main > b { font-size: 15px; color: var(--amber); } +.row-ic { width: 38px; height: 38px; flex: none; display: grid; place-items: center; border-radius: 10px; background: var(--panel3); color: var(--cyan); } +.row-ic svg.ic { width: 22px; height: 22px; } +.row-main { flex: 1; min-width: 0; display: grid; gap: 2px; } +.row-title { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; } +.row-title .lv { color: var(--dim); font-size: 13px; } +.row-sub { color: var(--dimmer); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.stat-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 10px; } +.stat { background: var(--panel2); border-radius: 10px; padding: 7px 10px; display: grid; } +.stat small { color: var(--dimmer); font-size: 11px; text-transform: uppercase; letter-spacing: .08em; } +.stat b { font-family: var(--mono); font-size: 17px; } +.good { color: var(--green); } .bad { color: var(--red); } +.power-card .bar { height: 8px; --c: var(--power); margin: 6px 0 8px; } +.power-status { font-size: 13px; color: var(--dim); } +.power-status.warn { color: var(--amber); } .power-status.bad { color: var(--red); } + +.groups { display: grid; gap: 12px; } +.group { --c: var(--cyan); } +.group.res-fiber { --c: var(--fiber); } .group.res-hardware { --c: var(--hardware); } .group.res-capital { --c: var(--capital); } .group.res-power { --c: var(--power); } +.group-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; color: var(--c); } +.group-head b { color: var(--text); } +.group-rate { margin-left: auto; font-family: var(--mono); font-size: 12px; color: var(--c); } +.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(56px, 1fr)); gap: 8px; } +.tile { position: relative; aspect-ratio: 1; min-height: 56px; border-radius: 14px; background: var(--panel2); border: 1px solid color-mix(in srgb, var(--c) 35%, var(--line)); color: var(--c); padding: 6px; display: block; text-align: left; overflow: hidden; } +.tile.res-fiber { --c: var(--fiber); } .tile.res-hardware { --c: var(--hardware); } .tile.res-capital { --c: var(--capital); } .tile.res-power { --c: var(--power); } +.tile-ic { width: 26px; height: 26px; opacity: .95; } +.tile-lvl { position: absolute; right: 8px; bottom: 6px; font-family: var(--mono); font-size: 22px; color: var(--text); line-height: 1; } +.tile-badge { position: absolute; right: 5px; top: 5px; display: grid; place-items: center; } +.tile-badge svg.ic { width: 15px; height: 15px; } +.tile-bar { position: absolute; left: 0; right: 0; bottom: 0; height: 4px; background: transparent; } +.tile-bar i { display: block; height: 100%; width: calc(var(--p, 0) * 100%); background: var(--amber); } +.tile[data-st="ready"] { border-color: var(--green); box-shadow: 0 0 0 1px rgba(53, 224, 161, .35), 0 0 14px rgba(53, 224, 161, .18); } +.tile[data-st="ready"] .tile-badge { color: var(--green); } +.tile[data-st="queued"] { border-color: var(--amber); } .tile[data-st="queued"] .tile-badge { color: var(--amber); } +.tile[data-st="locked"] { opacity: .65; } .tile[data-st="locked"] .tile-badge { color: var(--dimmer); } +.tile[data-st="max"] { border-color: #8a7a2a; } + +.rows { display: grid; gap: 8px; } +.row-btn { position: relative; width: 100%; display: flex; align-items: center; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; text-align: left; overflow: hidden; } +.row-btn[data-st="ready"] { border-color: color-mix(in srgb, var(--green) 70%, var(--line)); } +.row-btn[data-st="queued"] { border-color: var(--amber); } +.row-btn[data-st="locked"] .row-ic { color: var(--dimmer); } +.row-btn .pill { flex: none; max-width: 42%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + +/* ---------------------------------------------------------------- sheet */ +.sheet-wrap { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; justify-content: center; pointer-events: none; } +.backdrop { position: absolute; inset: 0; background: rgba(2, 5, 12, .62); opacity: 0; transition: opacity .18s; pointer-events: auto; } +.sheet { position: relative; width: min(100%, 520px); max-height: min(86dvh, 720px); overflow-y: auto; background: var(--panel); border: 1px solid var(--line2); border-bottom: 0; border-radius: 20px 20px 0 0; padding: 6px 16px calc(16px + var(--safe-b)); transform: translateY(24px); opacity: 0; transition: transform .2s ease-out, opacity .2s; pointer-events: auto; box-shadow: 0 -10px 40px rgba(0, 0, 0, .5); margin: 0 var(--safe-r) 0 var(--safe-l); } +.sheet-wrap.open .backdrop { opacity: 1; } +.sheet-wrap.open .sheet { transform: none; opacity: 1; } +.sheet-grab { width: 40px; height: 4px; border-radius: 2px; background: var(--line2); margin: 4px auto 6px; } +.sheet-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; } +.sheet-title { flex: 1; font-size: 19px; min-width: 0; overflow-wrap: anywhere; } +.sheet-icon { width: 40px; height: 40px; border-radius: 12px; background: var(--panel3); display: grid; place-items: center; color: var(--cyan); flex: none; } +.sheet-icon.res-fiber { color: var(--fiber); } .sheet-icon.res-hardware { color: var(--hardware); } .sheet-icon.res-capital { color: var(--capital); } .sheet-icon.res-power { color: var(--power); } +.sheet-icon svg.ic { width: 24px; height: 24px; } +.detail { display: grid; gap: 10px; } +.detail-desc { color: var(--dim); } +.detail-level { display: flex; justify-content: space-between; align-items: center; gap: 10px; } +.lvl-now { font-weight: 700; font-size: 17px; } +.lvl-next { display: inline-flex; align-items: center; gap: 4px; color: var(--green); font-size: 14px; } +.preview { color: var(--text); background: var(--panel2); border-radius: 10px; padding: 8px 12px; font-size: 14px; } +.sub { font-size: 12px; text-transform: uppercase; letter-spacing: .1em; color: var(--dimmer); margin-top: 2px; } +.costs { display: flex; flex-wrap: wrap; gap: 8px; } +.cost { display: inline-flex; align-items: center; gap: 6px; background: var(--panel2); border: 1px solid var(--line2); border-radius: 10px; padding: 6px 10px; --c: var(--dim); } +.cost.fiber { --c: var(--fiber); } .cost.hardware { --c: var(--hardware); } .cost.capital { --c: var(--capital); } +.cost svg.ic { color: var(--c); width: 18px; height: 18px; } +.cost b { font-family: var(--mono); } +.cost small { color: var(--dimmer); font-size: 11px; } +.cost.short { border-color: #7a2a3f; } .cost.short b { color: var(--red); } +.meta { justify-content: flex-start; color: var(--dim); } +.reqs { display: grid; gap: 6px; } +.reqs li { display: flex; align-items: center; gap: 8px; font-size: 14px; } +.reqs li.ok { color: var(--green); } .reqs li.miss { color: var(--red); } +.reqs small { margin-left: auto; color: var(--dimmer); } +.reason { color: var(--amber); font-size: 14px; min-height: 1.4em; } +.detail-queue { background: var(--panel2); border: 1px solid #5a4a14; border-radius: 12px; padding: 12px; display: grid; gap: 8px; } +.detail-queue .bar { --c: var(--amber); height: 6px; } +.detail-queue b { color: var(--amber); font-size: 18px; } + +@media (min-width: 700px) and (min-height: 560px) { + .sheet-wrap { align-items: center; } + .sheet { border-bottom: 1px solid var(--line2); border-radius: 20px; max-height: 86dvh; padding-bottom: 16px; } +} +@media (orientation: landscape) and (max-height: 520px) { + .sheet { max-height: 94dvh; width: min(100%, 560px); } + .sheet-grab { display: none; } +} + +/* ---------------------------------------------------------------- toasts */ +#toasts { position: fixed; left: 0; right: 0; bottom: calc(var(--nav-h) + var(--safe-b) + 12px); display: grid; justify-items: center; gap: 8px; z-index: 80; pointer-events: none; padding: 0 16px; } +.toast { background: #12203b; border: 1px solid var(--line2); color: var(--text); padding: 10px 16px; border-radius: 12px; font-size: 14px; max-width: 480px; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); transition: opacity .25s, transform .25s; } +.toast.ok { border-color: #1a6a4f; background: #0e2b23; } +.toast.error { border-color: #7a2a3f; background: #2d1019; color: #ffd0da; } +.toast.out { opacity: 0; transform: translateY(8px); } +@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) { #toasts { bottom: 14px; left: var(--rail-w); } } + +/* ---------------------------------------------------------------- map */ +.map-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; cursor: grab; outline: none; user-select: none; -webkit-user-select: none; } +.map-canvas.grabbing { cursor: grabbing; } +.map-canvas:focus-visible { outline: 2px solid var(--cyan); outline-offset: -2px; } +.map-controls { position: absolute; right: 12px; bottom: 14px; display: grid; gap: 8px; z-index: 3; } +.map-btn { width: 48px; height: 48px; border-radius: 14px; background: rgba(12, 19, 34, .92); border: 1px solid var(--line2); color: var(--text); display: grid; place-items: center; box-shadow: 0 4px 14px rgba(0, 0, 0, .45); } +.map-btn svg.ic { width: 24px; height: 24px; } +.map-coords { position: absolute; left: 12px; bottom: 14px; z-index: 3; padding: 4px 10px; border-radius: 999px; background: rgba(12, 19, 34, .85); border: 1px solid var(--line); color: var(--dim); font-size: 12px; pointer-events: none; } +.map-legend { position: absolute; left: 10px; top: 8px; z-index: 3; display: flex; flex-wrap: wrap; gap: 4px 12px; padding: 5px 10px; border-radius: 10px; background: rgba(12, 19, 34, .8); border: 1px solid var(--line); font-size: 11px; color: var(--dim); pointer-events: none; max-width: calc(100% - 20px); } +.map-legend li { display: flex; align-items: center; gap: 5px; } +.lg { width: 10px; height: 10px; display: inline-block; } +.lg.you { background: var(--cyan); clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); } +.lg.rival { background: #e08a4a; clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); } +.lg.rural { border: 2px solid var(--capital); border-radius: 50%; } +.lg.incumbent { background: #241338; border: 2px solid var(--violet); } +@media (max-height: 420px) { .map-legend { display: none; } } + +/* ---------------------------------------------------------------- alerts + settings */ +.alert-list { display: grid; gap: 8px; } +.alert { width: 100%; display: flex; align-items: center; gap: 10px; background: rgba(12, 19, 34, .88); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; text-align: left; } +.alert.new { border-color: var(--cyan); background: #0c1f33; } +.when { font-size: 12px; color: var(--dimmer); flex: none; } +.device-list { display: grid; gap: 8px; margin-top: 10px; } +.device { display: flex; align-items: center; gap: 10px; background: var(--panel2); border-radius: 12px; padding: 8px 10px; min-height: 56px; } +.device .row-sub { white-space: normal; } +.card .btn.wide { margin-top: 10px; } + +@media (prefers-reduced-motion: reduce) { .sheet, .backdrop, .toast, .bar i { transition: none; } } diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..ac9b72d87bbc0ba72d4d887650d2a6c13d365189 GIT binary patch literal 29602 zcmV)qK$^daP)v_*PU&*my}P~5`SssDZ@Rmxy63&OcPC>v=w^GSySl2n>Z|IWc{7dpUr-ipea>dB z8n!8grRB0-W{>9dGN5FR<)u(+88kY~5#|V(gFPx!*E;*d)HScWX7$!tfB121U6B)6 z-JMsoj&L5l?z_WX2n~FDRK|(um&*tP^eu%le2peOPH^M?>$3`THHd)eH$Q-1a#8ptm4%z1cQH!(Mdr^J8I^BU zO0uHjs;0;4tW%pSI#XD@ljuYjooKGPjXL9?^onR`?ZtBEne+JbiqO%FR%%>t%!&4d zv50@xUZ?wV`C@utPOp>vslu_s6@^q;&)b9gM2<)adh^h?iQE+V1@cNn4+tLU#p72)<~S0h$4$_U z_%A0S4(Gf6ah!1zx2N(IL?$j*d5>1=S`%`v9X)i%_2yC;{{!VwcYxk?FYIk-o&8-i zv2Qlj1r=ir0E;5zXV(Kp#)Y4cY_`s0rHDy{I4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uG?UUjA?&%e4g`rJP+FHcfD3puKM+qYM|f_FhiKflwei^psTw`5W-2#Q~IrYVR(w+W4|+c^Q9i9E?Edl91K`4&d? zr2B7QvF_Uu?EV`oEydLiFwo-AJCHG}zhF%#FvZ%*XPZdn_s9-#3(q4_(&m?)(qr(` zP}h;W@~p5}dt~^HK7Na~i$mt;%1IB4zE&4M07qY8E9glIq6cmgEqq-dzQf12itt#k z;u8EnEI`edE-EHd?UK{Doa}azSy$xSX(0mp1rmD|O$GXJ`S!eog53YvWM#bSuxG47 zh-|G%UIHZ@&STq}P?-WmahGe-_x%Cfmm*XqnqvN5ggdPK zQQ1_ol?O~OgI*JHMpQe##=;F^EG`pG%rjinvo&Z}(5T`ZnPkk{OSkq@d`LV7+zGjM zBf;m&DGxHR=qYf^Vi(O50v2DCr>HJZzAF^$FEI*$D834Ga6fl-x85oN7QK!Fn;~P} zR+a{nW8OrnE7(){D`;;Gy!6TQW~SZX|`L@xE&BA|zmS@cj%Ns9EZc&zAq%0gLfArKz;8nWSVyx)OzW)9Uc<2ey+BuFvgc)WG&|i(a7GED2r9 z540vvB+n)wfL=kZGcCkwH=kBNiP?4}Jv)FPuL;VjYF4#hLB_4cOV}1C>ZAaxB#?jh zg>-CWlW7Kr-kvvX9-A#2Lr+ReS$_ia>Y-GbN8Q`uc^+Q!IS6r-0K^I&nrC_RW^{t& z=y#Vb2D=C_fx6ftOfR15yr+dPCZTNMCirzJy^1`r6G@h*!P}St1|&`eqHYkt=B5)= z0%jr?N@0i>NE7dR=Sh&^^T1yFBVK?PSKcHezoc^~skF>9Q%ibRl*hx1wKM%*B%!um zwNDj>=nufs=w{o}Ad)|OYeN;+qtTfT!0%jCfbvW`FwVmvYykTua?+_=Vt*M!C$hs7 zr)ai6rywljDC~#-MLQiTr1B1Py}*fIJsRp|i8S)JQ6@K

+
+
+ + + + + + + + + + + + + + + + diff --git a/public/js/api.js b/public/js/api.js new file mode 100644 index 0000000..868ceb7 --- /dev/null +++ b/public/js/api.js @@ -0,0 +1,203 @@ +'use strict'; +/* + * REST client for /api/v1. No DOM; fetch, storage, clock and sleep are injected so Node tests can drive it + * (test/client-api.test.js). Loads as a browser script (window.UpstreamApi) and as a Node module. + * + * const api = UpstreamApi.createApi({ fetch, storage: localStorage }); + * const me = await api.get('/me'); + * await api.post('/towns/3/build', { key: 'f1' }, { intent: 'build:3:f1' }); + * api.serverNow(); // server clock estimate in ms: use this for every countdown + * api.on('unauthorized', fn); // token rejected: the shell drops to the login screen + * api.on('push', fn); // reserved: the WebSocket client (stage 6) calls api.emit('push', msg) + * + * Rules it follows (docs/API.md): + * - every response carries serverTime; the offset is kept from the lowest-latency sample (replayed idempotent + * responses carry the ORIGINAL serverTime and are ignored for this) + * - errors are { error: { code, message, details } } and become ApiError with .code; callers switch on code + * - mutating POSTs of a logged-in user carry an Idempotency-Key. An "intent" (a stable string like + * 'build:3:f1') keeps the same key across calls until the server has given a definite answer, so a tap that + * died on a flaky network and is tapped again cannot build twice. Without an intent, one key per call, reused + * by that call's retries. + * - retries with backoff: network errors, 429 (Retry-After honoured, seconds), 502/503/504 and request_in_progress. + * Network errors and 5xx are only retried when repeating is safe (GET, a keyed POST). 429 is always safe. + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.UpstreamApi = factory(); +}(typeof self !== 'undefined' ? self : this, function () { + class ApiError extends Error { + constructor(code, message, status, details, retryAfter) { + super(message || code); + this.name = 'ApiError'; + this.code = code; + this.status = status || 0; + this.details = details || {}; + this.retryAfter = retryAfter || 0; + } + } + + const KEY_RE = /^[A-Za-z0-9_.:-]{8,64}$/; + + function defaultHex() { + const c = typeof globalThis !== 'undefined' && globalThis.crypto; + if (c && c.getRandomValues) { + const a = new Uint8Array(12); + c.getRandomValues(a); + return Array.prototype.map.call(a, (b) => (b < 16 ? '0' : '') + b.toString(16)).join(''); + } + let s = ''; + for (let i = 0; i < 24; i++) s += Math.floor(Math.random() * 16).toString(16); + return s; + } + + function createApi(opts) { + opts = opts || {}; + const doFetch = opts.fetch; + const now = opts.now || Date.now; + const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms))); + const base = (opts.base || 'api/v1').replace(/\/$/, ''); + const tokenKey = opts.tokenKey || 'upstream.token'; + const maxRetries = opts.maxRetries === undefined ? 4 : opts.maxRetries; + const maxWaitMs = opts.maxWaitMs || 15000; // a Retry-After longer than this is given to the caller instead + const hex = opts.randomHex || defaultHex; + const jitter = opts.jitter || (() => Math.random()); + + // ---- token (storage can throw or be empty in private windows: stay usable from memory) + let memToken = null; + const store = opts.storage; + function getToken() { + if (memToken) return memToken; + try { return (store && store.getItem(tokenKey)) || null; } catch (e) { return null; } + } + function setToken(t) { + memToken = t || null; + try { if (store) { if (t) store.setItem(tokenKey, t); else store.removeItem(tokenKey); } } catch (e) { /* memory only */ } + } + const clearToken = () => setToken(null); + + // ---- events + const handlers = {}; + function on(evt, fn) { + (handlers[evt] = handlers[evt] || new Set()).add(fn); + return () => off(evt, fn); + } + function off(evt, fn) { if (handlers[evt]) handlers[evt].delete(fn); } + function emit(evt, data) { + if (!handlers[evt]) return; + for (const fn of Array.from(handlers[evt])) { try { fn(data); } catch (e) { /* a listener must not break the client */ } } + } + + // ---- server clock + let offset = 0, bestRtt = null, bestAt = 0, haveOffset = false; + function observeServerTime(serverTime, t0, t1) { + if (!Number.isFinite(serverTime)) return; + const rtt = Math.max(0, t1 - t0); + if (bestRtt === null || rtt <= bestRtt || t1 - bestAt > 5 * 60 * 1000) { + offset = serverTime - (t0 + t1) / 2; + bestRtt = rtt; bestAt = t1; haveOffset = true; + emit('offset', offset); + } + } + const serverNow = () => now() + offset; + + // ---- idempotency keys + const intents = new Map(); + const newKey = () => 'u' + hex(); + function keyFor(intent) { + if (!intent) return newKey(); + let k = intents.get(intent); + if (!k) { k = newKey(); intents.set(intent, k); } + return k; + } + + function backoff(attempt) { return Math.round(400 * Math.pow(2, attempt) * (0.75 + jitter() * 0.5)); } + + let offline = false; + function setOffline(v) { if (v !== offline) { offline = v; emit(v ? 'offline' : 'online'); } } + + function buildUrl(path, query) { + let u = base + (path[0] === '/' ? path : '/' + path); + if (query) { + const p = []; + for (const k of Object.keys(query)) if (query[k] !== undefined && query[k] !== null) p.push(encodeURIComponent(k) + '=' + encodeURIComponent(query[k])); + if (p.length) u += '?' + p.join('&'); + } + return u; + } + + async function request(method, path, o) { + o = o || {}; + const authed = o.auth !== false; + const token = authed ? getToken() : null; + const hasBody = o.body !== undefined && method !== 'GET'; + const keyed = method === 'POST' && !!token; + const key = keyed ? keyFor(o.intent) : null; + const safeToRepeat = method === 'GET' || keyed; + const headers = { Accept: 'application/json' }; + if (token) headers.Authorization = 'Bearer ' + token; + if (hasBody) headers['Content-Type'] = 'application/json'; + if (key) headers['Idempotency-Key'] = key; + const init = { method, headers, cache: 'no-store' }; + if (hasBody) init.body = JSON.stringify(o.body); + const url = buildUrl(path, o.query); + const retries = o.retries === undefined ? maxRetries : o.retries; + + for (let attempt = 0; ; attempt++) { + const t0 = now(); + let res; + try { + res = await doFetch(url, init); + } catch (e) { + setOffline(true); + if (attempt < retries && (safeToRepeat || method === 'DELETE')) { await sleep(backoff(attempt)); continue; } + throw new ApiError('network_error', String(e && e.message || e), 0); // intent key is kept: same tap, same key + } + const t1 = now(); + let body = null; + try { body = await res.json(); } catch (e) { body = null; } + const replay = res.headers && res.headers.get && res.headers.get('Idempotent-Replay'); + if (body && !replay) observeServerTime(body.serverTime, t0, t1); + + if (res.ok) { + setOffline(false); + if (o.intent) intents.delete(o.intent); + return body || {}; + } + + const err = body && body.error ? body.error : {}; + const code = err.code || (res.status === 429 ? 'rate_limited' : 'http_' + res.status); + let retryAfter = 0; + const ra = res.headers && res.headers.get ? Number(res.headers.get('Retry-After')) : NaN; + if (Number.isFinite(ra) && ra > 0) retryAfter = ra; + else if (err.details && Number(err.details.retryAfter) > 0) retryAfter = Number(err.details.retryAfter); + + // 429 was refused before doing anything, so it is always safe to repeat. + if (res.status === 429 && attempt < retries) { + const wait = retryAfter ? retryAfter * 1000 : backoff(attempt); + if (wait <= maxWaitMs) { await sleep(wait); continue; } + } + if ([502, 503, 504].includes(res.status) && attempt < retries && safeToRepeat) { await sleep(backoff(attempt)); continue; } + if (code === 'request_in_progress' && attempt < retries) { await sleep(500 + backoff(attempt)); continue; } + + setOffline(false); // the server answered: the network is fine + if (o.intent && res.status !== 429 && res.status < 500) intents.delete(o.intent); // a definite answer ends the intent + if (res.status === 401 && token && code === 'unauthorized') { clearToken(); emit('unauthorized', {}); } + throw new ApiError(code, err.message, res.status, err.details, retryAfter); + } + } + + return { + request, + get: (path, query, o) => request('GET', path, Object.assign({ query }, o)), + post: (path, body, o) => request('POST', path, Object.assign({ body: body === undefined ? {} : body }, o)), + del: (path, o) => request('DELETE', path, o), + getToken, setToken, clearToken, hasToken: () => !!getToken(), + on, off, emit, + serverNow, hasServerTime: () => haveOffset, serverOffset: () => offset, + pendingIntents: () => Array.from(intents.keys()), + isValidKey: (k) => KEY_RE.test(k), + }; + } + + return { createApi, ApiError }; +})); diff --git a/public/js/data.js b/public/js/data.js index 3a64673..f2799f1 100644 --- a/public/js/data.js +++ b/public/js/data.js @@ -94,6 +94,47 @@ // AS numbers come from the 32-bit private range (RFC 6996). Display name only. const AS_RANGE = { min: 4200000000, max: 4294967294 }; + // Alliances, diplomacy, messages (stage 5). Roles are listed most senior first. `permissions` maps an action to the + // roles allowed to do it; rules.allianceCan reads it. Times in hours are at world speed 1x unless noted "real". + const SOCIAL = { + roles: ['leader', 'diplomat', 'officer', 'member'], + permissions: { + invite: ['leader', 'officer'], + cancelInvite: ['leader', 'officer'], + viewInvites: ['leader', 'officer'], + kick: ['leader', 'officer'], // and only members the actor outranks + setRole: ['leader'], + transfer: ['leader'], + diplomacy: ['leader', 'diplomat'], + editNotes: ['leader', 'diplomat', 'officer'], + broadcast: ['leader', 'diplomat', 'officer', 'member'], + disband: ['leader'], + }, + allianceBaseSize: 10, // size cap = base + perLevel * Peering office level (best POP of the leader) + allianceSizePerLevel: 2, + minPeeringLevel: 1, // needed to found or join + nameLen: [3, 30], tagLen: [2, 5], + inviteTtlHours: 168, // real time, not divided by world speed + proposalTtlHours: 72, // real time + maxPendingInvites: 25, + maxNotes: 10, noteMax: 1000, + // Diplomacy. from -> to -> how the change happens: 'immediate' (one side decides), 'proposal' (the other side + // must accept) or 'delayed' (one side cancels, takes pactCancelHours / world speed). Missing = not allowed. + diplomacyStates: ['war', 'neutral', 'nap', 'confed'], + diplomacyMoves: { + neutral: { war: 'immediate', nap: 'proposal', confed: 'proposal' }, + nap: { neutral: 'delayed', war: 'delayed', confed: 'proposal' }, + confed: { neutral: 'delayed', nap: 'delayed', war: 'delayed' }, + war: { neutral: 'proposal', nap: 'proposal' }, + }, + pactCancelHours: 24, + // Messages: plain text, DB-backed send limits per sender (counted over the window, real time). + messageMax: 2000, + messageLimits: { dm10min: 15, dmHour: 60, broadcastHour: 20 }, + maxBlocks: 100, + rankingsPageMax: 100, + }; + const WORLD_DEFAULTS = { name: 'World 1', speed: 1, @@ -101,6 +142,99 @@ preset: 'standard', }; - return { HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS, - BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS }; + // ------------------------------------------------------------------ military (stages 3 and 4) + // Units. Stats: attack, defence, speed (tiles/hour at 1x), carry (loot per unit), draw (power points/hour while + // stationed), cost (per unit), time (seconds per unit at 1x, before building level), building (where it is trained), + // requires (all must hold; the training building is always required at level 1). `fixed: true` = never moves. + // role: scout | defender | attacker | siege | settler | conquest. Ids are generic; i18n.js holds the names. + const UNITS = { + port_scanner: { role: 'scout', building: 'noc', attack: 0, defence: 1, speed: 20, carry: 0, draw: 1, cost: { fiber: 30, hardware: 30, capital: 20 }, time: 90, requires: [{ type: 'noc', level: 1 }] }, + soc_analyst: { role: 'defender', building: 'noc', attack: 5, defence: 25, speed: 7, carry: 0, draw: 1, cost: { fiber: 60, hardware: 20, capital: 10 }, time: 120, requires: [{ type: 'noc', level: 1 }] }, + blue_team: { role: 'defender', building: 'noc', attack: 10, defence: 80, speed: 5, carry: 0, draw: 2, cost: { fiber: 100, hardware: 90, capital: 50 }, time: 300, requires: [{ type: 'noc', level: 5 }, { type: 'research_lab', level: 2 }] }, + honeypot: { role: 'defender', building: 'noc', attack: 0, defence: 100, speed: 0, carry: 0, draw: 1, cost: { fiber: 120, hardware: 80, capital: 40 }, time: 280, requires: [{ type: 'noc', level: 3 }, { type: 'research_lab', level: 1 }], fixed: true }, + script_crew: { role: 'attacker', building: 'ops_lab', attack: 40, defence: 10, speed: 8, carry: 50, draw: 1, cost: { fiber: 80, hardware: 40, capital: 30 }, time: 180, requires: [{ type: 'ops_lab', level: 1 }] }, + botnet: { role: 'attacker', building: 'ops_lab', attack: 90, defence: 25, speed: 14, carry: 150, draw: 3, cost: { fiber: 200, hardware: 160, capital: 120 }, time: 420, requires: [{ type: 'ops_lab', level: 5 }, { type: 'research_lab', level: 5 }] }, + ddos_rig: { role: 'siege', building: 'ops_lab', attack: 60, defence: 20, speed: 5, carry: 0, draw: 3, cost: { fiber: 300, hardware: 250, capital: 100 }, time: 600, requires: [{ type: 'ops_lab', level: 8 }, { type: 'research_lab', level: 6 }] }, + exploit_kit: { role: 'siege', building: 'ops_lab', attack: 40, defence: 10, speed: 5, carry: 0, draw: 3, cost: { fiber: 280, hardware: 300, capital: 150 }, time: 720, requires: [{ type: 'ops_lab', level: 10 }, { type: 'research_lab', level: 8 }] }, + rollout_crew: { role: 'settler', building: 'rollout_depot', attack: 0, defence: 5, speed: 6, carry: 0, draw: 2, cost: { fiber: 400, hardware: 300, capital: 300 }, time: 900, requires: [{ type: 'rollout_depot', level: 1 }] }, + ma_team: { role: 'conquest', building: 'rollout_depot', attack: 0, defence: 5, speed: 6, carry: 0, draw: 2, cost: { fiber: 700, hardware: 600, capital: 800 }, time: 1200, requires: [{ type: 'rollout_depot', level: 5 }] }, + }; + // Display / UI order. + const UNIT_ORDER = ['port_scanner', 'soc_analyst', 'blue_team', 'honeypot', 'script_crew', 'botnet', 'ddos_rig', 'exploit_kit', 'rollout_crew', 'ma_team']; + + const MILITARY = { + researchPerLevel: 0.05, // +5% attack or defence per research level of one unit type + trainSpeedPerLevel: 0.03, // training time / (1 + 0.03 * level of the training building) + maxTrainQueue: 8, // batches waiting per training building + maxBatch: 5000, + defenceBase: 10, // flat defence of any POP, before the firewall multiplier + rigFirewallDivisor: 10, // every 10 DDoS rigs lower the effective firewall by one level + lossExponent: 1.5, + raidLossFactor: 0.5, // raid: both sides lose 0.5 * (weak/strong)^1.5 + cachePerLevel: 0.10, // Rack hall hides 10% of the stock per level from raids ... + cacheMax: 0.5, // ... up to 50% + kitsMin: 5, // exploit kits (survivors) needed to damage a building at all + kitsPerLevel: 20, // levels destroyed = max(1, floor(kits / 20)) + loyaltyDrop: [15, 30], // inclusive range, rolled from the world seed + scanBuildingsRatio: 2, // attacking scanners needed per defending scanner to see buildings + scanLossExponent: 1.5, + recallWindowMs: 90 * 1000, + reportRetentionMs: 14 * 24 * HOUR_MS, // real time + pointsPerCost: 0.01, // battle points per resource point of killed units (operator_stats) + decommissionHours: 24, // offline this long (divided by world speed) and units are decommissioned + batteryEpsilon: 1e-6, + maxLists: 200, + }; + + // Research: +5% (MILITARY.researchPerLevel) attack or defence for ONE unit type per level, per POP, in the Research lab. + // Level n needs a Research lab of level n + labOffset. One research at a time per POP. + const RESEARCH = { + stats: ['attack', 'defence'], + maxLevel: 10, + labOffset: 2, + costFactor: 8, // times the unit's own cost, per level, growing with costGrowth + costGrowth: 1.35, + timeBase: 1800, // seconds at level 1 + timeGrowth: 1.3, + labSpeedPerLevel: 0.03, + }; + + // Founding and conquering POPs (stage 4). + const EXPANSION = { + settleUnit: 'rollout_crew', + crews: 3, // exactly this many found a POP; consumed + maxDistance: 15, // from any own POP + startResources: { fiber: 250, hardware: 250, capital: 250 }, // "1 h of resources" for a POP that produces nothing yet + foundedLoyalty: 100, + conqueredLoyalty: 25, + conquestUnit: 'ma_team', // one per takeover counts and is used up when it lowers loyalty + }; + + // Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level. + const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 500 }; + + // Which unit roles may go on which movement type. + const MOVE_ROLES = { + scan: ['scout'], + raid: ['attacker', 'defender'], + attack: ['attacker', 'defender', 'siege'], + takeover: ['attacker', 'defender', 'siege', 'conquest'], + reinforce: ['scout', 'defender', 'attacker', 'siege', 'settler', 'conquest'], + settle: ['settler'], + }; + + // Incumbent (NPC) sites: static defence that grows with world age. Taking one (first time per operator) gives a + // one-time Hardware bonus; each distinct site taken adds +10% research speed, up to researchSpeedMax. + const INCUMBENT = { + baseDefence: 600, + variance: 0.25, // per-site factor 1 +- variance, from the world seed + perDayGrowth: 0.04, // +4% of base per world day (world days = real days * speed) + scanStrength: 12, // counts as this many scanners when scanned + hardwareBonus: 2500, + researchSpeedBonus: 0.10, + researchSpeedMax: 0.5, + }; + + return { UNITS, UNIT_ORDER, MILITARY, RESEARCH, EXPANSION, TRANSPORT, MOVE_ROLES, INCUMBENT, HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS, + SOCIAL, BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS }; })); diff --git a/public/js/i18n.js b/public/js/i18n.js new file mode 100644 index 0000000..c821489 --- /dev/null +++ b/public/js/i18n.js @@ -0,0 +1,376 @@ +'use strict'; +/* + * UPSTREAM strings (en + nb) and number/time formatting. Pure: no DOM, no storage, no Date.now(). Loads as a browser + * script (window.UpstreamI18n) and as a Node module (the key-parity test lives in test/client-i18n.test.js). + * + * Player-facing names of buildings, resources and tile types live ONLY here (and as ids in data.js); game logic uses + * the generic ids. Keys are flat dotted strings. `{name}` placeholders are filled by t(). Both languages must have + * identical key sets and identical placeholders: the test enforces it. + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.UpstreamI18n = factory(); +}(typeof self !== 'undefined' ? self : this, function () { + const LANGS = ['en', 'nb']; + + const en = { + 'app.name': 'UPSTREAM', + 'app.tagline': 'Build your POP. Connect the region. Outlast the competition.', + + 'nav.pop': 'POP', 'nav.map': 'Map', 'nav.alerts': 'Alerts', 'nav.settings': 'Settings', 'nav.label': 'Main navigation', + 'screen.pop': 'Your POP', 'screen.map': 'Region map', 'screen.alerts': 'Alerts', 'screen.settings': 'Settings', + + 'common.cancel': 'Cancel', 'common.close': 'Close', 'common.back': 'Back', 'common.save': 'Save', 'common.confirm': 'Confirm', + 'common.loading': 'Loading…', 'common.retry': 'Retry', 'common.none': 'None', 'common.yes': 'Yes', 'common.no': 'No', + 'common.offline': 'Connection lost. Retrying…', 'common.online': 'Back online.', + 'common.perHour': '/h', 'common.tiles': 'tiles', + + 'res.fiber': 'Fiber', 'res.hardware': 'Hardware', 'res.capital': 'Capital', 'res.power': 'Power', 'res.battery': 'Battery', + + 'tile.land': 'Open land', 'tile.rural': 'Unconnected rural area', 'tile.incumbent': 'Legacy incumbent site', 'tile.pop': 'POP', 'tile.void': 'Off the map', + + 'building.cable_yard.name': 'Cable yard', + 'building.cable_yard.desc': 'Spools, reels and a suspicious amount of duct tape. Produces Fiber.', + 'building.supply_depot.name': 'Supply depot', + 'building.supply_depot.desc': 'Racks of spare parts nobody dares to count. Produces Hardware.', + 'building.sales_office.name': 'Sales office', + 'building.sales_office.desc': 'Convinces customers that 99.9% is a lot of nines. Produces Capital.', + 'building.substation.name': 'Substation', + 'building.substation.desc': 'Turns mains hum into power points. Everything you build draws from it.', + 'building.core_router.name': 'Core router', + 'building.core_router.desc': 'The thing everything else routes through. Shortens all build times.', + 'building.rack_hall.name': 'Rack hall', + 'building.rack_hall.desc': 'Floor space with good airflow. Sets how much Fiber, Hardware and Capital you can store.', + 'building.battery_bank.name': 'Battery bank', + 'building.battery_bank.desc': 'Buys you time when power is short. Sets the power buffer.', + 'building.firewall.name': 'Firewall', + 'building.firewall.desc': 'Default deny, mostly. Boosts the defence of the whole POP.', + 'building.noc.name': 'NOC', + 'building.noc.desc': 'Screens full of green dots and one red one. Trains defensive crews.', + 'building.research_lab.name': 'Research lab', + 'building.research_lab.desc': 'Where the clever ideas get a budget. Unlocks units and upgrades.', + 'building.ops_lab.name': 'Ops lab', + 'building.ops_lab.desc': 'Tools for the operations people do not talk about. Trains offensive units.', + 'building.internet_exchange.name': 'Internet exchange', + 'building.internet_exchange.desc': 'Where everyone meets and pretends not to compete. Trade between POPs.', + 'building.peering_office.name': 'Peering office', + 'building.peering_office.desc': 'Handshakes and mutual benefit. Found or join an alliance.', + 'building.rollout_depot.name': 'Rollout depot', + 'building.rollout_depot.desc': 'Trucks, trenchers and optimism. Trains the crews that found new POPs.', + 'building.backbone_node.name': 'Backbone node', + 'building.backbone_node.desc': 'The end-game building. Level 100 wins the world.', + + 'pop.capital': 'Capital POP', + 'pop.rename': 'Rename POP', 'pop.rename.label': 'POP name', 'pop.rename.done': 'POP renamed.', + 'pop.coords': 'x {x} · y {y}', + 'pop.loyalty': 'Customer loyalty', 'pop.footprint': 'Footprint', 'pop.footprintPerDay': '+{n}/day', + 'pop.queue.title': 'Build queue', 'pop.queue.slots': '{used}/{total} slots', + 'pop.queue.empty': 'Nothing under construction. An idle network is not the same as a healthy one.', + 'pop.queue.to': 'to level {n}', 'pop.queue.cancel': 'Cancel build', + 'pop.fields.title': 'Resource fields', 'pop.fields.group': '{name} · {n} fields', + 'pop.infra.title': 'Infrastructure', + 'pop.level': 'Lv {n}', 'pop.notBuilt': 'Not built', 'pop.max': 'Max', 'pop.inQueue': 'Building', + 'pop.upgradeReady': 'Can upgrade', 'pop.locked': 'Requirements missing', + 'pop.load.error': 'Could not load this POP.', + 'pop.noTown': 'No POP on this account yet.', + 'pop.bonus': 'Rural bonus', 'pop.bonus.none': 'No rural areas in reach', + + 'power.title': 'Power', 'power.out': 'Output', 'power.draw': 'Draw', 'power.net': 'Net', 'power.buffer': 'Buffer', + 'power.ok': 'Stable', 'power.draining': 'Draining: empty in {t}', 'power.charging': 'Charging: full in {t}', 'power.full': 'Buffer full', + 'power.empty': 'Buffer empty: units offline', 'power.unit': 'pts', + + 'sheet.level': 'Level {n}', 'sheet.nextLevel': 'Next: level {n}', + 'sheet.cost': 'Cost', 'sheet.time': 'Build time', 'sheet.requires': 'Requires', 'sheet.have': 'have {n}', + 'sheet.build': 'Build level {n}', 'sheet.upgrade': 'Upgrade to level {n}', 'sheet.building': 'Building…', + 'sheet.maxed': 'Fully upgraded', 'sheet.underway': 'Under construction', 'sheet.done': 'Done in {t}', + 'sheet.affordableIn': 'Affordable in {t}', 'sheet.capTooLow': 'Needs a bigger Rack hall (it holds {cap})', + 'sheet.cancel': 'Cancel this build', 'sheet.cancel.confirm': 'Cancel {name} to level {n}?', + 'sheet.cancel.refund': '80% of the cost comes back to the POP.', 'sheet.cancel.keep': 'Keep building', + 'sheet.built': 'Queued {name} to level {n}.', 'sheet.cancelled': 'Build cancelled. Refund added.', + 'sheet.preview.output': 'Output {a} → {b} per hour', 'sheet.preview.storage': 'Storage {a} → {b}', + 'sheet.preview.battery': 'Power buffer {a} → {b}', 'sheet.preview.core': 'Build time ×{a} → ×{b}', + 'sheet.preview.core2': 'Level {n} opens a second build slot.', 'sheet.preview.draw': 'Power draw +{n}', + 'sheet.preview.firewall': 'Defence ×{a} → ×{b}', 'sheet.preview.output.now': 'Output now: {a} per hour', + + 'map.centre': 'Centre on my POP', 'map.zoomIn': 'Zoom in', 'map.zoomOut': 'Zoom out', + 'map.label': 'Region map. Drag to pan, pinch or scroll to zoom, tap a tile for details.', + 'map.noWorld': 'This account has not joined a world yet.', 'map.error': 'Could not load part of the map.', + 'map.scanning': 'Scanning…', 'map.legend.rural': 'Rural', 'map.legend.incumbent': 'Incumbent', 'map.legend.you': 'You', 'map.legend.rival': 'Rival', + 'map.info.coords': 'x {x} · y {y}', 'map.info.distance': '{d} tiles from your capital', + 'map.info.land': 'Nothing here yet. Not a single strand of fibre.', + 'map.info.rural': 'POPs within {n} tiles get +{p}% {res} output while they stay connected.', + 'map.info.incumbent': 'A legacy telco stronghold. It never attacks. It does not need to.', + 'map.info.operator': 'Operator', 'map.info.as': 'AS number', 'map.info.yours': 'Your POP', 'map.info.rival': 'Rival operator', + 'map.info.protected': 'Beginner protection, no attacks in or out.', 'map.info.open': 'Open POP', 'map.info.capital': 'Capital', + + 'alerts.empty': 'All quiet on the wire.', 'alerts.error': 'Could not load alerts.', 'alerts.new': 'new', + 'alerts.build_done': '{name} reached level {level}', 'alerts.build_done.in': 'in {town}', + 'alerts.unknown': 'Event: {type}', 'alerts.more': 'Older alerts hidden', 'alerts.count': '{n} unread', + + 'settings.language': 'Language', 'settings.lang.en': 'English', 'settings.lang.nb': 'Norsk (bokmål)', + 'settings.account': 'Account', 'settings.username': 'Username', 'settings.operator': 'Operator', 'settings.as': 'AS number', 'settings.world': 'World', + 'settings.worldInfo': '{name} · {speed}× speed · radius {r}', + 'settings.devices': 'Devices', 'settings.devices.hint': 'Each device holds its own token. Revoke one and that device is logged out.', + 'settings.device.current': 'This device', 'settings.device.unnamed': 'Unnamed device', 'settings.device.revoke': 'Revoke', + 'settings.device.revoked': 'Device revoked.', 'settings.device.lastUsed': 'Last used {t}', 'settings.device.created': 'Added {t}', + 'settings.logout': 'Log out', 'settings.logout.confirm': 'Log out on this device?', + 'settings.about': 'About', 'settings.about.text': 'UPSTREAM is a hobby project. Fictional operators only; any resemblance to real networks is a routing leak.', + + 'auth.login': 'Log in', 'auth.signup': 'Sign up', 'auth.username': 'Username', 'auth.password': 'Password', + 'auth.invite': 'Invite code', 'auth.invite.hint': 'This server needs an invite code to sign up.', + 'auth.toSignup': 'New operator? Create an account', 'auth.toLogin': 'Already peering? Log in', + 'auth.username.hint': '3-20 letters, digits, _ or -', 'auth.password.hint': 'At least 8 characters', + 'auth.working': 'Working…', 'auth.expired': 'Your session ended. Log in again.', + 'auth.welcome': 'Welcome, operator.', + + 'time.d': 'd', 'time.h': 'h', 'time.m': 'm', 'time.s': 's', + 'time.now': 'just now', 'time.ago': '{t} ago', 'time.in': 'in {t}', + + 'err.bad_request': 'The request was malformed.', + 'err.validation_failed': 'Some field is missing or looks wrong.', + 'err.unauthorized': 'You are not logged in.', + 'err.invalid_credentials': 'Wrong username or password.', + 'err.forbidden': 'You may not do that.', + 'err.not_found': 'That no longer exists.', + 'err.method_not_allowed': 'That is not allowed here.', + 'err.conflict': 'That clashes with the current state. Refresh and try again.', + 'err.request_in_progress': 'Still working on your last request.', + 'err.idempotency_key_reuse': 'That request clashed with an earlier one. Try again.', + 'err.payload_too_large': 'That is too much data.', + 'err.rate_limited': 'Too many requests. Slow down a little.', + 'err.internal_error': 'Something broke on the server side.', + 'err.signup_closed': 'Signup needs a valid invite code.', + 'err.username_taken': 'That username is taken.', + 'err.world_full': 'No room left on the map.', + 'err.unknown_building': 'No such building or slot.', + 'err.not_buildable': 'That cannot be built here.', + 'err.max_level': 'Already at the maximum level.', + 'err.requirements_not_met': 'A required building is missing.', + 'err.already_queued': 'That is already under construction.', + 'err.queue_full': 'All build slots are busy.', + 'err.not_enough_resources': 'Not enough resources yet.', + 'err.network_error': 'Cannot reach the server.', + 'err.unknown': 'Something went wrong.', + }; + + const nb = { + 'app.name': 'UPSTREAM', + 'app.tagline': 'Bygg din POP. Koble sammen regionen. Overlev konkurrentene.', + + 'nav.pop': 'POP', 'nav.map': 'Kart', 'nav.alerts': 'Varsler', 'nav.settings': 'Innstillinger', 'nav.label': 'Hovednavigasjon', + 'screen.pop': 'Din POP', 'screen.map': 'Regionkart', 'screen.alerts': 'Varsler', 'screen.settings': 'Innstillinger', + + 'common.cancel': 'Avbryt', 'common.close': 'Lukk', 'common.back': 'Tilbake', 'common.save': 'Lagre', 'common.confirm': 'Bekreft', + 'common.loading': 'Laster…', 'common.retry': 'Prøv igjen', 'common.none': 'Ingen', 'common.yes': 'Ja', 'common.no': 'Nei', + 'common.offline': 'Mistet forbindelsen. Prøver igjen…', 'common.online': 'Tilbake på nett.', + 'common.perHour': '/t', 'common.tiles': 'ruter', + + 'res.fiber': 'Fiber', 'res.hardware': 'Maskinvare', 'res.capital': 'Kapital', 'res.power': 'Strøm', 'res.battery': 'Batteri', + + 'tile.land': 'Åpent land', 'tile.rural': 'Utkoblet landsbygd', 'tile.incumbent': 'Gammelt monopolsted', 'tile.pop': 'POP', 'tile.void': 'Utenfor kartet', + + 'building.cable_yard.name': 'Kabelgård', + 'building.cable_yard.desc': 'Trommer, kveiler og mistenkelig mye teip. Produserer Fiber.', + 'building.supply_depot.name': 'Utstyrslager', + 'building.supply_depot.desc': 'Hyller med reservedeler ingen tør telle. Produserer Maskinvare.', + 'building.sales_office.name': 'Salgskontor', + 'building.sales_office.desc': 'Overbeviser kunder om at 99,9 % er mange nitall. Produserer Kapital.', + 'building.substation.name': 'Transformatorstasjon', + 'building.substation.desc': 'Gjør nettbrumming om til strømpoeng. Alt du bygger trekker herfra.', + 'building.core_router.name': 'Kjerneruter', + 'building.core_router.desc': 'Alt annet ruter gjennom denne. Gjør alle byggetider kortere.', + 'building.rack_hall.name': 'Racksal', + 'building.rack_hall.desc': 'Gulvplass med god luftstrøm. Bestemmer hvor mye Fiber, Maskinvare og Kapital du kan lagre.', + 'building.battery_bank.name': 'Batteribank', + 'building.battery_bank.desc': 'Kjøper deg tid når strømmen er knapp. Bestemmer strømbufferen.', + 'building.firewall.name': 'Brannmur', + 'building.firewall.desc': 'Stort sett «deny all». Styrker forsvaret i hele POP-en.', + 'building.noc.name': 'NOC', + 'building.noc.desc': 'Skjermer full av grønne prikker og én rød. Trener forsvarsmannskap.', + 'building.research_lab.name': 'Forskningslab', + 'building.research_lab.desc': 'Der kloke ideer får budsjett. Låser opp enheter og oppgraderinger.', + 'building.ops_lab.name': 'Ops-lab', + 'building.ops_lab.desc': 'Verktøy for operasjoner ingen snakker høyt om. Trener angrepsenheter.', + 'building.internet_exchange.name': 'Internettknutepunkt', + 'building.internet_exchange.desc': 'Der alle møtes og later som de ikke konkurrerer. Handel mellom POP-er.', + 'building.peering_office.name': 'Peeringkontor', + 'building.peering_office.desc': 'Håndtrykk og gjensidig nytte. Stift eller bli med i en allianse.', + 'building.rollout_depot.name': 'Utrullingsdepot', + 'building.rollout_depot.desc': 'Lastebiler, grøftefresere og optimisme. Trener mannskapene som stifter nye POP-er.', + 'building.backbone_node.name': 'Ryggradsnode', + 'building.backbone_node.desc': 'Sluttspillbygget. Nivå 100 vinner verdenen.', + + 'pop.capital': 'Hoved-POP', + 'pop.rename': 'Gi POP-en nytt navn', 'pop.rename.label': 'POP-navn', 'pop.rename.done': 'POP-en har fått nytt navn.', + 'pop.coords': 'x {x} · y {y}', + 'pop.loyalty': 'Kundelojalitet', 'pop.footprint': 'Fotavtrykk', 'pop.footprintPerDay': '+{n}/døgn', + 'pop.queue.title': 'Byggekø', 'pop.queue.slots': '{used}/{total} plasser', + 'pop.queue.empty': 'Ingenting under bygging. Et stille nett er ikke det samme som et friskt nett.', + 'pop.queue.to': 'til nivå {n}', 'pop.queue.cancel': 'Avbryt bygging', + 'pop.fields.title': 'Ressursfelt', 'pop.fields.group': '{name} · {n} felt', + 'pop.infra.title': 'Infrastruktur', + 'pop.level': 'Nv {n}', 'pop.notBuilt': 'Ikke bygget', 'pop.max': 'Maks', 'pop.inQueue': 'Under bygging', + 'pop.upgradeReady': 'Kan oppgraderes', 'pop.locked': 'Mangler krav', + 'pop.load.error': 'Kunne ikke laste denne POP-en.', + 'pop.noTown': 'Ingen POP på denne kontoen ennå.', + 'pop.bonus': 'Landsbygdbonus', 'pop.bonus.none': 'Ingen landsbygd innen rekkevidde', + + 'power.title': 'Strøm', 'power.out': 'Produksjon', 'power.draw': 'Forbruk', 'power.net': 'Netto', 'power.buffer': 'Buffer', + 'power.ok': 'Stabil', 'power.draining': 'Tapper: tom om {t}', 'power.charging': 'Lader: full om {t}', 'power.full': 'Bufferen er full', + 'power.empty': 'Bufferen er tom: enheter er frakoblet', 'power.unit': 'p', + + 'sheet.level': 'Nivå {n}', 'sheet.nextLevel': 'Neste: nivå {n}', + 'sheet.cost': 'Kostnad', 'sheet.time': 'Byggetid', 'sheet.requires': 'Krever', 'sheet.have': 'har {n}', + 'sheet.build': 'Bygg nivå {n}', 'sheet.upgrade': 'Oppgrader til nivå {n}', 'sheet.building': 'Bygger…', + 'sheet.maxed': 'Fullt oppgradert', 'sheet.underway': 'Under bygging', 'sheet.done': 'Ferdig om {t}', + 'sheet.affordableIn': 'Råd om {t}', 'sheet.capTooLow': 'Trenger større Racksal (rommer {cap})', + 'sheet.cancel': 'Avbryt denne byggingen', 'sheet.cancel.confirm': 'Avbryte {name} til nivå {n}?', + 'sheet.cancel.refund': '80 % av kostnaden går tilbake til POP-en.', 'sheet.cancel.keep': 'Fortsett byggingen', + 'sheet.built': '{name} til nivå {n} er satt i kø.', 'sheet.cancelled': 'Bygging avbrutt. Refusjon lagt til.', + 'sheet.preview.output': 'Produksjon {a} → {b} per time', 'sheet.preview.storage': 'Lager {a} → {b}', + 'sheet.preview.battery': 'Strømbuffer {a} → {b}', 'sheet.preview.core': 'Byggetid ×{a} → ×{b}', + 'sheet.preview.core2': 'Nivå {n} åpner en ekstra byggeplass.', 'sheet.preview.draw': 'Strømforbruk +{n}', + 'sheet.preview.firewall': 'Forsvar ×{a} → ×{b}', 'sheet.preview.output.now': 'Produksjon nå: {a} per time', + + 'map.centre': 'Sentrer på min POP', 'map.zoomIn': 'Zoom inn', 'map.zoomOut': 'Zoom ut', + 'map.label': 'Regionkart. Dra for å flytte, knip eller scroll for å zoome, trykk på en rute for detaljer.', + 'map.noWorld': 'Denne kontoen er ikke med i noen verden ennå.', 'map.error': 'Kunne ikke laste deler av kartet.', + 'map.scanning': 'Skanner…', 'map.legend.rural': 'Landsbygd', 'map.legend.incumbent': 'Monopolist', 'map.legend.you': 'Deg', 'map.legend.rival': 'Rival', + 'map.info.coords': 'x {x} · y {y}', 'map.info.distance': '{d} ruter fra hovedstaden din', + 'map.info.land': 'Ingenting her ennå. Ikke en eneste fiberstreng.', + 'map.info.rural': 'POP-er innen {n} ruter får +{p} % {res}-produksjon så lenge de er tilkoblet.', + 'map.info.incumbent': 'Et gammelt telekomfestning. Det angriper aldri. Det trenger ikke.', + 'map.info.operator': 'Operatør', 'map.info.as': 'AS-nummer', 'map.info.yours': 'Din POP', 'map.info.rival': 'Rivaliserende operatør', + 'map.info.protected': 'Nybegynnerbeskyttelse, ingen angrep inn eller ut.', 'map.info.open': 'Åpne POP', 'map.info.capital': 'Hovedstad', + + 'alerts.empty': 'Stille på linja.', 'alerts.error': 'Kunne ikke laste varsler.', 'alerts.new': 'ny', + 'alerts.build_done': '{name} nådde nivå {level}', 'alerts.build_done.in': 'i {town}', + 'alerts.unknown': 'Hendelse: {type}', 'alerts.more': 'Eldre varsler er skjult', 'alerts.count': '{n} uleste', + + 'settings.language': 'Språk', 'settings.lang.en': 'English', 'settings.lang.nb': 'Norsk (bokmål)', + 'settings.account': 'Konto', 'settings.username': 'Brukernavn', 'settings.operator': 'Operatør', 'settings.as': 'AS-nummer', 'settings.world': 'Verden', + 'settings.worldInfo': '{name} · {speed}× fart · radius {r}', + 'settings.devices': 'Enheter', 'settings.devices.hint': 'Hver enhet har sin egen token. Tilbakekall én, så logges den enheten ut.', + 'settings.device.current': 'Denne enheten', 'settings.device.unnamed': 'Enhet uten navn', 'settings.device.revoke': 'Tilbakekall', + 'settings.device.revoked': 'Enheten er tilbakekalt.', 'settings.device.lastUsed': 'Sist brukt {t}', 'settings.device.created': 'Lagt til {t}', + 'settings.logout': 'Logg ut', 'settings.logout.confirm': 'Logge ut på denne enheten?', + 'settings.about': 'Om', 'settings.about.text': 'UPSTREAM er et hobbyprosjekt. Kun fiktive operatører; likhet med ekte nett er en rutelekkasje.', + + 'auth.login': 'Logg inn', 'auth.signup': 'Registrer deg', 'auth.username': 'Brukernavn', 'auth.password': 'Passord', + 'auth.invite': 'Invitasjonskode', 'auth.invite.hint': 'Denne serveren krever invitasjonskode for å registrere deg.', + 'auth.toSignup': 'Ny operatør? Opprett konto', 'auth.toLogin': 'Allerede peeret? Logg inn', + 'auth.username.hint': '3-20 bokstaver, tall, _ eller -', 'auth.password.hint': 'Minst 8 tegn', + 'auth.working': 'Jobber…', 'auth.expired': 'Økten er over. Logg inn igjen.', + 'auth.welcome': 'Velkommen, operatør.', + + 'time.d': 'd', 'time.h': 't', 'time.m': 'm', 'time.s': 's', + 'time.now': 'akkurat nå', 'time.ago': '{t} siden', 'time.in': 'om {t}', + + 'err.bad_request': 'Forespørselen var ugyldig.', + 'err.validation_failed': 'Et felt mangler eller ser feil ut.', + 'err.unauthorized': 'Du er ikke logget inn.', + 'err.invalid_credentials': 'Feil brukernavn eller passord.', + 'err.forbidden': 'Det har du ikke lov til.', + 'err.not_found': 'Det finnes ikke lenger.', + 'err.method_not_allowed': 'Det er ikke tillatt her.', + 'err.conflict': 'Det kolliderer med dagens tilstand. Oppdater og prøv igjen.', + 'err.request_in_progress': 'Jobber fortsatt med forrige forespørsel.', + 'err.idempotency_key_reuse': 'Forespørselen kolliderte med en tidligere. Prøv igjen.', + 'err.payload_too_large': 'Det er for mye data.', + 'err.rate_limited': 'For mange forespørsler. Ta det litt roligere.', + 'err.internal_error': 'Noe gikk i stykker hos serveren.', + 'err.signup_closed': 'Registrering krever gyldig invitasjonskode.', + 'err.username_taken': 'Brukernavnet er opptatt.', + 'err.world_full': 'Ikke plass igjen på kartet.', + 'err.unknown_building': 'Ingen slik bygning eller plass.', + 'err.not_buildable': 'Det kan ikke bygges her.', + 'err.max_level': 'Allerede på høyeste nivå.', + 'err.requirements_not_met': 'En påkrevd bygning mangler.', + 'err.already_queued': 'Det er allerede under bygging.', + 'err.queue_full': 'Alle byggeplasser er opptatt.', + 'err.not_enough_resources': 'Ikke nok ressurser ennå.', + 'err.network_error': 'Får ikke kontakt med serveren.', + 'err.unknown': 'Noe gikk galt.', + }; + + const strings = { en, nb }; + + function detectLang(navLang) { + const l = String(navLang || '').toLowerCase(); + return /^(nb|nn|no)(\b|-|_)/.test(l) || l === 'no' ? 'nb' : 'en'; + } + + // Fill {placeholders}. Missing vars stay visible as {name}, so a bug shows up on screen instead of as "undefined". + function fill(s, vars) { + if (!vars) return s; + return s.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m)); + } + + function t(lang, key, vars) { + const table = strings[lang] || en; + const s = Object.prototype.hasOwnProperty.call(table, key) ? table[key] : (Object.prototype.hasOwnProperty.call(en, key) ? en[key] : key); + return fill(s, vars); + } + + const locale = (lang) => (lang === 'nb' ? 'nb-NO' : 'en-GB'); + const nfCache = {}; + function nf(lang, digits) { + const k = lang + digits; + if (!nfCache[k]) nfCache[k] = new Intl.NumberFormat(locale(lang), { minimumFractionDigits: digits, maximumFractionDigits: digits }); + return nfCache[k]; + } + + // Whole numbers for amounts. Compact (12.3k, 4.5M) from 100 000 up so nothing overflows a phone-width chip. + function fmtNum(lang, n) { + n = Number(n) || 0; + const a = Math.abs(n); + if (a >= 1e6) return nf(lang, 1).format(Math.floor(n / 1e5) / 10) + 'M'; + if (a >= 1e5) return nf(lang, 0).format(Math.floor(n / 1e3)) + 'k'; + return nf(lang, 0).format(Math.floor(n + 1e-9)); + } + + // One decimal below 100, whole numbers above; always signed when `signed` (rates: +12.4, -3). + function fmtDec(lang, n, signed) { + n = Number(n) || 0; + const a = Math.abs(n); + const s = a >= 100 ? nf(lang, 0).format(Math.round(a)) : nf(lang, 1).format(a); + const sign = n < 0 ? '−' : (signed && n > 0 ? '+' : ''); + return sign + s; + } + + // "2d 3h", "2h 5m", "4m 10s", "12s". At most `parts` units (default 2), rounding the last one up never; floors. + function fmtDuration(lang, ms, parts) { + parts = parts || 2; + let s = Math.max(0, Math.floor(ms / 1000)); + if (s < 1) return '0' + t(lang, 'time.s'); + const units = [['time.d', 86400], ['time.h', 3600], ['time.m', 60], ['time.s', 1]]; + const out = []; + for (const [k, size] of units) { + const v = Math.floor(s / size); + s -= v * size; + if (v > 0 || out.length) out.push(v + t(lang, k)); + if (out.length >= parts) break; + } + while (out.length > 1 && /^0\D/.test(out[out.length - 1])) out.pop(); // "1h 0m" -> "1h" + return out.join(' '); + } + + // Countdown clock "h:mm:ss" (or "m:ss" under an hour). Ceil so it never shows 0:00 while time is left. + function fmtClock(ms) { + const total = Math.max(0, Math.ceil(ms / 1000)); + const h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60; + const p = (v) => (v < 10 ? '0' : '') + v; + return h > 0 ? h + ':' + p(m) + ':' + p(s) : m + ':' + p(s); + } + + // "5m ago", "just now". `diff` = now - then in ms. + function fmtAgo(lang, diff) { + if (diff < 45000) return t(lang, 'time.now'); + return t(lang, 'time.ago', { t: fmtDuration(lang, diff, 1) }); + } + + // Fictional AS numbers come from the private 32-bit range; shown as "AS4200000123". + const fmtAs = (n) => 'AS' + n; + + return { LANGS, strings, t, fill, detectLang, fmtNum, fmtDec, fmtDuration, fmtClock, fmtAgo, fmtAs }; +})); diff --git a/public/js/main.js b/public/js/main.js new file mode 100644 index 0000000..565cec0 --- /dev/null +++ b/public/js/main.js @@ -0,0 +1,404 @@ +'use strict'; +/* + * The shell: session, screen registry, bottom nav, resource bar (HUD), ticker, language. Screens live in + * js/screens/*.js and register themselves: + * + * App.registerScreen({ + * id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', // nav: false hides it from the nav + * hud: true, // show the resource bar above it + * render(container) {}, // once, when the screen is first shown: build the persistent DOM + * onShow(params) {}, // every time it becomes visible + * onHide() {}, + * onLang() {}, // optional: language changed while visible (default: onShow again) + * }); + * + * Later stages add screens (units, reports, ...) the same way: one file, one registerScreen call, one script tag. + * Everything time-based is computed from api.serverNow() (server clock), never from the device clock alone. + */ +(function () { + const { h, clear, icon, toast, safeStore } = UI; + const I = UpstreamI18n; + const R = UpstreamRules; + const D = UpstreamData; + + const api = UpstreamApi.createApi({ + fetch: window.fetch.bind(window), + storage: (function () { try { return window.localStorage; } catch (e) { return null; } }()), + }); + + const LANG_KEY = 'upstream.lang'; + const TOWN_KEY = 'upstream.town'; + const SEEN_KEY = 'upstream.alerts.seen.'; + + const App = { + api, + state: { user: null, operators: [], operator: null, world: null, towns: [], townId: null, townData: null, townFetchedAt: 0, lang: 'en', unread: 0 }, + screens: new Map(), + current: null, + params: null, + }; + window.App = App; + + // ------------------------------------------------------------------ tiny event bus (town, session, lang) + const bus = {}; + App.on = (evt, fn) => { (bus[evt] = bus[evt] || new Set()).add(fn); return () => bus[evt].delete(fn); }; + App.emit = (evt, data) => { if (bus[evt]) for (const fn of Array.from(bus[evt])) { try { fn(data); } catch (e) { console.error(e); } } }; + + // ------------------------------------------------------------------ i18n helpers + App.t = (key, vars) => I.t(App.state.lang, key, vars); + App.fmt = { + num: (n) => I.fmtNum(App.state.lang, n), + dec: (n, signed) => I.fmtDec(App.state.lang, n, signed), + dur: (ms, parts) => I.fmtDuration(App.state.lang, ms, parts), + clock: (ms) => I.fmtClock(ms), + ago: (ms) => I.fmtAgo(App.state.lang, ms), + compact: (n) => (Math.abs(n) >= 1000 ? I.fmtDec(App.state.lang, n / 1000) + 'k' : I.fmtNum(App.state.lang, n)), + }; + App.errMsg = (err) => { + const code = err && err.code; + if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code); + return (err && err.message) || App.t('err.unknown'); + }; + App.resName = (r) => App.t('res.' + r); + App.buildingName = (type) => (I.strings.en['building.' + type + '.name'] ? App.t('building.' + type + '.name') : type); + App.buildingDesc = (type) => (I.strings.en['building.' + type + '.desc'] ? App.t('building.' + type + '.desc') : ''); + + App.setLang = (lang) => { + if (!I.LANGS.includes(lang)) return; + App.state.lang = lang; + safeStore.set(LANG_KEY, lang); + document.documentElement.lang = lang; + buildNav(); + renderHud(true); + if (App.current) { + setTitle(App.current); + if (App.current.onLang) App.current.onLang(); else if (App.current.onShow) App.current.onShow(App.params || {}); + } + App.emit('lang', lang); + }; + + // ------------------------------------------------------------------ server clock + ticker + App.now = () => api.serverNow(); + const tickers = new Set(); + App.onTick = (fn) => { tickers.add(fn); return () => tickers.delete(fn); }; + setInterval(() => { + if (document.hidden) return; + const now = api.serverNow(); + tickHud(now); + for (const fn of Array.from(tickers)) { try { fn(now); } catch (e) { console.error(e); } } + }, 250); + + // ------------------------------------------------------------------ screens + nav + const elView = () => document.getElementById('view'); + const elNav = () => document.getElementById('nav'); + const elApp = () => document.getElementById('app'); + + App.registerScreen = (def) => { App.screens.set(def.id, def); }; + + function buildNav() { + const nav = elNav(); + clear(nav); + nav.setAttribute('aria-label', App.t('nav.label')); + for (const def of App.screens.values()) { + if (def.nav === false) continue; + const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' }); + const btn = h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick: () => App.go(def.id) }, + h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) })); + if (App.current && App.current.id === def.id) btn.setAttribute('aria-current', 'page'); + nav.appendChild(btn); + } + updateBadge(); + } + + function updateBadge() { + const n = App.state.unread; + const b = elNav().querySelector('[data-screen="alerts"] .nav-badge'); + if (!b) return; + b.hidden = !n; + b.textContent = n > 9 ? '9+' : String(n); + const btn = b.closest('button'); + if (btn) btn.setAttribute('aria-label', App.t('nav.alerts') + (n ? ' (' + App.t('alerts.count', { n }) + ')' : '')); + } + + function setTitle(def) { document.getElementById('title').textContent = def.id === 'auth' ? App.t('app.name') : App.t(def.titleKey); document.title = (def.id === 'auth' ? '' : App.t(def.titleKey) + ' · ') + 'UPSTREAM'; } + + // Navigate. Sets the hash (so back/forward work); hashchange does the actual switch. + App.go = (id, params) => { + App.nextParams = params || null; + const want = '#/' + id; + if (location.hash === want) show(id, App.nextParams); else location.hash = want; + }; + + function show(id, params) { + if (!App.state.user && id !== 'auth') id = 'auth'; + if (App.state.user && id === 'auth') id = 'pop'; + const def = App.screens.get(id) || App.screens.get(App.state.user ? 'pop' : 'auth'); + if (!def) return; + if (App.current && App.current !== def && App.current.onHide) App.current.onHide(); + const view = elView(); + for (const s of view.children) s.hidden = s.dataset.screen !== def.id; + let box = view.querySelector('[data-screen="' + def.id + '"]'); + if (!box) { + box = h('section', { class: 'screen screen-' + def.id, dataset: { screen: def.id }, tabindex: '-1' }); + view.appendChild(box); + if (def.render) def.render(box); + } + box.hidden = false; + App.current = def; + App.params = params || {}; + const app = elApp(); + app.dataset.screen = def.id; + app.dataset.state = App.state.user ? 'in' : 'out'; + elNav().hidden = !App.state.user; + for (const b of elNav().children) { if (b.dataset.screen === def.id) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); } + setTitle(def); + renderHud(false); + if (def.onShow) def.onShow(App.params); + if (App.state.user && def.nav !== false) safeStore.set('upstream.screen', def.id); + } + + window.addEventListener('hashchange', () => { + const id = (location.hash.match(/^#\/(\w+)/) || [])[1] || 'pop'; + const p = App.nextParams; App.nextParams = null; + show(id, p); + }); + + // ------------------------------------------------------------------ session + // Accepts the operators array of /me or of an auth response. + App.setSession = (user, operators) => { + const st = App.state; + st.user = user; + st.operators = operators || []; + st.operator = st.operators[0] || null; // v1: one world per account + st.world = st.operator ? st.operator.world : null; + st.towns = st.operator ? st.operator.towns : []; + const saved = Number(safeStore.get(TOWN_KEY)); + const pick = st.towns.find((t) => t.id === saved) || st.towns.find((t) => t.isCapital) || st.towns[0] || null; + st.townId = pick ? pick.id : null; + st.townData = null; + st.unread = 0; + App.emit('session', st); + }; + + App.clearSession = () => { + const st = App.state; + st.user = null; st.operators = []; st.operator = null; st.world = null; st.towns = []; st.townId = null; st.townData = null; st.unread = 0; + api.clearToken(); + renderHud(true); + App.emit('session', st); + }; + + App.loadMe = async () => { + const me = await api.get('/me'); + App.setSession(me.user, me.operators); + return me; + }; + + App.setTown = (id) => { + if (App.state.townId === id) return; + App.state.townId = id; App.state.townData = null; + safeStore.set(TOWN_KEY, String(id)); + App.refreshTown().catch(() => {}); + App.emit('townchange', id); + }; + + let townInflight = null; + App.refreshTown = () => { + const st = App.state; + if (!st.townId) return Promise.resolve(null); + if (townInflight) return townInflight; + const id = st.townId; + townInflight = api.get('/towns/' + id).then((r) => { + if (st.townId !== id) return null; + st.townData = r.town; + st.townFetchedAt = Date.now(); + App.fetchedServerTime = r.serverTime; // the instant the amounts in r.town are exact for + rulesCache = null; + renderHud(true); + App.emit('town', r.town); + return r.town; + }).finally(() => { townInflight = null; }); + return townInflight; + }; + + // ------------------------------------------------------------------ rules.js view of the current POP (previews + ticking) + let rulesCache = null; + // The rules.js town shape from the API response: same function the server settles with, so the numbers agree. + App.rulesTown = () => { + const st = App.state, td = st.townData; + if (!td || !st.world) return null; + if (rulesCache && rulesCache.src === td) return rulesCache.town; + const buildings = {}; + let bdraw = 0; + for (const b of td.buildings) { + if (b.level <= 0) continue; + buildings[b.key] = { type: b.type, level: b.level }; + const def = D.BUILDINGS[b.type]; + if (def && def.kind === 'infra') bdraw += def.draw * b.level; + } + const town = { + id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0, + res: { fiber: td.resources.fiber.amount, hardware: td.resources.hardware.amount, capital: td.resources.capital.amount, battery: td.power.buffer }, + footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {}, + }; + rulesCache = { src: td, town }; + return town; + }; + + // Current amounts at server time `now`. Falls back to the fetched values if the rules cannot be applied. + App.resourcesNow = (now) => { + const td = App.state.townData; + if (!td) return null; + try { + const rt = App.rulesTown(); + const cur = R.resourcesAt(rt, now === undefined ? api.serverNow() : now); + return { amounts: cur.amounts, caps: cur.caps, rates: cur.rates }; + } catch (e) { + const amounts = { battery: td.power.buffer }, caps = { battery: td.power.bufferCap }; + for (const r of D.RESOURCES) { amounts[r] = td.resources[r].amount; caps[r] = td.resources[r].cap; } + return { amounts, caps, rates: { fiber: td.resources.fiber.rate, hardware: td.resources.hardware.rate, capital: td.resources.capital.rate, powerOut: td.power.out, powerDraw: td.power.draw, powerNet: td.power.net } }; + } + }; + + // ------------------------------------------------------------------ resource bar + const hudRefs = {}; + + function renderHud(rebuild) { + const hud = document.getElementById('hud'); + const def = App.current; + const td = App.state.townData; + const want = !!(def && def.hud && td && App.state.user); + hud.hidden = !want; + if (!want) return; + if (!rebuild && hud.firstChild) return; + clear(hud); + for (const r of D.RESOURCES.concat(['power'])) { + const refs = { + val: h('b', { class: 'val' }), cap: h('span', { class: 'cap' }), rate: h('span', { class: 'rate' }), fill: h('i'), + }; + hudRefs[r] = refs; + hud.appendChild(h('div', { class: 'hud-chip ' + r, role: 'group', dataset: { res: r } }, + h('div', { class: 'hud-top' }, icon(r), refs.val, refs.cap), + h('div', { class: 'hud-sub' }, refs.rate), + h('div', { class: 'bar', 'aria-hidden': 'true' }, refs.fill))); + } + tickHud(api.serverNow(), true); + } + + const lastText = new WeakMap(); + function setText(el, s) { if (lastText.get(el) !== s) { lastText.set(el, s); el.textContent = s; } } + + function tickHud(now, force) { + const hud = document.getElementById('hud'); + if (hud.hidden && !force) return; + const cur = App.resourcesNow(now); + if (!cur || !hudRefs.fiber) return; + const f = App.fmt; + for (const r of D.RESOURCES) { + const refs = hudRefs[r]; + const amt = cur.amounts[r], cap = cur.caps[r], rate = cur.rates[r]; + const full = amt >= cap - 0.01; + setText(refs.val, f.num(amt)); + setText(refs.cap, '/' + f.compact(cap)); + setText(refs.rate, full ? 'FULL' : f.dec(rate, true) + App.t('common.perHour')); + refs.fill.style.setProperty('--p', String(cap > 0 ? Math.min(1, amt / cap) : 0)); + const chip = refs.val.closest('.hud-chip'); + chip.classList.toggle('full', full); + if (force) chip.setAttribute('aria-label', App.resName(r) + ': ' + f.num(amt) + ' / ' + f.num(cap) + ', ' + f.dec(rate, true) + App.t('common.perHour')); + } + const p = hudRefs.power; + const net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery; + setText(p.val, f.dec(net, true)); + setText(p.cap, App.t('power.unit')); + setText(p.rate, buf <= 0 && net < 0 ? App.t('power.empty').split(':')[0] : f.num(buf) + '/' + f.compact(bcap)); + p.fill.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0)); + const pc = p.val.closest('.hud-chip'); + pc.classList.toggle('bad', net < 0); + pc.classList.toggle('empty', buf <= 0 && net < 0); + if (force) pc.setAttribute('aria-label', App.t('res.power') + ': ' + f.dec(net, true) + ', ' + App.t('res.battery') + ' ' + f.num(buf) + ' / ' + f.num(bcap)); + } + + // ------------------------------------------------------------------ alerts badge (unread count from the notification feed) + const seenKey = () => SEEN_KEY + (App.state.user ? App.state.user.id : '0'); + App.getSeen = () => Number(safeStore.get(seenKey())) || 0; + App.markSeen = (id) => { + if (id > App.getSeen()) safeStore.set(seenKey(), String(id)); + App.state.unread = 0; + updateBadge(); + }; + App.checkAlerts = async () => { + if (!App.state.user) return; + try { + const after = App.getSeen(); + const r = await api.get('/notifications', { after, limit: 50 }); + if (App.current && App.current.id === 'alerts') { App.state.unread = 0; } + else App.state.unread = r.items.length; + updateBadge(); + } catch (e) { /* badge is a convenience */ } + }; + + // ------------------------------------------------------------------ connection state + let backTimer = null; + api.on('offline', () => { + const el = document.getElementById('netstate'); + el.textContent = App.t('common.offline'); el.hidden = false; el.classList.remove('ok'); + clearTimeout(backTimer); + }); + api.on('online', () => { + const el = document.getElementById('netstate'); + if (el.hidden) return; + el.textContent = App.t('common.online'); el.classList.add('ok'); + backTimer = setTimeout(() => { el.hidden = true; }, 1800); + if (App.state.user) App.refreshTown().catch(() => {}); + }); + api.on('unauthorized', () => { + App.clearSession(); + App.authNotice = App.t('auth.expired'); + App.go('auth'); + }); + + document.addEventListener('visibilitychange', () => { + if (document.hidden || !App.state.user) return; + if (Date.now() - App.state.townFetchedAt > 20000) App.refreshTown().catch(() => {}); + App.checkAlerts(); + }); + setInterval(() => { if (!document.hidden && App.state.user) App.checkAlerts(); }, 60000); + + // After login or boot: load the POP and go to the screen the hash asks for. + App.enter = async (wantScreen) => { + buildNav(); + const id = wantScreen || (location.hash.match(/^#\/(\w+)/) || [])[1] || safeStore.get('upstream.screen') || 'pop'; + App.go(App.screens.has(id) && id !== 'auth' ? id : 'pop'); + App.checkAlerts(); + try { await App.refreshTown(); } catch (e) { toast(App.errMsg(e), 'error'); } + }; + + // ------------------------------------------------------------------ boot + async function boot() { + const saved = safeStore.get(LANG_KEY); + App.state.lang = I.LANGS.includes(saved) ? saved : I.detectLang(navigator.language); + document.documentElement.lang = App.state.lang; + buildNav(); + if (!api.hasToken()) { App.go('auth'); return; } + const view = elView(); + const status = h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') })); + view.appendChild(status); + try { + await App.loadMe(); + status.remove(); + await App.enter(); + } catch (e) { + status.remove(); + if (e.code === 'network_error') { + const retry = h('button', { class: 'btn primary', type: 'button', onclick: () => { card.remove(); boot(); } }, icon('refresh'), App.t('common.retry')); + const card = h('div', { class: 'boot' }, h('p', { text: App.errMsg(e) }), retry); + view.appendChild(card); + } else if (e.code !== 'unauthorized') { + toast(App.errMsg(e), 'error'); + App.go('auth'); + } + } + } + + document.addEventListener('DOMContentLoaded', boot); +}()); diff --git a/public/js/render.js b/public/js/render.js new file mode 100644 index 0000000..8b28cfc --- /dev/null +++ b/public/js/render.js @@ -0,0 +1,398 @@ +'use strict'; +/* + * The canvas map and nothing else (window.MapRender.MapView): camera, pan / pinch / wheel / keyboard, tile culling, + * drawing. It knows no API. The screen gives it a `source` with the loaded data and callbacks: + * + * source.forEachSpecial(x0, y0, x1, y1, fn(special)) rural + incumbent tiles in the rect + * source.townsInRect(x0, y0, x1, y1) -> [town] POPs in the rect + * source.isOwn(town) -> bool + * onTap(x, y) a finger lift / click that was not a drag or a pinch (act on lift) + * onMoveEnd(view) debounced after the camera stopped; view = { x0, y0, x1, y1, cx, cy, zoom } + * + * Coordinates are tile units, y grows downward; tile (x, y) is the square [x-.5, x+.5] x [y-.5, y+.5]. + * Touch: one finger pans, two fingers pinch-zoom around their midpoint and never trigger a tap. A tap is only + * reported when no second finger was ever down and the finger moved less than a few pixels. + */ +(function () { + const COLORS = { + void: '#04070e', land: '#0d1626', land2: '#0f192b', grid: 'rgba(120,160,220,0.10)', grid10: 'rgba(120,160,220,0.22)', border: 'rgba(77,227,255,0.55)', + fiber: '#4de3ff', hardware: '#ff9f5a', capital: '#5be08f', incumbent: '#b06cff', incumbentFill: '#241338', + own: '#4de3ff', ownFill: '#0f4b63', select: '#ffd24d', text: '#e4f0ff', halo: 'rgba(4,7,14,0.9)', reach: 'rgba(77,227,255,0.35)', + }; + + const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v)); + + // A stable colour per operator id so rivals are told apart but never confused with you (cyan) or incumbents (violet). + function rivalColors(id) { + const hues = [8, 28, 48, 86, 150, 330, 355, 120]; // warm and green hues, no cyan/blue/violet + const hue = hues[Math.abs(id | 0) % hues.length]; + return { fill: 'hsl(' + hue + ',45%,24%)', stroke: 'hsl(' + hue + ',70%,62%)' }; + } + + class MapView { + constructor(canvas, source, opts) { + this.canvas = canvas; + this.ctx = canvas.getContext('2d'); + this.src = source; + this.opts = opts || {}; + this.radius = 50; + this.cx = 0; this.cy = 0; this.zoom = 24; + this.w = 0; this.h = 0; this.dpr = 1; + this.selected = null; + this.pointers = new Map(); + this.drag = null; + this.pinch = null; + this.raf = 0; + this.moveTimer = 0; + this.labelFn = null; + this.reachTiles = 2; + this._bind(); + } + + setWorld(radius) { this.radius = radius; this._limits(); this.invalidate(); } + setSelected(x, y) { this.selected = x === null ? null : { x, y }; this.invalidate(); } + + resize() { + const r = this.canvas.getBoundingClientRect(); + const dpr = Math.min(window.devicePixelRatio || 1, 3); + if (!r.width || !r.height) return false; + this.w = r.width; this.h = r.height; this.dpr = dpr; + this.canvas.width = Math.round(r.width * dpr); + this.canvas.height = Math.round(r.height * dpr); + this._limits(); + this.zoom = clamp(this.zoom, this.minZoom, this.maxZoom); + this._clampCenter(); + this.invalidate(); + this._scheduleMoveEnd(0); + return true; + } + + _limits() { + const span = this.radius * 2 + 3; + this.minZoom = clamp(Math.min(this.w || 300, this.h || 300) / span, 2.5, 20); + this.maxZoom = 90; + } + + _clampCenter() { + this.cx = clamp(this.cx, -this.radius, this.radius); + this.cy = clamp(this.cy, -this.radius, this.radius); + } + + setView(cx, cy, zoom) { + this.cx = cx; this.cy = cy; + if (zoom) this.zoom = clamp(zoom, this.minZoom, this.maxZoom); + this._clampCenter(); + this.invalidate(); + this._scheduleMoveEnd(0); + } + + // screen px (relative to the canvas) <-> tile coordinates + toTile(px, py) { return { x: (px - this.w / 2) / this.zoom + this.cx, y: (py - this.h / 2) / this.zoom + this.cy }; } + toScreen(x, y) { return { x: (x - this.cx) * this.zoom + this.w / 2, y: (y - this.cy) * this.zoom + this.h / 2 }; } + + // Visible tiles clamped to the world. + view() { + const a = this.toTile(0, 0), b = this.toTile(this.w, this.h), r = this.radius; + return { + x0: clamp(Math.floor(a.x), -r, r), y0: clamp(Math.floor(a.y), -r, r), + x1: clamp(Math.ceil(b.x), -r, r), y1: clamp(Math.ceil(b.y), -r, r), + cx: this.cx, cy: this.cy, zoom: this.zoom, + }; + } + + // Zoom keeping the world point under screen (px, py) fixed. + zoomAt(px, py, factor) { + const before = this.toTile(px, py); + this.zoom = clamp(this.zoom * factor, this.minZoom, this.maxZoom); + this.cx = before.x - (px - this.w / 2) / this.zoom; + this.cy = before.y - (py - this.h / 2) / this.zoom; + this._clampCenter(); + this.invalidate(); + this._scheduleMoveEnd(); + } + + panBy(dxPx, dyPx) { + this.cx -= dxPx / this.zoom; this.cy -= dyPx / this.zoom; + this._clampCenter(); + this.invalidate(); + this._scheduleMoveEnd(); + } + + _scheduleMoveEnd(delay) { + clearTimeout(this.moveTimer); + this.moveTimer = setTimeout(() => { if (this.opts.onMoveEnd && this.w) this.opts.onMoveEnd(this.view()); }, delay === undefined ? 200 : delay); + } + + invalidate() { + if (this.raf) return; + this.raf = requestAnimationFrame(() => { this.raf = 0; this.draw(); }); + } + + // ------------------------------------------------------------------ input + _bind() { + const c = this.canvas; + const rel = (e) => { const r = c.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; }; + + c.addEventListener('pointerdown', (e) => { + if (e.pointerType === 'mouse' && e.button !== 0) return; + try { c.setPointerCapture(e.pointerId); } catch (err) { /* synthetic */ } + const p = rel(e); + this.pointers.set(e.pointerId, { x: p.x, y: p.y }); + if (this.pointers.size === 1) { + this.drag = { startX: p.x, startY: p.y, lastX: p.x, lastY: p.y, moved: false, pinched: false, t: e.timeStamp, touch: e.pointerType !== 'mouse' }; + } else if (this.pointers.size === 2 && this.drag) { + this.drag.pinched = true; + this._startPinch(); + } + }); + + c.addEventListener('pointermove', (e) => { + const cur = this.pointers.get(e.pointerId); + if (!cur || !this.drag) return; + const p = rel(e); + cur.x = p.x; cur.y = p.y; + if (this.pointers.size >= 2 && this.pinch) { this._movePinch(); return; } + if (this.pointers.size === 1 && !this.drag.pinched) { + const slop = this.drag.touch ? 9 : 5; + if (!this.drag.moved && Math.hypot(p.x - this.drag.startX, p.y - this.drag.startY) > slop) this.drag.moved = true; + if (this.drag.moved) { + this.panBy(p.x - this.drag.lastX, p.y - this.drag.lastY); + c.classList.add('grabbing'); + } + this.drag.lastX = p.x; this.drag.lastY = p.y; + } + }); + + const end = (e, cancelled) => { + if (!this.pointers.has(e.pointerId)) return; + const p = rel(e); + this.pointers.delete(e.pointerId); + try { c.releasePointerCapture(e.pointerId); } catch (err) { /* already released */ } + const d = this.drag; + if (this.pointers.size === 1 && d) { + // one finger left after a pinch: continue as a pan from where that finger is, never as a tap + const [rest] = this.pointers.values(); + d.lastX = rest.x; d.lastY = rest.y; d.startX = rest.x; d.startY = rest.y; d.moved = true; + this.pinch = null; + } + if (this.pointers.size === 0 && d) { + const tap = !cancelled && !d.moved && !d.pinched && e.timeStamp - d.t < 700; + this.drag = null; this.pinch = null; + c.classList.remove('grabbing'); + if (tap && this.opts.onTap) { + const t = this.toTile(p.x, p.y); + this.opts.onTap(Math.round(t.x), Math.round(t.y)); + } + this._scheduleMoveEnd(60); + } + }; + c.addEventListener('pointerup', (e) => end(e, false)); + c.addEventListener('pointercancel', (e) => end(e, true)); + c.addEventListener('lostpointercapture', (e) => { if (this.pointers.has(e.pointerId)) end(e, true); }); + + c.addEventListener('wheel', (e) => { + e.preventDefault(); + const p = rel(e); + const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY; + this.zoomAt(p.x, p.y, Math.exp(-dy * 0.0016)); + }, { passive: false }); + + c.addEventListener('keydown', (e) => { + const step = Math.max(24, this.w * 0.2); + const k = e.key; + if (k === 'ArrowLeft') this.panBy(step, 0); + else if (k === 'ArrowRight') this.panBy(-step, 0); + else if (k === 'ArrowUp') this.panBy(0, step); + else if (k === 'ArrowDown') this.panBy(0, -step); + else if (k === '+' || k === '=') this.zoomAt(this.w / 2, this.h / 2, 1.3); + else if (k === '-' || k === '_') this.zoomAt(this.w / 2, this.h / 2, 1 / 1.3); + else if ((k === 'Enter' || k === ' ') && this.opts.onTap) this.opts.onTap(Math.round(this.cx), Math.round(this.cy)); + else return; + e.preventDefault(); + }); + } + + _pair() { const a = Array.from(this.pointers.values()); return [a[0], a[1]]; } + + _startPinch() { + const [a, b] = this._pair(); + const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + this.pinch = { dist: Math.max(10, Math.hypot(a.x - b.x, a.y - b.y)), zoom: this.zoom, world: this.toTile(mid.x, mid.y) }; + } + + _movePinch() { + const [a, b] = this._pair(); + const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + const k = Math.hypot(a.x - b.x, a.y - b.y) / this.pinch.dist; + this.zoom = clamp(this.pinch.zoom * k, this.minZoom, this.maxZoom); + // keep the world point that was under the fingers' midpoint under it (also pans with the midpoint) + this.cx = this.pinch.world.x - (mid.x - this.w / 2) / this.zoom; + this.cy = this.pinch.world.y - (mid.y - this.h / 2) / this.zoom; + this._clampCenter(); + this.invalidate(); + this._scheduleMoveEnd(); + } + + // ------------------------------------------------------------------ drawing + draw() { + const { ctx, dpr, w, h, zoom: z } = this; + if (!w || !h) return; + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.fillStyle = COLORS.void; + ctx.fillRect(0, 0, w, h); + + const r = this.radius; + const tl = this.toScreen(-r - 0.5, -r - 0.5), br = this.toScreen(r + 0.5, r + 0.5); + ctx.fillStyle = COLORS.land; + ctx.fillRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y); + + const v = this.view(); + // land texture + grid + if (z >= 9) { + ctx.fillStyle = COLORS.land2; + for (let y = v.y0; y <= v.y1; y++) { + for (let x = v.x0 + (((v.x0 + y) & 1) ? 1 : 0); x <= v.x1; x += 2) { + const s = this.toScreen(x - 0.5, y - 0.5); + ctx.fillRect(s.x, s.y, z, z); + } + } + } + ctx.lineWidth = 1; + if (z >= 14) { + ctx.strokeStyle = COLORS.grid; + ctx.beginPath(); + for (let x = v.x0; x <= v.x1 + 1; x++) { const s = this.toScreen(x - 0.5, 0).x; ctx.moveTo(Math.round(s) + 0.5, Math.max(0, tl.y)); ctx.lineTo(Math.round(s) + 0.5, Math.min(h, br.y)); } + for (let y = v.y0; y <= v.y1 + 1; y++) { const s = this.toScreen(0, y - 0.5).y; ctx.moveTo(Math.max(0, tl.x), Math.round(s) + 0.5); ctx.lineTo(Math.min(w, br.x), Math.round(s) + 0.5); } + ctx.stroke(); + } + // every 10 tiles, so a zoomed-out map still reads as a map + ctx.strokeStyle = COLORS.grid10; + ctx.beginPath(); + for (let x = Math.ceil(v.x0 / 10) * 10; x <= v.x1; x += 10) { const s = this.toScreen(x, 0).x; ctx.moveTo(Math.round(s) + 0.5, Math.max(0, tl.y)); ctx.lineTo(Math.round(s) + 0.5, Math.min(h, br.y)); } + for (let y = Math.ceil(v.y0 / 10) * 10; y <= v.y1; y += 10) { const s = this.toScreen(0, y).y; ctx.moveTo(Math.max(0, tl.x), Math.round(s) + 0.5); ctx.lineTo(Math.min(w, br.x), Math.round(s) + 0.5); } + ctx.stroke(); + + // specials: rural areas and incumbent sites + this.src.forEachSpecial(v.x0, v.y0, v.x1, v.y1, (sp) => { + const s = this.toScreen(sp.x, sp.y); + if (sp.type === 'rural') this._rural(s.x, s.y, sp.bonus); + else this._incumbent(s.x, s.y); + }); + + const towns = this.src.townsInRect(v.x0 - 1, v.y0 - 1, v.x1 + 1, v.y1 + 1); + // faint rural reach rings around your own POPs + if (z >= 10) { + ctx.save(); + ctx.setLineDash([4, 5]); + ctx.strokeStyle = COLORS.reach; + for (const t of towns) { + if (!this.src.isOwn(t)) continue; + const s = this.toScreen(t.x, t.y); + ctx.beginPath(); ctx.arc(s.x, s.y, this.reachTiles * z, 0, Math.PI * 2); ctx.stroke(); + } + ctx.restore(); + } + for (const t of towns) this._pop(t); + + // world border + ctx.strokeStyle = COLORS.border; + ctx.lineWidth = 2; + ctx.strokeRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y); + + // selection + if (this.selected) this._selection(this.selected); + } + + _rural(x, y, bonus) { + const { ctx, zoom: z } = this; + const col = COLORS[bonus] || COLORS.capital; + if (z < 6) { ctx.fillStyle = col; ctx.globalAlpha = 0.8; ctx.fillRect(x - Math.max(1, z / 2), y - Math.max(1, z / 2), Math.max(2, z), Math.max(2, z)); ctx.globalAlpha = 1; return; } + ctx.globalAlpha = 0.2; ctx.fillStyle = col; + ctx.beginPath(); ctx.arc(x, y, z * 0.46, 0, Math.PI * 2); ctx.fill(); + ctx.globalAlpha = 1; ctx.strokeStyle = col; ctx.lineWidth = Math.max(1, z * 0.06); + ctx.beginPath(); ctx.arc(x, y, z * 0.46, 0, Math.PI * 2); ctx.stroke(); + if (z >= 12) { + // "unconnected": a signal glyph with a cut line through it + ctx.lineWidth = Math.max(1, z * 0.07); ctx.lineCap = 'round'; + for (let i = 1; i <= 2; i++) { ctx.beginPath(); ctx.arc(x, y + z * 0.14, z * 0.1 * i + z * 0.04, Math.PI * 1.2, Math.PI * 1.8); ctx.stroke(); } + ctx.fillStyle = col; ctx.beginPath(); ctx.arc(x, y + z * 0.14, z * 0.05, 0, Math.PI * 2); ctx.fill(); + } + } + + _incumbent(x, y) { + const { ctx, zoom: z } = this; + const s = z * 0.78; + ctx.fillStyle = COLORS.incumbentFill; ctx.strokeStyle = COLORS.incumbent; ctx.lineWidth = Math.max(1, z * 0.07); + ctx.fillRect(x - s / 2, y - s / 2, s, s); + ctx.strokeRect(x - s / 2, y - s / 2, s, s); + if (z >= 14) { + ctx.fillStyle = COLORS.incumbent; + const n = 3, nw = s / 7; + for (let i = 0; i < n; i++) ctx.fillRect(x - s / 2 + s * 0.12 + i * (s * 0.3), y - s / 2 - nw * 0.0 + 1, nw * 1.3, nw * 1.3); + ctx.fillRect(x - s * 0.12, y + s * 0.02, s * 0.24, s * 0.28); + } + } + + _hex(x, y, rad) { + const { ctx } = this; + ctx.beginPath(); + for (let i = 0; i < 6; i++) { + const a = Math.PI / 6 + i * Math.PI / 3; + const px = x + Math.cos(a) * rad, py = y + Math.sin(a) * rad; + if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); + } + ctx.closePath(); + } + + _pop(t) { + const { ctx, zoom: z } = this; + const s = this.toScreen(t.x, t.y); + if (s.x < -40 || s.y < -40 || s.x > this.w + 40 || s.y > this.h + 40) return; + const own = this.src.isOwn(t); + const col = own ? { fill: COLORS.ownFill, stroke: COLORS.own } : rivalColors(t.owner.id); + const rad = Math.max(3, z * (own ? 0.5 : 0.42)); + if (own) { + ctx.save(); + ctx.shadowColor = COLORS.own; ctx.shadowBlur = Math.min(22, 6 + z * 0.35); + this._hex(s.x, s.y, rad); ctx.fillStyle = col.fill; ctx.fill(); + ctx.restore(); + } + this._hex(s.x, s.y, rad); + ctx.fillStyle = col.fill; ctx.fill(); + ctx.strokeStyle = col.stroke; ctx.lineWidth = own ? Math.max(2, z * 0.1) : Math.max(1.2, z * 0.07); ctx.stroke(); + if (z >= 10) { + ctx.fillStyle = col.stroke; + ctx.beginPath(); ctx.arc(s.x, s.y, Math.max(1.5, rad * (t.isCapital ? 0.38 : 0.22)), 0, Math.PI * 2); ctx.fill(); + if (t.isCapital) { ctx.strokeStyle = col.stroke; ctx.lineWidth = 1; this._hex(s.x, s.y, rad * 0.68); ctx.stroke(); } + } + if (z >= 18 && t.owner.protected) { + ctx.strokeStyle = COLORS.select; ctx.lineWidth = Math.max(1, z * 0.05); ctx.setLineDash([3, 3]); + this._hex(s.x, s.y, rad + z * 0.12); ctx.stroke(); ctx.setLineDash([]); + } + if (z >= 24 || (own && z >= 12)) { + const label = this.labelFn ? this.labelFn(t, own) : t.name; + ctx.font = (own ? '700 ' : '600 ') + Math.round(clamp(z * 0.34, 10, 14)) + 'px system-ui, sans-serif'; + ctx.textAlign = 'center'; ctx.textBaseline = 'top'; + ctx.lineWidth = 3; ctx.lineJoin = 'round'; ctx.strokeStyle = COLORS.halo; + ctx.strokeText(label, s.x, s.y + rad + 3); + ctx.fillStyle = own ? COLORS.own : COLORS.text; + ctx.fillText(label, s.x, s.y + rad + 3); + } + } + + _selection(sel) { + const { ctx, zoom: z } = this; + const s = this.toScreen(sel.x, sel.y); + const half = Math.max(5, z * 0.52), len = Math.max(3, half * 0.5); + ctx.strokeStyle = COLORS.select; ctx.lineWidth = 2.2; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; + ctx.beginPath(); + for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { + const px = s.x + sx * half, py = s.y + sy * half; + ctx.moveTo(px - sx * len, py); ctx.lineTo(px, py); ctx.lineTo(px, py - sy * len); + } + ctx.stroke(); + } + } + + window.MapRender = { MapView, COLORS }; +}()); diff --git a/public/js/rules.js b/public/js/rules.js index 5721b49..b09bc74 100644 --- a/public/js/rules.js +++ b/public/js/rules.js @@ -284,6 +284,37 @@ return out; } + // ------------------------------------------------------------------ alliances and diplomacy + // Member cap of an alliance for a given Peering office level (best POP of the leader). The server stores the cap at + // founding and only ever raises it (server/alliances.js effectiveCap), so a lost building never kicks anyone. + function allianceCap(peeringLevel) { + return D.SOCIAL.allianceBaseSize + D.SOCIAL.allianceSizePerLevel * Math.max(0, Math.floor(peeringLevel || 0)); + } + + // May a member with `role` perform `action` (a key of SOCIAL.permissions)? + function allianceCan(role, action) { + const list = hasOwn(D.SOCIAL.permissions, action) ? D.SOCIAL.permissions[action] : null; + return !!list && list.indexOf(role) >= 0; + } + + // Seniority: leader 4 .. member 1, unknown roles -1. + function roleRank(role) { + const i = D.SOCIAL.roles.indexOf(role); + return i < 0 ? -1 : D.SOCIAL.roles.length - i; + } + const outranks = (a, b) => roleRank(a) > roleRank(b); + + // How an alliance may move a relation from `from` to `to`: 'immediate' | 'proposal' | 'delayed' | null (not allowed). + function diplomacyMove(from, to) { + const row = hasOwn(D.SOCIAL.diplomacyMoves, from) ? D.SOCIAL.diplomacyMoves[from] : null; + return row && hasOwn(row, to) ? row[to] : null; + } + + // Time a unilateral cancel of a pact takes (24 h at 1x, shorter on faster worlds). + function pactCancelMs(worldSpeed) { + return Math.max(1000, Math.round(D.SOCIAL.pactCancelHours * HOUR / (worldSpeed || 1))); + } + // ------------------------------------------------------------------ movement // Latency in ms for a distance in tiles at `speed` tiles/hour (unit speed), world speed `worldSpeed`; min 10 min. function latencyMs(dist, unitSpeed, worldSpeed) { @@ -291,10 +322,343 @@ return Math.max(10 * 60 * 1000, Math.round(hours * HOUR)); } + // ------------------------------------------------------------------ military: units, training, research (stages 3-4) + // Units are always plain objects { unitId: count }. `research` is { 'unitId:attack': level, 'unitId:defence': level }. + const MIL = D.MILITARY; + + function unitDef(id) { return hasOwn(D.UNITS, id) ? D.UNITS[id] : null; } + const buildingLevel = (town, type) => (town.buildings[type] ? town.buildings[type].level : 0); + const unitCount = (units) => Object.keys(units || {}).reduce((s, k) => s + (units[k] || 0), 0); + const costValue = (cost) => D.RESOURCES.reduce((s, r) => s + ((cost && cost[r]) || 0), 0); + const unitValue = (id) => costValue(unitDef(id).cost); + const researchKey = (unit, stat) => unit + ':' + stat; + const researchLevel = (research, unit, stat) => (research && research[researchKey(unit, stat)]) || 0; + const researchMult = (level) => 1 + MIL.researchPerLevel * level; + // attack | defence of one unit of this type, with research + function unitStat(unit, stat, research) { return unitDef(unit)[stat] * researchMult(researchLevel(research, unit, stat)); } + + function unitCost(unit, count) { + const def = unitDef(unit), out = {}; + for (const r of D.RESOURCES) out[r] = def.cost[r] * count; + return out; + } + + // Training time in ms for a batch. The training building's level shortens it; world speed divides it. + function trainTimeMs(unit, count, buildingLvl, speed) { + const secs = unitDef(unit).time * count / (1 + MIL.trainSpeedPerLevel * buildingLvl) / (speed || 1); + return Math.max(1000, Math.round(secs * 1000)); + } + + // Missing requirements of a unit in a town: [{ type, level, have }]. The training building counts at level 1. + function unitMissing(town, unit) { + const def = unitDef(unit); + const need = [{ type: def.building, level: 1 }].concat(def.requires); + const best = {}; + for (const r of need) best[r.type] = Math.max(best[r.type] || 0, r.level); + const missing = []; + for (const type of Object.keys(best)) { + const have = buildingLevel(town, type); + if (have < best[type]) missing.push({ type, level: best[type], have }); + } + return missing; + } + + // Can `count` of `unit` be queued now? `tailAt` = due time of the last batch queued in the same building (batches of + // one building run one after another). Codes: unknown_unit, validation_failed, requirements_not_met, not_enough_resources. + function trainPlan(town, unit, count, now, tailAt) { + const def = unitDef(unit); + const base = { ok: false, unit, count }; + if (!def) return Object.assign(base, { code: 'unknown_unit' }); + if (!Number.isInteger(count) || count < 1 || count > MIL.maxBatch) return Object.assign(base, { code: 'validation_failed' }); + const missing = unitMissing(town, unit); + base.building = def.building; + base.cost = unitCost(unit, count); + base.durationMs = trainTimeMs(unit, count, buildingLevel(town, def.building), town.speed); + base.startAt = Math.max(now, tailAt || 0); + base.dueAt = base.startAt + base.durationMs; + base.missing = missing; + if (missing.length) return Object.assign(base, { code: 'requirements_not_met' }); + const have = resourcesAt(town, now).amounts; + for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' }); + base.ok = true; + return base; + } + + // ---- research + const RS = D.RESEARCH; + function researchCost(unit, toLevel) { + const def = unitDef(unit), out = {}; + for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * RS.costFactor * Math.pow(RS.costGrowth, toLevel - 1)); + return out; + } + // speedBonus: the operator's permanent research speed bonus from incumbent sites (0.1 = +10%). + function researchTimeMs(unit, toLevel, labLevel, speed, speedBonus) { + const secs = RS.timeBase * Math.pow(RS.timeGrowth, toLevel - 1) / (1 + RS.labSpeedPerLevel * labLevel) / (speed || 1) / (1 + (speedBonus || 0)); + return Math.max(1000, Math.round(secs * 1000)); + } + function researchSpeedBonus(sitesTaken) { return Math.min(D.INCUMBENT.researchSpeedMax, D.INCUMBENT.researchSpeedBonus * sitesTaken); } + + // Plan one research level. `current` = level now, `busy` = a research is already running in this POP. + // Codes: unknown_unit, not_researchable, max_level, requirements_not_met, queue_full, not_enough_resources. + function researchPlan(town, unit, stat, current, busy, now, speedBonus) { + const def = unitDef(unit); + const base = { ok: false, unit, stat, fromLevel: current, toLevel: current + 1 }; + if (!def) return Object.assign(base, { code: 'unknown_unit' }); + if (RS.stats.indexOf(stat) < 0 || !(def[stat] > 0)) return Object.assign(base, { code: 'not_researchable' }); + if (current >= RS.maxLevel) return Object.assign(base, { code: 'max_level' }); + const lab = buildingLevel(town, 'research_lab'); + const missing = unitMissing(town, unit); + const needLab = base.toLevel + RS.labOffset; + if (lab < needLab) missing.push({ type: 'research_lab', level: needLab, have: lab }); + base.missing = missing; + base.cost = researchCost(unit, base.toLevel); + base.durationMs = researchTimeMs(unit, base.toLevel, lab, town.speed, speedBonus); + if (missing.length) return Object.assign(base, { code: 'requirements_not_met' }); + if (busy) return Object.assign(base, { code: 'queue_full' }); + const have = resourcesAt(town, now).amounts; + for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' }); + base.ok = true; + return base; + } + + // ------------------------------------------------------------------ military: movements + // Slowest speed (tiles/hour at 1x) among the units actually in the group; Infinity when empty. + function slowestSpeed(units) { + let s = Infinity; + for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s = Math.min(s, unitDef(k).speed); + return s; + } + // Travel time of a unit group over `dist` tiles (min 10 min, see latencyMs). An empty group travels at transport speed. + function movementMs(dist, units, worldSpeed) { + const s = slowestSpeed(units); + return latencyMs(dist, isFinite(s) ? s : D.TRANSPORT.speed, worldSpeed); + } + function transportMs(dist, worldSpeed) { return latencyMs(dist, D.TRANSPORT.speed, worldSpeed); } + + // Shape and role check of the units on a movement of `type`. null when fine, otherwise { code, reason }. + function checkUnitsForType(type, units) { + const roles = hasOwn(D.MOVE_ROLES, type) ? D.MOVE_ROLES[type] : null; + if (!roles) return { code: 'validation_failed', reason: 'type carries no units' }; + let total = 0; + for (const k of Object.keys(units || {})) { + const n = units[k]; + const def = unitDef(k); + if (!def) return { code: 'unknown_unit', reason: k }; + if (!Number.isInteger(n) || n < 0) return { code: 'validation_failed', reason: 'bad count for ' + k }; + if (n === 0) continue; + if (def.fixed) return { code: 'validation_failed', reason: k + ' cannot move' }; + if (roles.indexOf(def.role) < 0) return { code: 'validation_failed', reason: k + ' cannot go on a ' + type }; + total += n; + } + if (total < 1) return { code: 'validation_failed', reason: 'no units' }; + if (type === 'settle') { + const only = Object.keys(units).filter((k) => units[k] > 0); + if (only.length !== 1 || only[0] !== D.EXPANSION.settleUnit || units[only[0]] !== D.EXPANSION.crews) { + return { code: 'validation_failed', reason: 'a settle needs exactly ' + D.EXPANSION.crews + ' ' + D.EXPANSION.settleUnit }; + } + } + if (type === 'takeover' && !(units[D.EXPANSION.conquestUnit] > 0)) return { code: 'validation_failed', reason: 'a takeover needs a ' + D.EXPANSION.conquestUnit }; + return null; + } + + // Beginner protection: a protected operator cannot be attacked (raid, attack, takeover). Scans are fine. + const isProtected = (protectionUntil, at) => (protectionUntil || 0) > at; + + // ------------------------------------------------------------------ military: combat + const firewallMult = (level) => 1 + F.firewallPerLevel * level; + const effectiveFirewall = (level, rigs) => Math.max(0, level - (rigs || 0) / MIL.rigFirewallDivisor); + + function powerOf(units, research, stat) { + let s = 0; + for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s += units[k] * unitStat(k, stat, research); + return s; + } + const attackPower = (units, research) => powerOf(units, research, 'attack'); + const defencePower = (units, research) => powerOf(units, research, 'defence'); + + // Remove a fraction of every unit type (rounded to whole units). -> { survivors, lost } + function applyLoss(units, fraction) { + const survivors = {}, lost = {}; + for (const k of Object.keys(units || {})) { + const n = units[k]; + if (!(n > 0)) continue; + const l = fraction >= 1 ? n : Math.min(n, Math.round(n * fraction)); + if (l > 0) lost[k] = l; + if (n - l > 0) survivors[k] = n - l; + } + return { survivors, lost }; + } + + // The battle. Deterministic: inputs in, result out, no randomness. + // o.kind: 'attack' (full) | 'raid' + // o.attackers: { units, research } + // o.defenders: [{ id, units, research }] everything defending the POP (home crews first, then each reinforcement) + // o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses) + // Full attack: the loser loses everything, the winner loses (loser/winner)^1.5 of its units. + // Raid: both sides lose 0.5 * (weaker/stronger)^1.5, whoever wins. Ties go to the defender. + function resolveBattle(o) { + const att = o.attackers.units || {}; + const A = attackPower(att, o.attackers.research); + const rigs = att.ddos_rig || 0; + const effFw = effectiveFirewall(o.firewall || 0, rigs); + const groups = o.defenders || []; + const raw = groups.map((g) => defencePower(g.units, g.research)); + const rawTotal = raw.reduce((s, v) => s + v, 0); + const isStatic = o.staticDefence !== undefined && o.staticDefence !== null; + const Dv = isStatic ? o.staticDefence : (rawTotal + MIL.defenceBase) * firewallMult(effFw); + const attackerWins = A > Dv; + const hi = Math.max(A, Dv), lo = Math.min(A, Dv); + const ratio = hi > 0 ? lo / hi : 0; + let attF, defF; + if (o.kind === 'raid') { + attF = defF = MIL.raidLossFactor * Math.pow(ratio, MIL.lossExponent); + } else if (attackerWins) { + attF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); defF = 1; + } else { + attF = 1; defF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); + } + if (isStatic) defF = 0; + const a = applyLoss(att, attF); + const defenders = groups.map((g, i) => { + const r = applyLoss(g.units, defF); + return { id: g.id, sent: g.units, lost: r.lost, survivors: r.survivors, share: rawTotal > 0 ? raw[i] / rawTotal : 0 }; + }); + return { kind: o.kind, A, D: Dv, defenceRaw: rawTotal, effectiveFirewall: effFw, attackerWins, ratio, attackerLossFraction: attF, defenderLossFraction: defF, + attacker: { sent: att, lost: a.lost, survivors: a.survivors }, defenders }; + } + + // Battle points for destroying units (operator_stats.attack_points / defense_points). + function battlePoints(lostUnits) { + let v = 0; + for (const k of Object.keys(lostUnits || {})) if (unitDef(k)) v += unitValue(k) * lostUnits[k]; + return v * MIL.pointsPerCost; + } + + // Share of the stock the Rack hall hides from a raid ("cold spare"). + const cacheFraction = (rackLevel) => Math.min(MIL.cacheMax, MIL.cachePerLevel * Math.max(0, rackLevel || 0)); + + // Loot: `carry` is split evenly over Fiber/Hardware/Capital; what one resource cannot give is shared by the others. + // avail = what can be taken. -> whole-number { fiber, hardware, capital }. + function lootSplit(carry, avail) { + const take = { fiber: 0, hardware: 0, capital: 0 }; + let left = Math.max(0, carry); + for (let pass = 0; pass < 4 && left > 1e-9; pass++) { + const open = D.RESOURCES.filter((r) => avail[r] - take[r] > 1e-9); + if (!open.length) break; + const share = left / open.length; + for (const r of open) { + const t = Math.min(share, avail[r] - take[r]); + take[r] += t; left -= t; + } + } + for (const r of D.RESOURCES) take[r] = Math.floor(take[r] + 1e-9); + return take; + } + const carryOf = (units) => Object.keys(units || {}).reduce((s, k) => s + (unitDef(k) ? unitDef(k).carry * units[k] : 0), 0); + + // Exploit kits (survivors) tear levels off one chosen building after a win. + const siegeLevels = (kits) => (kits >= MIL.kitsMin ? Math.max(1, Math.floor(kits / MIL.kitsPerLevel)) : 0); + + // Customer loyalty lost to one M&A team, from a seeded roll r in [0, 1). + function loyaltyDrop(r) { const lo = MIL.loyaltyDrop[0], hi = MIL.loyaltyDrop[1]; return lo + Math.min(hi - lo, Math.floor(r * (hi - lo + 1))); } + + // Why a POP cannot change owner: 'capital' | 'last_pop' | null. (A capital can still be dragged to zero loyalty.) + function takeoverBlock(isCapital, defenderTownCount) { + if (defenderTownCount <= 1) return 'last_pop'; // wins over 'capital': a lone capital is not even drained + if (isCapital) return 'capital'; + return null; + } + + // Footprint gate for founding or taking over: the operator owns `ownedCount` POPs now, `footprint` is their total. + function footprintGate(ownedCount, footprint) { + const need = footprintNeeded(ownedCount); + return { ok: footprint + 1e-6 >= need, need, have: footprint }; + } + + // Founding a POP: info about the target tile and the operator. Codes: invalid_target, out_of_range, footprint_too_low. + function settleCheck(o) { + if (o.tileType !== 'land' || o.occupied) return { ok: false, code: 'invalid_target', reason: o.occupied ? 'occupied' : 'not_empty_land' }; + if (!(o.nearestOwnDist <= D.EXPANSION.maxDistance)) return { ok: false, code: 'out_of_range', max: D.EXPANSION.maxDistance, have: o.nearestOwnDist }; + const g = footprintGate(o.ownedCount, o.footprint); + if (!g.ok) return { ok: false, code: 'footprint_too_low', need: g.need, have: g.have }; + return { ok: true }; + } + + // Wild slot choice at founding: two field types (any of FIELD_TYPES). Anything else falls back to the defaults. + function cleanWild(wild) { + const out = []; + for (let i = 0; i < D.WILD_SLOTS; i++) out.push(wild && D.FIELD_TYPES.indexOf(wild[i]) >= 0 ? wild[i] : D.START.wild[i]); + return out; + } + // A new POP: every field at level 0, no infrastructure at all. + function newTownBuildings(wild) { + const layout = fieldLayout(wild); + const out = {}; + for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: 0 }; + return out; + } + + // ---- scanning + const scanStrength = (count, research) => count * researchMult(researchLevel(research, 'port_scanner', 'defence')); + // sa = attacking scanner strength, sd = defending. Success needs sa > sd; buildings (and more) at 2:1. + // A failed scan loses every scanner and reveals the scanner to the target; a successful one loses 0.5*(sd/sa)^1.5. + function resolveScan(sa, sd) { + const success = sa > sd; + return { + success, + detail: !success ? 'none' : (sa >= MIL.scanBuildingsRatio * sd ? 'full' : 'basic'), + identityRevealed: !success, + lossFraction: success ? MIL.raidLossFactor * Math.pow(sd / sa, MIL.scanLossExponent) : 1, + }; + } + + // ---- incumbent (NPC) sites + // Static defence of the site at (x, y); ageDays = world age in world days (real days * speed). + function incumbentDefence(seed, x, y, ageDays) { + const f = 1 + D.INCUMBENT.variance * (2 * (hash(seed ^ 0x1ac0, x, y) / 4294967296) - 1); + return Math.round(D.INCUMBENT.baseDefence * f * (1 + D.INCUMBENT.perDayGrowth * Math.max(0, ageDays))); + } + + // ---- power: when the battery is empty, units go offline and are decommissioned later + const decommissionMs = (speed) => Math.round(MIL.decommissionHours * HOUR / (speed || 1)); + // units = { unit: count } of everything drawing power in one POP; allowedDraw = output minus building draw. + // Returns how many of each unit to decommission, most expensive first, until the draw fits. + function decommissionPlan(units, allowedDraw) { + let draw = 0; + for (const k of Object.keys(units)) draw += (units[k] || 0) * unitDef(k).draw; + const order = Object.keys(units).filter((k) => units[k] > 0).sort((a, b) => unitValue(b) - unitValue(a) || (a < b ? -1 : 1)); + const remove = {}; + for (const k of order) { + if (draw <= Math.max(0, allowedDraw) + 1e-9) break; + const d = unitDef(k).draw; + const n = d > 0 ? Math.min(units[k], Math.ceil((draw - Math.max(0, allowedDraw)) / d)) : 0; + if (n > 0) { remove[k] = n; draw -= n * d; } + } + return remove; + } + + // ---- transport (trade is built on it): concurrent links = Internet exchange level, each carries up to capacityPerLink + const transportLinks = (town) => buildingLevel(town, D.TRANSPORT.building); + // Codes: validation_failed, capacity_exceeded, no_transport_link, not_enough_resources. + function transportPlan(town, cargo, activeLinks, now) { + let total = 0; + for (const r of Object.keys(cargo || {})) { + if (D.RESOURCES.indexOf(r) < 0 || !Number.isInteger(cargo[r]) || cargo[r] < 0) return { ok: false, code: 'validation_failed' }; + total += cargo[r]; + } + if (total < 1) return { ok: false, code: 'validation_failed' }; + if (activeLinks >= transportLinks(town)) return { ok: false, code: 'no_transport_link', links: transportLinks(town), active: activeLinks }; + if (total > D.TRANSPORT.capacityPerLink) return { ok: false, code: 'capacity_exceeded', capacity: D.TRANSPORT.capacityPerLink, total }; + const have = resourcesAt(town, now).amounts; + for (const r of D.RESOURCES) if (have[r] + 1e-6 < (cargo[r] || 0)) return { ok: false, code: 'not_enough_resources' }; + return { ok: true, total }; + } + return { - rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn, + unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn, buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap, fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt, + allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs, footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs, }; })); diff --git a/public/js/screens/alerts.js b/public/js/screens/alerts.js new file mode 100644 index 0000000..2e3dff8 --- /dev/null +++ b/public/js/screens/alerts.js @@ -0,0 +1,84 @@ +'use strict'; +/* Alerts: the durable notification feed (GET /notifications). Newest first; what arrived since you last looked is marked. */ +(function () { + const { h, clear, icon } = UI; + const PAGE = 100, MAX_PAGES = 5; + + let box, listEl, statusEl, items = [], seenAtOpen = 0, loading = false, offTick = null; + + function townName(id) { + const t = App.state.towns.find((x) => x.id === id); + return t ? t.name : '#' + id; + } + + // One entry per notification type: icon + title + detail. Unknown types still show something readable. + function describe(n) { + const p = n.payload || {}; + if (n.type === 'build_done') { + return { icon: 'b-' + p.type, title: App.t('alerts.build_done', { name: App.buildingName(p.type), level: p.level }), detail: App.t('alerts.build_done.in', { town: townName(p.townId) }), go: 'pop' }; + } + return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null }; + } + + function draw() { + clear(listEl); + if (!items.length) { listEl.appendChild(h('p', { class: 'empty pad', text: App.t('alerts.empty') })); return; } + const now = App.now(); + for (const n of items.slice().reverse()) { + const d = describe(n); + const isNew = n.id > seenAtOpen; + listEl.appendChild(h('li', null, + h('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go); } }, + h('span', { class: 'row-ic' }, icon(d.icon)), + h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: d.title }), isNew ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null), + d.detail ? h('span', { class: 'row-sub', text: d.detail }) : null), + h('span', { class: 'when mono', dataset: { at: n.createdAt }, text: App.fmt.ago(now - n.createdAt) })))); + } + } + + async function load() { + if (loading) return; + loading = true; + statusEl.hidden = true; + try { + let after = items.length ? items[items.length - 1].id : 0; + for (let page = 0; page < MAX_PAGES; page++) { + const r = await App.api.get('/notifications', { after, limit: PAGE }); + items = items.concat(r.items); + if (r.next === null || !r.items.length) break; + after = r.next; + } + draw(); + if (items.length) App.markSeen(items[items.length - 1].id); else App.markSeen(0); + } catch (e) { + statusEl.textContent = App.t('alerts.error') + ' ' + App.errMsg(e); + statusEl.hidden = false; + } finally { loading = false; } + } + + App.registerScreen({ + id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false, + render(container) { + box = container; + listEl = h('ul', { class: 'alert-list' }); + statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true }); + box.appendChild(h('div', { class: 'page' }, + h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.alerts') }), + h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))), + statusEl, listEl)); + App.on('session', () => { items = []; }); + }, + onShow() { + seenAtOpen = App.getSeen(); + box.querySelector('h1').textContent = App.t('screen.alerts'); + draw(); + load(); + if (offTick) offTick(); + offTick = App.onTick(() => { + const now = App.now(); + for (const el of listEl.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; } + }); + }, + onHide() { if (offTick) offTick(); offTick = null; }, + }); +}()); diff --git a/public/js/screens/auth.js b/public/js/screens/auth.js new file mode 100644 index 0000000..d5a68fa --- /dev/null +++ b/public/js/screens/auth.js @@ -0,0 +1,100 @@ +'use strict'; +/* Login / signup. Not in the nav. The invite field appears when the server answers signup_closed. */ +(function () { + const { h, icon, clear } = UI; + let box, mode = 'login', needInvite = false, busy = false; + let refs = {}; + + function deviceName() { + const ua = navigator.userAgent || ''; + const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\//.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser'; + const os = /Android/.test(ua) ? 'Android' : /iPhone|iPad|iPod/.test(ua) ? 'iOS' : /Windows/.test(ua) ? 'Windows' : /Mac OS/.test(ua) ? 'macOS' : /Linux/.test(ua) ? 'Linux' : ''; + return (browser + (os ? ' on ' + os : '')).slice(0, 40); + } + + function showError(msg) { refs.err.textContent = msg || ''; refs.err.hidden = !msg; } + + function validationMessage(err) { + const list = err.details && err.details.errors; + const base = App.t('err.validation_failed'); + if (Array.isArray(list) && list.length) { + const f = list[0]; + const path = String(f.path || '').replace(/^\$?\.?/, ''); + return base + (path ? ' (' + path + ')' : ''); + } + return base; + } + + async function submit(ev) { + ev.preventDefault(); + if (busy) return; + showError(''); + const username = refs.user.value.trim(), password = refs.pass.value; + if (!username || !password) { showError(App.t('err.validation_failed')); return; } + busy = true; refs.go.disabled = true; refs.goText.textContent = App.t('auth.working'); + try { + let r; + if (mode === 'signup') { + const body = { username, password, device: deviceName() }; + if (needInvite && refs.invite.value.trim()) body.invite = refs.invite.value.trim(); + r = await App.api.post('/auth/signup', body, { auth: false }); + } else { + r = await App.api.post('/auth/login', { username, password, device: deviceName() }, { auth: false }); + } + App.api.setToken(r.token); + App.setSession(r.user, r.operators); + refs.pass.value = ''; + App.authNotice = null; + await App.enter('pop'); + } catch (e) { + if (e.code === 'signup_closed') { needInvite = true; draw(); refs.invite.focus(); showError(App.t('auth.invite.hint')); } + else if (e.code === 'validation_failed') showError(validationMessage(e)); + else showError(App.errMsg(e)); + } finally { + busy = false; + if (refs.go) { refs.go.disabled = false; refs.goText.textContent = App.t(mode === 'signup' ? 'auth.signup' : 'auth.login'); } + } + } + + function field(id, label, input, hint) { + return h('label', { class: 'field', for: id }, h('span', { class: 'field-lbl', text: label }), input, hint ? h('span', { class: 'field-hint', text: hint }) : null); + } + + function draw() { + const keep = { u: refs.user ? refs.user.value : '', p: refs.pass ? refs.pass.value : '', i: refs.invite ? refs.invite.value : '', e: refs.err ? refs.err.textContent : '' }; + clear(box); + const signup = mode === 'signup'; + refs.user = h('input', { id: 'f-user', name: 'username', type: 'text', autocomplete: 'username', autocapitalize: 'none', autocorrect: 'off', spellcheck: 'false', required: true, minlength: signup ? '3' : null, maxlength: '20', pattern: signup ? '[A-Za-z0-9_\\-]{3,20}' : null, enterkeyhint: 'next' }); + refs.pass = h('input', { id: 'f-pass', name: 'password', type: 'password', autocomplete: signup ? 'new-password' : 'current-password', required: true, minlength: signup ? '8' : null, maxlength: '128', enterkeyhint: needInvite && signup ? 'next' : 'go' }); + refs.invite = h('input', { id: 'f-invite', name: 'invite', type: 'text', autocomplete: 'off', autocapitalize: 'none', spellcheck: 'false', maxlength: '64', enterkeyhint: 'go' }); + refs.user.value = keep.u; refs.pass.value = keep.p; refs.invite.value = keep.i; + refs.err = h('p', { class: 'form-error', role: 'alert', hidden: true }); + refs.goText = h('span', { text: App.t(signup ? 'auth.signup' : 'auth.login') }); + refs.go = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), refs.goText); + const notice = App.authNotice ? h('p', { class: 'notice', text: App.authNotice }) : null; + + const form = h('form', { class: 'auth-form', novalidate: false, onsubmit: submit }, + h('h1', { class: 'auth-h', text: App.t(signup ? 'auth.signup' : 'auth.login') }), + notice, + field('f-user', App.t('auth.username'), refs.user, signup ? App.t('auth.username.hint') : null), + field('f-pass', App.t('auth.password'), refs.pass, signup ? App.t('auth.password.hint') : null), + signup && needInvite ? field('f-invite', App.t('auth.invite'), refs.invite) : null, + refs.err, refs.go, + h('button', { class: 'linklike', type: 'button', onclick: () => { mode = signup ? 'login' : 'signup'; draw(); } }, App.t(signup ? 'auth.toLogin' : 'auth.toSignup'))); + + box.appendChild(h('div', { class: 'auth-card' }, + h('div', { class: 'auth-logo' }, h('span', { class: 'brand-mark big', 'aria-hidden': 'true' }), h('span', { class: 'auth-name', text: App.t('app.name') })), + h('p', { class: 'auth-tag', text: App.t('app.tagline') }), + form, + h('div', { class: 'lang-switch', role: 'group', 'aria-label': App.t('settings.language') }, + ...['en', 'nb'].map((l) => h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(App.state.lang === l), onclick: () => App.setLang(l) }, l === 'en' ? 'EN' : 'NB'))))); + if (keep.e) showError(keep.e); + } + + App.registerScreen({ + id: 'auth', titleKey: 'app.name', nav: false, hud: false, + render(container) { box = container; }, + onShow() { draw(); if (window.matchMedia('(pointer: fine)').matches) setTimeout(() => { if (refs.user) refs.user.focus({ preventScroll: true }); }, 50); }, + onLang() { draw(); }, + }); +}()); diff --git a/public/js/screens/map.js b/public/js/screens/map.js new file mode 100644 index 0000000..6e0bff4 --- /dev/null +++ b/public/js/screens/map.js @@ -0,0 +1,220 @@ +'use strict'; +/* + * Map screen: owns the canvas (render.js draws it), fetches GET /map by viewport into a chunk cache, and shows the + * tile info sheet. One /map request returns at most a 81 x 81 window (r <= 40), so the world is cut into 40 x 40 + * chunks and only the chunks the viewport touches are fetched, again when the camera stops moving. Land tiles are + * implied by the API (only rural areas, incumbent sites and POPs are listed). + */ +(function () { + const { h, icon, openSheet, closeSheet, toast } = UI; + const R = UpstreamRules; + const F = UpstreamData.FORMULAS; + + const CHUNK = 40, STALE_MS = 60000, RETRY_MS = 6000, MAX_PARALLEL = 2; + + // ------------------------------------------------------------------ chunk store + class Store { + constructor() { this.chunks = new Map(); this.active = 0; this.errShown = 0; this.onChange = null; } + reset() { this.chunks.clear(); } + key(i, j) { return i + ',' + j; } + + // Make sure every chunk touching the rect is loaded and fresh. + ensure(v, radius) { + const i0 = Math.floor(v.x0 / CHUNK), i1 = Math.floor(v.x1 / CHUNK), j0 = Math.floor(v.y0 / CHUNK), j1 = Math.floor(v.y1 / CHUNK); + const want = []; + for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) { + if (i * CHUNK > radius || (i + 1) * CHUNK - 1 < -radius || j * CHUNK > radius || (j + 1) * CHUNK - 1 < -radius) continue; + const c = this.chunks.get(this.key(i, j)); + const now = Date.now(); + if (!c || (c.state === 'ok' && now - c.at > STALE_MS) || (c.state === 'error' && now - c.at > RETRY_MS)) want.push([i, j]); + } + // nearest to the view centre first + want.sort((a, b) => Math.hypot((a[0] + 0.5) * CHUNK - v.cx, (a[1] + 0.5) * CHUNK - v.cy) - Math.hypot((b[0] + 0.5) * CHUNK - v.cx, (b[1] + 0.5) * CHUNK - v.cy)); + for (const [i, j] of want) this.fetch(i, j); + } + + async fetch(i, j) { + const k = this.key(i, j); + const prev = this.chunks.get(k); + if (prev && prev.state === 'loading') return; + if (this.active >= MAX_PARALLEL) { setTimeout(() => this.fetch(i, j), 120); return; } + const rec = prev || { specials: [], towns: [], map: new Map(), at: 0 }; + rec.state = 'loading'; + this.chunks.set(k, rec); + this.active++; + const x0 = i * CHUNK, y0 = j * CHUNK; + try { + const r = await App.api.get('/map', { x: x0 + CHUNK / 2, y: y0 + CHUNK / 2, r: CHUNK / 2 }); + const inChunk = (o) => o.x >= x0 && o.x < x0 + CHUNK && o.y >= y0 && o.y < y0 + CHUNK; + rec.specials = r.specials.filter(inChunk); + rec.map = new Map(rec.specials.map((s) => [s.x * 4096 + s.y, s])); + rec.towns = r.towns.filter(inChunk); + rec.state = 'ok'; rec.at = Date.now(); + } catch (e) { + rec.state = prev && prev.at ? 'ok' : 'error'; rec.at = Date.now(); // keep showing old data when a refresh fails + if (Date.now() - this.errShown > 8000) { this.errShown = Date.now(); toast(App.t('map.error'), 'error'); } + } finally { + this.active--; + if (this.onChange) this.onChange(); + } + } + + chunkAt(x, y) { return this.chunks.get(this.key(Math.floor(x / CHUNK), Math.floor(y / CHUNK))); } + special(x, y) { const c = this.chunkAt(x, y); return c ? c.map.get(x * 4096 + y) : undefined; } + townAt(x, y) { const c = this.chunkAt(x, y); return c ? c.towns.find((t) => t.x === x && t.y === y) : undefined; } + loaded(x, y) { const c = this.chunkAt(x, y); return !!c && c.state === 'ok'; } + + forEachSpecial(x0, y0, x1, y1, fn) { + for (const c of this.chunks.values()) for (const s of c.specials) if (s.x >= x0 && s.x <= x1 && s.y >= y0 && s.y <= y1) fn(s); + } + townsInRect(x0, y0, x1, y1) { + const out = []; + for (const c of this.chunks.values()) for (const t of c.towns) if (t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1) out.push(t); + return out; + } + // After a rename the capital on the map must not show a stale name. + patchTown(id, patch) { for (const c of this.chunks.values()) for (const t of c.towns) if (t.id === id) Object.assign(t, patch); } + } + + // ------------------------------------------------------------------ screen + let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own'; + const store = new Store(); + let infoSheet = null; + + const ownOperatorId = () => (App.state.operator ? App.state.operator.id : null); + const capital = () => App.state.towns.find((t) => t.isCapital) || App.state.towns[0] || null; + + function updateCoords() { + if (!coordsEl || !view) return; + coordsEl.textContent = 'x ' + Math.round(view.cx) + ' · y ' + Math.round(view.cy); + } + + function centreOnOwn() { + const c = App.state.towns.find((t) => t.id === App.state.townId) || capital(); + if (!c) return; + view.setView(c.x, c.y, 30); + } + + function setup() { + if (ready) return; + ready = true; + canvas = h('canvas', { class: 'map-canvas', tabindex: '0', role: 'application', 'aria-label': App.t('map.label') }); + coordsEl = h('div', { class: 'map-coords mono', 'aria-hidden': 'true' }); + legendEl = h('ul', { class: 'map-legend', 'aria-hidden': 'true' }); + const zoomBtn = (name, label, f) => h('button', { class: 'map-btn', type: 'button', 'aria-label': label, onclick: f }, icon(name)); + const controls = h('div', { class: 'map-controls' }, + zoomBtn('plus', App.t('map.zoomIn'), () => view.zoomAt(view.w / 2, view.h / 2, 1.5)), + zoomBtn('minus', App.t('map.zoomOut'), () => view.zoomAt(view.w / 2, view.h / 2, 1 / 1.5)), + zoomBtn('locate', App.t('map.centre'), centreOnOwn)); + controls.dataset.role = 'controls'; + box.appendChild(canvas); box.appendChild(legendEl); box.appendChild(coordsEl); box.appendChild(controls); + + const source = { + forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn), + townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d), + isOwn: (t) => t.owner.id === ownOperatorId(), + }; + view = new MapRender.MapView(canvas, source, { + onTap: onTap, + onMoveEnd: (v) => { updateCoords(); store.ensure(v, App.state.world ? App.state.world.mapRadius : 50); }, + }); + view.labelFn = (t, own) => (own ? t.name : t.owner.name); + view.reachTiles = F.ruralReach; + store.onChange = () => view.invalidate(); + new ResizeObserver(() => { if (visible && view.resize()) updateCoords(); }).observe(box); + // The camera moves are frequent; keep the coords chip in step cheaply. + canvas.addEventListener('pointermove', () => updateCoords()); + canvas.addEventListener('wheel', () => updateCoords(), { passive: true }); + drawLegend(); + } + + function drawLegend() { + UI.clear(legendEl); + const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text); + legendEl.appendChild(item('you', App.t('map.legend.you'))); + legendEl.appendChild(item('rival', App.t('map.legend.rival'))); + legendEl.appendChild(item('rural', App.t('map.legend.rural'))); + legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent'))); + } + + // ------------------------------------------------------------------ tile info + function onTap(x, y) { + const w = App.state.world; + if (!w) return; + if (Math.abs(x) > w.mapRadius || Math.abs(y) > w.mapRadius) return; + showTile(x, y); + } + + function showTile(x, y) { + view.setSelected(x, y); + const town = store.townAt(x, y); + const special = store.special(x, y); + const known = store.loaded(x, y); + const type = town ? 'pop' : special ? special.type : 'land'; + const cap = capital(); + const body = []; + const row = (label, value) => h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value })); + + if (town) { + const own = town.owner.id === ownOperatorId(); + body.push(h('div', { class: 'pill-row' }, + own ? h('span', { class: 'pill accent', text: App.t('map.info.yours') }) : h('span', { class: 'pill', text: App.t('map.info.rival') }), + town.isCapital ? h('span', { class: 'pill', text: App.t('map.info.capital') }) : null, + town.owner.protected ? h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')) : null)); + body.push(row(App.t('map.info.operator'), town.owner.name)); + body.push(row(App.t('map.info.as'), UpstreamI18n.fmtAs(town.owner.asNumber))); + } else if (special && special.type === 'rural') { + body.push(h('p', { class: 'detail-desc', text: App.t('map.info.rural', { n: F.ruralReach, p: Math.round(F.ruralBonus * 100), res: App.resName(special.bonus) }) })); + body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus)))); + } else if (special && special.type === 'incumbent') { + body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') })); + } else if (!known) { + body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') })); + } else { + body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') })); + } + body.push(row('', App.t('map.info.coords', { x, y }))); + if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) }))); + if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) { + body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open'))); + } + const title = town ? town.name : App.t('tile.' + type); + infoSheet = openSheet({ + title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''), + closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body), + onClose: () => { if (view) view.setSelected(null); infoSheet = null; }, + }); + } + + // ------------------------------------------------------------------ screen registration + App.registerScreen({ + id: 'map', titleKey: 'screen.map', navKey: 'nav.map', icon: 'map', hud: true, + render(container) { + box = container; + App.on('session', () => { store.reset(); pendingFocus = 'own'; }); + App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); }); + }, + onShow(params) { + visible = true; + if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; } + setup(); + view.setWorld(App.state.world.mapRadius); + const apply = () => { + if (params && Number.isFinite(params.x)) view.setView(params.x, params.y, params.zoom || 40); + else if (pendingFocus) { centreOnOwn(); pendingFocus = null; } + else view.setView(view.cx, view.cy); + updateCoords(); + }; + // the container was display:none until now: measure after layout + requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); }); + }, + onHide() { visible = false; closeSheet(); }, + onLang() { + if (!ready) return; + canvas.setAttribute('aria-label', App.t('map.label')); + drawLegend(); + const labels = ['map.zoomIn', 'map.zoomOut', 'map.centre']; + box.querySelectorAll('.map-controls .map-btn').forEach((b, i) => b.setAttribute('aria-label', App.t(labels[i]))); + }, + }); +}()); diff --git a/public/js/screens/pop.js b/public/js/screens/pop.js new file mode 100644 index 0000000..2ee59fe --- /dev/null +++ b/public/js/screens/pop.js @@ -0,0 +1,495 @@ +'use strict'; +/* + * POP screen: header, build queue, power, resource fields (grouped by type), infrastructure; tap a building for + * the detail sheet. All numbers come from GET /towns/:id (the server's "next" plan decides what is buildable); the + * client only ticks values forward with rules.js and re-checks affordability live, so a button wakes up the moment + * the resources are there. Countdowns come from the server clock (App.now()). + */ +(function () { + const { h, clear, icon, toast, openSheet, closeSheet } = UI; + const R = UpstreamRules; + const D = UpstreamData; + const F = D.FORMULAS; + + let box = null, dirty = true, visible = false; + let refs = { tiles: new Map(), rows: new Map(), queue: [] }; + let offTick = null; + let prevQueue = null; + const refetchTries = new Map(); // queue event id -> refetch attempts after it came due + let sheetCtl = null; + + const td = () => App.state.townData; + const find = (key) => (td() ? td().buildings.find((b) => b.key === key) : null); + const resOf = (type) => D.FIELD_PRODUCES[type] || null; + + // ------------------------------------------------------------------ building state (live) + // 'queued' | 'ready' | 'locked' | 'max' | 'wait'. `code` is the reason it cannot be built now (null = can). + function stateOf(b, cur) { + const t = td(); + if (t.queue.some((q) => q.key === b.key)) return { st: 'queued', code: 'already_queued' }; + if (b.level >= b.maxLevel) return { st: 'max', code: 'max_level' }; + const n = b.next; + let code = n.code; + if (code === 'not_enough_resources' && cur && n.cost) { + let ok = true; + for (const r of D.RESOURCES) if (cur.amounts[r] + 1e-6 < n.cost[r]) ok = false; + if (ok) code = null; + } + if (code === null) return { st: 'ready', code: null }; + if (code === 'requirements_not_met') return { st: 'locked', code }; + return { st: 'wait', code }; + } + + // How long until the resources for `cost` are there (ms), or null if never (rate 0) / Infinity if above the storage cap. + function etaFor(cost, cur) { + let worst = 0; + for (const r of D.RESOURCES) { + const need = cost[r] - cur.amounts[r]; + if (need <= 0) continue; + if (cost[r] > cur.caps[r]) return Infinity; + const rate = cur.rates[r]; + if (rate <= 0) return null; + worst = Math.max(worst, need / rate * D.HOUR_MS); + } + return worst; + } + + // ------------------------------------------------------------------ pieces + function costChips(cost, cur, withHave) { + return h('div', { class: 'costs' }, D.RESOURCES.map((r) => { + const short = cur && cur.amounts[r] + 1e-6 < cost[r]; + return h('span', { class: 'cost ' + r + (short ? ' short' : ''), dataset: { res: r } }, icon(r), + h('b', { text: App.fmt.num(cost[r]) }), + withHave && cur ? h('small', { text: App.t('sheet.have', { n: App.fmt.num(cur.amounts[r]) }) }) : null); + })); + } + + const fmt2 = (x) => x.toFixed(2).replace('.', App.state.lang === 'nb' ? ',' : '.'); + + function levelPreview(b, toLevel) { + // [{ text }] lines describing what the next level changes, from rules.js. + const t = td(), rt = App.rulesTown(), world = App.state.world; + const lines = []; + const fmt = App.fmt; + const withLevel = (lvl) => { + const bb = Object.assign({}, rt.buildings); + bb[b.key] = { type: b.type, level: lvl }; + return Object.assign({}, rt, { buildings: bb }); + }; + if (b.kind === 'field') { + const res = resOf(b.type); + const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0)); + const a = R.fieldOutputPerHour(b.level) * mult, c = R.fieldOutputPerHour(toLevel) * mult; + lines.push(App.t('sheet.preview.output', { a: fmt.dec(a), b: fmt.dec(c) }) + ' ' + App.resName(res)); + } else if (b.type === 'rack_hall') { + lines.push(App.t('sheet.preview.storage', { a: fmt.num(R.storageCap(withLevel(b.level))), b: fmt.num(R.storageCap(withLevel(toLevel))) })); + } else if (b.type === 'battery_bank') { + lines.push(App.t('sheet.preview.battery', { a: fmt.num(R.batteryCap(withLevel(b.level))), b: fmt.num(R.batteryCap(withLevel(toLevel))) })); + } else if (b.type === 'core_router') { + const k = (l) => fmt2(1 / (1 + F.coreSpeedPerLevel * l)); + lines.push(App.t('sheet.preview.core', { a: k(b.level), b: k(toLevel) })); + if (toLevel === F.secondQueueCoreLevel) lines.push(App.t('sheet.preview.core2', { n: toLevel })); + } else if (b.type === 'firewall') { + lines.push(App.t('sheet.preview.firewall', { a: fmt2(1 + F.firewallPerLevel * b.level), b: fmt2(1 + F.firewallPerLevel * toLevel) })); + } + const def = D.BUILDINGS[b.type]; + if (def && def.draw > 0) lines.push(App.t('sheet.preview.draw', { n: def.draw })); + return lines; + } + + function requirementList(b) { + const def = D.BUILDINGS[b.type]; + const levels = {}; + for (const x of td().buildings) if (x.kind === 'infra') levels[x.type] = x.level; + return (def.requires || []).map((rq) => { + const have = levels[rq.type] || 0, ok = have >= rq.level; + return h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'), + h('span', { text: App.buildingName(rq.type) + ' ' + App.t('pop.level', { n: rq.level }) }), + h('small', { text: App.t('sheet.have', { n: have }) })); + }); + } + + // ------------------------------------------------------------------ detail sheet + function openBuilding(key, opts) { + const first = find(key); + if (!first) return; + const R_ = { cur: null }; + const body = h('div', { class: 'detail' }); + const ctl = openSheet({ + title: App.buildingName(first.type), icon: 'b-' + first.type, iconClass: first.kind === 'field' ? 'res-' + resOf(first.type) : '', + closeLabel: App.t('common.close'), body, + onClose: () => { if (offSheetTick) offSheetTick(); offSheetTick = null; sheetCtl = null; }, + }); + sheetCtl = ctl; + let offSheetTick = null; + + const els = {}; + function build() { + for (const k of Object.keys(els)) delete els[k]; + const b = find(key); + if (!b) { ctl.close(); return; } + const cur = App.resourcesNow(); + clear(body); + body.appendChild(h('p', { class: 'detail-desc', text: App.buildingDesc(b.type) })); + body.appendChild(h('div', { class: 'detail-level' }, + h('span', { class: 'lvl-now', text: b.level > 0 ? App.t('sheet.level', { n: b.level }) : App.t('pop.notBuilt') }), + b.level < b.maxLevel ? h('span', { class: 'lvl-next' }, icon('up'), App.t('sheet.nextLevel', { n: b.level + 1 })) : h('span', { class: 'lvl-next', text: App.t('sheet.maxed') }))); + + const queued = td().queue.find((q) => q.key === key); + if (queued) { + els.qbar = h('i'); + els.qtime = h('b', { class: 'mono' }); + body.appendChild(h('div', { class: 'detail-queue' }, + h('div', { class: 'row' }, h('span', { text: App.t('sheet.underway') + ' · ' + App.t('pop.queue.to', { n: queued.toLevel }) }), els.qtime), + h('div', { class: 'bar' }, els.qbar))); + els.cancel = h('button', { class: 'btn danger wide', type: 'button', onclick: () => confirmCancel(queued) }, icon('x'), App.t('sheet.cancel')); + body.appendChild(els.cancel); + updateQueueEls(queued, App.now()); + return; + } + if (b.level >= b.maxLevel) return; + + const to = b.level + 1; + const next = b.next; + for (const text of levelPreview(b, to)) body.appendChild(h('p', { class: 'preview', text })); + els.costs = costChips(next.cost, cur, true); + body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.cost') })); + body.appendChild(els.costs); + body.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('sheet.time') + ': ' }), h('b', { text: App.fmt.dur(next.durationMs) }))); + const reqs = requirementList(b); + if (reqs.length) { body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.requires') })); body.appendChild(h('ul', { class: 'reqs' }, reqs)); } + els.reason = h('p', { class: 'reason', 'aria-live': 'polite' }); + els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => doBuild(b.key) }, icon('up'), h('span', { text: App.t(b.level > 0 ? 'sheet.upgrade' : 'sheet.build', { n: to }) })); + body.appendChild(els.reason); + body.appendChild(els.btn); + updateLive(); + } + + function updateQueueEls(q, now) { + const left = q.dueAt - now; + els.qtime.textContent = App.fmt.clock(left); + els.qbar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt))))); + } + + let busy = false; + function updateLive() { + const b = find(key); + if (!b || !els.btn) return; + const cur = App.resourcesNow(); + const s = stateOf(b, cur); + for (const chip of els.costs.children) chip.classList.toggle('short', cur.amounts[chip.dataset.res] + 1e-6 < b.next.cost[chip.dataset.res]); + const can = s.code === null && !busy; + els.btn.disabled = !can; + let reason = ''; + if (s.code) { + reason = App.t('err.' + s.code); + if (s.code === 'not_enough_resources') { + const eta = etaFor(b.next.cost, cur); + if (eta === Infinity) reason = App.t('sheet.capTooLow', { cap: App.fmt.num(cur.caps.fiber) }); + else if (eta !== null) reason = App.t('sheet.affordableIn', { t: App.fmt.dur(Math.max(1000, eta)) }); + } + } + els.reason.textContent = reason; + els.reason.hidden = !reason; + } + + async function doBuild(k) { + if (busy) return; + busy = true; els.btn.disabled = true; + els.btn.querySelector('span').textContent = App.t('sheet.building'); + const t = td(); + try { + const b = find(k); + await App.api.post('/towns/' + t.id + '/build', { key: k }, { intent: 'build:' + t.id + ':' + k }); + toast(App.t('sheet.built', { name: App.buildingName(b.type), n: b.level + 1 }), 'ok'); + ctl.close(); + await App.refreshTown(); + } catch (e) { + toast(App.errMsg(e), 'error'); + busy = false; + try { await App.refreshTown(); } catch (e2) { /* shown by the offline chip */ } + if (sheetCtl === ctl) build(); + } + } + + function confirmCancel(q) { + clear(body); + const b = find(key); + body.appendChild(h('p', { class: 'detail-desc', text: App.t('sheet.cancel.confirm', { name: App.buildingName(b.type), n: q.toLevel }) })); + body.appendChild(h('p', { class: 'preview', text: App.t('sheet.cancel.refund') })); + body.appendChild(h('div', { class: 'btn-row' }, + h('button', { class: 'btn', type: 'button', onclick: () => build() }, App.t('sheet.cancel.keep')), + h('button', { class: 'btn danger', type: 'button', onclick: async (ev) => { + ev.currentTarget.disabled = true; + try { + await App.api.del('/towns/' + td().id + '/queue/' + q.id); + toast(App.t('sheet.cancelled'), 'ok'); + } catch (e) { toast(App.errMsg(e), 'error'); } + ctl.close(); + App.refreshTown().catch(() => {}); + } }, icon('x'), App.t('sheet.cancel')))); + } + + offSheetTick = App.onTick((now) => { + const q = td() && td().queue.find((x) => x.key === key); + if (q && els.qtime) updateQueueEls(q, now); else if (els.btn) updateLive(); + }); + const offTown = App.on('town', () => { if (sheetCtl === ctl) build(); }); + const prevClose = offSheetTick; + offSheetTick = () => { prevClose(); offTown(); }; + build(); + if (opts && opts.cancel) { const q = td().queue.find((x) => x.key === key); if (q) confirmCancel(q); } + } + + // ------------------------------------------------------------------ main drawing + function tileLabel(b, s) { + const status = s.st === 'queued' ? App.t('pop.inQueue') : s.st === 'ready' ? App.t('pop.upgradeReady') : s.st === 'max' ? App.t('pop.max') : s.st === 'locked' ? App.t('pop.locked') : ''; + return App.buildingName(b.type) + ', ' + (b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt')) + (status ? ', ' + status : ''); + } + + function fieldTile(b) { + const res = resOf(b.type); + const lvl = h('b', { class: 'tile-lvl', text: String(b.level) }); + const badge = h('span', { class: 'tile-badge', 'aria-hidden': 'true' }); + const bar = h('i'); + const el = h('button', { class: 'tile res-' + res, type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) }, + icon('b-' + b.type, 'tile-ic'), lvl, badge, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar)); + refs.tiles.set(b.key, { el, badge, bar, b }); + return el; + } + + function infraRow(b) { + const status = h('span', { class: 'pill' }); + const sub = h('span', { class: 'row-sub' }); + const bar = h('i'); + const el = h('button', { class: 'row-btn', type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) }, + h('span', { class: 'row-ic' }, icon('b-' + b.type)), + h('span', { class: 'row-main' }, + h('span', { class: 'row-title' }, h('b', { text: App.buildingName(b.type) }), h('span', { class: 'lv', text: b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt') })), + sub), + status, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar)); + refs.rows.set(b.key, { el, status, sub, bar, b }); + return el; + } + + function header(t) { + const st = App.state; + const bonus = D.RESOURCES.filter((r) => (t.bonus && t.bonus[r] > 0)).map((r) => h('span', { class: 'pill res-' + r }, icon(r), '+' + Math.round(t.bonus[r] * 100) + '% ' + App.resName(r))); + const title = st.towns.length > 1 + ? h('select', { class: 'town-select', 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) }, + st.towns.map((x) => h('option', { value: x.id, selected: x.id === t.id, text: x.name }))) + : h('h1', { class: 'town-name', text: t.name }); + return h('section', { class: 'card pop-head' }, + h('div', { class: 'pop-title' }, title, + h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.rename'), onclick: openRename }, icon('pencil'))), + h('div', { class: 'pop-meta' }, + h('span', { text: App.t('pop.coords', { x: t.x, y: t.y }) }), + t.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null, + h('span', { class: 'pill' }, icon('shield'), App.t('pop.loyalty') + ' ' + App.fmt.num(t.loyalty)), + h('span', { class: 'pill', text: App.t('pop.footprint') + ' ' + App.fmt.num(t.footprint) + ' (' + App.t('pop.footprintPerDay', { n: App.fmt.num(t.footprintPerDay) }) + ')' }), + bonus.length ? bonus : h('span', { class: 'pill dim', text: App.t('pop.bonus.none') }))); + } + + function openRename() { + const t = td(); + const input = h('input', { type: 'text', value: t.name, maxlength: '40', minlength: '2', 'aria-label': App.t('pop.rename.label'), autocomplete: 'off', enterkeyhint: 'done' }); + const err = h('p', { class: 'form-error', role: 'alert', hidden: true }); + const save = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), App.t('common.save')); + const form = h('form', { class: 'detail', onsubmit: async (ev) => { + ev.preventDefault(); + const name = input.value.trim(); + if (name.length < 2) { err.textContent = App.t('err.validation_failed'); err.hidden = false; return; } + save.disabled = true; + try { + const r = await App.api.post('/towns/' + t.id + '/rename', { name }); + const known = App.state.towns.find((x) => x.id === t.id); + if (known) known.name = r.name; + toast(App.t('pop.rename.done'), 'ok'); + sheet.close(); + await App.refreshTown(); + } catch (e) { err.textContent = App.errMsg(e); err.hidden = false; save.disabled = false; } + } }, h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('pop.rename.label') }), input), err, save); + const sheet = openSheet({ title: App.t('pop.rename'), icon: 'pencil', closeLabel: App.t('common.close'), body: form }); + setTimeout(() => { input.focus(); input.select(); }, 60); + } + + function queueCard(t) { + refs.queue = []; + const slots = h('span', { class: 'pill', text: App.t('pop.queue.slots', { used: t.queue.length, total: t.queueSlots }) }); + const list = h('div', { class: 'queue' }); + for (const q of t.queue) { + const time = h('b', { class: 'mono' }), bar = h('i'); + const name = App.buildingName(q.type); + list.appendChild(h('div', { class: 'q-item' }, + h('button', { class: 'q-main', type: 'button', onclick: () => openBuilding(q.key), 'aria-label': name + ' ' + App.t('pop.queue.to', { n: q.toLevel }) }, + h('span', { class: 'row-ic' }, icon('b-' + q.type)), + h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), h('span', { class: 'lv', text: App.t('pop.queue.to', { n: q.toLevel }) })), + h('span', { class: 'bar' }, bar)), + time), + h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.queue.cancel') + ': ' + name, onclick: () => openBuilding(q.key, { cancel: true }) }, icon('x')))); + refs.queue.push({ q, time, bar }); + } + if (!t.queue.length) list.appendChild(h('p', { class: 'empty', text: App.t('pop.queue.empty') })); + return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.queue.title') }), slots), list); + } + + function powerCard() { + refs.power = { out: h('b'), draw: h('b'), net: h('b'), buf: h('span', { class: 'mono' }), bar: h('i'), status: h('p', { class: 'power-status' }) }; + const p = refs.power; + return h('section', { class: 'card power-card' }, + h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('power.title'))), + h('div', { class: 'stat-row' }, + h('div', { class: 'stat' }, h('small', { text: App.t('power.out') }), p.out), + h('div', { class: 'stat' }, h('small', { text: App.t('power.draw') }), p.draw), + h('div', { class: 'stat' }, h('small', { text: App.t('power.net') }), p.net)), + h('div', { class: 'row' }, h('span', { class: 'dimmer', text: App.t('power.buffer') }), p.buf), + h('div', { class: 'bar power-bar', 'aria-hidden': 'true' }, p.bar), p.status); + } + + function fieldsCard(t) { + const fields = t.buildings.filter((b) => b.kind === 'field'); + const world = App.state.world; + const groups = h('div', { class: 'groups' }); + for (const type of D.FIELD_TYPES) { + const list = fields.filter((b) => b.type === type); + if (!list.length) continue; + const res = resOf(type); + const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0)); + const total = list.reduce((s, b) => s + R.fieldOutputPerHour(b.level) * mult, 0); + groups.appendChild(h('div', { class: 'group res-' + res }, + h('div', { class: 'group-head' }, icon(res), h('b', { text: App.buildingName(type) }), h('span', { class: 'dimmer', text: '×' + list.length }), + h('span', { class: 'group-rate', text: App.fmt.dec(total, true) + ' ' + App.resName(res) + App.t('common.perHour') })), + h('div', { class: 'tiles' }, list.map(fieldTile)))); + } + return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.fields.title') })), groups); + } + + function infraCard(t) { + const list = t.buildings.filter((b) => b.kind === 'infra'); + return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.infra.title') })), h('div', { class: 'rows' }, list.map(infraRow))); + } + + function draw() { + dirty = false; + refs = { tiles: new Map(), rows: new Map(), queue: [] }; + clear(box); + const t = td(); + if (!App.state.townId) { box.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; } + if (!t) { box.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; } + box.appendChild(h('div', { class: 'cols' }, + h('div', { class: 'col' }, header(t), queueCard(t), powerCard()), + h('div', { class: 'col' }, fieldsCard(t), infraCard(t)))); + tick(App.now()); + } + + // ------------------------------------------------------------------ ticking + function tick(now) { + const t = td(); + if (!t || !refs.power) return; + const cur = App.resourcesNow(now); + const f = App.fmt; + + // queue countdowns + the refetch when something comes due + for (const e of refs.queue) { + const q = e.q, left = q.dueAt - now; + const time = f.clock(left); + if (e.time.textContent !== time) e.time.textContent = time; + e.bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt))))); + if (left <= -300) { + const tries = refetchTries.get(q.id) || { n: 0, at: 0 }; + if (Date.now() >= tries.at) { + refetchTries.set(q.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) }); + App.refreshTown().catch(() => {}); + } + } + } + + // tiles and rows + const queueByKey = new Map(t.queue.map((q) => [q.key, q])); + for (const [key, e] of refs.tiles) { + const s = stateOf(e.b, cur); + if (e.el.dataset.st !== s.st) { + e.el.dataset.st = s.st; + e.badge.textContent = ''; + if (s.st === 'queued') e.badge.appendChild(icon('clock')); + else if (s.st === 'ready') e.badge.appendChild(icon('up')); + else if (s.st === 'locked') e.badge.appendChild(icon('lock')); + e.el.setAttribute('aria-label', tileLabel(e.b, s)); + } + const q = queueByKey.get(key); + e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0'); + } + for (const [key, e] of refs.rows) { + const s = stateOf(e.b, cur); + const q = queueByKey.get(key); + let pill = '', pillCls = 'pill', sub = ''; + if (s.st === 'queued') { pill = f.clock(q.dueAt - now); pillCls += ' amber mono'; sub = App.buildingDesc(e.b.type); } + else if (s.st === 'ready') { pill = App.t(e.b.level > 0 ? 'pop.upgradeReady' : 'sheet.build', { n: e.b.level + 1 }); pillCls += ' green'; sub = App.buildingDesc(e.b.type); } + else if (s.st === 'max') { pill = App.t('pop.max'); sub = App.buildingDesc(e.b.type); } + else if (s.st === 'locked') { + const m = (e.b.next.missing || [])[0]; + pill = m ? App.buildingName(m.type) + ' ' + App.t('pop.level', { n: m.level }) : App.t('pop.locked'); pillCls += ' dim'; + sub = App.buildingDesc(e.b.type); + } else sub = App.buildingDesc(e.b.type); + if (e.status.textContent !== pill) e.status.textContent = pill; + e.status.className = pillCls; + e.status.hidden = !pill; + if (e.sub.textContent !== sub) e.sub.textContent = sub; + e.el.dataset.st = s.st; + e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0'); + } + + // power + const p = refs.power, net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery; + p.out.textContent = f.dec(cur.rates.powerOut); + p.draw.textContent = f.dec(cur.rates.powerDraw); + p.net.textContent = f.dec(net, true); + p.net.className = net < 0 ? 'bad' : 'good'; + p.buf.textContent = f.num(buf) + ' / ' + f.num(bcap) + ' ' + App.t('power.unit'); + p.bar.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0)); + const speed = App.state.world.speed || 1; + let status, cls = ''; + if (net < 0) { + if (buf <= 0) { status = App.t('power.empty'); cls = 'bad'; } + else { status = App.t('power.draining', { t: f.dur(buf / (-net * speed) * D.HOUR_MS) }); cls = 'warn'; } + } else if (net > 0 && buf < bcap - 0.01) status = App.t('power.charging', { t: f.dur((bcap - buf) / (net * speed) * D.HOUR_MS) }); + else status = buf >= bcap - 0.01 && bcap > 0 ? App.t('power.full') : App.t('power.ok'); + if (p.status.textContent !== status) p.status.textContent = status; + p.status.className = 'power-status ' + cls; + } + + // ------------------------------------------------------------------ town changed + function onTown(t) { + // toast for levels that finished since the last fetch + if (prevQueue && prevQueue.townId === t.id) { + const nowIds = new Set(t.queue.map((q) => q.id)); + for (const q of prevQueue.items) { + if (nowIds.has(q.id)) continue; + const b = t.buildings.find((x) => x.key === q.key); + if (b && b.level >= q.toLevel) toast(App.t('alerts.build_done', { name: App.buildingName(q.type), level: b.level }), 'ok'); + refetchTries.delete(q.id); + App.checkAlerts(); + } + } + prevQueue = { townId: t.id, items: t.queue.slice() }; + if (visible) draw(); else dirty = true; + } + + App.registerScreen({ + id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', hud: true, + render(container) { + box = container; + App.on('town', onTown); + App.on('session', () => { dirty = true; prevQueue = null; }); + App.on('townchange', () => { dirty = true; if (visible) draw(); }); + }, + onShow() { + visible = true; + draw(); + if (offTick) offTick(); + offTick = App.onTick(tick); + if (td() && Date.now() - App.state.townFetchedAt > 15000) App.refreshTown().catch(() => {}); + }, + onHide() { visible = false; if (offTick) offTick(); offTick = null; closeSheet(); }, + }); +}()); diff --git a/public/js/screens/settings.js b/public/js/screens/settings.js new file mode 100644 index 0000000..12ad78b --- /dev/null +++ b/public/js/screens/settings.js @@ -0,0 +1,84 @@ +'use strict'; +/* Settings: language, account info, device tokens (list + revoke) and logout. */ +(function () { + const { h, clear, icon, toast, openSheet } = UI; + const I = UpstreamI18n; + + let box, devicesEl, tokens = null, tokenErr = null; + + function kv(label, value) { return h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value })); } + + async function loadTokens() { + try { tokens = (await App.api.get('/auth/tokens')).tokens; tokenErr = null; } catch (e) { tokenErr = App.errMsg(e); } + drawDevices(); + } + + function drawDevices() { + if (!devicesEl) return; + clear(devicesEl); + if (tokenErr) { devicesEl.appendChild(h('p', { class: 'form-error', role: 'alert', text: tokenErr })); return; } + if (!tokens) { devicesEl.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; } + const now = App.now(); + for (const t of tokens) { + devicesEl.appendChild(h('li', { class: 'device' }, + h('span', { class: 'row-ic' }, icon('device')), + h('span', { class: 'row-main' }, + h('span', { class: 'row-title' }, h('b', { text: t.device || App.t('settings.device.unnamed') }), t.current ? h('span', { class: 'pill accent', text: App.t('settings.device.current') }) : null), + h('span', { class: 'row-sub', text: App.t('settings.device.created', { t: App.fmt.ago(now - t.createdAt) }) + ' · ' + App.t('settings.device.lastUsed', { t: App.fmt.ago(now - t.lastUsedAt) }) })), + t.current ? null : h('button', { class: 'btn small danger', type: 'button', onclick: (ev) => revoke(t, ev.currentTarget) }, App.t('settings.device.revoke')))); + } + } + + async function revoke(t, btn) { + btn.disabled = true; + try { + await App.api.del('/auth/tokens/' + t.id); + toast(App.t('settings.device.revoked'), 'ok'); + } catch (e) { if (e.code !== 'not_found') toast(App.errMsg(e), 'error'); } + loadTokens(); + } + + function confirmLogout() { + const sheet = openSheet({ + title: App.t('settings.logout'), icon: 'logout', closeLabel: App.t('common.close'), + body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: App.t('settings.logout.confirm') }), + h('div', { class: 'btn-row' }, + h('button', { class: 'btn', type: 'button', onclick: () => sheet.close() }, App.t('common.cancel')), + h('button', { class: 'btn danger', type: 'button', onclick: async () => { + try { await App.api.post('/auth/logout', {}, { retries: 1 }); } catch (e) { /* the token may already be gone */ } + sheet.close(); + App.clearSession(); + App.authNotice = null; + App.go('auth'); + } }, icon('logout'), App.t('settings.logout')))), + }); + } + + function draw() { + clear(box); + const st = App.state; + const op = st.operator, w = st.world; + devicesEl = h('ul', { class: 'device-list' }); + box.appendChild(h('div', { class: 'page' }, + h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.language') })), + h('div', { class: 'seg', role: 'group', 'aria-label': App.t('settings.language') }, + I.LANGS.map((l) => h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(st.lang === l), onclick: () => App.setLang(l) }, App.t('settings.lang.' + l))))), + h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.account') })), + st.user ? kv(App.t('settings.username'), st.user.username) : null, + op ? kv(App.t('settings.operator'), op.name) : null, + op ? kv(App.t('settings.as'), I.fmtAs(op.asNumber)) : null, + w ? kv(App.t('settings.world'), App.t('settings.worldInfo', { name: w.name, speed: w.speed, r: w.mapRadius })) : null, + h('button', { class: 'btn danger wide', type: 'button', onclick: confirmLogout }, icon('logout'), App.t('settings.logout'))), + h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.devices') })), + h('p', { class: 'dimmer small', text: App.t('settings.devices.hint') }), devicesEl), + h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.about') })), + h('p', { class: 'dimmer small', text: App.t('settings.about.text') })))); + drawDevices(); + } + + App.registerScreen({ + id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false, + render(container) { box = container; App.on('session', () => { tokens = null; }); }, + onShow() { draw(); loadTokens(); }, + }); +}()); diff --git a/public/js/ui.js b/public/js/ui.js new file mode 100644 index 0000000..dc31d83 --- /dev/null +++ b/public/js/ui.js @@ -0,0 +1,132 @@ +'use strict'; +/* + * Small DOM helpers shared by the shell and the screens (window.UI). Everything is built with createElement and + * textContent: player-controlled strings (POP names, usernames) never go through innerHTML. No inline handlers + * (CSP): events are attached with addEventListener. + */ +(function () { + const SVG_NS = 'http://www.w3.org/2000/svg'; + const XLINK = 'http://www.w3.org/1999/xlink'; + + // h('button', { class: 'btn', onclick: fn, 'aria-label': 'x', dataset: { k: 1 } }, 'text', childNode, [more]) + function h(tag, props, ...kids) { + const el = document.createElement(tag); + if (props) { + for (const k of Object.keys(props)) { + const v = props[k]; + if (v === undefined || v === null || v === false) continue; + if (k === 'class') el.className = v; + else if (k === 'text') el.textContent = v; + else if (k === 'dataset') Object.assign(el.dataset, v); + else if (k === 'style') { for (const s of Object.keys(v)) el.style.setProperty(s, v[s]); } + else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v); + else if (v === true) el.setAttribute(k, ''); + else el.setAttribute(k, String(v)); + } + } + append(el, kids); + return el; + } + + function append(el, kids) { + for (const c of kids) { + if (c === null || c === undefined || c === false) continue; + if (Array.isArray(c)) append(el, c); + else el.appendChild(c instanceof Node ? c : document.createTextNode(String(c))); + } + return el; + } + + function clear(el) { while (el.firstChild) el.removeChild(el.firstChild); return el; } + + // + function icon(name, cls) { + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('class', 'ic' + (cls ? ' ' + cls : '')); + svg.setAttribute('aria-hidden', 'true'); + svg.setAttribute('focusable', 'false'); + const use = document.createElementNS(SVG_NS, 'use'); + use.setAttribute('href', 'icons/sprite.svg#i-' + name); + use.setAttributeNS(XLINK, 'xlink:href', 'icons/sprite.svg#i-' + name); + svg.appendChild(use); + return svg; + } + + // ------------------------------------------------------------------ toasts + function toast(msg, kind) { + const root = document.getElementById('toasts'); + if (!root) return; + const el = h('div', { class: 'toast ' + (kind || 'info'), text: msg }); + root.appendChild(el); + while (root.children.length > 3) root.removeChild(root.firstChild); + setTimeout(() => { el.classList.add('out'); setTimeout(() => el.remove(), 250); }, kind === 'error' ? 4500 : 2600); + } + + // ------------------------------------------------------------------ sheet (bottom sheet on phones, dialog on desktop) + // openSheet({ title, icon, body: Node|Node[], onClose }) -> { el, body, close(), setTitle() } + let current = null; + + function openSheet(opts) { + if (current) current.close(true); + const root = document.getElementById('sheet-root'); + const prevFocus = document.activeElement; + const titleId = 'sheet-title'; + const body = h('div', { class: 'sheet-body' }); + const titleEl = h('h2', { id: titleId, class: 'sheet-title', text: opts.title || '' }); + const closeBtn = h('button', { class: 'icon-btn', type: 'button', 'aria-label': opts.closeLabel || 'Close' }, icon('x')); + const panel = h('div', { class: 'sheet', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId, tabindex: '-1' }, + h('div', { class: 'sheet-grab', 'aria-hidden': 'true' }), + h('div', { class: 'sheet-head' }, opts.icon ? h('span', { class: 'sheet-icon ' + (opts.iconClass || '') }, icon(opts.icon)) : null, titleEl, closeBtn), + body); + const backdrop = h('div', { class: 'backdrop' }); + const wrap = h('div', { class: 'sheet-wrap' }, backdrop, panel); + append(body, [].concat(opts.body || [])); + root.appendChild(wrap); + requestAnimationFrame(() => wrap.classList.add('open')); + + let closed = false; + const api = { + el: panel, body, + setTitle(s) { titleEl.textContent = s; }, + close(silent) { + if (closed) return; + closed = true; + if (current === api) current = null; + document.removeEventListener('keydown', onKey, true); + wrap.classList.remove('open'); + setTimeout(() => wrap.remove(), 200); + if (!silent && prevFocus && prevFocus.focus && document.contains(prevFocus)) { try { prevFocus.focus({ preventScroll: true }); } catch (e) { /* gone */ } } + if (opts.onClose) opts.onClose(); + }, + }; + function onKey(e) { + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); api.close(); return; } + if (e.key !== 'Tab') return; + const f = panel.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'); + if (!f.length) return; + const first = f[0], last = f[f.length - 1]; + if (e.shiftKey && (document.activeElement === first || document.activeElement === panel)) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } + } + document.addEventListener('keydown', onKey, true); + closeBtn.addEventListener('click', () => api.close()); + // a sheet opened on finger lift (map tap) must not be closed by the compatibility click that follows the lift + const openedAt = Date.now(); + backdrop.addEventListener('click', () => { if (Date.now() - openedAt > 400) api.close(); }); + setTimeout(() => { try { panel.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, 0); + current = api; + return api; + } + + function closeSheet() { if (current) current.close(); } + const sheetOpen = () => !!current; + + // Cheap safe storage for per-viewer conveniences (language, last screen). Never for anything that must persist. + const safeStore = { + get(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } }, + set(k, v) { try { window.localStorage.setItem(k, v); } catch (e) { /* private window */ } }, + del(k) { try { window.localStorage.removeItem(k); } catch (e) { /* ignore */ } }, + }; + + window.UI = { h, append, clear, icon, toast, openSheet, closeSheet, sheetOpen, safeStore }; +}()); diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest new file mode 100644 index 0000000..8ae9d09 --- /dev/null +++ b/public/manifest.webmanifest @@ -0,0 +1,17 @@ +{ + "name": "UPSTREAM", + "short_name": "UPSTREAM", + "description": "A persistent strategy game about rival regional network operators. Build POPs, connect the region, outlast the competition.", + "start_url": "./", + "scope": "./", + "display": "standalone", + "orientation": "any", + "background_color": "#070b16", + "theme_color": "#070b16", + "icons": [ + { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" }, + { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" }, + { "src": "icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }, + { "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" } + ] +} diff --git a/server/alliances.js b/server/alliances.js new file mode 100644 index 0000000..c79b7f9 --- /dev/null +++ b/server/alliances.js @@ -0,0 +1,180 @@ +'use strict'; +/* + * Alliance data helpers shared by commands, events, queries and (later) the military stage. + * + * Other modules use the lookups at the bottom: + * relationBetween(db, allianceA, allianceB) -> 'war' | 'neutral' | 'nap' | 'confed' + * operatorRelation(db, opA, opB) -> 'self' | 'same_alliance' | 'war' | 'neutral' | 'nap' | 'confed' + * atWar(db, opA, opB), confederated(db, opA, opB), pactPartners(db, opA, opB) + * + * Membership is kept in alliance_members (role) and operators.alliance_id (quick lookup). addMember / removeMember + * are the only writers of both. + */ +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); +const { GameError } = require('./errors'); + +const S = D.SOCIAL; +const HOUR = D.HOUR_MS; + +// ------------------------------------------------------------------ operators and membership + +// The caller's operator. With worldId: the one in that world; without: their oldest. not_found when there is none. +function operatorOf(db, userId, worldId) { + const row = worldId !== undefined && worldId !== null + ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) + : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId); + if (!row) throw new GameError('not_found', { what: 'operator' }); + return row; +} + +// Best (highest) completed Peering office level over all POPs of an operator. +function peeringLevel(db, operatorId) { + const r = db.get(`SELECT MAX(b.level) AS lvl FROM buildings b JOIN towns t ON t.id = b.town_id + WHERE t.owner_id = ? AND b.type = 'peering_office'`, operatorId); + return r && r.lvl ? r.lvl : 0; +} + +const membership = (db, operatorId) => db.get('SELECT operator_id, alliance_id, role, joined_at FROM alliance_members WHERE operator_id = ?', operatorId) || null; +const getAlliance = (db, id) => db.get('SELECT * FROM alliances WHERE id = ?', id) || null; +const memberCount = (db, allianceId) => db.get('SELECT COUNT(*) AS n FROM alliance_members WHERE alliance_id = ?', allianceId).n; +const leaderOf = (db, allianceId) => db.get("SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND role = 'leader'", allianceId); + +// { id, tag, name } or null, for embedding in other views (/me, /map). +function allianceBrief(db, id) { + if (id === null || id === undefined) return null; + const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id); + return a || null; +} + +// The cap that applies now: the stored one, raised if the current leader's best Peering office would give more. +// Never lowered (a lost building must not kick anyone). Pure read; `refreshCap` persists a raise. +function effectiveCap(db, alliance) { + const lead = leaderOf(db, alliance.id); + const fromLeader = lead ? R.allianceCap(peeringLevel(db, lead.operator_id)) : 0; + return Math.max(alliance.size_cap, fromLeader); +} +function refreshCap(db, alliance) { + const cap = effectiveCap(db, alliance); + if (cap > alliance.size_cap) { db.run('UPDATE alliances SET size_cap = ? WHERE id = ?', cap, alliance.id); alliance.size_cap = cap; } + return cap; +} + +function addMember(db, allianceId, operatorId, role, now) { + db.run('INSERT INTO alliance_members (operator_id, alliance_id, role, joined_at) VALUES (?, ?, ?, ?)', operatorId, allianceId, role, now); + db.run('UPDATE operators SET alliance_id = ? WHERE id = ?', allianceId, operatorId); + // Any other open invites of this operator are moot now. + db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE operator_id = ? AND status = 'pending' AND alliance_id <> ?", now, operatorId, allianceId); +} + +function removeMember(db, operatorId) { + db.run('DELETE FROM alliance_members WHERE operator_id = ?', operatorId); + db.run('UPDATE operators SET alliance_id = NULL WHERE id = ?', operatorId); +} + +// Authorise an alliance action. Returns { op, alliance, member }. not_found: no such alliance (or the caller has no +// operator in its world); forbidden: not a member, or the role may not do `action`. +function requireRole(db, userId, allianceId, action) { + const alliance = getAlliance(db, allianceId); + if (!alliance) throw new GameError('not_found', { what: 'alliance' }); + const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id); + if (!op) throw new GameError('not_found', { what: 'alliance' }); + const member = membership(db, op.id); + if (!member || member.alliance_id !== alliance.id) throw new GameError('forbidden', { need: 'member' }); + if (action && !R.allianceCan(member.role, action)) throw new GameError('forbidden', { need: action, role: member.role }); + return { op, alliance, member }; +} + +// ------------------------------------------------------------------ notifications (rows in `notifications`) + +const userOfOperator = (db, operatorId) => { const r = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return r ? r.user_id : null; }; + +function notifyOperator(ctx, operatorId, type, payload) { + const o = ctx.db.get('SELECT user_id, world_id FROM operators WHERE id = ?', operatorId); + if (o) ctx.scheduler.notify(o.user_id, o.world_id, type, payload); +} + +// All members of an alliance, optionally only some roles, optionally skipping one operator. +function notifyAlliance(ctx, allianceId, type, payload, o) { + o = o || {}; + const rows = ctx.db.all(`SELECT m.operator_id AS oid, m.role AS role, op.user_id AS uid, op.world_id AS wid + FROM alliance_members m JOIN operators op ON op.id = m.operator_id WHERE m.alliance_id = ?`, allianceId); + for (const r of rows) { + if (o.except && r.oid === o.except) continue; + if (o.roles && o.roles.indexOf(r.role) < 0) continue; + ctx.scheduler.notify(r.uid, r.wid, type, payload); + } +} + +// ------------------------------------------------------------------ dissolving + +// Remove an alliance and everything hanging off it. Counterparts of non-neutral relations are told it is neutral now. +function dissolve(ctx, allianceId, reason) { + const { db, now } = ctx; + const a = getAlliance(db, allianceId); + if (!a) return; + const brief = { allianceId: a.id, tag: a.tag, name: a.name }; + notifyAlliance(ctx, a.id, 'alliance_disbanded', Object.assign({ reason }, brief)); + const rels = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id); + for (const r of rels) { + const other = r.a_id === a.id ? r.b_id : r.a_id; + if (r.pending_event) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, r.pending_event); + if (r.state !== 'neutral') notifyAlliance(ctx, other, 'diplomacy_changed', { allianceId: other, otherId: a.id, otherTag: a.tag, from: r.state, to: 'neutral', reason: 'disbanded' }); + } + db.run('DELETE FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id); + db.run('DELETE FROM alliance_proposals WHERE from_id = ? OR to_id = ?', a.id, a.id); + db.run('DELETE FROM alliance_invites WHERE alliance_id = ?', a.id); + db.run('DELETE FROM alliance_notes WHERE alliance_id = ?', a.id); + const ids = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id); + for (const m of ids) removeMember(db, m.operator_id); + db.run('DELETE FROM alliances WHERE id = ?', a.id); +} + +// ------------------------------------------------------------------ relations + +const pairOf = (x, y) => (x < y ? [x, y] : [y, x]); +const getRelation = (db, x, y) => { const [a, b] = pairOf(x, y); return db.get('SELECT * FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b) || null; }; + +// Set the current state of a pair, clearing any pending change. neutral with nothing pending = no row. +function setRelation(db, worldId, x, y, state, now) { + const [a, b] = pairOf(x, y); + if (state === 'neutral') { db.run('DELETE FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b); return; } + db.run(`INSERT INTO alliance_relations (a_id, b_id, world_id, state, since) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (a_id, b_id) DO UPDATE SET state = excluded.state, since = excluded.since, + pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL`, a, b, worldId, state, now); +} + +// Mark every open proposal between two alliances (either direction) as withdrawn: the state moved on under them. +function withdrawProposals(db, x, y, now) { + db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE status = 'pending' AND ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))", now, x, y, y, x); +} + +// ------------------------------------------------------------------ lookups for other modules + +function relationBetween(db, allianceA, allianceB) { + if (!allianceA || !allianceB || allianceA === allianceB) return 'neutral'; + const r = getRelation(db, allianceA, allianceB); + return r ? r.state : 'neutral'; +} + +function operatorRelation(db, opA, opB) { + if (opA === opB) return 'self'; + const rows = db.all('SELECT id, alliance_id FROM operators WHERE id IN (?, ?)', opA, opB); + const a = rows.find((r) => r.id === opA), b = rows.find((r) => r.id === opB); + if (!a || !b || !a.alliance_id || !b.alliance_id) return 'neutral'; + if (a.alliance_id === b.alliance_id) return 'same_alliance'; + return relationBetween(db, a.alliance_id, b.alliance_id); +} + +const atWar = (db, opA, opB) => operatorRelation(db, opA, opB) === 'war'; +// Can reinforce each other and see each other's incoming: same alliance or confederation. +const confederated = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'confed' || r === 'same_alliance'; }; +// May not attack each other: same alliance, NAP or confederation. +const pactPartners = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'nap' || r === 'confed' || r === 'same_alliance'; }; + +module.exports = { + S, HOUR, operatorOf, peeringLevel, membership, getAlliance, memberCount, leaderOf, allianceBrief, effectiveCap, refreshCap, + addMember, removeMember, requireRole, userOfOperator, notifyOperator, notifyAlliance, dissolve, + pairOf, getRelation, setRelation, withdrawProposals, + relationBetween, operatorRelation, atWar, confederated, pactPartners, +}; diff --git a/server/commands/allianceCreate.js b/server/commands/allianceCreate.js new file mode 100644 index 0000000..ef3634b --- /dev/null +++ b/server/commands/allianceCreate.js @@ -0,0 +1,35 @@ +'use strict'; +/* POST /alliances. Found an alliance: needs Peering office >= 1 on one of the founder's POPs; the founder becomes + * leader. Size cap = 10 + 2 * best Peering office level at this moment (rules.allianceCap), stored. */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const { cleanText } = require('../text'); +const A = require('../alliances'); + +const NAME_RE = /^[\p{L}\p{N}][\p{L}\p{N} _.'-]*$/u; + +module.exports = function allianceCreate(ctx, { userId, worldId, name, tag }) { + const { db, now } = ctx; + const S = A.S; + const op = A.operatorOf(db, userId, worldId); + if (A.membership(db, op.id)) throw new GameError('already_in_alliance', { allianceId: A.membership(db, op.id).alliance_id }); + const lvl = A.peeringLevel(db, op.id); + if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel }); + + name = cleanText(name); + tag = cleanText(tag); + const errors = []; + const len = [...name].length; + if (len < S.nameLen[0] || len > S.nameLen[1] || !NAME_RE.test(name)) errors.push({ path: 'name', message: 'must be ' + S.nameLen[0] + '-' + S.nameLen[1] + ' letters, digits, spaces or _ . \' -' }); + if (!/^[A-Za-z0-9]+$/.test(tag) || tag.length < S.tagLen[0] || tag.length > S.tagLen[1]) errors.push({ path: 'tag', message: 'must be ' + S.tagLen[0] + '-' + S.tagLen[1] + ' letters or digits' }); + if (errors.length) throw new GameError('validation_failed', { errors }); + + if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND name = ?', op.world_id, name)) throw new GameError('alliance_name_taken'); + if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND tag = ?', op.world_id, tag)) throw new GameError('alliance_tag_taken'); + + const cap = R.allianceCap(lvl); + const r = db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)', op.world_id, name, tag, cap, op.id, now); + const id = Number(r.lastInsertRowid); + A.addMember(db, id, op.id, 'leader', now); + return { allianceId: id, name, tag, sizeCap: cap, role: 'leader' }; +}; diff --git a/server/commands/allianceDisband.js b/server/commands/allianceDisband.js new file mode 100644 index 0000000..e452f98 --- /dev/null +++ b/server/commands/allianceDisband.js @@ -0,0 +1,9 @@ +'use strict'; +/* POST /alliances/:id/disband. Leader only. Removes members, invites, notes, proposals and relations. */ +const A = require('../alliances'); + +module.exports = function allianceDisband(ctx, { userId, allianceId }) { + const { alliance } = A.requireRole(ctx.db, userId, allianceId, 'disband'); + A.dissolve(ctx, alliance.id, 'disbanded'); + return { changed: true }; +}; diff --git a/server/commands/allianceInvite.js b/server/commands/allianceInvite.js new file mode 100644 index 0000000..2ad2ad5 --- /dev/null +++ b/server/commands/allianceInvite.js @@ -0,0 +1,32 @@ +'use strict'; +/* POST /alliances/:id/invite. Needs the `invite` permission. Target by operator id or name (same world). Idempotent: + * a second invite to the same operator returns the pending one. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceInvite(ctx, { userId, allianceId, operatorId, name }) { + const { db, now } = ctx; + const S = A.S; + const { op, alliance } = A.requireRole(db, userId, allianceId, 'invite'); + const target = operatorId !== undefined + ? db.get('SELECT * FROM operators WHERE id = ? AND world_id = ?', operatorId, alliance.world_id) + : db.get('SELECT * FROM operators WHERE name = ? COLLATE NOCASE AND world_id = ?', name, alliance.world_id); + if (!target) throw new GameError('not_found', { what: 'operator' }); + if (target.id === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you cannot invite yourself' }] }); + const m = A.membership(db, target.id); + if (m) throw new GameError('already_in_alliance', { allianceId: m.alliance_id }); + + db.run("UPDATE alliance_invites SET status = 'expired', answered_at = ? WHERE status = 'pending' AND expires_at <= ?", now, now); + const open = db.get("SELECT id, expires_at FROM alliance_invites WHERE alliance_id = ? AND operator_id = ? AND status = 'pending'", alliance.id, target.id); + if (open) return { inviteId: open.id, operatorId: target.id, expiresAt: open.expires_at, changed: false }; + + if (A.memberCount(db, alliance.id) >= A.refreshCap(db, alliance)) throw new GameError('alliance_full', { cap: alliance.size_cap }); + const pending = db.get("SELECT COUNT(*) AS n FROM alliance_invites WHERE alliance_id = ? AND status = 'pending'", alliance.id).n; + if (pending >= S.maxPendingInvites) throw new GameError('conflict', { what: 'too many pending invites', max: S.maxPendingInvites }); + + const expiresAt = now + Math.round(S.inviteTtlHours * A.HOUR); + const r = db.run('INSERT INTO alliance_invites (alliance_id, operator_id, invited_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?)', alliance.id, target.id, op.id, now, expiresAt); + const inviteId = Number(r.lastInsertRowid); + A.notifyOperator(ctx, target.id, 'alliance_invite', { inviteId, allianceId: alliance.id, tag: alliance.tag, name: alliance.name, by: op.name, expiresAt }); + return { inviteId, operatorId: target.id, expiresAt, changed: true }; +}; diff --git a/server/commands/allianceInviteAnswer.js b/server/commands/allianceInviteAnswer.js new file mode 100644 index 0000000..211e11c --- /dev/null +++ b/server/commands/allianceInviteAnswer.js @@ -0,0 +1,41 @@ +'use strict'; +/* POST /alliance-invites/:id/accept | /decline. Only the invited operator's user. Accepting needs Peering office >= 1, + * no current alliance, and room (cap re-evaluated). Answering an already answered invite the same way is a no-op. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceInviteAnswer(ctx, { userId, inviteId, accept }) { + const { db, now } = ctx; + const S = A.S; + const inv = db.get(`SELECT i.*, o.user_id AS uid, o.name AS oname FROM alliance_invites i JOIN operators o ON o.id = i.operator_id WHERE i.id = ?`, inviteId); + if (!inv || inv.uid !== userId) throw new GameError('not_found', { what: 'invite' }); + + if (inv.status !== 'pending') { + if ((accept && inv.status === 'accepted') || (!accept && inv.status === 'declined')) return { changed: false, allianceId: inv.alliance_id }; + throw new GameError(inv.status === 'expired' ? 'invite_expired' : 'conflict', { what: 'invite is ' + inv.status }); + } + if (inv.expires_at <= now) { + // The refusal rolls this transaction back; the invite is simply treated as expired whenever it is looked at. + throw new GameError('invite_expired', { expiresAt: inv.expires_at }); + } + const alliance = A.getAlliance(db, inv.alliance_id); + if (!alliance) throw new GameError('not_found', { what: 'alliance' }); + + if (!accept) { + db.run("UPDATE alliance_invites SET status = 'declined', answered_at = ? WHERE id = ?", now, inv.id); + A.notifyOperator(ctx, inv.invited_by, 'alliance_invite_declined', { inviteId: inv.id, allianceId: alliance.id, by: inv.oname }); + return { changed: true, allianceId: alliance.id }; + } + + const cur = A.membership(db, inv.operator_id); + if (cur) throw new GameError('already_in_alliance', { allianceId: cur.alliance_id }); + const lvl = A.peeringLevel(db, inv.operator_id); + if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel }); + const cap = A.refreshCap(db, alliance); + if (A.memberCount(db, alliance.id) >= cap) throw new GameError('alliance_full', { cap }); + + A.addMember(db, alliance.id, inv.operator_id, 'member', now); + db.run("UPDATE alliance_invites SET status = 'accepted', answered_at = ? WHERE id = ?", now, inv.id); + A.notifyAlliance(ctx, alliance.id, 'alliance_member_joined', { allianceId: alliance.id, operatorId: inv.operator_id, name: inv.oname }, { except: inv.operator_id }); + return { changed: true, allianceId: alliance.id, role: 'member' }; +}; diff --git a/server/commands/allianceInviteCancel.js b/server/commands/allianceInviteCancel.js new file mode 100644 index 0000000..2fa8518 --- /dev/null +++ b/server/commands/allianceInviteCancel.js @@ -0,0 +1,15 @@ +'use strict'; +/* DELETE /alliances/:id/invites/:inviteId. Needs `cancelInvite`. Idempotent for an already cancelled invite. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceInviteCancel(ctx, { userId, allianceId, inviteId }) { + const { db, now } = ctx; + const { alliance } = A.requireRole(db, userId, allianceId, 'cancelInvite'); + const inv = db.get('SELECT id, status FROM alliance_invites WHERE id = ? AND alliance_id = ?', inviteId, alliance.id); + if (!inv) throw new GameError('not_found', { what: 'invite' }); + if (inv.status === 'cancelled') return { changed: false }; + if (inv.status !== 'pending') throw new GameError('conflict', { what: 'invite is ' + inv.status }); + db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE id = ?", now, inv.id); + return { changed: true }; +}; diff --git a/server/commands/allianceKick.js b/server/commands/allianceKick.js new file mode 100644 index 0000000..03cb958 --- /dev/null +++ b/server/commands/allianceKick.js @@ -0,0 +1,19 @@ +'use strict'; +/* POST /alliances/:id/kick. Needs `kick` and the actor must outrank the target. Target not in the alliance: no-op. */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceKick(ctx, { userId, allianceId, operatorId }) { + const { db } = ctx; + const { op, alliance, member } = A.requireRole(db, userId, allianceId, 'kick'); + if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'use leave to leave an alliance' }] }); + const t = A.membership(db, operatorId); + if (!t || t.alliance_id !== alliance.id) return { changed: false }; + if (!R.outranks(member.role, t.role)) throw new GameError('forbidden', { need: 'outrank', role: member.role, targetRole: t.role }); + const target = db.get('SELECT id, name FROM operators WHERE id = ?', operatorId); + A.removeMember(db, operatorId); + A.notifyOperator(ctx, operatorId, 'alliance_kicked', { allianceId: alliance.id, tag: alliance.tag, name: alliance.name }); + A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId, name: target.name, kicked: true }); + return { changed: true }; +}; diff --git a/server/commands/allianceLeave.js b/server/commands/allianceLeave.js new file mode 100644 index 0000000..c9c4565 --- /dev/null +++ b/server/commands/allianceLeave.js @@ -0,0 +1,23 @@ +'use strict'; +/* POST /alliances/:id/leave. The leader cannot leave while others remain (transfer first); a leader who is alone + * dissolves the alliance. Leaving an alliance you are not in is a no-op. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceLeave(ctx, { userId, allianceId }) { + const { db } = ctx; + const alliance = A.getAlliance(db, allianceId); + if (!alliance) throw new GameError('not_found', { what: 'alliance' }); + const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id); + if (!op) throw new GameError('not_found', { what: 'alliance' }); + const m = A.membership(db, op.id); + if (!m || m.alliance_id !== alliance.id) return { changed: false }; + if (m.role === 'leader') { + if (A.memberCount(db, alliance.id) > 1) throw new GameError('leader_must_transfer'); + A.dissolve(ctx, alliance.id, 'last_member_left'); + return { changed: true, disbanded: true }; + } + A.removeMember(db, op.id); + A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId: op.id, name: op.name, kicked: false }); + return { changed: true, disbanded: false }; +}; diff --git a/server/commands/allianceNote.js b/server/commands/allianceNote.js new file mode 100644 index 0000000..56911b2 --- /dev/null +++ b/server/commands/allianceNote.js @@ -0,0 +1,41 @@ +'use strict'; +/* Pinned notes of an alliance. Three commands, one file: allianceNoteAdd / allianceNoteEdit / allianceNoteDelete + * (registered separately in commands/index.js). Needs `editNotes`. */ +const { GameError } = require('../errors'); +const { cleanText } = require('../text'); +const A = require('../alliances'); + +function text(raw) { + const t = cleanText(raw, { multiline: true }); + if (!t || [...t].length > A.S.noteMax) throw new GameError('validation_failed', { errors: [{ path: 'text', message: 'must be 1-' + A.S.noteMax + ' characters of plain text' }] }); + return t; +} + +const view = (n) => ({ id: n.id, authorId: n.author_id, text: n.text, createdAt: n.created_at, updatedAt: n.updated_at }); + +function allianceNoteAdd(ctx, { userId, allianceId, text: raw }) { + const { db, now } = ctx; + const { op, alliance } = A.requireRole(db, userId, allianceId, 'editNotes'); + const t = text(raw); + if (db.get('SELECT COUNT(*) AS n FROM alliance_notes WHERE alliance_id = ?', alliance.id).n >= A.S.maxNotes) throw new GameError('notes_full', { max: A.S.maxNotes }); + const r = db.run('INSERT INTO alliance_notes (alliance_id, author_id, text, created_at, updated_at) VALUES (?, ?, ?, ?, ?)', alliance.id, op.id, t, now, now); + return { note: view(db.get('SELECT * FROM alliance_notes WHERE id = ?', Number(r.lastInsertRowid))) }; +} + +function allianceNoteEdit(ctx, { userId, allianceId, noteId, text: raw }) { + const { db, now } = ctx; + const { alliance } = A.requireRole(db, userId, allianceId, 'editNotes'); + const t = text(raw); + const r = db.run('UPDATE alliance_notes SET text = ?, updated_at = ? WHERE id = ? AND alliance_id = ?', t, now, noteId, alliance.id); + if (!r.changes) throw new GameError('not_found', { what: 'note' }); + return { note: view(db.get('SELECT * FROM alliance_notes WHERE id = ?', noteId)) }; +} + +function allianceNoteDelete(ctx, { userId, allianceId, noteId }) { + const { db } = ctx; + const { alliance } = A.requireRole(db, userId, allianceId, 'editNotes'); + const r = db.run('DELETE FROM alliance_notes WHERE id = ? AND alliance_id = ?', noteId, alliance.id); + return { changed: r.changes > 0 }; +} + +module.exports = { allianceNoteAdd, allianceNoteEdit, allianceNoteDelete, noteView: view }; diff --git a/server/commands/allianceRole.js b/server/commands/allianceRole.js new file mode 100644 index 0000000..9e7c401 --- /dev/null +++ b/server/commands/allianceRole.js @@ -0,0 +1,17 @@ +'use strict'; +/* POST /alliances/:id/role. Needs `setRole` (leader). Roles diplomat | officer | member; use transfer for leadership. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceRole(ctx, { userId, allianceId, operatorId, role }) { + const { db } = ctx; + const { op, alliance } = A.requireRole(db, userId, allianceId, 'setRole'); + if (A.S.roles.indexOf(role) < 0 || role === 'leader') throw new GameError('validation_failed', { errors: [{ path: 'role', message: 'must be diplomat, officer or member' }] }); + if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'the leader cannot change their own role; transfer leadership' }] }); + const t = A.membership(db, operatorId); + if (!t || t.alliance_id !== alliance.id) throw new GameError('not_found', { what: 'member' }); + if (t.role === role) return { changed: false, role }; + db.run('UPDATE alliance_members SET role = ? WHERE operator_id = ?', role, operatorId); + A.notifyOperator(ctx, operatorId, 'alliance_role', { allianceId: alliance.id, tag: alliance.tag, from: t.role, role }); + return { changed: true, role }; +}; diff --git a/server/commands/allianceTransfer.js b/server/commands/allianceTransfer.js new file mode 100644 index 0000000..804f80c --- /dev/null +++ b/server/commands/allianceTransfer.js @@ -0,0 +1,18 @@ +'use strict'; +/* POST /alliances/:id/transfer. The leader hands leadership to another member and becomes an officer. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function allianceTransfer(ctx, { userId, allianceId, operatorId }) { + const { db } = ctx; + const { op, alliance } = A.requireRole(db, userId, allianceId, 'transfer'); + if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you are already the leader' }] }); + const t = A.membership(db, operatorId); + if (!t || t.alliance_id !== alliance.id) throw new GameError('not_found', { what: 'member' }); + db.run("UPDATE alliance_members SET role = 'officer' WHERE operator_id = ?", op.id); // before promoting: one leader at a time + db.run("UPDATE alliance_members SET role = 'leader' WHERE operator_id = ?", operatorId); + A.refreshCap(db, alliance); + const target = db.get('SELECT name FROM operators WHERE id = ?', operatorId); + A.notifyAlliance(ctx, alliance.id, 'alliance_leader', { allianceId: alliance.id, operatorId, name: target.name, from: op.name }); + return { changed: true, leaderId: operatorId }; +}; diff --git a/server/commands/diploAnswer.js b/server/commands/diploAnswer.js new file mode 100644 index 0000000..4368516 --- /dev/null +++ b/server/commands/diploAnswer.js @@ -0,0 +1,35 @@ +'use strict'; +/* POST /diplomacy/proposals/:proposalId/accept | /decline. Needs `diplomacy` in the receiving alliance. The move is + * validated again against the CURRENT relation (it may have changed since the proposal was made). */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const A = require('../alliances'); +const Dip = require('../diplomacy'); + +module.exports = function diploAnswer(ctx, { userId, proposalId, accept }) { + const { db, now } = ctx; + const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId); + if (!p) throw new GameError('not_found', { what: 'proposal' }); + const { op, alliance } = A.requireRole(db, userId, p.to_id, 'diplomacy'); // forbidden/not_found for outsiders + if (p.status !== 'pending') { + if ((accept && p.status === 'accepted') || (!accept && p.status === 'declined')) return { changed: false }; + throw new GameError(p.status === 'expired' ? 'proposal_expired' : 'conflict', { what: 'proposal is ' + p.status }); + } + if (p.expires_at <= now) throw new GameError('proposal_expired', { expiresAt: p.expires_at }); + const proposer = A.getAlliance(db, p.from_id); + if (!proposer) throw new GameError('not_found', { what: 'alliance' }); + + if (!accept) { + db.run("UPDATE alliance_proposals SET status = 'declined', answered_at = ? WHERE id = ?", now, p.id); + A.notifyAlliance(ctx, proposer.id, 'diplomacy_declined', { proposalId: p.id, by: Dip.brief(alliance), state: p.state }, { roles: ['leader', 'diplomat'] }); + return { changed: true }; + } + + const rel = A.getRelation(db, alliance.id, proposer.id); + const from = rel ? rel.state : 'neutral'; + if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at }); + if (R.diplomacyMove(from, p.state) !== 'proposal') throw new GameError('diplomacy_invalid', { from, to: p.state }); + db.run("UPDATE alliance_proposals SET status = 'accepted', answered_at = ? WHERE id = ?", now, p.id); + Dip.applyChange(ctx, alliance, proposer, p.state, { by: op.name, proposalId: p.id }); + return { changed: true, from, state: p.state }; +}; diff --git a/server/commands/diploPropose.js b/server/commands/diploPropose.js new file mode 100644 index 0000000..42c82b4 --- /dev/null +++ b/server/commands/diploPropose.js @@ -0,0 +1,54 @@ +'use strict'; +/* POST /alliances/:id/diplomacy { targetId, state }. Needs `diplomacy`. What happens depends on the move + * (rules.diplomacyMove): 'immediate' applies at once (declaring war from neutral), 'delayed' schedules a cancel that + * takes 24 h / world speed (a `diploChange` event), 'proposal' asks the other alliance to accept. */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const { loadWorld } = require('../state'); +const A = require('../alliances'); +const Dip = require('../diplomacy'); + +module.exports = function diploPropose(ctx, { userId, allianceId, targetId, state }) { + const { db, now, scheduler } = ctx; + const { op, alliance } = A.requireRole(db, userId, allianceId, 'diplomacy'); + if (targetId === alliance.id) throw new GameError('validation_failed', { errors: [{ path: 'targetId', message: 'cannot be your own alliance' }] }); + const other = A.getAlliance(db, targetId); + if (!other || other.world_id !== alliance.world_id) throw new GameError('not_found', { what: 'alliance' }); + + const rel = A.getRelation(db, alliance.id, other.id); + const from = rel ? rel.state : 'neutral'; + if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at, startedBy: rel.pending_by }); + const move = R.diplomacyMove(from, state); + if (!move) throw new GameError('diplomacy_invalid', { from, to: state }); + + if (move === 'immediate') { + Dip.applyChange(ctx, alliance, other, state, { by: op.name }); + return { result: 'applied', from, state }; + } + + if (move === 'delayed') { + const world = loadWorld(db, alliance.world_id); + const dueAt = now + R.pactCancelMs(world.speed); + A.withdrawProposals(db, alliance.id, other.id, now); + const eventId = scheduler.enqueue({ worldId: alliance.world_id, dueAt, type: 'diploChange', payload: { a: alliance.id, b: other.id, to: state, by: alliance.id } }); + const [x, y] = A.pairOf(alliance.id, other.id); + db.run('UPDATE alliance_relations SET pending_to = ?, pending_at = ?, pending_by = ?, pending_event = ? WHERE a_id = ? AND b_id = ?', state, dueAt, alliance.id, eventId, x, y); + for (const [me, o2] of [[alliance, other], [other, alliance]]) { + A.notifyAlliance(ctx, me.id, 'diplomacy_cancel_pending', { allianceId: me.id, other: Dip.brief(o2), from, to: state, effectiveAt: dueAt, startedBy: alliance.id }); + } + return { result: 'scheduled', from, state, effectiveAt: dueAt, eventId }; + } + + // proposal + const reverse = db.get("SELECT id, state AS st, expires_at FROM alliance_proposals WHERE from_id = ? AND to_id = ? AND status = 'pending'", other.id, alliance.id); + if (reverse && reverse.expires_at > now && reverse.st === state) throw new GameError('proposal_exists', { proposalId: reverse.id }); + db.run("UPDATE alliance_proposals SET status = 'expired', answered_at = ? WHERE status = 'pending' AND expires_at <= ?", now, now); + // a new proposal from the same side replaces the old one + db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE from_id = ? AND to_id = ? AND status = 'pending'", now, alliance.id, other.id); + const expiresAt = now + Math.round(A.S.proposalTtlHours * A.HOUR); + const r = db.run('INSERT INTO alliance_proposals (world_id, from_id, to_id, state, proposed_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)', + alliance.world_id, alliance.id, other.id, state, op.id, now, expiresAt); + const proposalId = Number(r.lastInsertRowid); + A.notifyAlliance(ctx, other.id, 'diplomacy_proposal', { proposalId, from: Dip.brief(alliance), state, expiresAt }, { roles: ['leader', 'diplomat'] }); + return { result: 'proposed', from, state, proposalId, expiresAt }; +}; diff --git a/server/commands/diploRevoke.js b/server/commands/diploRevoke.js new file mode 100644 index 0000000..cf7a05f --- /dev/null +++ b/server/commands/diploRevoke.js @@ -0,0 +1,22 @@ +'use strict'; +/* DELETE /alliances/:id/diplomacy/:otherId/pending. The alliance that started a delayed change (cancelling a pact, + * declaring war out of a pact) may take it back before it takes effect. Nothing pending: no-op. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); +const Dip = require('../diplomacy'); + +module.exports = function diploRevoke(ctx, { userId, allianceId, otherId }) { + const { db, now } = ctx; + const { alliance } = A.requireRole(db, userId, allianceId, 'diplomacy'); + const other = A.getAlliance(db, otherId); + if (!other) throw new GameError('not_found', { what: 'alliance' }); + const rel = A.getRelation(db, alliance.id, other.id); + if (!rel || !rel.pending_to) return { changed: false }; + if (rel.pending_by !== alliance.id) throw new GameError('forbidden', { need: 'pending change started by your alliance' }); + db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, rel.pending_event); + db.run('UPDATE alliance_relations SET pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL WHERE a_id = ? AND b_id = ?', rel.a_id, rel.b_id); + for (const [me, o2] of [[alliance, other], [other, alliance]]) { + A.notifyAlliance(ctx, me.id, 'diplomacy_cancel_revoked', { allianceId: me.id, other: Dip.brief(o2), state: rel.state }); + } + return { changed: true, state: rel.state }; +}; diff --git a/server/commands/diploWithdraw.js b/server/commands/diploWithdraw.js new file mode 100644 index 0000000..35e5778 --- /dev/null +++ b/server/commands/diploWithdraw.js @@ -0,0 +1,15 @@ +'use strict'; +/* DELETE /diplomacy/proposals/:proposalId. The proposing alliance withdraws it. Needs `diplomacy`. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +module.exports = function diploWithdraw(ctx, { userId, proposalId }) { + const { db, now } = ctx; + const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId); + if (!p) throw new GameError('not_found', { what: 'proposal' }); + A.requireRole(db, userId, p.from_id, 'diplomacy'); + if (p.status === 'withdrawn') return { changed: false }; + if (p.status !== 'pending') throw new GameError('conflict', { what: 'proposal is ' + p.status }); + db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE id = ?", now, p.id); + return { changed: true }; +}; diff --git a/server/commands/index.js b/server/commands/index.js index c408741..f017bd4 100644 --- a/server/commands/index.js +++ b/server/commands/index.js @@ -5,11 +5,41 @@ * scheduler timer because the command may have enqueued events. */ const handlers = { + // stage 3/4: military and expansion + train: require('./train'), + research: require('./research'), + sendMovement: require('./sendMovement'), + sendTransport: require('./sendTransport'), + recallMovement: require('./recallMovement'), + withdrawStationed: require('./withdrawStationed'), + markReportRead: require('./markReportRead'), signup: require('./signup'), joinWorld: require('./joinWorld'), build: require('./build'), cancelBuild: require('./cancelBuild'), renameTown: require('./renameTown'), + // stage 5: alliances, diplomacy, messages + allianceCreate: require('./allianceCreate'), + allianceInvite: require('./allianceInvite'), + allianceInviteCancel: require('./allianceInviteCancel'), + allianceInviteAnswer: require('./allianceInviteAnswer'), + allianceLeave: require('./allianceLeave'), + allianceKick: require('./allianceKick'), + allianceRole: require('./allianceRole'), + allianceTransfer: require('./allianceTransfer'), + allianceDisband: require('./allianceDisband'), + allianceNoteAdd: require('./allianceNote').allianceNoteAdd, + allianceNoteEdit: require('./allianceNote').allianceNoteEdit, + allianceNoteDelete: require('./allianceNote').allianceNoteDelete, + diploPropose: require('./diploPropose'), + diploAnswer: require('./diploAnswer'), + diploWithdraw: require('./diploWithdraw'), + diploRevoke: require('./diploRevoke'), + messageSend: require('./messageSend'), + messageRead: require('./messageRead'), + messageDelete: require('./messageDelete'), + messageBlock: require('./messageBlock').messageBlock, + messageUnblock: require('./messageBlock').messageUnblock, }; function createCommands({ db, clock, scheduler }) { diff --git a/server/commands/markReportRead.js b/server/commands/markReportRead.js new file mode 100644 index 0000000..adead23 --- /dev/null +++ b/server/commands/markReportRead.js @@ -0,0 +1,14 @@ +'use strict'; +/* POST /reports/:id/read (and /reports/read-all). Per-user read flag; the report itself is shared. */ +const { GameError } = require('../errors'); + +module.exports = function markReportRead(ctx, { userId, reportId, all }) { + const { db, now } = ctx; + if (all) { + const r = db.run('UPDATE report_recipients SET read_at = ? WHERE user_id = ? AND read_at IS NULL', now, userId); + return { marked: Number(r.changes) }; + } + const r = db.run('UPDATE report_recipients SET read_at = COALESCE(read_at, ?) WHERE report_id = ? AND user_id = ?', now, reportId, userId); + if (!r.changes) throw new GameError('not_found', { what: 'report' }); + return { marked: 1 }; +}; diff --git a/server/commands/messageBlock.js b/server/commands/messageBlock.js new file mode 100644 index 0000000..be63f27 --- /dev/null +++ b/server/commands/messageBlock.js @@ -0,0 +1,31 @@ +'use strict'; +/* POST /messages/blocks { operatorId } and DELETE /messages/blocks/:operatorId. Blocked senders' messages are not + * delivered (the sender is not told). Both idempotent. Registered as messageBlock and messageUnblock. */ +const { GameError } = require('../errors'); +const A = require('../alliances'); + +function resolve(db, userId, operatorId) { + const target = db.get('SELECT * FROM operators WHERE id = ?', operatorId); + if (!target) throw new GameError('not_found', { what: 'operator' }); + const me = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, target.world_id); + if (!me) throw new GameError('not_found', { what: 'operator' }); + if (me.id === target.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you cannot block yourself' }] }); + return { me, target }; +} + +function messageBlock(ctx, { userId, operatorId }) { + const { db, now } = ctx; + const { me, target } = resolve(db, userId, operatorId); + if (db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', me.id, target.id)) return { changed: false }; + if (db.get('SELECT COUNT(*) AS n FROM message_blocks WHERE operator_id = ?', me.id).n >= A.S.maxBlocks) throw new GameError('conflict', { what: 'block list full', max: A.S.maxBlocks }); + db.run('INSERT INTO message_blocks (operator_id, blocked_id, created_at) VALUES (?, ?, ?)', me.id, target.id, now); + return { changed: true }; +} + +function messageUnblock(ctx, { userId, operatorId }) { + const { db } = ctx; + const { me, target } = resolve(db, userId, operatorId); + return { changed: db.run('DELETE FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', me.id, target.id).changes > 0 }; +} + +module.exports = { messageBlock, messageUnblock }; diff --git a/server/commands/messageDelete.js b/server/commands/messageDelete.js new file mode 100644 index 0000000..75f5100 --- /dev/null +++ b/server/commands/messageDelete.js @@ -0,0 +1,24 @@ +'use strict'; +/* DELETE /messages/:id. Removes the caller's own copy only (sender copy or recipient copy). When nobody has a copy + * left the row is purged. Deleting an already deleted copy is a no-op; a message you never saw is not_found. */ +const { GameError } = require('../errors'); + +module.exports = function messageDelete(ctx, { userId, messageId }) { + const { db, now } = ctx; + const m = db.get('SELECT m.id, m.sender_id, m.sender_deleted_at, o.user_id AS suid FROM messages m JOIN operators o ON o.id = m.sender_id WHERE m.id = ?', messageId); + if (!m) throw new GameError('not_found', { what: 'message' }); + let changed = false; + if (m.suid === userId) { + changed = !m.sender_deleted_at; + if (changed) db.run('UPDATE messages SET sender_deleted_at = ? WHERE id = ?', now, m.id); + } else { + const r = db.get(`SELECT r.operator_id, r.deleted_at FROM message_recipients r JOIN operators o ON o.id = r.operator_id WHERE r.message_id = ? AND o.user_id = ?`, m.id, userId); + if (!r) throw new GameError('not_found', { what: 'message' }); + changed = !r.deleted_at; + if (changed) db.run('UPDATE message_recipients SET deleted_at = ? WHERE message_id = ? AND operator_id = ?', now, m.id, r.operator_id); + } + const left = db.get(`SELECT (SELECT sender_deleted_at IS NULL FROM messages WHERE id = ?) AS s, + (SELECT COUNT(*) FROM message_recipients WHERE message_id = ? AND deleted_at IS NULL) AS r`, m.id, m.id); + if (!left.s && !left.r) { db.run('DELETE FROM message_recipients WHERE message_id = ?', m.id); db.run('DELETE FROM messages WHERE id = ?', m.id); } + return { changed }; +}; diff --git a/server/commands/messageRead.js b/server/commands/messageRead.js new file mode 100644 index 0000000..8e45919 --- /dev/null +++ b/server/commands/messageRead.js @@ -0,0 +1,12 @@ +'use strict'; +/* POST /messages/read { ids } or { all: true }: mark received messages read. Already-read ones are left alone. */ +module.exports = function messageRead(ctx, { userId, ids, all, worldId }) { + const { db, now } = ctx; + const ops = db.all(worldId !== undefined ? 'SELECT id FROM operators WHERE user_id = ? AND world_id = ?' : 'SELECT id FROM operators WHERE user_id = ?', userId, ...(worldId !== undefined ? [worldId] : [])); + let changed = 0; + for (const o of ops) { + if (all) changed += db.run('UPDATE message_recipients SET read_at = ? WHERE operator_id = ? AND read_at IS NULL AND deleted_at IS NULL', now, o.id).changes; + else for (const id of ids || []) changed += db.run('UPDATE message_recipients SET read_at = ? WHERE operator_id = ? AND message_id = ? AND read_at IS NULL AND deleted_at IS NULL', now, o.id, id).changes; + } + return { changed: Number(changed) }; +}; diff --git a/server/commands/messageSend.js b/server/commands/messageSend.js new file mode 100644 index 0000000..0b94d02 --- /dev/null +++ b/server/commands/messageSend.js @@ -0,0 +1,72 @@ +'use strict'; +/* POST /messages. Player-to-player (toOperatorId | toName) or broadcast to the sender's alliance (toAlliance: true). + * Plain text, control/bidi characters stripped, at most SOCIAL.messageMax characters, rate-limited per sender by + * counting their recent rows in `messages` (DB-backed: survives restarts, follows the injected clock). + * A recipient who blocked the sender gets no row at all; the sender is not told. */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const { cleanText } = require('../text'); +const A = require('../alliances'); + +const MIN = 60 * 1000; + +function limit(db, senderId, kind, now) { + const L = A.S.messageLimits; + const windows = kind === 'dm' ? [[10 * MIN, L.dm10min], [60 * MIN, L.dmHour]] : [[60 * MIN, L.broadcastHour]]; + for (const [ms, max] of windows) { + const r = db.get('SELECT COUNT(*) AS n, MIN(created_at) AS first FROM messages WHERE sender_id = ? AND kind = ? AND created_at > ?', senderId, kind, now - ms); + if (r.n >= max) throw new GameError('rate_limited', { retryAfter: Math.max(1, Math.ceil((r.first + ms - now) / 1000)), limit: max, windowMs: ms, scope: 'messages' }); + } +} + +module.exports = function messageSend(ctx, { userId, worldId, toOperatorId, toName, toAlliance, text }) { + const { db, now } = ctx; + const S = A.S; + const body = cleanText(text, { multiline: true }); + if (!body || [...body].length > S.messageMax) throw new GameError('validation_failed', { errors: [{ path: 'text', message: 'must be 1-' + S.messageMax + ' characters of plain text' }] }); + const targets = [toOperatorId !== undefined, toName !== undefined, !!toAlliance].filter(Boolean).length; + if (targets !== 1) throw new GameError('validation_failed', { errors: [{ path: 'toOperatorId', message: 'give exactly one of toOperatorId, toName, toAlliance' }] }); + + if (toAlliance) { + const me = A.operatorOf(db, userId, worldId); + const m = A.membership(db, me.id); + if (!m) throw new GameError('not_in_alliance'); + if (!R.allianceCan(m.role, 'broadcast')) throw new GameError('forbidden', { need: 'broadcast', role: m.role }); + limit(db, me.id, 'alliance', now); + const alliance = A.getAlliance(db, m.alliance_id); + const r = db.run('INSERT INTO messages (world_id, sender_id, kind, alliance_id, alliance_tag, thread, body, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + me.world_id, me.id, 'alliance', alliance.id, alliance.tag, 'alliance:' + alliance.id, body, now); + const id = Number(r.lastInsertRowid); + const members = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND operator_id <> ?', alliance.id, me.id); + let delivered = 0; + for (const mm of members) { + if (db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', mm.operator_id, me.id)) continue; + db.run('INSERT INTO message_recipients (message_id, operator_id) VALUES (?, ?)', id, mm.operator_id); + delivered++; + A.notifyOperator(ctx, mm.operator_id, 'alliance_message', { messageId: id, allianceId: alliance.id, tag: alliance.tag, from: me.name }); + } + return { messageId: id, kind: 'alliance', recipients: delivered, createdAt: now }; + } + + let target; + if (toOperatorId !== undefined) target = db.get('SELECT * FROM operators WHERE id = ?', toOperatorId); + else { + const mine = A.operatorOf(db, userId, worldId); // the world the name is looked up in + target = db.get('SELECT * FROM operators WHERE name = ? COLLATE NOCASE AND world_id = ?', toName, mine.world_id); + } + if (!target) throw new GameError('not_found', { what: 'operator' }); + const me = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, target.world_id); + if (!me) throw new GameError('not_found', { what: 'operator' }); + if (me.id === target.id) throw new GameError('validation_failed', { errors: [{ path: 'toOperatorId', message: 'you cannot message yourself' }] }); + limit(db, me.id, 'dm', now); + const lo = Math.min(me.id, target.id), hi = Math.max(me.id, target.id); + const r = db.run('INSERT INTO messages (world_id, sender_id, kind, to_id, thread, body, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)', + me.world_id, me.id, 'dm', target.id, 'dm:' + lo + ':' + hi, body, now); + const id = Number(r.lastInsertRowid); + const blocked = !!db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', target.id, me.id); + if (!blocked) { + db.run('INSERT INTO message_recipients (message_id, operator_id) VALUES (?, ?)', id, target.id); + A.notifyOperator(ctx, target.id, 'message', { messageId: id, from: { operatorId: me.id, name: me.name } }); + } + return { messageId: id, kind: 'dm', recipients: blocked ? 0 : 1, createdAt: now }; +}; diff --git a/server/commands/recallMovement.js b/server/commands/recallMovement.js new file mode 100644 index 0000000..bc8b4ca --- /dev/null +++ b/server/commands/recallMovement.js @@ -0,0 +1,30 @@ +'use strict'; +/* POST /movements/:id/recall. Within the first 90 s (MILITARY.recallWindowMs) an outbound movement can turn around: + * its arrive event is cancelled and a return leg takes the same units and cargo home in as long as they were out. */ +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const ctxOf = require('../military/ctx'); +const U = require('../military/units'); +const M = require('../military/movements'); + +module.exports = function recallMovement(ctx0, { userId, movementId }) { + const ctx = ctxOf(ctx0); + const { db, now } = ctx; + const mv = M.getMovement(db, movementId); + const op = mv && db.get('SELECT id FROM operators WHERE id = ? AND user_id = ?', mv.ownerId, userId); + if (!mv || !op) throw new GameError('not_found', { what: 'movement' }); + if (mv.status !== 'out' || mv.type === 'return') throw new GameError('conflict', { what: 'movement cannot be recalled', status: mv.status, type: mv.type }); + if (now - mv.departAt > D.MILITARY.recallWindowMs) throw new GameError('recall_expired', { departAt: mv.departAt, windowMs: D.MILITARY.recallWindowMs }); + const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null; + const dest = U.homeTownFor(db, mv.ownerId, origin && origin.owner_id === mv.ownerId ? origin.id : null); + if (!dest) throw new GameError('conflict', { what: 'no POP to return to' }); + db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, mv.eventId); + db.run("UPDATE movements SET status = 'recalled' WHERE id = ?", mv.id); + const elapsed = Math.max(1000, now - mv.departAt); + const f = Math.min(1, (now - mv.departAt) / Math.max(1, mv.arriveAt - mv.departAt)); + const at = { x: Math.round(mv.from.x + (mv.to.x - mv.from.x) * f), y: Math.round(mv.from.y + (mv.to.y - mv.from.y) * f) }; + const extra = Object.assign({}, mv.extra, { recalled: true }); + if (mv.type === 'transport') extra.link = 1; + const ret = M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at, to: dest, units: mv.units, cargo: mv.cargo, arriveAt: now + elapsed, parentId: mv.id, extra }); + return { recalled: mv.id, returnMovementId: ret.id, arriveAt: ret.arriveAt }; +}; diff --git a/server/commands/research.js b/server/commands/research.js new file mode 100644 index 0000000..801a43f --- /dev/null +++ b/server/commands/research.js @@ -0,0 +1,26 @@ +'use strict'; +/* POST /towns/:id/research. One research at a time per POP (a `researchDone` event). +5% attack or defence per level + * of one unit type; level n needs a Research lab of level n + RESEARCH.labOffset. Incumbent sites speed it up. */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const { settle, spend } = require('../state'); +const { ownedTown } = require('./build'); +const U = require('../military/units'); + +module.exports = function research(ctx, { userId, townId, unit, stat }) { + const { db, now, scheduler } = ctx; + const town = ownedTown(db, userId, townId); + if (!R.unitDef(unit)) throw new GameError('unknown_unit', { unit }); + settle(db, town, now); + const busy = !!db.get("SELECT 1 AS x FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' LIMIT 1", town.id); + const current = U.researchLevels(db, town.id)[R.researchKey(unit, stat)] || 0; + const plan = R.researchPlan(town, unit, stat, current, busy, now, U.researchBonusOf(db, town.ownerId)); + if (!plan.ok) throw new GameError(plan.code, { unit, stat, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing }); + spend(db, town, plan.cost); + const dueAt = now + plan.durationMs; + const eventId = scheduler.enqueue({ + worldId: town.worldId, townId: town.id, type: 'researchDone', dueAt, + payload: { unit, stat, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId }, + }); + return { eventId, unit, stat, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost }; +}; diff --git a/server/commands/sendMovement.js b/server/commands/sendMovement.js new file mode 100644 index 0000000..e2d5d22 --- /dev/null +++ b/server/commands/sendMovement.js @@ -0,0 +1,120 @@ +'use strict'; +/* + * POST /movements. Send units from one of your POPs: scan, raid, attack, takeover, reinforce, settle. (Resources go + * through sendTransport.) Validates everything against the rules, takes the units out of the POP and enqueues the + * `arrive` event. Nothing resolves now: combat happens at arrival, in the event queue, in order. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { settle, loadWorld } = require('../state'); +const { ownedTown } = require('./build'); +const ctxOf = require('../military/ctx'); +const U = require('../military/units'); +const M = require('../military/movements'); +const P = require('../military/power'); + +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) { + 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); + if (!town) throw new GameError('not_found', { what: 'town' }); + x = town.x; y = town.y; + } else if (Number.isInteger(args.x) && Number.isInteger(args.y)) { + x = args.x; y = args.y; + town = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y) || null; + } 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); + if (tile.type === 'void') throw new GameError('invalid_target', { reason: 'outside_map' }); + return { town, x, y, tile }; +} + +module.exports = function sendMovement(ctx0, args) { + const ctx = ctxOf(ctx0); + const { db, now } = ctx; + const { userId, fromTownId, type } = args; + if (TYPES.indexOf(type) < 0) throw new GameError('validation_failed', { errors: [{ path: 'type', message: 'must be one of ' + TYPES.join(', ') }] }); + const from = ownedTown(db, userId, fromTownId); + const world = loadWorld(db, from.worldId); + const op = U.getOperator(db, from.ownerId); + const units = U.cleanUnits(args.units || {}); + const chk = R.checkUnitsForType(type, units); + if (chk) throw new GameError(chk.code, { reason: chk.reason }); + settle(db, from, now); + + const home = U.homeUnits(db, from.id); + 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); + 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); + const extra = { research: U.researchSnapshot(db, from.id, units) }; + let defOp = null; + let endProtection = false; + + if (type === 'scan' || HOSTILE.indexOf(type) >= 0) { + if (tgt.town) { + defOp = U.getOperator(db, tgt.town.owner_id); + if (defOp.id === op.id) throw new GameError('invalid_target', { reason: 'own_town' }); + if (type !== 'scan') { + if (U.pactBlocks(db, op.id, defOp.id)) throw new GameError('invalid_target', { reason: 'pact' }); + if (R.isProtected(defOp.protection_until, arriveAt)) throw new GameError('target_protected', { until: defOp.protection_until }); + if (R.isProtected(op.protection_until, now)) { + if (!args.confirmEndProtection) throw new GameError('protection_active', { until: op.protection_until }); + endProtection = true; + } + } + if (type === 'takeover') { + const count = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n; + const block = R.takeoverBlock(!!tgt.town.is_capital, count); + if (block === 'last_pop') throw new GameError('cannot_takeover', { reason: block }); + const gate = R.footprintGate(U.operatorTowns(db, op.id).length, U.operatorFootprint(db, op.id, now)); + if (!gate.ok) throw new GameError('footprint_too_low', { need: gate.need, have: gate.have }); + } + } else if (tgt.tile.type === 'incumbent') { + if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'incumbent_scan_or_attack_only' }); + } else { + throw new GameError('invalid_target', { reason: 'nothing_there' }); + } + if ((type === 'attack' || type === 'takeover') && units.exploit_kit && args.target !== undefined && args.target !== null) { + const t = String(args.target); + const bdef = R.isFieldKey(t) ? { special: false } : R.buildingDef(t); + if (!bdef || bdef.special) throw new GameError('validation_failed', { errors: [{ path: 'target', message: 'not a building' }] }); + extra.target = t; + } + } else if (type === 'reinforce') { + if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' }); + if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' }); + defOp = U.getOperator(db, tgt.town.owner_id); + } else if (type === 'settle') { + 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) }); + if (!chk2.ok) throw new GameError(chk2.code, chk2); + extra.wild = R.cleanWild(args.wild); + } + + // ---- all checks passed: apply + if (endProtection) db.run('UPDATE operators SET protection_until = ? WHERE id = ?', now, op.id); + U.removeHome(db, from.id, units); + P.reschedule(ctx, from.id, now); + const mv = M.insertMovement(ctx, { + worldId: from.worldId, ownerId: op.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null, + from: { x: from.x, y: from.y }, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, extra, + }); + if (tgt.town && defOp && defOp.id !== op.id) { + const uid = U.userOfOperator(db, defOp.id); + if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: tgt.town.id, fromTownId: from.id, arriveAt }); // type hidden + } + return { movementId: mv.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, protectionEnded: endProtection }; +}; +module.exports.resolveTarget = resolveTarget; diff --git a/server/commands/sendTransport.js b/server/commands/sendTransport.js new file mode 100644 index 0000000..5d65d3b --- /dev/null +++ b/server/commands/sendTransport.js @@ -0,0 +1,52 @@ +'use strict'; +/* + * POST /movements with type 'transport': carry resources from one of your POPs to any POP. Capacity and the number + * of concurrent transports come from the Internet exchange (D.TRANSPORT): `links` = its level, each link carries + * `capacityPerLink`. The cargo leaves the POP now and is added to the target on arrival (anything above the target's + * Rack hall cap is lost). The trade stage calls `launchTransport` directly for the two legs of an accepted offer. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { settle, loadWorld } = require('../state'); +const { ownedTown } = require('./build'); +const ctxOf = require('../military/ctx'); +const U = require('../military/units'); +const M = require('../military/movements'); + +// Validate + dispatch from an already settled, owned POP `from`. `toRow` is the target POP row. `extra` is stored on +// the movement (and its return leg) for later stages, e.g. { tradeId }. Returns the movement. +function launchTransport(ctx, from, toRow, cargo, extra) { + const { db, now } = ctx; + const plan = R.transportPlan(from, cargo, M.activeLinks(db, from.id), now); + if (!plan.ok) throw new GameError(plan.code, plan); + const world = loadWorld(db, from.worldId); + const dist = R.distance(from.x, from.y, toRow.x, toRow.y); + const clean = {}; + for (const r of D.RESOURCES) if (cargo[r] > 0) clean[r] = cargo[r]; + for (const r of D.RESOURCES) from.res[r] -= clean[r] || 0; + db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', from.res.fiber, from.res.hardware, from.res.capital, from.id); + return M.insertMovement(ctx, { + worldId: from.worldId, ownerId: from.ownerId, type: 'transport', fromTownId: from.id, toTownId: toRow.id, + from: { x: from.x, y: from.y }, to: { x: toRow.x, y: toRow.y }, units: {}, cargo: clean, + departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: Object.assign({}, extra || {}), + }); +} + +module.exports = function sendTransport(ctx0, { userId, fromTownId, toTownId, cargo }) { + const ctx = ctxOf(ctx0); + const { db, now } = ctx; + const from = ownedTown(db, userId, fromTownId); + const to = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', toTownId, from.worldId); + if (!to) throw new GameError('not_found', { what: 'town' }); + if (to.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' }); + settle(db, from, now); + const mv = launchTransport(ctx, from, to, cargo || {}); + const toOp = U.getOperator(db, to.owner_id); + if (toOp.id !== from.ownerId) { + const uid = U.userOfOperator(db, toOp.id); + if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: to.id, fromTownId: from.id, arriveAt: mv.arriveAt }); + } + return { movementId: mv.id, type: 'transport', fromTownId: from.id, toTownId: to.id, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt }; +}; +module.exports.launchTransport = launchTransport; diff --git a/server/commands/train.js b/server/commands/train.js new file mode 100644 index 0000000..004dee0 --- /dev/null +++ b/server/commands/train.js @@ -0,0 +1,37 @@ +'use strict'; +/* + * POST /towns/:id/train. Queue a batch of one unit type. Batches of the same training building run one after another + * (each is a `trainDone` event); different buildings train in parallel. Units appear when the batch finishes. + */ +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'); + +// Pending batches of a training building, in due order: [{ id, dueAt, ...payload }]. +function pendingBatches(db, townId, building) { + return db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", townId) + .map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload))) + .filter((b) => !building || b.building === building); +} + +module.exports = function train(ctx, { userId, townId, unit, count }) { + const { db, now, scheduler } = ctx; + const town = ownedTown(db, userId, townId); + const def = R.unitDef(unit); + if (!def) throw new GameError('unknown_unit', { unit }); + settle(db, town, now); + const queue = pendingBatches(db, town.id, def.building); + if (queue.length >= D.MILITARY.maxTrainQueue) throw new GameError('queue_full', { building: def.building, max: D.MILITARY.maxTrainQueue }); + const tail = queue.length ? queue[queue.length - 1].dueAt : 0; + const plan = R.trainPlan(town, unit, count, now, tail); + if (!plan.ok) throw new GameError(plan.code, { unit, count, cost: plan.cost, missing: plan.missing }); + spend(db, town, plan.cost); + const eventId = scheduler.enqueue({ + worldId: town.worldId, townId: town.id, type: 'trainDone', dueAt: plan.dueAt, + payload: { unit, count, building: def.building, startAt: plan.startAt, cost: plan.cost, userId }, + }); + return { eventId, unit, count, building: def.building, startAt: plan.startAt, dueAt: plan.dueAt, cost: plan.cost }; +}; +module.exports.pendingBatches = pendingBatches; diff --git a/server/commands/withdrawStationed.js b/server/commands/withdrawStationed.js new file mode 100644 index 0000000..782d1ba --- /dev/null +++ b/server/commands/withdrawStationed.js @@ -0,0 +1,35 @@ +'use strict'; +/* POST /towns/:id/withdraw. Reinforcements standing in host POP :id go home. Either side may do it: the host owner + * sends them away, the units' owner calls them back. `units` defaults to the whole group. They travel home as a + * return movement and stop drawing the host's power right away. */ +const { GameError } = require('../errors'); +const { settle } = require('../state'); +const ctxOf = require('../military/ctx'); +const U = require('../military/units'); +const M = require('../military/movements'); +const P = require('../military/power'); + +module.exports = function withdrawStationed(ctx0, { userId, hostTownId, ownerTownId, units }) { + const ctx = ctxOf(ctx0); + const { db, now } = ctx; + const host = db.get('SELECT * FROM towns WHERE id = ?', hostTownId); + const owner = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId); + if (!host || !owner) throw new GameError('not_found', { what: 'town' }); + const mine = (t) => !!db.get('SELECT 1 AS x FROM operators WHERE id = ? AND user_id = ?', t.owner_id, userId); + if (!mine(host) && !mine(owner)) throw new GameError('not_found', { what: 'town' }); + const have = U.stationedOf(db, host.id, owner.id); + let take = units && Object.keys(units).length ? U.cleanUnits(units) : have; + take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0)); + if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' }); + for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] }); + const hostTown = require('../state').loadTown(db, host.id); + settle(db, hostTown, now); // the host's draw changes + U.removeStationed(db, host.id, owner.id, take); + P.reschedule(ctx, host.id, now); + const mv = M.launchReturn(ctx, { worldId: host.world_id, ownerId: owner.owner_id, fromTownId: host.id, at: { x: host.x, y: host.y }, to: owner, units: take, cargo: {}, extra: { withdrawn: true } }); + if (!mine(owner)) { + const uid = U.userOfOperator(db, owner.owner_id); + if (uid) ctx.notify(uid, host.world_id, 'reinforcements_sent_home', { hostTownId: host.id, ownerTownId: owner.id, units: take }); + } + return { movementId: mv.id, units: take, arriveAt: mv.arriveAt }; +}; diff --git a/server/diplomacy.js b/server/diplomacy.js new file mode 100644 index 0000000..0d0d25b --- /dev/null +++ b/server/diplomacy.js @@ -0,0 +1,25 @@ +'use strict'; +/* Shared pieces of the diplomacy commands and the delayed `diploChange` event. */ +const A = require('./alliances'); + +const brief = (a) => ({ id: a.id, tag: a.tag, name: a.name }); + +// Everybody in both alliances hears about a relation that changed. +function announceChange(ctx, x, y, from, to, extra) { + for (const [me, other] of [[x, y], [y, x]]) { + A.notifyAlliance(ctx, me.id, 'diplomacy_changed', Object.assign({ allianceId: me.id, other: brief(other), from, to }, extra || {})); + } +} + +// Make `to` the current relation of the pair right now, drop proposals that this overtakes, tell everyone. +function applyChange(ctx, x, y, to, extra) { + const { db, now } = ctx; + const cur = A.getRelation(db, x.id, y.id); + const from = cur ? cur.state : 'neutral'; + A.setRelation(db, x.world_id, x.id, y.id, to, now); + A.withdrawProposals(db, x.id, y.id, now); + announceChange(ctx, x, y, from, to, extra); + return from; +} + +module.exports = { brief, announceChange, applyChange }; diff --git a/server/errors.js b/server/errors.js index 4126426..fc9dfd5 100644 --- a/server/errors.js +++ b/server/errors.js @@ -28,6 +28,34 @@ const CODES = { already_queued: [409, 'That building is already being built.'], queue_full: [409, 'All build slots are busy.'], not_enough_resources: [409, 'Not enough resources.'], + // social: alliances, diplomacy, messages + peering_office_required: [409, 'A Peering office (level 1 or higher) is needed to found or join an alliance.'], + already_in_alliance: [409, 'That operator is already in an alliance.'], + not_in_alliance: [409, 'You are not in that alliance.'], + alliance_name_taken: [409, 'That alliance name is taken.'], + alliance_tag_taken: [409, 'That alliance tag is taken.'], + alliance_full: [409, 'The alliance has no room for more members.'], + invite_expired: [409, 'The invite has expired.'], + leader_must_transfer: [409, 'The leader must hand over leadership before leaving.'], + notes_full: [409, 'The alliance has reached its pinned-note limit.'], + diplomacy_invalid: [409, 'That diplomatic move is not allowed from the current state.'], + diplomacy_pending: [409, 'A diplomatic change between these alliances is already scheduled.'], + proposal_exists: [409, 'The other alliance already proposed this; accept their proposal instead.'], + proposal_expired: [409, 'The proposal has expired.'], + // military and expansion + unknown_unit: [404, 'No such unit type.'], + not_researchable: [409, 'That unit stat cannot be researched.'], + not_enough_units: [409, 'Not enough units at home.'], + units_offline: [409, 'Those units are offline (the battery is empty).'], + invalid_target: [409, 'That target is not valid for this kind of movement.'], + target_protected: [409, 'The target is under beginner protection.'], + protection_active: [409, 'Attacking ends your beginner protection; confirm to go ahead.'], + out_of_range: [409, 'The target is too far from your POPs.'], + footprint_too_low: [409, 'Your footprint is too low for another POP.'], + cannot_takeover: [409, 'That POP cannot be taken over.'], + recall_expired: [409, 'The recall window (first 90 seconds) has passed.'], + capacity_exceeded: [409, 'More than one transport link can carry.'], + no_transport_link: [409, 'All transport links are busy (or there is no Internet exchange).'], }; class GameError extends Error { diff --git a/server/events/arrive.js b/server/events/arrive.js new file mode 100644 index 0000000..610c55a --- /dev/null +++ b/server/events/arrive.js @@ -0,0 +1,19 @@ +'use strict'; +/* A movement reached its destination. Payload { movementId }. Dispatches by movement type; everything runs at the + * event's own due time, inside the scheduler's transaction. Idempotent: only an `out` movement is processed. */ +const M = require('../military/movements'); +const A = require('../military/arrivals'); +const combat = require('../military/combat'); + +module.exports = function arrive(ctx, ev) { + const mv = M.getMovement(ctx.db, ev.payload.movementId); + if (!mv || mv.status !== 'out') return; + ctx.db.run("UPDATE movements SET status = 'done' WHERE id = ?", mv.id); + switch (mv.type) { + case 'scan': case 'raid': case 'attack': case 'takeover': return combat.arrive(ctx, mv, ev); + case 'reinforce': return A.arriveReinforce(ctx, mv, ev); + case 'transport': return A.arriveTransport(ctx, mv, ev); + case 'settle': return A.arriveSettle(ctx, mv, ev); + default: throw new Error('unknown movement type ' + mv.type); + } +}; diff --git a/server/events/buildDone.js b/server/events/buildDone.js index 94c4c21..0a4c24b 100644 --- a/server/events/buildDone.js +++ b/server/events/buildDone.js @@ -11,5 +11,6 @@ module.exports = function buildDone(ctx, ev) { const cur = town.buildings[key]; if (!cur) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, toLevel); else if (cur.level < toLevel) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', toLevel, town.id, key); + require('../military/power').reschedule(ctx, town.id, ev.dueAt); // building draw / battery cap changed: units' power check if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel }); }; diff --git a/server/events/diploChange.js b/server/events/diploChange.js new file mode 100644 index 0000000..639c5e1 --- /dev/null +++ b/server/events/diploChange.js @@ -0,0 +1,15 @@ +'use strict'; +/* A unilateral cancel of a pact (or war declared out of a pact) came due. Payload { a, b, to, by }. + * Idempotent and safe against cancellation: it only acts when the relation row still points at THIS event. */ +const A = require('../alliances'); +const Dip = require('../diplomacy'); + +module.exports = function diploChange(ctx, ev) { + const { db } = ctx; + const { a, b, to } = ev.payload; + const rel = A.getRelation(db, a, b); + if (!rel || rel.pending_event !== ev.id) return; // revoked, replaced, or already applied + const x = A.getAlliance(db, a), y = A.getAlliance(db, b); + if (!x || !y) return; + Dip.applyChange(ctx, x, y, to, { delayed: true, startedBy: ev.payload.by }); +}; diff --git a/server/events/index.js b/server/events/index.js index db31347..a17c393 100644 --- a/server/events/index.js +++ b/server/events/index.js @@ -1,5 +1,13 @@ 'use strict'; /* Event type -> handler. One file per event type. */ module.exports = { + // stage 3/4: military and expansion + trainDone: require('./trainDone'), + researchDone: require('./researchDone'), + arrive: require('./arrive'), + return: require('./return'), + powerCheck: require('./powerCheck'), + reportCleanup: require('./reportCleanup'), buildDone: require('./buildDone'), + diploChange: require('./diploChange'), }; diff --git a/server/events/powerCheck.js b/server/events/powerCheck.js new file mode 100644 index 0000000..41da6c7 --- /dev/null +++ b/server/events/powerCheck.js @@ -0,0 +1,3 @@ +'use strict'; +/* Battery empty / offline for 24 h: see server/military/power.js. Payload { townId }. */ +module.exports = require('../military/power').powerCheck; diff --git a/server/events/reportCleanup.js b/server/events/reportCleanup.js new file mode 100644 index 0000000..9942b98 --- /dev/null +++ b/server/events/reportCleanup.js @@ -0,0 +1,9 @@ +'use strict'; +/* Delete expired reports (14 days, real time), then arm the next cleanup for the earliest remaining expiry. createReport + * arms it when none is pending, so there is at most one pending cleanup per world and none while no reports exist. */ +module.exports = function reportCleanup(ctx, ev) { + const { db } = ctx; + db.run('DELETE FROM reports WHERE world_id = ? AND expires_at <= ?', ev.worldId, ev.dueAt); + const left = db.get('SELECT MIN(expires_at) AS e FROM reports WHERE world_id = ?', ev.worldId); + if (left && left.e !== null) ctx.enqueue({ worldId: ev.worldId, dueAt: left.e, type: 'reportCleanup', payload: { worldId: ev.worldId } }); +}; diff --git a/server/events/researchDone.js b/server/events/researchDone.js new file mode 100644 index 0000000..df9d6e1 --- /dev/null +++ b/server/events/researchDone.js @@ -0,0 +1,12 @@ +'use strict'; +/* A research level finished. Payload { unit, stat, toLevel, userId }. Idempotent: a level never goes down. */ +const R = require('../../public/js/rules.js'); + +module.exports = function researchDone(ctx, ev) { + const { db } = ctx; + const { unit, stat, toLevel, userId } = ev.payload; + if (!db.get('SELECT 1 AS x FROM towns WHERE id = ?', ev.townId)) return; + db.run(`INSERT INTO town_research (town_id, unit, stat, level) VALUES (?, ?, ?, ?) + ON CONFLICT (town_id, unit, stat) DO UPDATE SET level = MAX(level, excluded.level)`, ev.townId, unit, stat, toLevel); + if (userId) ctx.notify(userId, ev.worldId, 'research_done', { townId: ev.townId, unit, stat, level: toLevel, key: R.researchKey(unit, stat) }); +}; diff --git a/server/events/return.js b/server/events/return.js new file mode 100644 index 0000000..f20b7b1 --- /dev/null +++ b/server/events/return.js @@ -0,0 +1,28 @@ +'use strict'; +/* + * A return leg arrived: units and cargo go back home. If the origin POP changed hands meanwhile they go to the + * operator's capital (or oldest POP) instead; with no POP left they are lost. Cargo above the Rack hall cap is lost. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { loadTown, settle } = require('../state'); +const M = require('../military/movements'); +const U = require('../military/units'); +const P = require('../military/power'); +const { addCargo } = require('../military/arrivals'); + +module.exports = function ret(ctx, ev) { + const { db } = ctx; + const mv = M.getMovement(db, ev.payload.movementId); + if (!mv || mv.status !== 'out') return; + db.run("UPDATE movements SET status = 'done' WHERE id = ?", mv.id); + const dest = U.homeTownFor(db, mv.ownerId, mv.toTownId); + const uid = U.userOfOperator(db, mv.ownerId); + if (!dest) { if (uid) ctx.notify(uid, mv.worldId, 'movement_lost', { movementId: mv.id }); return; } + const town = loadTown(db, dest.id); + settle(db, town, ev.dueAt); + U.addHome(db, town.id, mv.units); + const lost = addCargo(db, town, mv.cargo); + P.reschedule(ctx, town.id, ev.dueAt); + if (uid && !mv.extra.link) ctx.notify(uid, mv.worldId, 'movement_returned', { movementId: mv.id, townId: town.id, units: mv.units, cargo: mv.cargo, cargoLost: lost }); +}; diff --git a/server/events/trainDone.js b/server/events/trainDone.js new file mode 100644 index 0000000..eeea5b7 --- /dev/null +++ b/server/events/trainDone.js @@ -0,0 +1,17 @@ +'use strict'; +/* A training batch finished. Payload { unit, count, building, userId }. The POP is settled to the due time at the OLD + * power draw, then the units appear (and the draw rises). */ +const { loadTown, settle } = require('../state'); +const U = require('../military/units'); +const P = require('../military/power'); + +module.exports = function trainDone(ctx, ev) { + const { db } = ctx; + const { unit, count, userId } = ev.payload; + const town = loadTown(db, ev.townId); + if (!town) return; + settle(db, town, ev.dueAt); + U.addHome(db, town.id, { [unit]: count }); + P.reschedule(ctx, town.id, ev.dueAt); + if (userId) ctx.notify(userId, ev.worldId, 'train_done', { townId: town.id, unit, count }); +}; diff --git a/server/http.js b/server/http.js index a41834f..61edef7 100644 --- a/server/http.js +++ b/server/http.js @@ -17,7 +17,7 @@ const { TokenBucket, clientIp } = require('./net'); const { applySecurityHeaders } = require('./static'); const MAX_BODY = 32 * 1024; -const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId']); +const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId']); // Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound. class Limiter { diff --git a/server/migrations/002_military.sql b/server/migrations/002_military.sql new file mode 100644 index 0000000..5d13b76 --- /dev/null +++ b/server/migrations/002_military.sql @@ -0,0 +1,102 @@ +-- Stage 3/4 (military, expansion): units at home, reinforcements, research, movements, reports, battle points. +-- Units are { unit id: count } everywhere. Times are integer ms since the epoch (UTC). + +-- Units at home, owned by the town's owner. Always settle() the town before changing these (power draw changes). +CREATE TABLE town_units ( + town_id INTEGER NOT NULL REFERENCES towns(id), + unit TEXT NOT NULL, + count INTEGER NOT NULL CHECK (count > 0), + PRIMARY KEY (town_id, unit) +); + +-- Reinforcements: units of owner_town_id's operator standing in host_town_id. They defend the host and draw its power. +CREATE TABLE stationed ( + host_town_id INTEGER NOT NULL REFERENCES towns(id), + owner_town_id INTEGER NOT NULL REFERENCES towns(id), + unit TEXT NOT NULL, + count INTEGER NOT NULL CHECK (count > 0), + PRIMARY KEY (host_town_id, owner_town_id, unit) +); +CREATE INDEX stationed_owner ON stationed(owner_town_id); + +-- Research levels per POP (attack or defence of one unit type). +CREATE TABLE town_research ( + town_id INTEGER NOT NULL REFERENCES towns(id), + unit TEXT NOT NULL, + stat TEXT NOT NULL, -- attack | defence + level INTEGER NOT NULL, + PRIMARY KEY (town_id, unit, stat) +); + +-- When the units in a POP went offline (battery empty, net power negative). NULL / no row = online. +CREATE TABLE town_power ( + town_id INTEGER PRIMARY KEY REFERENCES towns(id), + offline_since INTEGER +); + +-- Everything that is travelling. type: scan | raid | attack | takeover | reinforce | settle | transport | return. +-- status: out (travelling, arrive/return event pending) | done | recalled (turned around, a return movement exists). +-- A target is a POP (to_town_id) or just a tile (settle, incumbent sites): to_x/to_y are always set. +CREATE TABLE movements ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL REFERENCES worlds(id), + owner_id INTEGER NOT NULL REFERENCES operators(id), + type TEXT NOT NULL, + from_town_id INTEGER REFERENCES towns(id), + to_town_id INTEGER REFERENCES towns(id), + from_x INTEGER NOT NULL, + from_y INTEGER NOT NULL, + to_x INTEGER NOT NULL, + to_y INTEGER NOT NULL, + units TEXT NOT NULL DEFAULT '{}', + cargo TEXT NOT NULL DEFAULT '{}', + depart_at INTEGER NOT NULL, + arrive_at INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'out', + event_id INTEGER, + parent_id INTEGER, -- the outbound movement a return belongs to + extra TEXT NOT NULL DEFAULT '{}', -- research snapshot, building target, wild slots, trade metadata, ... + created_at INTEGER NOT NULL +); +CREATE INDEX movements_owner ON movements(owner_id, status); +CREATE INDEX movements_to ON movements(to_town_id, status); +CREATE INDEX movements_from ON movements(from_town_id, status); + +-- A report is one row, shared by all participants (report_recipients). Kept 14 days (expires_at), cleaned by an event. +CREATE TABLE reports ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL REFERENCES worlds(id), + type TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + summary TEXT NOT NULL DEFAULT '{}', + data TEXT NOT NULL DEFAULT '{}' +); +CREATE INDEX reports_expires ON reports(expires_at); + +CREATE TABLE report_recipients ( + report_id INTEGER NOT NULL REFERENCES reports(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id), + role TEXT NOT NULL, -- attacker | defender | reinforcer | sender | target + read_at INTEGER, + PRIMARY KEY (report_id, user_id) +); +CREATE INDEX report_recipients_user ON report_recipients(user_id, report_id); + +-- Battle points per operator, written by combat; rankings (social) read it. +CREATE TABLE operator_stats ( + operator_id INTEGER PRIMARY KEY REFERENCES operators(id), + attack_points REAL NOT NULL DEFAULT 0, + defense_points REAL NOT NULL DEFAULT 0 +); + +-- Incumbent sites an operator has taken (one-time Hardware bonus per site; the count drives the research speed bonus). +CREATE TABLE incumbent_takes ( + world_id INTEGER NOT NULL REFERENCES worlds(id), + x INTEGER NOT NULL, + y INTEGER NOT NULL, + operator_id INTEGER NOT NULL REFERENCES operators(id), + taken_at INTEGER NOT NULL, + PRIMARY KEY (world_id, x, y, operator_id) +); +CREATE INDEX incumbent_takes_operator ON incumbent_takes(operator_id); diff --git a/server/migrations/003_social.sql b/server/migrations/003_social.sql new file mode 100644 index 0000000..cc442e6 --- /dev/null +++ b/server/migrations/003_social.sql @@ -0,0 +1,113 @@ +-- Stage 5 (social): alliances, diplomacy between alliances, pinned notes, messages. +-- operators.alliance_id (001) stays the quick lookup; alliance_members adds the role and is kept in step with it by +-- server/alliances.js (addMember / removeMember are the only writers). + +CREATE TABLE alliances ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL REFERENCES worlds(id), + name TEXT NOT NULL COLLATE NOCASE, + tag TEXT NOT NULL COLLATE NOCASE, + size_cap INTEGER NOT NULL, -- stored at founding, only ever raised (rules.allianceCap) + created_by INTEGER NOT NULL REFERENCES operators(id), + created_at INTEGER NOT NULL, + UNIQUE (world_id, name), + UNIQUE (world_id, tag) +); + +CREATE TABLE alliance_members ( + operator_id INTEGER PRIMARY KEY REFERENCES operators(id), + alliance_id INTEGER NOT NULL REFERENCES alliances(id), + role TEXT NOT NULL, -- leader | diplomat | officer | member + joined_at INTEGER NOT NULL +); +CREATE INDEX alliance_members_alliance ON alliance_members(alliance_id); +CREATE UNIQUE INDEX alliance_one_leader ON alliance_members(alliance_id) WHERE role = 'leader'; + +CREATE TABLE alliance_invites ( + id INTEGER PRIMARY KEY, + alliance_id INTEGER NOT NULL REFERENCES alliances(id), + operator_id INTEGER NOT NULL REFERENCES operators(id), -- the invitee + invited_by INTEGER NOT NULL REFERENCES operators(id), + status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | cancelled | expired + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + answered_at INTEGER +); +CREATE UNIQUE INDEX alliance_invites_pending ON alliance_invites(alliance_id, operator_id) WHERE status = 'pending'; +CREATE INDEX alliance_invites_operator ON alliance_invites(operator_id, status); + +CREATE TABLE alliance_notes ( + id INTEGER PRIMARY KEY, + alliance_id INTEGER NOT NULL REFERENCES alliances(id), + author_id INTEGER NOT NULL REFERENCES operators(id), + text TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); +CREATE INDEX alliance_notes_alliance ON alliance_notes(alliance_id, id); + +-- One row per alliance pair that is not plainly neutral (a_id < b_id). state = the CURRENT relation. A unilateral cancel +-- keeps `state` until the delayed `diploChange` event (pending_event) applies pending_to at pending_at. +CREATE TABLE alliance_relations ( + a_id INTEGER NOT NULL REFERENCES alliances(id), + b_id INTEGER NOT NULL REFERENCES alliances(id), + world_id INTEGER NOT NULL, + state TEXT NOT NULL, -- war | neutral | nap | confed + since INTEGER NOT NULL, + pending_to TEXT, + pending_at INTEGER, + pending_by INTEGER, -- the alliance that started the change + pending_event INTEGER, -- events.id + PRIMARY KEY (a_id, b_id), + CHECK (a_id < b_id) +); +CREATE INDEX alliance_relations_b ON alliance_relations(b_id); + +CREATE TABLE alliance_proposals ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL, + from_id INTEGER NOT NULL REFERENCES alliances(id), + to_id INTEGER NOT NULL REFERENCES alliances(id), + state TEXT NOT NULL, -- the proposed relation + status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | withdrawn | expired + proposed_by INTEGER NOT NULL REFERENCES operators(id), + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + answered_at INTEGER +); +CREATE UNIQUE INDEX alliance_proposals_pending ON alliance_proposals(from_id, to_id) WHERE status = 'pending'; +CREATE INDEX alliance_proposals_to ON alliance_proposals(to_id, status); + +-- Messages. No foreign key on alliance_id: broadcasts outlive a disbanded alliance (alliance_tag is a snapshot). +-- Each recipient has their own row (read / deleted); the sender's copy is hidden with sender_deleted_at. +CREATE TABLE messages ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL, + sender_id INTEGER NOT NULL REFERENCES operators(id), + kind TEXT NOT NULL, -- dm | alliance + to_id INTEGER REFERENCES operators(id), -- dm only + alliance_id INTEGER, -- alliance broadcast only + alliance_tag TEXT, + thread TEXT NOT NULL, -- 'dm::' | 'alliance:' + body TEXT NOT NULL, + created_at INTEGER NOT NULL, + sender_deleted_at INTEGER +); +CREATE INDEX messages_sender ON messages(sender_id, id); +CREATE INDEX messages_thread ON messages(thread, id); + +CREATE TABLE message_recipients ( + message_id INTEGER NOT NULL REFERENCES messages(id), + operator_id INTEGER NOT NULL REFERENCES operators(id), + read_at INTEGER, + deleted_at INTEGER, + PRIMARY KEY (message_id, operator_id) +); +CREATE INDEX message_recipients_operator ON message_recipients(operator_id, message_id); + +CREATE TABLE message_blocks ( + operator_id INTEGER NOT NULL REFERENCES operators(id), -- who blocks + blocked_id INTEGER NOT NULL REFERENCES operators(id), + created_at INTEGER NOT NULL, + PRIMARY KEY (operator_id, blocked_id) +); diff --git a/server/military/arrivals.js b/server/military/arrivals.js new file mode 100644 index 0000000..b6abf4c --- /dev/null +++ b/server/military/arrivals.js @@ -0,0 +1,122 @@ +'use strict'; +/* + * Arrival handlers for the movements that are not fights: reinforce, transport, settle. Plus the shared pieces every + * arrival uses (cargo delivery, bouncing a movement back, brief descriptions for reports). Each handler runs inside the + * `arrive` event's transaction at the event's own due time. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { loadTown, settle, loadWorld } = require('../state'); +const { createTown } = require('../commands/joinWorld'); +const U = require('./units'); +const M = require('./movements'); +const P = require('./power'); +const { createReport } = require('./reports'); + +const townBrief = (t) => t ? { id: t.id, name: t.name, x: t.x, y: t.y } : null; +const opBrief = (o) => o ? { id: o.id, name: o.name, asNumber: o.as_number } : null; + +// Add resources to a SETTLED town, capped at its storage (an amount already above the cap is kept). -> what was lost +function addCargo(db, town, cargo) { + const cap = R.storageCap(town); + const lost = {}; + for (const r of D.RESOURCES) { + const add = (cargo && cargo[r]) || 0; + if (!add) continue; + const cur = town.res[r]; + const next = Math.min(Math.max(cap, cur), cur + add); + lost[r] = Math.max(0, Math.round(cur + add - next)); + town.res[r] = next; + } + db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id); + return lost; +} + +// The movement cannot do what it came for: its units (and cargo) turn around and a report tells the sender why. +function bounce(ctx, mv, now, reason, details) { + const { db } = ctx; + const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId); + if (dest && !U.isEmpty(mv.units)) { + M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: mv.units, cargo: mv.cargo, parentId: mv.id, extra: { bounced: reason } }); + } + createReport(ctx, { + worldId: mv.worldId, type: 'movement_failed', now, + summary: { movementType: mv.type, reason, to: mv.to }, + data: { movementType: mv.type, reason, details: details || {}, to: mv.to, units: mv.units }, + recipients: [{ userId: U.userOfOperator(db, mv.ownerId), role: 'sender' }], + }); +} + +function arriveReinforce(ctx, mv, ev) { + const { db } = ctx; + const now = ev.dueAt; + const target = mv.toTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId) : null; + if (!target || !U.mayReinforce(db, mv.ownerId, target.owner_id)) return bounce(ctx, mv, now, 'not_allied'); + const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId); + if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to + const host = loadTown(db, target.id); + settle(db, host, now); // the host's draw rises at this moment + // Moving units between your own POPs: they simply live in the new POP now. Only other operators' units are "stationed". + if (ownerTown.id === host.id || target.owner_id === mv.ownerId) U.addHome(db, host.id, mv.units); + else U.addStationed(db, host.id, ownerTown.id, mv.units); + P.reschedule(ctx, host.id, now); + const sender = U.getOperator(db, mv.ownerId), hostOp = U.getOperator(db, target.owner_id); + createReport(ctx, { + worldId: mv.worldId, type: 'reinforce', now, + summary: { host: townBrief(target), from: townBrief(ownerTown), units: mv.units }, + data: { host: townBrief(target), hostOperator: opBrief(hostOp), from: townBrief(ownerTown), operator: opBrief(sender), units: mv.units }, + recipients: [{ userId: U.userOfOperator(db, sender.id), role: 'sender' }, { userId: U.userOfOperator(db, hostOp.id), role: 'target' }], + }); +} + +function arriveTransport(ctx, mv, ev) { + const { db } = ctx; + const now = ev.dueAt; + const target = mv.toTownId ? loadTown(db, mv.toTownId) : null; + let lost = {}; + if (target) { + settle(db, target, now); + lost = addCargo(db, target, mv.cargo); + const sender = U.userOfOperator(db, mv.ownerId), receiver = U.userOfOperator(db, target.ownerId); + if (receiver) ctx.notify(receiver, mv.worldId, 'transport_arrived', { movementId: mv.id, townId: target.id, fromTownId: mv.fromTownId, cargo: mv.cargo, cargoLost: lost, own: receiver === sender }); + if (sender && sender !== receiver) ctx.notify(sender, mv.worldId, 'transport_delivered', { movementId: mv.id, toTownId: target.id, cargo: mv.cargo, cargoLost: lost }); + for (const fn of M.hooks.transportArrived) fn(ctx, mv, { added: mv.cargo, lost }); + } + const cargoBack = target ? {} : mv.cargo; // no such POP any more: the cargo rides home with the carriers + // The empty carriers drive back; the link is busy until they are home. + const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId); + if (dest) { + const world = loadWorld(db, mv.worldId); + const dist = R.distance(mv.to.x, mv.to.y, dest.x, dest.y); + M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: {}, cargo: cargoBack, arriveAt: now + R.transportMs(dist, world.speed), parentId: mv.id, extra: Object.assign({}, mv.extra, { link: 1 }) }); + } +} + +// Three Rollout crews found a new POP on the empty tile, if it is still empty land, still in range, footprint still enough. +function arriveSettle(ctx, mv, ev) { + const { db } = ctx; + const now = ev.dueAt; + const world = loadWorld(db, mv.worldId); + const op = U.getOperator(db, mv.ownerId); + const { x, y } = mv.to; + const tile = R.tileAt(world.seed, world.map_radius, x, y); + const occupied = !!db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y); + 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, x, y)); + const chk = R.settleCheck({ tileType: tile.type, occupied, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) }); + if (!chk.ok) return bounce(ctx, mv, now, chk.code, chk); + const wild = R.cleanWild(mv.extra.wild); + const name = op.name + ' POP ' + (own.length + 1); + const id = createTown(db, { worldId: world.id, ownerId: op.id, name, x, y, isCapital: false, now, buildings: R.newTownBuildings(wild), res: D.EXPANSION.startResources }); + db.run('UPDATE towns SET battery = 0, loyalty = ? WHERE id = ?', D.EXPANSION.foundedLoyalty, id); + const founded = { id, name, x, y }; + createReport(ctx, { + worldId: world.id, type: 'settle', now, + summary: { success: true, town: founded }, + data: { success: true, town: founded, wild, crews: mv.units, from: mv.fromTownId }, + recipients: [{ userId: U.userOfOperator(db, op.id), role: 'sender' }], + }); +} + +module.exports = { addCargo, bounce, arriveReinforce, arriveTransport, arriveSettle, townBrief, opBrief }; diff --git a/server/military/combat.js b/server/military/combat.js new file mode 100644 index 0000000..3c0b1bf --- /dev/null +++ b/server/military/combat.js @@ -0,0 +1,282 @@ +'use strict'; +/* + * Arrival of scan / raid / attack / takeover. Everything here runs inside the `arrive` event's transaction at the + * event's own due time, after every earlier event, so combat order is exactly event order. Deterministic: the only + * dice (the loyalty roll) are seeded from (world seed, movement id). + * + * Steps: re-check the target (it may have changed since departure) -> settle the target to the due time -> gather + * defenders (home crews + reinforcements, only while online) -> rules.resolveBattle -> apply losses, loot, siege, + * takeover -> survivors drive home with the loot -> reports + battle points. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { loadTown, settle, loadWorld } = require('../state'); +const U = require('./units'); +const M = require('./movements'); +const P = require('./power'); +const { createReport } = require('./reports'); +const { bounce, townBrief, opBrief } = require('./arrivals'); + +const DAY = 24 * D.HOUR_MS; + +// All groups standing in the target: home crews then each reinforcing POP's units, with the research that applies. +function defenderGroups(db, target) { + const groups = []; + const home = U.homeUnits(db, target.id); + if (!U.isEmpty(home)) groups.push({ id: 'home', ownerTownId: target.id, ownerOpId: target.ownerId, units: home, research: U.researchLevels(db, target.id) }); + for (const g of U.hostedGroups(db, target.id)) { + const ot = db.get('SELECT owner_id FROM towns WHERE id = ?', g.ownerTownId); + groups.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: ot ? ot.owner_id : null, units: g.units, research: U.researchLevels(db, g.ownerTownId) }); + } + return groups; +} + +// Write a defending group's units back after the battle. +function writeGroup(db, hostTownId, group, units) { + const keys = new Set(Object.keys(group.units).concat(Object.keys(units))); + for (const k of keys) { + if (group.id === 'home') U.setHomeUnit(db, hostTownId, k, units[k] || 0); + else U.setStationed(db, hostTownId, group.ownerTownId, k, units[k] || 0); + } +} + +function addPoints(db, operatorId, column, v) { + if (!operatorId || !(v > 0)) return; + db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 0, 0) ON CONFLICT (operator_id) DO NOTHING', operatorId); + db.run('UPDATE operator_stats SET ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' = ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' + ? WHERE operator_id = ?', v, operatorId); +} + +const sumValues = (list) => list.reduce((acc, u) => U.sumInto(acc, u), {}); + +// Survivors drive home (with loot). No survivors, no movement. +function sendHome(ctx, mv, survivors, cargo) { + const { db } = ctx; + if (U.isEmpty(survivors)) return null; + const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId); + if (!dest) return null; + return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: {} }); +} + +function arrive(ctx, mv, ev) { + const { db } = ctx; + const now = ev.dueAt; + const world = loadWorld(db, mv.worldId); + if (!mv.toTownId) return arriveSite(ctx, mv, now, world); + const targetRow = db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId); + if (!targetRow) return bounce(ctx, mv, now, 'target_gone'); + const attackerOp = U.getOperator(db, mv.ownerId); + const defOp = U.getOperator(db, targetRow.owner_id); + if (defOp.id === attackerOp.id) return bounce(ctx, mv, now, 'own_town'); + if (mv.type !== 'scan') { + if (R.isProtected(defOp.protection_until, now)) return bounce(ctx, mv, now, 'protected', { until: defOp.protection_until }); + if (U.pactBlocks(db, attackerOp.id, defOp.id)) return bounce(ctx, mv, now, 'pact'); + } + const target = loadTown(db, targetRow.id); + settle(db, target, now); + const online = P.online(target, now); + const groups = defenderGroups(db, target); + const active = online ? groups : []; + const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null; + + if (mv.type === 'scan') return resolveScanOnTown(ctx, mv, now, { target, targetRow, defOp, attackerOp, origin, groups, active, online }); + + const kind = mv.type === 'raid' ? 'raid' : 'attack'; + const fwLevel = target.buildings.firewall ? target.buildings.firewall.level : 0; + const b = R.resolveBattle({ + kind, attackers: { units: mv.units, research: mv.extra.research || {} }, + defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: fwLevel, + }); + const win = b.attackerWins; + + // ---- defenders: losses (a full attack lost by the defender wipes everything in the POP, offline units included) + const wipe = b.defenderLossFraction >= 1; + const groupReports = []; + let defenderLost = {}; + for (const g of groups) { + const res = b.defenders.find((d) => d.id === g.id); + let survivors, lost; + if (wipe) { survivors = {}; lost = g.units; } + else if (res) { survivors = res.survivors; lost = res.lost; } + else { survivors = g.units; lost = {}; } // offline and not wiped: untouched + writeGroup(db, target.id, g, survivors); + U.sumInto(defenderLost, lost); + groupReports.push({ id: g.id, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors, share: res ? res.share : 0, offline: !res }); + } + const survivorsAtt = Object.assign({}, b.attacker.survivors); + + // ---- loot + let loot = { fiber: 0, hardware: 0, capital: 0 }; + let hidden = 0; + if (win) { + hidden = kind === 'raid' ? R.cacheFraction(target.buildings.rack_hall ? target.buildings.rack_hall.level : 0) : 0; + const avail = {}; + for (const r of D.RESOURCES) avail[r] = target.res[r] * (1 - hidden); + loot = R.lootSplit(R.carryOf(survivorsAtt), avail); + for (const r of D.RESOURCES) target.res[r] -= loot[r]; + db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', target.res.fiber, target.res.hardware, target.res.capital, target.id); + } + + // ---- siege: exploit kits tear levels off the chosen building + let siege = null; + if (win && mv.type !== 'raid' && mv.extra.target) { + const levels = R.siegeLevels(survivorsAtt.exploit_kit || 0); + const cur = levels > 0 ? target.buildings[mv.extra.target] : null; + if (cur && cur.level > 0) { + const to = Math.max(0, cur.level - levels); + db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', to, target.id, mv.extra.target); + siege = { key: mv.extra.target, type: cur.type, from: cur.level, to }; + } + } + + // ---- takeover + let takeover = null; + let captured = false; + if (mv.type === 'takeover' && win && (survivorsAtt[D.EXPANSION.conquestUnit] || 0) > 0) { + const defTowns = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n; + const block = R.takeoverBlock(!!targetRow.is_capital, defTowns); + const gate = R.footprintGate(U.operatorTowns(db, attackerOp.id).length, U.operatorFootprint(db, attackerOp.id, now)); + takeover = { attempted: true, blocked: block === 'last_pop' ? 'last_pop' : (gate.ok ? null : 'footprint'), capital: block === 'capital', loyaltyBefore: target.loyalty, loyaltyAfter: target.loyalty, drop: 0, captured: false }; + if (takeover.blocked === null) { + const rand = R.rng(R.hash(world.seed, mv.id, 0x7a11))(); + const drop = R.loyaltyDrop(rand); + const after = Math.max(0, target.loyalty - drop); + const left = survivorsAtt[D.EXPANSION.conquestUnit] - 1; // the M&A team that did the talking is used up + if (left > 0) survivorsAtt[D.EXPANSION.conquestUnit] = left; else delete survivorsAtt[D.EXPANSION.conquestUnit]; + db.run('UPDATE towns SET loyalty = ?, loyalty_at = ? WHERE id = ?', after, now, target.id); + Object.assign(takeover, { drop, loyaltyAfter: after }); + if (after <= 0 && block === null) { transferTown(ctx, target, attackerOp, defOp, now); captured = true; takeover.captured = true; } + } + } + + // ---- battle points + const attLost = b.attacker.lost; + addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost)); + const defPts = R.battlePoints(attLost); + for (const g of groupReports) addPoints(db, g.ownerOpId, 'defense', defPts * g.share); + + P.reschedule(ctx, target.id, now); + const ret = sendHome(ctx, mv, survivorsAtt, loot); + + // ---- reports + const data = { + type: mv.type, outcome: win ? 'attacker_won' : 'defender_won', arrivedAt: now, + attacker: { operator: opBrief(attackerOp), town: townBrief(origin), units: { sent: mv.units, lost: attLost, survivors: survivorsAtt } }, + defender: { operator: opBrief(defOp), town: townBrief(target), online, groups: groupReports.map((g) => ({ ownerTownId: g.ownerTownId, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) }, + power: { attack: b.A, defence: b.D, defenceRaw: b.defenceRaw, firewallLevel: fwLevel, effectiveFirewall: b.effectiveFirewall }, + loot, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null, + }; + const summary = { type: mv.type, outcome: data.outcome, attacker: opBrief(attackerOp), defender: opBrief(defOp), target: townBrief(target), loot, captured }; + const recipients = [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }, { userId: U.userOfOperator(db, defOp.id), role: 'defender' }]; + for (const g of groupReports) if (g.id !== 'home' && g.ownerOpId) recipients.push({ userId: U.userOfOperator(db, g.ownerOpId), role: 'reinforcer' }); + createReport(ctx, { worldId: mv.worldId, type: mv.type, now, summary, data, recipients }); +} + +// ---- scans +function resolveScanOnTown(ctx, mv, now, s) { + const { db } = ctx; + const { target, defOp, attackerOp, origin, groups, active, online } = s; + const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research); + let sd = 0; + for (const g of active) sd += R.scanStrength(g.units.port_scanner || 0, g.research); + const res = R.resolveScan(sa, sd); + const loss = R.applyLoss(mv.units, res.lossFraction); + let intel = null; + if (res.success) { + intel = { + detail: res.detail, online, + units: { home: U.homeUnits(db, target.id), stationed: groups.filter((g) => g.id !== 'home').map((g) => ({ ownerTownId: g.ownerTownId, units: g.units })) }, + resources: { fiber: target.res.fiber, hardware: target.res.hardware, capital: target.res.capital }, + }; + if (res.detail === 'full') { + intel.buildings = Object.keys(target.buildings).map((k) => ({ key: k, type: target.buildings[k].type, level: target.buildings[k].level })); + intel.loyalty = target.loyalty; + intel.outgoing = db.all("SELECT id, type, to_x, to_y, arrive_at FROM movements WHERE from_town_id = ? AND status = 'out' AND type != 'return' ORDER BY arrive_at, id", target.id) + .map((m) => ({ type: m.type, to: { x: m.to_x, y: m.to_y }, arriveAt: m.arrive_at })); + } + } + const aData = { success: res.success, detail: res.detail, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, strength: { attacker: sa, defender: sd }, target: townBrief(target), operator: opBrief(defOp), intel }; + createReport(ctx, { + worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, target: townBrief(target), operator: opBrief(defOp) }, + data: aData, recipients: [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }], + }); + const dData = { identityRevealed: res.identityRevealed, target: townBrief(target), by: res.identityRevealed ? { operator: opBrief(attackerOp), town: townBrief(origin) } : null }; + createReport(ctx, { + worldId: mv.worldId, type: 'scan_detected', now, summary: { identityRevealed: res.identityRevealed, target: townBrief(target), by: dData.by && dData.by.operator }, + data: dData, recipients: [{ userId: U.userOfOperator(db, defOp.id), role: 'defender' }], + }); + sendHome(ctx, mv, loss.survivors, {}); +} + +// ---- incumbent sites (NPC): static defence, no losses for the site, never attack +function arriveSite(ctx, mv, now, world) { + const { db } = ctx; + const { x, y } = mv.to; + const tile = R.tileAt(world.seed, world.map_radius, x, y); + if (tile.type !== 'incumbent' || (mv.type !== 'scan' && mv.type !== 'attack')) return bounce(ctx, mv, now, 'invalid_target'); + const attackerOp = U.getOperator(db, mv.ownerId); + const ageDays = Math.max(0, (now - world.start_at) / DAY * world.speed); + const staticDef = R.incumbentDefence(world.seed, x, y, ageDays); + const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null; + const site = { x, y, type: 'incumbent' }; + const uid = U.userOfOperator(db, attackerOp.id); + + if (mv.type === 'scan') { + const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research); + const res = R.resolveScan(sa, D.INCUMBENT.scanStrength); + const loss = R.applyLoss(mv.units, res.lossFraction); + const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, attackerOp.id); + const intel = res.success ? { defence: staticDef, bonusAvailable: !taken, hardwareBonus: D.INCUMBENT.hardwareBonus } : null; + createReport(ctx, { + worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site }, + data: { success: res.success, detail: res.detail, site, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel }, + recipients: [{ userId: uid, role: 'attacker' }], + }); + sendHome(ctx, mv, loss.survivors, {}); + return; + } + + const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef }); + const survivors = Object.assign({}, b.attacker.survivors); + let bonus = null; + const cargo = {}; + if (b.attackerWins) { + const first = db.run('INSERT OR IGNORE INTO incumbent_takes (world_id, x, y, operator_id, taken_at) VALUES (?, ?, ?, ?, ?)', world.id, x, y, attackerOp.id, now); + if (first.changes) { + cargo.hardware = D.INCUMBENT.hardwareBonus; + bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) }; + } + } + const ret = sendHome(ctx, mv, survivors, cargo); + createReport(ctx, { + worldId: mv.worldId, type: 'incumbent', now, + summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus }, + data: { + outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site, origin: townBrief(origin), + attacker: { operator: opBrief(attackerOp), units: { sent: mv.units, lost: b.attacker.lost, survivors } }, + power: { attack: b.A, defence: b.D }, bonus, returnMovementId: ret ? ret.id : null, + }, + recipients: [{ userId: uid, role: 'attacker' }], + }); +} + +// A takeover completed: the POP changes owner. Pending work of the old owner stops, reinforcements of the old owner +// standing elsewhere are re-homed, the new owner starts at conqueredLoyalty. +function transferTown(ctx, town, newOp, oldOp, now) { + const { db } = ctx; + db.run('UPDATE towns SET owner_id = ?, is_capital = 0, loyalty = ?, loyalty_at = ? WHERE id = ?', newOp.id, D.EXPANSION.conqueredLoyalty, now, town.id); + db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type IN ('trainDone', 'researchDone') AND status = 'pending'", now, town.id); + db.run("UPDATE events SET payload = json_set(payload, '$.userId', ?) WHERE town_id = ? AND type = 'buildDone' AND status = 'pending'", U.userOfOperator(db, newOp.id), town.id); + // units of the old owner that were hosted here (should be dead already) or that belonged to this POP and stand elsewhere + const home = U.homeTownFor(db, oldOp.id); + for (const g of U.awayGroups(db, town.id)) { + db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', g.hostTownId, town.id); + if (!home) continue; + if (home.id === g.hostTownId) U.addHome(db, home.id, g.units); else U.addStationed(db, g.hostTownId, home.id, g.units); + } + db.run('DELETE FROM town_power WHERE town_id = ?', town.id); + const oldUser = U.userOfOperator(db, oldOp.id), newUser = U.userOfOperator(db, newOp.id); + if (oldUser) ctx.notify(oldUser, town.worldId, 'town_lost', { townId: town.id, name: town.name, by: opBrief(newOp) }); + if (newUser) ctx.notify(newUser, town.worldId, 'town_gained', { townId: town.id, name: town.name }); +} + +module.exports = { arrive, defenderGroups, transferTown }; diff --git a/server/military/ctx.js b/server/military/ctx.js new file mode 100644 index 0000000..d84ec88 --- /dev/null +++ b/server/military/ctx.js @@ -0,0 +1,8 @@ +'use strict'; +/* Commands get { db, clock, now, scheduler }, events additionally { enqueue, notify }. Military code uses the event shape + * everywhere, so command entry points call `ctxOf(ctx)` first (idempotent). */ +module.exports = function ctxOf(ctx) { + if (ctx.enqueue && ctx.notify) return ctx; + const s = ctx.scheduler; + return Object.assign({}, ctx, { enqueue: (e) => s.enqueue(e), notify: (u, w, t, p) => s.notify(u, w, t, p) }); +}; diff --git a/server/military/movements.js b/server/military/movements.js new file mode 100644 index 0000000..088a758 --- /dev/null +++ b/server/military/movements.js @@ -0,0 +1,58 @@ +'use strict'; +/* + * Movement rows: creating them (together with their arrive/return event), reading them, return legs. + * A movement is `out` until its event runs; a recall turns it into `recalled` and creates a return movement. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); + +const j = (s) => JSON.parse(s || '{}'); + +function fromRow(r) { + if (!r) return null; + return { + id: r.id, worldId: r.world_id, ownerId: r.owner_id, type: r.type, fromTownId: r.from_town_id, toTownId: r.to_town_id, + from: { x: r.from_x, y: r.from_y }, to: { x: r.to_x, y: r.to_y }, units: j(r.units), cargo: j(r.cargo), + departAt: r.depart_at, arriveAt: r.arrive_at, status: r.status, eventId: r.event_id, parentId: r.parent_id, extra: j(r.extra), + }; +} + +function getMovement(db, id) { return fromRow(db.get('SELECT * FROM movements WHERE id = ?', id)); } + +// Insert a movement and the event that will resolve it ('arrive' for everything but returns, 'return' for returns). +// o: { worldId, ownerId, type, fromTownId, toTownId, from:{x,y}, to:{x,y}, units, cargo, departAt, arriveAt, parentId, extra } +function insertMovement(ctx, o) { + const { db } = ctx; + const r = db.run(`INSERT INTO movements (world_id, owner_id, type, from_town_id, to_town_id, from_x, from_y, to_x, to_y, units, cargo, + depart_at, arrive_at, status, parent_id, extra, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'out', ?, ?, ?)`, + o.worldId, o.ownerId, o.type, o.fromTownId || null, o.toTownId || null, o.from.x, o.from.y, o.to.x, o.to.y, + JSON.stringify(o.units || {}), JSON.stringify(o.cargo || {}), o.departAt, Math.round(o.arriveAt), o.parentId || null, JSON.stringify(o.extra || {}), ctx.now); + const id = Number(r.lastInsertRowid); + const eventId = ctx.enqueue({ worldId: o.worldId, dueAt: o.arriveAt, type: o.type === 'return' ? 'return' : 'arrive', townId: o.toTownId || null, payload: { movementId: id } }); + db.run('UPDATE movements SET event_id = ? WHERE id = ?', eventId, id); + return getMovement(db, id); +} + +// Units (and cargo) heading home from where they are. `fromTown` may be null (an incumbent site or an empty tile); +// `at` = where they are ({x,y}); `to` = the destination POP row. arriveAt defaults to now + travel time. +function launchReturn(ctx, o) { + const to = o.to; + const dist = R.distance(o.at.x, o.at.y, to.x, to.y); + const world = ctx.db.get('SELECT speed FROM worlds WHERE id = ?', o.worldId); + const arriveAt = o.arriveAt !== undefined ? o.arriveAt : ctx.now + R.movementMs(dist, o.units, world.speed); + return insertMovement(ctx, { + worldId: o.worldId, ownerId: o.ownerId, type: 'return', fromTownId: o.fromTownId || null, toTownId: to.id, + from: o.at, to: { x: to.x, y: to.y }, units: o.units, cargo: o.cargo, departAt: ctx.now, arriveAt, parentId: o.parentId, extra: o.extra, + }); +} + +// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports. +function activeLinks(db, townId) { + return db.get(`SELECT COUNT(*) AS n FROM movements WHERE status = 'out' AND + ((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n; +} + +// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }). +const hooks = { transportArrived: [] }; + +module.exports = { fromRow, getMovement, insertMovement, launchReturn, activeLinks, hooks }; diff --git a/server/military/power.js b/server/military/power.js new file mode 100644 index 0000000..69b36d3 --- /dev/null +++ b/server/military/power.js @@ -0,0 +1,109 @@ +'use strict'; +/* + * Unit power: while the battery is empty and net power is negative, the units in a POP are offline (no attack or + * defence value, cannot move). After MILITARY.decommissionHours (divided by world speed) offline, the most expensive + * units are decommissioned until the draw fits the output again. + * + * Whether units are online right now is always computed from the lazy battery value (`online`), so reads and combat + * never depend on an event having run. The `powerCheck` event exists for the side effects: the "units offline" + * notification and the decommission. `reschedule` is idempotent: it cancels the pending check of the POP and enqueues + * the one that is correct for the current rates. Call it after ANYTHING that changes unit draw or building levels of a + * POP (units arriving or leaving, losses, buildings finishing or being damaged). + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { loadTown, settle } = require('../state'); +const U = require('./units'); + +const EPS = D.MILITARY.batteryEpsilon; + +// Are the units in this town online at `now`? (the town object may be unsettled: resourcesAt projects it) +function online(town, now) { + const c = R.resourcesAt(town, now); + return !(c.amounts.battery <= EPS && c.rates.powerNet < 0); +} + +// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }. +function drawingUnits(db, townId) { + const out = U.homeUnits(db, townId); + for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units); + return out; +} + +function reschedule(ctx, townId, now) { + const { db } = ctx; + db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type = 'powerCheck' AND status = 'pending'", now, townId); + const town = loadTown(db, townId); + if (!town) return; + if (!(town.unitDraw > 0)) { db.run('DELETE FROM town_power WHERE town_id = ?', townId); return; } + if (online(town, now)) { + db.run('DELETE FROM town_power WHERE town_id = ?', townId); + const at = R.batteryEmptyAt(town, now); + if (at !== null) ctx.enqueue({ worldId: town.worldId, dueAt: at + 1, type: 'powerCheck', townId, payload: { townId } }); + return; + } + let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', townId); + if (!row || row.offline_since === null) { + db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', townId, now); + row = { offline_since: now }; + } + ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } }); +} + +// Decommission the most expensive units (home first, then reinforcements) until the draw fits. The town is settled. +function decommission(ctx, town, now) { + const { db } = ctx; + const units = drawingUnits(db, town.id); + const rates = R.ratesPerHour(Object.assign({}, town, { unitDraw: 0 })); + const plan = R.decommissionPlan(units, rates.powerOut - rates.powerDraw); + const removed = {}; + const byOwner = new Map(); // userId -> { unit: n }, who lost units + const note = (userId, unit, n) => { if (!byOwner.has(userId)) byOwner.set(userId, {}); const o = byOwner.get(userId); o[unit] = (o[unit] || 0) + n; }; + const ownerUser = U.userOfOperator(db, town.ownerId); + for (const unit of Object.keys(plan)) { + let left = plan[unit]; + const home = U.homeUnits(db, town.id)[unit] || 0; + const fromHome = Math.min(home, left); + if (fromHome > 0) { U.setHomeUnit(db, town.id, unit, home - fromHome); left -= fromHome; note(ownerUser, unit, fromHome); } + for (const g of U.hostedGroups(db, town.id)) { + if (left <= 0) break; + const have = g.units[unit] || 0; + const n = Math.min(have, left); + if (n > 0) { + U.setStationed(db, town.id, g.ownerTownId, unit, have - n); left -= n; + const ot = db.get('SELECT t.owner_id AS oid FROM towns t WHERE t.id = ?', g.ownerTownId); + note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n); + } + } + removed[unit] = plan[unit] - left; + } + for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost }); + return removed; +} + +// Event handler: payload { townId }. Settles the POP to the due time and acts on what it finds. +function powerCheck(ctx, ev) { + const { db } = ctx; + const town = loadTown(db, ev.townId); + if (!town) return; + settle(db, town, ev.dueAt); + if (town.unitDraw > 0 && !online(town, ev.dueAt)) { + let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', town.id); + if (!row || row.offline_since === null) { + db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', town.id, ev.dueAt); + row = { offline_since: ev.dueAt }; + const uid = U.userOfOperator(db, town.ownerId); + if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId: town.id, since: ev.dueAt }); + } + if (ev.dueAt >= row.offline_since + R.decommissionMs(town.speed)) { + const removed = decommission(ctx, town, ev.dueAt); + if (!Object.keys(removed).some((k) => removed[k] > 0)) { // rounding noise, nothing to remove: stand down, never loop + db.run('DELETE FROM town_power WHERE town_id = ?', town.id); + return; + } + } + } + reschedule(ctx, town.id, ev.dueAt); +} + +module.exports = { online, drawingUnits, reschedule, decommission, powerCheck }; diff --git a/server/military/reports.js b/server/military/reports.js new file mode 100644 index 0000000..8f31ce6 --- /dev/null +++ b/server/military/reports.js @@ -0,0 +1,32 @@ +'use strict'; +/* + * Reports: one `reports` row shared by every participant (`report_recipients`, with a per-user read flag). Kept + * MILITARY.reportRetentionMs (real time); the `reportCleanup` event deletes expired ones and re-arms itself only while + * reports remain. + */ +const D = require('../../public/js/data.js'); + +// o: { worldId, type, now, summary, data, recipients: [{ userId, role }] } -> report id +function createReport(ctx, o) { + const { db } = ctx; + const r = db.run('INSERT INTO reports (world_id, type, created_at, expires_at, summary, data) VALUES (?, ?, ?, ?, ?, ?)', + o.worldId, o.type, o.now, o.now + D.MILITARY.reportRetentionMs, JSON.stringify(o.summary || {}), JSON.stringify(o.data || {})); + const id = Number(r.lastInsertRowid); + const seen = new Set(); + for (const rc of o.recipients) { + if (!rc.userId || seen.has(rc.userId)) continue; + seen.add(rc.userId); + db.run('INSERT INTO report_recipients (report_id, user_id, role) VALUES (?, ?, ?)', id, rc.userId, rc.role); + ctx.notify(rc.userId, o.worldId, 'report', { reportId: id, type: o.type, role: rc.role }); + } + ensureCleanup(ctx, o.worldId, o.now); + return id; +} + +function ensureCleanup(ctx, worldId, now) { + const { db } = ctx; + const pending = db.get("SELECT 1 AS x FROM events WHERE type = 'reportCleanup' AND world_id = ? AND status = 'pending' LIMIT 1", worldId); + if (!pending) ctx.enqueue({ worldId, dueAt: now + D.MILITARY.reportRetentionMs, type: 'reportCleanup', payload: { worldId } }); +} + +module.exports = { createReport, ensureCleanup }; diff --git a/server/military/units.js b/server/military/units.js new file mode 100644 index 0000000..b4cc8e0 --- /dev/null +++ b/server/military/units.js @@ -0,0 +1,153 @@ +'use strict'; +/* + * Data helpers for units, reinforcements, research and operators, shared by the military commands, events and views. + * Units are always { unitId: count }. Always settle() a town before changing its units: unit power draw is part of its + * rates (state.unitDraw reads town_units and stationed). + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { loadTown } = require('../state'); + +function homeUnits(db, townId) { + const out = {}; + for (const r of db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) out[r.unit] = r.count; + return out; +} + +function setHomeUnit(db, townId, unit, count) { + if (count > 0) db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, unit, count); + else db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', townId, unit); +} + +function addHome(db, townId, units) { + const cur = homeUnits(db, townId); + for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, (cur[k] || 0) + units[k]); +} + +// Removes `units` from home; throws not_enough_units when the town does not have them (callers check first). +function removeHome(db, townId, units) { + const cur = homeUnits(db, townId); + for (const k of Object.keys(units || {})) { + if (!(units[k] > 0)) continue; + if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] }); + } + for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, cur[k] - units[k]); +} + +// Reinforcements standing in a host town: [{ ownerTownId, units }] grouped by the POP they belong to. +function hostedGroups(db, hostTownId) { + const by = new Map(); + for (const r of db.all('SELECT owner_town_id, unit, count FROM stationed WHERE host_town_id = ? ORDER BY owner_town_id, unit', hostTownId)) { + if (!by.has(r.owner_town_id)) by.set(r.owner_town_id, {}); + by.get(r.owner_town_id)[r.unit] = r.count; + } + return Array.from(by, ([ownerTownId, units]) => ({ ownerTownId, units })); +} + +// Units of owner_town_id's operator standing in other POPs: [{ hostTownId, units }]. +function awayGroups(db, ownerTownId) { + const by = new Map(); + for (const r of db.all('SELECT host_town_id, unit, count FROM stationed WHERE owner_town_id = ? ORDER BY host_town_id, unit', ownerTownId)) { + if (!by.has(r.host_town_id)) by.set(r.host_town_id, {}); + by.get(r.host_town_id)[r.unit] = r.count; + } + return Array.from(by, ([hostTownId, units]) => ({ hostTownId, units })); +} + +function stationedOf(db, hostTownId, ownerTownId) { + const out = {}; + for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', hostTownId, ownerTownId)) out[r.unit] = r.count; + return out; +} + +function setStationed(db, hostTownId, ownerTownId, unit, count) { + if (count > 0) db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (host_town_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', hostTownId, ownerTownId, unit, count); + else db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ? AND unit = ?', hostTownId, ownerTownId, unit); +} + +function addStationed(db, hostTownId, ownerTownId, units) { + const cur = stationedOf(db, hostTownId, ownerTownId); + for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, (cur[k] || 0) + units[k]); +} + +function removeStationed(db, hostTownId, ownerTownId, units) { + const cur = stationedOf(db, hostTownId, ownerTownId); + for (const k of Object.keys(units || {})) { + if (!(units[k] > 0)) continue; + if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] }); + } + for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, cur[k] - units[k]); +} + +// Research levels of a POP as { 'unit:stat': level }. +function researchLevels(db, townId) { + const out = {}; + for (const r of db.all('SELECT unit, stat, level FROM town_research WHERE town_id = ?', townId)) out[R.researchKey(r.unit, r.stat)] = r.level; + return out; +} + +// Snapshot of the research of `townId` for the unit types in `units` (stored on a movement at departure). +function researchSnapshot(db, townId, units) { + const all = researchLevels(db, townId); + const out = {}; + for (const u of Object.keys(units)) for (const stat of D.RESEARCH.stats) { const k = R.researchKey(u, stat); if (all[k]) out[k] = all[k]; } + return out; +} + +// Validates and normalises the `units` object of a request: known ids, whole numbers >= 0, zeros dropped. +function cleanUnits(raw) { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new GameError('validation_failed', { errors: [{ path: 'units', message: 'must be an object' }] }); + const out = {}; + for (const k of Object.keys(raw)) { + if (!R.unitDef(k)) throw new GameError('unknown_unit', { unit: k }); + const n = raw[k]; + if (!Number.isInteger(n) || n < 0 || n > 1e7) throw new GameError('validation_failed', { errors: [{ path: 'units.' + k, message: 'must be a whole number >= 0' }] }); + if (n > 0) out[k] = n; + } + return out; +} + +const sumInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; }; +const isEmpty = (units) => !Object.keys(units || {}).some((k) => units[k] > 0); + +// ---- operators +function getOperator(db, id) { return db.get('SELECT * FROM operators WHERE id = ?', id); } +function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; } +function operatorTowns(db, operatorId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY id', operatorId); } + +// Footprint over all POPs of the operator at `now` (each POP's footprint keeps growing from its buildings). +function operatorFootprint(db, operatorId, now) { + let sum = 0; + for (const t of operatorTowns(db, operatorId)) sum += R.footprintAt(loadTown(db, t.id), now); + return sum; +} + +function incumbentTakes(db, operatorId) { return db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', operatorId).n; } +function researchBonusOf(db, operatorId) { return R.researchSpeedBonus(incumbentTakes(db, operatorId)); } + +// Where do units of `operatorId` go when their origin POP is gone: the capital, else the oldest POP; null if none. +function homeTownFor(db, operatorId, preferTownId) { + if (preferTownId) { + const t = db.get('SELECT * FROM towns WHERE id = ? AND owner_id = ?', preferTownId, operatorId); + if (t) return t; + } + return db.get('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id LIMIT 1', operatorId) || null; +} + +// May `fromOp` stand units in a POP of `toOp`? Own POPs, same alliance, confederation. +function mayReinforce(db, fromOp, toOp) { + if (fromOp === toOp) return true; + return require('../alliances').confederated(db, fromOp, toOp); +} +// Pacts (same alliance, NAP, confederation) forbid hostile movements between the partners. +function pactBlocks(db, fromOp, toOp) { + if (fromOp === toOp) return false; + return require('../alliances').pactPartners(db, fromOp, toOp); +} + +module.exports = { + homeUnits, setHomeUnit, addHome, removeHome, hostedGroups, awayGroups, stationedOf, setStationed, addStationed, removeStationed, + researchLevels, researchSnapshot, cleanUnits, sumInto, isEmpty, + getOperator, userOfOperator, operatorTowns, operatorFootprint, incumbentTakes, researchBonusOf, homeTownFor, mayReinforce, pactBlocks, +}; diff --git a/server/military/views.js b/server/military/views.js new file mode 100644 index 0000000..c4c90fa --- /dev/null +++ b/server/military/views.js @@ -0,0 +1,155 @@ +'use strict'; +/* + * Read models for the military stage: the military part of GET /towns/:id, the movements list with incoming warnings, + * reports, and tile info for the send dialog. Reads catch the event queue up first (via `fresh`) and never write. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { loadWorld } = require('../state'); +const U = require('./units'); +const P = require('./power'); + +const j = (s) => JSON.parse(s || '{}'); + +function townNames(db, ids) { + const out = new Map(); + for (const id of ids) { + if (!id || out.has(id)) continue; + const t = db.get('SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?', id); + out.set(id, t ? { id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital, owner: { id: t.oid, name: t.oname, asNumber: t.asn } } : null); + } + return out; +} + +// What the owner of a movement sees. +function ownerView(m, names) { + const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null; + const extra = j(m.extra); + return { + id: m.id, type: m.type, status: m.status, ownerId: m.owner_id, + from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null }, + to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null }, + units: j(m.units), cargo: j(m.cargo), departAt: m.depart_at, arriveAt: m.arrive_at, + recallableUntil: m.type === 'return' ? null : m.depart_at + D.MILITARY.recallWindowMs, + target: extra.target || null, parentId: m.parent_id, + }; +} + +// What the target of somebody else's movement sees: origin and ETA, never the type, units or cargo. +function incomingView(m, names) { + const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null; + return { + id: m.id, type: 'unknown', status: m.status, incoming: true, + from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null, owner: f ? f.owner : null }, + to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null }, + departAt: m.depart_at, arriveAt: m.arrive_at, + }; +} + +// Active movements: the operator's own (outgoing legs, returns, transports) and other operators' movements heading for +// the operator's POPs. `townId` limits both to one POP. +function movementLists(db, operatorId, townId) { + const own = db.all(`SELECT * FROM movements WHERE owner_id = ? AND status = 'out' ${townId ? 'AND (from_town_id = ? OR to_town_id = ?)' : ''} ORDER BY arrive_at, id LIMIT ?`, + ...(townId ? [operatorId, townId, townId, D.MILITARY.maxLists] : [operatorId, D.MILITARY.maxLists])); + const inc = db.all(`SELECT m.* FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id = ? AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return' + ${townId ? 'AND m.to_town_id = ?' : ''} ORDER BY m.arrive_at, m.id LIMIT ?`, + ...(townId ? [operatorId, operatorId, townId, D.MILITARY.maxLists] : [operatorId, operatorId, D.MILITARY.maxLists])); + const names = townNames(db, own.concat(inc).flatMap((m) => [m.from_town_id, m.to_town_id])); + return { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) }; +} + +// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller). +function townMilitary(db, t, now, world) { + const home = U.homeUnits(db, t.id); + const online = P.online(t, now); + const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId))); + const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units })); + const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units })); + const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id) + .map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; }); + const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id); + const rp = rq ? JSON.parse(rq.payload) : null; + const bonus = U.researchBonusOf(db, t.ownerId); + const trainable = D.UNIT_ORDER.map((unit) => { + const def = D.UNITS[unit]; + const missing = R.unitMissing(t, unit); + return { unit, building: def.building, role: def.role, cost: R.unitCost(unit, 1), timeMs: R.trainTimeMs(unit, 1, t.buildings[def.building] ? t.buildings[def.building].level : 0, world.speed), missing, locked: missing.length > 0 }; + }); + const offline = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', t.id); + const op = U.getOperator(db, t.ownerId); + const links = R.transportLinks(t); + return { + units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away }, + training, trainable, + research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel }, + transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: D.TRANSPORT.capacityPerLink }, + movements: movementLists(db, t.ownerId, t.id), + protectionUntil: op.protection_until, + }; +} + +function createMilitaryQueries({ db, clock, scheduler }) { + const fresh = () => { scheduler.runDue(); return clock.now(); }; + + function operatorFor(userId, worldId) { + const op = worldId ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId); + if (!op) throw new GameError('not_found', { what: 'operator' }); + return op; + } + + function movements(userId, { worldId }) { + const now = fresh(); + const op = operatorFor(userId, worldId); + return Object.assign({ serverTime: now }, movementLists(db, op.id, null)); + } + + function reports(userId, { after, limit, unread }) { + const now = fresh(); + const n = limit || 25; + const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id + WHERE rr.user_id = ? ${after ? 'AND r.id < ?' : ''} ${unread ? 'AND rr.read_at IS NULL' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [userId, after, n + 1] : [userId, n + 1])); + const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, role: r.role, read: r.read_at !== null, summary: j(r.summary) })); + const unreadCount = db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NULL', userId).n; + return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null, unread: unreadCount }; + } + + function report(userId, id) { + const now = fresh(); + const r = db.get(`SELECT r.*, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? AND r.id = ?`, userId, id); + if (!r) throw new GameError('not_found', { what: 'report' }); + return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, role: r.role, read: r.read_at !== null, summary: j(r.summary), data: j(r.data) } }; + } + + // Public information about a tile, for the send dialog: what is there, who owns it, how far it is from each of my POPs, + // whether I could found a POP there. + function tileInfo(userId, { worldId, x, y }) { + const now = fresh(); + const op = operatorFor(userId, worldId); + const world = loadWorld(db, op.world_id); + const tile = R.tileAt(world.seed, world.map_radius, x, y); + if (tile.type === 'void') throw new GameError('not_found', { what: 'tile' }); + const row = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y); + const mine = U.operatorTowns(db, op.id); + const out = { serverTime: now, x, y, type: row ? 'pop' : tile.type, bonus: tile.bonus || null, distances: mine.map((t) => ({ townId: t.id, distance: R.distance(t.x, t.y, x, y) })) }; + if (row) { + const o = U.getOperator(db, row.owner_id); + out.town = { id: row.id, name: row.name, isCapital: !!row.is_capital, owner: { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protected: R.isProtected(o.protection_until, now), protectionUntil: o.protection_until }, mine: o.id === op.id }; + } + if (tile.type === 'incumbent') { + const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, op.id); + out.incumbent = { takenByYou: taken, hardwareBonus: taken ? 0 : D.INCUMBENT.hardwareBonus }; + } + const fp = U.operatorFootprint(db, op.id, now); + const gate = R.footprintGate(mine.length, fp); + let nearest = Infinity; + for (const t of mine) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y)); + const sc = R.settleCheck({ tileType: tile.type, occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp }); + out.settle = { possible: sc.ok, code: sc.ok ? null : sc.code, footprint: fp, footprintNeeded: gate.need, maxDistance: D.EXPANSION.maxDistance }; + return out; + } + + return { movements, reports, report, tileInfo }; +} + +module.exports = { townMilitary, movementLists, createMilitaryQueries }; diff --git a/server/queries.js b/server/queries.js index 4c07c45..80135b3 100644 --- a/server/queries.js +++ b/server/queries.js @@ -7,6 +7,7 @@ const R = require('../public/js/rules.js'); const D = require('../public/js/data.js'); const { GameError } = require('./errors'); const { loadWorld, townFromRow, pendingBuilds } = require('./state'); +const { allianceBrief } = require('./alliances'); function createQueries({ db, clock, scheduler }) { const fresh = () => { scheduler.runDue(); return clock.now(); }; @@ -23,7 +24,7 @@ function createQueries({ db, clock, scheduler }) { const world = loadWorld(db, o.world_id); const towns = db.all('SELECT id, name, x, y, is_capital FROM towns WHERE owner_id = ? ORDER BY id', o.id) .map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital })); - return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protectionUntil: o.protection_until, world: worldView(world), towns }; + return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, alliance: allianceBrief(db, o.alliance_id), protectionUntil: o.protection_until, world: worldView(world), towns }; }); return { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators }; } @@ -68,6 +69,7 @@ function createQueries({ db, clock, scheduler }) { loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t), resources, power, buildings, queue, queueSlots: R.queueSlots(t), bonus: t.bonus, + military: require('./military/views').townMilitary(db, t, now, world), }, }; } @@ -93,11 +95,11 @@ function createQueries({ db, clock, scheduler }) { if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null }); } } - const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, o.protection_until AS prot - FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`, + const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, a.tag AS atag, a.name AS aname, o.protection_until AS prot + FROM towns t JOIN operators o ON o.id = t.owner_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`, world.id, x0, x1, y0, y1).map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital, - owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, protected: t.prot > now }, + owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, alliance: t.ally ? { id: t.ally, tag: t.atag, name: t.aname } : null, protected: t.prot > now }, })); return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns }; } diff --git a/server/routes/alliances.js b/server/routes/alliances.js new file mode 100644 index 0000000..5274801 --- /dev/null +++ b/server/routes/alliances.js @@ -0,0 +1,140 @@ +'use strict'; +/* Alliances, invites, pinned notes and diplomacy (stage 5). Fixed paths are registered before /alliances/:id. */ +const { reply } = require('../http'); +const { GameError } = require('../errors'); +const { createSocialQueries } = require('../socialQueries'); +const D = require('../../public/js/data.js'); + +const S = D.SOCIAL; +const int1 = { type: 'integer', minimum: 1 }; +const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }; +const worldQ = { worldId: int1 }; + +function register(router, services) { + const { commands } = services; + const social = createSocialQueries(services); + const run = (name, args) => commands.run(name, args); + const base = ['unauthorized', 'not_found', 'validation_failed']; + const roleErrs = base.concat(['forbidden']); + + router.get('/alliances/mine', { + summary: 'Your alliance, role and permissions (null alliance when you are not in one)', tag: 'alliances', + query: { type: 'object', properties: worldQ }, response: { $ref: 'AllianceMine' }, errors: ['unauthorized', 'not_found', 'validation_failed'], + }, ({ user, query }) => social.mine(user.id, query.worldId)); + + router.get('/alliances', { + summary: 'Alliance directory of a world, optional name/tag search (cursor: after = last id)', tag: 'alliances', + query: { type: 'object', properties: Object.assign({ q: { type: 'string', maxLength: 40 } }, page, worldQ) }, response: { $ref: 'AllianceList' }, errors: base, + }, ({ user, query }) => social.list(user.id, query)); + + router.post('/alliances', { + summary: 'Found an alliance (needs Peering office 1+); you become its leader', tag: 'alliances', status: 201, + body: { type: 'object', required: ['name', 'tag'], properties: { name: { type: 'string', minLength: S.nameLen[0], maxLength: S.nameLen[1] * 2 }, tag: { type: 'string', minLength: S.tagLen[0], maxLength: S.tagLen[1] }, worldId: int1 } }, + response: { $ref: 'AllianceCreated' }, errors: base.concat(['peering_office_required', 'already_in_alliance', 'alliance_name_taken', 'alliance_tag_taken']), + }, ({ user, body }) => reply(201, run('allianceCreate', { userId: user.id, worldId: body.worldId, name: body.name, tag: body.tag }))); + + router.get('/alliance-invites', { + summary: 'Open invites addressed to you', tag: 'alliances', response: { $ref: 'ReceivedInviteList' }, errors: ['unauthorized'], + }, ({ user }) => social.invitesReceived(user.id)); + + const answerErrs = ['unauthorized', 'not_found', 'conflict', 'invite_expired', 'already_in_alliance', 'peering_office_required', 'alliance_full']; + router.post('/alliance-invites/:id/accept', { + summary: 'Accept an invite (needs Peering office 1+ and no alliance yet)', tag: 'alliances', response: { $ref: 'Changed' }, errors: answerErrs, + }, ({ user, params }) => run('allianceInviteAnswer', { userId: user.id, inviteId: params.id, accept: true })); + router.post('/alliance-invites/:id/decline', { + summary: 'Decline an invite', tag: 'alliances', response: { $ref: 'Changed' }, errors: answerErrs, + }, ({ user, params }) => run('allianceInviteAnswer', { userId: user.id, inviteId: params.id, accept: false })); + + router.get('/alliances/:id', { + summary: 'Public alliance profile: size, leader, footprint, your role and relation to it', tag: 'alliances', response: { $ref: 'AllianceDetail' }, errors: ['unauthorized', 'not_found'], + }, ({ user, params }) => social.get(user.id, params.id)); + + router.get('/alliances/:id/members', { + summary: 'Member list with role, POP count, footprint and last online (members only)', tag: 'alliances', response: { $ref: 'AllianceMemberList' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => social.members(user.id, params.id)); + + router.get('/alliances/:id/invites', { + summary: 'Pending invites sent by this alliance (needs viewInvites)', tag: 'alliances', response: { $ref: 'AllianceInviteList' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => social.invitesSent(user.id, params.id)); + + router.post('/alliances/:id/invite', { + summary: 'Invite an operator by id or name (needs invite). Repeating it returns the pending invite', tag: 'alliances', status: 201, + body: { type: 'object', properties: { operatorId: int1, name: { type: 'string', minLength: 1, maxLength: 40 } } }, + response: { $ref: 'InviteResult' }, errors: roleErrs.concat(['already_in_alliance', 'alliance_full', 'conflict']), + }, ({ user, params, body }) => { + if ((body.operatorId === undefined) === (body.name === undefined)) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'give exactly one of operatorId, name' }] }); + const r = run('allianceInvite', { userId: user.id, allianceId: params.id, operatorId: body.operatorId, name: body.name }); + return reply(r.changed ? 201 : 200, r); + }); + + router.del('/alliances/:id/invites/:inviteId', { + summary: 'Cancel a pending invite (needs cancelInvite)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden', 'conflict'], + }, ({ user, params }) => run('allianceInviteCancel', { userId: user.id, allianceId: params.id, inviteId: params.inviteId })); + + router.post('/alliances/:id/leave', { + summary: 'Leave the alliance. The leader must transfer first unless alone (then it is disbanded)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'leader_must_transfer'], + }, ({ user, params }) => run('allianceLeave', { userId: user.id, allianceId: params.id })); + + router.post('/alliances/:id/kick', { + summary: 'Remove a member you outrank (needs kick)', tag: 'alliances', body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, + response: { $ref: 'Changed' }, errors: roleErrs, + }, ({ user, params, body }) => run('allianceKick', { userId: user.id, allianceId: params.id, operatorId: body.operatorId })); + + router.post('/alliances/:id/role', { + summary: 'Set a member role: diplomat, officer or member (leader only)', tag: 'alliances', + body: { type: 'object', required: ['operatorId', 'role'], properties: { operatorId: int1, role: { type: 'string', enum: ['diplomat', 'officer', 'member'] } } }, + response: { $ref: 'Changed' }, errors: roleErrs, + }, ({ user, params, body }) => run('allianceRole', { userId: user.id, allianceId: params.id, operatorId: body.operatorId, role: body.role })); + + router.post('/alliances/:id/transfer', { + summary: 'Hand leadership to another member; you become an officer (leader only)', tag: 'alliances', + body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, response: { $ref: 'Changed' }, errors: roleErrs, + }, ({ user, params, body }) => run('allianceTransfer', { userId: user.id, allianceId: params.id, operatorId: body.operatorId })); + + router.post('/alliances/:id/disband', { + summary: 'Disband the alliance (leader only)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => run('allianceDisband', { userId: user.id, allianceId: params.id })); + + // ---- pinned notes + const noteBody = { type: 'object', required: ['text'], properties: { text: { type: 'string', minLength: 1, maxLength: S.noteMax } } }; + router.get('/alliances/:id/notes', { + summary: 'Pinned notes (members only)', tag: 'alliances', response: { $ref: 'AllianceNoteList' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => social.notes(user.id, params.id)); + router.post('/alliances/:id/notes', { + summary: 'Pin a note (needs editNotes)', tag: 'alliances', status: 201, body: noteBody, response: { $ref: 'AllianceNoteResponse' }, errors: roleErrs.concat(['notes_full']), + }, ({ user, params, body }) => reply(201, run('allianceNoteAdd', { userId: user.id, allianceId: params.id, text: body.text }))); + router.post('/alliances/:id/notes/:noteId', { + summary: 'Edit a pinned note (needs editNotes)', tag: 'alliances', body: noteBody, response: { $ref: 'AllianceNoteResponse' }, errors: roleErrs, + }, ({ user, params, body }) => run('allianceNoteEdit', { userId: user.id, allianceId: params.id, noteId: params.noteId, text: body.text })); + router.del('/alliances/:id/notes/:noteId', { + summary: 'Remove a pinned note (needs editNotes)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => run('allianceNoteDelete', { userId: user.id, allianceId: params.id, noteId: params.noteId })); + + // ---- diplomacy + router.get('/alliances/:id/diplomacy', { + summary: 'Relations with other alliances (with scheduled changes) and open proposals (members only)', tag: 'diplomacy', response: { $ref: 'Diplomacy' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => social.diplomacy(user.id, params.id)); + + router.post('/alliances/:id/diplomacy', { + summary: 'Change the relation to another alliance (needs diplomacy): war applies at once from neutral, pacts need acceptance, cancelling a pact takes 24 h / world speed', tag: 'diplomacy', + body: { type: 'object', required: ['targetId', 'state'], properties: { targetId: int1, state: { type: 'string', enum: S.diplomacyStates } } }, + response: { $ref: 'DiplomacyResult' }, errors: roleErrs.concat(['diplomacy_invalid', 'diplomacy_pending', 'proposal_exists']), + }, ({ user, params, body }) => run('diploPropose', { userId: user.id, allianceId: params.id, targetId: body.targetId, state: body.state })); + + router.del('/alliances/:id/diplomacy/:otherId/pending', { + summary: 'Take back a scheduled cancel before it takes effect (the alliance that started it, needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'], + }, ({ user, params }) => run('diploRevoke', { userId: user.id, allianceId: params.id, otherId: params.otherId })); + + const propErrs = ['unauthorized', 'not_found', 'forbidden', 'conflict', 'proposal_expired', 'diplomacy_invalid', 'diplomacy_pending']; + router.post('/diplomacy/proposals/:proposalId/accept', { + summary: 'Accept a diplomatic proposal addressed to your alliance (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: propErrs, + }, ({ user, params }) => run('diploAnswer', { userId: user.id, proposalId: params.proposalId, accept: true })); + router.post('/diplomacy/proposals/:proposalId/decline', { + summary: 'Decline a diplomatic proposal addressed to your alliance (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: propErrs, + }, ({ user, params }) => run('diploAnswer', { userId: user.id, proposalId: params.proposalId, accept: false })); + router.del('/diplomacy/proposals/:proposalId', { + summary: 'Withdraw a proposal your alliance made (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden', 'conflict'], + }, ({ user, params }) => run('diploWithdraw', { userId: user.id, proposalId: params.proposalId })); +} + +module.exports = { register }; diff --git a/server/routes/index.js b/server/routes/index.js index bbf5683..42d1a62 100644 --- a/server/routes/index.js +++ b/server/routes/index.js @@ -1,6 +1,6 @@ 'use strict'; /* Registers every REST route. One file per resource; each exports register(router, services). */ -const files = [require('./auth'), require('./me'), require('./towns'), require('./map')]; +const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports')]; function register(router, services) { for (const f of files) f.register(router, services); diff --git a/server/routes/messages.js b/server/routes/messages.js new file mode 100644 index 0000000..116b29d --- /dev/null +++ b/server/routes/messages.js @@ -0,0 +1,71 @@ +'use strict'; +/* Player messages and alliance broadcasts (stage 5). Fixed paths first, /messages/:id last. */ +const { reply } = require('../http'); +const { createSocialQueries } = require('../socialQueries'); +const D = require('../../public/js/data.js'); + +const int1 = { type: 'integer', minimum: 1 }; +const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }; +const listQuery = (extra) => ({ type: 'object', properties: Object.assign({}, page, { worldId: int1 }, extra || {}) }); + +function register(router, services) { + const { commands } = services; + const social = createSocialQueries(services); + const run = (name, args) => commands.run(name, args); + + router.get('/messages/inbox', { + summary: 'Received messages, newest first (cursor: after = last id of the previous page); `unread` counts all unread', tag: 'messages', + query: listQuery({ unread: { type: 'boolean' } }), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'], + }, ({ user, query }) => social.inbox(user.id, query)); + + router.get('/messages/outbox', { + summary: 'Sent messages, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'], + }, ({ user, query }) => social.outbox(user.id, query)); + + router.get('/messages/alliance', { + summary: 'Broadcasts of your alliance, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'not_in_alliance', 'validation_failed'], + }, ({ user, query }) => social.allianceFeed(user.id, query)); + + router.get('/messages/thread/:operatorId', { + summary: 'The conversation with one operator, both directions, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'], + }, ({ user, params, query }) => social.thread(user.id, params.operatorId, query)); + + router.get('/messages/blocks', { + summary: 'Operators you blocked', tag: 'messages', query: { type: 'object', properties: { worldId: int1 } }, response: { $ref: 'BlockList' }, errors: ['unauthorized', 'not_found', 'validation_failed'], + }, ({ user, query }) => social.blocks(user.id, query)); + + router.post('/messages/blocks', { + summary: 'Block an operator: their messages are no longer delivered to you (they are not told)', tag: 'messages', + body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'validation_failed', 'conflict'], + }, ({ user, body }) => run('messageBlock', { userId: user.id, operatorId: body.operatorId })); + + router.del('/messages/blocks/:operatorId', { + summary: 'Unblock an operator', tag: 'messages', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'validation_failed'], + }, ({ user, params }) => run('messageUnblock', { userId: user.id, operatorId: params.operatorId })); + + router.post('/messages/read', { + summary: 'Mark received messages read: a list of ids (max 100) or all', tag: 'messages', + body: { type: 'object', properties: { ids: { type: 'array', maxItems: 100, items: int1 }, all: { type: 'boolean' }, worldId: int1 } }, + response: { $ref: 'Changed' }, errors: ['unauthorized', 'validation_failed'], + }, ({ user, body }) => { + const r = commands.run('messageRead', { userId: user.id, ids: body.ids, all: body.all, worldId: body.worldId }); + return { changed: r.changed > 0, count: r.changed }; + }); + + router.post('/messages', { + summary: 'Send a message to an operator (toOperatorId or toName) or to your alliance (toAlliance). Plain text, max 2000 characters, rate-limited', tag: 'messages', status: 201, + body: { type: 'object', required: ['text'], properties: { + text: { type: 'string', minLength: 1, maxLength: D.SOCIAL.messageMax }, toOperatorId: int1, toName: { type: 'string', minLength: 1, maxLength: 40 }, toAlliance: { type: 'boolean' }, worldId: int1 } }, + response: { $ref: 'MessageSent' }, errors: ['unauthorized', 'not_found', 'validation_failed', 'forbidden', 'not_in_alliance', 'rate_limited'], + }, ({ user, body }) => reply(201, run('messageSend', { userId: user.id, worldId: body.worldId, toOperatorId: body.toOperatorId, toName: body.toName, toAlliance: body.toAlliance, text: body.text }))); + + router.get('/messages/:id', { + summary: 'One message you sent or received', tag: 'messages', response: { $ref: 'MessageResponse' }, errors: ['unauthorized', 'not_found'], + }, ({ user, params }) => social.message(user.id, params.id)); + + router.del('/messages/:id', { + summary: 'Delete your own copy of a message (the other side keeps theirs)', tag: 'messages', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found'], + }, ({ user, params }) => run('messageDelete', { userId: user.id, messageId: params.id })); +} + +module.exports = { register }; diff --git a/server/routes/movements.js b/server/routes/movements.js new file mode 100644 index 0000000..8eeb082 --- /dev/null +++ b/server/routes/movements.js @@ -0,0 +1,65 @@ +'use strict'; +/* Movements: send, recall, list (with incoming warnings), withdraw reinforcements, tile info for the send dialog. */ +const { reply } = require('../http'); +const { GameError } = require('../errors'); +const { createMilitaryQueries } = require('../military/views'); + +function register(router, services) { + const { commands, db, clock, scheduler } = services; + const mq = createMilitaryQueries({ db, clock, scheduler }); + const errs = ['unauthorized', 'not_found', 'validation_failed']; + + router.post('/movements', { + summary: 'Send units (scan, raid, attack, takeover, reinforce, settle) or resources (transport) from one of your POPs. Target = toTownId or the tile x,y', tag: 'movements', + body: { + type: 'object', required: ['fromTownId', 'type'], + properties: { + fromTownId: { type: 'integer', minimum: 1 }, + type: { type: 'string', enum: ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle', 'transport'] }, + toTownId: { type: 'integer', minimum: 1 }, + x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, + units: { type: 'object', additionalProperties: true, description: 'unit id -> count' }, + cargo: { type: 'object', additionalProperties: true, description: 'transport only: fiber/hardware/capital -> amount' }, + target: { type: 'string', maxLength: 32, pattern: '^[a-z0-9_]+$', description: 'exploit kits: the building (f1..f18 or an infrastructure type) to damage on a win' }, + wild: { type: 'array', maxItems: 2, items: { type: 'string', maxLength: 32 }, description: 'settle: the two wild slot field types of the new POP' }, + confirmEndProtection: { type: 'boolean', description: 'raid/attack/takeover from a protected operator: attacking ends beginner protection' }, + }, + }, + response: { $ref: 'MovementSent' }, status: 201, + errors: errs.concat(['unknown_unit', 'not_enough_units', 'units_offline', 'invalid_target', 'target_protected', 'protection_active', 'out_of_range', 'footprint_too_low', + 'cannot_takeover', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources']), + }, ({ user, body }) => { + if (body.type === 'transport') { + if (body.toTownId === undefined) throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'is required for a transport' }] }); + return reply(201, commands.run('sendTransport', { userId: user.id, fromTownId: body.fromTownId, toTownId: body.toTownId, cargo: body.cargo })); + } + return reply(201, commands.run('sendMovement', { + userId: user.id, fromTownId: body.fromTownId, type: body.type, toTownId: body.toTownId, x: body.x, y: body.y, units: body.units, + target: body.target, wild: body.wild, confirmEndProtection: body.confirmEndProtection, + })); + }); + + router.get('/movements', { + summary: 'Your active movements and other operators\' movements heading for your POPs (incoming warnings: origin and ETA only, type hidden)', tag: 'movements', + query: { type: 'object', properties: { worldId: { type: 'integer', minimum: 1 } } }, + response: { $ref: 'MovementList' }, errors: errs, + }, ({ user, query }) => mq.movements(user.id, { worldId: query.worldId })); + + router.post('/movements/:id/recall', { + summary: 'Turn an outbound movement around within the first 90 seconds', tag: 'movements', + response: { $ref: 'RecallResult' }, errors: errs.concat(['conflict', 'recall_expired']), + }, ({ user, params }) => commands.run('recallMovement', { userId: user.id, movementId: params.id })); + + router.post('/towns/:id/withdraw', { + summary: 'Send reinforcements standing in this POP home (host kicks them out, or the units\' owner calls them back)', tag: 'movements', + body: { type: 'object', required: ['ownerTownId'], properties: { ownerTownId: { type: 'integer', minimum: 1 }, units: { type: 'object', additionalProperties: true, description: 'defaults to the whole group' } } }, + response: { $ref: 'WithdrawResult' }, errors: errs.concat(['not_enough_units', 'unknown_unit']), + }, ({ user, params, body }) => commands.run('withdrawStationed', { userId: user.id, hostTownId: params.id, ownerTownId: body.ownerTownId, units: body.units })); + + router.get('/map/tile', { + summary: 'Public information about one tile for the send dialog: what is there, owner, distance from your POPs, whether you could settle it', tag: 'map', + query: { type: 'object', required: ['x', 'y'], properties: { x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, worldId: { type: 'integer', minimum: 1 } } }, + response: { $ref: 'TileInfo' }, errors: errs, + }, ({ user, query }) => mq.tileInfo(user.id, { worldId: query.worldId, x: query.x, y: query.y })); +} +module.exports = { register }; diff --git a/server/routes/rankings.js b/server/routes/rankings.js new file mode 100644 index 0000000..ac9de00 --- /dev/null +++ b/server/routes/rankings.js @@ -0,0 +1,28 @@ +'use strict'; +/* Rankings (stage 5): operators by footprint, alliances by summed footprint, attackers/defenders by battle points. */ +const { createSocialQueries } = require('../socialQueries'); +const D = require('../../public/js/data.js'); + +const q = (extra) => ({ type: 'object', properties: Object.assign({ + worldId: { type: 'integer', minimum: 1 }, after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: D.SOCIAL.rankingsPageMax }, +}, extra || {}) }); + +function register(router, services) { + const social = createSocialQueries(services); + const errs = ['unauthorized', 'not_found', 'validation_failed']; + + router.get('/rankings/operators', { + summary: 'Operators by footprint (cursor: after = number of ranks already seen)', tag: 'rankings', query: q(), response: { $ref: 'RankOperators' }, errors: errs, + }, ({ user, query }) => social.rankOperators(user.id, query)); + + router.get('/rankings/alliances', { + summary: 'Alliances by summed footprint of their members', tag: 'rankings', query: q(), response: { $ref: 'RankAlliances' }, errors: errs, + }, ({ user, query }) => social.rankAlliances(user.id, query)); + + router.get('/rankings/battles', { + summary: 'Attackers / defenders by battle points (`by`: attack, defense or total). Empty with available=false until the military stage records points', tag: 'rankings', + query: q({ by: { type: 'string', enum: ['attack', 'defense', 'total'] } }), response: { $ref: 'RankBattles' }, errors: errs, + }, ({ user, query }) => social.rankBattles(user.id, query)); +} + +module.exports = { register }; diff --git a/server/routes/reports.js b/server/routes/reports.js new file mode 100644 index 0000000..eb8a520 --- /dev/null +++ b/server/routes/reports.js @@ -0,0 +1,26 @@ +'use strict'; +/* Reports of battles, scans, settles and reinforcements (kept 14 days). Newest first; `after` = the last id you have, + * the next page holds older ones. */ +const { createMilitaryQueries } = require('../military/views'); + +function register(router, services) { + const { commands, db, clock, scheduler } = services; + const mq = createMilitaryQueries({ db, clock, scheduler }); + const errs = ['unauthorized', 'not_found', 'validation_failed']; + + router.get('/reports', { + summary: 'Your reports, newest first (cursor: after = id of the last report seen, returns older ones)', tag: 'reports', + query: { type: 'object', properties: { after: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 }, unread: { type: 'boolean' } } }, + response: { $ref: 'ReportList' }, errors: errs, + }, ({ user, query }) => mq.reports(user.id, query)); + + router.post('/reports/read-all', { summary: 'Mark all your reports as read', tag: 'reports', response: { $ref: 'Marked' }, errors: ['unauthorized'] }, + ({ user }) => commands.run('markReportRead', { userId: user.id, all: true })); + + router.get('/reports/:id', { summary: 'One report with its full data', tag: 'reports', response: { $ref: 'ReportResponse' }, errors: errs }, + ({ user, params }) => mq.report(user.id, params.id)); + + router.post('/reports/:id/read', { summary: 'Mark a report as read', tag: 'reports', response: { $ref: 'Marked' }, errors: errs }, + ({ user, params }) => commands.run('markReportRead', { userId: user.id, reportId: params.id })); +} +module.exports = { register }; diff --git a/server/routes/schemas.js b/server/routes/schemas.js index c600090..ab6a95e 100644 --- a/server/routes/schemas.js +++ b/server/routes/schemas.js @@ -15,7 +15,7 @@ const schemas = { Error: obj({ serverTime: int, error: obj({ code: str, message: str, details: { type: 'object', additionalProperties: true } }) }), World: obj({ id: int, name: str, speed: num, mapRadius: int, seed: int, startAt: int, endAt: { type: ['integer', 'null'] }, status: str, preset: str }), TownSummary: obj({ id: int, name: str, x: int, y: int, isCapital: bool }), - Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }), + Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }), Me: obj({ serverTime: int, user: obj({ id: int, username: str, createdAt: int }), operators: arr({ $ref: 'Operator' }) }), AuthResult: obj({ serverTime: int, token: str, tokenId: int, user: obj({ id: int, username: str }), operators: arr({ $ref: 'Operator' }) }), Token: obj({ id: int, device: str, createdAt: int, lastUsedAt: int, current: bool }), @@ -31,13 +31,52 @@ const schemas = { bonus: obj({ fiber: num, hardware: num, capital: num }), }), TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }), - MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protected: bool }) }), + MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }), MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }), MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }), BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }), Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }), NotificationList: obj({ serverTime: int, items: arr({ $ref: 'Notification' }), next: { type: ['integer', 'null'] } }), + // ---- stage 5: alliances, diplomacy, messages, rankings + AllianceBrief: obj({ id: int, tag: str, name: str }), + OperatorBrief: obj({ operatorId: int, name: str }), + AllianceInfo: obj({ id: int, worldId: int, name: str, tag: str, sizeCap: int, memberCount: int, leader: { type: ['object', 'null'], additionalProperties: true }, createdAt: int }), + AllianceDetail: obj({ serverTime: int, alliance: { $ref: 'AllianceInfo' } }), + AllianceMine: obj({ serverTime: int, operatorId: int, worldId: int, alliance: { type: ['object', 'null'], additionalProperties: true }, role: { type: ['string', 'null'] }, permissions: arr(str), peeringLevel: int }), + AllianceList: obj({ serverTime: int, items: arr({ $ref: 'AllianceInfo' }), next: { type: ['integer', 'null'] } }), + AllianceMember: obj({ operatorId: int, name: str, asNumber: int, role: str, joinedAt: int, towns: int, footprint: num, lastOnline: { type: ['integer', 'null'] } }), + AllianceMemberList: obj({ serverTime: int, items: arr({ $ref: 'AllianceMember' }), next: { type: ['integer', 'null'] } }), + AllianceCreated: obj({ serverTime: int, allianceId: int, name: str, tag: str, sizeCap: int, role: str }), + AllianceInvite: obj({ id: int, operator: { $ref: 'OperatorBrief' }, invitedBy: { $ref: 'OperatorBrief' }, createdAt: int, expiresAt: int }), + AllianceInviteList: obj({ serverTime: int, items: arr({ $ref: 'AllianceInvite' }), next: { type: ['integer', 'null'] } }), + ReceivedInvite: obj({ id: int, operatorId: int, alliance: { $ref: 'AllianceBrief' }, invitedBy: { $ref: 'OperatorBrief' }, createdAt: int, expiresAt: int }), + ReceivedInviteList: obj({ serverTime: int, items: arr({ $ref: 'ReceivedInvite' }), next: { type: ['integer', 'null'] } }), + InviteResult: obj({ serverTime: int, inviteId: int, operatorId: int, expiresAt: int, changed: bool }), + Changed: obj({ serverTime: int, changed: bool }), + AllianceNote: obj({ id: int, authorId: int, text: str, createdAt: int, updatedAt: int }), + AllianceNoteResponse: obj({ serverTime: int, note: { $ref: 'AllianceNote' } }), + AllianceNoteList: obj({ serverTime: int, items: arr({ $ref: 'AllianceNote' }), next: { type: ['integer', 'null'] } }), + Relation: obj({ other: { type: 'object', additionalProperties: true }, state: str, since: int, pending: { type: ['object', 'null'], additionalProperties: true } }), + Proposal: obj({ id: int, other: { type: 'object', additionalProperties: true }, state: str, createdAt: int, expiresAt: int }), + Diplomacy: obj({ serverTime: int, allianceId: int, relations: arr({ $ref: 'Relation' }), proposalsIn: arr({ $ref: 'Proposal' }), proposalsOut: arr({ $ref: 'Proposal' }) }), + DiplomacyResult: obj({ serverTime: int, result: str, from: str, state: str }, ['serverTime', 'result', 'from', 'state']), + Message: obj({ + id: int, kind: str, direction: str, thread: str, from: { $ref: 'OperatorBrief' }, to: { type: ['object', 'null'], additionalProperties: true }, + alliance: { type: ['object', 'null'], additionalProperties: true }, text: str, createdAt: int, readAt: { type: ['integer', 'null'] }, + }), + MessageList: obj({ serverTime: int, items: arr({ $ref: 'Message' }), next: { type: ['integer', 'null'] }, unread: int }, ['serverTime', 'items', 'next']), + MessageResponse: obj({ serverTime: int, message: { $ref: 'Message' } }), + MessageSent: obj({ serverTime: int, messageId: int, kind: str, recipients: int, createdAt: int }), + BlockList: obj({ serverTime: int, items: arr(obj({ operatorId: int, name: str, createdAt: int })), next: { type: ['integer', 'null'] } }), + RankOperator: obj({ rank: int, operatorId: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, allianceTag: { type: ['string', 'null'] }, towns: int, footprint: num }), + RankAlliance: obj({ rank: int, allianceId: int, name: str, tag: str, members: int, towns: int, footprint: num }), + RankBattle: obj({ rank: int, operatorId: int, name: str, allianceTag: { type: ['string', 'null'] }, attackPoints: num, defensePoints: num }), + RankOperators: obj({ serverTime: int, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankOperator' }), next: { type: ['integer', 'null'] } }), + RankAlliances: obj({ serverTime: int, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankAlliance' }), next: { type: ['integer', 'null'] } }), + RankBattles: obj({ serverTime: int, by: str, available: bool, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankBattle' }), next: { type: ['integer', 'null'] } }), Ok: obj({ serverTime: int }), }; +require('./schemasMilitary')(schemas, { int, num, str, bool, obj, arr }); + module.exports = { schemas, int, num, str, bool, obj, arr }; diff --git a/server/routes/schemasMilitary.js b/server/routes/schemasMilitary.js new file mode 100644 index 0000000..27446ca --- /dev/null +++ b/server/routes/schemasMilitary.js @@ -0,0 +1,42 @@ +'use strict'; +/* Response schemas of the military stage (merged into routes/schemas.js). Documentation only, like the others. */ +module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj, arr }) { + const nint = { type: ['integer', 'null'] }; + const free = { type: 'object', additionalProperties: true }; + const Units = { type: 'object', additionalProperties: true, description: 'unit id -> count' }; + const Cost = { $ref: 'Cost' }; + Object.assign(schemas, { + Units, + TrainResult: obj({ serverTime: int, eventId: int, unit: str, count: int, building: str, startAt: int, dueAt: int, cost: Cost }), + ResearchResult: obj({ serverTime: int, eventId: int, unit: str, stat: str, toLevel: int, startedAt: int, dueAt: int, cost: Cost }), + MovementSent: obj({ serverTime: int, movementId: int, type: str, fromTownId: int, toTownId: nint, to: obj({ x: int, y: int }), units: Units, cargo: free, departAt: int, arriveAt: int, protectionEnded: bool }, ['serverTime', 'movementId', 'type', 'fromTownId', 'toTownId', 'departAt', 'arriveAt']), + RecallResult: obj({ serverTime: int, recalled: int, returnMovementId: int, arriveAt: int }), + WithdrawResult: obj({ serverTime: int, movementId: int, units: Units, arriveAt: int }), + MovementEnd: obj({ townId: nint, x: int, y: int, name: { type: ['string', 'null'] }, owner: { type: ['object', 'null'], additionalProperties: true } }, ['townId', 'x', 'y']), + Movement: obj({ + id: int, type: str, status: str, ownerId: int, from: { $ref: 'MovementEnd' }, to: { $ref: 'MovementEnd' }, units: Units, cargo: free, + departAt: int, arriveAt: int, recallableUntil: nint, target: { type: ['string', 'null'] }, parentId: nint, incoming: bool, + }, ['id', 'type', 'status', 'from', 'to', 'departAt', 'arriveAt']), + MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }), + Marked: obj({ serverTime: int, marked: int }), + ReportItem: obj({ id: int, type: str, createdAt: int, role: str, read: bool, summary: free }), + ReportList: obj({ serverTime: int, items: arr({ $ref: 'ReportItem' }), next: nint, unread: int }), + Report: obj({ id: int, type: str, createdAt: int, expiresAt: int, role: str, read: bool, summary: free, data: free }), + ReportResponse: obj({ serverTime: int, report: { $ref: 'Report' } }), + TileInfo: obj({ + serverTime: int, x: int, y: int, type: str, bonus: { type: ['string', 'null'] }, + distances: arr(obj({ townId: int, distance: num })), town: free, incumbent: free, + settle: obj({ possible: bool, code: { type: ['string', 'null'] }, footprint: num, footprintNeeded: num, maxDistance: int }), + }, ['serverTime', 'x', 'y', 'type', 'distances', 'settle']), + TownMilitary: obj({ + units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free) }), + training: arr(obj({ id: int, unit: str, count: int, building: str, startAt: int, dueAt: int })), + trainable: arr(obj({ unit: str, building: str, role: str, cost: Cost, timeMs: int, missing: arr(free), locked: bool })), + research: obj({ levels: free, queue: { type: ['object', 'null'], additionalProperties: true }, speedBonus: num, maxLevel: int }), + transport: obj({ links: int, active: int, capacityPerLink: int }), + movements: obj({ outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }), + protectionUntil: int, + }), + }); + if (schemas.Town && schemas.Town.properties) schemas.Town.properties.military = { $ref: 'TownMilitary' }; // optional: not in `required` +}; diff --git a/server/routes/units.js b/server/routes/units.js new file mode 100644 index 0000000..2deff2d --- /dev/null +++ b/server/routes/units.js @@ -0,0 +1,21 @@ +'use strict'; +/* Training queue and research of a POP (stage 3). */ +const { reply } = require('../http'); +const D = require('../../public/js/data.js'); + +function register(router, { commands }) { + const errs = ['unauthorized', 'not_found', 'validation_failed']; + + router.post('/towns/:id/train', { + summary: 'Queue a batch of one unit type. Batches of the same training building run in order; units appear when the batch is done', tag: 'units', + body: { type: 'object', required: ['unit', 'count'], properties: { unit: { type: 'string', maxLength: 32, pattern: '^[a-z_]+$' }, count: { type: 'integer', minimum: 1, maximum: D.MILITARY.maxBatch } } }, + response: { $ref: 'TrainResult' }, status: 201, errors: errs.concat(['unknown_unit', 'requirements_not_met', 'not_enough_resources', 'queue_full']), + }, ({ user, params, body }) => reply(201, commands.run('train', { userId: user.id, townId: params.id, unit: body.unit, count: body.count }))); + + router.post('/towns/:id/research', { + summary: 'Research +5% attack or defence for one unit type (one research at a time per POP, needs a Research lab)', tag: 'units', + body: { type: 'object', required: ['unit', 'stat'], properties: { unit: { type: 'string', maxLength: 32, pattern: '^[a-z_]+$' }, stat: { type: 'string', enum: ['attack', 'defence'] } } }, + response: { $ref: 'ResearchResult' }, status: 201, errors: errs.concat(['unknown_unit', 'not_researchable', 'max_level', 'requirements_not_met', 'not_enough_resources', 'queue_full']), + }, ({ user, params, body }) => reply(201, commands.run('research', { userId: user.id, townId: params.id, unit: body.unit, stat: body.stat }))); +} +module.exports = { register }; diff --git a/server/socialQueries.js b/server/socialQueries.js new file mode 100644 index 0000000..d79d703 --- /dev/null +++ b/server/socialQueries.js @@ -0,0 +1,313 @@ +'use strict'; +/* + * Read models for stage 5: alliances, diplomacy, messages, rankings. Like queries.js, every read first catches the + * event queue up to now and reads never write. List cursors: alliances/invites/notes by id ascending, messages newest + * first (cursor = the last id of the previous page, next page holds smaller ids), rankings by rank offset. + */ +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); +const { GameError } = require('./errors'); +const { loadWorld, hasTable } = require('./state'); +const A = require('./alliances'); +const { noteView } = require('./commands/allianceNote'); + +const S = D.SOCIAL; +const MAX_ID = Number.MAX_SAFE_INTEGER; + +function createSocialQueries({ db, clock, scheduler }) { + const fresh = () => { scheduler.runDue(); return clock.now(); }; + const opBrief = (id, name) => ({ operatorId: id, name }); + + // ---------------------------------------------------------------- footprint (rankings and alliance sums) + + // operatorId -> { footprint, towns } for a whole world, from two queries (no per-town round trips). + function footprints(worldId, now) { + const world = loadWorld(db, worldId); + const towns = new Map(); + for (const t of db.all('SELECT id, owner_id, footprint, res_at FROM towns WHERE world_id = ?', worldId)) { + towns.set(t.id, { owner: t.owner_id, town: { speed: world.speed, footprint: t.footprint, updatedAt: t.res_at, buildings: {} } }); + } + for (const b of db.all('SELECT b.town_id AS tid, b.key AS key, b.level AS level FROM buildings b JOIN towns t ON t.id = b.town_id WHERE t.world_id = ?', worldId)) { + const e = towns.get(b.tid); + if (e) e.town.buildings[b.key] = { level: b.level }; + } + const out = new Map(); + for (const e of towns.values()) { + const cur = out.get(e.owner) || { footprint: 0, towns: 0 }; + cur.footprint += R.footprintAt(e.town, now); + cur.towns += 1; + out.set(e.owner, cur); + } + return out; + } + + // ---------------------------------------------------------------- alliances + + function allianceInfo(a) { + const lead = db.get(`SELECT o.id AS id, o.name AS name FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE m.alliance_id = ? AND m.role = 'leader'`, a.id); + return { + id: a.id, worldId: a.world_id, name: a.name, tag: a.tag, sizeCap: A.effectiveCap(db, a), memberCount: A.memberCount(db, a.id), + leader: lead ? opBrief(lead.id, lead.name) : null, createdAt: a.created_at, + }; + } + + function permissionsOf(role) { return Object.keys(S.permissions).filter((k) => R.allianceCan(role, k)); } + + // Caller's operator + membership in a world (default: their oldest operator). + function mine(userId, worldId) { + const now = fresh(); + const op = A.operatorOf(db, userId, worldId); + const m = A.membership(db, op.id); + const a = m ? A.getAlliance(db, m.alliance_id) : null; + return { + serverTime: now, operatorId: op.id, worldId: op.world_id, + alliance: a ? allianceInfo(a) : null, role: m ? m.role : null, permissions: m ? permissionsOf(m.role) : [], + peeringLevel: A.peeringLevel(db, op.id), + }; + } + + function list(userId, { worldId, after, limit, q }) { + const now = fresh(); + const op = A.operatorOf(db, userId, worldId); + limit = limit || 30; + const needle = q ? String(q).toLowerCase() : ''; + const rows = db.all(`SELECT * FROM alliances WHERE world_id = ? AND id > ? AND (? = '' OR instr(lower(name), ?) > 0 OR instr(lower(tag), ?) > 0) + ORDER BY id LIMIT ?`, op.world_id, after || 0, needle, needle, needle, limit + 1); + const items = rows.slice(0, limit).map(allianceInfo); + return { serverTime: now, items, next: rows.length > limit ? items[items.length - 1].id : null }; + } + + function get(userId, id) { + const now = fresh(); + const a = A.getAlliance(db, id); + const op = a && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, a.world_id); + if (!a || !op) throw new GameError('not_found', { what: 'alliance' }); + const fp = footprints(a.world_id, now); + let footprint = 0; + for (const m of db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id)) footprint += (fp.get(m.operator_id) || { footprint: 0 }).footprint; + const mm = A.membership(db, op.id); + const info = allianceInfo(a); + info.footprint = Math.round(footprint * 100) / 100; + info.myRole = mm && mm.alliance_id === a.id ? mm.role : null; + info.relation = !mm ? null : mm.alliance_id === a.id ? 'same' : A.relationBetween(db, mm.alliance_id, a.id); + return { serverTime: now, alliance: info }; + } + + function memberOnly(userId, allianceId) { + const a = A.getAlliance(db, allianceId); + const op = a && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, a.world_id); + if (!a || !op) throw new GameError('not_found', { what: 'alliance' }); + const m = A.membership(db, op.id); + if (!m || m.alliance_id !== a.id) throw new GameError('forbidden', { need: 'member' }); + return { a, op, m }; + } + + // Member list with POP count, footprint and last online (newest token use of the user; tokens.last_used_at is + // refreshed at most once a minute by auth.authenticate). The list is bounded by the size cap, so it is not paginated. + function members(userId, allianceId) { + const now = fresh(); + const { a } = memberOnly(userId, allianceId); + const fp = footprints(a.world_id, now); + const rows = db.all(`SELECT m.operator_id AS id, m.role AS role, m.joined_at AS joined, o.name AS name, o.as_number AS asn, + (SELECT MAX(t.last_used_at) FROM tokens t WHERE t.user_id = o.user_id) AS seen + FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE m.alliance_id = ?`, a.id); + const items = rows.map((r) => { + const f = fp.get(r.id) || { footprint: 0, towns: 0 }; + return { operatorId: r.id, name: r.name, asNumber: r.asn, role: r.role, joinedAt: r.joined, towns: f.towns, footprint: Math.round(f.footprint * 100) / 100, lastOnline: r.seen }; + }).sort((x, y) => R.roleRank(y.role) - R.roleRank(x.role) || x.name.localeCompare(y.name)); + return { serverTime: now, items, next: null }; + } + + function invitesSent(userId, allianceId) { + const now = fresh(); + const { a, m } = memberOnly(userId, allianceId); + if (!R.allianceCan(m.role, 'viewInvites')) throw new GameError('forbidden', { need: 'viewInvites', role: m.role }); + const rows = db.all(`SELECT i.id, i.operator_id AS oid, i.created_at, i.expires_at, t.name AS tname, b.name AS bname, i.invited_by AS bid + FROM alliance_invites i JOIN operators t ON t.id = i.operator_id JOIN operators b ON b.id = i.invited_by + WHERE i.alliance_id = ? AND i.status = 'pending' AND i.expires_at > ? ORDER BY i.id`, a.id, now); + return { serverTime: now, items: rows.map((r) => ({ id: r.id, operator: opBrief(r.oid, r.tname), invitedBy: opBrief(r.bid, r.bname), createdAt: r.created_at, expiresAt: r.expires_at })), next: null }; + } + + function invitesReceived(userId) { + const now = fresh(); + const rows = db.all(`SELECT i.id, i.alliance_id AS aid, i.created_at, i.expires_at, a.tag AS tag, a.name AS name, b.id AS bid, b.name AS bname, o.id AS oid + FROM alliance_invites i JOIN operators o ON o.id = i.operator_id JOIN alliances a ON a.id = i.alliance_id JOIN operators b ON b.id = i.invited_by + WHERE o.user_id = ? AND i.status = 'pending' AND i.expires_at > ? ORDER BY i.id`, userId, now); + return { serverTime: now, items: rows.map((r) => ({ id: r.id, operatorId: r.oid, alliance: { id: r.aid, tag: r.tag, name: r.name }, invitedBy: opBrief(r.bid, r.bname), createdAt: r.created_at, expiresAt: r.expires_at })), next: null }; + } + + function notes(userId, allianceId) { + const now = fresh(); + const { a } = memberOnly(userId, allianceId); + const rows = db.all('SELECT * FROM alliance_notes WHERE alliance_id = ? ORDER BY id', a.id); + return { serverTime: now, items: rows.map(noteView), next: null }; + } + + function diplomacy(userId, allianceId) { + const now = fresh(); + const { a } = memberOnly(userId, allianceId); + const brief = (id) => { const x = A.allianceBrief(db, id); return x || { id, tag: null, name: null }; }; + const relations = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ? ORDER BY since, a_id', a.id, a.id).map((r) => { + const other = r.a_id === a.id ? r.b_id : r.a_id; + return { + other: brief(other), state: r.state, since: r.since, + pending: r.pending_to ? { to: r.pending_to, effectiveAt: r.pending_at, startedBy: r.pending_by, byUs: r.pending_by === a.id } : null, + }; + }); + const prop = (r, otherId) => ({ id: r.id, other: brief(otherId), state: r.state, createdAt: r.created_at, expiresAt: r.expires_at }); + const incoming = db.all("SELECT * FROM alliance_proposals WHERE to_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id", a.id, now).map((r) => prop(r, r.from_id)); + const outgoing = db.all("SELECT * FROM alliance_proposals WHERE from_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id", a.id, now).map((r) => prop(r, r.to_id)); + return { serverTime: now, allianceId: a.id, relations, proposalsIn: incoming, proposalsOut: outgoing }; + } + + // ---------------------------------------------------------------- rankings + + function rankingWorld(userId, worldId) { + const op = A.operatorOf(db, userId, worldId); + return op; + } + + function page(rows, after, limit) { + const start = after || 0, n = limit || 50; + const slice = rows.slice(start, start + n).map((r, i) => Object.assign({ rank: start + i + 1 }, r)); + return { items: slice, next: start + n < rows.length ? start + n : null }; + } + + function rankOperators(userId, { worldId, after, limit }) { + const now = fresh(); + const me = rankingWorld(userId, worldId); + const fp = footprints(me.world_id, now); + const ops = db.all('SELECT o.id AS id, o.name AS name, o.as_number AS asn, a.id AS aid, a.tag AS tag FROM operators o LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?', me.world_id); + const rows = ops.map((o) => { + const f = fp.get(o.id) || { footprint: 0, towns: 0 }; + return { operatorId: o.id, name: o.name, asNumber: o.asn, allianceId: o.aid, allianceTag: o.tag, towns: f.towns, footprint: Math.round(f.footprint * 100) / 100 }; + }).sort((x, y) => y.footprint - x.footprint || x.operatorId - y.operatorId); + const you = rows.findIndex((r) => r.operatorId === me.id); + return Object.assign({ serverTime: now, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit)); + } + + function rankAlliances(userId, { worldId, after, limit }) { + const now = fresh(); + const me = rankingWorld(userId, worldId); + const fp = footprints(me.world_id, now); + const byAlliance = new Map(); + for (const o of db.all('SELECT o.id AS id, o.alliance_id AS aid FROM operators o WHERE o.world_id = ? AND o.alliance_id IS NOT NULL', me.world_id)) { + const cur = byAlliance.get(o.aid) || { footprint: 0, members: 0, towns: 0 }; + const f = fp.get(o.id) || { footprint: 0, towns: 0 }; + cur.footprint += f.footprint; cur.towns += f.towns; cur.members += 1; + byAlliance.set(o.aid, cur); + } + const rows = db.all('SELECT id, name, tag FROM alliances WHERE world_id = ?', me.world_id).map((a) => { + const s = byAlliance.get(a.id) || { footprint: 0, members: 0, towns: 0 }; + return { allianceId: a.id, name: a.name, tag: a.tag, members: s.members, towns: s.towns, footprint: Math.round(s.footprint * 100) / 100 }; + }).sort((x, y) => y.footprint - x.footprint || x.allianceId - y.allianceId); + const mm = A.membership(db, me.id); + const you = mm ? rows.findIndex((r) => r.allianceId === mm.alliance_id) : -1; + return Object.assign({ serverTime: now, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit)); + } + + // Battle points come from operator_stats, created by the military stage (migration 002). Without the table the + // list is simply empty (`available: false`). + function rankBattles(userId, { worldId, by, after, limit }) { + const now = fresh(); + const me = rankingWorld(userId, worldId); + by = by || 'attack'; + if (!hasTable(db, 'operator_stats')) return Object.assign({ serverTime: now, by, available: false, total: 0, you: null }, page([], after, limit)); + const rows = db.all(`SELECT o.id AS id, o.name AS name, a.tag AS tag, s.attack_points AS att, s.defense_points AS def + FROM operator_stats s JOIN operators o ON o.id = s.operator_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?`, me.world_id) + .map((r) => ({ operatorId: r.id, name: r.name, allianceTag: r.tag, attackPoints: r.att || 0, defensePoints: r.def || 0 })) + .filter((r) => r.attackPoints > 0 || r.defensePoints > 0) + .sort((x, y) => { + const k = (r) => (by === 'defense' ? r.defensePoints : by === 'total' ? r.attackPoints + r.defensePoints : r.attackPoints); + return k(y) - k(x) || x.operatorId - y.operatorId; + }); + const you = rows.findIndex((r) => r.operatorId === me.id); + return Object.assign({ serverTime: now, by, available: true, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit)); + } + + // ---------------------------------------------------------------- messages + + const BASE = `SELECT m.*, s.name AS sname, t.name AS tname, r.operator_id AS rop, r.read_at AS rread + FROM messages m JOIN operators s ON s.id = m.sender_id LEFT JOIN operators t ON t.id = m.to_id + LEFT JOIN message_recipients r ON r.message_id = m.id AND r.operator_id = ?`; + const VISIBLE_IN = '(r.operator_id IS NOT NULL AND r.deleted_at IS NULL)'; + const VISIBLE_OUT = '(m.sender_id = ? AND m.sender_deleted_at IS NULL)'; + + function msgView(row, meId) { + const out = row.sender_id === meId; + return { + id: row.id, kind: row.kind, direction: out ? 'out' : 'in', thread: row.thread, + from: opBrief(row.sender_id, row.sname), to: row.kind === 'dm' ? opBrief(row.to_id, row.tname) : null, + alliance: row.kind === 'alliance' ? { id: row.alliance_id, tag: row.alliance_tag } : null, + text: row.body, createdAt: row.created_at, readAt: out ? null : row.rread, + }; + } + + function messagePage(me, sql, params, limit) { + limit = limit || 30; + const rows = db.all(sql + ' ORDER BY m.id DESC LIMIT ?', me.id, ...params, limit + 1); + const items = rows.slice(0, limit).map((r) => msgView(r, me.id)); + return { items, next: rows.length > limit ? items[items.length - 1].id : null }; + } + + const unreadCount = (opId) => db.get('SELECT COUNT(*) AS n FROM message_recipients WHERE operator_id = ? AND read_at IS NULL AND deleted_at IS NULL', opId).n; + + function inbox(userId, { worldId, after, limit, unread }) { + const now = fresh(); + const me = A.operatorOf(db, userId, worldId); + const sql = BASE + ' WHERE ' + VISIBLE_IN + (unread ? ' AND r.read_at IS NULL' : '') + ' AND m.id < ?'; + return Object.assign({ serverTime: now, unread: unreadCount(me.id) }, messagePage(me, sql, [after || MAX_ID], limit)); + } + + function outbox(userId, { worldId, after, limit }) { + const now = fresh(); + const me = A.operatorOf(db, userId, worldId); + return Object.assign({ serverTime: now }, messagePage(me, BASE + ' WHERE ' + VISIBLE_OUT + ' AND m.id < ?', [me.id, after || MAX_ID], limit)); + } + + // Conversation with one operator, both directions, newest first. + function thread(userId, otherId, { after, limit }) { + const now = fresh(); + const other = db.get('SELECT id, world_id FROM operators WHERE id = ?', otherId); + const me = other && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, other.world_id); + if (!other || !me) throw new GameError('not_found', { what: 'operator' }); + const key = 'dm:' + Math.min(me.id, other.id) + ':' + Math.max(me.id, other.id); + const sql = BASE + ' WHERE m.thread = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ') AND m.id < ?'; + return Object.assign({ serverTime: now }, messagePage(me, sql, [key, me.id, after || MAX_ID], limit)); + } + + // Broadcasts of the caller's current alliance. + function allianceFeed(userId, { worldId, after, limit }) { + const now = fresh(); + const me = A.operatorOf(db, userId, worldId); + const m = A.membership(db, me.id); + if (!m) throw new GameError('not_in_alliance'); + const sql = BASE + ' WHERE m.thread = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ') AND m.id < ?'; + return Object.assign({ serverTime: now }, messagePage(me, sql, ['alliance:' + m.alliance_id, me.id, after || MAX_ID], limit)); + } + + function message(userId, id) { + const now = fresh(); + const m = db.get('SELECT world_id FROM messages WHERE id = ?', id); + const me = m && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, m.world_id); + if (!m || !me) throw new GameError('not_found', { what: 'message' }); + const row = db.get(BASE + ' WHERE m.id = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ')', me.id, id, me.id); + if (!row) throw new GameError('not_found', { what: 'message' }); + return { serverTime: now, message: msgView(row, me.id) }; + } + + function blocks(userId, { worldId }) { + const now = fresh(); + const me = A.operatorOf(db, userId, worldId); + const rows = db.all('SELECT b.blocked_id AS id, o.name AS name, b.created_at AS at FROM message_blocks b JOIN operators o ON o.id = b.blocked_id WHERE b.operator_id = ? ORDER BY b.created_at, b.blocked_id', me.id); + return { serverTime: now, items: rows.map((r) => ({ operatorId: r.id, name: r.name, createdAt: r.at })), next: null }; + } + + return { + mine, list, get, members, invitesSent, invitesReceived, notes, diplomacy, + rankOperators, rankAlliances, rankBattles, + inbox, outbox, thread, allianceFeed, message, blocks, footprints, + }; +} + +module.exports = { createSocialQueries }; diff --git a/server/state.js b/server/state.js index e2a0182..c7991a7 100644 --- a/server/state.js +++ b/server/state.js @@ -35,6 +35,10 @@ function unitDraw(db, townId) { const rows = db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId); let draw = 0; for (const r of rows) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count; + // Reinforcements draw from the host, not from their owner. + if (hasTable(db, 'stationed')) { + for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ?', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count; + } return draw; } diff --git a/server/text.js b/server/text.js new file mode 100644 index 0000000..9e690b7 --- /dev/null +++ b/server/text.js @@ -0,0 +1,26 @@ +'use strict'; +/* + * Plain-text hygiene for everything players type that other players read (messages, notes, alliance names). + * Strips control characters and the invisible/bidirectional formatting characters that can be used to spoof text + * ("Trojan Source" style reordering, zero-width padding to hide content), normalises to NFC and fixes lone surrogates. + * Newlines and tabs survive only in multiline text. + */ +// C0 (except \t \n, CR is normalised first), DEL + C1, ALM, zero-width space, LRM/RLM, bidi embeddings/overrides +// (202A-202E), word joiner and invisible operators (2060-2064), bidi isolates and deprecated formatting (2066-206F), +// BOM, interlinear annotation, and the invisible Unicode tag block. ZWJ/ZWNJ (200C/200D) stay: emoji and some scripts need them. +const STRIP = new RegExp('[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200B\\u200E\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u206F\\uFEFF\\uFFF9-\\uFFFB\\u{E0000}-\\u{E007F}]', 'gu'); + +function cleanText(input, opts) { + const multiline = !!(opts && opts.multiline); + let s = String(input === undefined || input === null ? '' : input); + if (s.toWellFormed) s = s.toWellFormed(); + s = s.normalize('NFC').replace(/\r\n?/g, '\n').replace(/[\u2028\u2029\u0085]/g, '\n').replace(STRIP, ''); + if (multiline) s = s.replace(/[ \t]+\n/g, '\n').replace(/\n{4,}/g, '\n\n\n'); + else s = s.replace(/[\n\t]+/g, ' ').replace(/ {2,}/g, ' '); + return s.trim(); +} + +// Length in code points (what a player counts), not UTF-16 units. +const textLength = (s) => { let n = 0; for (const _ of s) n++; return n; }; // eslint-disable-line no-unused-vars + +module.exports = { cleanText, textLength }; diff --git a/test/admin-cli.test.js b/test/admin-cli.test.js new file mode 100644 index 0000000..85e74c3 --- /dev/null +++ b/test/admin-cli.test.js @@ -0,0 +1,284 @@ +'use strict'; +// tools/admin.js against temp databases. The ban test runs the real HTTP server and the CLI on the same DB file +// at the same time, which is exactly how the CLI is used in production. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const admin = require('../tools/admin.js'); +const { createServer } = require('../server'); +const { openDb, migrate } = require('../server/db'); + +function tmp() { return fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-admin-test-')); } + +// run the CLI in-process; returns { code, out, err, json } +function cli(dbPath, args, now) { + const out = [], err = []; + const code = admin.main(args.concat(['--db', dbPath]), { out: (s) => out.push(s), err: (s) => err.push(s), env: {}, now: now ? () => now : undefined }); + const text = out.join('\n'); + let json = null; + if (args.includes('--json')) { try { json = JSON.parse(text); } catch (e) { /* not json */ } } + return { code, out: text, err: err.join('\n'), json }; +} + +function freshDb(dir) { + const file = path.join(dir, 'game.db'); + const db = openDb(file); migrate(db); db.close(); + return file; +} + +async function api(srv, method, url, body, token) { + const res = await fetch('http://127.0.0.1:' + srv.port + '/api/v1' + url, { + method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}), + body: body ? JSON.stringify(body) : undefined, + }); + return { status: res.status, body: await res.json() }; +} + +test('parseArgs, parseTime, parseDuration', () => { + const a = admin.parseArgs(['backup', '/x', '--keep', '5', '--yes', '--type=buildDone']); + assert.deepEqual(a._, ['backup', '/x']); + assert.deepEqual(a.flags, { keep: '5', yes: true, type: 'buildDone' }); + assert.throws(() => admin.parseArgs(['events', '--limit']), /needs a value/); + const now = Date.UTC(2026, 0, 1); + assert.equal(admin.parseTime('now', now), now); + assert.equal(admin.parseTime('+2h', now), now + 7200e3); + assert.equal(admin.parseTime('-30m', now), now - 1800e3); + assert.equal(admin.parseTime('2026-01-02T00:00:00Z', now), now + 86400e3); + assert.equal(admin.parseDuration('14d'), 14 * 86400e3); + assert.throws(() => admin.parseTime('soon', now), /bad time/); +}); + +test('help and unknown command', () => { + const dir = tmp(); + const h = cli(path.join(dir, 'none.db'), ['help']); + assert.equal(h.code, 0); + assert.match(h.out, /reset-world/); + const u = cli(path.join(dir, 'none.db'), ['frobnicate']); + assert.equal(u.code, 2); + assert.match(u.err, /unknown command/); +}); + +test('missing database is an error, not a silently created empty file', () => { + const dir = tmp(); + const file = path.join(dir, 'nope.db'); + const r = cli(file, ['worlds']); + assert.equal(r.code, 1); + assert.match(r.err, /database not found/); + assert.equal(fs.existsSync(file), false); +}); + +test('create-world, worlds, end-world needs --yes', () => { + const file = freshDb(tmp()); + const c = cli(file, ['create-world', '--name', 'Lab', '--speed', '3', '--radius', '12', '--seed', '42', '--json']); + assert.equal(c.code, 0); + assert.equal(c.json.world.name, 'Lab'); + assert.equal(c.json.world.seed, 42); + assert.equal(c.json.world.map_radius, 12); + assert.equal(cli(file, ['create-world', '--speed', 'fast']).code, 2); + const w = cli(file, ['worlds', '--json']); + assert.equal(w.json.worlds.length, 1); + const id = w.json.worlds[0].id; + assert.equal(cli(file, ['end-world', String(id)]).code, 2); + assert.equal(cli(file, ['worlds', '--json']).json.worlds[0].status, 'running'); + assert.equal(cli(file, ['end-world', String(id), '--yes']).code, 0); + assert.equal(cli(file, ['worlds', '--json']).json.worlds[0].status, 'ended'); + assert.equal(cli(file, ['end-world', '99', '--yes']).code, 3); +}); + +test('backup: readable verified snapshot, never overwrites, retention prunes only its own files', () => { + const dir = tmp(); + const file = freshDb(dir); + cli(file, ['create-world', '--name', 'Backed up']); + const dest = path.join(dir, 'bk'); + fs.mkdirSync(dest); + fs.writeFileSync(path.join(dest, 'notes.txt'), 'keep me'); + const t0 = Date.UTC(2026, 5, 1, 4, 0, 0); + + const b1 = cli(file, ['backup', dest, '--json'], t0); + assert.equal(b1.code, 0, b1.err); + assert.match(path.basename(b1.json.file), /^upstream-20260601T040000Z\.db$/); + const v = admin.verifySnapshot(b1.json.file); + assert.equal(v.integrity, 'ok'); + assert.equal(v.worlds, 1); + assert.equal(cli(file, ['verify-backup', b1.json.file]).code, 0); + + // the snapshot opens as an ordinary database and holds the data + const snap = openDb(b1.json.file); + assert.equal(snap.get('SELECT name FROM worlds').name, 'Backed up'); + snap.close(); + + // same second: a second file, the first one untouched + const before = fs.readFileSync(b1.json.file); + const b2 = cli(file, ['backup', dest, '--json'], t0); + assert.equal(b2.code, 0); + assert.notEqual(b2.json.file, b1.json.file); + assert.deepEqual(fs.readFileSync(b1.json.file), before); + + // retention by count: three more days of snapshots, keep 2 + for (let d = 1; d <= 3; d++) assert.equal(cli(file, ['backup', dest], t0 + d * 86400e3).code, 0); + const r = cli(file, ['backup', dest, '--keep', '2', '--json'], t0 + 4 * 86400e3); + assert.equal(r.code, 0); + const left = admin.listBackups(dest).map((b) => b.name); + assert.equal(left.length, 2); + assert.ok(left[0].includes('20260605')); + assert.ok(fs.existsSync(path.join(dest, 'notes.txt')), 'foreign files are never touched'); + assert.equal(fs.readdirSync(dest).filter((n) => n.startsWith('.partial')).length, 0); + + // a corrupt target is not a backup + fs.writeFileSync(path.join(dir, 'junk.db'), 'not a database'); + assert.notEqual(cli(file, ['verify-backup', path.join(dir, 'junk.db')]).code, 0); +}); + +test('pruneSet: count, age, both, never the newest', () => { + const now = Date.UTC(2026, 5, 10); + const mk = (daysAgo) => ({ name: 'd' + daysAgo, at: now - daysAgo * 86400e3, seq: 0 }); + const list = [mk(0), mk(1), mk(2), mk(5), mk(9)]; + assert.deepEqual(admin.pruneSet(list, now, {}), []); + assert.deepEqual(admin.pruneSet(list, now, { keep: 2 }).map((b) => b.name), ['d2', 'd5', 'd9']); + assert.deepEqual(admin.pruneSet(list, now, { keepDays: 3 }).map((b) => b.name), ['d5', 'd9']); + assert.deepEqual(admin.pruneSet(list, now, { keep: 1, keepDays: 3 }).map((b) => b.name), ['d5', 'd9']); + assert.deepEqual(admin.pruneSet(list, now, { keep: 1, keepDays: 0.1 }).map((b) => b.name), ['d1', 'd2', 'd5', 'd9']); +}); + +test('ban stops login and revokes tokens on a RUNNING server; unban restores; output never leaks secrets', async () => { + const dir = tmp(); + const file = path.join(dir, 'game.db'); + const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, world: { mapRadius: 20 } }); + try { + const s = await api(srv, 'POST', '/auth/signup', { username: 'mallory', password: 'correct horse battery' }); + assert.equal(s.status, 201); + const token = s.body.token; + assert.equal((await api(srv, 'GET', '/me', null, token)).status, 200); + + const u = cli(file, ['users']); + assert.match(u.out, /mallory/); + assert.ok(!u.out.includes(token)); + assert.ok(!/scrypt/.test(u.out + cli(file, ['inspect-operator', 'mallory']).out), 'no password hashes in output'); + + const b = cli(file, ['ban', 'mallory', '--json']); + assert.equal(b.code, 0, b.err); + assert.equal(b.json.tokensRevoked, 1); + assert.equal((await api(srv, 'GET', '/me', null, token)).status, 401, 'old token is dead'); + const login = await api(srv, 'POST', '/auth/login', { username: 'mallory', password: 'correct horse battery' }); + assert.equal(login.status, 403); + assert.equal(login.body.error.code, 'forbidden'); + assert.match(cli(file, ['users', '--banned']).out, /BANNED/); + + assert.equal(cli(file, ['unban', 'mallory']).code, 0); + const again = await api(srv, 'POST', '/auth/login', { username: 'mallory', password: 'correct horse battery' }); + assert.equal(again.status, 200); + + assert.equal(cli(file, ['revoke-tokens', 'mallory', '--json']).json.revoked, 1); + assert.equal((await api(srv, 'GET', '/me', null, again.body.token)).status, 401); + assert.equal(cli(file, ['ban', 'nobody']).code, 3); + } finally { await srv.close(); } +}); + +test('inspect-town, grant (needs --yes), events and replay-events leave the database untouched', async () => { + const dir = tmp(); + const file = path.join(dir, 'game.db'); + const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false, world: { mapRadius: 20 } }); + let townId; + try { + const s = await api(srv, 'POST', '/auth/signup', { username: 'ada', password: 'analytical engine' }); + townId = s.body.operators[0].towns ? s.body.operators[0].towns[0].id : (await api(srv, 'GET', '/me', null, s.body.token)).body.operators[0].towns[0].id; + const built = await api(srv, 'POST', '/towns/' + townId + '/build', { key: 'f1' }, s.body.token); + assert.equal(built.status, 201, JSON.stringify(built.body)); + } finally { await srv.close(); } + + const it = cli(file, ['inspect-town', String(townId), '--json']); + assert.equal(it.code, 0, it.err); + assert.equal(it.json.town.id, townId); + assert.ok(it.json.buildings.length >= 1); + assert.equal(it.json.queue.length, 1); + assert.ok(it.json.town.resources.fiber > 0); + assert.equal(cli(file, ['inspect-town', '99999']).code, 3); + assert.equal(cli(file, ['inspect-operator', 'ada', '--json']).json.operators[0].towns[0].id, townId); + + // grant: refused without --yes, nothing changes + const before = it.json.town.resources.fiber; + assert.equal(cli(file, ['grant', String(townId), '--fiber', '500']).code, 2); + assert.equal(cli(file, ['inspect-town', String(townId), '--json']).json.town.resources.fiber, before); + const g = cli(file, ['grant', String(townId), '--fiber', '10', '--yes', '--json']); + assert.equal(g.code, 0, g.err); + assert.ok(g.json.after.fiber >= g.json.before.fiber + 9.9); + assert.equal(cli(file, ['grant', String(townId), '--yes']).code, 2); + + // events + const ev = cli(file, ['events', '--pending', '--json']); + assert.equal(ev.json.events.length, 1); + assert.equal(ev.json.events[0].type, 'buildDone'); + assert.equal(cli(file, ['events', '--type', 'nothing', '--json']).json.events.length, 0); + + // replay: dry run and simulation never change the real queue + const dbSnapshot = () => { const db = openDb(file); const r = db.all('SELECT id, status, due_at FROM events ORDER BY id'); const n = db.get('SELECT COUNT(*) AS n FROM notifications').n; const b = db.all('SELECT * FROM buildings ORDER BY town_id, key'); db.close(); return JSON.stringify([r, n, b]); }; + const snap = dbSnapshot(); + const far = cli(file, ['replay-events', '--until', '+30d', '--simulate', '--json']); + assert.equal(far.code, 0, far.err); + assert.equal(far.json.dueCount, 1); + assert.equal(far.json.simulated.outcome[0].status, 'done'); + assert.ok(far.json.simulated.notifications >= 1); + assert.equal(dbSnapshot(), snap, 'the real database is unchanged'); + const near = cli(file, ['replay-events', '--json']); + assert.equal(near.json.dueCount, 0); + assert.ok(near.json.next && near.json.next.type === 'buildDone'); + assert.equal(dbSnapshot(), snap); + assert.deepEqual(fs.readdirSync(os.tmpdir()).filter((n) => n.startsWith('upstream-replay-')).length, 0, 'scratch copy removed'); +}); + +test('reset-world refuses without --yes-destroy, then wipes the world and keeps accounts', async () => { + const dir = tmp(); + const file = path.join(dir, 'game.db'); + const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false, world: { mapRadius: 20 } }); + try { + const s = await api(srv, 'POST', '/auth/signup', { username: 'grace', password: 'compiler compiler' }); + assert.equal(s.status, 201); + } finally { await srv.close(); } + const counts = () => { const db = openDb(file); const r = { users: db.get('SELECT COUNT(*) AS n FROM users').n, tokens: db.get('SELECT COUNT(*) AS n FROM tokens').n, towns: db.get('SELECT COUNT(*) AS n FROM towns').n, operators: db.get('SELECT COUNT(*) AS n FROM operators').n, buildings: db.get('SELECT COUNT(*) AS n FROM buildings').n }; db.close(); return r; }; + const before = counts(); + assert.equal(before.towns, 1); + + const refused = cli(file, ['reset-world', '1']); + assert.equal(refused.code, 2); + assert.match(refused.err, /--yes-destroy/); + assert.deepEqual(counts(), before, 'refusal changes nothing'); + assert.equal(cli(file, ['reset-world', '1', '--yes']).code, 2, '--yes is not enough for reset-world'); + + const bk = path.join(dir, 'bk'); + const done = cli(file, ['reset-world', '1', '--yes-destroy', '--backup', bk, '--new-seed', '--json']); + assert.equal(done.code, 0, done.err); + const after = counts(); + assert.equal(after.towns, 0); + assert.equal(after.operators, 0); + assert.equal(after.buildings, 0); + assert.equal(after.users, 1, 'accounts are kept'); + assert.equal(after.tokens, 1, 'tokens are kept'); + assert.equal(admin.listBackups(bk).length, 1, 'a backup was taken first'); + assert.equal(admin.verifySnapshot(path.join(bk, admin.listBackups(bk)[0].name)).towns, 1, 'the backup still has the town'); + assert.equal(cli(file, ['reset-world', '77', '--yes-destroy']).code, 3); + + // the world is playable again: the account can join it + const srv2 = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false }); + try { + const login = await api(srv2, 'POST', '/auth/login', { username: 'grace', password: 'compiler compiler' }); + assert.equal(login.status, 200); + assert.equal(login.body.operators.length, 0); + assert.equal(srv2.db.get('SELECT COUNT(*) AS n FROM worlds').n, 1); + } finally { await srv2.close(); } +}); + +test('resetPlan finds tables of later stages by world_id and foreign keys', () => { + const db = openDb(':memory:'); + migrate(db); + db.exec('CREATE TABLE zz_movements (id INTEGER PRIMARY KEY, world_id INTEGER NOT NULL, town_id INTEGER); CREATE TABLE zz_units (town_id INTEGER, unit TEXT, count INTEGER); CREATE TABLE zz_global (id INTEGER PRIMARY KEY, note TEXT)'); + const plan = admin.resetPlan(db, 1); + const names = plan.steps.map((s) => s.table); + for (const t of ['zz_movements', 'zz_units', 'towns', 'buildings', 'events', 'operators']) assert.ok(names.includes(t), t); + assert.ok(names.indexOf('buildings') < names.indexOf('towns'), 'children before parents'); + assert.ok(names.indexOf('towns') < names.indexOf('operators')); + assert.ok(plan.skipped.includes('zz_global')); + for (const t of ['users', 'tokens', 'worlds', 'schema_migrations']) assert.ok(!names.includes(t), t); + db.close(); +}); diff --git a/test/client-api.test.js b/test/client-api.test.js new file mode 100644 index 0000000..1319658 --- /dev/null +++ b/test/client-api.test.js @@ -0,0 +1,186 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const { createApi, ApiError } = require('../public/js/api.js'); + +// A scripted fetch: each call takes the next response (or throws when given an Error). +function harness(script, extra) { + const calls = []; + const sleeps = []; + let t = 1000; + const store = new Map(); + const api = createApi(Object.assign({ + fetch: async (url, init) => { + calls.push({ url, init }); + const step = script.shift(); + if (step instanceof Error) throw step; + t += step.rtt || 0; + return { + ok: step.status >= 200 && step.status < 300, status: step.status, + headers: { get: (k) => (step.headers || {})[k] || null }, + json: async () => step.body, + }; + }, + now: () => t, sleep: async (ms) => { sleeps.push(ms); t += ms; }, jitter: () => 0.5, + storage: { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => store.set(k, v), removeItem: (k) => store.delete(k) }, + randomHex: (() => { let n = 0; return () => 'abcdef' + String(++n).padStart(6, '0'); })(), + }, extra)); + return { api, calls, sleeps, store, tick: (ms) => { t += ms; } }; +} + +const ok = (body, more) => Object.assign({ status: 200, body: Object.assign({ serverTime: 5000 }, body) }, more); +const err = (status, code, more) => Object.assign({ status, body: { serverTime: 5000, error: { code, message: code, details: {} } } }, more); + +test('bearer token, JSON body and Idempotency-Key on authenticated POST', async () => { + const h = harness([ok({ a: 1 })]); + h.api.setToken('tok'); + assert.strictEqual(h.store.get('upstream.token'), 'tok'); + await h.api.post('/towns/1/build', { key: 'f1' }); + const { url, init } = h.calls[0]; + assert.strictEqual(url, 'api/v1/towns/1/build'); + assert.strictEqual(init.headers.Authorization, 'Bearer tok'); + assert.strictEqual(init.headers['Content-Type'], 'application/json'); + assert.ok(h.api.isValidKey(init.headers['Idempotency-Key'])); + assert.strictEqual(init.body, '{"key":"f1"}'); +}); + +test('login POST carries no token and no idempotency key; GET carries no key', async () => { + const h = harness([ok({}), ok({})]); + await h.api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false }); + assert.strictEqual(h.calls[0].init.headers['Idempotency-Key'], undefined); + assert.strictEqual(h.calls[0].init.headers.Authorization, undefined); + h.api.setToken('t'); + await h.api.get('/me'); + assert.strictEqual(h.calls[1].init.headers['Idempotency-Key'], undefined); +}); + +test('query string is encoded and skips undefined values', async () => { + const h = harness([ok({})]); + await h.api.get('/map', { x: -3, y: 4, r: 20, worldId: undefined }); + assert.strictEqual(h.calls[0].url, 'api/v1/map?x=-3&y=4&r=20'); +}); + +test('error envelope becomes ApiError with code, status and details', async () => { + const h = harness([{ status: 409, body: { serverTime: 1, error: { code: 'not_enough_resources', message: 'no', details: { key: 'f1' } } } }]); + h.api.setToken('t'); + await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }), (e) => e instanceof ApiError && e.code === 'not_enough_resources' && e.status === 409 && e.details.key === 'f1'); +}); + +test('401 clears the token and emits unauthorized', async () => { + const h = harness([err(401, 'unauthorized')]); + h.api.setToken('t'); + let fired = 0; + h.api.on('unauthorized', () => fired++); + await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'unauthorized'); + assert.strictEqual(fired, 1); + assert.strictEqual(h.api.hasToken(), false); + assert.strictEqual(h.store.has('upstream.token'), false); +}); + +test('network errors on GET retry with growing backoff, then succeed', async () => { + const h = harness([new TypeError('fail'), new TypeError('fail'), ok({ fine: true })]); + const events = []; + h.api.on('offline', () => events.push('offline')); h.api.on('online', () => events.push('online')); + const r = await h.api.get('/me'); + assert.strictEqual(r.fine, true); + assert.deepStrictEqual(h.sleeps, [400, 800]); + assert.deepStrictEqual(events, ['offline', 'online']); +}); + +test('network errors give up as network_error after the retry budget', async () => { + const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x')], { maxRetries: 2 }); + await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'network_error' && e.status === 0); + assert.strictEqual(h.calls.length, 3); +}); + +test('unkeyed POST (login) is NOT retried on a network error', async () => { + const h = harness([new TypeError('x'), ok({})]); + await assert.rejects(() => h.api.post('/auth/signup', { username: 'a' }, { auth: false }), (e) => e.code === 'network_error'); + assert.strictEqual(h.calls.length, 1); +}); + +test('429 honours Retry-After (seconds) and is retried even for unkeyed POSTs', async () => { + const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '3' } }), ok({ done: 1 })]); + const r = await h.api.post('/auth/login', {}, { auth: false }); + assert.strictEqual(r.done, 1); + assert.deepStrictEqual(h.sleeps, [3000]); +}); + +test('a Retry-After beyond the cap is handed to the caller instead of blocking', async () => { + const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '120' } })]); + await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'rate_limited' && e.retryAfter === 120); + assert.deepStrictEqual(h.sleeps, []); +}); + +test('retries of one call reuse its Idempotency-Key; the next call gets a new one', async () => { + const h = harness([new TypeError('x'), ok({}), ok({})]); + h.api.setToken('t'); + await h.api.post('/towns/1/build', { key: 'f1' }); + await h.api.post('/towns/1/build', { key: 'f1' }); + const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']); + assert.strictEqual(keys[0], keys[1]); + assert.notStrictEqual(keys[1], keys[2]); +}); + +test('an intent keeps its key across failed attempts until the server answers', async () => { + const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x'), err(409, 'not_enough_resources'), ok({})], { maxRetries: 0 }); + h.api.setToken('t'); + for (let i = 0; i < 3; i++) await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'network_error'); + assert.deepStrictEqual(h.api.pendingIntents(), ['build:1:f1']); + await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'not_enough_resources'); + assert.deepStrictEqual(h.api.pendingIntents(), []); // definite answer: the intent is over + await h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }); + const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']); + assert.strictEqual(new Set(keys.slice(0, 4)).size, 1); + assert.notStrictEqual(keys[4], keys[3]); +}); + +test('request_in_progress is retried after a short delay', async () => { + const h = harness([err(409, 'request_in_progress'), ok({ x: 1 })]); + h.api.setToken('t'); + const r = await h.api.post('/towns/1/build', { key: 'f1' }); + assert.strictEqual(r.x, 1); + assert.strictEqual(h.sleeps.length, 1); +}); + +test('503 on GET is retried, on unkeyed POST is not', async () => { + const a = harness([err(503, 'internal_error'), ok({ y: 1 })]); + assert.strictEqual((await a.api.get('/me')).y, 1); + const b = harness([err(503, 'internal_error'), ok({})]); + await assert.rejects(() => b.api.post('/auth/login', {}, { auth: false }), (e) => e.status === 503); + assert.strictEqual(b.calls.length, 1); +}); + +test('server clock offset comes from the lowest-latency sample; replayed responses are ignored', async () => { + // t0=1000, rtt 400, serverTime 5000 -> offset 5000 - 1200 = 3800 + const h = harness([ok({}, { rtt: 400 }), ok({ serverTime: 99999 }, { rtt: 100 }), ok({ serverTime: 1 }, { rtt: 900 }), ok({ serverTime: 99999 }, { rtt: 1, headers: { 'Idempotent-Replay': 'true' } })]); + await h.api.get('/me'); + assert.strictEqual(h.api.serverOffset(), 3800); + await h.api.get('/me'); // better rtt (100): adopted. t0 was 1400 -> mid 1450 -> offset 99999-1450 + assert.strictEqual(h.api.serverOffset(), 99999 - 1450); + const before = h.api.serverOffset(); + await h.api.get('/me'); // worse rtt: kept + assert.strictEqual(h.api.serverOffset(), before); + await h.api.get('/me'); // replay: ignored + assert.strictEqual(h.api.serverOffset(), before); +}); + +test('push events can be emitted and unsubscribed; a throwing listener does not break others', () => { + const h = harness([]); + const got = []; + const off = h.api.on('push', (m) => got.push(m)); + h.api.on('push', () => { throw new Error('boom'); }); + h.api.on('push', (m) => got.push('2:' + m.type)); + h.api.emit('push', { type: 'town', id: 1 }); + off(); + h.api.emit('push', { type: 'x' }); + assert.deepStrictEqual(got, [{ type: 'town', id: 1 }, '2:town', '2:x']); +}); + +test('storage failures fall back to memory', () => { + const api = createApi({ fetch: async () => { throw new Error('unused'); }, storage: { getItem() { throw new Error('denied'); }, setItem() { throw new Error('denied'); }, removeItem() { throw new Error('denied'); } } }); + api.setToken('abc'); + assert.strictEqual(api.getToken(), 'abc'); + api.clearToken(); + assert.strictEqual(api.getToken(), null); +}); diff --git a/test/client-i18n.test.js b/test/client-i18n.test.js new file mode 100644 index 0000000..eec903a --- /dev/null +++ b/test/client-i18n.test.js @@ -0,0 +1,71 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const I = require('../public/js/i18n.js'); +const D = require('../public/js/data.js'); + +const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(','); + +test('en and nb have identical key sets and placeholders', () => { + const en = Object.keys(I.strings.en).sort(), nb = Object.keys(I.strings.nb).sort(); + assert.deepStrictEqual(nb.filter((k) => !en.includes(k)), [], 'keys only in nb'); + assert.deepStrictEqual(en.filter((k) => !nb.includes(k)), [], 'keys only in en'); + for (const k of en) assert.strictEqual(placeholders(I.strings.nb[k]), placeholders(I.strings.en[k]), 'placeholders differ for ' + k); +}); + +test('every building, resource and tile type has a player-facing name in both languages', () => { + for (const l of I.LANGS) { + for (const b of Object.keys(D.BUILDINGS)) { + assert.ok(I.strings[l]['building.' + b + '.name'], l + ' name for ' + b); + assert.ok(I.strings[l]['building.' + b + '.desc'], l + ' desc for ' + b); + } + for (const r of D.RESOURCES.concat(['power', 'battery'])) assert.ok(I.strings[l]['res.' + r], l + ' res.' + r); + for (const t of ['land', 'rural', 'incumbent', 'pop', 'void']) assert.ok(I.strings[l]['tile.' + t], l + ' tile.' + t); + } +}); + +test('every error code the client can meet is translated', () => { + // codes the current screens can see (auth, build, cancel, rename, map, notifications, tokens) + client-side ones + const codes = ['bad_request', 'validation_failed', 'unauthorized', 'invalid_credentials', 'forbidden', 'not_found', 'conflict', 'request_in_progress', + 'idempotency_key_reuse', 'payload_too_large', 'rate_limited', 'internal_error', 'signup_closed', 'username_taken', 'world_full', 'unknown_building', + 'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources', 'network_error', 'unknown', 'method_not_allowed']; + for (const l of I.LANGS) for (const c of codes) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c); +}); + +test('t() fills placeholders, falls back to en then to the key', () => { + assert.strictEqual(I.t('en', 'sheet.build', { n: 3 }), 'Build level 3'); + assert.strictEqual(I.t('nb', 'sheet.build', { n: 3 }), 'Bygg nivå 3'); + assert.strictEqual(I.t('xx', 'common.close'), 'Close'); + assert.strictEqual(I.t('en', 'no.such.key'), 'no.such.key'); + assert.strictEqual(I.t('en', 'sheet.build'), 'Build level {n}'); +}); + +test('duration and clock formatting', () => { + assert.strictEqual(I.fmtDuration('en', 0), '0s'); + assert.strictEqual(I.fmtDuration('en', 45000), '45s'); + assert.strictEqual(I.fmtDuration('en', 133000), '2m 13s'); + assert.strictEqual(I.fmtDuration('en', 3600000), '1h'); + assert.strictEqual(I.fmtDuration('en', 3600000 * 26 + 60000 * 5), '1d 2h'); + assert.strictEqual(I.fmtDuration('nb', 3600000 * 2 + 60000 * 5), '2t 5m'); + assert.strictEqual(I.fmtClock(1), '0:01'); + assert.strictEqual(I.fmtClock(65000), '1:05'); + assert.strictEqual(I.fmtClock(3661000), '1:01:01'); + assert.strictEqual(I.fmtClock(-5), '0:00'); +}); + +test('number formatting', () => { + assert.strictEqual(I.fmtNum('en', 749.9), '749'); + assert.strictEqual(I.fmtNum('en', 123456), '123k'); + assert.strictEqual(I.fmtNum('en', 2500000), '2.5M'); + assert.strictEqual(I.fmtDec('en', 12.34, true), '+12.3'); + assert.strictEqual(I.fmtDec('en', -3, true), '−3.0'); + assert.strictEqual(I.fmtDec('en', 420.4), '420'); +}); + +test('language detection', () => { + assert.strictEqual(I.detectLang('nb-NO'), 'nb'); + assert.strictEqual(I.detectLang('nn'), 'nb'); + assert.strictEqual(I.detectLang('no'), 'nb'); + assert.strictEqual(I.detectLang('en-GB'), 'en'); + assert.strictEqual(I.detectLang(undefined), 'en'); +}); diff --git a/test/helpers.js b/test/helpers.js new file mode 100644 index 0000000..99a0e23 --- /dev/null +++ b/test/helpers.js @@ -0,0 +1,111 @@ +'use strict'; +/* + * Shared test helpers (no tests in here). An in-memory server on port 0 with a fake clock and no background timer: + * events only run when a request, a command or the test calls scheduler.runDue(). + * + * const { createTestServer } = require('./helpers'); + * const t = await createTestServer(); + * const alice = await t.signup('alice'); // { token, userId, operatorId, townId, name } + * const r = await t.api('/alliances', { method: 'POST', body: { name: 'X', tag: 'X1' } }, alice.token); + * t.clock.advance(3600e3); t.srv.scheduler.runDue(); + * await t.close(); + */ +const assert = require('node:assert'); +const { createServer } = require('../server'); +const { FakeClock } = require('../server/clock'); + +// ---- optional response contract check: every 2xx JSON body must satisfy its route's declared `response` schema +// (server/routes/schemas.js), error bodies the Error schema. Opt-in: createTestServer({ contract: true }). +let contractRouter = null; +function contract() { + if (contractRouter) return contractRouter; + const { Router } = require('../server/http'); + const routes = require('../server/routes'); + const router = new Router(); + routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null, apply: () => null }) })); + contractRouter = { router, schemas: require('../server/routes/schemas').schemas }; + return contractRouter; +} + +function conforms(schemas, schema, v, path, errs) { + if (schema.$ref) return conforms(schemas, schemas[schema.$ref], v, path, errs); + const types = Array.isArray(schema.type) ? schema.type : [schema.type]; + if (v === null) { if (!types.includes('null')) errs.push(path + ' is null'); return; } + const t = types.find((x) => x !== 'null'); + if (t === 'integer') { if (!Number.isInteger(v)) errs.push(path + ' not an integer: ' + JSON.stringify(v)); } + else if (t === 'number') { if (typeof v !== 'number') errs.push(path + ' not a number'); } + else if (t === 'string') { if (typeof v !== 'string') errs.push(path + ' not a string'); } + else if (t === 'boolean') { if (typeof v !== 'boolean') errs.push(path + ' not a boolean'); } + else if (t === 'array') { + if (!Array.isArray(v)) errs.push(path + ' not an array'); + else if (schema.items) v.forEach((x, i) => conforms(schemas, schema.items, x, path + '[' + i + ']', errs)); + } else if (t === 'object') { + if (typeof v !== 'object' || Array.isArray(v)) { errs.push(path + ' not an object'); return; } + for (const k of schema.required || []) if (!(k in v)) errs.push(path + '.' + k + ' missing'); + for (const k of Object.keys(schema.properties || {})) if (k in v) conforms(schemas, schema.properties[k], v[k], path + '.' + k, errs); + } +} + +function checkContract(method, path, status, body) { + const { router, schemas } = contract(); + const found = router.find(method, path.split('?')[0].replace(/^\/api\/v1/, '')); + if (!found || !found.route) return; + const errs = []; + conforms(schemas, status < 300 ? (found.route.meta.response || { $ref: 'Ok' }) : { $ref: 'Error' }, body, '', errs); + if (errs.length) throw new assert.AssertionError({ message: method + ' ' + path + ' -> ' + status + ' breaks its response schema: ' + errs.join('; ') + ' in ' + JSON.stringify(body).slice(0, 400) }); +} + +async function createTestServer(o) { + o = o || {}; + const clock = o.clock || new FakeClock(); + const srv = await createServer(Object.assign({ + port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {}, + // many signups and calls from one IP: lift the per-IP/token/auth rate limits + ipRate: 1e6, ipBurst: 1e6, tokenRate: 1e6, tokenBurst: 1e6, authRate: 1e6, authBurst: 1e6, + }, o.server || {})); + const base = 'http://127.0.0.1:' + srv.port + '/api/v1'; + + // api(path, { method, body, headers }, token) -> { status, body, headers } + async function api(path, opts, token) { + opts = opts || {}; + const headers = Object.assign({ 'content-type': 'application/json' }, opts.headers || {}); + if (token) headers.authorization = 'Bearer ' + token; + const r = await fetch(base + path, { method: opts.method || 'GET', headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body) }); + const out = { status: r.status, body: await r.json(), headers: r.headers }; + if (o.contract) checkContract(opts.method || 'GET', path, out.status, out.body); + return out; + } + + const names = new Map(); + async function signup(name) { + const r = await api('/auth/signup', { method: 'POST', body: { username: name, password: 'correct horse battery' } }); + assert.equal(r.status, 201, 'signup ' + name + ': ' + JSON.stringify(r.body)); + const op = r.body.operators[0]; + const u = { token: r.body.token, userId: r.body.user.id, operatorId: op.id, townId: op.towns[0].id, name }; + names.set(name, u); + return u; + } + + // Set a building level directly (tests that need a Peering office without playing through the build chain). + function setBuilding(townId, type, level) { + srv.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?) ON CONFLICT (town_id, key) DO UPDATE SET level = excluded.level', townId, type, type, level); + } + + // signup + Peering office level (default 1), ready to found or join an alliance. + async function signupPeering(name, level) { + const u = await signup(name); + setBuilding(u.townId, 'peering_office', level === undefined ? 1 : level); + return u; + } + + // Bulk operators without the scrypt cost and without a usable token (drive them through srv.commands.run). + function quickSignup(name) { + const r = srv.commands.run('signup', { username: name, passHash: 'x', tokenHash: require('crypto').randomBytes(16).toString('hex'), device: 'test' }); + return { userId: r.userId, operatorId: r.operatorId, townId: r.townId, name }; + } + + const close = () => srv.close(); + return { srv, clock, api, signup, signupPeering, quickSignup, setBuilding, close, base }; +} + +module.exports = { createTestServer, checkContract }; diff --git a/test/military-api.test.js b/test/military-api.test.js new file mode 100644 index 0000000..0e0fd8a --- /dev/null +++ b/test/military-api.test.js @@ -0,0 +1,121 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const { createServer } = require('../server'); +const { FakeClock } = require('../server/clock'); +const T = require('./military-helpers'); +const { D, H } = T; + +// A real server on port 0 with a fake clock: signup two players over HTTP, then drive the military routes. +async function boot() { + const clock = new FakeClock(); + const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {} }); + const base = 'http://127.0.0.1:' + srv.port + '/api/v1'; + const call = async (p, o, token) => { + o = o || {}; + const headers = Object.assign({ 'content-type': 'application/json' }, o.headers || {}); + if (token) headers.authorization = 'Bearer ' + token; + const r = await fetch(base + p, Object.assign({}, o, { headers, body: o.body && JSON.stringify(o.body) })); + return { status: r.status, body: await r.json() }; + }; + const signup = async (username) => { + const r = await call('/auth/signup', { method: 'POST', body: { username, password: 'correct horse battery' } }); + assert.equal(r.status, 201, JSON.stringify(r.body)); + const t = r.body.operators[0].towns[0]; + return { token: r.body.token, townId: t.id, x: t.x, y: t.y, opId: r.body.operators[0].id, userId: r.body.user.id }; + }; + return { srv, clock, call, signup }; +} + +test('API: train, send a raid, warning for the target, reports, recall, error codes', async () => { + const { srv, clock, call, signup } = await boot(); + try { + const a = await signup('alice'), b = await signup('bobby'); + const db = srv.db; + // both start protected (72 h): move the clock past it, give alice infrastructure to train + clock.advance(73 * H); + for (const [t, lv] of [['ops_lab', 3], ['research_lab', 3], ['noc', 2]]) db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, t, t, lv); + db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId); + + let r = await call('/towns/' + a.townId + '/train', { method: 'POST', body: { unit: 'script_crew', count: 20 } }, a.token); + assert.equal(r.status, 201, JSON.stringify(r.body)); + assert.equal(typeof r.body.serverTime, 'number'); + r = await call('/towns/' + a.townId, {}, a.token); + assert.equal(r.body.town.military.training.length, 1); + assert.equal(r.body.town.military.trainable.find((u) => u.unit === 'script_crew').locked, false); + assert.equal(r.body.town.military.trainable.find((u) => u.unit === 'botnet').locked, true); + clock.advance(3 * H); + r = await call('/towns/' + a.townId, {}, a.token); + assert.deepEqual(r.body.town.military.units.home, { script_crew: 20 }); + + // errors are enveloped with stable codes + r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 99 } } }, a.token); + assert.equal(r.status, 409); assert.equal(r.body.error.code, 'not_enough_units'); + r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 5 } } }, b.token); + assert.equal(r.status, 404, 'cannot send from somebody else\'s POP'); + r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 5 }, extra: 1 } }, a.token); + assert.equal(r.status, 422); + r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'teleport', toTownId: b.townId, units: {} } }, a.token); + assert.equal(r.status, 422); + + // alice is protected no more (73 h passed) and bob neither: the raid goes out + r = await call('/movements', { method: 'POST', headers: { 'idempotency-key': 'raid-key-0001' }, body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } } }, a.token); + assert.equal(r.status, 201, JSON.stringify(r.body)); + const mid = r.body.movementId; + const replay = await call('/movements', { method: 'POST', headers: { 'idempotency-key': 'raid-key-0001' }, body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } } }, a.token); + assert.equal(replay.body.movementId, mid, 'idempotent replay: no second movement'); + assert.equal(db.get('SELECT COUNT(*) AS n FROM movements').n, 1); + + r = await call('/movements', {}, b.token); + assert.equal(r.body.incoming.length, 1); assert.equal(r.body.incoming[0].type, 'unknown'); + r = await call('/movements', {}, a.token); + assert.equal(r.body.outgoing[0].type, 'raid'); + + // recall inside 90 s, then send again and let it land + r = await call('/movements/' + mid + '/recall', { method: 'POST' }, a.token); + assert.equal(r.status, 200, JSON.stringify(r.body)); + clock.advance(H); + r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 } } }, a.token); + assert.equal(r.status, 201, JSON.stringify(r.body)); + clock.advance(100 * 1000); + r = await call('/movements/' + r.body.movementId + '/recall', { method: 'POST' }, a.token); + assert.equal(r.status, 409); assert.equal(r.body.error.code, 'recall_expired'); + clock.advance(5 * H); + + r = await call('/reports', {}, a.token); + assert.equal(r.status, 200); assert.equal(r.body.items.length, 1); assert.equal(r.body.unread, 1); + const id = r.body.items[0].id; + const rb = await call('/reports', {}, b.token); + assert.equal(rb.body.items[0].id, id, 'defender sees the same report'); + r = await call('/reports/' + id, {}, a.token); + assert.equal(r.body.report.type, 'raid'); assert.equal(r.body.report.data.outcome, 'attacker_won'); + r = await call('/reports/' + id + '/read', { method: 'POST' }, a.token); + assert.equal(r.status, 200); + r = await call('/reports?unread=true', {}, a.token); + assert.equal(r.body.items.length, 0); + r = await call('/reports/999999', {}, a.token); + assert.equal(r.status, 404); + + // tile info and research over the API + r = await call('/map/tile?x=' + b.x + '&y=' + b.y, {}, a.token); + assert.equal(r.body.type, 'pop'); assert.equal(r.body.town.owner.name, 'bobby'); + r = await call('/towns/' + a.townId + '/research', { method: 'POST', body: { unit: 'script_crew', stat: 'attack' } }, a.token); + assert.equal(r.status, 201, JSON.stringify(r.body)); + r = await call('/towns/' + a.townId + '/research', { method: 'POST', body: { unit: 'script_crew', stat: 'attack' } }, a.token); + assert.equal(r.status, 409); assert.equal(r.body.error.code, 'queue_full'); + r = await call('/notifications', {}, b.token); + assert.ok(r.body.items.some((n) => n.type === 'incoming')); + assert.ok(r.body.items.some((n) => n.type === 'report')); + } finally { await srv.close(); } +}); + +test('API: openapi describes every military route', () => { + const { build } = require('../tools/gen-openapi'); + const spec = build(); + for (const [p, m] of [['/towns/{id}/train', 'post'], ['/towns/{id}/research', 'post'], ['/movements', 'post'], ['/movements', 'get'], ['/movements/{id}/recall', 'post'], + ['/towns/{id}/withdraw', 'post'], ['/reports', 'get'], ['/reports/{id}', 'get'], ['/reports/{id}/read', 'post'], ['/reports/read-all', 'post'], ['/map/tile', 'get']]) { + assert.ok(spec.paths[p] && spec.paths[p][m], m + ' ' + p + ' is in openapi.json'); + } + for (const c of ['not_enough_units', 'units_offline', 'target_protected', 'protection_active', 'footprint_too_low', 'cannot_takeover', 'recall_expired']) assert.ok(spec['x-error-codes'][c], c); + assert.ok(D.UNIT_ORDER.length === 10); +}); diff --git a/test/military-expansion.test.js b/test/military-expansion.test.js new file mode 100644 index 0000000..3f34dc3 --- /dev/null +++ b/test/military-expansion.test.js @@ -0,0 +1,203 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const T = require('./military-helpers'); +const { R, D, H } = T; +const { loadTown } = require('../server/state'); + +function sendTakeover(h, att, targetTownId, units) { + return h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: targetTownId, units: units || { script_crew: 80, ma_team: 2 } }); +} + +test('takeover: loyalty drops by the seeded roll, the POP changes owner at zero, pending work stops', () => { + const h = T.setup(); + const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 80, ma_team: 2 } }); + const def = T.addOperator(h, 'seller', { x: 10, y: 0 }); + const extra = T.addTown(h, def, { x: 12, y: 2, infra: { noc: 2 } }); + h.db.run('UPDATE towns SET loyalty = 40, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId); + h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, 4)', extra.townId, 'soc_analyst'); + h.run('train', { userId: def.userId, townId: extra.townId, unit: 'soc_analyst', count: 5 }); // pending work that must be cancelled + + let s = sendTakeover(h, att, extra.townId); + h.advanceTo(s.arriveAt); + let rep = T.reportsOf(h, att.userId)[0].data; + assert.equal(rep.outcome, 'attacker_won'); + assert.equal(rep.takeover.attempted, true); + assert.ok(rep.takeover.drop >= 15 && rep.takeover.drop <= 30, 'drop in range'); + assert.equal(rep.takeover.captured, false, '40 loyalty needs two hits'); + assert.ok(Math.abs(T.town(h, extra.townId).loyalty - (rep.takeover.loyaltyBefore - rep.takeover.drop)) < 0.01); + assert.equal(T.town(h, extra.townId).owner_id, def.opId); + const retMv = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'"); + assert.equal(JSON.parse(retMv.units).ma_team, 1, 'one M&A team was used up, the other comes home'); + + // second hit + h.advanceTo(retMv.arrive_at); + h.db.run('UPDATE towns SET loyalty = 10, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId); + s = sendTakeover(h, att, extra.townId, { script_crew: 70, ma_team: 1 }); + h.advanceTo(s.arriveAt); + rep = T.reportsOf(h, att.userId)[1].data; + assert.equal(rep.takeover.captured, true); + const taken = T.town(h, extra.townId); + assert.equal(taken.owner_id, att.opId); + assert.equal(taken.is_capital, 0); + assert.equal(taken.loyalty, D.EXPANSION.conqueredLoyalty); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending'", extra.townId).n, 0, 'old owner training cancelled'); + assert.deepEqual(T.units(h, extra.townId), {}, 'the defenders died with the loss'); + assert.equal(T.notes(h, def.userId, 'town_lost').length, 1); + assert.equal(T.notes(h, att.userId, 'town_gained').length, 1); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', def.opId).n, 1); + // loyalty then regenerates for the new owner (+1/h) + const t = loadTown(h.db, extra.townId); + assert.equal(R.loyaltyAt(t.loyalty, t.loyaltyAt, t.loyaltyAt + 10 * H, 1), D.EXPANSION.conqueredLoyalty + 10); +}); + +test('takeover protections: capital is only drained, last POP and low footprint are refused', () => { + const h = T.setup(); + const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 160, ma_team: 4 } }); + const def = T.addOperator(h, 'seller', { x: 10, y: 0 }); + const second = T.addTown(h, def, { x: 12, y: 2 }); + const lone = T.addOperator(h, 'lone', { x: 20, y: 0 }); + // last POP: refused at send + assert.throws(() => sendTakeover(h, att, lone.townId), (e) => e.code === 'cannot_takeover'); + // capital: loyalty is dragged to zero, the owner stays + h.db.run('UPDATE towns SET loyalty = 5, loyalty_at = ? WHERE id = ?', h.clock.now(), def.townId); + const s = sendTakeover(h, att, def.townId, { script_crew: 80, ma_team: 2 }); + h.advanceTo(s.arriveAt); + const rep = T.reportsOf(h, att.userId)[0].data; + assert.equal(rep.takeover.capital, true); + assert.equal(rep.takeover.captured, false); + assert.equal(T.town(h, def.townId).loyalty, 0); + assert.equal(T.town(h, def.townId).owner_id, def.opId); + // footprint gate + const poor = T.addOperator(h, 'poor', { x: 30, y: 0, footprint: 10, units: { script_crew: 80, ma_team: 1 } }); + assert.throws(() => sendTakeover(h, poor, second.townId, { script_crew: 80, ma_team: 1 }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(1)); + // a takeover needs an M&A team, which only goes on takeovers + assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: second.townId, units: { script_crew: 5 } }), (e) => e.code === 'validation_failed'); + assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: second.townId, units: { script_crew: 5, ma_team: 1 } }), (e) => e.code === 'validation_failed'); +}); + +test('exploit kits damage the chosen building on a win; DDoS rigs lower the firewall in the battle', () => { + const h = T.setup(); + const att = T.addOperator(h, 'siege', { x: 5, y: 0, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 } }); + const def = T.addOperator(h, 'wall', { x: 9, y: 0, units: { soc_analyst: 40 }, infra: { firewall: 10, noc: 7 } }); + const s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 }, target: 'noc' }); + h.advanceTo(s.arriveAt); + const rep = T.reportsOf(h, att.userId)[0].data; + assert.equal(rep.outcome, 'attacker_won'); + assert.equal(rep.power.effectiveFirewall, 8, '20 rigs lower a level-10 firewall by 2'); + assert.equal(rep.siege.key, 'noc'); + const kits = rep.attacker.units.survivors.exploit_kit; + assert.equal(rep.siege.to, 7 - R.siegeLevels(kits)); + assert.equal(h.db.get('SELECT level FROM buildings WHERE town_id = ? AND key = ?', def.townId, 'noc').level, rep.siege.to); + // the lost units are gone for good + assert.deepEqual(T.units(h, def.townId), {}); +}); + +test('protection: protected targets cannot be attacked, attacking ends your own protection, arrival re-checks', () => { + const h = T.setup(); + const now = h.clock.now(); + const newbie = T.addOperator(h, 'newbie', { x: 5, y: 0, protectedUntil: now + 72 * H, units: { script_crew: 20, port_scanner: 3 } }); + const vet = T.addOperator(h, 'vet', { x: 9, y: 0, units: { script_crew: 40, port_scanner: 3 } }); + // nobody may attack a protected operator ... + assert.throws(() => h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'raid', toTownId: newbie.townId, units: { script_crew: 10 } }), (e) => e.code === 'target_protected'); + // ... but scouting is allowed + h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'scan', toTownId: newbie.townId, units: { port_scanner: 3 } }); + // a protected operator must confirm to attack, which ends the protection at once + assert.throws(() => h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 } }), (e) => e.code === 'protection_active'); + assert.ok(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p > now, 'the refused send changed nothing'); + const r = h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 }, confirmEndProtection: true }); + assert.equal(r.protectionEnded, true); + assert.equal(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p, now); + // protection that lasts past the arrival blocks the attack at arrival time (units turn around, report to the sender) + const h2 = T.setup(); + const a2 = T.addOperator(h2, 'a', { x: 5, y: 0, units: { script_crew: 30 } }); + const d2 = T.addOperator(h2, 'd', { x: 9, y: 0, units: { soc_analyst: 2 } }); + const s2 = h2.run('sendMovement', { userId: a2.userId, fromTownId: a2.townId, type: 'raid', toTownId: d2.townId, units: { script_crew: 30 } }); + h2.db.run('UPDATE operators SET protection_until = ? WHERE id = ?', s2.arriveAt + H, d2.opId); // e.g. an admin grants protection + h2.advanceTo(s2.arriveAt); + const rep = T.reportsOf(h2, a2.userId)[0]; + assert.equal(rep.type, 'movement_failed'); + assert.equal(rep.data.reason, 'protected'); + assert.equal(T.reportsOf(h2, d2.userId).length, 0, 'the protected side is not bothered'); + assert.deepEqual(T.units(h2, d2.townId), { soc_analyst: 2 }); + h2.advance(10 * H); + assert.equal(T.units(h2, a2.townId).script_crew, 30, 'the units came back untouched'); +}); + +test('expansion: three Rollout crews found a POP; wild slots, empty start, range, footprint, occupied tile', () => { + const h = T.setup(); + const a = T.addOperator(h, 'founder', { x: 5, y: 0, footprint: 3000, units: { rollout_crew: 9 } }); + const spot = T.landNear(h, 12, 3); + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 }, wild: ['substation', 'sales_office'] }); + assert.equal(T.units(h, a.townId).rollout_crew, 6); + h.advanceTo(s.arriveAt); + const t = h.db.get('SELECT * FROM towns WHERE x = ? AND y = ?', spot.x, spot.y); + assert.ok(t, 'a new POP exists'); + assert.equal(t.owner_id, a.opId); assert.equal(t.is_capital, 0); + const b = h.db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', t.id); + assert.ok(b.every((x) => x.level === 0), 'everything at level 0'); + assert.equal(b.length, D.FIELD_SLOTS, 'fields only, no infrastructure'); + assert.equal(b.find((x) => x.key === 'f17').type, 'substation'); + assert.equal(b.find((x) => x.key === 'f18').type, 'sales_office'); + assert.equal(t.fiber, D.EXPANSION.startResources.fiber); + assert.equal(T.reportsOf(h, a.userId)[0].type, 'settle'); + assert.equal(T.units(h, a.townId).rollout_crew, 6, 'the crews were consumed'); + + // the second extra POP needs more footprint (500 * 2^1.8 = 1741 for the 2nd extra; the operator has 3000 + ...) + h.db.run('UPDATE towns SET footprint = 700 WHERE id = ?', a.townId); + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x + 2, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(2)); + // too far from every own POP + const far = T.landNear(h, 30, 0); + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: far.x, y: far.y, units: { rollout_crew: 3 } }), (e) => e.code === 'out_of_range'); + // not exactly three crews + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y + 3, units: { rollout_crew: 2 } }), (e) => e.code === 'validation_failed'); + // an occupied tile + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'invalid_target'); + + // somebody else takes the tile while the crews are on the way: the crews come home with a report + h.db.run('UPDATE towns SET footprint = 99999 WHERE id = ?', a.townId); + const free = T.landNear(h, 10, -4); + const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: free.x, y: free.y, units: { rollout_crew: 3 } }); + const squatter = T.addOperator(h, 'squatter', { x: free.x, y: free.y }); // lands exactly on `free` + assert.equal(squatter.x, free.x); + h.advanceTo(s2.arriveAt); + const failed = T.reportsOf(h, a.userId).filter((r) => r.type === 'movement_failed'); + assert.equal(failed.length, 1); + assert.equal(failed[0].data.reason, 'invalid_target'); + h.advance(48 * H); + assert.equal(T.units(h, a.townId).rollout_crew, 6, 'crews returned'); +}); + +test('incumbent site: static defence, one-time Hardware bonus per operator, research speed bonus', () => { + const h = T.setup({ seed: 99 }); + let site = null; + for (let x = -20; x <= 20 && !site; x++) for (let y = -20; y <= 20 && !site; y++) if (R.tileAt(h.world.seed, 50, x, y).type === 'incumbent' && Math.abs(x) + Math.abs(y) > 6) site = { x, y }; + assert.ok(site, 'the test world has an incumbent site'); + const need = R.incumbentDefence(h.world.seed, site.x, site.y, 0); + const crews = Math.ceil(need / 40 * 1.6); + const a = T.addOperator(h, 'raider', { x: site.x - 3, y: site.y, res: 3000, units: { script_crew: crews } }); + const hwBefore = T.town(h, a.townId).hardware; + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: { script_crew: crews } }); + assert.equal(s.toTownId, null); + h.advanceTo(s.arriveAt); + const rep = T.reportsOf(h, a.userId)[0]; + assert.equal(rep.type, 'incumbent'); + assert.equal(rep.data.outcome, 'attacker_won'); + assert.equal(rep.data.bonus.hardware, D.INCUMBENT.hardwareBonus); + assert.ok(rep.data.bonus.researchSpeedBonus > 0); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', a.opId).n, 1); + const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'"); + h.advanceTo(ret.arrive_at); + assert.ok(T.town(h, a.townId).hardware > hwBefore + 1000, 'the bonus arrived with the survivors'); + // a second take gives no second bonus + const back = JSON.parse(ret.units); + const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: back }); + h.advanceTo(s2.arriveAt); + assert.equal(T.reportsOf(h, a.userId)[1].data.bonus, null); + // research gets faster + const plain = R.researchTimeMs('script_crew', 1, 8, 1, 0), fast = R.researchTimeMs('script_crew', 1, 8, 1, R.researchSpeedBonus(1)); + assert.ok(fast < plain); + // incumbent sites accept only scans and attacks, and defence scales with world age + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', x: site.x, y: site.y, units: { script_crew: 1 } }), (e) => e.code === 'invalid_target' || e.code === 'not_enough_units'); + assert.ok(R.incumbentDefence(h.world.seed, site.x, site.y, 50) > need); +}); diff --git a/test/military-flow.test.js b/test/military-flow.test.js new file mode 100644 index 0000000..9807ae4 --- /dev/null +++ b/test/military-flow.test.js @@ -0,0 +1,148 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const T = require('./military-helpers'); +const { R, D, H } = T; + +test('training: batches of one building run in order, other buildings in parallel, requirements and queue limit', () => { + const h = T.setup(); + const a = T.addOperator(h, 'alice'); + const t0 = h.clock.now(); + const r1 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 10 }); + const r2 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'port_scanner', count: 4 }); // same building (noc): after r1 + const r3 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'script_crew', count: 5 }); // ops_lab: in parallel + assert.equal(r1.startAt, t0); + assert.equal(r2.startAt, r1.dueAt, 'second noc batch starts when the first is done'); + assert.equal(r3.startAt, t0, 'other buildings train in parallel'); + assert.equal(r1.dueAt - r1.startAt, R.trainTimeMs('soc_analyst', 10, 5, 1)); + assert.deepEqual(T.units(h, a.townId), {}); + h.advanceTo(r3.dueAt); + assert.deepEqual(T.units(h, a.townId), { script_crew: 5 }, 'only the parallel batch is done so far'); + h.advanceTo(r1.dueAt); + assert.deepEqual(T.units(h, a.townId), { script_crew: 5, soc_analyst: 10 }); + h.advanceTo(r2.dueAt); + assert.deepEqual(T.units(h, a.townId), { script_crew: 5, soc_analyst: 10, port_scanner: 4 }); + assert.equal(T.notes(h, a.userId, 'train_done').length, 3); + + // unit power draw is part of the town's rates once the units exist + const t = require('../server/state').loadTown(h.db, a.townId); + assert.equal(t.unitDraw, 10 * 1 + 4 * 1 + 5 * 1); + + // costs were paid; requirements are enforced; the queue is limited + assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'exploit_kit', count: 1 }), (e) => e.code === 'requirements_not_met'); + assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'nonsense', count: 1 }), (e) => e.code === 'unknown_unit'); + assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 100000 }), (e) => e.code === 'validation_failed'); + const b = T.addOperator(h, 'bob', { res: 100 }); + assert.throws(() => h.run('train', { userId: b.userId, townId: b.townId, unit: 'botnet', count: 50 }), (e) => e.code === 'not_enough_resources' || e.code === 'requirements_not_met'); + for (let i = 0; i < D.MILITARY.maxTrainQueue; i++) h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 }); + assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 }), (e) => e.code === 'queue_full'); +}); + +test('raid end to end: send, incoming warning, arrive, loot, reports for both sides, return', () => { + const h = T.setup(); + const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 40 } }); + const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 20 }, infra: { rack_hall: 2 } }); + h.db.run('UPDATE towns SET fiber = 600, hardware = 600, capital = 600 WHERE id = ?', def.townId); + const before = T.town(h, def.townId); + + const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } }); + assert.equal(T.units(h, att.townId).script_crew, undefined, 'units left home'); + assert.equal(sent.arriveAt - sent.departAt, R.latencyMs(4, 8, 1)); + + // the target sees origin and ETA but not the type + const mv = h.mq.movements(def.userId, {}); + assert.equal(mv.incoming.length, 1); + assert.equal(mv.incoming[0].type, 'unknown'); + assert.equal(mv.incoming[0].units, undefined); + assert.equal(mv.incoming[0].arriveAt, sent.arriveAt); + assert.equal(h.mq.movements(att.userId, {}).outgoing[0].type, 'raid'); + assert.equal(T.notes(h, def.userId, 'incoming').length, 1); + assert.equal(T.notes(h, def.userId, 'incoming')[0].type, undefined); + + h.advanceTo(sent.arriveAt); + const ra = T.reportsOf(h, att.userId), rd = T.reportsOf(h, def.userId); + assert.equal(ra.length, 1); assert.equal(rd.length, 1); + assert.equal(ra[0].id, rd[0].id, 'one report shared by both sides'); + assert.equal(ra[0].role, 'attacker'); assert.equal(rd[0].role, 'defender'); + const rep = ra[0].data; + assert.equal(rep.outcome, 'attacker_won'); + assert.ok(rep.loot.fiber > 0 && rep.loot.fiber === rep.loot.hardware, 'loot is split evenly'); + // 10% per rack hall level hides stock from a raid: level 2 hides 20% + assert.equal(rep.cacheHidden, 0.2); + const d1 = T.town(h, def.townId); + assert.ok(d1.fiber < before.fiber, 'target lost fiber'); + const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'"); + assert.ok(ret, 'a return movement carries the loot'); + assert.deepEqual(JSON.parse(ret.cargo), rep.loot); + const attBefore = T.town(h, att.townId).fiber; + + h.advanceTo(ret.arrive_at); + assert.equal(T.units(h, att.townId).script_crew, 40 - (rep.attacker.units.lost.script_crew || 0)); + assert.ok(T.town(h, att.townId).fiber > attBefore, 'loot arrived home'); + assert.equal(T.notes(h, att.userId, 'movement_returned').length, 1); + const stats = h.db.get('SELECT * FROM operator_stats WHERE operator_id = ?', att.opId); + assert.ok(stats.attack_points > 0, 'killed units give battle points'); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); +}); + +test('a failed raid loses units and loots nothing; both sides still get the report', () => { + const h = T.setup(); + const att = T.addOperator(h, 'weak', { x: 5, y: 0, units: { script_crew: 2 } }); + const def = T.addOperator(h, 'strong', { x: 8, y: 0, units: { blue_team: 20 }, infra: { firewall: 10 } }); + const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 2 } }); + h.advanceTo(sent.arriveAt); + const rep = T.reportsOf(h, att.userId)[0].data; + assert.equal(rep.outcome, 'defender_won'); + assert.deepEqual(rep.loot, { fiber: 0, hardware: 0, capital: 0 }); + assert.equal(T.units(h, def.townId).blue_team, 20 - (rep.defender.groups[0].lost.blue_team || 0)); + assert.equal(T.reportsOf(h, def.userId).length, 1); +}); + +test('scan: success shows units, resources, buildings at 2:1; failed scan loses scanners and reveals the scanner', () => { + const h = T.setup(); + const att = T.addOperator(h, 'spy', { x: 5, y: 0, units: { port_scanner: 10 } }); + const def = T.addOperator(h, 'watched', { x: 8, y: 0, units: { port_scanner: 3, soc_analyst: 4 } }); + let s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'scan', toTownId: def.townId, units: { port_scanner: 10 } }); + h.advanceTo(s.arriveAt); + const ok = T.reportsOf(h, att.userId).find((r) => r.type === 'scan').data; + assert.equal(ok.success, true); + assert.equal(ok.detail, 'full'); // 10 >= 2 * 3 + assert.deepEqual(ok.intel.units.home, { port_scanner: 3, soc_analyst: 4 }); + assert.ok(ok.intel.buildings.length > 0 && ok.intel.resources.fiber > 0); + const det = T.reportsOf(h, def.userId).find((r) => r.type === 'scan_detected').data; + assert.equal(det.identityRevealed, false, 'the defender only learns who scanned when their scanners win'); + assert.equal(det.by, null); + + // now a scan that fails: 2 scanners against 3 + h.advance(3 * H); + h.db.run("UPDATE town_units SET count = 2 WHERE town_id = ? AND unit = 'port_scanner'", att.townId); // 10 came home (minus losses); keep 2 for the test + s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'scan', toTownId: def.townId, units: { port_scanner: 2 } }); + h.advanceTo(s.arriveAt); + const bad = T.reportsOf(h, att.userId).filter((r) => r.type === 'scan')[1].data; + assert.equal(bad.success, false); + assert.deepEqual(bad.scanners.survivors, {}); + const det2 = T.reportsOf(h, def.userId).filter((r) => r.type === 'scan_detected')[1].data; + assert.equal(det2.identityRevealed, true); + assert.equal(det2.by.operator.name, 'spy'); +}); + +test('event order: combat resolves in (arrive time, id) order and the whole run is deterministic', () => { + function run() { + const h = T.setup({ seed: 777 }); + const slow = T.addOperator(h, 'slow', { x: 40, y: 0, units: { script_crew: 60 } }); + const fast = T.addOperator(h, 'fast', { x: 20, y: 0, units: { botnet: 25 } }); + const def = T.addOperator(h, 'victim', { x: 8, y: 0, units: { soc_analyst: 30 } }); + h.db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', def.townId); + const a = h.run('sendMovement', { userId: slow.userId, fromTownId: slow.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 60 } }); + const b = h.run('sendMovement', { userId: fast.userId, fromTownId: fast.townId, type: 'raid', toTownId: def.townId, units: { botnet: 25 } }); + assert.ok(a.movementId < b.movementId); + h.advance(200 * H); + return { h, a, b, slow, fast, def }; + } + const x = run(), y = run(); + assert.ok(x.b.arriveAt < x.a.arriveAt, 'the botnet raid is faster although it was sent second'); + const reps = x.h.db.all("SELECT id, type, created_at FROM reports WHERE type IN ('raid','attack') ORDER BY id"); + assert.deepEqual(reps.map((r) => r.type), ['raid', 'attack'], 'reports are created in arrival order'); + assert.ok(T.snapshot(x.h) === T.snapshot(y.h), 'same inputs, same world seed: identical state'); + assert.equal(x.h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); +}); diff --git a/test/military-helpers.js b/test/military-helpers.js new file mode 100644 index 0000000..20f2cfe --- /dev/null +++ b/test/military-helpers.js @@ -0,0 +1,108 @@ +'use strict'; +/* Shared fixtures of the military tests: an in-memory (or file) game with a fake clock and hand-placed operators. + * Not a test file itself (node:test finds no tests in it). */ +const crypto = require('crypto'); +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); +const { openDb, migrate } = require('../server/db'); +const { FakeClock } = require('../server/clock'); +const { Scheduler } = require('../server/scheduler'); +const { createCommands } = require('../server/commands'); +const { createQueries } = require('../server/queries'); +const { createWorld } = require('../server/world'); +const { createTown } = require('../server/commands/joinWorld'); +const handlers = require('../server/events'); +const { createMilitaryQueries } = require('../server/military/views'); + +const H = D.HOUR_MS; + +function setup(o) { + o = o || {}; + const clock = o.clock || new FakeClock(); + const db = openDb(o.file || ':memory:'); + migrate(db); + const row = db.get('SELECT id FROM worlds LIMIT 1'); + const worldId = row ? row.id : createWorld(db, clock.now(), { seed: o.seed || 4242, speed: o.speed || 1, mapRadius: o.radius || 50 }); + const scheduler = new Scheduler({ db, clock, handlers, autoArm: false, log: o.log || (() => {}) }); + const commands = createCommands({ db, clock, scheduler }); + const queries = createQueries({ db, clock, scheduler }); + const mq = createMilitaryQueries({ db, clock, scheduler }); + const world = db.get('SELECT * FROM worlds WHERE id = ?', worldId); + const h = { db, clock, scheduler, commands, queries, mq, worldId, world }; + h.run = (name, args) => commands.run(name, args); + h.advance = (ms) => { clock.advance(ms); return scheduler.runDue(); }; + h.advanceTo = (t) => { clock.set(t); return scheduler.runDue(); }; + h.ctx = () => ({ db, clock, now: clock.now(), scheduler, enqueue: (e) => scheduler.enqueue(e), notify: (u, w, t, p) => scheduler.notify(u, w, t, p) }); + return h; +} + +// First free land tile at or near (x, y), scanning rightwards. +function landNear(h, x, y) { + for (let i = 0; i < 400; i++) { + const xx = x + i; + if (R.tileAt(h.world.seed, h.world.map_radius, xx, y).type === 'land' && !h.db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', h.worldId, xx, y)) return { x: xx, y }; + } + throw new Error('no land near ' + x + ',' + y); +} + +// An operator with one capital POP at the first land tile from (x, y). Buildings: the starting POP plus `infra` levels, +// strong power, lots of resources. Beginner protection off unless `protectedUntil`. +function addOperator(h, name, o) { + o = o || {}; + const { x, y } = landNear(h, o.x === undefined ? 5 : o.x, o.y === undefined ? 0 : o.y); + const now = h.clock.now(); + const u = h.db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', name, 'x', now); + const userId = Number(u.lastInsertRowid); + const op = h.db.run('INSERT INTO operators (world_id, user_id, name, as_number, protection_until, created_at) VALUES (?, ?, ?, ?, ?, ?)', h.worldId, userId, name, D.AS_RANGE.min + (h.asn = (h.asn || 0) + 1), o.protectedUntil || 0, now); + const opId = Number(op.lastInsertRowid); + const townId = createTown(h.db, { worldId: h.worldId, ownerId: opId, name: name + ' POP 1', x, y, isCapital: true, now }); + setBuildings(h, townId, Object.assign({ core_router: 10, rack_hall: 10, battery_bank: 10, noc: 5, ops_lab: 5, research_lab: 8, rollout_depot: 5, internet_exchange: 3, firewall: 0 }, o.infra || {})); + for (const k of ['f13', 'f14', 'f15', 'f16']) h.db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', o.power === undefined ? 10 : o.power, townId, k); + const big = o.res || 4000; + h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ? WHERE id = ?', big, big, big, o.battery === undefined ? 1000 : o.battery, o.footprint || 0, townId); + if (o.units) giveUnits(h, townId, o.units); + return { name, userId, opId, townId, x, y }; +} + +// Another POP for an existing operator. +function addTown(h, op, o) { + o = o || {}; + const { x, y } = landNear(h, o.x === undefined ? op.x + 2 : o.x, o.y === undefined ? op.y + 1 : o.y); + const id = createTown(h.db, { worldId: h.worldId, ownerId: op.opId, name: op.name + ' POP ' + (o.n || 2), x, y, isCapital: false, now: h.clock.now() }); + setBuildings(h, id, Object.assign({ core_router: 3, rack_hall: 3, battery_bank: 3 }, o.infra || {})); + h.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000, battery = 100 WHERE id = ?', id); + return { townId: id, x, y }; +} + +function setBuildings(h, townId, levels) { + for (const type of Object.keys(levels)) { + if (h.db.get('SELECT 1 AS x FROM buildings WHERE town_id = ? AND key = ?', townId, type)) h.db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', levels[type], townId, type); + else h.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', townId, type, type, levels[type]); + } +} + +function giveUnits(h, townId, units) { + for (const k of Object.keys(units)) { + const cur = h.db.get('SELECT count FROM town_units WHERE town_id = ? AND unit = ?', townId, k); + h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, k, (cur ? cur.count : 0) + units[k]); + } +} +const units = (h, townId) => { const o = {}; for (const r of h.db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) o[r.unit] = r.count; return o; }; +const town = (h, id) => h.db.get('SELECT * FROM towns WHERE id = ?', id); +const reportsOf = (h, userId) => h.db.all('SELECT r.id, r.type, r.created_at, r.data, r.summary, rr.role FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? ORDER BY r.id', userId) + .map((r) => Object.assign({}, r, { data: JSON.parse(r.data), summary: JSON.parse(r.summary) })); +const notes = (h, userId, type) => h.db.all('SELECT type, payload FROM notifications WHERE user_id = ? AND type = ? ORDER BY id', userId, type).map((r) => JSON.parse(r.payload)); + +// All state a battle could touch, as one comparable value (determinism tests). +function snapshot(h) { + const q = (sql) => h.db.all(sql).map((r) => JSON.stringify(r)); + return JSON.stringify([ + q('SELECT id, owner_id, loyalty, round(fiber, 4) AS fiber, round(hardware, 4) AS hardware, round(capital, 4) AS capital FROM towns ORDER BY id'), + q('SELECT * FROM town_units ORDER BY town_id, unit'), q('SELECT * FROM stationed ORDER BY host_town_id, owner_town_id, unit'), + q('SELECT id, type, status, units, cargo, arrive_at FROM movements ORDER BY id'), + q('SELECT id, type, data FROM reports ORDER BY id'), q('SELECT * FROM operator_stats ORDER BY operator_id'), + q('SELECT id, due_at, type, status FROM events ORDER BY id'), + ]); +} + +module.exports = { setup, addOperator, addTown, setBuildings, giveUnits, units, town, reportsOf, notes, landNear, snapshot, H, R, D, crypto }; diff --git a/test/military-moves.test.js b/test/military-moves.test.js new file mode 100644 index 0000000..66118fe --- /dev/null +++ b/test/military-moves.test.js @@ -0,0 +1,182 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const T = require('./military-helpers'); +const { R, D, H } = T; + +test('transport: capacity and links come from the Internet exchange; cargo arrives, carriers drive back, hooks fire', () => { + const h = T.setup(); + const a = T.addOperator(h, 'sender', { x: 5, y: 0, infra: { internet_exchange: 2 } }); + const b = T.addOperator(h, 'receiver', { x: 9, y: 0 }); + h.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000 WHERE id = ?', b.townId); + const M = require('../server/military/movements'); + const seen = []; + M.hooks.transportArrived.push((ctx, mv, r) => seen.push({ id: mv.id, added: r.added, extra: mv.extra })); + const send = (cargo) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo }); + assert.throws(() => send({ fiber: 600 }), (e) => e.code === 'capacity_exceeded'); + assert.throws(() => send({ fiber: 0 }), (e) => e.code === 'validation_failed'); + assert.throws(() => send({ fiber: 5000 }), (e) => e.code === 'capacity_exceeded'); + const noIx = T.addOperator(h, 'no-ix', { x: 12, y: 0, infra: { internet_exchange: 0 } }); + assert.throws(() => h.run('sendTransport', { userId: noIx.userId, fromTownId: noIx.townId, toTownId: b.townId, cargo: { fiber: 10 } }), (e) => e.code === 'no_transport_link'); + const before = T.town(h, a.townId).fiber; + const t1 = send({ fiber: 300, capital: 200 }); + const t2 = send({ hardware: 100 }); + assert.throws(() => send({ hardware: 10 }), (e) => e.code === 'no_transport_link', 'two links, both busy'); + assert.ok(Math.abs(T.town(h, a.townId).fiber - (before - 300)) < 1, 'cargo left the POP at once'); + assert.equal(t1.arriveAt - t1.departAt, R.transportMs(4, 1)); + const rb = T.town(h, b.townId).fiber; + h.advanceTo(t1.arriveAt); + assert.ok(T.town(h, b.townId).fiber >= rb + 300 - 1, 'delivered'); + assert.equal(seen.length, 2, 'the arrival hook fired for both transports (same distance, same time)'); + assert.deepEqual(seen[0].added, { fiber: 300, capital: 200 }); + assert.equal(T.notes(h, b.userId, 'transport_arrived').length, 2); + // the link is busy until the carriers are home, then free again + assert.throws(() => send({ hardware: 10 }), (e) => e.code === 'no_transport_link'); + h.advance(10 * H); + assert.doesNotThrow(() => send({ hardware: 10 })); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); +}); + +test('transport above the Rack hall cap is lost; transports are recallable only in the first 90 s', () => { + const h = T.setup(); + const a = T.addOperator(h, 'a', { x: 5, y: 0, infra: { internet_exchange: 3 } }); + const b = T.addOperator(h, 'b', { x: 30, y: 0 }); + const cap = R.storageCap(require('../server/state').loadTown(h.db, b.townId)); + h.db.run('UPDATE towns SET fiber = ?, hardware = 0, capital = 0 WHERE id = ?', cap - 100, b.townId); + const t = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: 400 } }); + h.advanceTo(t.arriveAt); + assert.ok(Math.abs(T.town(h, b.townId).fiber - cap) < 1e-6 + 60, 'capped at the Rack hall'); + assert.equal(T.notes(h, b.userId, 'transport_arrived')[0].cargoLost.fiber > 0, true); + + const c = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { capital: 250 } }); + const capBefore = T.town(h, a.townId).capital; + h.advance(60 * 1000); + const rc = h.run('recallMovement', { userId: a.userId, movementId: c.movementId }); + assert.ok(rc.arriveAt <= h.clock.now() + 61 * 1000 + 1000); + assert.equal(h.db.get('SELECT status FROM movements WHERE id = ?', c.movementId).status, 'recalled'); + h.advanceTo(rc.arriveAt); + assert.ok(T.town(h, a.townId).capital > capBefore + 200, 'the cargo is back home'); + // too late + const d = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { capital: 50 } }); + h.advance(91 * 1000); + assert.throws(() => h.run('recallMovement', { userId: a.userId, movementId: d.movementId }), (e) => e.code === 'recall_expired'); + // others cannot recall your movements + const e2 = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { capital: 10 } }); + assert.throws(() => h.run('recallMovement', { userId: b.userId, movementId: e2.movementId }), (e) => e.code === 'not_found'); +}); + +test('recall: a recalled raid never fights and its units come home after as long as they were out', () => { + const h = T.setup(); + const a = T.addOperator(h, 'a', { x: 5, y: 0, units: { script_crew: 20 } }); + const d = T.addOperator(h, 'd', { x: 12, y: 0, units: { soc_analyst: 2 } }); + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { script_crew: 20 } }); + h.advance(30 * 1000); + const r = h.run('recallMovement', { userId: a.userId, movementId: s.movementId }); + assert.equal(r.arriveAt, h.clock.now() + 30 * 1000); + assert.equal(h.mq.movements(d.userId, {}).incoming.length, 0, 'the warning disappears'); + h.advance(2 * H); + assert.equal(T.units(h, a.townId).script_crew, 20); + assert.equal(T.reportsOf(h, d.userId).length, 0); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); +}); + +test('research: levels need a Research lab, take time, cost resources, and raise unit strength by 5% per level', () => { + const h = T.setup(); + const a = T.addOperator(h, 'scholar', { infra: { research_lab: 3, ops_lab: 3 } }); + const r1 = h.run('research', { userId: a.userId, townId: a.townId, unit: 'script_crew', stat: 'attack' }); + assert.equal(r1.toLevel, 1); + assert.throws(() => h.run('research', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', stat: 'defence' }), (e) => e.code === 'queue_full', 'one research at a time per POP'); + h.advanceTo(r1.dueAt); + assert.equal(h.db.get('SELECT level FROM town_research WHERE town_id = ?', a.townId).level, 1); + assert.equal(T.notes(h, a.userId, 'research_done').length, 1); + // level 2 needs lab 4 + assert.throws(() => h.run('research', { userId: a.userId, townId: a.townId, unit: 'script_crew', stat: 'attack' }), (e) => e.code === 'requirements_not_met'); + T.setBuildings(h, a.townId, { research_lab: 8 }); + const r2 = h.run('research', { userId: a.userId, townId: a.townId, unit: 'script_crew', stat: 'attack' }); + h.advanceTo(r2.dueAt); + assert.equal(h.db.get('SELECT level FROM town_research WHERE town_id = ?', a.townId).level, 2); + assert.throws(() => h.run('research', { userId: a.userId, townId: a.townId, unit: 'port_scanner', stat: 'attack' }), (e) => e.code === 'not_researchable'); + assert.equal(R.unitStat('script_crew', 'attack', { 'script_crew:attack': 2 }), 40 * 1.1); + + // research is applied in combat: the snapshot taken at departure is what the attack uses + T.giveUnits(h, a.townId, { script_crew: 10 }); + const d = T.addOperator(h, 'd', { x: 12, y: 0 }); + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { script_crew: 10 } }); + h.advanceTo(s.arriveAt); + assert.ok(Math.abs(T.reportsOf(h, a.userId).find((r) => r.type === 'raid').data.power.attack - 10 * 40 * 1.1) < 1e-9); +}); + +test('movement list: own outgoing movements are detailed, foreign incoming ones hide type, units and cargo', () => { + const h = T.setup(); + const a = T.addOperator(h, 'a', { x: 5, y: 0, units: { script_crew: 10, port_scanner: 2 }, infra: { internet_exchange: 1 } }); + const d = T.addOperator(h, 'd', { x: 9, y: 0 }); + h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', toTownId: d.townId, units: { script_crew: 10 } }); + h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', toTownId: d.townId, units: { port_scanner: 2 } }); + h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: d.townId, cargo: { fiber: 10 } }); + const mine = h.mq.movements(a.userId, {}); + assert.deepEqual(mine.outgoing.map((m) => m.type).sort(), ['attack', 'scan', 'transport']); + assert.ok(mine.outgoing.every((m) => m.recallableUntil !== null)); + const theirs = h.mq.movements(d.userId, {}); + assert.equal(theirs.incoming.length, 3); + for (const m of theirs.incoming) { + assert.equal(m.type, 'unknown'); assert.equal(m.units, undefined); assert.equal(m.cargo, undefined); + assert.equal(m.from.townId, a.townId); assert.equal(m.from.owner.name, 'a'); + } + // and the town view carries the same warnings + assert.equal(h.queries.town(d.userId, d.townId).town.military.movements.incoming.length, 3); + // someone else cannot look at your POP + assert.throws(() => h.queries.town(d.userId, a.townId), (e) => e.code === 'not_found'); +}); + +test('tile info: public facts, distances, settle verdict', () => { + const h = T.setup(); + const a = T.addOperator(h, 'a', { x: 5, y: 0 }); + const d = T.addOperator(h, 'd', { x: 9, y: 0, protectedUntil: h.clock.now() + H }); + const info = h.mq.tileInfo(a.userId, { x: d.x, y: d.y }); + assert.equal(info.type, 'pop'); assert.equal(info.town.owner.protected, true); assert.equal(info.town.mine, false); + assert.ok(Math.abs(info.distances[0].distance - 4) < 1e-9); + const land = T.landNear(h, 8, 3); + const li = h.mq.tileInfo(a.userId, { x: land.x, y: land.y }); + assert.equal(li.type, 'land'); assert.equal(li.settle.possible, false); assert.equal(li.settle.code, 'footprint_too_low'); + assert.equal(li.settle.footprintNeeded, R.footprintNeeded(1)); + assert.throws(() => h.mq.tileInfo(a.userId, { x: 999, y: 0 }), (e) => e.code === 'not_found'); +}); + +test('reports: cursor pages newest first, read flags, 14 day retention cleanup', () => { + const h = T.setup(); + const a = T.addOperator(h, 'a', { x: 5, y: 0, units: { port_scanner: 30 } }); + const d = T.addOperator(h, 'd', { x: 9, y: 0 }); + for (let i = 0; i < 3; i++) { + h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', toTownId: d.townId, units: { port_scanner: 5 } }); + h.advance(2 * H); + } + const p1 = h.mq.reports(a.userId, { limit: 2 }); + assert.equal(p1.items.length, 2); assert.ok(p1.items[0].id > p1.items[1].id); + assert.equal(p1.unread, 3); + const p2 = h.mq.reports(a.userId, { limit: 2, after: p1.next }); + assert.equal(p2.items.length, 1); assert.equal(p2.next, null); + h.run('markReportRead', { userId: a.userId, reportId: p1.items[0].id }); + assert.equal(h.mq.reports(a.userId, {}).unread, 2); + assert.equal(h.mq.report(a.userId, p1.items[0].id).report.read, true); + assert.throws(() => h.mq.report(d.userId, p1.items[0].id), (e) => e.code === 'not_found', 'the scanner owner only: the defender has his own scan_detected report'); + h.run('markReportRead', { userId: a.userId, all: true }); + assert.equal(h.mq.reports(a.userId, { unread: true }).items.length, 0); + // retention + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM reports').n, 6); + h.advance(15 * 24 * H); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM reports').n, 0, 'expired reports are gone'); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'reportCleanup' AND status = 'pending'").n, 0, 'no cleanup pending without reports'); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM report_recipients').n, 0); +}); + +test('moving units between your own POPs makes them live there (no "stationed" bookkeeping)', () => { + const h = T.setup(); + const a = T.addOperator(h, 'mover', { x: 5, y: 0, units: { soc_analyst: 10 } }); + const second = T.addTown(h, a, { x: 8, y: 1 }); + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: second.townId, units: { soc_analyst: 6 } }); + h.advanceTo(s.arriveAt); + assert.deepEqual(T.units(h, second.townId), { soc_analyst: 6 }); + assert.deepEqual(T.units(h, a.townId), { soc_analyst: 4 }); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM stationed').n, 0); + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: a.townId, units: { soc_analyst: 1 } }), (e) => e.code === 'invalid_target'); +}); diff --git a/test/military-power.test.js b/test/military-power.test.js new file mode 100644 index 0000000..9ddfb8d --- /dev/null +++ b/test/military-power.test.js @@ -0,0 +1,151 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const T = require('./military-helpers'); +const P = require('../server/military/power'); +const { loadTown } = require('../server/state'); +const { R, D, H } = T; + +// A POP whose units draw more than it produces, with a small battery: units must go offline when the battery is empty. +function strainedTown(h, name, o) { + const op = T.addOperator(h, name, Object.assign({ power: 5, battery: 40, infra: { battery_bank: 1 } }, o)); + T.giveUnits(h, op.townId, { script_crew: 40, soc_analyst: 10 }); + P.reschedule(h.ctx(), op.townId, h.clock.now()); + return op; +} + +test('power: the battery empties, units go offline (cannot move, do not defend), then the expensive ones are decommissioned', () => { + const h = T.setup(); + const a = strainedTown(h, 'strained', { x: 5, y: 0 }); + const t0 = loadTown(h.db, a.townId); + const net = R.ratesPerHour(t0).powerNet; + assert.ok(net < 0, 'net power is negative with 50 units'); + const emptyAt = R.batteryEmptyAt(t0, h.clock.now()); + assert.ok(emptyAt > h.clock.now()); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'powerCheck' AND status = 'pending'").n, 1, 'exactly one pending check'); + + // before the battery is empty: units online and can move + h.advanceTo(emptyAt - 60000); + assert.ok(P.online(loadTown(h.db, a.townId), h.clock.now())); + assert.equal(h.queries.town(a.userId, a.townId).town.power.online, true); + + // after: offline + h.advanceTo(emptyAt + 5000); + const offline = h.db.get('SELECT offline_since FROM town_power WHERE town_id = ?', a.townId); + assert.ok(offline && offline.offline_since >= emptyAt, 'offline since the battery ran dry'); + assert.equal(T.notes(h, a.userId, 'units_offline').length, 1); + assert.equal(h.queries.town(a.userId, a.townId).town.power.online, false); + const target = T.addOperator(h, 'target', { x: 9, y: 0 }); + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: target.townId, units: { script_crew: 10 } }), (e) => e.code === 'units_offline'); + + // offline units do not defend: a small raid against the strained POP loots it although it "has" 50 units + const raider = T.addOperator(h, 'raider', { x: 3, y: 2, units: { script_crew: 15 } }); + const s = h.run('sendMovement', { userId: raider.userId, fromTownId: raider.townId, type: 'raid', toTownId: a.townId, units: { script_crew: 15 } }); + h.advanceTo(s.arriveAt); + const rep = T.reportsOf(h, raider.userId).find((r) => r.type === 'raid').data; + assert.equal(rep.defender.online, false); + assert.equal(rep.outcome, 'attacker_won'); + assert.equal(rep.power.defenceRaw, 0); + assert.deepEqual(T.units(h, a.townId), { script_crew: 40, soc_analyst: 10 }, 'offline units are not hurt by a raid'); + + // 24 h offline: decommission, most expensive first, until the draw fits again + const since = h.db.get('SELECT offline_since FROM town_power WHERE town_id = ?', a.townId).offline_since; + h.advanceTo(since + R.decommissionMs(1) - 1000); + assert.deepEqual(T.units(h, a.townId), { script_crew: 40, soc_analyst: 10 }, 'nothing before the 24 hours are up'); + h.advanceTo(since + R.decommissionMs(1) + 1000); + const left = T.units(h, a.townId); + assert.ok(left.script_crew < 40 || left.soc_analyst < 10, 'units were decommissioned'); + const t1 = loadTown(h.db, a.townId); + assert.ok(R.ratesPerHour(t1).powerNet >= 0, 'the draw fits the output now'); + assert.ok(P.online(t1, h.clock.now()), 'online again'); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM town_power WHERE town_id = ?', a.townId).n, 0); + assert.equal(T.notes(h, a.userId, 'units_decommissioned').length, 1); + const unit = (id) => D.UNITS[id]; + // script_crew (cost 150) is more expensive than soc_analyst (90): the crews go first + assert.ok(unit('script_crew').cost.fiber + unit('script_crew').cost.hardware + unit('script_crew').cost.capital > unit('soc_analyst').cost.fiber + unit('soc_analyst').cost.hardware + unit('soc_analyst').cost.capital); + assert.equal(left.soc_analyst, 10, 'the cheaper defenders survive'); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); +}); + +test('power: building more substations before the battery is empty re-arms the check (no offline)', () => { + const h = T.setup(); + const a = strainedTown(h, 'saver', { x: 5, y: 0 }); + const emptyAt = R.batteryEmptyAt(loadTown(h.db, a.townId), h.clock.now()); + // more output: the reschedule moves the check, units never go offline + h.db.run("UPDATE buildings SET level = 12 WHERE town_id = ? AND key IN ('f13','f14','f15','f16')", a.townId); + P.reschedule(h.ctx(), a.townId, h.clock.now()); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'powerCheck' AND status = 'pending'").n, 0, 'net power is positive: no check needed'); + h.advanceTo(emptyAt + 10 * H); + assert.equal(T.notes(h, a.userId, 'units_offline').length, 0); + assert.ok(P.online(loadTown(h.db, a.townId), h.clock.now())); +}); + +test('power: reinforcements draw from the host, and leaving units stops the draw at the origin', () => { + const h = T.setup(); + const a = T.addOperator(h, 'ally-a', { x: 5, y: 0, units: { soc_analyst: 20 } }); + const b = T.addOperator(h, 'ally-b', { x: 8, y: 0 }); + const t = (id) => loadTown(h.db, id).unitDraw; + assert.equal(t(a.townId), 20); + // not allied: refused + assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: b.townId, units: { soc_analyst: 5 } }), (e) => e.code === 'invalid_target'); + // allies via the social tables + h.db.run("INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, 'N', 'NN', 10, ?, ?)", h.worldId, a.opId, h.clock.now()); + const aid = h.db.get('SELECT id FROM alliances').id; + for (const op of [a, b]) h.db.run('UPDATE operators SET alliance_id = ? WHERE id = ?', aid, op.opId); + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: b.townId, units: { soc_analyst: 12 } }); + assert.equal(t(a.townId), 8, 'units in transit draw nothing'); + h.advanceTo(s.arriveAt); + assert.equal(t(b.townId), 12, 'the host pays for the reinforcements'); + assert.equal(t(a.townId), 8); + const view = h.queries.town(b.userId, b.townId).town.military.units; + assert.equal(view.stationedHere.length, 1); + assert.deepEqual(view.stationedHere[0].units, { soc_analyst: 12 }); + assert.equal(h.queries.town(a.userId, a.townId).town.military.units.stationedAway[0].hostTownId, b.townId); + + // the reinforcement defends the host + const raider = T.addOperator(h, 'raider', { x: 12, y: 0, units: { script_crew: 20 } }); + const rs = h.run('sendMovement', { userId: raider.userId, fromTownId: raider.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 } }); + h.advanceTo(rs.arriveAt); + const rep = T.reportsOf(h, raider.userId).find((r) => r.type === 'raid'); + assert.equal(rep.data.defender.groups[0].sent.soc_analyst, 12); + assert.ok(T.reportsOf(h, a.userId).some((r) => r.role === 'reinforcer'), 'the reinforcing owner gets the report'); + + // the host sends them home: draw moves back after they arrive + const w = h.run('withdrawStationed', { userId: b.userId, hostTownId: b.townId, ownerTownId: a.townId }); + assert.equal(t(b.townId), 0); + h.advanceTo(w.arriveAt); + assert.equal(T.units(h, a.townId).soc_analyst > 8, true); +}); + +test('restart: overdue events are caught up in order after reopening the same database file', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-mil-')); + const file = path.join(dir, 'game.db'); + const h1 = T.setup({ file }); + const clock = h1.clock; + const a = T.addOperator(h1, 'raider', { x: 5, y: 0, units: { script_crew: 60, botnet: 10 } }); + const d = T.addOperator(h1, 'victim', { x: 20, y: 0, units: { soc_analyst: 5 } }); + const slow = h1.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { script_crew: 60 } }); + const fast = h1.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { botnet: 10 } }); + h1.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 3 }); + assert.ok(fast.arriveAt < slow.arriveAt); + h1.db.close(); // "the server is down" + clock.advance(100 * H); // ... for a long time + const h2 = T.setup({ file, clock }); + const n = h2.scheduler.catchUp(); + assert.ok(n >= 5, 'arrivals, returns and the training batch were all overdue: ' + n); + const reps = h2.db.all("SELECT id, type, data FROM reports WHERE type = 'raid' ORDER BY id").map((r) => JSON.parse(r.data)); + assert.equal(reps.length, 2); + assert.ok(reps[0].arrivedAt === fast.arriveAt && reps[1].arrivedAt === slow.arriveAt, 'reports follow event order, not creation order'); + assert.equal(h2.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending' AND due_at <= ?", clock.now()).n, 0); + assert.equal(h2.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); + const home = T.units(h2, a.townId); + assert.ok(home.script_crew > 0 && home.botnet > 0, 'everyone came home'); + assert.equal(home.soc_analyst, 3, 'the training batch finished during the downtime'); + // resources: the first (fast) raid saw the victim's stock at ITS time, not at catch-up time + assert.equal(reps[0].defender.groups[0].sent.soc_analyst, 5); + h2.db.close(); + fs.rmSync(dir, { recursive: true, force: true }); +}); diff --git a/test/military-rules.test.js b/test/military-rules.test.js new file mode 100644 index 0000000..58481ce --- /dev/null +++ b/test/military-rules.test.js @@ -0,0 +1,159 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); +const H = D.HOUR_MS; + +const close = (a, b, eps) => Math.abs(a - b) <= (eps || 1e-9); + +test('units: data is complete and consistent', () => { + assert.equal(D.UNIT_ORDER.length, Object.keys(D.UNITS).length); + for (const [id, u] of Object.entries(D.UNITS)) { + assert.ok(D.BUILDINGS[u.building], id + ' has a training building'); + for (const r of u.requires) assert.ok(D.BUILDINGS[r.type], id + ' requires a real building'); + assert.ok(u.draw >= 0 && u.speed >= 0 && u.time > 0, id); + for (const res of D.RESOURCES) assert.ok(u.cost[res] > 0, id + ' costs ' + res); + } + assert.equal(D.UNITS.honeypot.fixed, true); + assert.equal(D.UNITS.honeypot.speed, 0); +}); + +test('training and research: costs, times, requirements', () => { + assert.deepEqual(R.unitCost('script_crew', 10), { fiber: 800, hardware: 400, capital: 300 }); + // building level and world speed shorten training + assert.equal(R.trainTimeMs('script_crew', 1, 0, 1), 180000); + assert.equal(R.trainTimeMs('script_crew', 1, 10, 1), Math.round(180000 / 1.3)); + assert.equal(R.trainTimeMs('script_crew', 10, 0, 2), 900000); + const town = { speed: 1, updatedAt: 0, res: { fiber: 1000, hardware: 1000, capital: 1000, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { ops_lab: { type: 'ops_lab', level: 1 } } }; + assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 0).ok, true); + assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 0).dueAt, R.trainTimeMs('script_crew', 5, 1, 1)); + assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 99999).startAt, 99999, 'queued behind the tail'); + assert.equal(R.trainPlan(town, 'botnet', 1, 0, 0).code, 'requirements_not_met'); + assert.deepEqual(R.unitMissing(town, 'botnet').map((m) => m.type).sort(), ['ops_lab', 'research_lab']); + assert.equal(R.trainPlan(town, 'script_crew', 500, 0, 0).code, 'not_enough_resources'); + assert.equal(R.trainPlan(town, 'script_crew', 0, 0, 0).code, 'validation_failed'); + assert.equal(R.trainPlan(town, 'nope', 1, 0, 0).code, 'unknown_unit'); + // research + const t2 = Object.assign({}, town, { buildings: { ops_lab: { type: 'ops_lab', level: 1 }, research_lab: { type: 'research_lab', level: 3 } } }); + assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 0, false, 0, 0).ok, true); + assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 1, false, 0, 0).code, 'requirements_not_met', 'level 2 needs lab 4'); + assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 0, true, 0, 0).code, 'queue_full'); + assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 10, false, 0, 0).code, 'max_level'); + assert.equal(R.researchPlan(t2, 'honeypot', 'attack', 0, false, 0, 0).code, 'not_researchable'); + assert.equal(R.researchPlan(t2, 'script_crew', 'speed', 0, false, 0, 0).code, 'not_researchable'); + assert.ok(R.researchCost('script_crew', 2).fiber > R.researchCost('script_crew', 1).fiber); + assert.ok(R.researchTimeMs('script_crew', 1, 3, 1, 0.1) < R.researchTimeMs('script_crew', 1, 3, 1, 0)); + assert.equal(R.researchSpeedBonus(2), 0.2); assert.equal(R.researchSpeedBonus(99), D.INCUMBENT.researchSpeedMax); +}); + +test('movement rules: slowest unit, latency, unit/role checks', () => { + assert.equal(R.slowestSpeed({ script_crew: 5, botnet: 5 }), 8); + assert.equal(R.slowestSpeed({ script_crew: 0, botnet: 5 }), 14); + assert.equal(R.movementMs(20, { script_crew: 1, ddos_rig: 1 }, 1), Math.round(20 / 5 * H), 'the slowest unit sets the pace'); + assert.equal(R.movementMs(20, { script_crew: 1 }, 2), Math.round(20 / 16 * H), 'world speed'); + assert.equal(R.movementMs(0.1, { port_scanner: 1 }, 1), 10 * 60 * 1000, 'minimum 10 minutes'); + assert.equal(R.checkUnitsForType('raid', { script_crew: 5 }), null); + assert.equal(R.checkUnitsForType('raid', { ddos_rig: 5 }).code, 'validation_failed', 'no siege on raids'); + assert.equal(R.checkUnitsForType('attack', { script_crew: 5, ddos_rig: 1, exploit_kit: 1 }), null); + assert.equal(R.checkUnitsForType('scan', { script_crew: 1 }).code, 'validation_failed'); + assert.equal(R.checkUnitsForType('attack', { honeypot: 1 }).code, 'validation_failed', 'honeypots never move'); + assert.equal(R.checkUnitsForType('attack', {}).code, 'validation_failed'); + assert.equal(R.checkUnitsForType('attack', { nope: 1 }).code, 'unknown_unit'); + assert.equal(R.checkUnitsForType('settle', { rollout_crew: 3 }), null); + assert.equal(R.checkUnitsForType('settle', { rollout_crew: 4 }).code, 'validation_failed'); + assert.equal(R.checkUnitsForType('takeover', { script_crew: 3 }).code, 'validation_failed'); + assert.equal(R.checkUnitsForType('takeover', { script_crew: 3, ma_team: 1 }), null); + assert.equal(R.checkUnitsForType('reinforce', { honeypot: 1 }).code, 'validation_failed'); + assert.equal(R.isProtected(100, 99), true); assert.equal(R.isProtected(100, 100), false); +}); + +test('combat: full attack, raid, firewall, rigs, research, ties, empty target', () => { + const att = (units, research) => ({ units, research: research || {} }); + // attacker wins a full attack: defender is wiped, attacker loses (D/A)^1.5 + let b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 100 }), defenders: [{ id: 'h', units: { soc_analyst: 80 } }], firewall: 0 }); + assert.equal(b.A, 4000); assert.equal(b.D, 2010); + assert.equal(b.attackerWins, true); + assert.deepEqual(b.defenders[0].survivors, {}); + assert.ok(close(b.attackerLossFraction, Math.pow(2010 / 4000, 1.5))); + assert.equal(b.attacker.lost.script_crew, Math.round(100 * Math.pow(2010 / 4000, 1.5))); + // defender wins: attacker wiped, defender loses (A/D)^1.5 + b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 10 }), defenders: [{ id: 'h', units: { blue_team: 10 } }], firewall: 0 }); + assert.equal(b.attackerWins, false); + assert.deepEqual(b.attacker.survivors, {}); + assert.ok(close(b.defenderLossFraction, Math.pow(400 / 810, 1.5))); + // ties go to the defender + b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 1 }), defenders: [], firewall: 0, staticDefence: 40 }); + assert.equal(b.attackerWins, false); + // raid: both lose 0.5 * ratio^1.5 + b = R.resolveBattle({ kind: 'raid', attackers: att({ script_crew: 100 }), defenders: [{ id: 'h', units: { soc_analyst: 80 } }], firewall: 0 }); + const f = 0.5 * Math.pow(2010 / 4000, 1.5); + assert.ok(close(b.attackerLossFraction, f) && close(b.defenderLossFraction, f)); + assert.equal(b.defenders[0].survivors.soc_analyst, 80 - Math.round(80 * f)); + // firewall multiplies defence; rigs lower it by one level per 10 + const fw = (rigs) => R.resolveBattle({ kind: 'attack', attackers: att(Object.assign({ script_crew: 10 }, rigs ? { ddos_rig: rigs } : {})), defenders: [{ id: 'h', units: { soc_analyst: 10 } }], firewall: 10 }); + assert.ok(close(fw(0).D, (250 + 10) * 1.3)); + assert.ok(close(fw(20).D, (250 + 10) * 1.24), 'level 10 - 20 rigs / 10 = 8'); + assert.equal(fw(20).effectiveFirewall, 8); + assert.equal(R.effectiveFirewall(3, 100), 0, 'never below zero'); + // research: +5% per level, per unit type and stat + b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 10 }, { 'script_crew:attack': 4 }), defenders: [{ id: 'h', units: { soc_analyst: 10 }, research: { 'soc_analyst:defence': 2 } }], firewall: 0 }); + assert.ok(close(b.A, 400 * 1.2)); assert.ok(close(b.D, 250 * 1.1 + 10)); + // empty POP: only the base defence stands + b = R.resolveBattle({ kind: 'raid', attackers: att({ script_crew: 1 }), defenders: [], firewall: 0 }); + assert.equal(b.D, 10); assert.equal(b.attackerWins, true); assert.deepEqual(b.attacker.lost, {}); + // reinforcements count together with home crews, and the share goes by defence power + b = R.resolveBattle({ kind: 'attack', attackers: att({ botnet: 50 }), defenders: [{ id: 'home', units: { soc_analyst: 10 } }, { id: 'ally', units: { blue_team: 10 } }], firewall: 0 }); + assert.ok(close(b.defenceRaw, 250 + 800)); assert.ok(close(b.defenders[1].share, 800 / 1050)); + // determinism: the same call gives the same result + assert.deepEqual(R.resolveBattle({ kind: 'raid', attackers: att({ botnet: 7 }), defenders: [{ id: 'h', units: { soc_analyst: 9 } }], firewall: 2 }), + R.resolveBattle({ kind: 'raid', attackers: att({ botnet: 7 }), defenders: [{ id: 'h', units: { soc_analyst: 9 } }], firewall: 2 })); + assert.ok(R.battlePoints({ script_crew: 10 }) > 0); +}); + +test('loot, cache, siege, loyalty, scan, incumbent, decommission, transport plan', () => { + assert.deepEqual(R.lootSplit(300, { fiber: 1000, hardware: 1000, capital: 1000 }), { fiber: 100, hardware: 100, capital: 100 }); + assert.deepEqual(R.lootSplit(300, { fiber: 10, hardware: 1000, capital: 1000 }), { fiber: 10, hardware: 145, capital: 145 }, 'what fiber cannot give is shared'); + assert.deepEqual(R.lootSplit(9999, { fiber: 5, hardware: 6, capital: 7 }), { fiber: 5, hardware: 6, capital: 7 }, 'never more than there is'); + assert.deepEqual(R.lootSplit(0, { fiber: 5, hardware: 6, capital: 7 }), { fiber: 0, hardware: 0, capital: 0 }); + assert.equal(R.carryOf({ script_crew: 10, botnet: 2, soc_analyst: 5 }), 10 * 50 + 2 * 150); + assert.equal(R.cacheFraction(0), 0); assert.ok(close(R.cacheFraction(3), 0.3)); assert.equal(R.cacheFraction(20), 0.5); + assert.equal(R.siegeLevels(4), 0); assert.equal(R.siegeLevels(5), 1); assert.equal(R.siegeLevels(19), 1); assert.equal(R.siegeLevels(45), 2); + assert.equal(R.loyaltyDrop(0), 15); assert.equal(R.loyaltyDrop(0.999999), 30); + for (let i = 0; i < 200; i++) { const d = R.loyaltyDrop(R.rng(i)()); assert.ok(d >= 15 && d <= 30); } + assert.equal(R.takeoverBlock(true, 3), 'capital'); assert.equal(R.takeoverBlock(false, 1), 'last_pop'); assert.equal(R.takeoverBlock(true, 1), 'last_pop'); assert.equal(R.takeoverBlock(false, 2), null); + assert.deepEqual(R.footprintGate(1, 499), { ok: false, need: 500, have: 499 }); assert.equal(R.footprintGate(2, 1741).ok, true); assert.equal(R.footprintGate(2, 1740).ok, false); + // scan: success needs more scanners than the defender; buildings at 2:1; failure loses everything + assert.deepEqual(R.resolveScan(5, 5), { success: false, detail: 'none', identityRevealed: true, lossFraction: 1 }); + assert.equal(R.resolveScan(6, 5).detail, 'basic'); + assert.equal(R.resolveScan(10, 5).detail, 'full'); + assert.equal(R.resolveScan(3, 0).detail, 'full'); assert.equal(R.resolveScan(3, 0).lossFraction, 0); + assert.equal(R.resolveScan(6, 5).identityRevealed, false); + // incumbent: static, grows with age, varies per site, deterministic + assert.equal(R.incumbentDefence(1, 5, 5, 0), R.incumbentDefence(1, 5, 5, 0)); + assert.ok(R.incumbentDefence(1, 5, 5, 100) > R.incumbentDefence(1, 5, 5, 0)); + assert.notEqual(R.incumbentDefence(1, 5, 5, 0), R.incumbentDefence(1, 6, 5, 0)); + // decommission: most expensive first, only as many as needed + assert.deepEqual(R.decommissionPlan({ botnet: 5, script_crew: 10 }, 8), { botnet: 5, script_crew: 2 }); + assert.deepEqual(R.decommissionPlan({ botnet: 5, script_crew: 10 }, 100), {}); + assert.deepEqual(R.decommissionPlan({ botnet: 5, soc_analyst: 3 }, -5), { botnet: 5, soc_analyst: 3 }); + assert.equal(R.decommissionMs(1), 24 * H); assert.equal(R.decommissionMs(4), 6 * H); + // transport plan + const town = { speed: 1, updatedAt: 0, res: { fiber: 400, hardware: 400, capital: 400, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 }, rack_hall: { type: 'rack_hall', level: 5 } } }; + assert.equal(R.transportPlan(town, { fiber: 100 }, 0, 0).ok, true); + assert.equal(R.transportPlan(town, { fiber: 100 }, 2, 0).code, 'no_transport_link'); + assert.equal(R.transportPlan(town, { fiber: 501 }, 0, 0).code, 'capacity_exceeded'); + assert.equal(R.transportPlan(town, { fiber: 450 }, 0, 0).code, 'not_enough_resources'); + assert.equal(R.transportPlan(town, { gold: 5 }, 0, 0).code, 'validation_failed'); + assert.equal(R.transportPlan(town, {}, 0, 0).code, 'validation_failed'); + // settle checks and new-POP helpers + assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).ok, true); + assert.equal(R.settleCheck({ tileType: 'rural', occupied: false, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).code, 'invalid_target'); + assert.equal(R.settleCheck({ tileType: 'land', occupied: true, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).code, 'invalid_target'); + assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 15.01, ownedCount: 1, footprint: 600 }).code, 'out_of_range'); + assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 15, ownedCount: 1, footprint: 400 }).code, 'footprint_too_low'); + assert.deepEqual(R.cleanWild(['substation', 'bogus']), ['substation', D.START.wild[1]]); + const nb = R.newTownBuildings(['substation', 'sales_office']); + assert.equal(Object.keys(nb).length, 18); assert.ok(Object.values(nb).every((b) => b.level === 0)); + assert.equal(nb.f17.type, 'substation'); +}); diff --git a/test/social-alliances.test.js b/test/social-alliances.test.js new file mode 100644 index 0000000..3a4d2e3 --- /dev/null +++ b/test/social-alliances.test.js @@ -0,0 +1,310 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const { createTestServer } = require('./helpers'); +const A = require('../server/alliances'); + +const post = (body) => ({ method: 'POST', body }); + +async function found(t, u, name, tag) { + const r = await t.api('/alliances', post({ name, tag }), u.token); + assert.equal(r.status, 201, JSON.stringify(r.body)); + return r.body.allianceId; +} +// invite + accept +async function join(t, leader, allianceId, u) { + const inv = await t.api('/alliances/' + allianceId + '/invite', post({ operatorId: u.operatorId }), leader.token); + assert.equal(inv.status, 201, JSON.stringify(inv.body)); + const r = await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, u.token); + assert.equal(r.status, 200, JSON.stringify(r.body)); +} + +test('alliances: founding needs a Peering office, names and tags are unique per world', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const noOffice = await t.signup('nooffice'); + let r = await t.api('/alliances', post({ name: 'Nope', tag: 'NO' }), noOffice.token); + assert.equal(r.status, 409); assert.equal(r.body.error.code, 'peering_office_required'); + + const a = await t.signupPeering('ada', 3); + r = await t.api('/alliances', post({ name: 'Fibre Friends', tag: 'FF' }), a.token); + assert.equal(r.status, 201); + assert.equal(r.body.sizeCap, 16, '10 + 2 * 3'); + assert.equal(r.body.role, 'leader'); + + r = await t.api('/alliances', post({ name: 'Other', tag: 'OT' }), a.token); + assert.equal(r.body.error.code, 'already_in_alliance'); + + const b = await t.signupPeering('bob'); + r = await t.api('/alliances', post({ name: 'fibre friends', tag: 'XX' }), b.token); + assert.equal(r.body.error.code, 'alliance_name_taken', 'case-insensitive'); + r = await t.api('/alliances', post({ name: 'Different', tag: 'ff' }), b.token); + assert.equal(r.body.error.code, 'alliance_tag_taken'); + r = await t.api('/alliances', post({ name: 'Bad<>Name', tag: 'BN' }), b.token); + assert.equal(r.status, 422); + r = await t.api('/alliances', post({ name: 'Fine Name', tag: 'a b' }), b.token); + assert.equal(r.status, 422); + r = await t.api('/alliances', post({ name: 'Zero​width', tag: 'ZW' }), b.token); + assert.equal(r.status, 201, 'invisible characters are stripped, not rejected'); + assert.equal(r.body.name, 'Zerowidth'); +}); + +test('alliances: invite, accept, decline, cancel, idempotency and room checks', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const lead = await t.signupPeering('lead', 1); + const m1 = await t.signupPeering('mem1'); + const m2 = await t.signupPeering('mem2'); + const bare = await t.signup('bare'); // no Peering office + const id = await found(t, lead, 'Core Club', 'CC'); + + // invite twice: same invite, second call is a no-op (200) + let r = await t.api('/alliances/' + id + '/invite', post({ name: 'MEM1' }), lead.token); + assert.equal(r.status, 201); const inv1 = r.body.inviteId; + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m1.operatorId }), lead.token); + assert.equal(r.status, 200); assert.equal(r.body.inviteId, inv1); assert.equal(r.body.changed, false); + r = await t.api('/alliances/' + id + '/invite', post({}), lead.token); + assert.equal(r.status, 422, 'needs a target'); + + // the invitee sees it and got a notification + r = await t.api('/alliance-invites', {}, m1.token); + assert.equal(r.body.items.length, 1); assert.equal(r.body.items[0].alliance.tag, 'CC'); + r = await t.api('/notifications', {}, m1.token); + assert.ok(r.body.items.some((n) => n.type === 'alliance_invite' && n.payload.inviteId === inv1)); + + // someone else cannot answer it + r = await t.api('/alliance-invites/' + inv1 + '/accept', { method: 'POST' }, m2.token); + assert.equal(r.status, 404); + r = await t.api('/alliance-invites/' + inv1 + '/accept', { method: 'POST' }, m1.token); + assert.equal(r.status, 200); assert.equal(r.body.changed, true); + r = await t.api('/alliance-invites/' + inv1 + '/accept', { method: 'POST' }, m1.token); + assert.equal(r.status, 200); assert.equal(r.body.changed, false, 'accepting twice is a no-op'); + r = await t.api('/alliance-invites/' + inv1 + '/decline', { method: 'POST' }, m1.token); + assert.equal(r.status, 409, 'cannot decline what was accepted'); + + // a plain member may not invite + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), m1.token); + assert.equal(r.status, 403); assert.equal(r.body.error.details.need, 'invite'); + // already in an alliance + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m1.operatorId }), lead.token); + assert.equal(r.body.error.code, 'already_in_alliance'); + + // decline, then re-invite, then cancel + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), lead.token); + const inv2 = r.body.inviteId; + r = await t.api('/alliance-invites/' + inv2 + '/decline', { method: 'POST' }, m2.token); + assert.equal(r.body.changed, true); + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), lead.token); + const inv3 = r.body.inviteId; assert.notEqual(inv3, inv2); + r = await t.api('/alliances/' + id + '/invites', {}, lead.token); + assert.equal(r.body.items.length, 1); + r = await t.api('/alliances/' + id + '/invites/' + inv3, { method: 'DELETE' }, lead.token); + assert.equal(r.body.changed, true); + r = await t.api('/alliances/' + id + '/invites/' + inv3, { method: 'DELETE' }, lead.token); + assert.equal(r.body.changed, false); + r = await t.api('/alliance-invites/' + inv3 + '/accept', { method: 'POST' }, m2.token); + assert.equal(r.status, 409); + + // joining needs a Peering office + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: bare.operatorId }), lead.token); + r = await t.api('/alliance-invites/' + r.body.inviteId + '/accept', { method: 'POST' }, bare.token); + assert.equal(r.body.error.code, 'peering_office_required'); + t.setBuilding(bare.townId, 'peering_office', 1); + r = await t.api('/alliances/' + id + '/invites', {}, lead.token); + r = await t.api('/alliance-invites/' + r.body.items[0].id + '/accept', { method: 'POST' }, bare.token); + assert.equal(r.status, 200, JSON.stringify(r.body)); + + // room: the cap is 10 + 2 * 1 = 12 members; fill it with quick operators + const filler = []; + for (let i = 0; filler.length < 12 - 3; i++) { + const f = t.quickSignup('fill' + i); + t.setBuilding(f.townId, 'peering_office', 1); + filler.push(f); + } + for (const f of filler) t.srv.commands.run('allianceInvite', { userId: lead.userId, allianceId: id, operatorId: f.operatorId }); + for (const f of filler) { + const inv = t.srv.db.get("SELECT id FROM alliance_invites WHERE operator_id = ? AND status = 'pending'", f.operatorId); + t.srv.commands.run('allianceInviteAnswer', { userId: f.userId, inviteId: inv.id, accept: true }); + } + assert.equal(A.memberCount(t.srv.db, id), 12); + r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), lead.token); + assert.equal(r.body.error.code, 'alliance_full'); + assert.equal(r.body.error.details.cap, 12); +}); + +test('alliances: the size cap is stored, only raised, and refreshed from the leader\'s best Peering office', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const lead = await t.signupPeering('lead', 1); + const m = await t.signupPeering('mmm'); + const id = await found(t, lead, 'Growers', 'GR'); + let r = await t.api('/alliances/' + id, {}, lead.token); + assert.equal(r.body.alliance.sizeCap, 12); + t.setBuilding(lead.townId, 'peering_office', 6); + r = await t.api('/alliances/' + id, {}, lead.token); + assert.equal(r.body.alliance.sizeCap, 22, 'reads show the effective cap'); + assert.equal(t.srv.db.get('SELECT size_cap FROM alliances WHERE id = ?', id).size_cap, 12, 'reads do not write'); + await t.api('/alliances/' + id + '/invite', post({ operatorId: m.operatorId }), lead.token); + assert.equal(t.srv.db.get('SELECT size_cap FROM alliances WHERE id = ?', id).size_cap, 22, 'a command stores the raise'); + t.srv.db.run("UPDATE buildings SET level = 1 WHERE town_id = ? AND type = 'peering_office'", lead.townId); + r = await t.api('/alliances/' + id, {}, lead.token); + assert.equal(r.body.alliance.sizeCap, 22, 'never lowered'); +}); + +test('alliances: roles, kick rules, leader transfer, leaving, notes, members list', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const lead = await t.signupPeering('lead'); + const off = await t.signupPeering('off'); + const dip = await t.signupPeering('dip'); + const mem = await t.signupPeering('mem'); + const id = await found(t, lead, 'Roles', 'RL'); + for (const u of [off, dip, mem]) await join(t, lead, id, u); + const url = (p) => '/alliances/' + id + p; + + // role changes: leader only, never to leader via /role + let r = await t.api(url('/role'), post({ operatorId: off.operatorId, role: 'officer' }), lead.token); + assert.equal(r.body.changed, true); + r = await t.api(url('/role'), post({ operatorId: off.operatorId, role: 'officer' }), lead.token); + assert.equal(r.body.changed, false); + await t.api(url('/role'), post({ operatorId: dip.operatorId, role: 'diplomat' }), lead.token); + r = await t.api(url('/role'), post({ operatorId: mem.operatorId, role: 'leader' }), lead.token); + assert.equal(r.status, 422); + r = await t.api(url('/role'), post({ operatorId: mem.operatorId, role: 'officer' }), off.token); + assert.equal(r.status, 403, 'officers cannot promote'); + r = await t.api(url('/role'), post({ operatorId: lead.operatorId, role: 'member' }), lead.token); + assert.equal(r.status, 422, 'the leader cannot demote themselves'); + + // kick: officer may kick members but not diplomats or the leader + r = await t.api(url('/kick'), post({ operatorId: dip.operatorId }), off.token); + assert.equal(r.status, 403); assert.equal(r.body.error.details.need, 'outrank'); + r = await t.api(url('/kick'), post({ operatorId: lead.operatorId }), off.token); + assert.equal(r.status, 403); + r = await t.api(url('/kick'), post({ operatorId: mem.operatorId }), dip.token); + assert.equal(r.status, 403, 'a diplomat has no kick permission'); + r = await t.api(url('/kick'), post({ operatorId: mem.operatorId }), off.token); + assert.equal(r.body.changed, true); + r = await t.api(url('/kick'), post({ operatorId: mem.operatorId }), off.token); + assert.equal(r.body.changed, false, 'kicking twice is a no-op'); + r = await t.api('/notifications', {}, mem.token); + assert.ok(r.body.items.some((n) => n.type === 'alliance_kicked')); + assert.equal(t.srv.db.get('SELECT alliance_id FROM operators WHERE id = ?', mem.operatorId).alliance_id, null); + + // members list, with last online from the token use + t.clock.advance(10 * 60 * 1000); + await t.api('/me', {}, dip.token); // touches dip's token at the new time + r = await t.api(url('/members'), {}, lead.token); + assert.deepEqual(r.body.items.map((m) => m.role), ['leader', 'diplomat', 'officer']); + const d = r.body.items.find((m) => m.name === 'dip'); + assert.equal(d.towns, 1); assert.equal(d.lastOnline, t.clock.now()); + const o = r.body.items.find((m) => m.name === 'off'); + assert.ok(o.lastOnline < t.clock.now(), 'off was not online since'); + r = await t.api(url('/members'), {}, mem.token); + assert.equal(r.status, 403, 'non-members cannot list members'); + + // notes + r = await t.api(url('/notes'), post({ text: 'Rally at 20:00‮' }), mem.token); + assert.equal(r.status, 403); + r = await t.api(url('/notes'), post({ text: 'Rally at 20:00‮' }), off.token); + assert.equal(r.status, 201); assert.equal(r.body.note.text, 'Rally at 20:00'); + const nid = r.body.note.id; + r = await t.api(url('/notes/' + nid), post({ text: 'Rally at 21:00' }), dip.token); + assert.equal(r.body.note.text, 'Rally at 21:00'); + r = await t.api(url('/notes'), {}, dip.token); + assert.equal(r.body.items.length, 1); + r = await t.api(url('/notes/' + nid), { method: 'DELETE' }, off.token); + assert.equal(r.body.changed, true); + for (let i = 0; i < 10; i++) await t.api(url('/notes'), post({ text: 'n' + i }), lead.token); + r = await t.api(url('/notes'), post({ text: 'one too many' }), lead.token); + assert.equal(r.body.error.code, 'notes_full'); + + // leader cannot leave while others remain; transfer then leave + r = await t.api(url('/leave'), { method: 'POST' }, lead.token); + assert.equal(r.body.error.code, 'leader_must_transfer'); + r = await t.api(url('/transfer'), post({ operatorId: lead.operatorId }), lead.token); + assert.equal(r.status, 422); + r = await t.api(url('/transfer'), post({ operatorId: mem.operatorId }), lead.token); + assert.equal(r.status, 404, 'target must be a member'); + r = await t.api(url('/transfer'), post({ operatorId: dip.operatorId }), off.token); + assert.equal(r.status, 403); + r = await t.api(url('/transfer'), post({ operatorId: dip.operatorId }), lead.token); + assert.equal(r.body.changed, true); + assert.equal(A.membership(t.srv.db, dip.operatorId).role, 'leader'); + assert.equal(A.membership(t.srv.db, lead.operatorId).role, 'officer'); + r = await t.api(url('/leave'), { method: 'POST' }, lead.token); + assert.equal(r.body.changed, true); + r = await t.api(url('/leave'), { method: 'POST' }, lead.token); + assert.equal(r.body.changed, false, 'leaving twice is a no-op'); + + // disband: leader only; everything goes, names are free again + r = await t.api(url('/disband'), { method: 'POST' }, off.token); + assert.equal(r.status, 403); + r = await t.api(url('/disband'), { method: 'POST' }, dip.token); + assert.equal(r.status, 200); + assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliances').n, 0); + assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_members').n, 0); + assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_notes').n, 0); + assert.equal((await t.api(url(''), {}, dip.token)).status, 404); + r = await t.api('/alliances', post({ name: 'Roles', tag: 'RL' }), off.token); + assert.equal(r.status, 201, 'name and tag are reusable after a disband'); +}); + +test('alliances: a lone leader leaving disbands; alliance shows in /me and /map; directory and profile', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signupPeering('aa1'); + const b = await t.signupPeering('bb1'); + const idA = await found(t, a, 'Alpha Net', 'ALP'); + const idB = await found(t, b, 'Beta Net', 'BET'); + + let r = await t.api('/me', {}, a.token); + assert.deepEqual(r.body.operators[0].alliance, { id: idA, tag: 'ALP', name: 'Alpha Net' }); + const out = await t.api('/map?x=0&y=0&r=40', {}, b.token); + const mine = out.body.towns.find((x) => x.owner.id === a.operatorId); + assert.deepEqual(mine.owner.alliance, { id: idA, tag: 'ALP', name: 'Alpha Net' }); + assert.equal(mine.owner.allianceId, idA); + + r = await t.api('/alliances', {}, a.token); + assert.deepEqual(r.body.items.map((x) => x.tag), ['ALP', 'BET']); + r = await t.api('/alliances?q=beta', {}, a.token); + assert.deepEqual(r.body.items.map((x) => x.tag), ['BET']); + r = await t.api('/alliances?limit=1', {}, a.token); + assert.equal(r.body.items.length, 1); assert.equal(r.body.next, idA); + r = await t.api('/alliances?limit=1&after=' + r.body.next, {}, a.token); + assert.equal(r.body.items[0].tag, 'BET'); assert.equal(r.body.next, null); + + r = await t.api('/alliances/' + idB, {}, a.token); + assert.equal(r.body.alliance.memberCount, 1); assert.equal(r.body.alliance.myRole, null); assert.equal(r.body.alliance.relation, 'neutral'); + assert.equal(r.body.alliance.leader.name, 'bb1'); assert.ok(r.body.alliance.footprint >= 0); + r = await t.api('/alliances/mine', {}, a.token); + assert.equal(r.body.role, 'leader'); assert.ok(r.body.permissions.includes('disband')); assert.equal(r.body.peeringLevel, 1); + assert.equal((await t.api('/alliances/abc', {}, a.token)).status, 404); + + r = await t.api('/alliances/' + idA + '/leave', { method: 'POST' }, a.token); + assert.equal(r.body.disbanded, true); + r = await t.api('/alliances/mine', {}, a.token); + assert.equal(r.body.alliance, null); assert.equal(r.body.role, null); + r = await t.api('/me', {}, a.token); + assert.equal(r.body.operators[0].alliance, null); +}); + +test('alliances: lookup helpers for other modules', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signupPeering('hh1'), b = await t.signupPeering('hh2'), c = await t.signupPeering('hh3'), d = await t.signup('hh4'); + const idA = await found(t, a, 'Hel A', 'HA'); + const idB = await found(t, b, 'Hel B', 'HB'); + await join(t, a, idA, c); + const db = t.srv.db; + assert.equal(A.operatorRelation(db, a.operatorId, a.operatorId), 'self'); + assert.equal(A.operatorRelation(db, a.operatorId, c.operatorId), 'same_alliance'); + assert.equal(A.operatorRelation(db, a.operatorId, b.operatorId), 'neutral'); + assert.equal(A.operatorRelation(db, a.operatorId, d.operatorId), 'neutral'); + await t.api('/alliances/' + idA + '/diplomacy', post({ targetId: idB, state: 'war' }), a.token); + assert.equal(A.operatorRelation(db, c.operatorId, b.operatorId), 'war'); + assert.ok(A.atWar(db, b.operatorId, c.operatorId)); + assert.ok(!A.pactPartners(db, a.operatorId, b.operatorId)); + assert.ok(A.pactPartners(db, a.operatorId, c.operatorId) && A.confederated(db, a.operatorId, c.operatorId)); + assert.equal(A.relationBetween(db, idA, idB), 'war'); + assert.equal(A.relationBetween(db, idA, idA), 'neutral'); +}); diff --git a/test/social-diplomacy.test.js b/test/social-diplomacy.test.js new file mode 100644 index 0000000..9f03668 --- /dev/null +++ b/test/social-diplomacy.test.js @@ -0,0 +1,186 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const { createTestServer } = require('./helpers'); +const A = require('../server/alliances'); + +const post = (body) => ({ method: 'POST', body }); +const H = 3600 * 1000; + +// Two alliances (leaders lA, lB), each with a diplomat (dA, dB) and a plain member (mA). +async function setup() { + const t = await createTestServer({ contract: true }); + const lA = await t.signupPeering('lead_a'), lB = await t.signupPeering('lead_b'); + const dA = await t.signupPeering('dip_a'), dB = await t.signupPeering('dip_b'), mA = await t.signupPeering('mem_a'); + const mk = async (lead, name, tag) => (await t.api('/alliances', post({ name, tag }), lead.token)).body.allianceId; + const A1 = await mk(lA, 'Alpha', 'AAA'), B1 = await mk(lB, 'Bravo', 'BBB'); + const join = async (lead, id, u, role) => { + const inv = await t.api('/alliances/' + id + '/invite', post({ operatorId: u.operatorId }), lead.token); + await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, u.token); + if (role) await t.api('/alliances/' + id + '/role', post({ operatorId: u.operatorId, role }), lead.token); + }; + await join(lA, A1, dA, 'diplomat'); await join(lB, B1, dB, 'diplomat'); await join(lA, A1, mA); + return { t, lA, lB, dA, dB, mA, A1, B1 }; +} +const rel = (t, id, tok) => t.api('/alliances/' + id + '/diplomacy', {}, tok); +const types = async (t, u) => (await t.api('/notifications', {}, u.token)).body.items.map((n) => n.type); + +test('diplomacy: war is declared at once, peace and pacts need the other side to accept', async (t0) => { + const { t, lA, lB, dA, dB, mA, A1, B1 } = await setup(); + t0.after(() => t.close()); + + // permission: members cannot, diplomats can + let r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'war' }), mA.token); + assert.equal(r.status, 403); + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dA.token); + assert.equal(r.status, 422); + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'neutral' }), dA.token); + assert.equal(r.body.error.code, 'diplomacy_invalid', 'already neutral'); + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'bogus' }), dA.token); + assert.equal(r.status, 422); + + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'war' }), dA.token); + assert.equal(r.status, 200); assert.equal(r.body.result, 'applied'); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'war'); + r = await rel(t, B1, lB.token); + assert.equal(r.body.relations[0].state, 'war'); assert.equal(r.body.relations[0].other.tag, 'AAA'); + assert.ok((await types(t, dB)).includes('diplomacy_changed'), 'the other side is told'); + assert.ok((await types(t, mA)).includes('diplomacy_changed'), 'so are plain members of the declaring side'); + + // war -> confed is not allowed; war -> neutral is a proposal + r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'confed' }), dB.token); + assert.equal(r.body.error.code, 'diplomacy_invalid'); + r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'neutral' }), dB.token); + assert.equal(r.body.result, 'proposed'); const pid = r.body.proposalId; + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'war', 'nothing changes before acceptance'); + assert.ok((await types(t, dA)).includes('diplomacy_proposal')); + assert.ok(!(await types(t, mA)).includes('diplomacy_proposal'), 'only leader/diplomats are pinged'); + + r = await rel(t, A1, dA.token); + assert.equal(r.body.proposalsIn.length, 1); assert.equal(r.body.proposalsIn[0].state, 'neutral'); + r = await rel(t, B1, dB.token); + assert.equal(r.body.proposalsOut.length, 1); + + // wrong alliance / wrong role cannot answer + r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dB.token); + assert.equal(r.status, 403, 'the proposer cannot accept their own proposal'); + r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, mA.token); + assert.equal(r.status, 403); + r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dA.token); + assert.equal(r.body.changed, true); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'neutral'); + assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_relations').n, 0, 'neutral keeps no row'); + r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dA.token); + assert.equal(r.body.changed, false, 'idempotent'); + r = await t.api('/diplomacy/proposals/' + pid + '/decline', { method: 'POST' }, dA.token); + assert.equal(r.status, 409); + + // a pact: propose, replace, withdraw, decline, accept + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token); + const p1 = r.body.proposalId; + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'confed' }), dA.token); + const p2 = r.body.proposalId; assert.notEqual(p1, p2); + assert.equal(t.srv.db.get('SELECT status FROM alliance_proposals WHERE id = ?', p1).status, 'withdrawn', 'a new proposal replaces the old one'); + r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'confed' }), dB.token); + assert.equal(r.body.error.code, 'proposal_exists'); + r = await t.api('/diplomacy/proposals/' + p2, { method: 'DELETE' }, dB.token); + assert.equal(r.status, 403, 'only the proposer may withdraw'); + r = await t.api('/diplomacy/proposals/' + p2, { method: 'DELETE' }, dA.token); + assert.equal(r.body.changed, true); + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token); + r = await t.api('/diplomacy/proposals/' + r.body.proposalId + '/decline', { method: 'POST' }, dB.token); + assert.equal(r.body.changed, true); + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token); + r = await t.api('/diplomacy/proposals/' + r.body.proposalId + '/accept', { method: 'POST' }, dB.token); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'nap'); + assert.ok(A.pactPartners(t.srv.db, lA.operatorId, lB.operatorId)); + assert.ok(!A.confederated(t.srv.db, lA.operatorId, lB.operatorId)); +}); + +test('diplomacy: cancelling a pact takes 24 h / world speed, can be revoked, and runs through the event queue', async (t0) => { + const { t, lA, lB, dA, dB, A1, B1 } = await setup(); + t0.after(() => t.close()); + const accept = async (from, fromTok, to, toTok, state) => { + const r = await t.api('/alliances/' + from + '/diplomacy', post({ targetId: to, state }), fromTok); + return t.api('/diplomacy/proposals/' + r.body.proposalId + '/accept', { method: 'POST' }, toTok); + }; + await accept(A1, dA.token, B1, dB.token, 'confed'); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed'); + assert.ok(A.confederated(t.srv.db, lA.operatorId, lB.operatorId)); + + const t0ms = t.clock.now(); + let r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'neutral' }), dA.token); + assert.equal(r.body.result, 'scheduled'); assert.equal(r.body.effectiveAt, t0ms + 24 * H); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed', 'the pact still holds while the cancel is pending'); + r = await rel(t, B1, dB.token); + assert.equal(r.body.relations[0].pending.to, 'neutral'); assert.equal(r.body.relations[0].pending.byUs, false); + assert.ok((await types(t, lB)).includes('diplomacy_cancel_pending')); + // no further changes while one is pending + r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dB.token); + assert.equal(r.body.error.code, 'diplomacy_pending'); + + // revoke: only the side that started it + r = await t.api('/alliances/' + B1 + '/diplomacy/' + A1 + '/pending', { method: 'DELETE' }, dB.token); + assert.equal(r.status, 403); + r = await t.api('/alliances/' + A1 + '/diplomacy/' + B1 + '/pending', { method: 'DELETE' }, dA.token); + assert.equal(r.body.changed, true); + r = await t.api('/alliances/' + A1 + '/diplomacy/' + B1 + '/pending', { method: 'DELETE' }, dA.token); + assert.equal(r.body.changed, false); + t.clock.advance(25 * H); t.srv.scheduler.runDue(); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed', 'a revoked cancel never fires'); + assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'diploChange' AND status = 'cancelled'").n, 1); + + // cancel again and let it run: just before the deadline nothing, after it the change applies + r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dB.token); + assert.equal(r.body.result, 'scheduled', 'confed -> war is also a delayed move'); + t.clock.advance(24 * H - 1000); t.srv.scheduler.runDue(); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed'); + t.clock.advance(2000); t.srv.scheduler.runDue(); + assert.equal(A.relationBetween(t.srv.db, A1, B1), 'war'); + r = await rel(t, A1, dA.token); + assert.equal(r.body.relations[0].pending, null); + assert.ok((await types(t, lA)).filter((x) => x === 'diplomacy_changed').length >= 2); + assert.equal(t.srv.db.get("SELECT status FROM events WHERE type = 'diploChange' ORDER BY id DESC LIMIT 1").status, 'done'); +}); + +test('diplomacy: faster worlds shorten the cancel, disbanding clears relations and pending events', async (t0) => { + const t = await createTestServer({ contract: true, server: { world: { speed: 3 } } }); + t0.after(() => t.close()); + const l1 = await t.signupPeering('lead_one'), l2 = await t.signupPeering('lead_two'); + const a = (await t.api('/alliances', post({ name: 'One', tag: 'ONE' }), l1.token)).body.allianceId; + const b = (await t.api('/alliances', post({ name: 'Two', tag: 'TWO' }), l2.token)).body.allianceId; + let r = await t.api('/alliances/' + a + '/diplomacy', post({ targetId: b, state: 'nap' }), l1.token); + await t.api('/diplomacy/proposals/' + r.body.proposalId + '/accept', { method: 'POST' }, l2.token); + const now = t.clock.now(); + r = await t.api('/alliances/' + a + '/diplomacy', post({ targetId: b, state: 'neutral' }), l1.token); + assert.equal(r.body.effectiveAt, now + 8 * H, '24 h at 3x'); + + // disband the other side while the cancel is pending + await t.api('/alliances/' + b + '/disband', { method: 'POST' }, l2.token); + assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_relations').n, 0); + assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'diploChange' AND status = 'pending'").n, 0); + t.clock.advance(9 * H); t.srv.scheduler.runDue(); + assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); + r = await t.api('/notifications', {}, l1.token); + assert.ok(r.body.items.some((n) => n.type === 'diplomacy_changed' && n.payload.reason === 'disbanded' && n.payload.to === 'neutral')); +}); + +test('diplomacy: proposals expire, and a stale proposal is re-validated on accept', async (t0) => { + const { t, dA, dB, A1, B1 } = await setup(); + t0.after(() => t.close()); + let r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token); + const pid = r.body.proposalId; + t.clock.advance(73 * H); + r = await rel(t, B1, dB.token); + assert.equal(r.body.proposalsIn.length, 0, 'expired proposals are not listed'); + r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dB.token); + assert.equal(r.body.error.code, 'proposal_expired'); + + // pending proposal, then war is declared: the proposal is withdrawn by the state change + r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token); + const p2 = r.body.proposalId; + await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dB.token); + assert.equal(t.srv.db.get('SELECT status FROM alliance_proposals WHERE id = ?', p2).status, 'withdrawn'); + r = await t.api('/diplomacy/proposals/' + p2 + '/accept', { method: 'POST' }, dB.token); + assert.equal(r.status, 409); +}); diff --git a/test/social-messages.test.js b/test/social-messages.test.js new file mode 100644 index 0000000..f0fac57 --- /dev/null +++ b/test/social-messages.test.js @@ -0,0 +1,171 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const { createTestServer } = require('./helpers'); + +const post = (body) => ({ method: 'POST', body }); +const MIN = 60 * 1000; + +test('messages: send, inbox/outbox/thread, read, delete own copy', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signup('alice'), b = await t.signup('bobby'), c = await t.signup('carol'); + + let r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'hi‮ bob​!\u0007' }), a.token); + assert.equal(r.status, 201); assert.equal(r.body.recipients, 1); + const m1 = r.body.messageId; + t.clock.advance(1000); + r = await t.api('/messages', post({ toName: 'ALICE', text: 'hello back' }), b.token); + assert.equal(r.status, 201); const m2 = r.body.messageId; + t.clock.advance(1000); + r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'third' }), c.token); + const m3 = r.body.messageId; + + r = await t.api('/messages/inbox', {}, b.token); + assert.deepEqual(r.body.items.map((m) => m.id), [m3, m1], 'newest first'); + assert.equal(r.body.unread, 2); + assert.equal(r.body.items[1].text, 'hi bob!', 'control and bidi characters are stripped'); + assert.equal(r.body.items[1].from.name, 'alice'); assert.equal(r.body.items[1].direction, 'in'); + assert.equal(r.body.items[1].readAt, null); + + // cursor: page of one + r = await t.api('/messages/inbox?limit=1', {}, b.token); + assert.equal(r.body.items.length, 1); assert.equal(r.body.next, m3); + r = await t.api('/messages/inbox?limit=1&after=' + r.body.next, {}, b.token); + assert.deepEqual(r.body.items.map((m) => m.id), [m1]); assert.equal(r.body.next, null); + + r = await t.api('/messages/outbox', {}, a.token); + assert.deepEqual(r.body.items.map((m) => m.id), [m1]); assert.equal(r.body.items[0].to.name, 'bobby'); assert.equal(r.body.items[0].direction, 'out'); + + // thread alice <-> bobby, both directions, excludes carol + r = await t.api('/messages/thread/' + b.operatorId, {}, a.token); + assert.deepEqual(r.body.items.map((m) => m.id), [m2, m1]); + assert.deepEqual(r.body.items.map((m) => m.direction), ['in', 'out']); + r = await t.api('/messages/thread/' + a.operatorId, {}, b.token); + assert.deepEqual(r.body.items.map((m) => m.id), [m2, m1]); + + // read + r = await t.api('/messages/read', post({ ids: [m1, 99999] }), b.token); + assert.equal(r.body.changed, true); assert.equal(r.body.count, 1); + r = await t.api('/messages/read', post({ ids: [m1] }), b.token); + assert.equal(r.body.changed, false); + r = await t.api('/messages/inbox?unread=true', {}, b.token); + assert.deepEqual(r.body.items.map((m) => m.id), [m3]); + r = await t.api('/messages/read', post({ all: true }), b.token); + assert.equal(r.body.count, 1); + r = await t.api('/messages/inbox', {}, b.token); + assert.equal(r.body.unread, 0); assert.ok(r.body.items.every((m) => m.readAt === t.clock.now())); + r = await t.api('/messages/' + m1, {}, b.token); + assert.equal(r.body.message.text, 'hi bob!'); + assert.equal((await t.api('/messages/' + m1, {}, c.token)).status, 404, 'strangers cannot read it'); + + // delete own copy only + r = await t.api('/messages/' + m1, { method: 'DELETE' }, b.token); + assert.equal(r.body.changed, true); + r = await t.api('/messages/' + m1, { method: 'DELETE' }, b.token); + assert.equal(r.body.changed, false); + assert.equal((await t.api('/messages/' + m1, {}, c.token).then((x) => x.status)), 404); + assert.equal((await t.api('/messages/inbox', {}, b.token)).body.items.some((m) => m.id === m1), false); + assert.equal((await t.api('/messages/outbox', {}, a.token)).body.items.length, 1, 'the sender keeps theirs'); + r = await t.api('/messages/' + m1, { method: 'DELETE' }, a.token); + assert.equal(r.body.changed, true); + assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM messages WHERE id = ?', m1).n, 0, 'purged when nobody has a copy'); + assert.equal((await t.api('/messages/' + m1, { method: 'DELETE' }, a.token)).status, 404); + + // notifications for the recipient + r = await t.api('/notifications', {}, b.token); + assert.ok(r.body.items.some((n) => n.type === 'message' && n.payload.from.name === 'alice')); +}); + +test('messages: validation, self, empty, too long', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signup('alice'), b = await t.signup('bobby'); + const send = (body) => t.api('/messages', post(body), a.token); + assert.equal((await send({ text: 'no target' })).status, 422); + assert.equal((await send({ toOperatorId: b.operatorId, toName: 'bobby', text: 'two targets' })).status, 422); + assert.equal((await send({ toOperatorId: a.operatorId, text: 'self' })).status, 422); + assert.equal((await send({ toOperatorId: b.operatorId, text: '' })).status, 422); + assert.equal((await send({ toOperatorId: b.operatorId, text: '‮​ \u0007' })).status, 422, 'nothing left after stripping'); + assert.equal((await send({ toOperatorId: b.operatorId, text: 'x'.repeat(2001) })).status, 422); + assert.equal((await send({ toOperatorId: b.operatorId, text: 'x'.repeat(2000) })).status, 201); + assert.equal((await send({ toName: 'nobody', text: 'x' })).status, 404); + assert.equal((await send({ toOperatorId: 999999, text: 'x' })).status, 404); + assert.equal((await send({ toAlliance: true, text: 'x' })).body.error.code, 'not_in_alliance'); + assert.equal((await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'x' }))).status, 401); +}); + +test('messages: per-sender rate limit follows the clock', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signup('alice'), b = await t.signup('bobby'); + for (let i = 0; i < 15; i++) { + const r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'm' + i }), a.token); + assert.equal(r.status, 201, 'message ' + i); + } + let r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'one more' }), a.token); + assert.equal(r.status, 429); assert.equal(r.body.error.code, 'rate_limited'); + assert.ok(r.body.error.details.retryAfter > 0 && r.body.error.details.retryAfter <= 600); + assert.equal(r.headers.get('retry-after'), String(r.body.error.details.retryAfter)); + // bobby is not affected by alice's limit + assert.equal((await t.api('/messages', post({ toOperatorId: a.operatorId, text: 'hey' }), b.token)).status, 201); + t.clock.advance(11 * MIN); + assert.equal((await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'again' }), a.token)).status, 201); + // hourly cap: 60 per hour + for (let i = 0; i < 100; i++) { + t.clock.advance(11 * MIN / 15 * 1); // ~44 s apart: within the 10-minute window never more than 15 + r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'h' + i }), a.token); + if (r.status === 429) break; + } + assert.equal(r.status, 429); + assert.equal(r.body.error.details.windowMs, 60 * MIN, 'the hourly window is the one that bites'); +}); + +test('messages: alliance broadcast, block list, and the feed', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const lead = await t.signupPeering('leader'), m1 = await t.signupPeering('memb1'), m2 = await t.signupPeering('memb2'), out = await t.signup('outsider'); + const id = (await t.api('/alliances', post({ name: 'Chat Club', tag: 'CHAT' }), lead.token)).body.allianceId; + for (const u of [m1, m2]) { + const inv = await t.api('/alliances/' + id + '/invite', post({ operatorId: u.operatorId }), lead.token); + await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, u.token); + } + // m2 blocks m1 + let r = await t.api('/messages/blocks', post({ operatorId: m1.operatorId }), m2.token); + assert.equal(r.body.changed, true); + r = await t.api('/messages/blocks', post({ operatorId: m1.operatorId }), m2.token); + assert.equal(r.body.changed, false); + r = await t.api('/messages/blocks', {}, m2.token); + assert.deepEqual(r.body.items.map((b) => b.name), ['memb1']); + + r = await t.api('/messages', post({ toAlliance: true, text: 'meeting at 8' }), m1.token); + assert.equal(r.status, 201); assert.equal(r.body.kind, 'alliance'); assert.equal(r.body.recipients, 1, 'lead only: m2 blocked the sender'); + r = await t.api('/messages', post({ toAlliance: true, text: 'from the lead' }), lead.token); + assert.equal(r.body.recipients, 2); + + r = await t.api('/messages/alliance', {}, lead.token); + assert.deepEqual(r.body.items.map((m) => m.text), ['from the lead', 'meeting at 8']); + assert.equal(r.body.items[0].alliance.tag, 'CHAT'); + r = await t.api('/messages/alliance', {}, m2.token); + assert.deepEqual(r.body.items.map((m) => m.text), ['from the lead']); + r = await t.api('/messages/alliance', {}, m1.token); + assert.equal(r.body.items.length, 2, 'the sender sees their own broadcast and the lead\'s'); + assert.equal((await t.api('/messages/alliance', {}, out.token)).body.error.code, 'not_in_alliance'); + assert.equal((await t.api('/messages/inbox', {}, out.token)).body.items.length, 0); + + // blocked DMs are accepted silently and never delivered + r = await t.api('/messages', post({ toOperatorId: m2.operatorId, text: 'dm to the blocker' }), m1.token); + assert.equal(r.status, 201); assert.equal(r.body.recipients, 0); + assert.equal((await t.api('/messages/inbox', {}, m2.token)).body.items.filter((m) => m.text === 'dm to the blocker').length, 0); + assert.equal((await t.api('/messages/outbox', {}, m1.token)).body.items[0].text, 'dm to the blocker'); + + r = await t.api('/messages/blocks/' + m1.operatorId, { method: 'DELETE' }, m2.token); + assert.equal(r.body.changed, true); + r = await t.api('/messages', post({ toOperatorId: m2.operatorId, text: 'now it arrives' }), m1.token); + assert.equal(r.body.recipients, 1); + + // the broadcast stays readable after the alliance is gone + await t.api('/alliances/' + id + '/disband', { method: 'POST' }, lead.token); + r = await t.api('/messages/inbox', {}, lead.token); + assert.ok(r.body.items.some((m) => m.text === 'meeting at 8' && m.alliance.tag === 'CHAT')); +}); diff --git a/test/social-rankings.test.js b/test/social-rankings.test.js new file mode 100644 index 0000000..ed82431 --- /dev/null +++ b/test/social-rankings.test.js @@ -0,0 +1,76 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const { createTestServer } = require('./helpers'); + +const post = (body) => ({ method: 'POST', body }); +const DAY = 24 * 3600 * 1000; + +test('rankings: operators and alliances by footprint, ties by id, rank-offset cursor', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signupPeering('rank_a'), b = await t.signupPeering('rank_b'), c = await t.signup('rank_c'); + const ia = (await t.api('/alliances', post({ name: 'Rank A', tag: 'RA' }), a.token)).body.allianceId; + const ib = (await t.api('/alliances', post({ name: 'Rank B', tag: 'RB' }), b.token)).body.allianceId; + const inv = await t.api('/alliances/' + ia + '/invite', post({ operatorId: c.operatorId }), a.token); + t.setBuilding(c.townId, 'peering_office', 1); + await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, c.token); + + // all three have the same buildings (+ an office): after a day the footprint is equal; give b a core router bump + t.setBuilding(b.townId, 'core_router', 5); + t.clock.advance(DAY); + let r = await t.api('/rankings/operators', {}, a.token); + assert.equal(r.body.total, 3); + assert.deepEqual(r.body.items.map((x) => x.name), ['rank_b', 'rank_a', 'rank_c'], 'b leads, a and c tie and a has the lower id'); + assert.deepEqual(r.body.items.map((x) => x.rank), [1, 2, 3]); + assert.equal(r.body.you.rank, 2); + assert.equal(r.body.items[1].allianceTag, 'RA'); assert.equal(r.body.items[0].towns, 1); + assert.ok(r.body.items[0].footprint > r.body.items[1].footprint && r.body.items[1].footprint > 0); + + // the number is the rules' footprintAt over the town + const R = require('../public/js/rules.js'); + const { loadTown } = require('../server/state'); + const fpB = R.footprintAt(loadTown(t.srv.db, b.townId), t.clock.now()); + assert.ok(Math.abs(r.body.items[0].footprint - fpB) < 0.01, r.body.items[0].footprint + ' vs ' + fpB); + + r = await t.api('/rankings/operators?limit=2', {}, a.token); + assert.equal(r.body.items.length, 2); assert.equal(r.body.next, 2); + r = await t.api('/rankings/operators?limit=2&after=2', {}, a.token); + assert.deepEqual(r.body.items.map((x) => x.rank), [3]); assert.equal(r.body.next, null); + + r = await t.api('/rankings/alliances', {}, a.token); + assert.deepEqual(r.body.items.map((x) => x.tag), ['RA', 'RB'], 'two members beat one stronger member'); + assert.equal(r.body.items[0].members, 2); assert.equal(r.body.items[0].towns, 2); + assert.equal(r.body.you.rank, 1); + const sumA = r.body.items[0].footprint; + const ops = (await t.api('/rankings/operators', {}, a.token)).body.items; + const expect = ops.filter((x) => x.allianceTag === 'RA').reduce((s, x) => s + x.footprint, 0); + assert.ok(Math.abs(sumA - expect) < 0.02); + assert.ok(ib); + r = await t.api('/rankings/alliances', {}, c.token); + assert.equal(r.body.you.tag, 'RA'); +}); + +test('rankings: battles read operator_stats when the military stage created it', async (t0) => { + const t = await createTestServer({ contract: true }); + t0.after(() => t.close()); + const a = await t.signup('war_a'), b = await t.signup('war_b'), c = await t.signup('war_c'); + const hasTable = !!t.srv.db.get("SELECT 1 AS x FROM sqlite_master WHERE name = 'operator_stats'"); + let r = await t.api('/rankings/battles', {}, a.token); + assert.equal(r.status, 200); + if (!hasTable) { + assert.equal(r.body.available, false); assert.deepEqual(r.body.items, []); + return; + } + assert.equal(r.body.available, true); assert.deepEqual(r.body.items, [], 'nobody has points yet'); + t.srv.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, ?, ?)', a.operatorId, 50, 5); + t.srv.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, ?, ?)', b.operatorId, 10, 90); + r = await t.api('/rankings/battles', {}, c.token); + assert.deepEqual(r.body.items.map((x) => x.name), ['war_a', 'war_b']); + assert.equal(r.body.by, 'attack'); + r = await t.api('/rankings/battles?by=defense', {}, c.token); + assert.deepEqual(r.body.items.map((x) => x.name), ['war_b', 'war_a']); + r = await t.api('/rankings/battles?by=total', {}, a.token); + assert.deepEqual(r.body.items.map((x) => x.name), ['war_b', 'war_a']); assert.equal(r.body.you.name, 'war_a'); + assert.equal((await t.api('/rankings/battles?by=bogus', {}, a.token)).status, 422); +}); diff --git a/test/social-rules.test.js b/test/social-rules.test.js new file mode 100644 index 0000000..3d3b2fc --- /dev/null +++ b/test/social-rules.test.js @@ -0,0 +1,54 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); +const { cleanText } = require('../server/text'); + +test('rules: alliance size cap is 10 + 2 per Peering office level', () => { + assert.equal(R.allianceCap(0), 10); + assert.equal(R.allianceCap(1), 12); + assert.equal(R.allianceCap(10), 30); + assert.equal(R.allianceCap(-3), 10); +}); + +test('rules: permission table and seniority', () => { + assert.ok(R.allianceCan('leader', 'disband') && !R.allianceCan('officer', 'disband')); + assert.ok(R.allianceCan('officer', 'invite') && !R.allianceCan('member', 'invite')); + assert.ok(R.allianceCan('diplomat', 'diplomacy') && !R.allianceCan('officer', 'diplomacy')); + assert.ok(!R.allianceCan('leader', 'no_such_action')); + assert.ok(R.outranks('leader', 'diplomat') && R.outranks('diplomat', 'officer') && R.outranks('officer', 'member')); + assert.ok(!R.outranks('officer', 'officer') && !R.outranks('member', 'leader')); + // every role listed in the table exists + for (const roles of Object.values(D.SOCIAL.permissions)) for (const r of roles) assert.ok(D.SOCIAL.roles.includes(r), r); +}); + +test('rules: diplomacy moves', () => { + assert.equal(R.diplomacyMove('neutral', 'war'), 'immediate'); + assert.equal(R.diplomacyMove('neutral', 'nap'), 'proposal'); + assert.equal(R.diplomacyMove('war', 'neutral'), 'proposal'); + assert.equal(R.diplomacyMove('nap', 'neutral'), 'delayed'); + assert.equal(R.diplomacyMove('confed', 'war'), 'delayed'); + assert.equal(R.diplomacyMove('war', 'confed'), null); + assert.equal(R.diplomacyMove('war', 'war'), null); + assert.equal(R.diplomacyMove('bogus', 'war'), null); + assert.equal(R.pactCancelMs(1), 24 * 3600 * 1000); + assert.equal(R.pactCancelMs(3), 8 * 3600 * 1000); +}); + +test('text: control, bidi and invisible characters are stripped', () => { + assert.equal(cleanText('a‮b​c\u0007d'), 'abcd'); + assert.equal(cleanText('x\u{E0041}y؜z'), 'xyz'); + assert.equal(cleanText(' a \t\n b '), 'a b'); + assert.equal(cleanText('l1\r\nl2\n\n\n\n\nl3', { multiline: true }), 'l1\nl2\n\n\nl3'); + assert.equal(cleanText('é'), 'é'); // NFC + assert.equal(cleanText('\u{1F468}‍\u{1F469}'), '\u{1F468}‍\u{1F469}'); // ZWJ emoji sequences survive + assert.equal(cleanText(undefined), ''); +}); + +test('helpers: the response contract check really fails on a body that breaks its schema', () => { + const { checkContract } = require('./helpers'); + assert.throws(() => checkContract('GET', '/alliances/mine', 200, { serverTime: 1 }), /breaks its response schema/); + assert.throws(() => checkContract('GET', '/rankings/alliances', 200, { serverTime: 1, total: 'x', you: null, items: [], next: null }), /total/); + checkContract('GET', '/alliances/mine', 200, { serverTime: 1, operatorId: 1, worldId: 1, alliance: null, role: null, permissions: [], peeringLevel: 0 }); +}); diff --git a/test/spine-core.test.js b/test/spine-core.test.js new file mode 100644 index 0000000..6523468 --- /dev/null +++ b/test/spine-core.test.js @@ -0,0 +1,228 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { createServer } = require('../server'); +const { FakeClock } = require('../server/clock'); +const { openDb, migrate } = require('../server/db'); +const { Scheduler } = require('../server/scheduler'); +const { validate } = require('../server/validate'); +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); + +async function boot(opts) { + const clock = new FakeClock(); + const srv = await createServer(Object.assign({ port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {} }, opts)); + const base = 'http://127.0.0.1:' + srv.port + '/api/v1'; + const call = async (p, o, token) => { + o = o || {}; + const headers = Object.assign({ 'content-type': 'application/json' }, o.headers || {}); + if (token) headers.authorization = 'Bearer ' + token; + const r = await fetch(base + p, Object.assign({}, o, { headers, body: o.body && JSON.stringify(o.body) })); + return { status: r.status, body: await r.json(), headers: r.headers }; + }; + const signup = async (username) => { + const r = await call('/auth/signup', { method: 'POST', body: { username, password: 'correct horse battery' } }); + assert.equal(r.status, 201, JSON.stringify(r.body)); + return { token: r.body.token, townId: r.body.operators[0].towns[0].id, userId: r.body.user.id }; + }; + return { srv, clock, call, signup }; +} + +test('rules: lazy resources are exact between settles and capped', () => { + const town = { speed: 1, updatedAt: 0, res: { fiber: 0, hardware: 0, capital: 0, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, + buildings: R.initialBuildings() }; + const h = D.HOUR_MS; + const a = R.resourcesAt(town, h).amounts; + assert.ok(Math.abs(a.fiber - 30) < 1e-9, 'five level-1 cable yards make 30/h'); + assert.equal(R.resourcesAt(town, 1000 * h).amounts.fiber, R.storageCap(town)); + assert.equal(R.resourcesAt(town, 0).amounts.fiber, 0); + // splitting the interval changes nothing + const mid = R.resourcesAt(town, 3 * h).amounts; + const t2 = Object.assign({}, town, { updatedAt: 3 * h, res: mid }); + assert.ok(Math.abs(R.resourcesAt(t2, 5 * h).amounts.fiber - R.resourcesAt(town, 5 * h).amounts.fiber) < 1e-9); +}); + +test('rules: map generation is deterministic and spawn respects spacing', () => { + assert.deepEqual(R.tileAt(7, 50, 10, 10), R.tileAt(7, 50, 10, 10)); + assert.equal(R.tileAt(7, 50, 51, 0).type, 'void'); + const towns = []; + for (let i = 0; i < 40; i++) { + const s = R.pickSpawn(7, 50, i, towns); + assert.ok(s, 'spawn ' + i); + assert.equal(R.tileAt(7, 50, s.x, s.y).type, 'land'); + for (const t of towns) assert.ok(Math.max(Math.abs(t.x - s.x), Math.abs(t.y - s.y)) >= D.TILE.spawnMinSpacing); + towns.push(s); + } +}); + +test('validate: unknown fields, types, coercion', () => { + const s = { type: 'object', required: ['a'], properties: { a: { type: 'integer', minimum: 1 }, b: { type: 'string', maxLength: 3 } } }; + assert.ok(validate(s, { a: 1 }).ok); + assert.ok(!validate(s, {}).ok); + assert.ok(!validate(s, { a: 1, c: 2 }).ok); + assert.ok(!validate(s, { a: 1.5 }).ok); + assert.ok(!validate(s, { a: 1, b: 'long' }).ok); + assert.ok(validate(s, { a: '5' }, { coerce: true }).ok); +}); + +test('migrations: applied once, edits are detected', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mig-')); + fs.writeFileSync(path.join(dir, '001_a.sql'), 'CREATE TABLE a (x INTEGER);'); + const db = openDb(':memory:'); + assert.deepEqual(migrate(db, dir), ['001_a.sql']); + assert.deepEqual(migrate(db, dir), []); + fs.writeFileSync(path.join(dir, '001_a.sql'), 'CREATE TABLE a (x INTEGER, y INTEGER);'); + assert.throws(() => migrate(db, dir), /edited after/); +}); + +test('scheduler: events run in (due_at, id) order, failures do not block, handlers see their own due time', () => { + const clock = new FakeClock(1000); + const db = openDb(':memory:'); + migrate(db); + db.run("INSERT INTO worlds (name, speed, map_radius, seed, start_at, created_at) VALUES ('w', 1, 10, 1, 0, 0)"); + const seen = []; + const s = new Scheduler({ db, clock, log: () => {}, autoArm: false, handlers: { + a: (ctx, ev) => { seen.push([ev.payload.n, ctx.now]); if (ev.payload.n === 2) ctx.enqueue({ worldId: 1, dueAt: 1500, type: 'a', payload: { n: 9 } }); }, + boom: () => { throw new Error('nope'); }, + } }); + s.enqueue({ worldId: 1, dueAt: 3000, type: 'a', payload: { n: 3 } }); + s.enqueue({ worldId: 1, dueAt: 2000, type: 'a', payload: { n: 2 } }); + s.enqueue({ worldId: 1, dueAt: 2000, type: 'boom' }); + s.enqueue({ worldId: 1, dueAt: 2000, type: 'a', payload: { n: 4 } }); + assert.equal(s.runDue(1999), 0); + clock.set(10000); + assert.equal(s.runDue(), 5); + // a follow-up enqueued with an earlier due time is processed next, before later-due events + assert.deepEqual(seen, [[2, 2000], [9, 1500], [4, 2000], [3, 3000]]); + assert.equal(db.get("SELECT status FROM events WHERE type = 'boom'").status, 'failed'); + assert.equal(db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'done'").n, 4); +}); + +test('api: signup, build lifecycle with a fake clock, queue limits, cancel refund', async () => { + const { srv, clock, call, signup } = await boot(); + try { + const p = await signup('alice'); + let r = await call('/towns/' + p.townId, {}, p.token); + assert.equal(r.status, 200); + const before = r.body.town.resources.fiber.amount; + r = await call('/towns/' + p.townId + '/build', { method: 'POST', body: { key: 'f1' } }, p.token); + assert.equal(r.status, 201); + const { dueAt, cost, eventId } = r.body; + // one slot only: second build is refused with a stable code + r = await call('/towns/' + p.townId + '/build', { method: 'POST', body: { key: 'f2' } }, p.token); + assert.equal(r.status, 409); assert.equal(r.body.error.code, 'queue_full'); + // not done yet one ms before + clock.set(dueAt - 1); + r = await call('/towns/' + p.townId, {}, p.token); + assert.equal(r.body.town.buildings.find((b) => b.key === 'f1').level, 1); + assert.equal(r.body.town.queue.length, 1); + clock.set(dueAt); + r = await call('/towns/' + p.townId, {}, p.token); + assert.equal(r.body.town.buildings.find((b) => b.key === 'f1').level, 2); + assert.equal(r.body.town.queue.length, 0); + const n = await call('/notifications', {}, p.token); + assert.equal(n.body.items[0].type, 'build_done'); + // cancel refunds 80% + const f = r.body.town.resources.fiber.amount; + r = await call('/towns/' + p.townId + '/build', { method: 'POST', body: { key: 'rack_hall' } }, p.token); + assert.equal(r.status, 201); + const rack = r.body; + r = await call('/towns/' + p.townId + '/queue/' + rack.eventId, { method: 'DELETE' }, p.token); + assert.equal(r.status, 200); + r = await call('/towns/' + p.townId, {}, p.token); + assert.ok(r.body.town.resources.fiber.amount >= f - rack.cost.fiber + Math.floor(rack.cost.fiber * 0.8) - 1e-6); + assert.equal(r.body.town.queue.length, 0); + assert.ok(before > 0 && cost.fiber > 0 && eventId > 0); + } finally { await srv.close(); } +}); + +test('api: ownership is not leaked, auth is required, errors use the envelope', async () => { + const { srv, call, signup } = await boot(); + try { + const a = await signup('alice'), b = await signup('bobby'); + let r = await call('/towns/' + a.townId, {}, b.token); + assert.equal(r.status, 404); assert.equal(r.body.error.code, 'not_found'); + r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1' } }, b.token); + assert.equal(r.status, 404); + r = await call('/towns/' + a.townId); + assert.equal(r.status, 401); assert.equal(r.body.error.code, 'unauthorized'); + r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1', extra: 1 } }, a.token); + assert.equal(r.status, 422); assert.equal(r.body.error.code, 'validation_failed'); + r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'nope' } }, a.token); + assert.equal(r.body.error.code, 'unknown_building'); + r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'ops_lab' } }, a.token); + assert.equal(r.body.error.code, 'requirements_not_met'); + assert.ok(typeof r.body.serverTime === 'number'); + } finally { await srv.close(); } +}); + +test('api: idempotency key replays and rejects reuse with a different request', async () => { + const { srv, call, signup } = await boot(); + try { + const a = await signup('alice'); + const h = { 'idempotency-key': 'abcdef123456' }; + const r1 = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1' }, headers: h }, a.token); + const r2 = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1' }, headers: h }, a.token); + assert.equal(r1.status, 201); assert.equal(r2.status, 201); + assert.equal(r2.headers.get('idempotent-replay'), 'true'); + assert.equal(r1.body.eventId, r2.body.eventId); + const r3 = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f2' }, headers: h }, a.token); + assert.equal(r3.body.error.code, 'idempotency_key_reuse'); + const t = await call('/towns/' + a.townId, {}, a.token); + assert.equal(t.body.town.queue.length, 1); + } finally { await srv.close(); } +}); + +test('auth: login, token list/revoke, wrong password, duplicate username', async () => { + const { srv, call, signup } = await boot(); + try { + const a = await signup('alice'); + let r = await call('/auth/signup', { method: 'POST', body: { username: 'ALICE', password: 'correct horse battery' } }); + assert.equal(r.body.error.code, 'username_taken'); + r = await call('/auth/login', { method: 'POST', body: { username: 'alice', password: 'wrong password!!' } }); + assert.equal(r.status, 401); assert.equal(r.body.error.code, 'invalid_credentials'); + r = await call('/auth/login', { method: 'POST', body: { username: 'alice', password: 'correct horse battery', device: 'phone' } }); + assert.equal(r.status, 200); + const t2 = r.body.token; + r = await call('/auth/tokens', {}, a.token); + assert.equal(r.body.tokens.length, 2); + assert.equal(r.body.tokens.filter((t) => t.current).length, 1); + const phone = r.body.tokens.find((t) => t.device === 'phone'); + r = await call('/auth/tokens/' + phone.id, { method: 'DELETE' }, a.token); + assert.equal(r.status, 200); + r = await call('/me', {}, t2); + assert.equal(r.status, 401); + } finally { await srv.close(); } +}); + +test('restart: overdue events are caught up in order before traffic', async () => { + const dbPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'restart-')), 'game.db'); + const clock = new FakeClock(); + const mk = () => createServer({ port: 0, host: '127.0.0.1', dbPath, clock, autoArm: false, log: () => {} }); + let srv = await mk(); + const base = () => 'http://127.0.0.1:' + srv.port + '/api/v1'; + let r = await (await fetch(base() + '/auth/signup', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'alice', password: 'correct horse battery' }) })).json(); + const token = r.token, townId = r.operators[0].towns[0].id; + const b = await (await fetch(base() + '/towns/' + townId + '/build', { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + token }, body: JSON.stringify({ key: 'f1' }) })).json(); + await srv.close(); + clock.set(b.dueAt + 10 * 60 * 1000); + srv = await mk(); + try { + assert.equal(srv.db.get("SELECT level FROM buildings WHERE town_id = ? AND key = 'f1'", townId).level, 2, 'completed during catch-up'); + assert.equal(srv.db.get("SELECT status FROM events WHERE id = ?", b.eventId).status, 'done'); + } finally { await srv.close(); } +}); + +test('openapi.json is up to date and describes every route', () => { + const { render, FILE, build } = require('../tools/gen-openapi'); + assert.equal(fs.readFileSync(FILE, 'utf8'), render(), 'run npm run openapi'); + const { Router } = require('../server/http'); + const routes = require('../server/routes'); + const router = new Router(); + routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null }) })); + const spec = build(); + for (const r of router.routes) assert.ok(spec.paths[r.path.replace(/:([A-Za-z]+)/g, '{$1}')][r.method.toLowerCase()], r.method + ' ' + r.path); +}); diff --git a/tools/admin.js b/tools/admin.js new file mode 100644 index 0000000..c2e1f56 --- /dev/null +++ b/tools/admin.js @@ -0,0 +1,719 @@ +#!/usr/bin/env node +'use strict'; +/* + * UPSTREAM admin CLI. Node core + the game's own modules only (server/db.js, server/state.js, server/world.js, + * public/js/rules.js). Works on a stopped OR a running server's database: SQLite WAL allows a second process to read + * and write, every write here is one short BEGIN IMMEDIATE transaction (db.tx) and the connection is always closed. + * + * node tools/admin.js help + * DB_PATH=/var/lib/upstream/game.db node tools/admin.js worlds + * + * Run it as the service user (deploy/upstream-admin does that), otherwise the -wal/-shm files can end up owned by + * root and the server can no longer open the database. Never prints tokens or password hashes: those columns are not + * selected anywhere in this file. + * + * Exit codes: 0 ok, 1 failed, 2 usage / missing confirmation flag, 3 not found. + */ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const ROOT = path.join(__dirname, '..'); +const R = require(path.join(ROOT, 'public', 'js', 'rules.js')); +const { openDb, migrate } = require(path.join(ROOT, 'server', 'db.js')); +const { createWorld } = require(path.join(ROOT, 'server', 'world.js')); +const { loadWorld, townFromRow } = require(path.join(ROOT, 'server', 'state.js')); +const { FakeClock } = require(path.join(ROOT, 'server', 'clock.js')); + +const HOUR = 3600 * 1000; +const DAY = 24 * HOUR; + +class AdminError extends Error { + constructor(message, code) { super(message); this.exitCode = code || 1; } +} +const usage = (m) => new AdminError(m, 2); +const notFound = (m) => new AdminError(m, 3); + +// ---- argument parsing and small helpers (exported for tests) ----------------------------------------------------- + +const BOOLEAN_FLAGS = new Set(['yes', 'yes-destroy', 'json', 'pending', 'simulate', 'banned', 'help', 'new-seed']); + +// argv (without node and script) -> { _: [positionals], flags: { name: string | true } } +function parseArgs(argv) { + const out = { _: [], flags: {} }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--') { out._.push(...argv.slice(i + 1)); break; } + if (a.startsWith('--') && a.length > 2) { + let name = a.slice(2), val; + const eq = name.indexOf('='); + if (eq >= 0) { val = name.slice(eq + 1); name = name.slice(0, eq); } + if (BOOLEAN_FLAGS.has(name)) out.flags[name] = val === undefined ? true : !/^(0|false|no)$/i.test(val); + else { + if (val === undefined) { + if (i + 1 >= argv.length) throw usage('--' + name + ' needs a value'); + val = argv[++i]; + } + out.flags[name] = val; + } + } else if (a === '-h') out.flags.help = true; + else out._.push(a); + } + return out; +} + +function parseDuration(s) { + const m = /^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i.exec(String(s).trim()); + if (!m) throw usage('bad duration ' + JSON.stringify(s) + ' (examples: 90m, 36h, 14d)'); + return Math.round(Number(m[1]) * { s: 1000, m: 60000, h: HOUR, d: DAY, w: 7 * DAY }[m[2].toLowerCase()]); +} + +// "now", +2h, -30m, an ISO date/time or integer ms since the epoch -> ms +function parseTime(s, now) { + s = String(s).trim(); + if (s === 'now') return now; + if (/^\d{9,}$/.test(s)) return Number(s); + if (/^[+-]/.test(s)) return now + (s[0] === '-' ? -1 : 1) * parseDuration(s.slice(1)); + const t = Date.parse(s); + if (Number.isNaN(t)) throw usage('bad time ' + JSON.stringify(s) + ' (use now, +2h, an ISO date or ms since the epoch)'); + return t; +} + +function intFlag(flags, name, { min = -Infinity, max = Infinity, def } = {}) { + const v = flags[name]; + if (v === undefined) return def; + const n = Number(v); + if (!Number.isInteger(n) || n < min || n > max) throw usage('--' + name + ' must be an integer between ' + min + ' and ' + max); + return n; +} + +function numFlag(flags, name, { min = -Infinity, max = Infinity, def } = {}) { + const v = flags[name]; + if (v === undefined) return def; + const n = Number(v); + if (!Number.isFinite(n) || n < min || n > max) throw usage('--' + name + ' must be a number between ' + min + ' and ' + max); + return n; +} + +const iso = (ms) => (ms === null || ms === undefined ? '-' : new Date(ms).toISOString().replace(/\.\d+Z$/, 'Z')); + +function rel(ms, now) { + if (ms === null || ms === undefined) return '-'; + const d = ms - now, a = Math.abs(d); + const s = a < 90e3 ? Math.round(a / 1000) + 's' : a < 90 * 60e3 ? Math.round(a / 60e3) + 'm' + : a < 48 * HOUR ? (a / HOUR).toFixed(1) + 'h' : (a / DAY).toFixed(1) + 'd'; + return d >= 0 ? 'in ' + s : s + ' ago'; +} + +const num = (n) => (Number.isInteger(n) ? String(n) : (Math.round(n * 10) / 10).toFixed(1)); + +// rows (array of objects) + column keys -> aligned text lines +function table(rows, cols) { + if (!rows.length) return ['(none)']; + const cells = rows.map((r) => cols.map((c) => { const v = r[c]; return v === null || v === undefined ? '-' : String(v); })); + const w = cols.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length))); + const line = (arr) => arr.map((v, i) => v.padEnd(w[i])).join(' ').trimEnd(); + return [line(cols), line(w.map((n) => '-'.repeat(n))), ...cells.map(line)]; +} + +// ---- database access ---------------------------------------------------------------------------------------------- + +function tableExists(db, name) { + return !!db.get("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?", name); +} + +function openDatabase(ctx, { allowMissing } = {}) { + const file = ctx.dbPath; + if (file !== ':memory:' && !fs.existsSync(file)) { + if (!allowMissing) throw new AdminError('database not found: ' + file + ' (set DB_PATH or --db; the server creates it on first start)'); + } + const db = openDb(file); + ctx.opened.push(db); + if (!allowMissing && !tableExists(db, 'worlds')) { + throw new AdminError('database has no schema yet: ' + file + ' (start the server once, or run `admin.js migrate`)'); + } + return db; +} + +function worldOrThrow(db, id) { + const w = db.get('SELECT * FROM worlds WHERE id = ?', id); + if (!w) throw notFound('no world with id ' + id); + return w; +} + +function idArg(args, what) { + const v = args._[0]; + if (v === undefined) throw usage('missing <' + what + '>'); + if (!/^\d+$/.test(v)) throw usage('<' + what + '> must be a number, got ' + JSON.stringify(v)); + return Number(v); +} + +function userOrThrow(db, username) { + if (!username) throw usage('missing '); + const u = db.get('SELECT id, username, banned FROM users WHERE username = ?', username); + if (!u) throw notFound('no user named ' + JSON.stringify(username)); + return u; +} + +function requireFlag(args, name, why) { + if (!args.flags[name]) throw usage('refusing without --' + name + ': ' + why); +} + +// ---- backups ------------------------------------------------------------------------------------------------------- + +const BACKUP_RE = /^upstream-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z(?:-(\d+))?\.db$/; + +function backupStamp(ms) { return new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z'); } + +// Snapshot files of ours in `dir`, newest first: [{ name, at, seq }] +function listBackups(dir) { + if (!fs.existsSync(dir)) return []; + const out = []; + for (const name of fs.readdirSync(dir)) { + const m = BACKUP_RE.exec(name); + if (!m) continue; + out.push({ name, at: Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]), seq: m[7] ? Number(m[7]) : 0 }); + } + return out.sort((a, b) => b.at - a.at || b.seq - a.seq); +} + +// Which of the (newest-first) backups to delete. `keep` = newest N, `keepDays` = younger than D days. With both, a +// snapshot survives if EITHER keeps it. With neither, nothing is deleted. The newest one is never deleted. +function pruneSet(backups, now, { keep, keepDays }) { + if (keep === undefined && keepDays === undefined) return []; + return backups.filter((b, i) => { + if (i === 0) return false; + const byCount = keep !== undefined && i < keep; + const byAge = keepDays !== undefined && b.at >= now - keepDays * DAY; + return !(byCount || byAge); + }); +} + +// Open a snapshot read-only and check it. Throws if it is not a healthy copy of an UPSTREAM database. +function verifySnapshot(file) { + const { DatabaseSync } = require('node:sqlite'); + let raw; + try { raw = new DatabaseSync(file, { readOnly: true }); } catch (e) { throw new AdminError('cannot open ' + file + ': ' + e.message); } + try { + const ic = raw.prepare('PRAGMA integrity_check').all().map((r) => r.integrity_check); + if (ic.length !== 1 || ic[0] !== 'ok') throw new AdminError('integrity_check failed for ' + file + ': ' + ic.slice(0, 3).join('; ')); + const has = (t) => !!raw.prepare("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?").get(t); + if (!has('worlds') || !has('schema_migrations')) throw new AdminError(file + ' is not an UPSTREAM database (no worlds / schema_migrations table)'); + const count = (t) => Number(raw.prepare('SELECT COUNT(*) AS n FROM ' + t).get().n); + const last = raw.prepare('SELECT name FROM schema_migrations ORDER BY name DESC LIMIT 1').get(); + return { + file, bytes: fs.statSync(file).size, integrity: 'ok', worlds: count('worlds'), users: has('users') ? count('users') : 0, + towns: has('towns') ? count('towns') : 0, lastMigration: last ? last.name : null, + }; + } finally { raw.close(); } +} + +// VACUUM INTO a partial file, verify it, then publish it under its final dated name without ever replacing a file. +function doBackup(db, destDir, now, { keep, keepDays } = {}) { + fs.mkdirSync(destDir, { recursive: true, mode: 0o700 }); + const stamp = backupStamp(now); + const partial = path.join(destDir, '.partial-' + process.pid + '-' + stamp + '.db'); + try { + db.backup(partial); + verifySnapshot(partial); + fs.chmodSync(partial, 0o600); + let final = null; + for (let seq = 0; seq < 1000 && !final; seq++) { + const cand = path.join(destDir, 'upstream-' + stamp + (seq ? '-' + seq : '') + '.db'); + try { fs.linkSync(partial, cand); final = cand; } catch (e) { + if (e.code === 'EEXIST') continue; + if (fs.existsSync(cand)) continue; + fs.renameSync(partial, cand); final = cand; // file system without hard links + } + } + if (!final) throw new AdminError('could not find a free backup file name in ' + destDir); + return { file: final, bytes: fs.statSync(final).size, pruned: pruneBackups(destDir, now, { keep, keepDays }) }; + } finally { + try { fs.unlinkSync(partial); } catch (e) { /* already moved or never created */ } + } +} + +function pruneBackups(dir, now, opts) { + const del = pruneSet(listBackups(dir), now, opts); + for (const b of del) fs.unlinkSync(path.join(dir, b.name)); + for (const name of fs.readdirSync(dir)) { // partial files left behind by a crashed run + if (!name.startsWith('.partial-')) continue; + const p = path.join(dir, name); + try { if (now - fs.statSync(p).mtimeMs > DAY) fs.unlinkSync(p); } catch (e) { /* ignore */ } + } + return del.map((b) => b.name); +} + +// ---- reset-world: schema-driven so tables added by later stages are handled without editing this file ------------ + +const NEVER_RESET = new Set(['worlds', 'users', 'tokens', 'schema_migrations', 'idempotency']); +const IMPLICIT_FK = { town_id: 'towns', operator_id: 'operators' }; + +// -> [{ table, parents: [{ col, table, refCol }], scope }] children first. A table belongs to the world if it has a +// world_id column or points (declared FK, or a town_id / operator_id column) at a table that does. +function resetPlan(db, worldId) { + const tables = db.all("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").map((r) => r.name); + const info = {}; + for (const t of tables) { + const cols = db.all('PRAGMA table_info(' + JSON.stringify(t) + ')').map((c) => c.name); + const parents = db.all('PRAGMA foreign_key_list(' + JSON.stringify(t) + ')').map((f) => ({ col: f.from, table: f.table, refCol: f.to || 'id' })); + for (const c of cols) { + if (IMPLICIT_FK[c] && tables.includes(IMPLICIT_FK[c]) && !parents.some((p) => p.col === c)) parents.push({ col: c, table: IMPLICIT_FK[c], refCol: 'id' }); + } + info[t] = { cols, parents }; + } + const scopeOf = (t, seen) => { + const i = info[t]; + if (i.cols.includes('world_id')) return { sql: 'world_id = ?', params: [worldId] }; + for (const p of i.parents) { + if (NEVER_RESET.has(p.table) || !info[p.table] || seen.has(p.table)) continue; + const s = scopeOf(p.table, new Set([...seen, t])); + if (s) return { sql: p.col + ' IN (SELECT ' + p.refCol + ' FROM ' + p.table + ' WHERE ' + s.sql + ')', params: s.params }; + } + return null; + }; + const owned = [], skipped = []; + for (const t of tables) { + if (NEVER_RESET.has(t)) continue; + const scope = scopeOf(t, new Set()); + if (scope) owned.push({ table: t, parents: info[t].parents, scope }); else skipped.push(t); + } + // children before parents + const ordered = [], left = new Map(owned.map((o) => [o.table, o])); + while (left.size) { + let pick = null; + for (const [t] of left) { + let referenced = false; + for (const [u, o] of left) if (u !== t && o.parents.some((p) => p.table === t)) { referenced = true; break; } + if (!referenced) { pick = t; break; } + } + if (!pick) pick = left.keys().next().value; // a cycle: foreign keys are off during the delete + ordered.push(left.get(pick)); left.delete(pick); + } + return { steps: ordered, skipped }; +} + +// ---- commands ------------------------------------------------------------------------------------------------------ +// Each returns { data, lines }: `data` is printed by --json, `lines` is the human view. + +const commands = {}; + +commands.help = () => ({ data: { commands: Object.keys(HELP_CMDS) }, lines: helpText() }); + +commands.status = (args, ctx) => { + const db = openDatabase(ctx); + const now = ctx.now(); + const migDir = path.join(ROOT, 'server', 'migrations'); + const files = fs.existsSync(migDir) ? fs.readdirSync(migDir).filter((f) => /^\d+.*\.sql$/.test(f)).sort() : []; + const applied = tableExists(db, 'schema_migrations') ? db.all('SELECT name FROM schema_migrations ORDER BY name').map((r) => r.name) : []; + const pending = files.filter((f) => !applied.includes(f)); + const size = (f) => (fs.existsSync(f) ? fs.statSync(f).size : 0); + const ev = tableExists(db, 'events') + ? db.get("SELECT COUNT(*) AS pending, SUM(due_at <= ?) AS overdue FROM events WHERE status = 'pending'", now) + : { pending: 0, overdue: 0 }; + const data = { + db: path.resolve(ctx.dbPath), bytes: size(ctx.dbPath), walBytes: size(ctx.dbPath + '-wal'), + journalMode: db.get('PRAGMA journal_mode').journal_mode, + migrationsApplied: applied.length, migrationsPending: pending, + worlds: db.get('SELECT COUNT(*) AS n FROM worlds').n, users: db.get('SELECT COUNT(*) AS n FROM users').n, + banned: db.get('SELECT COUNT(*) AS n FROM users WHERE banned = 1').n, + eventsPending: ev.pending, eventsOverdue: ev.overdue || 0, + }; + const lines = [ + 'database ' + data.db + ' (' + data.bytes + ' bytes, WAL ' + data.walBytes + ', mode ' + data.journalMode + ')', + 'migrations ' + data.migrationsApplied + ' applied' + (pending.length ? ', PENDING: ' + pending.join(', ') + ' (start the server or run `migrate`)' : ', none pending'), + 'worlds / users ' + data.worlds + ' / ' + data.users + (data.banned ? ' (' + data.banned + ' banned)' : ''), + 'events pending ' + data.eventsPending + (data.eventsOverdue ? ' (' + data.eventsOverdue + ' overdue: the server is stopped or stuck)' : ''), + ]; + return { data, lines }; +}; + +commands.migrate = (args, ctx) => { + const db = openDatabase(ctx, { allowMissing: true }); + const applied = migrate(db); + return { data: { applied }, lines: [applied.length ? 'applied: ' + applied.join(', ') : 'nothing to apply'] }; +}; + +commands.worlds = (args, ctx) => { + const db = openDatabase(ctx); + const rows = db.all(`SELECT w.id, w.name, w.speed, w.map_radius AS radius, w.seed, w.status, w.start_at AS startAt, w.end_at AS endAt, + (SELECT COUNT(*) FROM operators o WHERE o.world_id = w.id) AS operators, + (SELECT COUNT(*) FROM towns t WHERE t.world_id = w.id) AS towns, + (SELECT COUNT(*) FROM events e WHERE e.world_id = w.id AND e.status = 'pending') AS pendingEvents + FROM worlds w ORDER BY w.id`); + const view = rows.map((r) => Object.assign({}, r, { start: iso(r.startAt), end: iso(r.endAt) })); + return { data: { worlds: rows }, lines: table(view, ['id', 'name', 'speed', 'radius', 'seed', 'status', 'start', 'end', 'operators', 'towns', 'pendingEvents']) }; +}; + +commands['create-world'] = (args, ctx) => { + const f = args.flags; + const speed = numFlag(f, 'speed', { min: 0.1, max: 100, def: undefined }); + const radius = intFlag(f, 'radius', { min: 5, max: 500, def: undefined }); + const seed = intFlag(f, 'seed', { min: 1, max: 2 ** 31 - 1, def: undefined }); + const now = ctx.now(); + const endAt = f['end-in'] !== undefined ? now + parseDuration(f['end-in']) : undefined; + const db = openDatabase(ctx); + const id = db.tx(() => createWorld(db, now, { name: f.name, speed, mapRadius: radius, seed, endAt })); + const w = worldOrThrow(db, id); + return { data: { world: w }, lines: ['created world ' + id + ' "' + w.name + '" speed ' + w.speed + ', radius ' + w.map_radius + ', seed ' + w.seed + (endAt ? ', planned end ' + iso(endAt) : '')] }; +}; + +commands['end-world'] = (args, ctx) => { + const id = idArg(args, 'world-id'); + const db = openDatabase(ctx); + const w = worldOrThrow(db, id); + if (w.status === 'ended') return { data: { id, status: 'ended', changed: false }, lines: ['world ' + id + ' is already ended'] }; + requireFlag(args, 'yes', 'ending world ' + id + ' ("' + w.name + '") stops signups and new joins'); + db.tx(() => db.run("UPDATE worlds SET status = 'ended', end_at = ? WHERE id = ?", ctx.now(), id)); + return { data: { id, status: 'ended', changed: true }, lines: ['world ' + id + ' ended'] }; +}; + +commands.users = (args, ctx) => { + const db = openDatabase(ctx); + const rows = db.all(`SELECT u.id, u.username, u.banned, u.created_at AS createdAt, + (SELECT COUNT(*) FROM tokens t WHERE t.user_id = u.id AND t.revoked_at IS NULL) AS tokens, + (SELECT MAX(t.last_used_at) FROM tokens t WHERE t.user_id = u.id) AS lastSeen, + (SELECT COUNT(*) FROM operators o WHERE o.user_id = u.id) AS operators + FROM users u ${args.flags.banned ? 'WHERE u.banned = 1' : ''} ORDER BY u.id`); + const view = rows.map((r) => Object.assign({}, r, { banned: r.banned ? 'BANNED' : '', created: iso(r.createdAt), lastSeen: iso(r.lastSeen) })); + return { data: { users: rows }, lines: table(view, ['id', 'username', 'banned', 'created', 'lastSeen', 'tokens', 'operators']) }; +}; + +commands.operators = (args, ctx) => { + const db = openDatabase(ctx); + const wid = intFlag(args.flags, 'world', { min: 1 }); + const rows = db.all(`SELECT o.id, o.world_id AS world, o.name, o.as_number AS asNumber, u.username AS user, u.banned, + o.alliance_id AS alliance, o.protection_until AS protectionUntil, + (SELECT COUNT(*) FROM towns t WHERE t.owner_id = o.id) AS towns + FROM operators o JOIN users u ON u.id = o.user_id ${wid ? 'WHERE o.world_id = ?' : ''} ORDER BY o.world_id, o.id`, ...(wid ? [wid] : [])); + const now = ctx.now(); + const view = rows.map((r) => Object.assign({}, r, { banned: r.banned ? 'BANNED' : '', protection: r.protectionUntil > now ? rel(r.protectionUntil, now) : '' })); + return { data: { operators: rows }, lines: table(view, ['id', 'world', 'name', 'asNumber', 'user', 'banned', 'towns', 'alliance', 'protection']) }; +}; + +commands.ban = (args, ctx) => { + const db = openDatabase(ctx); + const u = userOrThrow(db, args._[0]); + const revoked = db.tx(() => { + db.run('UPDATE users SET banned = 1 WHERE id = ?', u.id); + return db.run('UPDATE tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL', ctx.now(), u.id).changes; + }); + return { data: { username: u.username, banned: true, tokensRevoked: Number(revoked) }, lines: [u.username + ' banned, ' + revoked + ' token(s) revoked (login now answers 403 forbidden)'] }; +}; + +commands.unban = (args, ctx) => { + const db = openDatabase(ctx); + const u = userOrThrow(db, args._[0]); + db.tx(() => db.run('UPDATE users SET banned = 0 WHERE id = ?', u.id)); + return { data: { username: u.username, banned: false }, lines: [u.username + ' unbanned (they must log in again, their old tokens stay revoked)'] }; +}; + +commands['revoke-tokens'] = (args, ctx) => { + const db = openDatabase(ctx); + const u = userOrThrow(db, args._[0]); + const n = Number(db.tx(() => db.run('UPDATE tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL', ctx.now(), u.id).changes)); + return { data: { username: u.username, revoked: n }, lines: [u.username + ': ' + n + ' token(s) revoked'] }; +}; + +// One town as { town row, current resources } for inspection. `overdue` counts pending events that should already have run. +function describeTown(db, row, now) { + const world = loadWorld(db, row.world_id); + const town = townFromRow(db, row, world); + const cur = R.resourcesAt(town, now); + const overdue = db.get("SELECT COUNT(*) AS n FROM events WHERE town_id = ? AND status = 'pending' AND due_at <= ?", row.id, now).n; + const r1 = (o) => { const x = {}; for (const k of Object.keys(o)) x[k] = Math.round(o[k] * 10) / 10; return x; }; + return { + id: row.id, name: row.name, world: row.world_id, ownerId: row.owner_id, x: row.x, y: row.y, capital: !!row.is_capital, + loyalty: Math.round(R.loyaltyAt(town.loyalty, town.loyaltyAt, now, town.speed) * 10) / 10, + resourcesAt: now, resources: r1(cur.amounts), caps: r1(cur.caps), ratesPerHour: r1(cur.rates), + storedAt: row.res_at, overdueEvents: overdue, + }; +} + +commands['inspect-town'] = (args, ctx) => { + const id = idArg(args, 'town-id'); + const db = openDatabase(ctx); + const row = db.get('SELECT * FROM towns WHERE id = ?', id); + if (!row) throw notFound('no town with id ' + id); + const now = ctx.now(); + const t = describeTown(db, row, now); + const owner = db.get('SELECT o.id, o.name, o.as_number AS asNumber, u.username FROM operators o JOIN users u ON u.id = o.user_id WHERE o.id = ?', row.owner_id); + const buildings = db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', id) + .sort((a, b) => (a.key[0] === 'f' && b.key[0] === 'f' ? Number(a.key.slice(1)) - Number(b.key.slice(1)) : a.key.localeCompare(b.key))); + const queue = db.all("SELECT id, type, due_at AS dueAt, payload FROM events WHERE town_id = ? AND status = 'pending' ORDER BY due_at, id", id) + .map((e) => ({ id: e.id, type: e.type, dueAt: e.dueAt, payload: e.payload })); + const units = tableExists(db, 'town_units') ? db.all('SELECT unit, count FROM town_units WHERE town_id = ? ORDER BY unit', id) : null; + const data = { town: t, owner, buildings, queue, units }; + const res = ['fiber', 'hardware', 'capital', 'battery'].map((k) => k + ' ' + num(t.resources[k]) + (t.caps[k] ? '/' + num(t.caps[k]) : '')).join(' '); + const lines = [ + 'town ' + t.id + ' "' + t.name + '" at (' + t.x + ',' + t.y + ') world ' + t.world + (t.capital ? ' [capital]' : '') + ' loyalty ' + t.loyalty, + 'owner ' + (owner ? '#' + owner.id + ' ' + owner.name + ' (AS' + owner.asNumber + ', user ' + owner.username + ')' : '#' + t.ownerId + ' (missing)'), + 'now (' + iso(now) + '): ' + res, + 'rates/h: fiber ' + num(t.ratesPerHour.fiber) + ' hardware ' + num(t.ratesPerHour.hardware) + ' capital ' + num(t.ratesPerHour.capital) + + ' power out ' + num(t.ratesPerHour.powerOut) + ' draw ' + num(t.ratesPerHour.powerDraw) + ' net ' + num(t.ratesPerHour.powerNet), + ]; + if (t.overdueEvents) lines.push('NOTE: ' + t.overdueEvents + ' overdue pending event(s) for this town (server stopped?): values above ignore them'); + lines.push('', 'buildings:', ...table(buildings, ['key', 'type', 'level'])); + lines.push('', 'queue:', ...table(queue.map((e) => ({ id: e.id, type: e.type, due: iso(e.dueAt), in: rel(e.dueAt, now), payload: e.payload })), ['id', 'type', 'due', 'in', 'payload'])); + if (units) lines.push('', 'units:', ...table(units, ['unit', 'count'])); + return { data, lines }; +}; + +commands['inspect-operator'] = (args, ctx) => { + const key = args._[0]; + if (key === undefined) throw usage('missing (or --id )'); + const db = openDatabase(ctx); + const wid = intFlag(args.flags, 'world', { min: 1 }); + const wcond = wid ? ' AND o.world_id = ?' : ''; + const wpar = wid ? [wid] : []; + const cols = 'o.id, o.world_id AS world, o.name, o.as_number AS asNumber, o.alliance_id AS alliance, o.protection_until AS protectionUntil, o.created_at AS createdAt, u.id AS userId, u.username, u.banned'; + let rows; + if (args.flags.id !== undefined) rows = db.all('SELECT ' + cols + ' FROM operators o JOIN users u ON u.id = o.user_id WHERE o.id = ?' + wcond, intFlag(args.flags, 'id', { min: 1 }), ...wpar); + else rows = db.all('SELECT ' + cols + ' FROM operators o JOIN users u ON u.id = o.user_id WHERE (o.name = ? COLLATE NOCASE OR u.username = ?)' + wcond + ' ORDER BY o.world_id, o.id', key, key, ...wpar); + if (!rows.length) throw notFound('no operator matching ' + JSON.stringify(key)); + if (rows.length > 1 && !args.flags.world) { + throw usage('several operators match ' + JSON.stringify(key) + ': ' + rows.map((r) => '#' + r.id + ' (world ' + r.world + ')').join(', ') + '; use --world or --id '); + } + const now = ctx.now(); + const out = rows.map((o) => { + const towns = db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY id', o.id).map((r) => describeTown(db, r, now)); + const tokens = db.get('SELECT COUNT(*) AS n FROM tokens WHERE user_id = ? AND revoked_at IS NULL', o.userId).n; + return Object.assign({}, o, { banned: !!o.banned, activeTokens: tokens, towns }); + }); + const lines = []; + for (const o of out) { + lines.push('operator #' + o.id + ' "' + o.name + '" AS' + o.asNumber + ' world ' + o.world + ' user ' + o.username + (o.banned ? ' [BANNED]' : '') + + ' tokens ' + o.activeTokens + (o.alliance ? ' alliance ' + o.alliance : '') + + (o.protectionUntil > now ? ' protected ' + rel(o.protectionUntil, now) : '')); + lines.push(...table(o.towns.map((t) => ({ + id: t.id, name: t.name, pos: t.x + ',' + t.y, fiber: num(t.resources.fiber), hardware: num(t.resources.hardware), capital: num(t.resources.capital), battery: num(t.resources.battery), + })), ['id', 'name', 'pos', 'fiber', 'hardware', 'capital', 'battery']), ''); + } + return { data: { operators: out }, lines }; +}; + +commands.events = (args, ctx) => { + const db = openDatabase(ctx); + const f = args.flags; + const where = [], par = []; + const status = f.pending ? 'pending' : f.status; + if (status) { where.push('status = ?'); par.push(status); } + if (f.type) { where.push('type = ?'); par.push(f.type); } + if (f.town !== undefined) { where.push('town_id = ?'); par.push(intFlag(f, 'town', { min: 1 })); } + if (f.world !== undefined) { where.push('world_id = ?'); par.push(intFlag(f, 'world', { min: 1 })); } + const limit = intFlag(f, 'limit', { min: 1, max: 10000, def: 50 }); + const pendingOrder = status === 'pending'; + const rows = db.all('SELECT id, world_id AS world, due_at AS dueAt, type, town_id AS town, status, error, payload FROM events' + + (where.length ? ' WHERE ' + where.join(' AND ') : '') + (pendingOrder ? ' ORDER BY due_at, id' : ' ORDER BY id DESC') + ' LIMIT ' + limit, ...par); + const now = ctx.now(); + const view = rows.map((r) => Object.assign({}, r, { due: iso(r.dueAt), when: rel(r.dueAt, now), payload: r.payload.length > 60 ? r.payload.slice(0, 57) + '...' : r.payload, error: r.error ? r.error.slice(0, 40) : '' })); + const lines = table(view, ['id', 'world', 'due', 'when', 'type', 'town', 'status', 'payload', 'error']); + lines.push('(' + rows.length + ' shown, limit ' + limit + (pendingOrder ? ', in processing order' : ', newest first') + ')'); + return { data: { events: rows }, lines }; +}; + +// Dry run: what would the scheduler process up to `--until` (default now)? --simulate additionally runs the real +// handlers on a scratch COPY of the database (VACUUM INTO a temp file, deleted afterwards) and reports the outcome. +commands['replay-events'] = (args, ctx) => { + const db = openDatabase(ctx); + const f = args.flags; + const now = ctx.now(); + const until = f.until !== undefined ? parseTime(f.until, now) : now; + const limit = intFlag(f, 'limit', { min: 1, max: 100000, def: 200 }); + const wid = intFlag(f, 'world', { min: 1 }); + const wc = wid ? ' AND world_id = ?' : ''; + const wp = wid ? [wid] : []; + const due = db.all("SELECT id, world_id AS world, due_at AS dueAt, type, town_id AS town, payload FROM events WHERE status = 'pending' AND due_at <= ?" + wc + ' ORDER BY due_at, id LIMIT ' + limit, until, ...wp); + const total = db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending' AND due_at <= ?" + wc, until, ...wp).n; + const next = db.get("SELECT id, due_at AS dueAt, type FROM events WHERE status = 'pending' AND due_at > ?" + wc + ' ORDER BY due_at, id LIMIT 1', until, ...wp); + const data = { until, dueCount: total, due, next: next || null, simulated: null }; + const lines = ['up to ' + iso(until) + ' the scheduler would process ' + total + ' event(s), in this order (nothing was changed):']; + const view = due.map((e) => Object.assign({}, e, { due: iso(e.dueAt), payload: e.payload.length > 60 ? e.payload.slice(0, 57) + '...' : e.payload })); + lines.push(...table(view, ['id', 'world', 'due', 'type', 'town', 'payload'])); + if (total > due.length) lines.push('... ' + (total - due.length) + ' more (raise --limit)'); + lines.push(next ? 'next after that: #' + next.id + ' ' + next.type + ' at ' + iso(next.dueAt) + ' (' + rel(next.dueAt, now) + ')' : 'no pending event after that'); + + if (f.simulate) { + const sim = simulate(db, until, due.map((e) => e.id)); + data.simulated = sim; + lines.push('', 'simulation on a scratch copy (the real database was not touched):'); + lines.push(...table(sim.outcome.map((o) => ({ id: o.id, type: o.type, status: o.status, error: o.error || '' })), ['id', 'type', 'status', 'error'])); + lines.push('follow-up events enqueued: ' + sim.followUps.length + ', notifications written: ' + sim.notifications); + if (sim.followUps.length) lines.push(...table(sim.followUps.map((e) => ({ id: e.id, type: e.type, due: iso(e.dueAt), status: e.status })), ['id', 'type', 'due', 'status'])); + if (sim.logs.length) lines.push('handler log:', ...sim.logs.map((l) => ' ' + l)); + } + return { data, lines }; +}; + +function simulate(db, until, ids) { + const { Scheduler } = require(path.join(ROOT, 'server', 'scheduler.js')); + const handlers = require(path.join(ROOT, 'server', 'events')); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-replay-')); + const file = path.join(dir, 'copy.db'); + let copy; + try { + db.backup(file); + copy = openDb(file); + const maxBefore = copy.get('SELECT COALESCE(MAX(id), 0) AS m FROM events').m; + const notesBefore = tableExists(copy, 'notifications') ? copy.get('SELECT COUNT(*) AS n FROM notifications').n : 0; + const logs = []; + const sched = new Scheduler({ db: copy, clock: new FakeClock(until), handlers, log: (m) => logs.push(String(m).split('\n')[0]), autoArm: false }); + sched.runDue(until); + const outcome = ids.length ? copy.all('SELECT id, type, status, error FROM events WHERE id IN (' + ids.map(() => '?').join(',') + ') ORDER BY due_at, id', ...ids) : []; + const followUps = copy.all('SELECT id, type, due_at AS dueAt, status FROM events WHERE id > ? ORDER BY due_at, id', maxBefore); + const notes = tableExists(copy, 'notifications') ? copy.get('SELECT COUNT(*) AS n FROM notifications').n - notesBefore : 0; + return { outcome, followUps, notifications: notes, logs }; + } finally { + if (copy) copy.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +commands.backup = (args, ctx) => { + const dest = args._[0]; + if (!dest) throw usage('missing '); + const keep = intFlag(args.flags, 'keep', { min: 1 }); + const keepDays = numFlag(args.flags, 'keep-days', { min: 0.1 }); + const db = openDatabase(ctx); + const r = doBackup(db, path.resolve(ctx.cwd, dest), ctx.now(), { keep, keepDays }); + const lines = ['backup written: ' + r.file + ' (' + r.bytes + ' bytes, verified)']; + if (r.pruned.length) lines.push('pruned ' + r.pruned.length + ' old snapshot(s): ' + r.pruned.join(', ')); + return { data: r, lines }; +}; + +commands['verify-backup'] = (args) => { + if (!args._[0]) throw usage('missing '); + const file = path.resolve(args._[0]); + if (!fs.existsSync(file)) throw notFound('no such file: ' + file); + const v = verifySnapshot(file); + return { data: v, lines: ['ok: ' + v.file + ' (' + v.bytes + ' bytes, integrity ok, ' + v.worlds + ' world(s), ' + v.users + ' user(s), ' + v.towns + ' town(s), last migration ' + v.lastMigration + ')'] }; +}; + +commands['reset-world'] = (args, ctx) => { + const id = idArg(args, 'world-id'); + const db = openDatabase(ctx); + const w = worldOrThrow(db, id); + const plan = resetPlan(db, id); + const counts = plan.steps.map((s) => ({ table: s.table, rows: db.get('SELECT COUNT(*) AS n FROM ' + s.table + ' WHERE ' + s.scope.sql, ...s.scope.params).n })); + const summary = table(counts, ['table', 'rows']); + if (!args.flags['yes-destroy']) { + throw usage('refusing without --yes-destroy. reset-world ' + id + ' ("' + w.name + '") would delete these game rows (accounts and tokens are kept):\n ' + + summary.join('\n ') + '\n untouched tables: ' + (plan.skipped.join(', ') || 'none') + + '\nStop the server first and take a backup (`backup ` or --backup ), then repeat with --yes-destroy.'); + } + const now = ctx.now(); + let backup = null; + if (args.flags.backup) backup = doBackup(db, path.resolve(ctx.cwd, args.flags.backup), now, {}); + const newSeed = args.flags.seed !== undefined ? intFlag(args.flags, 'seed', { min: 1, max: 2 ** 31 - 1 }) + : args.flags['new-seed'] ? require('crypto').randomInt(1, 2 ** 31 - 1) : null; + db.exec('PRAGMA foreign_keys = OFF'); // children are deleted first, but later stages may add odd tables + try { + db.tx(() => { + if (tableExists(db, 'idempotency')) db.run('DELETE FROM idempotency WHERE user_id IN (SELECT user_id FROM operators WHERE world_id = ?)', id); + for (const s of plan.steps) db.run('DELETE FROM ' + s.table + ' WHERE ' + s.scope.sql, ...s.scope.params); + db.run("UPDATE worlds SET start_at = ?, end_at = NULL, status = 'running'" + (newSeed ? ', seed = ?' : '') + ' WHERE id = ?', now, ...(newSeed ? [newSeed] : []), id); + const bad = db.all('PRAGMA foreign_key_check'); + if (bad.length) throw new AdminError('reset would leave dangling references (' + bad.length + ', first in table ' + bad[0].table + '): rolled back'); + }); + } finally { db.exec('PRAGMA foreign_keys = ON'); } + const lines = ['world ' + id + ' reset (running again, start ' + iso(now) + (newSeed ? ', new seed ' + newSeed : ', same seed') + '). Deleted:', ...summary, + 'Accounts were kept; players must join the world again.']; + if (backup) lines.push('backup before reset: ' + backup.file); + return { data: { id, deleted: counts, seed: newSeed, backup: backup && backup.file }, lines }; +}; + +commands.grant = (args, ctx) => { + const id = idArg(args, 'town-id'); + const f = args.flags; + const keys = ['fiber', 'hardware', 'capital', 'battery']; + const add = {}; + const all = numFlag(f, 'all', { min: 0, max: 1e9 }); + for (const k of keys) { + const v = numFlag(f, k, { min: 0, max: 1e9 }); + if (v !== undefined) add[k] = v; else if (all !== undefined && k !== 'battery') add[k] = all; + } + if (!Object.keys(add).length) throw usage('nothing to grant: use --fiber N --hardware N --capital N --battery N (or --all N for the three stockpiles)'); + const db = openDatabase(ctx); + const row = db.get('SELECT * FROM towns WHERE id = ?', id); + if (!row) throw notFound('no town with id ' + id); + requireFlag(args, 'yes', 'grant changes a town\'s resources outside the rules (test tool)'); + const now = ctx.now(); + const before = describeTown(db, row, now).resources; + // Added to the stored amounts (valid at res_at): the lazy model then carries them forward, no settle needed. + db.tx(() => db.run('UPDATE towns SET fiber = fiber + ?, hardware = hardware + ?, capital = capital + ?, battery = battery + ? WHERE id = ?', + add.fiber || 0, add.hardware || 0, add.capital || 0, add.battery || 0, id)); + const after = describeTown(db, db.get('SELECT * FROM towns WHERE id = ?', id), now).resources; + return { data: { id, granted: add, before, after }, lines: ['granted to town ' + id + ': ' + Object.keys(add).map((k) => k + ' +' + num(add[k])).join(', '), + 'now: ' + keys.map((k) => k + ' ' + num(before[k]) + ' -> ' + num(after[k])).join(' ')] }; +}; + +// ---- help --------------------------------------------------------------------------------------------------------- + +const HELP_CMDS = { + help: 'this text', + status: 'database file, migrations, counts, overdue events', + migrate: 'apply pending migrations (the server does this at boot too; creates the file if missing)', + worlds: 'list worlds', + 'create-world': '[--name N] [--speed X] [--radius R] [--seed S] [--end-in 90d] new world (a second one runs in parallel)', + 'end-world': ' --yes mark a world ended (no new signups/joins)', + users: '[--banned] list accounts (no hashes, no tokens)', + operators: '[--world ID] list operators (a user in a world)', + ban: ' ban and revoke all tokens; login answers 403', + unban: '', + 'revoke-tokens': ' log the user out everywhere', + 'inspect-operator': ' [--world ID] | --id N operator with POPs and current resources', + 'inspect-town': ' current resources (rules.resourcesAt), buildings, queue, units', + events: '[--pending] [--status S] [--type T] [--town ID] [--world ID] [--limit N] event queue', + 'replay-events': '[--until now|+2h|ISO] [--world ID] [--limit N] [--simulate] dry run: what the scheduler would process; --simulate runs the handlers on a scratch copy', + backup: ' [--keep N] [--keep-days D] consistent VACUUM INTO snapshot, verified, never overwrites; prunes old ones', + 'verify-backup': ' integrity check of a snapshot (read-only)', + 'reset-world': ' --yes-destroy [--backup DIR] [--seed S | --new-seed] delete that world\'s game rows, keep accounts', + grant: ' --yes [--fiber N] [--hardware N] [--capital N] [--battery N] [--all N] add resources (testing)', +}; + +function helpText() { + const w = Math.max(...Object.keys(HELP_CMDS).map((k) => k.length)); + return [ + 'UPSTREAM admin: node tools/admin.js [args] [--db FILE] [--json]', + '', + 'Database: --db FILE, else $DB_PATH, else ./data/game.db. Safe on a running server (WAL); run it as the service user', + '(deploy/upstream-admin does). Destructive commands need an explicit flag: --yes or --yes-destroy.', + 'Exit codes: 0 ok, 1 failed, 2 usage or missing confirmation flag, 3 not found.', + '', + ...Object.keys(HELP_CMDS).map((k) => ' ' + k.padEnd(w + 1) + HELP_CMDS[k]), + ]; +} + +// ---- entry point --------------------------------------------------------------------------------------------------- + +// main(argv, io) -> exit code. io = { out, err, env, cwd, now } (all optional, for tests). +function main(argv, io) { + io = io || {}; + const out = io.out || ((s) => process.stdout.write(s + '\n')); + const err = io.err || ((s) => process.stderr.write(s + '\n')); + const env = io.env || process.env; + const ctx = { opened: [], cwd: io.cwd || process.cwd(), now: io.now || (() => Date.now()), dbPath: null }; + try { + const args = parseArgs(argv); + const name = args._.shift() || 'help'; + if (args.flags.help && name !== 'help') { for (const l of helpText()) out(l); return 0; } + const cmd = commands[name]; + if (!cmd) throw usage('unknown command ' + JSON.stringify(name) + ' (try `help`)'); + ctx.dbPath = args.flags.db || env.DB_PATH || './data/game.db'; + if (ctx.dbPath !== ':memory:') ctx.dbPath = path.resolve(ctx.cwd, ctx.dbPath); + const res = cmd(args, ctx); + if (args.flags.json) out(JSON.stringify(res.data, null, 2)); else for (const l of res.lines) out(l); + return 0; + } catch (e) { + if (e instanceof AdminError) { err('error: ' + e.message); return e.exitCode; } + err('error: ' + (e && e.message || e)); + if (env.DEBUG && e && e.stack) err(e.stack); + return 1; + } finally { + for (const db of ctx.opened) { try { db.close(); } catch (e) { /* already closed */ } } + } +} + +module.exports = { main, commands, parseArgs, parseTime, parseDuration, listBackups, pruneSet, backupStamp, verifySnapshot, doBackup, resetPlan, table, AdminError }; + +if (require.main === module) process.exitCode = main(process.argv.slice(2));

1jol}i)DsH`m(tMPhZ z`b?MtC33E5;&!6fv-oA1^m0<7Y)Q}gU=$P}i62R|Ak0H*K~~m8H<_@6LhQD!5l|)u zP2+ED-vHKg?~rxX!r0n|!-qQC)zf#|nhbXv*DqY#;H&v}zq+9p{D))EZ#=t7i#qb& z%4dJQnZu_l36lSVy%7`fFT7$x7WqEx`5K2F_Zj5E)G{bi?X(u4Z) zEoQJaCvZM)gk{tP^dzOk5x(@7|8iiHAz)ZL&S&+qGk(!2qGKHyaC_PbNgd98ua%t- z|FWJ$Yq|*Dcsr0R#?4cm(PZ&@l8g z^MqzYl-t>{(oL3((Xb@ywtO=1Tb&Y9g1!u{7th)6{JVq24_9oO)PRy>rTr*|S165J z|JTUyJ4N1hr)xEdPRVq%eo4}G3)Gml`Bxpu>Yn{`f9xQAfDD}L~G^Y8YXoSUO zY9M{Sf)x2;dg4?Hln;<)$LJTL5*lUxQTbZe%t9)IYgkuc6yJ+SKcHvnT56{vuKH`0 zu7p0t_|gwmQht@%BJz(*zZC-ZHwO-HA8>3~z*l>d#@t$#2+$1nhs10TN{GLK5q_TG ziVDt)cpmIudZCe@UMXtp{TDv7*QW01w@;!pIwjxsHOq$u<^D_V4&6r%rpfty?xZ${ zwU%FX|H)FoEMvO+%SY5n^wym^VdiUQP~`!R6({Z`O3i1VR)-dYEl zk7YU#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2EUA6S`>`8ATjTn+a!m{5l{YmYMt%N1u3zoGy0Nbku>+kOlOsgg*s+Hb#v zbFQW&Zuj#j`5bqI_5J?q@=ifN@PKb=8zyx?_-nMf0d~|>XM3vXU@e7gGCZTX*aI;E z)W4Zv?x*`AxhBmH=_g?|uxvxA2n~Qmdz3R&FG_J3#XS0Bl!;|0m5YR;Fp zN1&O-10aCNXh2y%m1xEES&R3sbyU-$-g76P^ly`dLi5OBCi(7<=@tXS_brRX@j>;r zSUK(bxkM{m?0MGmz~h<;9AT+iBvs{-Ww!bTwY=W|(HLD|6374R*S&fBYM4%g#6`9j z`FGKN_uBqx%Qa;09jJ{E&|$o*=S*e5(4)^K{mALyy8+lp^9xo%^f$v$PAIo&K<0%) zW+fp4vp{+VD<~rBl*IR0lwqw`VVUf1a#rHKVZ-fU(O=)-LIF~oVqcMF^1{v8Ku7lA{ z8&(p=QPA-As9_KEJIR^NxPt|xn>|+$0e1XalMnM^+&%ArbbP!83rUd+9LR}-yxpKy z0z1CX4sXPZ?Hr{VD6&ddZFGv^UvJw?HuNT136C4ZvmI7c(e^g^1B + + + + + + + + + + + + + + + + diff --git a/public/icons/sprite.svg b/public/icons/sprite.svg new file mode 100644 index 0000000..d5b2943 --- /dev/null +++ b/public/icons/sprite.svg @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..4c15efe --- /dev/null +++ b/public/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + +UPSTREAM + + + + + + +